All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v4 01/42] xen/riscv: add helper to check APLIC MSI mode
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 02/42] xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64() Oleksii Kurochko
                   ` (40 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Use convenient helper instead of open-coding the things.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
Acked-by: Jan Beulich <jbeulich@suse.com>
---
Changes in v4:
 - Nothing changed. Only move  this patch first in patch series to merge
   it faster.
---
Changes in v3:
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
 - Add Acked-by: Jan Beulich <jbeulich@suse.com>.
---
Changes in v2:
 - Rename helper.
 - Update the commit message.
---
---
 xen/arch/riscv/aplic.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
index 17c96177a3b1..79bbc0e864d5 100644
--- a/xen/arch/riscv/aplic.c
+++ b/xen/arch/riscv/aplic.c
@@ -38,6 +38,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;
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
@@ -130,7 +135,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));
 
@@ -161,7 +166,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));
 
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 02/42] xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64()
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
  2026-11-13 15:48 ` [PATCH v4 01/42] xen/riscv: add helper to check APLIC MSI mode Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-18  9:50   ` Baptiste Le Duc
  2026-11-13 15:48 ` [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64() Oleksii Kurochko
                   ` (39 subsequent siblings)
  41 siblings, 1 reply; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

csr_write64() uses its csr parameter both as an operand of ## (to form the
name of the CSR holding the upper half on RV32) and in ordinary,
macro-expanded context. As the CSR_* constants are macros themselves, this
violates MISRA C Rule 20.12.

Make csr_write64() take the CSR name without the CSR_ prefix and paste the
prefix as well, so that the parameter is used as an operand of ## only.

While at it, drop the (void) of the upper half CSR on RV64: it generated
no code and only made the build fail if CSR_<name>H wasn't defined, while
a pure 64-bit environment has no need for the ...H constants.

No functional change.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/include/asm/csr.h | 16 ++++++----------
 xen/arch/riscv/time.c            |  4 ++--
 2 files changed, 8 insertions(+), 12 deletions(-)

diff --git a/xen/arch/riscv/include/asm/csr.h b/xen/arch/riscv/include/asm/csr.h
index a805f7ed0ba1..3cf8e1857ce2 100644
--- a/xen/arch/riscv/include/asm/csr.h
+++ b/xen/arch/riscv/include/asm/csr.h
@@ -33,18 +33,14 @@
 })
 
 #ifdef CONFIG_RISCV_32
-#define csr_write64(csr, val)       \
-({                                  \
-    uint64_t v_ = (val);            \
-    csr_write(csr, v_);             \
-    csr_write(csr ## H, v_ >> 32);  \
+#define csr_write64(name, val)              \
+({                                          \
+    uint64_t v_ = (val);                    \
+    csr_write(CSR_ ## name, v_);            \
+    csr_write(CSR_ ## name ## H, v_ >> 32); \
 })
 #else
-#define csr_write64(csr, val)       \
-({                                  \
-    csr_write(csr, val);            \
-    (void)csr ## H;                 \
-})
+#define csr_write64(name, val) csr_write(CSR_ ## name, val)
 #endif
 
 #define csr_swap(csr, val)                                      \
diff --git a/xen/arch/riscv/time.c b/xen/arch/riscv/time.c
index 782d9cd450f3..97ebe402ae41 100644
--- a/xen/arch/riscv/time.c
+++ b/xen/arch/riscv/time.c
@@ -15,7 +15,7 @@ uint64_t __ro_after_init boot_clock_cycles;
 
 static int cf_check sstc_set_xen_timer(uint64_t deadline)
 {
-    csr_write64(CSR_STIMECMP, deadline);
+    csr_write64(STIMECMP, deadline);
 
     return 0;
 }
@@ -103,6 +103,6 @@ void __init preinit_xen_time(void)
          * Thereby to avoid spurious VS-timer irqs set vstimecmp CSR to
          * ~0.
          */
-        csr_write64(CSR_VSTIMECMP, ~0);
+        csr_write64(VSTIMECMP, ~0);
     }
 }
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
  2026-11-13 15:48 ` [PATCH v4 01/42] xen/riscv: add helper to check APLIC MSI mode Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 02/42] xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64() Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-18  9:50   ` Baptiste Le Duc
  2026-11-13 15:48 ` [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register Oleksii Kurochko
                   ` (38 subsequent siblings)
  41 siblings, 1 reply; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading
the halves with two separate instructions isn't always safe: for a CSR
which hardware increments, a carry from the low half into the high one can
happen in between, 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.

Only CSRs which change under Xen's feet need that, hence the name. The
majority can be read with a plain pair of csr_read()s, so no helper for
those is introduced here as there would be no user for it.

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.

No functional change on RV64.

Fixes: a541ddadec0a ("xen/riscv: introduce time.h")
Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Take the CSR name without the CSR_ prefix, so that the macro parameter
   is used as an operand of ## only (MISRA C Rule 20.12).
 - Drop the (void) of the ...H constant on RV64.
 - Initialise hi_ in its declaration.
---
Changes in v3:
 - Rename csr_read64() to csr_volatile_read64(): only CSRs which change
   under Xen's feet need the retry, the majority can be read with a plain
   split access, which isn't introduced here as it would have no user.
 - Carry the high half read at the end of an iteration over to the next
   one, instead of reading it twice per retry.
 - Update the commit message.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/include/asm/csr.h  | 22 ++++++++++++++++++++++
 xen/arch/riscv/include/asm/time.h |  4 ++--
 2 files changed, 24 insertions(+), 2 deletions(-)

diff --git a/xen/arch/riscv/include/asm/csr.h b/xen/arch/riscv/include/asm/csr.h
index 3cf8e1857ce2..6df595e810ef 100644
--- a/xen/arch/riscv/include/asm/csr.h
+++ b/xen/arch/riscv/include/asm/csr.h
@@ -39,8 +39,30 @@
     csr_write(CSR_ ## name, v_);            \
     csr_write(CSR_ ## name ## 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.
+ *
+ * Only needed for CSRs which change under Xen's feet.
+ */
+#define csr_volatile_read64(name)                            \
+({                                                           \
+    uint32_t lo_, old_, hi_ = csr_read(CSR_ ## name ## H);   \
+                                                             \
+    do {                                                     \
+        old_ = hi_;                                          \
+        lo_ = csr_read(CSR_ ## name);                        \
+    } while ( (hi_ = csr_read(CSR_ ## name ## H)) != old_ ); \
+                                                             \
+    ((uint64_t)hi_ << 32) | lo_;                             \
+})
 #else
 #define csr_write64(name, val) csr_write(CSR_ ## name, val)
+
+#define csr_volatile_read64(name) csr_read(CSR_ ## name)
 #endif
 
 #define csr_swap(csr, val)                                      \
diff --git a/xen/arch/riscv/include/asm/time.h b/xen/arch/riscv/include/asm/time.h
index 0e5b96a8631c..02b9a03ed90d 100644
--- a/xen/arch/riscv/include/asm/time.h
+++ b/xen/arch/riscv/include/asm/time.h
@@ -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_volatile_read64(TIME);
 }
 
 void preinit_xen_time(void);
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (2 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64() Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-27 15:23   ` Baptiste Le Duc
  2026-11-13 15:48 ` [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index() Oleksii Kurochko
                   ` (37 subsequent siblings)
  41 siblings, 1 reply; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

aplic_init_hw_interrupts() initialises the IPRIO field of the target
registers with APLIC_DEFAULT_PRIORITY, a constant private to aplic.c,
whereas, since commit 60004aa6da75 ("xen/riscv: add missing APLIC
register offsets, masks to asm/aplic.h"), the fields of each APLIC
register and the values they take are defined in <asm/aplic.h>, right
below the register's offset, as described at the top of that header.

Define APLIC_TARGET_IPRIO and APLIC_TARGET_IPRIO_DEFAULT there
accordingly and use the latter instead of APLIC_DEFAULT_PRIORITY. As
the layout of the target register depends on the delivery mode, and
IPRIO overlaps with EIID, also note which fields exist in which mode.

No functional change.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - New patch, split out of "xen/riscv: implement virtual APLIC MMIO
   emulation".
---
---
 xen/arch/riscv/aplic.c             | 6 ++----
 xen/arch/riscv/include/asm/aplic.h | 4 ++++
 2 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
index 79bbc0e864d5..bffa29bb21ac 100644
--- a/xen/arch/riscv/aplic.c
+++ b/xen/arch/riscv/aplic.c
@@ -28,8 +28,6 @@
 #include <asm/io.h>
 #include <asm/riscv_encoding.h>
 
-#define APLIC_DEFAULT_PRIORITY  1
-
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
 };
@@ -58,9 +56,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);
diff --git a/xen/arch/riscv/include/asm/aplic.h b/xen/arch/riscv/include/asm/aplic.h
index 51be469b69e5..6afdb9cae7a2 100644
--- a/xen/arch/riscv/include/asm/aplic.h
+++ b/xen/arch/riscv/include/asm/aplic.h
@@ -86,9 +86,13 @@
 #define APLIC_TARGET_LAST               0x3ffc
 #define  APLIC_TARGET_HART_IDX          GENMASK(31, 18)
 #define  APLIC_TARGET_HART_IDX_SHIFT    18
+/* If target is in MSI delivery mode (domaincfg.DM = 1) */
 #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 direct delivery mode (domaincfg.DM = 0) */
+#define  APLIC_TARGET_IPRIO             GENMASK(7, 0)
+#define   APLIC_TARGET_IPRIO_DEFAULT    1U
 
 #define APLIC_IDC_SIZE                  32
 
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index()
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (3 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-27 16:00   ` Baptiste Le Duc
  2026-11-13 15:48 ` [PATCH v4 06/42] xen/riscv: introduce CPU_NONE Oleksii Kurochko
                   ` (36 subsequent siblings)
  41 siblings, 1 reply; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

aplic_set_irq_affinity() computes the target register value by hand:

    cpu         = cpuid_to_hartid(<cpu picked from mask>);
    group_index = <bits taken from msi[cpu].base_addr>;
    hart_index  = cpu;

This is wrong in three ways:

- msi[] is indexed by logical CPU id, not by hart id. When the two
  differ, the wrong CPU's interrupt file is used, or msi[] is read
  out of bounds.

- The hart id is used as the low hart index. The AIA spec defines
  the low hart index as bits of the IMSIC interrupt file address,
  and the two are not guaranteed to be equal.

- The group index is taken from msi[].base_addr only. base_addr is
  the start of the IMSIC MMIO region, which may hold the interrupt
  files of several harts; the file of this CPU is at base_addr +
  msi[].offset, and both indexes must be extracted from that
  address.

Introduce aplic_hart_index(), together with the
APLIC_xMSICFGADDR_PPN_* macros it uses, which does this correctly: it
derives both indexes from the full address of the CPU's interrupt file
and packs them the way the Hart Index field expects. Use it here, and
insert the result with MASK_INSR(APLIC_TARGET_HART_IDX) rather than a
plain shift, so it cannot overflow the 14-bit field.
APLIC_TARGET_HART_IDX_SHIFT has no users left and is removed.

desc->irq is written as the EIID unchanged. Assert that it is a
valid APLIC source number, which also ensures it fits in the EIID
field.

No functional change on platforms with a single group, hart ids
equal to CPU ids, and one interrupt file per IMSIC MMIO region.

Fixes: d4676a1398bc ("xen/riscv: implementation of aplic and imsic operations")
Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Reword the commit message.
 - Initialize cpu in its declaration.
 - Introduce aplic_hart_index() and the APLIC_xMSICFGADDR_PPN_* macros
   here, moving them from "xen/riscv: implement virtual APLIC MMIO
   emulation", so that this patch no longer depends on it.
 - In the comment on the MSI address, describe g and h as the group
   number and the hart number relative to the group: the Hart Index
   is (g << lhxw) | h, not h.
---
Changes in v3:
 - s/aplic_hart_field/aplic_hart_index/ (in the subject too) following the
   rename of the helper in "xen/riscv: implement virtual APLIC MMIO
   emulation".
 - Don't mask desc->irq with APLIC_TARGET_EIID. Instead, bound it by
   the APLIC source range rather than NR_IRQS, which will also have to
   cover device MSIs: add a BUILD_BUG_ON() that ARRAY_SIZE(target) fits
   the EIID field and an ASSERT() that desc->irq is a valid APLIC source
   (1..num_irqs), which also covers the target[desc->irq - 1] index.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/aplic.c             | 117 +++++++++++++++++++++++------
 xen/arch/riscv/include/asm/aplic.h |  10 ++-
 2 files changed, 103 insertions(+), 24 deletions(-)

diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
index bffa29bb21ac..29663bc29b7b 100644
--- a/xen/arch/riscv/aplic.c
+++ b/xen/arch/riscv/aplic.c
@@ -41,6 +41,90 @@ 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
+ * 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 number (g), the
+ * hart number relative to the group (h) and, for a supervisor-level
+ * interrupt domain, the Guest Index:
+ *
+ *   ( Base PPN | (g << (HHXS + 12)) | (h << LHXS) | Guest Index ) << 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
+ * 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.
+ *
+ * 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_index(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;
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
@@ -207,10 +291,8 @@ 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;
+    unsigned int cpu = aplic_get_cpu_from_mask(mask);
+    uint32_t value;
 
     /*
      * TODO: Currently, APLIC is supported only with MSI interrupts.
@@ -223,27 +305,16 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
     ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
     /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
+     * desc->irq is used as the EIID as-is, which is only valid for APLIC
+     * sources: they are numbered 1..num_irqs, with at most ARRAY_SIZE(target).
      */
-    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);
+    BUILD_BUG_ON(ARRAY_SIZE(aplic.regs->target) >
+                 MASK_EXTR(~0U, APLIC_TARGET_EIID));
+    ASSERT(desc->irq && desc->irq <= aplic_info.num_irqs);
+
+    value = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
+            desc->irq;
 
     spin_lock(&aplic.lock);
 
diff --git a/xen/arch/riscv/include/asm/aplic.h b/xen/arch/riscv/include/asm/aplic.h
index 6afdb9cae7a2..93f0033b52d0 100644
--- a/xen/arch/riscv/include/asm/aplic.h
+++ b/xen/arch/riscv/include/asm/aplic.h
@@ -85,7 +85,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
 /* If target is in MSI delivery mode (domaincfg.DM = 1) */
 #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
 /* Bit 11 is reserved and reads as zero */
@@ -102,6 +101,15 @@
 #define APLIC_SIZE(nr_cpus) \
     (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+#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 */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 06/42] xen/riscv: introduce CPU_NONE
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (4 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index() Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-27 16:08   ` Baptiste Le Duc
  2026-11-13 15:48 ` [PATCH v4 07/42] xen/riscv: introduce device-agnostic MMIO emulation dispatch Oleksii Kurochko
                   ` (35 subsequent siblings)
  41 siblings, 1 reply; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Introduce CPU_NONE, a CPU number which doesn't identify any physical
CPU, to be used wherever a pCPU has to be recorded but there may be
none.

NR_CPUS has been used for that so far: hartid_to_cpuid() returns it for
a hart Xen doesn't know, pcpu_info[] uses it for an entry whose
processor_id isn't valid yet, and vsfile_cpu in struct vimsic_state,
which records the pCPU whose h/w guest interrupt file backs the vCPU's
IMSIC VS-file, uses it to mean that no h/w guest interrupt file is
attached. NR_CPUS is however the number of possible CPUs, i.e. an upper
bound, and a comparison against it reads like a range check rather than
like a test for "no pCPU". Use CPU_NONE in all these places instead,
which states that meaning explicitly.

Checks telling valid CPU numbers from invalid ones by comparing them
against NR_CPUS or nr_cpu_ids keep working, as CPU_NONE is made sure at
build time not to be below NR_CPUS.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
CPU_NONE is also used later in this series:
 - "xen/riscv: implement virtual APLIC MMIO emulation" checks vsfile_cpu
   against it to tell whether the target vCPU has a h/w guest interrupt
   file.
 - "xen/riscv: implement vCPU context switching" initialises the new
   arch_vcpu.last_cpu with it.
 - "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu",
   "xen/riscv: remap interrupts to new IMSIC VS-file" and
   "xen/riscv: save and clear the old IMSIC VS-file on vCPU migration"
   check vsfile_cpu against it to tell a vCPU without a h/w guest
   interrupt file.
 - "xen/riscv: introduce imsic_migrate_vcpu()" checks vsfile_cpu against
   it to tell whether the vCPU has a h/w guest interrupt file to move.
---
Changes in v4:
 - Switch hartid_to_cpuid() and pcpu_info[] over to CPU_NONE as well,
   and update the commit message accordingly.
 - Add BUILD_BUG_ON(CPU_NONE < NR_CPUS) to smp_processor_id().
---
Changes in v3:
 - New patch.
---
---
 xen/arch/riscv/imsic.c               | 6 +++---
 xen/arch/riscv/include/asm/config.h  | 3 +++
 xen/arch/riscv/include/asm/current.h | 2 ++
 xen/arch/riscv/include/asm/imsic.h   | 2 +-
 xen/arch/riscv/include/asm/smp.h     | 2 +-
 xen/arch/riscv/smp.c                 | 4 ++--
 6 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index 44b8640ea39a..8f29c5d2eec1 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -357,9 +357,9 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
     /*
      * xvzalloc() already cleared the context, so guest_file_id == 0, i.e. the
      * always-available s/w IMSIC VS-file. Only vsfile_cpu needs an explicit
-     * initializer as its s/w VS-file value is NR_CPUS rather than 0.
+     * initializer as its s/w VS-file value is CPU_NONE rather than 0.
      */
-    imsic_state->vsfile_cpu = NR_CPUS;
+    imsic_state->vsfile_cpu = CPU_NONE;
 
     v->arch.vimsic_state = imsic_state;
 
@@ -465,7 +465,7 @@ int __init imsic_init(const struct dt_device_node *node)
         }
 
         /*
-         * hartid_to_cpuid() returns NR_CPUS for a hart Xen doesn't know, so
+         * hartid_to_cpuid() returns CPU_NONE for a hart Xen doesn't know, so
          * the range has to be checked before msi[] is indexed at all.
          */
         cpu = hartid_to_cpuid(hartid);
diff --git a/xen/arch/riscv/include/asm/config.h b/xen/arch/riscv/include/asm/config.h
index 8d43ee76da5f..c61406e9dcf8 100644
--- a/xen/arch/riscv/include/asm/config.h
+++ b/xen/arch/riscv/include/asm/config.h
@@ -136,6 +136,9 @@
 #define OPT_CONSOLE_STR "dtuart"
 #define INVALID_VCPU_ID MAX_VIRT_CPUS
 
+/* A CPU number which doesn't identify any physical CPU. */
+#define CPU_NONE (~0U)
+
 /* Linkage for RISCV */
 #ifdef __ASSEMBLER__
 #define CODE_FILL /* empty */
diff --git a/xen/arch/riscv/include/asm/current.h b/xen/arch/riscv/include/asm/current.h
index 06683d7ae060..1f1010e5864f 100644
--- a/xen/arch/riscv/include/asm/current.h
+++ b/xen/arch/riscv/include/asm/current.h
@@ -35,6 +35,8 @@ static inline unsigned int smp_processor_id(void)
 {
     unsigned int id = tp->processor_id;
 
+    /* An entry whose processor_id isn't valid yet holds CPU_NONE. */
+    BUILD_BUG_ON(CPU_NONE < NR_CPUS);
     BUG_ON(id >= NR_CPUS);
 
     return id;
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index 639ee327dc67..11e1e3950f42 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -71,7 +71,7 @@ struct vimsic_state {
      */
     unsigned int guest_file_id;
     /*
-     * s/w IMSIC VS-file -> vsfile_cpu == NR_CPUS
+     * s/w IMSIC VS-file -> vsfile_cpu == CPU_NONE
      * h/w IMSIC VS-file -> vsfile_cpu < NR_CPUS
      */
     unsigned int vsfile_cpu;
diff --git a/xen/arch/riscv/include/asm/smp.h b/xen/arch/riscv/include/asm/smp.h
index 625e30b91bb2..3d3d1fa7fbaf 100644
--- a/xen/arch/riscv/include/asm/smp.h
+++ b/xen/arch/riscv/include/asm/smp.h
@@ -28,7 +28,7 @@ static inline unsigned int hartid_to_cpuid(unsigned long hartid)
     }
 
     /* hartid isn't valid for some reason */
-    return NR_CPUS;
+    return CPU_NONE;
 }
 
 static inline void set_cpuid_to_hartid(unsigned long cpuid,
diff --git a/xen/arch/riscv/smp.c b/xen/arch/riscv/smp.c
index d645364ea47d..21f4dc006252 100644
--- a/xen/arch/riscv/smp.c
+++ b/xen/arch/riscv/smp.c
@@ -9,10 +9,10 @@
  * tp points to one of these per cpu.
  *
  * hart_id would be valid (no matter which value) if its
- * processor_id field is valid (less than NR_CPUS).
+ * processor_id field is valid (not CPU_NONE).
  */
 struct pcpu_info pcpu_info[NR_CPUS] = { [0 ... NR_CPUS - 1] = {
-    .processor_id = NR_CPUS,
+    .processor_id = CPU_NONE,
 }};
 
 void smp_send_event_check_mask(const cpumask_t *mask)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 07/42] xen/riscv: introduce device-agnostic MMIO emulation dispatch
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (5 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 06/42] xen/riscv: introduce CPU_NONE Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-27 16:42   ` Baptiste Le Duc
  2026-11-13 15:48 ` [PATCH v4 08/42] xen/riscv: distinguish h/w and virtual vINTC sources Oleksii Kurochko
                   ` (34 subsequent siblings)
  41 siblings, 1 reply; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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.

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 do_mmio()
entry point and remains agnostic of which device owns a particular
address.

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

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
do_mmio() gets its first caller in "xen/riscv: add guest load emulation
for trapped MMIO accesses" in this series.
---
Changes in v4:
 - Put the opening brace of enum io_state on the same line as the
   enum's name.
 - Drop the redundant else in try_handle_mmio().
 - Allocate struct vmmio dynamically and make its definition, together
   with MAX_IO_HANDLER and struct mmio_handler, private to mmio.c, so
   that <asm/domain.h> doesn't need <asm/mmio.h> any more. As a result,
   domain_io_init() can fail again and domain_io_free() is reintroduced.
 - Name the domain parameter of find_mmio_handler() currd (and constify
   it) and the vCPU variable of try_handle_mmio() curr, as both always
   refer to current.
 - Drop the NULL check of ops and turn the checks of its callbacks into
   an ASSERT(), keeping -EINVAL for an empty or wrapping region.
---
Changes in v3:
 - Update the commit message.
 - Capitalize the comments inside mmio_info_t and drop the list of access
   widths from the one on len, as it could go stale.
 - Drop the parentheses around the typedef names.
 - Reject an access width which isn't a power of 2 in do_mmio().
 - Fold the !size check of register_mmio_handler() into end <= addr.
 - Return -EADDRINUSE instead of -EEXIST for an overlapping region.
 - Drop setting d->arch.vmmio.num_entries to 0, as struct domain starts
   out zero-filled.
---
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             |   6 +
 xen/arch/riscv/include/asm/domain.h |   2 +
 xen/arch/riscv/include/asm/mmio.h   |  48 +++++++
 xen/arch/riscv/mmio.c               | 205 ++++++++++++++++++++++++++++
 5 files changed, 262 insertions(+)
 create mode 100644 xen/arch/riscv/include/asm/mmio.h
 create mode 100644 xen/arch/riscv/mmio.c

diff --git a/xen/arch/riscv/Makefile b/xen/arch/riscv/Makefile
index 665ec2693335..5454517724bd 100644
--- a/xen/arch/riscv/Makefile
+++ b/xen/arch/riscv/Makefile
@@ -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
diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index cfce8e91fa16..683c37c0ee5a 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -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>
 
@@ -294,6 +295,8 @@ void arch_domain_destroy(struct domain *d)
     printk(XENLOG_WARNING "%s: not fully implemented\n", __func__);
 
     domain_vintc_deinit(d);
+
+    domain_io_free(d);
 }
 
 int arch_domain_create(struct domain *d,
@@ -310,6 +313,9 @@ int arch_domain_create(struct domain *d,
     if ( (rc = p2m_init(d, config)) != 0)
         goto fail;
 
+    if ( (rc = domain_io_init(d)) )
+        goto fail;
+
     if ( (rc = domain_vintc_init(d)) )
         goto fail;
 
diff --git a/xen/arch/riscv/include/asm/domain.h b/xen/arch/riscv/include/asm/domain.h
index 98e5e72e58ba..8c48833353f5 100644
--- a/xen/arch/riscv/include/asm/domain.h
+++ b/xen/arch/riscv/include/asm/domain.h
@@ -101,6 +101,8 @@ struct arch_domain {
     const unsigned long *isa;
 
     struct vintc *vintc;
+
+    struct vmmio *vmmio;
 };
 
 #include <xen/sched.h>
diff --git a/xen/arch/riscv/include/asm/mmio.h b/xen/arch/riscv/include/asm/mmio.h
new file mode 100644
index 000000000000..21402f67eb2a
--- /dev/null
+++ b/xen/arch/riscv/include/asm/mmio.h
@@ -0,0 +1,48 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#ifndef RISCV_MMIO_H
+#define RISCV_MMIO_H
+
+#include <xen/lib.h>
+
+struct domain;
+struct vcpu;
+
+typedef struct {
+    paddr_t gpa;
+    unsigned int len;  /* Access width in bytes */
+    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;
+};
+
+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);
+int domain_io_init(struct domain *d);
+void domain_io_free(struct domain *d);
+
+#endif /* RISCV_MMIO_H */
+
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
diff --git a/xen/arch/riscv/mmio.c b/xen/arch/riscv/mmio.c
new file mode 100644
index 000000000000..feeff06e3a12
--- /dev/null
+++ b/xen/arch/riscv/mmio.c
@@ -0,0 +1,205 @@
+/* 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 <xen/xvmalloc.h>
+
+#include <asm/current.h>
+#include <asm/mmio.h>
+
+#define MAX_IO_HANDLER  16
+
+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];
+};
+
+/*
+ * 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(const struct domain *currd, paddr_t gpa,
+                              struct mmio_handler *out)
+{
+    struct vmmio *vmmio = currd->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 *curr = current;
+    struct mmio_handler handler = {};
+
+    if ( !find_mmio_handler(curr->domain, info->gpa, &handler) )
+        return IO_UNHANDLED;
+
+    if ( info->is_write )
+        return handler.ops->write(curr, info);
+
+    return handler.ops->read(curr, 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 ( (len & (len - 1)) || (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)
+{
+    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;
+
+    ASSERT(ops->read && ops->write);
+
+    if ( end <= addr )
+        return -EINVAL;
+
+    write_lock(&vmmio->lock);
+
+    if ( vmmio->num_entries >= ARRAY_SIZE(vmmio->handlers) )
+    {
+        rc = -ENOSPC;
+        goto out;
+    }
+
+    /*
+     * The array is kept sorted by base address, so rather than appending and
+     * re-sorting, find the slot the new region belongs to and shift the tail
+     * up by one.
+     */
+    for ( i = vmmio->num_entries;
+          i > 0 && handlers[i - 1].addr > addr;
+          i-- )
+        /* Nothing to do */;
+
+    /*
+     * Regions are required not to overlap; check both neighbours. Their
+     * addr + size cannot overflow, as such regions are rejected above when
+     * they get registered.
+     */
+    overlap = (i > 0 && handlers[i - 1].addr + handlers[i - 1].size > addr) ||
+              (i < vmmio->num_entries && end > handlers[i].addr);
+
+    if ( overlap )
+    {
+        rc = -EADDRINUSE;
+        goto out;
+    }
+
+    memmove(&handlers[i + 1], &handlers[i],
+            (vmmio->num_entries - i) * sizeof(*handlers));
+
+    handlers[i] = (struct mmio_handler){
+        .addr = addr,
+        .size = size,
+        .ops = ops,
+    };
+
+    vmmio->num_entries++;
+
+ out:
+    write_unlock(&vmmio->lock);
+
+    return rc;
+}
+
+int domain_io_init(struct domain *d)
+{
+    struct vmmio *vmmio = xvzalloc(struct vmmio);
+
+    if ( !vmmio )
+        return -ENOMEM;
+
+    rwlock_init(&vmmio->lock);
+    d->arch.vmmio = vmmio;
+
+    return 0;
+}
+
+void domain_io_free(struct domain *d)
+{
+    XVFREE(d->arch.vmmio);
+}
+
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 08/42] xen/riscv: distinguish h/w and virtual vINTC sources
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (6 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 07/42] xen/riscv: introduce device-agnostic MMIO emulation dispatch Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-12-01 12:54   ` Baptiste Le Duc
  2026-11-13 15:48 ` [PATCH v4 09/42] xen/riscv: implement virtual APLIC MMIO emulation Oleksii Kurochko
                   ` (33 subsequent siblings)
  41 siblings, 1 reply; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

A vIRQ of a domain's vINTC is either a h/w source, one a physical IRQ is
routed to by route_irq_to_guest(), or a virtual source, whose line is
driven by the emulator of a device in Xen and whose state exists in the
vINTC only. used_irqs only tells that a vIRQ is taken, not which of the
two it is, whereas they have to be told apart: only a h/w source has a
physical IRQ to release when the domain goes away, and h/w registers to
keep in line with the guest's view.

Track the h/w sources in a new hw_irqs bitmap, the subset of used_irqs
a h/w IRQ is routed to. intc_route_irq_to_guest() sets the vIRQ's bit
there, so it now takes the domain and the vIRQ, and
domain_vintc_deinit() releases the h/w sources only.

An IRQ shared between devices is routed to the domain once per device,
so vintc_reserve_virq() legitimately fails with -EEXIST for all but the
first of them. map_irq_to_domain() now accepts -EEXIST only for a vIRQ
which is a h/w source already, so that a vIRQ reserved for a virtual
source can't be taken over by a h/w IRQ.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
More context on why the two kinds of sources have to be told apart is
given by the patches relying on hw_irqs:
 - "xen/riscv: implement virtual APLIC MMIO emulation", the next one,
   which accesses the registers of a source in the h/w APLIC only for a
   h/w source;
 - "xen/riscv: introduce vaplic_reconfigure_target()", which retargets
   the h/w sources only;
 - the patches introducing virtual sources to vAPLIC:
   "xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE",
   "xen/riscv: emulate target[] of virtual vAPLIC sources",
   "xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC
   sources" and "xen/riscv: drive the line of a virtual vAPLIC source".
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/device.c           | 17 ++++++++++++-----
 xen/arch/riscv/include/asm/intc.h |  5 ++++-
 xen/arch/riscv/intc.c             | 26 +++++++++++++++++++-------
 xen/arch/riscv/irq.c              |  2 +-
 4 files changed, 36 insertions(+), 14 deletions(-)

diff --git a/xen/arch/riscv/device.c b/xen/arch/riscv/device.c
index fc41c075c772..4c1e18b83c3a 100644
--- a/xen/arch/riscv/device.c
+++ b/xen/arch/riscv/device.c
@@ -25,14 +25,21 @@ int __overlay_init map_irq_to_domain(struct domain *d, unsigned int irq,
     {
         /*
          * -EEXIST merely means that the IRQ has already been reserved, which
-         * legitimately happens when the IRQ is shared between devices. Any
-         * other failure has to be fatal: the IRQ would otherwise be routed to
-         * the domain without domain_vintc_deinit() ever releasing it again.
+         * legitimately happens when the IRQ is shared between devices: the
+         * vIRQ is then a h/w source already, route_irq_to_guest() having
+         * connected it to the IRQ for the first of them. A vIRQ reserved for
+         * a virtual source, whose line an emulator in Xen drives, mustn't be
+         * taken over by a h/w IRQ, though. Any other failure has to be fatal
+         * too: the IRQ would otherwise be routed to the domain without
+         * domain_vintc_deinit() ever releasing it again.
          */
         res = vintc_reserve_virq(d, irq);
-        if ( res && (res != -EEXIST) )
+        if ( res == -EEXIST && test_bit(irq, d->arch.vintc->hw_irqs) )
+            res = 0;
+        if ( res )
         {
-            printk(XENLOG_ERR "Unable to reserve vIRQ %u for %pd\n", irq, d);
+            printk(XENLOG_ERR "Unable to reserve vIRQ %u for %pd: %d\n",
+                   irq, d, res);
             return res;
         }
 
diff --git a/xen/arch/riscv/include/asm/intc.h b/xen/arch/riscv/include/asm/intc.h
index 909317335769..7a31c6a298a0 100644
--- a/xen/arch/riscv/include/asm/intc.h
+++ b/xen/arch/riscv/include/asm/intc.h
@@ -69,6 +69,8 @@ struct vintc_ops {
 struct vintc {
     unsigned int nr_virqs;
     unsigned long *used_irqs;
+    /* Sources of used_irqs a h/w IRQ is routed to; the rest are virtual. */
+    unsigned long *hw_irqs;
     /* Callbacks invoked during domain construction only. */
     const struct vintc_init_ops *init_ops;
     /* Runtime callbacks used for the lifetime of the guest. */
@@ -82,7 +84,8 @@ void register_intc_ops(const struct intc_hw_init_ops *init_ops);
 void intc_init(void);
 
 void intc_route_irq_to_xen(struct irq_desc *desc, unsigned int priority);
-int intc_route_irq_to_guest(struct irq_desc *desc, unsigned int priority);
+int intc_route_irq_to_guest(const struct domain *d, unsigned int virq,
+                            struct irq_desc *desc, unsigned int priority);
 
 void intc_handle_external_irqs(struct cpu_user_regs *regs);
 
diff --git a/xen/arch/riscv/intc.c b/xen/arch/riscv/intc.c
index 810d126e263d..ac9c798ec36b 100644
--- a/xen/arch/riscv/intc.c
+++ b/xen/arch/riscv/intc.c
@@ -82,19 +82,25 @@ void intc_route_irq_to_xen(struct irq_desc *desc, unsigned int priority)
     intc_set_irq_priority(desc, priority);
 }
 
-int intc_route_irq_to_guest(struct irq_desc *desc,
-                            unsigned int priority)
+int intc_route_irq_to_guest(const struct domain *d, unsigned int virq,
+                            struct irq_desc *desc, unsigned int priority)
 {
     ASSERT(spin_is_locked(&desc->lock));
 
     ASSERT(intc_hw_ops->guest_irq_type);
 
+    /* The caller has reserved @virq, see vintc_reserve_virq(). */
+    ASSERT(virq < d->arch.vintc->nr_virqs);
+
     desc->handler = intc_hw_ops->guest_irq_type;
     desc->status |= IRQ_GUEST;
 
     intc_set_irq_type(desc, desc->arch.type);
     intc_set_irq_priority(desc, priority);
 
+    /* Connect @virq to the h/w IRQ: it isn't a virtual source. */
+    set_bit(virq, d->arch.vintc->hw_irqs);
+
     return 0;
 }
 
@@ -126,7 +132,10 @@ int domain_vintc_init(struct domain *d)
         d->arch.vintc->used_irqs =
             xvzalloc_array(unsigned long,
                            BITS_TO_LONGS(d->arch.vintc->nr_virqs));
-        if ( !d->arch.vintc->used_irqs )
+        d->arch.vintc->hw_irqs =
+            xvzalloc_array(unsigned long,
+                           BITS_TO_LONGS(d->arch.vintc->nr_virqs));
+        if ( !d->arch.vintc->used_irqs || !d->arch.vintc->hw_irqs )
             ret = -ENOMEM;
     }
 
@@ -140,17 +149,19 @@ void domain_vintc_deinit(struct domain *d)
     if ( !d->arch.vintc )
         return;
 
-    if ( d->arch.vintc->used_irqs )
+    if ( d->arch.vintc->hw_irqs )
     {
         unsigned int virq;
 
+        /* A virtual source has no h/w IRQ routed to the domain to release. */
         for ( virq = 0; virq < d->arch.vintc->nr_virqs; virq++ )
-            if ( test_bit(virq, d->arch.vintc->used_irqs) )
+            if ( test_bit(virq, d->arch.vintc->hw_irqs) )
                 release_guest_irq(d, virq);
-
-        XVFREE(d->arch.vintc->used_irqs);
     }
 
+    XVFREE(d->arch.vintc->used_irqs);
+    XVFREE(d->arch.vintc->hw_irqs);
+
     switch ( variant )
     {
     case INTC_APLIC:
@@ -169,6 +180,7 @@ void domain_vintc_deinit(struct domain *d)
  * Returns 0 on success, -EEXIST if @virq has already been reserved, which
  * legitimately happens when an IRQ is shared between devices, and -ERANGE if
  * @virq is outside the range of the interrupt sources the vINTC provides.
+ * A virtual source can't be shared, so for one -EEXIST is a failure.
  */
 int __overlay_init vintc_reserve_virq(const struct domain *d,
                                       unsigned int virq)
diff --git a/xen/arch/riscv/irq.c b/xen/arch/riscv/irq.c
index 9fc5a1bb703c..1b07b811b1fd 100644
--- a/xen/arch/riscv/irq.c
+++ b/xen/arch/riscv/irq.c
@@ -463,7 +463,7 @@ int route_irq_to_guest(struct domain *d, unsigned int virq,
     if ( retval )
         goto out;
 
-    retval = intc_route_irq_to_guest(desc, IRQ_NO_PRIORITY);
+    retval = intc_route_irq_to_guest(d, virq, desc, IRQ_NO_PRIORITY);
     if ( retval )
     {
         struct irqaction *action = irq_detach_action(desc, info);
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 09/42] xen/riscv: implement virtual APLIC MMIO emulation
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (7 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 08/42] xen/riscv: distinguish h/w and virtual vINTC sources Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 10/42] xen/riscv: leave the h/w source of an IRQ routed to a guest inactive Oleksii Kurochko
                   ` (32 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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.

Only the h/w (passed-through) sources of a domain, the ones a h/w IRQ is
routed to (see vintc->hw_irqs), are emulated, by passing the accesses to
their registers through to the physical APLIC. A virtual source has
nothing in the h/w, so it reads as zero and ignores writes, like a
source which isn't assigned to the domain.

Register the vAPLIC range with the MMIO dispatch and emulate the accesses:
 - reads and writes are masked with the domain's h/w sources, so that a
   guest can neither observe nor affect interrupts it does not own;
 - target registers are shadowed per source, so that a guest reads back
   what it wrote, or zero while the source is inactive, as target[i] is
   then read-only zero. Of a value written, only Hart Index and EIID are
   kept: Guest Index is read-only zero, as a guest's harts don't
   implement the H extension, and bit 11 is reserved. The h/w register
   instead gets the hart index and guest interrupt file of the pCPU the
   target vCPU's interrupt file lives on, as the APLIC uses these fields
   directly to compute the MSI address. As long as the target vCPU has
   no h/w guest interrupt file, only the shadow copy is updated;
 - vAPLIC is a leaf interrupt domain, so a source can't be delegated: a
   write to sourcecfg[] with D (bit 10) set zeroes the whole register,
   as the AIA spec requires for a leaf domain;
 - the registers a supervisor-level domain with domaincfg.BE hardwired
   to 0 doesn't implement, i.e. the MSI address configuration ones and
   setipnum_be, read as zero and ignore writes, as the AIA spec makes
   the bytes of a register which isn't implemented read-only zero;
 - only MSI delivery mode is emulated, so domaincfg.DM is hardwired to 1
   and the region holds no IDC structures;
 - domaincfg.IE isn't honoured: the h/w forwards the MSIs of the h/w
   sources whatever its value is. Linux as a guest sets IE before it
   enables any source and never clears it, so a write may set IE, but
   not clear it. This is temporary: honouring IE needs the guest's view
   of the enable bits of the h/w sources to be kept, which is left to a
   separate patch.

Co-developed-by: Romain Caritey <Romain.Caritey@microchip.com>
Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
The state of virtual sources, which devices emulated by Xen need, isn't
emulated here. It is introduced at the end of this series, by
"xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE",
"xen/riscv: emulate target[] of virtual vAPLIC sources",
"xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC
sources" and "xen/riscv: drive the line of a virtual vAPLIC source".

All the patches connected to virtual interrupts support for vAPLIC/vIMSIC
were tested on [1]. This branch is based on Denis M's framework which should
be soon sent to ML. Note that in [1] RISC-V is only draft version and
it has been ported in a quick way just to verify virtual interrupts are
working.

[1] https://gitlab.com/xen-project/people/olkur/xen/-/tree/riscv-vuart-support-wip?ref_type=heads
---
Changes in v4:
- Turn AUTH_IRQ_BIT() into a function, vaplic_is_hw_source(), as it
  now tells whether a source is a h/w one.
- Emulate only the h/w sources of the domain, the ones in
  vintc->hw_irqs: a virtual source reads as zero and ignores writes.
- Zero sourcecfg[] on a write with D set, as the AIA spec requires for a
  leaf domain, instead of crashing the domain, and log it at debug level.
  Drop APLIC_SOURCECFG_WMASK, as SM is then the only field a write may
  change.
- Emulate a read of sourcecfg[] instead of crashing the domain on it: a
  h/w source reads the h/w register, which a write goes to, and any other
  source reads as zero.
- Make mmsiaddrcfg, mmsiaddrcfgh, smsiaddrcfg, smsiaddrcfgh and
  setipnum_be read-only zero instead of crashing the domain on an access
  to them, and add APLIC_MMSICFGADDR{,H} and APLIC_SETIPNUM_BE.
- Make Guest Index of a target register read-only zero and drop the
  reserved bit 11, keeping Hart Index and EIID of the value written,
  instead of ignoring a write with a non-zero Guest Index as a whole.
- Sort <xen/sched.h> before <xen/sections.h>.
- Drop inline from generate_auth_mask().
- Compute the register offset as addr - regs_start: masking addr with
  APLIC_CTRL_REGION_OFFSET_MASK aliased the accesses beyond the first
  16 KiB onto its registers and relied on GUEST_APLIC_S_BASE being
  16 KiB aligned. Drop APLIC_CTRL_REGION_OFFSET_MASK.
- Hardwire domaincfg.DM to 1, as only MSI delivery mode is emulated, and
  drop the handling of a target register write in direct delivery mode.
- Let a write to domaincfg set IE, but not clear it, as IE isn't
  honoured.
- Size the vAPLIC region with no IDC structures, as an interrupt domain
  which supports only MSI delivery mode needs none, and rename the
  parameter of APLIC_SIZE() to nr_idcs to make that clear.
- Make target[i] read-only zero while source i is inactive.
- Use array_index_nospec() for the guest-controlled indexes into
  hw_irqs[] and sources[] after they are bounds-checked.
- Add a comment on why the writes passed through to the h/w can affect
  only the h/w sources of the domain.
- Drop the comment claiming that the value read is zero-extended to the
  guest register width: it is the load emulation which extends it, as the
  instruction requires.
- Constify target_vcpu in the target register emulation.
- Put the arguments of the "Unhandled APLIC write" message on one line.
- Rename the vCPU parameter of vaplic_mmio_{read,write}() to curr, as it
  is always current.
- Drop the "VAPLIC:" prefix of the gdprintk() messages in
  vaplic_mmio_{read,write}() and add a blank line before the return
  following them.
- Add a TODO comment about genmsi, which isn't emulated yet.
- Don't claim in the comment on writing the h/w target register that the
  stored copy reaches the h/w later, as nothing in this patch does that.
- Update the commit message for the changes above.
- Move the definitions of APLIC_TARGET_IPRIO{,_DEFAULT}, and the
  switch of aplic_init_hw_interrupts() to them, to a separate patch.
- Emulate a write to target[] in vaplic_target_write() instead of in
  vaplic_emulate_store(), and drop the comments repeating the code or
  struct vaplic_source.
- Read target[] under the lock of the source, so that a write is seen
  only once the h/w register follows it.
- Move aplic_hart_index() and the APLIC_xMSICFGADDR_PPN_* macros to
  "xen/riscv: build the target hart index via aplic_hart_index()", which
  now comes first.
---
Changes in v3:
- sourcecfg store emulation: mask the guest value with the new
  APLIC_SOURCECFG_WMASK (D and SM are the only implemented fields, all the
  other bits are reserved and read as zero) instead of rejecting the write
  when the value is above APLIC_SOURCECFG_SM_LEVEL_LOW. The dropped check
  compared the whole value against 7 rather than the SM field, so a legal
  SM with anything set in the reserved bits 9:3 was rejected. SM is WARL
  and vAPLIC keeps no shadow copy of sourcecfg[], so a reserved SM value
  is left to the h/w to normalize; add a TODO covering what will have to be
  emulated here once sourcecfg[] is shadowed.
- Introduce APLIC_SOURCECFG_WMASK in asm/aplic.h.
- target store emulation: reword the comment about a non-zero guest index
  to say that such a write is illegal and is therefore ignored as a whole,
  that the shadow copy keeps the zero it was allocated with, and that
  aplic_msi_target_gen() overwrites the field with vcpu_guest_file_id()
  anyway. Drop the now-redundant "Ignore such writes ..." comment.
- s/aplic_hart_field/aplic_hart_index/ (and the local variable with it):
  the value is the APLIC "Hart Index", not a field of it.
- Clarify the MSI target address documentation above aplic_hart_index():
  name the Guest Index in the address formula, say that the APLIC computes
  the MSI target address itself in MSI delivery mode, and label the two
  parts of the 14-bit Hart Index field as g and h to match the surrounding
  text.
- Don't add the MSI target address scheme diagram to asm/imsic.h: it
  would duplicate the one documented above aplic_hart_index().
- Fix the comment on APLIC_TARGET_IPRIO: the field exists when the target
  is in direct delivery mode (domaincfg.DM = 0), not "in DM mode".
- Rearrange the case blocks of vaplic_emulate_load() and
  vaplic_emulate_store() primarily by register offset: APLIC_DOMAINCFG
  comes first and APLIC_SOURCECFG handling directly follows it; the
  set/clr-num registers are also listed in offset order. No functional
  change.
- Rename the first parameter of aplic_msi_target_gen() from target_vcpu
  to v.
- Use a const-qualified pointer in aplic_hw_read_reg()'s cast to match
  readl()'s prototype.
- Put APLIC_xMSICFGADDR_PPN_HHX_MASK(), APLIC_xMSICFGADDR_PPN_LHX_MASK()
  and APLIC_xMSICFGADDR_PPN_LHX_SHIFT() on a single line each.
- Use gdprintk() instead of dprintk() for guest-triggered messages in
  vaplic.c and drop the redundant "is passed" from the word_idx message.
- Call domain_vaplic_deinit() in both failure paths of
  domain_vaplic_init() instead of open-coding the clean-up.
- aplic_msi_target_gen() takes the hart index from the pCPU the vCPU's
  interrupt file lives on (vsfile_cpu) instead of v->processor, which may
  already name the new pCPU while the vCPU is being migrated. Callers
  have to hold vsfile_lock until the value is written to the h/w, which
  the vAPLIC target write path now does.
- A target register write for a vCPU which has no h/w guest interrupt file
  yet (its vsfile_cpu is CPU_NONE) only updates the stored copy; the h/w
  register isn't programmed, as there is neither a hart nor a guest
  interrupt file to point it at. Add a TODO about s/w guest interrupt
  files, for which the h/w register will have to be written too.
- Turn vaplic_regs.target[] into vaplic_regs.sources[], an array of
  struct vaplic_source holding the guest's view of the target register
  together with a per-source lock which keeps the stored copy and the h/w
  target register updated as a pair. Document how many elements it holds
  and why index 0 is unused.
- Drop the emulation of target register writes in direct delivery mode:
  such writes are ignored with a one-time warning. Resolve the target
  vCPU only in the MSI delivery mode path, where it is used.
---
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         |   2 +
 xen/arch/riscv/aplic.c              |  49 +++
 xen/arch/riscv/include/asm/aplic.h  |  28 +-
 xen/arch/riscv/include/asm/vaplic.h |  19 ++
 xen/arch/riscv/vaplic.c             | 504 +++++++++++++++++++++++++++-
 5 files changed, 591 insertions(+), 11 deletions(-)

diff --git a/xen/arch/riscv/aplic-priv.h b/xen/arch/riscv/aplic-priv.h
index 009020c83fb9..9e85343cce0f 100644
--- a/xen/arch/riscv/aplic-priv.h
+++ b/xen/arch/riscv/aplic-priv.h
@@ -47,4 +47,6 @@ struct aplic_priv {
  */
 extern unsigned int guest_aplic_num_sources;
 
+uint32_t aplic_msi_target_gen(const struct vcpu *v, uint32_t base_val);
+
 #endif /* RISCV_APLIC_PRIV_H */
diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
index 29663bc29b7b..51d7eae4617a 100644
--- a/xen/arch/riscv/aplic.c
+++ b/xen/arch/riscv/aplic.c
@@ -15,6 +15,7 @@
 #include <xen/init.h>
 #include <xen/irq.h>
 #include <xen/mm.h>
+#include <xen/sched.h>
 #include <xen/sections.h>
 #include <xen/spinlock.h>
 #include <xen/types.h>
@@ -125,6 +126,54 @@ static unsigned long aplic_hart_index(unsigned int cpu)
     return (g << lhxw) | h;
 }
 
+/*
+ * v->processor can't be used here: during a migration it names the new pCPU
+ * before the interrupt file is moved there. The caller has to hold
+ * vsfile_lock until the result is written to the h/w.
+ */
+uint32_t aplic_msi_target_gen(const struct vcpu *v, uint32_t base_val)
+{
+    const struct vimsic_state *vimsic_state = v->arch.vimsic_state;
+    unsigned int guest_id = vcpu_guest_file_id(v);
+    unsigned long hart_index;
+
+    ASSERT(rw_is_locked(&vimsic_state->vsfile_lock));
+    ASSERT(vimsic_state->vsfile_cpu < NR_CPUS);
+
+    hart_index = aplic_hart_index(vimsic_state->vsfile_cpu);
+
+    base_val &= APLIC_TARGET_EIID;
+    base_val |= MASK_INSR(guest_id, APLIC_TARGET_GUEST_IDX);
+    base_val |= MASK_INSR(hart_index, 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((const 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;
diff --git a/xen/arch/riscv/include/asm/aplic.h b/xen/arch/riscv/include/asm/aplic.h
index 93f0033b52d0..b2f1d140f6f8 100644
--- a/xen/arch/riscv/include/asm/aplic.h
+++ b/xen/arch/riscv/include/asm/aplic.h
@@ -27,8 +27,6 @@
  * 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):
@@ -39,6 +37,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. DM is WARL and hardwired to 1 as only MSI
+ * delivery mode is emulated. 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
 
 #define APLIC_SOURCECFG_BASE            0x0004
 #define APLIC_SOURCECFG_LAST            0x0ffc
@@ -59,6 +64,8 @@
 #define   APLIC_SOURCECFG_SM_LEVEL_HIGH 0x6
 #define   APLIC_SOURCECFG_SM_LEVEL_LOW  0x7
 
+#define APLIC_MMSICFGADDR               0x1bc0
+#define APLIC_MMSICFGADDRH              0x1bc4
 #define APLIC_SMSICFGADDR               0x1bc8
 #define APLIC_SMSICFGADDRH              0x1bcc
 
@@ -79,6 +86,7 @@
 #define APLIC_CLRIENUM                  0x1fdc
 
 #define APLIC_SETIPNUM_LE               0x2000
+#define APLIC_SETIPNUM_BE               0x2004
 
 #define APLIC_GENMSI                    0x3000
 
@@ -98,8 +106,17 @@
 #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_idcs) \
+    (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_idcs)))
+
+/*
+ * 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
 
@@ -153,4 +170,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 /* RISCV_APLIC_H */
diff --git a/xen/arch/riscv/include/asm/vaplic.h b/xen/arch/riscv/include/asm/vaplic.h
index dcbe0d59a886..9a121904a346 100644
--- a/xen/arch/riscv/include/asm/vaplic.h
+++ b/xen/arch/riscv/include/asm/vaplic.h
@@ -11,6 +11,7 @@
 #define RISCV_VAPLIC_H
 
 #include <xen/kernel.h>
+#include <xen/spinlock.h>
 #include <xen/types.h>
 
 #include <asm/intc.h>
@@ -19,13 +20,31 @@ struct domain;
 
 #define to_vaplic(d) container_of((d)->arch.vintc, struct vaplic, vintc)
 
+/* State of one vAPLIC interrupt source. */
+struct vaplic_source {
+    /* Protects target together with the h/w target register of the source. */
+    spinlock_t lock;
+
+    /* Guest's view of the APLIC target register. */
+    uint32_t target;
+};
+
 struct vaplic_regs {
     uint32_t domaincfg;
+
+    /*
+     * Indexed by source number. The array holds d->arch.vintc->nr_virqs
+     * elements; sources[0] is unused as APLIC interrupt sources start from 1.
+     */
+    struct vaplic_source *sources;
 };
 
 struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
+
+    paddr_t regs_start;
+    unsigned int regs_size;
 };
 
 int domain_vaplic_init(struct domain *d);
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index 6fbdc07805fd..7898455b4934 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -11,12 +11,14 @@
 #include <xen/errno.h>
 #include <xen/fdt-kernel.h>
 #include <xen/libfdt/libfdt.h>
+#include <xen/nospec.h>
 #include <xen/sched.h>
 #include <xen/xvmalloc.h>
 
 #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,23 +29,428 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 
 #define FDT_VAPLIC_INT_CELLS 2
 
+/*
+ * Only a h/w source of a domain, one a h/w IRQ is routed to (see
+ * vintc.hw_irqs), may be accessed in the h/w. A virtual source has nothing
+ * there: until its state is emulated, it reads as zero and ignores writes,
+ * like a source not assigned to the domain.
+ */
+static bool vaplic_is_hw_source(const struct domain *d, unsigned int irqn)
+{
+    const struct vintc *vintc = d->arch.vintc;
+
+    return (irqn < vintc->nr_virqs) &&
+           test_bit(array_index_nospec(irqn, vintc->nr_virqs),
+                    vintc->hw_irqs);
+}
+
+/*
+ * Convert a byte offset (within a SETIP/CLRIP/SETIE/CLRIE register group) to
+ * a 32-bit word index into the hw_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))
+
+/*
+ * vAPLIC keeps no shadow copy of sourcecfg[], and a guest's writes to it go
+ * straight to the h/w register, so it is the h/w register which tells whether
+ * a source is active.
+ */
+static bool vaplic_source_is_active(unsigned int irqn)
+{
+    uint32_t sourcecfg = aplic_hw_read_reg(APLIC_SOURCECFG_BASE +
+                                           (irqn - 1) * sizeof(uint32_t));
+
+    /*
+     * A source is inactive if it is delegated to a child domain (D = 1), in
+     * which case the low bits hold the Child Index rather than SM, or if it
+     * isn't delegated and SM is Inactive.
+     */
+    return !(sourcecfg & APLIC_SOURCECFG_D) &&
+           (MASK_EXTR(sourcecfg, APLIC_SOURCECFG_SM) !=
+            APLIC_SOURCECFG_SM_INACTIVE);
+}
+
+static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    struct vaplic_source *src;
+    unsigned long flags;
+    uint32_t val = 0;
+
+    /* target[0] doesn't exist so irqn == 0 should be impossible */
+    if ( !irqn || irqn >= vaplic->vintc.nr_virqs )
+        return 0;
+
+    irqn = array_index_nospec(irqn, vaplic->vintc.nr_virqs);
+    src = &vaplic->regs.sources[irqn];
+
+    /*
+     * src->lock makes the read atomic as a whole, against a write to
+     * target[] which changes both this copy and the h/w register.
+     */
+    spin_lock_irqsave(&src->lock, flags);
+
+    /* target[i] is read-only zero while source i is inactive. */
+    if ( vaplic_source_is_active(irqn) )
+        val = src->target;
+
+    spin_unlock_irqrestore(&src->lock, flags);
+
+    return val;
+}
+
+/* Emulate a write of @value to target[@irqn]. */
+static void vaplic_target_write(const struct domain *d, unsigned int irqn,
+                                uint32_t value)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    struct vimsic_state *vimsic_state;
+    const struct vcpu *target_vcpu;
+    struct vaplic_source *src;
+    unsigned long flags;
+
+    if ( !vaplic_is_hw_source(d, irqn) )
+        return;
+
+    irqn = array_index_nospec(irqn, d->arch.vintc->nr_virqs);
+
+    /* target[i] is read-only zero while source i is inactive. */
+    if ( !vaplic_source_is_active(irqn) )
+        return;
+
+    target_vcpu = domain_vcpu(d, MASK_EXTR(value, APLIC_TARGET_HART_IDX));
+    if ( !target_vcpu )
+    {
+        gdprintk(XENLOG_ERR, "Invalid vCPU id in target register\n");
+
+        return;
+    }
+
+    /*
+     * Guest Index names an interrupt file of a nested guest, and the AIA
+     * spec makes it read-only zero unless the domain's harts implement the
+     * H extension, which a guest's harts don't. Bit 11 is reserved and reads
+     * as zero, so only Hart Index and EIID are kept.
+     * What ends up in the h/w register is Xen's own value anyway:
+     * aplic_msi_target_gen() takes only EIID from it.
+     */
+    value &= APLIC_TARGET_HART_IDX | APLIC_TARGET_EIID;
+
+    src = &vaplic->regs.sources[irqn];
+    vimsic_state = target_vcpu->arch.vimsic_state;
+
+    spin_lock_irqsave(&src->lock, flags);
+
+    write_atomic(&src->target, value);
+
+    /* IRQs are already off under src->lock. */
+    read_lock(&vimsic_state->vsfile_lock);
+
+    /*
+     * The h/w register names the hart and the guest interrupt file MSIs are
+     * sent to, and there is none of either until the target vCPU is given a
+     * h/w guest interrupt file, so until then only the stored copy is
+     * updated.
+     *
+     * TODO: once s/w guest interrupt files are supported, a vCPU using one
+     * still needs its MSIs, so the h/w register will have to be written for
+     * it too, pointing at an interrupt file Xen receives them in on the
+     * vCPU's behalf.
+     */
+    if ( vimsic_state->vsfile_cpu != CPU_NONE )
+        aplic_hw_write_reg(offsetof(struct aplic_regs, target[irqn - 1]),
+                           aplic_msi_target_gen(target_vcpu, value));
+
+    read_unlock(&vimsic_state->vsfile_lock);
+
+    spin_unlock_irqrestore(&src->lock, flags);
+}
+
+static uint32_t generate_auth_mask(const struct domain *currd,
+                                   unsigned int word_idx)
+{
+    unsigned int nr_words = DIV_ROUND_UP(currd->arch.vintc->nr_virqs,
+                                         sizeof(uint32_t) * BITS_PER_BYTE);
+    unsigned int first_bit;
+
+    if ( word_idx >= nr_words )
+    {
+        gdprintk(XENLOG_DEBUG, "incorrect word_idx(%u)\n", word_idx);
+
+        return 0;
+    }
+
+    first_bit = array_index_nospec(word_idx, nr_words) *
+                sizeof(uint32_t) * BITS_PER_BYTE;
+
+    return currd->arch.vintc->hw_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 - vaplic->regs_start;
+    uint32_t auth_mask;
+    unsigned int i;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_DOMAINCFG:
+        *out = vaplic->regs.domaincfg;
+
+        return true;
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        /*
+         * Look at vaplic_emulate_store() for explanation why APLIC_DOMAINCFG
+         * is subtracted.
+         */
+        i = regoffset_to_word_idx(offset - APLIC_DOMAINCFG);
+        *out = vaplic_is_hw_source(currd, i) ? aplic_hw_read_reg(offset) : 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_SETIPNUM:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+    case APLIC_CLRIENUM:
+    case APLIC_SETIPNUM_LE:
+        /*
+         * Based on the RISC-V AIA spec a read of these registers
+         * always returns zero
+         */
+        *out = 0;
+
+        return true;
+
+    /*
+     * vAPLIC is a supervisor-level domain with BE hardwired to 0, and such
+     * a domain doesn't implement these registers: the MSI address
+     * configuration ones exist in machine-level domains only, and
+     * setipnum_be isn't needed by a little-endian only domain. Bytes of a
+     * register which isn't implemented are read-only zero, like other
+     * reserved bytes.
+     */
+    case APLIC_MMSICFGADDR:
+    case APLIC_MMSICFGADDRH:
+    case APLIC_SMSICFGADDR:
+    case APLIC_SMSICFGADDRH:
+    case APLIC_SETIPNUM_BE:
+        *out = 0;
+
+        return true;
+
+    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 = vaplic_is_hw_source(currd, i) ? vaplic_target_read(currd, i) : 0;
+
+        return true;
+
+    /*
+     * TODO: emulate genmsi. A write to it has to send an extempore MSI to
+     * the target vCPU, and a guest typically waits for that MSI to become
+     * pending in its interrupt file. Just recording the written value would
+     * leave such a guest waiting forever, so until genmsi is emulated, an
+     * access to it is treated as an unhandled one, which gets the domain
+     * crashed.
+     */
+    case APLIC_GENMSI:
+    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;
+    struct vaplic *vaplic = to_vaplic(currd);
+    unsigned int offset = addr - vaplic->regs_start;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_DOMAINCFG:
+        /*
+         * TODO: domaincfg.IE isn't honoured: the h/w forwards the MSIs of the
+         * h/w sources whatever its value is. Linux as a guest sets IE before
+         * it enables any source and never clears it, so a write may set IE,
+         * but not clear it.
+         */
+        vaplic->regs.domaincfg |= value & APLIC_DOMAINCFG_WMASK;
+
+        return true;
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        /*
+         * vAPLIC is a leaf domain: it has no child domain a source could be
+         * delegated to. With D = 1, the low bits of the value would hold a
+         * Child Index rather than SM, and for a leaf domain the AIA spec
+         * makes such a write set the entire register to zero instead.
+         */
+        if ( value & APLIC_SOURCECFG_D )
+        {
+            gdprintk(XENLOG_DEBUG,
+                     "sourcecfg write with D set at offset %#x, zeroing it\n",
+                     offset);
+
+            value = 0;
+        }
+
+        /*
+         * SM is the only field left, the other bits are reserved and read as
+         * zero, so ignore what a guest writes to them.
+         */
+        value &= APLIC_SOURCECFG_SM;
+
+        /*
+         * 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
+         *   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 ( !vaplic_is_hw_source(currd,
+                                  regoffset_to_word_idx(offset -
+                                                        APLIC_DOMAINCFG)) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        break;
+
+    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_SETIPNUM:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+    case APLIC_SETIPNUM_LE:
+        if ( !value || !vaplic_is_hw_source(currd, value) )
+            return true;
+
+        break;
+
+    /* Not implemented by vAPLIC, see vaplic_emulate_load(). */
+    case APLIC_MMSICFGADDR:
+    case APLIC_MMSICFGADDRH:
+    case APLIC_SMSICFGADDR:
+    case APLIC_SMSICFGADDRH:
+    case APLIC_SETIPNUM_BE:
+        return true;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+        /*
+         * Look at vaplic_emulate_load() for explanation why APLIC_GENMSI is
+         * subtracted.
+         */
+        vaplic_target_write(currd,
+                            regoffset_to_word_idx(offset - APLIC_GENMSI),
+                            value);
+
+        return true;
+
+    /* TODO: emulate genmsi, see vaplic_emulate_load(). */
+    case APLIC_GENMSI:
+    default:
+        gdprintk(XENLOG_WARNING,
+                 "Unhandled APLIC write at offset %#x (value %#x)\n",
+                 offset, value);
+
+        return false;
+    }
+
+    /*
+     * What is left is passed through to the h/w, which can affect only the
+     * h/w sources of currd:
+     *  - setip, clrip, setie and clrie are write-1-to-set/clear, and the
+     *    value was masked with currd's h/w sources above, so the bits of
+     *    the other sources are written as 0, which leaves them untouched;
+     *  - {set,clr}i{p,e}num, setipnum_le and sourcecfg[] name one source,
+     *    which was checked above to be a h/w source of currd.
+     * route_irq_to_guest() never assigns a source to more than one domain,
+     * or to both a domain and Xen, and as virq == pirq, no translation is
+     * needed either.
+     */
+    aplic_hw_write_reg(offset, value);
+
+    return true;
+}
+
 static int __init cf_check vaplic_make_domu_dt_node(struct kernel_info *kinfo)
 {
-    struct domain *d = kinfo->bd.d;
     int res;
     void *fdt = kinfo->fdt;
     unsigned int msi_parent_phandle;
     char vaplic_name[32];
-    unsigned int aplic_size = APLIC_SIZE(d->max_vcpus);
     const __be32 reg[] = {
         cpu_to_be32(GUEST_APLIC_S_BASE >> 32),
         cpu_to_be32(GUEST_APLIC_S_BASE),
         cpu_to_be32(0),
-        cpu_to_be32(aplic_size),
+        cpu_to_be32(APLIC_SIZE(0)),
     };
 
-    BUILD_BUG_ON(APLIC_SIZE(MAX_VIRT_CPUS) > UINT_MAX);
-
     res = snprintf(vaplic_name, ARRAY_SIZE(vaplic_name), "/soc/aplic@%lx",
                    GUEST_APLIC_S_BASE);
     if ( res >= sizeof(vaplic_name) )
@@ -95,6 +502,57 @@ static const struct vintc_init_ops __initconstrel init_ops = {
     .make_domu_dt_node = vaplic_make_domu_dt_node,
 };
 
+static enum io_state cf_check vaplic_mmio_read(struct vcpu *curr,
+                                               mmio_info_t *info)
+{
+    uint32_t val;
+
+    ASSERT(curr == current);
+
+    if ( info->len != sizeof(uint32_t) ||
+         !IS_ALIGNED(info->gpa, sizeof(uint32_t)) )
+    {
+        gdprintk(XENLOG_DEBUG,
+                 "unaligned/wrong-width read gpa=%"PRIpaddr" len=%u\n",
+                 info->gpa, info->len);
+
+        return IO_ABORT;
+    }
+
+    if ( !vaplic_emulate_load(curr, info->gpa, &val) )
+        return IO_ABORT;
+
+    info->data = val;
+
+    return IO_HANDLED;
+}
+
+static enum io_state cf_check vaplic_mmio_write(struct vcpu *curr,
+                                                const mmio_info_t *info)
+{
+    ASSERT(curr == current);
+
+    if ( info->len != sizeof(uint32_t) ||
+         !IS_ALIGNED(info->gpa, sizeof(uint32_t)) )
+    {
+        gdprintk(XENLOG_DEBUG,
+                 "unaligned/wrong-width write gpa=%"PRIpaddr" len=%u\n",
+                 info->gpa, info->len);
+
+        return IO_ABORT;
+    }
+
+    if ( !vaplic_emulate_store(curr, info->gpa, info->data) )
+        return IO_ABORT;
+
+    return IO_HANDLED;
+}
+
+static const struct mmio_handler_ops vaplic_mmio_ops = {
+    .read  = vaplic_mmio_read,
+    .write = vaplic_mmio_write,
+};
+
 static const struct vintc_ops vintc_ops = {
     .vcpu_init = vcpu_imsic_init,
     .vcpu_deinit = vcpu_imsic_deinit,
@@ -103,6 +561,8 @@ static const struct vintc_ops vintc_ops = {
 int domain_vaplic_init(struct domain *d)
 {
     struct vaplic *vaplic = xvzalloc(struct vaplic);
+    unsigned int i;
+    int rc;
 
     if ( !vaplic )
         return -ENOMEM;
@@ -111,7 +571,7 @@ int domain_vaplic_init(struct domain *d)
     d->arch.vintc->ops = &vintc_ops;
     d->arch.vintc->init_ops = &init_ops;
 
-    vaplic->regs.domaincfg = APLIC_DOMAINCFG_RO;
+    vaplic->regs.domaincfg = APLIC_DOMAINCFG_RO | APLIC_DOMAINCFG_DM;
 
     /*
      * APLIC source 0 is reserved; sources are numbered
@@ -123,7 +583,36 @@ int domain_vaplic_init(struct domain *d)
      */
     d->arch.vintc->nr_virqs = guest_aplic_num_sources + 1;
 
-    return 0;
+    /* Slot 0 is unused: APLIC source numbering starts at 1 (see used_irqs). */
+    vaplic->regs.sources = xvzalloc_array(struct vaplic_source,
+                                          d->arch.vintc->nr_virqs);
+    if ( !vaplic->regs.sources )
+    {
+        domain_vaplic_deinit(d);
+
+        return -ENOMEM;
+    }
+
+    for ( i = 0; i < d->arch.vintc->nr_virqs; i++ )
+        spin_lock_init(&vaplic->regs.sources[i].lock);
+
+    vaplic->regs_start = GUEST_APLIC_S_BASE;
+    /*
+     * IDC structures are used only in direct delivery mode, so the control
+     * region of vAPLIC, which supports MSI delivery mode only, holds none.
+     *
+     * TODO: should direct delivery mode ever be supported, the region will
+     * have to hold an IDC structure per vCPU, i.e. be APLIC_SIZE(d->max_vcpus)
+     * here and in vaplic_make_domu_dt_node().
+     */
+    vaplic->regs_size = APLIC_SIZE(0);
+
+    rc = register_mmio_handler(d, &vaplic_mmio_ops,
+                               vaplic->regs_start, vaplic->regs_size);
+    if ( rc )
+        domain_vaplic_deinit(d);
+
+    return rc;
 }
 
 void domain_vaplic_deinit(struct domain *d)
@@ -135,5 +624,6 @@ void domain_vaplic_deinit(struct domain *d)
 
     vaplic = to_vaplic(d);
     d->arch.vintc = NULL;
+    xvfree(vaplic->regs.sources);
     xvfree(vaplic);
 }
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 10/42] xen/riscv: leave the h/w source of an IRQ routed to a guest inactive
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (8 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 09/42] xen/riscv: implement virtual APLIC MMIO emulation Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 11/42] xen/riscv: implement vCPU context switching Oleksii Kurochko
                   ` (31 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

intc_route_irq_to_guest() has set the h/w IRQ to the trigger type given
by the host DT. A guest configures its h/w sources itself, though:
vAPLIC passes the guest's writes to their sourcecfg[] through to the h/w
registers. So whatever Xen writes there at routing time gets
overwritten, and until then a source the guest hasn't configured yet
isn't in its reset state, Inactive.

Put the h/w source into Inactive instead, by IRQ_TYPE_NONE. That also
covers an IRQ an earlier domain has left configured, as nothing resets
the h/w source when the IRQ is released. desc->arch.type stays as it is,
and the guest learns the trigger type from its DT as before.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
This patch doesn't depend on the rest of the series, but what it
prevents only shows up later in it:
 - from "xen/riscv: introduce IMSIC h/w interrupt file attaching to
   vcpu" on, the h/w target register of a guest's h/w source points at a
   real guest interrupt file, so a source left active could deliver an
   MSI there before the guest has configured it;
 - "xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC
   sources" reads the h/w pending bits of h/w sources as they are, and
   these stay in line with the guest's view of the source being
   Inactive only if the h/w source is Inactive as well.
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/intc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/xen/arch/riscv/intc.c b/xen/arch/riscv/intc.c
index ac9c798ec36b..cdbc039d0258 100644
--- a/xen/arch/riscv/intc.c
+++ b/xen/arch/riscv/intc.c
@@ -95,7 +95,7 @@ int intc_route_irq_to_guest(const struct domain *d, unsigned int virq,
     desc->handler = intc_hw_ops->guest_irq_type;
     desc->status |= IRQ_GUEST;
 
-    intc_set_irq_type(desc, desc->arch.type);
+    intc_set_irq_type(desc, IRQ_TYPE_NONE);
     intc_set_irq_priority(desc, priority);
 
     /* Connect @virq to the h/w IRQ: it isn't a virtual source. */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 11/42] xen/riscv: implement vCPU context switching
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (9 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 10/42] xen/riscv: leave the h/w source of an IRQ routed to a guest inactive Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 12/42] xen/riscv: save and restore vsiselect on vCPU context switch Oleksii Kurochko
                   ` (30 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Implement context_switch() and the helpers it needs: save/restore of
H/VS CSRs, virtual timer and P2M context, and __context_switch() in
assembly, which switches Xen's own callee-saved state (and thereby the
stack) from prev to next. The virtual interrupt controller state isn't
switched here.

Add offsets of struct arch_vcpu's xen_saved_context to asm-offsets.c for
use by __context_switch().

henvcfg, htimedelta and vsie are 64-bit on both RV32 and RV64, so store
them as uint64_t and access them with csr_{read,write}64(). For that
purpose introduce csr_read64().

The VMID has to be claimed on the context switch rather than on guest
entry: once p2m_ctxt_switch_to() writes HGATP, speculation can populate
G-stage entries under whatever VMID is written there. This is done by
p2m_vmid_switch_to(), called right before the HGATP write:

 - VMIDs are a per-hart resource, so the (generation, vmid) pair of a
   vCPU which last ran on another hart is invalidated before a VMID is
   claimed for it. The local flush for a wrapped generation moves along
   with the claim.
 - Nothing is switched in for the idle vCPU, so HGATP keeps pointing at
   the p2m of the domain which ran on the hart last. Track that domain
   per hart (hgatp_owner) and keep the hart in its dirty_cpumask until a
   vCPU of another domain is switched in: p2m_tlb_flush() then goes on
   reaching the hart, and a domain which idles between two runs on the
   same hart keeps its VMIDs.
 - When the owner changes, the hart leaves the old owner's dirty_cpumask
   while its TLB may still hold that domain's G-stage translations, so it
   is moved to a new VMID generation, which makes none of them reachable
   again. It joins the new owner's dirty_cpumask before HGATP is written;
   a full barrier there, paired with one in p2m_tlb_flush(), guarantees
   that a concurrent P2M change either reaches the hart with an
   HFENCE.GVMA or is visible to it before it walks the p2m.

That leaves p2m_handle_vmenter() with nothing to do, so drop it together
with its call from check_for_pcpu_work(): a VMID is only ever invalidated
while its vCPU isn't running, and p2m_tlb_flush() drops stale entries
with a remote HFENCE.GVMA rather than by retiring VMIDs. Unlike
p2m_handle_vmenter(), HGATP is written unconditionally, as it holds the
G-stage root too, which on a context switch belongs to another domain.

While at it, fix the inclusion order of headers in asm-offsets.c: Xen's
headers go first, then arch specific ones.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Take the CSR name without the CSR_ prefix in csr_read64(), so that the
   macro parameter is used as an operand of ## only (MISRA C Rule 20.12),
   and update the csr_{read,write}64() callers accordingly.
 - Drop the (void) of the ...H constant on RV64.
 - Simplify the comment on resetting the VMID generation of a vCPU which
   comes from another hart.
 - Spell out in the comment on claiming the VMID what makes doing so on
   guest entry too late.
 - s/csr_regs_ctxt_switch_/csrs_ctxt_switch_/.
 - Replace the commented-out code in csrs_ctxt_switch_from() with a
   comment on why hedeleg, hideleg, henvcfg, hcounteren, htimedelta
   and hstateen0 aren't saved.
 - Declare __context_switch() asmlinkage, as it is implemented in
   assembly.
---
Changes in v3:
 - Update the commit message.
 - Introduce csr_read64(), as vsie is 64-bit on RV32 too, i.e. has to be
   accessed as the vsie/vsieh pair there.
 - Make vsie declared as uint64_t instead of register_t.
 - Rename the parameter of save_csr_regs() to p and of restore_csr_regs()
   to n, to match their callers ctxt_switch_from()/ctxt_switch_to() and the
   rest of the context switch helpers (p2m_ctxt_switch_{from,to}(),
   vtimer_ctxt_switch_{from,to}()).
 - s/save_csr_regs/csr_regs_ctxt_switch_from/
 - s/restore_csr_regs/csr_regs_ctxt_switch_to/
 - Drop the forward declaration of struct vcpu in <asm/system.h>: the
   return type of __context_switch() already declares the tag at file
   scope.
 - Make the next parameter of __context_switch() pointer-to-const, as
   next's saved context is only read.
 - Extend the comment above __context_switch(): as ra is switched too, it
   doesn't return to its caller, but to where next last called it from
   (next's own context_switch(), or continue_new_vcpu() for a vCPU which
   has never run).
 - Call vtimer_ctxt_switch_to() after csr_regs_ctxt_switch_to(), so that
   ctxt_switch_to() restores state in the reverse order of
   ctxt_switch_from() saving it.
 - Rework p2m's VMID handling in the context switch: track the domain
   whose p2m HGATP points at in a per-CPU hgatp_owner, so a pass through
   idle no longer drops the hart from that domain's dirty_cpumask nor
   burns a VMID generation; move the dirty_cpumask update and the
   invalidation of a VMID brought from another hart from schedule_tail()
   and ctxt_switch_to() to p2m_ctxt_switch_to(), next to the VMID claim;
   add the barriers ordering the dirty_cpumask update against
   p2m_tlb_flush().
 - Initialise arch_vcpu.last_cpu to CPU_NONE instead of NR_CPUS.
 - Mark prev's dirty_cpu clean before ctxt_switch_to() and set current's
   after it.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/domain.c              | 118 ++++++++++++++++++++
 xen/arch/riscv/entry.S               |  48 ++++++++
 xen/arch/riscv/include/asm/csr.h     |   9 ++
 xen/arch/riscv/include/asm/domain.h  |  15 ++-
 xen/arch/riscv/include/asm/p2m.h     |   1 -
 xen/arch/riscv/include/asm/system.h  |   3 +
 xen/arch/riscv/p2m.c                 | 157 ++++++++++++++++++---------
 xen/arch/riscv/riscv64/asm-offsets.c |  19 +++-
 xen/arch/riscv/stubs.c               |   5 -
 xen/arch/riscv/traps.c               |   2 -
 10 files changed, 318 insertions(+), 59 deletions(-)

diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index 683c37c0ee5a..9feeaa59b887 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -11,6 +11,7 @@
 #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>
@@ -152,6 +153,8 @@ int arch_vcpu_create(struct vcpu *v)
     if ( is_idle_vcpu(v) )
         return 0;
 
+    v->arch.last_cpu = CPU_NONE;
+
     vcpu_csr_init(v);
 
     if ( (rc = vcpu_vtimer_init(v)) )
@@ -326,6 +329,121 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+static void csrs_ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * hedeleg, hideleg, henvcfg, hcounteren, htimedelta and hstateen0 aren't
+     * saved: neither the guest nor Xen changes them other than by
+     * csrs_ctxt_switch_to() writing them from v->arch.*, which is left
+     * unchanged after vcpu_csr_init().
+     */
+
+    p->arch.hvip = csr_read(CSR_HVIP);
+
+    p->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    p->arch.vsie = csr_read64(VSIE);
+    p->arch.vstvec = csr_read(CSR_VSTVEC);
+    p->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    p->arch.vscause = csr_read(CSR_VSCAUSE);
+    p->arch.vstval = csr_read(CSR_VSTVAL);
+    p->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+static void csrs_ctxt_switch_to(struct vcpu *n)
+{
+    csr_write(CSR_HEDELEG, n->arch.hedeleg);
+    csr_write(CSR_HIDELEG, n->arch.hideleg);
+    csr_write(CSR_HVIP, n->arch.hvip);
+    csr_write64(HENVCFG, n->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, n->arch.hcounteren);
+    csr_write64(HTIMEDELTA, n->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, n->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, n->arch.vsstatus);
+    csr_write64(VSIE, n->arch.vsie);
+    csr_write(CSR_VSTVEC, n->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, n->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, n->arch.vscause);
+    csr_write(CSR_VSTVAL, n->arch.vstval);
+    csr_write(CSR_VSEPC, n->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);
+
+    csrs_ctxt_switch_from(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;
+
+    csrs_ctxt_switch_to(n);
+
+    vtimer_ctxt_switch_to(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);
+
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
+    ctxt_switch_to(current);
+
+    write_atomic(&current->dirty_cpu, cpu);
+
+    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)
 {
     /*
diff --git a/xen/arch/riscv/entry.S b/xen/arch/riscv/entry.S
index 202a35fb03a8..017fbb06262c 100644
--- a/xen/arch/riscv/entry.S
+++ b/xen/arch/riscv/entry.S
@@ -99,3 +99,51 @@ restore_registers:
 
         sret
 END(handle_trap)
+
+/*
+ * struct vcpu *__context_switch(struct vcpu *prev, const struct vcpu *next)
+ *
+ * This is called on prev's stack, and returns on next's. As ra is
+ * switched too, it doesn't return to its caller: it returns to where
+ * next last called it from, i.e. into next's own context_switch(), or,
+ * for a vCPU which has never run, to continue_new_vcpu() with an empty
+ * stack.
+ *
+ * a0 - prev
+ * a1 - next
+ *
+ * Returns prev in a0
+ */
+FUNC(__context_switch)
+        REG_S   s0, VCPU_XEN_SAVED_CONTEXT_S0(a0)
+        REG_S   s1, VCPU_XEN_SAVED_CONTEXT_S1(a0)
+        REG_S   s2, VCPU_XEN_SAVED_CONTEXT_S2(a0)
+        REG_S   s3, VCPU_XEN_SAVED_CONTEXT_S3(a0)
+        REG_S   s4, VCPU_XEN_SAVED_CONTEXT_S4(a0)
+        REG_S   s5, VCPU_XEN_SAVED_CONTEXT_S5(a0)
+        REG_S   s6, VCPU_XEN_SAVED_CONTEXT_S6(a0)
+        REG_S   s7, VCPU_XEN_SAVED_CONTEXT_S7(a0)
+        REG_S   s8, VCPU_XEN_SAVED_CONTEXT_S8(a0)
+        REG_S   s9, VCPU_XEN_SAVED_CONTEXT_S9(a0)
+        REG_S   s10, VCPU_XEN_SAVED_CONTEXT_S10(a0)
+        REG_S   s11, VCPU_XEN_SAVED_CONTEXT_S11(a0)
+        REG_S   sp, VCPU_XEN_SAVED_CONTEXT_SP(a0)
+        REG_S   ra, VCPU_XEN_SAVED_CONTEXT_RA(a0)
+
+        REG_L   s0, VCPU_XEN_SAVED_CONTEXT_S0(a1)
+        REG_L   s1, VCPU_XEN_SAVED_CONTEXT_S1(a1)
+        REG_L   s2, VCPU_XEN_SAVED_CONTEXT_S2(a1)
+        REG_L   s3, VCPU_XEN_SAVED_CONTEXT_S3(a1)
+        REG_L   s4, VCPU_XEN_SAVED_CONTEXT_S4(a1)
+        REG_L   s5, VCPU_XEN_SAVED_CONTEXT_S5(a1)
+        REG_L   s6, VCPU_XEN_SAVED_CONTEXT_S6(a1)
+        REG_L   s7, VCPU_XEN_SAVED_CONTEXT_S7(a1)
+        REG_L   s8, VCPU_XEN_SAVED_CONTEXT_S8(a1)
+        REG_L   s9, VCPU_XEN_SAVED_CONTEXT_S9(a1)
+        REG_L   s10, VCPU_XEN_SAVED_CONTEXT_S10(a1)
+        REG_L   s11, VCPU_XEN_SAVED_CONTEXT_S11(a1)
+        REG_L   sp, VCPU_XEN_SAVED_CONTEXT_SP(a1)
+        REG_L   ra, VCPU_XEN_SAVED_CONTEXT_RA(a1)
+
+        ret
+END(__context_switch)
diff --git a/xen/arch/riscv/include/asm/csr.h b/xen/arch/riscv/include/asm/csr.h
index 6df595e810ef..ef6c22a90e76 100644
--- a/xen/arch/riscv/include/asm/csr.h
+++ b/xen/arch/riscv/include/asm/csr.h
@@ -40,6 +40,13 @@
     csr_write(CSR_ ## name ## H, v_ >> 32); \
 })
 
+#define csr_read64(name)                       \
+({                                             \
+    uint64_t v_ = csr_read(CSR_ ## name ## H); \
+                                               \
+    (v_ << 32) | csr_read(CSR_ ## name);       \
+})
+
 /*
  * 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,
@@ -63,6 +70,8 @@
 #define csr_write64(name, val) csr_write(CSR_ ## name, val)
 
 #define csr_volatile_read64(name) csr_read(CSR_ ## name)
+
+#define csr_read64(name) csr_read(CSR_ ## name)
 #endif
 
 #define csr_swap(csr, val)                                      \
diff --git a/xen/arch/riscv/include/asm/domain.h b/xen/arch/riscv/include/asm/domain.h
index 8c48833353f5..63e34c1a11ab 100644
--- a/xen/arch/riscv/include/asm/domain.h
+++ b/xen/arch/riscv/include/asm/domain.h
@@ -28,6 +28,11 @@ struct arch_vcpu_io {
 struct arch_vcpu {
     struct vcpu_vmid vmid;
 
+    /*
+     * The last CPU this vCPU ran on. Initialised to CPU_NONE.
+     */
+    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.
@@ -59,11 +64,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;
+    uint64_t   vsie;
+    register_t vsscratch;
+    register_t vsstatus;
+    register_t vstval;
+    register_t vstvec;
 
     /*
      * VCPU interrupts
diff --git a/xen/arch/riscv/include/asm/p2m.h b/xen/arch/riscv/include/asm/p2m.h
index c0538281517f..1104854c4021 100644
--- a/xen/arch/riscv/include/asm/p2m.h
+++ b/xen/arch/riscv/include/asm/p2m.h
@@ -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 /* RISCV_P2M_H */
 
diff --git a/xen/arch/riscv/include/asm/system.h b/xen/arch/riscv/include/asm/system.h
index cb382487751c..50e2e369fcb6 100644
--- a/xen/arch/riscv/include/asm/system.h
+++ b/xen/arch/riscv/include/asm/system.h
@@ -76,6 +76,9 @@ static inline bool local_irq_is_enabled(void)
 
 #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
+struct vcpu * asmlinkage __context_switch(struct vcpu *prev,
+                                          const struct vcpu *next);
+
 #endif /* __ASSEMBLER__ */
 
 #endif /* RISCV_SYSTEM_H */
diff --git a/xen/arch/riscv/p2m.c b/xen/arch/riscv/p2m.c
index a2d81a9c8a95..fedb029dcc37 100644
--- a/xen/arch/riscv/p2m.c
+++ b/xen/arch/riscv/p2m.c
@@ -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 p2m_vmid_switch_to(). 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);
 }
 
@@ -1497,16 +1506,110 @@ void p2m_ctxt_switch_from(struct vcpu *p)
      * VMID, world-switch code should zero vsatp, then swap hgatp, then
      * finally write the new vsatp value what will be done in
      * p2m_ctxt_switch_to().
-     * Note, that also HGATP update could happen in p2m_handle_vmenter().
      */
     p->arch.vsatp = csr_swap(CSR_VSATP, 0);
 
     /*
-     * Nothing to do with HGATP as it will be update in p2m_ctxt_switch_to()
-     * or/and in p2m_handle_vmenter().
+     * Nothing to do with HGATP as it will be updated in
+     * p2m_ctxt_switch_to().
      */
 }
 
+/*
+ * 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. The hart also keeps its place in the owner'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.
+ *
+ * TODO: nothing resets hgatp_owner when its domain is destroyed, so a hart
+ *       which stays idle from the domain's last run until it is freed is
+ *       left with a dangling pointer. Once domain_relinquish_resources()
+ *       tears down the p2m, it has to reset hgatp_owner of every hart still
+ *       pointing at the domain (cmpxchg() against d), i.e. before the RCU
+ *       grace period of domain_destroy() and so before the domain is freed.
+ */
+static DEFINE_PER_CPU(struct domain *, hgatp_owner);
+
+/*
+ * Update this hart's place in the dirty_cpumask of the domains involved and
+ * claim a VMID for n. Must be called before HGATP is pointed at n's p2m, as
+ * it is written with the VMID claimed here.
+ */
+static void p2m_vmid_switch_to(struct vcpu *n)
+{
+    unsigned int cpu = smp_processor_id();
+    struct domain *owner = this_cpu(hgatp_owner);
+    bool need_flush;
+
+    ASSERT(!is_idle_vcpu(n));
+
+    if ( owner != n->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.
+         *
+         * This has to precede the VMID claim below, so that n gets a VMID of
+         * the new generation.
+         */
+        if ( owner )
+        {
+            vmid_flush_hart();
+
+            cpumask_clear_cpu(cpu, owner->dirty_cpumask);
+        }
+
+        /*
+         * Mark this hart in the incoming domain's dirty_cpumask before HGATP
+         * is pointed at its p2m: from that write on the hart may cache the
+         * p2m's translations, so p2m_tlb_flush() must already reach it.
+         */
+        cpumask_set_cpu(cpu, n->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) = n->domain;
+    }
+
+    /*
+     * VMIDs and generations are per hart, so a pair issued on another hart
+     * may match this hart's generation by coincidence. Reset the generation
+     * to 0, which no hart ever uses, so that a fresh VMID is claimed from
+     * this hart's pool.
+     */
+    if ( n->arch.last_cpu != cpu )
+        vmid_flush_vcpu(n);
+
+    /*
+     * Claim the VMID before the caller writes HGATP rather than on guest
+     * entry: from that write on, speculation may fill the TLB with this
+     * domain's G-stage entries tagged with that VMID. A stale VMID may
+     * already have been re-issued to a vCPU of another domain, which would
+     * then hit these entries.
+     */
+    need_flush = vmid_handle_vmenter(&n->arch.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();
+}
+
 /*
  * As speculation may occur at any time, an incorrect set of page tables could
  * be used. Therefore, this function must be called only after all other guest
@@ -1521,11 +1624,9 @@ void p2m_ctxt_switch_to(struct vcpu *n)
     if ( is_idle_vcpu(n) )
         return;
 
+    p2m_vmid_switch_to(n);
+
     csr_write(CSR_HGATP, construct_hgatp(p2m, n->arch.vmid.vmid));
-    /*
-     * As VMID is unique per vCPU and just re-used here thereby there is no
-     * need for G-stage TLB flush here.
-     */
 
     csr_write(CSR_VSATP, n->arch.vsatp);
 
@@ -1541,48 +1642,6 @@ void p2m_ctxt_switch_to(struct vcpu *n)
     flush_tlb_guest_local();
 }
 
-void p2m_handle_vmenter(void)
-{
-    struct vcpu *curr = current;
-    struct p2m_domain *p2m = p2m_get_hostp2m(curr->domain);
-    struct vcpu_vmid *p_vmid = &curr->arch.vmid;
-    unsigned short old_vmid, new_vmid;
-    bool need_flush;
-
-    BUG_ON(is_idle_vcpu(curr));
-
-    old_vmid = p_vmid->vmid;
-    need_flush = vmid_handle_vmenter(p_vmid);
-    new_vmid = p_vmid->vmid;
-
-#ifdef P2M_DEBUG
-    printk("%pv: oldvmid(%d) new_vmid(%d), need_flush(%d)\n",
-           curr, old_vmid, new_vmid, need_flush);
-#endif
-
-    /*
-     * There is no need to set VSATP to 0 to stop speculation before updating
-     * HGATP, as VSATP is not modified here.
-     */
-    if ( old_vmid != new_vmid )
-        csr_write(CSR_HGATP, construct_hgatp(p2m, p_vmid->vmid));
-
-    /*
-     * There is also no need to flush G-stage TLB unconditionally as old VMID
-     * won't be reused until need_flush is set to true.
-     */
-    if ( unlikely(need_flush) )
-        local_hfence_gvma_all();
-
-    /*
-     * 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. 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.
-     */
-}
-
 struct page_info *get_page_from_gfn(struct domain *d, unsigned long gfn,
                                     p2m_type_t *t, p2m_query_t q)
 {
diff --git a/xen/arch/riscv/riscv64/asm-offsets.c b/xen/arch/riscv/riscv64/asm-offsets.c
index 1290b9dbbe82..c1be1614ce94 100644
--- a/xen/arch/riscv/riscv64/asm-offsets.c
+++ b/xen/arch/riscv/riscv64/asm-offsets.c
@@ -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();
 }
diff --git a/xen/arch/riscv/stubs.c b/xen/arch/riscv/stubs.c
index 3a7953593d93..e0febae432b2 100644
--- a/xen/arch/riscv/stubs.c
+++ b/xen/arch/riscv/stubs.c
@@ -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");
diff --git a/xen/arch/riscv/traps.c b/xen/arch/riscv/traps.c
index dd53454f23f4..2db3b74f95cf 100644
--- a/xen/arch/riscv/traps.c
+++ b/xen/arch/riscv/traps.c
@@ -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)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 12/42] xen/riscv: save and restore vsiselect on vCPU context switch
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (10 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 11/42] xen/riscv: implement vCPU context switching Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 13/42] xen/riscv: introduce vintc_ctxt_switch_{from,to}() Oleksii Kurochko
                   ` (29 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

vsiselect isn't saved/restored, yet the guest writes it directly
(VS-mode accesses to siselect go to vsiselect). After a context switch a
vCPU therefore sees the selector left by the previous vCPU on that hart:
a guest writing siselect, getting descheduled, then accessing sireg hits
a register it never selected, and it can 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.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
Acked-by: Jan Beulich <jbeulich@suse.com>
---
Changes in v4:
 - Reword the commit message.
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
 - Add Acked-by: Jan Beulich <jbeulich@suse.com>.
---
Changes in v3:
 - Rename from "xen/riscv: save and restore AIA state on vCPU context
   switch", as only vsiselect is switched now.
 - Save and restore only vsiselect: drop hviprio1 and hviprio2.
 - Rename vcpu_has_aia_state() to vcpu_can_access_vsiselect() and drop
   its hstateen0 bit argument.
 - Move switching vsie to uint64_t and csr_{read,write}64() to "xen/riscv:
   implement vCPU context switching".
 - Update the commit message.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/domain.c             | 28 ++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/domain.h |  1 +
 2 files changed, 29 insertions(+)

diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index 9feeaa59b887..089d968ace27 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -329,6 +329,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 csrs_ctxt_switch_from(struct vcpu *p)
 {
     /*
@@ -347,6 +369,9 @@ static void csrs_ctxt_switch_from(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 csrs_ctxt_switch_to(struct vcpu *n)
@@ -368,6 +393,9 @@ static void csrs_ctxt_switch_to(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)
diff --git a/xen/arch/riscv/include/asm/domain.h b/xen/arch/riscv/include/asm/domain.h
index 63e34c1a11ab..c424e2428f60 100644
--- a/xen/arch/riscv/include/asm/domain.h
+++ b/xen/arch/riscv/include/asm/domain.h
@@ -73,6 +73,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;
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 13/42] xen/riscv: introduce vintc_ctxt_switch_{from,to}()
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (11 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 12/42] xen/riscv: save and restore vsiselect on vCPU context switch Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 14/42] xen/riscv: extend exception tables with type and data fields Oleksii Kurochko
                   ` (28 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Acked-by: Jan Beulich <jbeulich@suse.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
Changes in v4:
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
---
Changes in v3:
 - s/v/{p,n} for vintc_ctxt_switch_{from,to}() arguments and also for
   hook prototypes.
 - Add Acked-by: Jan Beulich <jbeulich@suse.com>.
---
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(+)

diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index 089d968ace27..a65de57e486f 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -412,6 +412,8 @@ static void ctxt_switch_from(struct vcpu *p)
 
     vtimer_ctxt_switch_from(p);
 
+    vintc_ctxt_switch_from(p);
+
     csrs_ctxt_switch_from(p);
 }
 
@@ -427,6 +429,8 @@ static void ctxt_switch_to(struct vcpu *n)
 
     csrs_ctxt_switch_to(n);
 
+    vintc_ctxt_switch_to(n);
+
     vtimer_ctxt_switch_to(n);
 
     p2m_ctxt_switch_to(n);
diff --git a/xen/arch/riscv/include/asm/intc.h b/xen/arch/riscv/include/asm/intc.h
index 7a31c6a298a0..58196927aab2 100644
--- a/xen/arch/riscv/include/asm/intc.h
+++ b/xen/arch/riscv/include/asm/intc.h
@@ -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 *p);
+
+    /* Restore vINTC state of the vCPU being switched in */
+    void (*ctxt_switch_to)(struct vcpu *n);
 };
 
 struct vintc {
@@ -94,4 +100,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 *p);
+void vintc_ctxt_switch_to(struct vcpu *n);
+
 #endif /* RISCV_INTC_H */
diff --git a/xen/arch/riscv/intc.c b/xen/arch/riscv/intc.c
index cdbc039d0258..70dfe6cd6f34 100644
--- a/xen/arch/riscv/intc.c
+++ b/xen/arch/riscv/intc.c
@@ -190,3 +190,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 *p)
+{
+    const struct vintc_ops *ops = p->domain->arch.vintc->ops;
+
+    ops->ctxt_switch_from(p);
+}
+
+void vintc_ctxt_switch_to(struct vcpu *n)
+{
+    const struct vintc_ops *ops = n->domain->arch.vintc->ops;
+
+    ops->ctxt_switch_to(n);
+}
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 14/42] xen/riscv: extend exception tables with type and data fields
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (12 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 13/42] xen/riscv: introduce vintc_ctxt_switch_{from,to}() Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 15/42] xen/riscv: add guest page fault handling stub Oleksii Kurochko
                   ` (27 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Extend the RISC-V exception table format to include a type and
auxiliary data field.

The existing format only supports simple fixups. Some use cases require
additional context from the fault (e.g. capturing trap information),
which cannot be expressed with the current EX_TYPE_FIXUP entries.

Introduce a generic ASM_EXTABLE_RAW() helper to describe entries with a
handler type and associated data. Reimplement ASM_EXTABLE() in terms of
it using EX_TYPE_FIXUP for compatibility.

Add EX_TYPE_TRAP_INFO to allow handlers to retrieve trap state
(sepc/scause/stval) and pass it to the fixup path. The data field is
used to encode which GPR contains a pointer to a struct trap_info.
Provide ASM_EXTABLE_TRAP_INFO() as a convenience wrapper for this case,
and pass the trap cause down to fixup_exception() for it.

Also add gpr-num.h, providing symbolic GPR numbers for use in assembly
and inline asm. It is derived from Linux 6.16, with the register list
turned into a GPR_LIST() macro instead of being open-coded with .irp, so
that it can be used from C as well.

Resolving a GPR number to the saved value of the register relies on
struct cpu_user_regs holding x0..x31 contiguously and in register-number
order. Add regs_gpr_ptr() for that, and check the layout against
GPR_LIST() at build time. x0..x31 don't have to start at offset 0 of the
structure, so anchor REG_PTR() at ->zero too, rather than at the
structure itself, which relied on them doing so.

Update the exception handling code to dispatch based on the entry type.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Pass the cause to the fixup_exception() call in do_trap(), which
   "xen/riscv: look up the exception table for any trap taken in Xen
   context" has moved ahead of the cause switch, and mention
   EX_TYPE_TRAP_INFO in the comment above it.
 - Update the commit message.
 - gpr-num.h: name the assembler GPR_NUM_EQU() in the comment of its C
   flavour instead of referring to "the __ASSEMBLER__ flavour above",
   which was hard to tie to a particular comment.
---
Changes in v3:
 - Update the commit message.
 - Keep the name of the asm_extable assembler macro: renaming it to
   _asm_extable was unrelated to this patch.
 - Replace regs_get_gpr() in extable.c with regs_gpr_ptr() in asm/regs.h,
   returning where the register's value is saved rather than the value
   itself, so that a single helper serves code which reads a guest register
   as well as code which writes one. Anchor the array access at
   &regs->zero rather than casting regs itself, matching the relaxed
   layout requirement below, and bound the index with array_index_nospec()
   so that release builds, where the ASSERT() is compiled out, cannot read
   past the register frame. Add NR_GPRS instead of open-coding 32.
 - Move the layout BUILD_BUG_ON()s out of regs_get_gpr() into
   build_assertions() in domain.c, so that they no longer sit in one
   particular consumer of the mapping.
 - Anchor those checks at offsetof(struct cpu_user_regs, zero) rather than
   at offset 0: the x0..x31 block only has to be contiguous and in
   register-number order, it no longer has to sit at the start of the
   structure. Update the comment above struct cpu_user_regs accordingly,
   keeping the "->zero must read as 0" requirement as a separate point.
 - REG_PTR(): anchor at &regs->zero for the same reason.
 - gpr-num.h: move the part of the comment describing the generation of the
   .L_gpr_num_<name> symbols down to the construct which actually generates
   them; GPR_LIST() itself has other users.
 - gpr-num.h: emit the separator ahead of each list entry instead of after
   it, so that the expansion doesn't end with one and whatever follows a use
   of the list has to supply its own; ASM_EXTABLE_TRAP_INFO() supplies the
   "\n" it needs.
 - gpr-num.h: state in the file header what was changed compared to the
   Linux original.
 - asm/extable.h: no functional change, put EX_TRAP_INFO_REG() on a single
   line and reflow the comment describing the exception table entry format.
 - Drop BUG_ON() in ex_handler_trap_info() as trap_info pointer should be
   guaranteed properly filled by compilation process.
---
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/domain.c                     | 22 ++++++++
 xen/arch/riscv/extable.c                    | 48 +++++++++++++++-
 xen/arch/riscv/include/asm/extable.h        | 61 ++++++++++++++-------
 xen/arch/riscv/include/asm/gpr-num.h        | 53 ++++++++++++++++++
 xen/arch/riscv/include/asm/processor.h      | 14 ++++-
 xen/arch/riscv/include/asm/regs.h           | 23 +++++++-
 xen/arch/riscv/include/asm/riscv_encoding.h |  7 ++-
 xen/arch/riscv/include/asm/traps.h          |  6 ++
 xen/arch/riscv/traps.c                      |  5 +-
 9 files changed, 212 insertions(+), 27 deletions(-)
 create mode 100644 xen/arch/riscv/include/asm/gpr-num.h

diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index a65de57e486f..7be019e2ad12 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -12,6 +12,7 @@
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/current.h>
+#include <asm/gpr-num.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
@@ -478,9 +479,30 @@ void context_switch(struct vcpu *prev, struct vcpu *next)
 
 static void __init __maybe_unused build_assertions(void)
 {
+/*
+ * GPR_LIST() puts nothing between its entries, so the separator has to come
+ * from here. It is emitted ahead of each entry rather than after it, so that
+ * the expansion doesn't end with one and its use below can be terminated like
+ * an ordinary statement.
+ */
+#define CHECK_GPR_INDEX(num, name)                          \
+    ; BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) !=  \
+                   offsetof(struct cpu_user_regs, zero) +   \
+                   (num) * sizeof(unsigned long))
+
     /*
      * Enforce the requirement documented in struct cpu_info that
      * guest_cpu_user_regs must be the first field.
      */
     BUILD_BUG_ON(offsetof(struct cpu_info, guest_cpu_user_regs));
+
+    /*
+     * Enforce the requirement documented in struct cpu_user_regs that the
+     * x0..x31 fields are contiguous and in architectural register-number
+     * order, which is what lets a register number be resolved to its saved
+     * value by indexing them as an array anchored at ->zero.
+     */
+    GPR_LIST(CHECK_GPR_INDEX);
+
+#undef CHECK_GPR_INDEX
 }
diff --git a/xen/arch/riscv/extable.c b/xen/arch/riscv/extable.c
index 5b89c4278c65..19d9e3617c81 100644
--- a/xen/arch/riscv/extable.c
+++ b/xen/arch/riscv/extable.c
@@ -6,8 +6,11 @@
 #include <xen/sort.h>
 #include <xen/virtual_region.h>
 
+#include <asm/csr.h>
 #include <asm/extable.h>
 #include <asm/processor.h>
+#include <asm/regs.h>
+#include <asm/traps.h>
 
 #define EX_FIELD(ptr, field) ((unsigned long)&(ptr)->field + (ptr)->field)
 
@@ -32,6 +35,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 +68,26 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
     regs->sepc = ex_fixup(ex);
 }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+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_gpr_ptr(regs, ex->data);
+
+    /*
+     * 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 +105,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;
 }
diff --git a/xen/arch/riscv/include/asm/extable.h b/xen/arch/riscv/include/asm/extable.h
index 0209b2f3bfa5..76dadb3b9b21 100644
--- a/xen/arch/riscv/include/asm/extable.h
+++ b/xen/arch/riscv/include/asm/extable.h
@@ -3,17 +3,24 @@
 #ifndef RISCV_EXTABLE_H
 #define RISCV_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)
+    ASM_EXTABLE_RAW(\insn, \fixup, EX_TYPE_FIXUP, 0)
 .endm
 
 #else /* __ASSEMBLER__ */
@@ -23,20 +30,35 @@
 
 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 "\n"                                        \
+    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 in case of a fault, `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 +67,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 /* RISCV_EXTABLE_H */
diff --git a/xen/arch/riscv/include/asm/gpr-num.h b/xen/arch/riscv/include/asm/gpr-num.h
new file mode 100644
index 000000000000..6da5450c0757
--- /dev/null
+++ b/xen/arch/riscv/include/asm/gpr-num.h
@@ -0,0 +1,53 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Based on Linux 6.16 arch/riscv/include/asm/gpr-num.h, with the
+ * register list turned into GPR_LIST() instead of being open-coded
+ * with .irp, so that it can also be used outside of assembly.
+ */
+#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; users expand it with
+ * their own per-register macro. Among them, the layout of struct cpu_user_regs
+ * is checked against this list at build time (see build_assertions() in
+ * domain.c), so neither list can 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)
+
+/* Number of GPRs described by GPR_LIST(). */
+#define NR_GPRS 32
+
+#ifdef __ASSEMBLER__
+
+/*
+ * Generate the .L_gpr_num_<name> assembler symbols, used to turn a register
+ * name emitted by the compiler into a register number.
+ *
+ * The separator is emitted ahead of each entry rather than after it, so that
+ * the expansion doesn't end with one: whatever follows a use of the list has
+ * to supply its own separator, instead of silently relying on a trailing one.
+ */
+#define GPR_NUM_EQU(num, name)  ; .equ .L_gpr_num_##name, num
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU
+
+#else /* __ASSEMBLER__ */
+
+/* See the comment above the assembler GPR_NUM_EQU() about the separator. */
+#define GPR_NUM_EQU(num, name)  "\n.equ .L_gpr_num_" #name ", " #num
+#define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
+
+#endif /* __ASSEMBLER__ */
+
+#endif /* RISCV_GPR_NUM_H */
diff --git a/xen/arch/riscv/include/asm/processor.h b/xen/arch/riscv/include/asm/processor.h
index 007c22d2e611..83dd59a27295 100644
--- a/xen/arch/riscv/include/asm/processor.h
+++ b/xen/arch/riscv/include/asm/processor.h
@@ -12,7 +12,19 @@
 
 #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * The x0..x31 fields must remain contiguous and in architectural
+ * register-number order: code which resolves a register number to its saved
+ * value indexes them as an array anchored at ->zero. Where that block sits
+ * within the structure is of no interest, but nothing may be inserted in
+ * between its fields. The layout is checked against GPR_LIST() at build
+ * time; see build_assertions() in domain.c.
+ *
+ * ->zero additionally has to always read as 0, since it supplies the value
+ * of x0 when x0 is used as a source operand.
+ */
 struct cpu_user_regs
 {
     unsigned long zero;
diff --git a/xen/arch/riscv/include/asm/regs.h b/xen/arch/riscv/include/asm/regs.h
index 24674d37cfe4..00aa6ff964e8 100644
--- a/xen/arch/riscv/include/asm/regs.h
+++ b/xen/arch/riscv/include/asm/regs.h
@@ -5,16 +5,35 @@
 #ifndef __ASSEMBLER__
 
 #include <xen/bug.h>
+#include <xen/nospec.h>
 
-#define hyp_mode(r)     (0)
+#include <asm/gpr-num.h>
+#include <asm/processor.h>
 
-struct cpu_user_regs;
+#define hyp_mode(r)     (0)
 
 static inline bool guest_mode(const struct cpu_user_regs *r)
 {
     BUG_ON("unimplemented");
 }
 
+/*
+ * Resolve an architectural register number to where its value is saved in
+ * @regs. Relies on x0..x31 being laid out as an array anchored at ->zero; see
+ * the comment above struct cpu_user_regs.
+ */
+static inline unsigned long *regs_gpr_ptr(struct cpu_user_regs *regs,
+                                          unsigned int num)
+{
+    ASSERT(num < NR_GPRS);
+
+    /*
+     * Not a speculation concern, but a convenient way to keep the access in
+     * bounds in release builds, where the assertion above is compiled out.
+     */
+    return &(&regs->zero)[array_index_nospec(num, NR_GPRS)];
+}
+
 #endif /* __ASSEMBLER__ */
 
 #endif /* RISCV_REGS_H */
diff --git a/xen/arch/riscv/include/asm/riscv_encoding.h b/xen/arch/riscv/include/asm/riscv_encoding.h
index 481ee2813b0e..887edce6b604 100644
--- a/xen/arch/riscv/include/asm/riscv_encoding.h
+++ b/xen/arch/riscv/include/asm/riscv_encoding.h
@@ -903,8 +903,13 @@
 #define REG_OFFSET(insn, pos)		\
 	(SHIFT_RIGHT((insn), (pos) - LOG_REGBYTES) & REG_MASK)
 
+/*
+ * The x0..x31 block of struct cpu_user_regs is not required to sit at the
+ * start of the structure, so anchor the offset at ->zero (x0) rather than
+ * at the structure itself.
+ */
 #define REG_PTR(insn, pos, regs)	\
-	(unsigned long *)((unsigned long)(regs) + REG_OFFSET(insn, pos))
+	(unsigned long *)((unsigned long)&(regs)->zero + REG_OFFSET(insn, pos))
 
 #define GET_RM(insn)			(((insn) >> 12) & 7)
 
diff --git a/xen/arch/riscv/include/asm/traps.h b/xen/arch/riscv/include/asm/traps.h
index 08c6215e931a..3f2b5b7ccb5f 100644
--- a/xen/arch/riscv/include/asm/traps.h
+++ b/xen/arch/riscv/include/asm/traps.h
@@ -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);
diff --git a/xen/arch/riscv/traps.c b/xen/arch/riscv/traps.c
index 2db3b74f95cf..efeba0a9ce03 100644
--- a/xen/arch/riscv/traps.c
+++ b/xen/arch/riscv/traps.c
@@ -202,7 +202,8 @@ void do_trap(struct cpu_user_regs *cpu_regs)
      *
      * 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 fully under guest control.
+     * 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
@@ -212,7 +213,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
      * that only runs for traps taken from the guest.
      */
     if ( !from_guest && !(cause & CAUSE_IRQ_FLAG) &&
-         fixup_exception(cpu_regs) )
+         fixup_exception(cpu_regs, cause) )
         return;
 
     switch ( cause )
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 15/42] xen/riscv: add guest page fault handling stub
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (13 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 14/42] xen/riscv: extend exception tables with type and data fields Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 16/42] xen/riscv: implement trap redirection to a guest Oleksii Kurochko
                   ` (26 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Add a handler for guest page faults and hook it into the trap path,
providing the trap-side entry point for 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: this is where MMIO emulation hooks in. Not
  in scope of this patch.

Any of these three faults is instead reported via a pseudoinstruction
in htinst, when both:

(a) the fault is caused by an implicit memory access for VS-stage
    address translation, 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.

resolve_faulting_gpa() is a stub which always fails for now, so any guest
page fault other than one taken on an implicit access for VS-stage
translation currently crashes the domain. That one is reflected to the
guest through trap_redirect(), which is still a BUG_ON() placeholder
though, and so takes the host down. This is no worse than before this
patch, where these traps fell through to do_unexpected_trap() and die().

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Drop the from_guest local and the paragraph on it in the commit
   message: "xen/riscv: look up the exception table for any trap taken
   in Xen context" introduces it now.
 - Update the commit message.
 - Rewrite the comment ahead of the htinst_is_pseudo() check along the
   lines of the commit message.
 - Drop __func__ from the domain_crash() messages: they are unique
   enough.
 - Drop the comment ahead of the definition of trap_redirect(): it
   duplicates the one on its declaration.
---
Changes in v3:
 - Update the commit message.
 - Make resolve_faulting_gpa() return an error, which the caller checks.
 - Add a FIXME about guest page tables residing in emulated MMIO.
 - Don't refer to fixup_exception() in the comment ahead of
   BUG_ON(!from_guest): it isn't consulted for guest page faults yet.
 - Mention the from_guest local in the commit message.
 - Say in the comment above resolve_faulting_gpa() that it stores the address
   in @gf->gpa.
 - Make emulate_store() take a pointer to const, as emulate_load() does:
   neither modifies *gf.
---
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             | 177 +++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/emulate.h |  10 ++
 xen/arch/riscv/include/asm/traps.h   |   3 +
 xen/arch/riscv/traps.c               |  18 +++
 5 files changed, 209 insertions(+)
 create mode 100644 xen/arch/riscv/emulate.c
 create mode 100644 xen/arch/riscv/include/asm/emulate.h

diff --git a/xen/arch/riscv/Makefile b/xen/arch/riscv/Makefile
index 5454517724bd..2b84dace6bd5 100644
--- a/xen/arch/riscv/Makefile
+++ b/xen/arch/riscv/Makefile
@@ -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
diff --git a/xen/arch/riscv/emulate.c b/xen/arch/riscv/emulate.c
new file mode 100644
index 000000000000..de8c09fe1505
--- /dev/null
+++ b/xen/arch/riscv/emulate.c
@@ -0,0 +1,177 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>
+#include <asm/traps.h>
+
+/*
+ * The hardware-reported details of a guest page fault, gathered once by
+ * handle_guest_page_fault() and passed down to the emulation of the faulted
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state. */
+    struct cpu_user_regs *regs;
+    /* 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 special pseudoinstruction values, reported for a guest
+ * page fault taken on an implicit memory access done for VS-stage address
+ * translation?
+ *
+ * It is enough to check only bits[1:0] as according to the spec:
+ *
+ * The value is one of the special pseudoinstructions defined later, all of
+ * which have bits 1:0 equal to 00.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    return htinst && !(htinst & 3);
+}
+
+/*
+ * Reconstruct the guest physical address the access faulted on into @gf->gpa.
+ */
+static int resolve_faulting_gpa(struct guest_fault *gf)
+{
+    return -EOPNOTSUPP;
+}
+
+static int emulate_load(const struct guest_fault *gf)
+{
+    return -EOPNOTSUPP;
+}
+
+static int emulate_store(const struct guest_fault *gf)
+{
+    return -EOPNOTSUPP;
+}
+
+static void inject_access_fault(const struct guest_fault *gf)
+{
+    struct trap_info utrap = {
+        .sepc = gf->regs->sepc,
+        .stval = gf->stval,
+    };
+
+    switch ( gf->cause )
+    {
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_FETCH_ACCESS;
+        break;
+
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_LOAD_ACCESS;
+        break;
+
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_STORE_ACCESS;
+        break;
+
+    default:
+        domain_crash(current->domain, "Impossible cause (%#lx)?\n", gf->cause);
+        return;
+    }
+
+    trap_redirect(&utrap);
+}
+
+void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause)
+{
+    struct guest_fault gf = {
+        .regs = regs,
+        .cause = cause,
+        .gpa = INVALID_PADDR,
+    };
+    int rc;
+
+    gf.htinst = csr_read(CSR_HTINST);
+    gf.htval = csr_read(CSR_HTVAL);
+    gf.stval = csr_read(CSR_STVAL);
+
+    /*
+     * htinst reports one of the special pseudoinstruction values when both:
+     *   (a) the fault is caused by an implicit memory access for VS-stage
+     *       address translation
+     *   (b) htval holds a nonzero value: the guest physical address of that
+     *       VS-stage PTE, not of the guest's original access, which is
+     *       unknown as VS-stage translation didn't complete.
+     *
+     * No access to emulate then: to match bare hardware behavior, inject an
+     * access fault of the ORIGINAL access type (Instruction, Load, or
+     * Store/AMO) that initiated the address translation.
+     *
+     * FIXME: This assumes that guest page tables never reside in an emulated
+     * MMIO region, i.e. that an implicit access faulting at G-stage always
+     * targets an unpopulated GPA. Guests may (even transiently) place page
+     * tables in MMIO-backed memory, e.g. a video frame buffer. Supporting
+     * that would require walking the VS-stage page tables in software,
+     * accessing the PTEs (including A/D updates) through the MMIO handlers,
+     * and then emulating the original access, instead of injecting a fault.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
+        inject_access_fault(&gf);
+
+        return;
+    }
+
+    rc = resolve_faulting_gpa(&gf);
+    if ( rc )
+        goto out;
+
+    switch ( cause )
+    {
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        rc = emulate_load(&gf);
+        break;
+
+    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.
+         */
+        inject_access_fault(&gf);
+        return;
+
+    default:
+        ASSERT_UNREACHABLE();
+        rc = -EOPNOTSUPP;
+
+        break;
+    }
+
+ out:
+    if ( rc )
+        domain_crash(current->domain,
+                     "unable to handle guest page fault (cause=%#lx) at gpa %#"PRIpaddr"\n",
+                     cause, gf.gpa);
+}
diff --git a/xen/arch/riscv/include/asm/emulate.h b/xen/arch/riscv/include/asm/emulate.h
new file mode 100644
index 000000000000..59e69ca6794c
--- /dev/null
+++ b/xen/arch/riscv/include/asm/emulate.h
@@ -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 */
diff --git a/xen/arch/riscv/include/asm/traps.h b/xen/arch/riscv/include/asm/traps.h
index 3f2b5b7ccb5f..a7c79ae6165b 100644
--- a/xen/arch/riscv/include/asm/traps.h
+++ b/xen/arch/riscv/include/asm/traps.h
@@ -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 /* RISCV_TRAPS_H */
diff --git a/xen/arch/riscv/traps.c b/xen/arch/riscv/traps.c
index efeba0a9ce03..db8873d1e43f 100644
--- a/xen/arch/riscv/traps.c
+++ b/xen/arch/riscv/traps.c
@@ -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>
@@ -225,6 +226,18 @@ 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:
+        /*
+         * Xen doesn't access guest memory, so it can't take a guest page
+         * fault itself: 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 )
         {
@@ -294,3 +307,8 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
     BUG_ON("unimplemented");
     return mc_continue;
 }
+
+void trap_redirect(const struct trap_info *trap)
+{
+    BUG_ON("unimplemented");
+}
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 16/42] xen/riscv: implement trap redirection to a guest
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (14 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 15/42] xen/riscv: add guest page fault handling stub Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 17/42] xen/riscv: detect Shtvala Oleksii Kurochko
                   ` (25 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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, such as those taken by the
  hlv/hlvx sequences Xen uses to access guest memory.
- Access faults handle_guest_page_fault() injects for a guest-page
  fault that can never become an emulated access.

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.

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.

STVEC_MODE_DIRECT and STVEC_MODE_VECTORED are unused for now and are
added only for completeness alongside STVEC_MODE_MASK.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
Changes in v4:
 - Add extra tab to definition of STVEC_MODE_MASK.
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
---
Changes in v3:
 - Update the commit message.
 - Drop STVEC_BASE_MASK for now and use ~STVEC_MODE_MASK instead.
---
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 |  5 +++
 xen/arch/riscv/traps.c                      | 50 ++++++++++++++++++++-
 2 files changed, 54 insertions(+), 1 deletion(-)

diff --git a/xen/arch/riscv/include/asm/riscv_encoding.h b/xen/arch/riscv/include/asm/riscv_encoding.h
index 887edce6b604..fa26f5a2eb86 100644
--- a/xen/arch/riscv/include/asm/riscv_encoding.h
+++ b/xen/arch/riscv/include/asm/riscv_encoding.h
@@ -107,6 +107,11 @@
 #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 PRV_U				_UL(0)
 #define PRV_S				_UL(1)
 #define PRV_M				_UL(3)
diff --git a/xen/arch/riscv/traps.c b/xen/arch/riscv/traps.c
index db8873d1e43f..3672774271ff 100644
--- a/xen/arch/riscv/traps.c
+++ b/xen/arch/riscv/traps.c
@@ -310,5 +310,53 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
 
 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.
+     *
+     * 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_MODE_MASK;
+
+    /* Set Guest privilege mode to supervisor */
+    regs->sstatus |= SSTATUS_SPP;
 }
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 17/42] xen/riscv: detect Shtvala
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (15 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 16/42] xen/riscv: implement trap redirection to a guest Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 18/42] xen/riscv: resolve the faulting guest physical address Oleksii Kurochko
                   ` (24 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

The H extension allows htval, on a guest-page fault, to be written with
either the faulting guest physical address or zero. The 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.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
Acked-by: Jan Beulich <jbeulich@suse.com>
---
Changes in v4:
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
 - Add Acked-by: Jan Beulich <jbeulich@suse.com>.
---
Changes in v3:
 - Update the commit message.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/cpufeature.c             | 1 +
 xen/arch/riscv/include/asm/cpufeature.h | 1 +
 2 files changed, 2 insertions(+)

diff --git a/xen/arch/riscv/cpufeature.c b/xen/arch/riscv/cpufeature.c
index b1c614867cd8..2cca5165804f 100644
--- a/xen/arch/riscv/cpufeature.c
+++ b/xen/arch/riscv/cpufeature.c
@@ -196,6 +196,7 @@ static const struct riscv_isa_ext_entry __initconstrel riscv_isa_ext[] = {
     RISCV_ISA_EXT_ENTRY(zba,            ANY),
     RISCV_ISA_EXT_ENTRY(zbb,            ANY),
     RISCV_ISA_EXT_ENTRY(zbs,            ANY),
+    RISCV_ISA_EXT_ENTRY(shtvala,        NONE),
     RISCV_ISA_EXT_ENTRY(smaia,          ANY),
     RISCV_ISA_EXT_ENTRY(smstateen,      ANY),
     RISCV_ISA_EXT_ENTRY(ssaia,          ANY),
diff --git a/xen/arch/riscv/include/asm/cpufeature.h b/xen/arch/riscv/include/asm/cpufeature.h
index d42189e8ebe7..f0f9b5ad72d2 100644
--- a/xen/arch/riscv/include/asm/cpufeature.h
+++ b/xen/arch/riscv/include/asm/cpufeature.h
@@ -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,
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 18/42] xen/riscv: resolve the faulting guest physical address
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (16 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 17/42] xen/riscv: detect Shtvala Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 19/42] xen/riscv: add guest memory read helper Oleksii Kurochko
                   ` (23 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini, Alistair Francis, Baptiste Le Duc,
	Connor Davis

Recover the guest physical address from htval and stval. On a guest-page
fault to hypervisor, htval holds the guest physical address shifted
right by 2, so that an address wider than HSXLEN fits, and stval holds
the faulting guest virtual address. Shift htval back left by 2 and take
the two low bits from stval. htval is first converted to paddr_t, then
shifted: a guest physical address is 34 bits wide on RV32 with Sv32x4,
so shifting the XLEN-wide register itself would drop the top two bits.

However, there are two cases to distinguish when recovering the
faulting GPA:
- Explicit memory access: the two least significant bits of stval are
  the same as those of the guest physical address.
- Implicit memory access for VS-stage translation: the two least
  significant bits of the guest physical address (GPA[1:0]) are zero.
These two cases can be distinguished using the value provided in
register htinst.

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; until it is
written, such a fault crashes the domain rather than acting on an address
which may not be the one which faulted.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
Changes in v4:
 - Update the commit message.
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
---
Changes in v3:
 - Update the commit message.
 - Drop panic() inside resolve_faulting_gpa() and return -EOPNOTSUPP +
   printk_once().
 - Leave the comment above resolve_faulting_gpa() alone: it already says
   what the function does since "xen/riscv: add guest page fault handling
   stub".
 - Document in docs/misc/riscv/booting.txt why Shtvala is recommended.
---
Changes in v2:
 - New patch.
---
---
 docs/misc/riscv/booting.txt | 11 +++++++++++
 xen/arch/riscv/emulate.c    | 27 ++++++++++++++++++++++++++-
 2 files changed, 37 insertions(+), 1 deletion(-)

diff --git a/docs/misc/riscv/booting.txt b/docs/misc/riscv/booting.txt
index 14212ed62f99..283aa49a3b64 100644
--- a/docs/misc/riscv/booting.txt
+++ b/docs/misc/riscv/booting.txt
@@ -35,3 +35,14 @@ Other extensions recognised by Xen are listed in riscv_isa_ext[] in
 xen/arch/riscv/cpufeature.c. Xen uses them when present, but they are not
 needed to boot. The second column of that table says whether the extension
 is also exposed to guests.
+
+Some of them are nevertheless recommended, as functionality depends on them:
+- Shtvala:
+  Guarantees that htval is written with the faulting guest physical address
+  on a guest-page fault. Without it an implementation may write zero instead,
+  which can't be told apart from a genuine fault on guest physical addresses
+  0-3. Xen needs that address to emulate a guest's MMIO accesses; recovering
+  it in software (by walking the guest's VS-stage page tables) isn't
+  implemented, so on such hardware a guest-page fault reported with a zero
+  htval crashes the domain. See resolve_faulting_gpa() in
+  xen/arch/riscv/emulate.c.
diff --git a/xen/arch/riscv/emulate.c b/xen/arch/riscv/emulate.c
index de8c09fe1505..d661ef0bf204 100644
--- a/xen/arch/riscv/emulate.c
+++ b/xen/arch/riscv/emulate.c
@@ -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>
@@ -58,7 +59,31 @@ static bool htinst_is_pseudo(unsigned long htinst)
  */
 static int resolve_faulting_gpa(struct guest_fault *gf)
 {
-    return -EOPNOTSUPP;
+    /*
+     * 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) )
+    {
+        printk_once(XENLOG_WARNING
+                    "Shtvala isn't supported by h/w; s/w VS-stage walk required\n");
+        return -EOPNOTSUPP;
+    }
+
+    /*
+     * 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));
+
+    return 0;
 }
 
 static int emulate_load(const struct guest_fault *gf)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 19/42] xen/riscv: add guest memory read helper
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (17 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 18/42] xen/riscv: resolve the faulting guest physical address Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 20/42] xen/riscv: add helpers for decoding a trapped load or store Oleksii Kurochko
                   ` (22 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Introduce 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.

do_trap() looks up the exception table for any trap taken in Xen
context, so a fault of these accesses reaches its fixup. Update the
comments there, which still name only probing accesses and say that Xen
can't take a guest page fault itself.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Update the comments in do_trap() on the exception table lookup and
   on the guest page fault case. "xen/riscv: look up the exception table
   for any trap taken in Xen context" used to do that, but went to
   staging without it.
 - Move the comment describing read_guest() to its declaration in
   asm/guest_access.h.
 - Explain the check of bits[1:0] of the first halfword fetched by
   read_guest().
---
Changes in v3:
 - Rename riscv_read_guest() to read_guest().
 - Document that @trap must be zero-initialised by the caller: it is
   written only when an access faults, so trap->scause == 0 on return is
   what tells the caller that the read succeeded.
 - Drop the ASSERT() on hstatus.SPV: vcpu_guest_cpu_user_regs(current)
   is the guest frame whatever context Xen is in, so SPV is always set in
   it and the check couldn't catch a call made from a nested trap. State
   in the comment above read_guest() that it must not be called from a
   nested trap taken in HS-mode instead.
 - Declare read_guest() in asm/guest_access.h.
---
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                | 68 +++++++++++++++++++++++
 xen/arch/riscv/include/asm/guest_access.h | 28 ++++++++++
 xen/arch/riscv/traps.c                    | 13 +++--
 3 files changed, 104 insertions(+), 5 deletions(-)

diff --git a/xen/arch/riscv/guestcopy.c b/xen/arch/riscv/guestcopy.c
index 8a89212e0bea..283a96322caa 100644
--- a/xen/arch/riscv/guestcopy.c
+++ b/xen/arch/riscv/guestcopy.c
@@ -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,70 @@ 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);
 }
+
+unsigned long 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.
+     */
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1: hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            /*
+             * bits[1:0] != 0b11: 16-bit (compressed) instruction, nothing
+             * more to read.
+             */
+            "   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;
+}
diff --git a/xen/arch/riscv/include/asm/guest_access.h b/xen/arch/riscv/include/asm/guest_access.h
index e94aa838a3e7..77911bffbdbf 100644
--- a/xen/arch/riscv/include/asm/guest_access.h
+++ b/xen/arch/riscv/include/asm/guest_access.h
@@ -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,33 @@ 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);
 
+/*
+ * 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.
+ *        It must be zero-initialised by the caller: it is written only when
+ *        an access faults, so trap->scause == 0 on return is what tells the
+ *        caller that the read succeeded.
+ *
+ * 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. It must therefore only be called
+ * while handling a trap taken from that vCPU, never from a nested trap
+ * taken in HS-mode, which may have interrupted Xen at a point where
+ * hstatus, vsatp or hgatp don't belong to the 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 read_guest(unsigned long guest_addr, bool read_insn,
+                         struct trap_info *trap);
+
 #endif /* RISCV_GUEST_ACCESS_H */
 /*
  * Local variables:
diff --git a/xen/arch/riscv/traps.c b/xen/arch/riscv/traps.c
index 3672774271ff..97e604091458 100644
--- a/xen/arch/riscv/traps.c
+++ b/xen/arch/riscv/traps.c
@@ -197,9 +197,11 @@ void do_trap(struct cpu_user_regs *cpu_regs)
     bool from_guest = cpu_regs->hstatus & HSTATUS_SPV;
 
     /*
-     * A synchronous trap taken in Xen context may come from a probing access
-     * like csr_read_safe(), covered by an exception table entry which resumes
-     * execution past the faulting instruction.
+     * 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 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
@@ -230,8 +232,9 @@ void do_trap(struct cpu_user_regs *cpu_regs)
     case CAUSE_LOAD_GUEST_PAGE_FAULT:
     case CAUSE_STORE_GUEST_PAGE_FAULT:
         /*
-         * Xen doesn't access guest memory, so it can't take a guest page
-         * fault itself: only a guest can get here.
+         * 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);
 
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 20/42] xen/riscv: add helpers for decoding a trapped load or store
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (18 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 19/42] xen/riscv: add guest memory read helper Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 21/42] xen/riscv: add guest load emulation for trapped MMIO accesses Oleksii Kurochko
                   ` (21 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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

Nothing calls any of this yet, so reference the functions from the
emulate_load() stub to keep the build going; the references go away once
emulate_load() gains its body later.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
How these helpers are used can be seen in the patches adding emulate_load()
and emulate_store().
---
Changes in v4:
 - Reword the comment above guest_xlen() on why hstatus.VSXL is
   consulted whichever mode the trap came from.
 - Reword the comment on a transformed instruction reported in htinst,
   saying first that a compressed one comes already expanded.
 - Don't imply in the comment on a zero htinst that the ASSERT() rules the
   pseudoinstructions out: handle_guest_page_fault() does.
 - Fix the grammar of the comment on a G-stage fault taken while fetching
   the trapped instruction, and say that it is reported as an instruction
   access fault rather than as a bus error.
 - Reflow the description of @xlen above decode_ldst_insn().
 - Say that decode_ldst_insn() also returns false for a load or store
   which cannot be emulated, not only for other instructions.
 - Say where funct3 sits in the 32-bit LOAD and STORE encodings, as the
   comment on the compressed ones does.
 - Make the xl local of guest_xlen() unsigned int: it only ever holds the
   value of a 2-bit field.
---
Changes in v3:
 - Update the commit message.
 - Restore the opcode bits of a transformed instruction with 3 rather
   than INSN_16BIT_MASK: the macro is dropped by "xen/riscv: drop
   INSN_{16,32}BIT_MASK and report unknown instruction lengths", and its
   name didn't fit this use anyway.
 - Use (void) references in emulate_load() instead of __maybe_unused.
 - Use read_guest(), the new name of riscv_read_guest().
 - Shrink struct decoded_insn from 24 to 8 bytes (RV64): insn becomes
   uint32_t, as no instruction is wider than 32 bits, insn_len, len and reg
   become uint8_t (rather than bit-fields, for better code generation), and
   is_write and is_unsigned become bit-fields.
 - Don't take a custom htinst value with bits above bit[31] set for a
   transformed instruction (truncating it could yield a valid load/store
   encoding); fetch the instruction from guest memory instead.
 - Drop is_load_guest_page_fault() and open-code the check at its only
   user: with no store counterpart, such a helper is fragile.
 - Make guest_xlen() RV128-compatible by checking (xl > XLEN_FIELD_32)
   instead of (xl == XLEN_FIELD_64) before consulting vsstatus.UXL.
 - Clarify in struct decoded_insn that insn may hold the 32-bit transformed
   equivalent of the trapped instruction, and that insn_len is the length of
   the trapped instruction in guest memory rather than of the encoding in
   insn.
 - Say that none of the extensions exposed to guests has instructions wider
   than 32 bits, instead of referring to what the ISA defines, which is at
   risk of going stale.
 - Document in guest_gpr() that register bits above the guest's XLEN are not
   guaranteed to be zero or a sign extension, so callers must not rely on
   them when reading and must sign-extend what they write.
 - Explain why utrap.sepc can't be set in the initializer: on a fault
   read_guest() overwrites it with the address of its own faulting access.
 - Mention that stval, being XLEN bits wide, may not be able to hold a wider
   instruction as another reason for leaving it zero.
 - Calculate insn_len ahead of the width check and use it there, instead of
   testing INSN_IS_16BIT() and INSN_IS_32BIT() separately.
 - Drop the resets of is_write and is_unsigned in decode_ldst_insn() and
   state that @di is expected to start out zeroed instead.
 - Report an illegal instruction for a compressed encoding read back from
   guest memory when C isn't exposed to the guest.
 - Have guest_gpr() take the decoded instruction rather than a bare register
   number, and assert there that the access width fits a guest register.
 - Decode the access width from funct3 (from bits[15:13] for the
   compressed forms), which the loads and stores encode uniformly, instead
   of matching the instruction against each of them in turn. Introduce
   INSN_OPCODE_{MASK,LOAD,STORE} for that. Reject by a single check what
   the guest's XLEN doesn't allow, i.e. an access wider than a guest
   register, which neither the value an emulated access moves nor the
   register operand guest_gpr() hands out could carry.
 - Say which field of the compressed forms holds the register operand:
   RVC_RS2S() gives rd' of a load as well as rs2' of a store.
 - guest_gpr(): resolve the register via regs_gpr_ptr() from asm/regs.h
   instead of REG_PTR(), sharing its bounds check.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/emulate.c                    | 335 ++++++++++++++++++++
 xen/arch/riscv/include/asm/riscv_encoding.h |  14 +
 2 files changed, 349 insertions(+)

diff --git a/xen/arch/riscv/emulate.c b/xen/arch/riscv/emulate.c
index d661ef0bf204..a30b2a7fadae 100644
--- a/xen/arch/riscv/emulate.c
+++ b/xen/arch/riscv/emulate.c
@@ -13,9 +13,40 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
+#include <asm/regs.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 trapped instruction: as read from guest memory, or the 32-bit
+     * equivalent the hardware transformed it into (see insn_fetch_faulted()).
+     * None of the extensions exposed to guests has instructions wider than
+     * 32 bits, and insn_fetch_faulted() rejects anything longer.
+     */
+    uint32_t insn;
+    /*
+     * Length in bytes of the trapped instruction in guest memory: 2 or 4.
+     * This need not be the length of the encoding in insn, as a compressed
+     * instruction may have been transformed into its 32-bit equivalent.
+     */
+    uint8_t insn_len;
+    /* Width of the memory access, in bytes. */
+    uint8_t len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    uint8_t reg;
+    /* The access is a store rather than a load. */
+    bool is_write:1;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned:1;
+};
+
 /*
  * 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 +70,65 @@ struct guest_fault {
     paddr_t gpa;
 };
 
+static 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: if VSXL says 32,
+ * vsstatus has no UXL field, so VU-mode is 32-bit as well and there is
+ * 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 unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned int xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);
+
+    if ( (xl > XLEN_FIELD_32) && !(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 special pseudoinstruction values, reported for a guest
  * page fault taken on an implicit memory access done for VS-stage address
@@ -86,8 +176,253 @@ static int resolve_faulting_gpa(struct guest_fault *gf)
     return 0;
 }
 
+/*
+ * Where the value of a decoded instruction's register operand is held.
+ *
+ * The register is held at its full width, whatever the guest's XLEN is (see
+ * guest_xlen()). Where XLEN is narrower, the bits above it are not guaranteed
+ * to be zero, nor even a sign extension: hardware only ignores them in source
+ * operands, so they may have been left there by more privileged code running
+ * at a wider XLEN. Hence callers must not rely on those bits when reading a
+ * value, and must sign-extend what they write from bit XLEN-1, as hardware
+ * does for the result of an operation.
+ */
+static unsigned long *guest_gpr(struct cpu_user_regs *regs,
+                                const struct decoded_insn *di)
+{
+    /*
+     * decode_ldst_insn() is what fills @di in, and it rejects an access
+     * wider than a guest register.
+     */
+    ASSERT(di->len <= (guest_xlen(regs) / BITS_PER_BYTE));
+
+    return regs_gpr_ptr(regs, di->reg);
+}
+
+/*
+ * 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 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));
+
+    /*
+     * Bit[0] == 1 implies trapped instruction value is transformed instruction
+     * or custom value. A transformed instruction is a 32-bit encoding, so a
+     * value with any bit above bit[31] set is a custom one, which is of no use
+     * for decoding: fetch the instruction from guest memory then, as for zero.
+     */
+    if ( (htinst & BIT(0, UL)) && (htinst == (uint32_t)htinst) )
+    {
+        /*
+         * A compressed instruction is reported already expanded to its 32-bit
+         * equivalent, so htinst always holds a 32-bit encoding, except for
+         * bits[1:0], which hold a marker: bit[0] is set to flag the
+         * transformation and bit[1] is clear if the trapped instruction was
+         * compressed. Setting both bits gives a 32-bit encoding
+         * decode_ldst_insn() can decode. (Its handling of compressed
+         * encodings is for the branch below, which reads the instruction from
+         * guest memory as is.)
+         *
+         * 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 | 3;
+        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. Pseudoinstructions never get here (see the comment ahead of
+         * the ASSERT() above), so only zero (or a custom value, see above) is
+         * left: the instruction has to be read from guest memory.
+         */
+
+        di->insn = read_guest(regs->sepc, true, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * If a G-stage translation fault happens while fetching the
+             * trapped instruction, CAUSE_LOAD_GUEST_PAGE_FAULT is generated,
+             * hlvx being a load. Such a fault is reported to the guest as an
+             * instruction access fault.
+             */
+            if ( utrap.scause == CAUSE_LOAD_GUEST_PAGE_FAULT )
+                utrap.scause = CAUSE_FETCH_ACCESS;
+
+            /*
+             * Not set in the initializer: on a fault read_guest() leaves in
+             * utrap.sepc the address of its own faulting access, whereas the
+             * trap is to be reported at the guest instruction.
+             */
+            utrap.sepc = regs->sepc;
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        di->insn_len = INSN_LEN(di->insn);
+
+        /*
+         * read_guest() fetches at most two halfwords, so a wider encoding has
+         * been read in part only and cannot be decoded here.
+         *
+         * Report an illegal instruction: none of the extensions exposed to
+         * guests has instructions wider than 32 bits, so such an encoding is
+         * not a valid instruction for the guest in the first place.
+         *
+         * The same goes for a compressed encoding where C isn't exposed to the
+         * guest. The instruction in guest memory may have changed since the
+         * trap, so what is read back must not be assumed to be what trapped,
+         * nor to be valid for the guest.
+         */
+        if ( !di->insn_len ||
+             (di->insn_len == 2 &&
+              !riscv_isa_extension_available(current->domain->arch.isa,
+                                             RISCV_ISA_EXT_c)) )
+        {
+            utrap.sepc = regs->sepc;
+            utrap.scause = CAUSE_ILLEGAL_INSTRUCTION;
+            /*
+             * stval is left zero, which the spec allows for an illegal
+             * instruction: only part of the instruction is in hand, and stval,
+             * being only XLEN bits wide, may not be able to hold all of it
+             * anyway.
+             */
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+    }
+
+    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()). Fields which don't apply to the instruction are left
+ * alone, so @di is expected to start out zeroed.
+ *
+ * @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, or cannot be
+ * emulated here.
+ */
+static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)
+{
+    uint32_t insn = di->insn;
+    unsigned int funct3, width_log2;
+
+    if ( INSN_IS_16BIT(insn) )
+    {
+        /*
+         * C.LW, C.LD, C.SW and C.SD (bits[1:0] == 00), and their sp-relative
+         * C.*SP forms (bits[1:0] == 10), have bits[15:13] of the form x1y:
+         * x is set for a store, and y selects a width of 4 or 8 bytes.
+         */
+        funct3 = RV_X(insn, 13, 3);
+
+        if ( (insn & 1) || !(funct3 & 2) )
+            return false;
+
+        di->is_write = funct3 & 4;
+        width_log2 = 2 + (funct3 & 1);
+
+        if ( !(insn & 2) )
+            /* Quadrant 0: bits[4:2] encode rd' (load) or rs2' (store) */
+            di->reg = RVC_RS2S(insn);
+        else if ( di->is_write )
+            /* Quadrant 2 (CSS): bits[6:2] encode rs2 for C.SWSP / C.SDSP */
+            di->reg = RVC_RS2(insn);
+        else
+        {
+            /* Quadrant 2 (CI): bits[11:7] encode rd for C.LWSP / C.LDSP */
+            di->reg = RV_RD(insn);
+
+            /* C.LWSP and C.LDSP are reserved with rd being x0. */
+            if ( !di->reg )
+                return false;
+        }
+    }
+    else
+    {
+        /*
+         * LOAD and STORE (I/S-type) have funct3 in bits[14:12]: funct3[1:0]
+         * is log2 of the width in bytes, and funct3[2] selects zero-extension
+         * for a load, while being reserved for a store.
+         */
+        funct3 = RV_X(insn, 12, 3);
+        width_log2 = funct3 & 3;
+
+        switch ( insn & INSN_OPCODE_MASK )
+        {
+        case INSN_OPCODE_LOAD:
+            di->is_unsigned = funct3 & 4;
+            di->reg = RV_RD(insn);
+            break;
+
+        case INSN_OPCODE_STORE:
+            if ( funct3 & 4 )
+                return false;
+            di->is_write = true;
+            di->reg = RV_RS2(insn);
+            break;
+
+        default:
+            return false;
+        }
+    }
+
+    di->len = 1U << width_log2;
+
+    /*
+     * No access is wider than XLEN, and one as wide as XLEN exists only in
+     * its sign-extending form: this rules out the encodings which exist for
+     * XLEN=64 only on a 32-bit guest, including C.FLW for C.LD (and alike).
+     */
+    if ( (di->len * BITS_PER_BYTE > xlen) ||
+         (di->is_unsigned && di->len * BITS_PER_BYTE == xlen) )
+        return false;
+
+    return true;
+}
+
 static int emulate_load(const struct guest_fault *gf)
 {
+    /* Transient, until the helpers gain their users. */
+    (void)advance_pc;
+    (void)guest_xlen;
+    (void)guest_gpr;
+    (void)insn_fetch_faulted;
+    (void)decode_ldst_insn;
+
     return -EOPNOTSUPP;
 }
 
diff --git a/xen/arch/riscv/include/asm/riscv_encoding.h b/xen/arch/riscv/include/asm/riscv_encoding.h
index fa26f5a2eb86..4529bef856b1 100644
--- a/xen/arch/riscv/include/asm/riscv_encoding.h
+++ b/xen/arch/riscv/include/asm/riscv_encoding.h
@@ -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
@@ -854,6 +862,10 @@
 /* 32-bit write for VS-stage address translation (VSXLEN=32) */
 #define INSN_PSEUDO_VS_STORE32		0x00002020
 
+#define INSN_OPCODE_MASK		0x7f
+#define INSN_OPCODE_LOAD		0x03
+#define INSN_OPCODE_STORE		0x23
+
 #define INSN_IS_16BIT(insn)	(((insn) & 3) != 3)
 #define INSN_IS_32BIT(insn)	(!INSN_IS_16BIT(insn) && ((insn) & 0x1c) != 0x1c)
 
@@ -895,6 +907,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)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 21/42] xen/riscv: add guest load emulation for trapped MMIO accesses
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (19 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 20/42] xen/riscv: add helpers for decoding a trapped load or store Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 22/42] xen/riscv: add guest store " Oleksii Kurochko
                   ` (20 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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

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

Sign and zero extension are done here rather than in the handlers: a
shift pair drops whatever lies above the access width in the value read
and, for a signed load, sign-extends it, 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.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Drop the bits above the access width from the value read for an
   unsigned load too, so that a handler need not clear them itself.
 - Update the commit message accordingly.
---
Changes in v3:
 - Shorten the comment above "if ( di.reg )" by dropping redundant part.
 - s/sizeof(unsigned long)/sizeof(info.data) in emulate_load().
 - Zero-initialize di, as decode_ldst_insn() expects it to start out zeroed.
 - Adjust to guest_gpr() taking the decoded instruction rather than a bare
   register number.
---
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 | 40 +++++++++++++++++++++++++++++++++-------
 1 file changed, 33 insertions(+), 7 deletions(-)

diff --git a/xen/arch/riscv/emulate.c b/xen/arch/riscv/emulate.c
index a30b2a7fadae..e95642b7617f 100644
--- a/xen/arch/riscv/emulate.c
+++ b/xen/arch/riscv/emulate.c
@@ -14,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/regs.h>
 #include <asm/riscv_encoding.h>
@@ -416,14 +417,39 @@ static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)
 
 static int emulate_load(const struct guest_fault *gf)
 {
-    /* Transient, until the helpers gain their users. */
-    (void)advance_pc;
-    (void)guest_xlen;
-    (void)guest_gpr;
-    (void)insn_fetch_faulted;
-    (void)decode_ldst_insn;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = false };
+    struct decoded_insn di = {};
+    unsigned int shift;
+    int rc;
 
-    return -EOPNOTSUPP;
+    /* 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;
+
+    shift = BITS_PER_BYTE * (sizeof(info.data) - 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. */
+    if ( di.reg )
+        *guest_gpr(regs, &di) = di.is_unsigned
+                                ? (info.data << shift) >> shift
+                                : (long)(info.data << shift) >> shift;
+
+    advance_pc(regs, di.insn_len);
+
+    return 0;
 }
 
 static int emulate_store(const struct guest_fault *gf)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 22/42] xen/riscv: add guest store emulation for trapped MMIO accesses
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (20 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 21/42] xen/riscv: add guest load emulation for trapped MMIO accesses Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 23/42] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL Oleksii Kurochko
                   ` (19 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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

Like emulate_load(), emulate_store() obtains the trapped instruction with
insn_fetch_faulted(), which also deals with a fault taken while re-reading
it, and decodes it with decode_ldst_insn(). As with the load path, the
access is completed synchronously through do_mmio().

At the moment the only MMIO handler registered is the vAPLIC one, so in
practice every trapped guest store ends up in vaplic_mmio_ops' write
handler.

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

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
Changes in v4:
 - Update the commit message.
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
---
Changes in v3:
 - Update the commit message.
 - Zero-initialize di, as decode_ldst_insn() expects it to start out zeroed.
 - Adjust to guest_gpr() taking the decoded instruction rather than a bare
   register number.
 - Don't change the prototype of emulate_store(): the stub takes a pointer
   to const already.
---
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 | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)

diff --git a/xen/arch/riscv/emulate.c b/xen/arch/riscv/emulate.c
index e95642b7617f..170485ef4c01 100644
--- a/xen/arch/riscv/emulate.c
+++ b/xen/arch/riscv/emulate.c
@@ -454,7 +454,26 @@ static int emulate_load(const 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);
+
+    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)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 23/42] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (21 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 22/42] xen/riscv: add guest store " Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 24/42] xen/riscv: implement continue_new_vcpu() Oleksii Kurochko
                   ` (18 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

The reset value of hstatus.VSXL isn't architecturally defined, so it
has to be programmed explicitly from the domain's type instead of
relying on whatever the hardware happens to leave there.

This matters beyond the guest's own view of itself: decoding of 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.

The field is WARL: an implementation is permitted to make it read-only
with a value that always keeps VSXLEN == HSXLEN. Probe at boot which
encodings can really be set, and refuse to construct a domain whose
width the hardware cannot provide, rather than silently running it at
the wrong XLEN.

The field occupies bits 33:32 and hence doesn't exist when HSXLEN=32,
where VSXLEN is always 32 and HSTATUS_VSXL isn't even defined. Hence
the split on CONFIG_RISCV_32, even though RV32 isn't buildable yet.

vCPU0 is created before kernel_probe() reads the guest kernel header,
from which set_domain_type() derives the domain's type, and hence the
guest's XLEN, so the field can't be set when the vCPU is created:
vcpu_csr_init() leaves it zero. vcpu_set_vsxl() is to fill it in from
continue_new_vcpu() instead, on the vCPU's first entry, which every
vCPU goes through whichever way its domain is built.
continue_new_vcpu() isn't implemented yet, so for now it only
references vcpu_set_vsxl() to keep the compiler from complaining about
it being unused.

By then the domain is built and about to run, so it is too late to
reject a width the hardware cannot provide. construct_domain()
therefore checks it up front, before any of the domain's images are
loaded.

domain_vsxl() only maps a domain type onto the encoding, and
hstatus_vsxl_settable() tells whether the hardware accepts it. The
switch() in domain_vsxl() deliberately has no default case, so that
adding a 128-bit domain type fails to build until the mapping is
updated. Should it nevertheless be left without a mapping, it returns
the reserved encoding, named XLEN_FIELD_RESERVED, which
hstatus_vsxl_settable() never accepts.

While at it drop HSTATUS_VSXL_SHIFT, which has no users and isn't
expected to gain any.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Move ahead of "xen/riscv: implement continue_new_vcpu()", so that
   hstatus is never loaded with the reserved VSXL encoding of 0.
 - Move the explanation of the missing default case into the switch() of
   domain_vsxl(), saying it is -Wswitch which fails the build.
 - Introduce XLEN_FIELD_RESERVED for the value domain_vsxl() returns
   when it can't map the domain's type.
 - Name kernel_probe() in the comment in vcpu_csr_init() and in the
   commit message, as "probe" could be taken for the probing of the
   settable hstatus.VSXL values.
---
Changes in v3:
 - Derive the width from the domain's type instead of hardcoding
   HSTATUS_VSXL_64, now that the preceding patches make d->type correct.
 - Probe at boot which VSXL encodings the hardware really accepts, and
   refuse in construct_domain() a domain whose width it cannot provide
   instead of silently running the guest at the wrong XLEN.
 - Move the write out of vcpu_csr_init(), which runs before the domain's
   type is known, into vcpu_set_vsxl() called from continue_new_vcpu().
   As a consequence the patch is moved after the one implementing
   continue_new_vcpu().
 - Handle RV32, where the field doesn't exist at all and VSXLEN is
   always 32.
 - Use XLEN_FIELD_{32,64} introduced earlier in the series instead of
   adding HSTATUS_VSXL_{32,64}: it is the same encoding, and unlike the
   latter it isn't hidden behind #if __riscv_xlen == 64, which the RV32
   paths need.
 - Drop HSTATUS_VSXL_SHIFT, which has no users.
 - Rework the commit message accordingly.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/domain-build.c               |   8 ++
 xen/arch/riscv/domain.c                     | 123 ++++++++++++++++++++
 xen/arch/riscv/include/asm/domain.h         |   3 +
 xen/arch/riscv/include/asm/riscv_encoding.h |   2 +-
 xen/arch/riscv/include/asm/setup.h          |   2 +
 xen/arch/riscv/setup.c                      |   2 +
 6 files changed, 139 insertions(+), 1 deletion(-)

diff --git a/xen/arch/riscv/domain-build.c b/xen/arch/riscv/domain-build.c
index 1e3abe259ccd..1acaf0946130 100644
--- a/xen/arch/riscv/domain-build.c
+++ b/xen/arch/riscv/domain-build.c
@@ -15,9 +15,17 @@ int __init construct_domain(struct domain *d, struct kernel_info *kinfo)
 {
     struct vcpu *v = d->vcpu[0];
     struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(v);
+    unsigned int vsxl = domain_vsxl(d);
 
     BUG_ON(v->is_initialised);
 
+    /* Refuse the domain before any of its images are loaded. */
+    if ( !hstatus_vsxl_settable(vsxl) )
+    {
+        printk(XENLOG_ERR "%pd: hstatus.VSXL cannot be set to %u\n", d, vsxl);
+        return -EOPNOTSUPP;
+    }
+
     /*
      * At the moment *_load() don't return value and will just panic()
      * inside.
diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index 7be019e2ad12..66fa14c89eaf 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -51,6 +51,121 @@ static struct csr_masks __ro_after_init csr_masks;
 #define HENVCFG_VALID_MASK 0xe0000003000000ffUL
 #define HSTATEEN0_VALID_MASK 0xde00000000000007UL
 
+/*
+ * Return the hstatus.VSXL value encoding the guest's XLEN. Whether the
+ * hardware can actually provide that width is a separate question, answered
+ * by hstatus_vsxl_settable().
+ */
+unsigned int domain_vsxl(const struct domain *d)
+{
+    switch ( d->type )
+    {
+    case DOMAIN_32BIT:
+        return XLEN_FIELD_32;
+
+    case DOMAIN_64BIT:
+        return XLEN_FIELD_64;
+
+    /*
+     * No default case: -Wswitch then fails the build should a new
+     * domain_type (a 128-bit one, in particular) be added without
+     * updating this mapping.
+     */
+    }
+
+    ASSERT_UNREACHABLE();
+
+    /* Never accepted by hstatus_vsxl_settable(). */
+    return XLEN_FIELD_RESERVED;
+}
+
+#ifdef CONFIG_RISCV_32
+
+/*
+ * hstatus.VSXL occupies bits 33:32 and hence does not exist when HSXLEN=32.
+ * VSXLEN is then always 32, so there is nothing to probe and no width other
+ * than 32 to accept.
+ */
+void __init init_hstatus_vsxl_settable_mask(void)
+{
+}
+
+bool hstatus_vsxl_settable(unsigned int vsxl)
+{
+    return vsxl == XLEN_FIELD_32;
+}
+
+static void vcpu_set_vsxl(struct vcpu *v)
+{
+    ASSERT(is_32bit_domain(v->domain));
+}
+
+#else /* CONFIG_RISCV_64 */
+
+/*
+ * Bitmap of the hstatus.VSXL values this hardware accepts, indexed by field
+ * value. Not one of csr_masks: those are bit masks ANDed into a CSR write,
+ * this is a set of legal values of a single WARL field.
+ */
+static unsigned int __ro_after_init hstatus_vsxl_settable_mask;
+
+/*
+ * hstatus.VSXL is WARL and, in particular, an implementation is permitted to
+ * make it read-only with a value that always keeps VSXLEN == HSXLEN. Probe
+ * once which values can really be set, so that a domain whose width the
+ * hardware cannot provide is refused rather than silently run at the wrong
+ * XLEN.
+ *
+ * Every encoding the field can hold is probed, XLEN_FIELD_128 included, so
+ * that a guest width added later needs no change here.
+ *
+ * Like the CSR masks below this assumes all harts behave the same way.
+ */
+void __init init_hstatus_vsxl_settable_mask(void)
+{
+    register_t hstatus = csr_read(CSR_HSTATUS);
+
+    /* Encoding 0 is reserved, hence starting at the narrowest width. */
+    for ( unsigned int vsxl = XLEN_FIELD_32; vsxl <= XLEN_FIELD_128; vsxl++ )
+    {
+        register_t test = (hstatus & ~HSTATUS_VSXL) |
+                          MASK_INSR(vsxl, HSTATUS_VSXL);
+
+        csr_write(CSR_HSTATUS, test);
+
+        if ( MASK_EXTR(csr_read(CSR_HSTATUS), HSTATUS_VSXL) == vsxl )
+            hstatus_vsxl_settable_mask |= BIT(vsxl, U);
+    }
+
+    csr_write(CSR_HSTATUS, hstatus);
+}
+
+/*
+ * Whether the hardware really accepts the given hstatus.VSXL value, i.e.
+ * whether a guest of that XLEN can be run at all.
+ */
+bool hstatus_vsxl_settable(unsigned int vsxl)
+{
+    return hstatus_vsxl_settable_mask & BIT(vsxl, U);
+}
+
+/*
+ * Set the guest's XLEN explicitly rather than leaving it to the WARL
+ * behaviour of hstatus.VSXL.
+ */
+static void vcpu_set_vsxl(struct vcpu *v)
+{
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(v);
+    unsigned int vsxl = domain_vsxl(v->domain);
+
+    ASSERT(hstatus_vsxl_settable(vsxl));
+
+    regs->hstatus = (regs->hstatus & ~HSTATUS_VSXL) |
+                    MASK_INSR(vsxl, HSTATUS_VSXL);
+}
+
+#endif /* CONFIG_RISCV_32 */
+
 void __init init_csr_masks(void)
 {
     /*
@@ -91,6 +206,11 @@ static void vcpu_csr_init(struct vcpu *v)
 {
     v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
+    /*
+     * hstatus.VSXL is left zero here: vCPU0 is created before
+     * kernel_probe() reads the guest kernel header, so the domain's type,
+     * and hence the guest's XLEN, is not known yet.
+     */
     vcpu_guest_cpu_user_regs(v)->hstatus = HSTATUS_SPV | HSTATUS_SPVP;
 
     v->arch.hideleg = HIDELEG_DEFAULT & csr_masks.hideleg;
@@ -134,6 +254,9 @@ static void vcpu_csr_init(struct vcpu *v)
 
 static void continue_new_vcpu(struct vcpu *prev)
 {
+    /* Avoid an unused-function error until this function is implemented. */
+    (void)vcpu_set_vsxl;
+
     BUG_ON("unimplemented\n");
 }
 
diff --git a/xen/arch/riscv/include/asm/domain.h b/xen/arch/riscv/include/asm/domain.h
index c424e2428f60..005553648a3b 100644
--- a/xen/arch/riscv/include/asm/domain.h
+++ b/xen/arch/riscv/include/asm/domain.h
@@ -144,6 +144,9 @@ int vcpu_unset_interrupt(struct vcpu *v, unsigned int irq);
 void vcpu_sync_interrupts(struct vcpu *curr);
 void vcpu_flush_interrupts(struct vcpu *curr);
 
+bool hstatus_vsxl_settable(unsigned int vsxl);
+unsigned int domain_vsxl(const struct domain *d);
+
 #endif /* RISCV_DOMAIN_H */
 
 /*
diff --git a/xen/arch/riscv/include/asm/riscv_encoding.h b/xen/arch/riscv/include/asm/riscv_encoding.h
index 4529bef856b1..e909e1742f51 100644
--- a/xen/arch/riscv/include/asm/riscv_encoding.h
+++ b/xen/arch/riscv/include/asm/riscv_encoding.h
@@ -69,13 +69,13 @@
  * Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one
  * encoding. 0 is reserved.
  */
+#define XLEN_FIELD_RESERVED		_UL(0)
 #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
 #endif
 #define HSTATUS_VTSR			_UL(0x00400000)
 #define HSTATUS_VTW			_UL(0x00200000)
diff --git a/xen/arch/riscv/include/asm/setup.h b/xen/arch/riscv/include/asm/setup.h
index 8eee8a746335..7e6e81751ddb 100644
--- a/xen/arch/riscv/include/asm/setup.h
+++ b/xen/arch/riscv/include/asm/setup.h
@@ -11,6 +11,8 @@ void copy_from_paddr(void *dst, paddr_t paddr, unsigned long len);
 
 void init_csr_masks(void);
 
+void init_hstatus_vsxl_settable_mask(void);
+
 #endif /* RISCV_SETUP_H */
 
 /*
diff --git a/xen/arch/riscv/setup.c b/xen/arch/riscv/setup.c
index 05f93a74c9d3..fd699defcfc3 100644
--- a/xen/arch/riscv/setup.c
+++ b/xen/arch/riscv/setup.c
@@ -149,6 +149,8 @@ void __init noreturn start_xen(unsigned long bootcpu_id,
 
     init_csr_masks();
 
+    init_hstatus_vsxl_settable_mask();
+
     preinit_xen_time();
 
     intc_preinit();
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 24/42] xen/riscv: implement continue_new_vcpu()
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (22 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 23/42] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 25/42] xen/riscv: add basic VGEIN management for AIA guests Oleksii Kurochko
                   ` (17 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

continue_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, enter the guest through the new
   return_to_new_vcpu() path in entry.S. It restores hstatus and
   sepc and passes the hart id in a0. a1 holds the DTB address for
   the boot vCPU (as expected by the RISC-V boot protocol), or the
   opaque value passed to SBI HSM hart_start() for secondary vCPUs.
   It then clears the remaining GPRs, sets sstatus.SPP and
   sstatus.SPIE, and executes sret.

The remaining GPRs have to be cleared as sret neither switches stacks
nor touches the GPRs: the guest would otherwise start with Xen's values
in them, sp pointing to this vCPU's Xen stack among them.

Interrupts have to stay disabled across the restore. A trap taken in
HS-mode overwrites hstatus.SPV, sstatus.SPP and sepc (trap entry clears
hstatus.SPV in particular), so an interrupt taken between the write of
hstatus and sret would make sret return to HS-mode instead of VS-mode,
and restoring them afterwards is non-trivial. Instead interrupts are
simply kept off and sstatus.SPIE is set, so that sret re-enables them
by restoring sstatus.SIE from SPIE.

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 only introduced as a stub.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
Changes in v4:
 - Split the description of the guest vCPU case in the commit message
   into several sentences.
 - Call vcpu_set_vsxl() before entering the guest, as "xen/riscv: set
   the guest's XLEN explicitly in hstatus.VSXL" now comes first.
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
---
Changes in v3:
 - Drop unneeded inclusion of asm/aia.h, asm/aplic.h and asm/imsic.h.
 - Mark return_to_new_vcpu() declaration with asmlinkage.
 - Drop the "else" after reset_stack_and_jump(idle_loop), which cannot
   return.
 - Move the restore of hstatus and the setting of sstatus.SPIE from
   continue_new_vcpu() to return_to_new_vcpu(), so that everything sret
   depends on is set up in one place, and shorten the comment in
   continue_new_vcpu() accordingly.
 - Move the tp/SSCRATCH swap out to a separate patch, as nothing reads
   SSCRATCH yet.
 - Reword the comments in return_to_new_vcpu(), which suggested that
   the values of .a0 and .a1 are established there.
 - Clear the GPRs which are not meaningful to the vCPU being started
   before sret, so that Xen register values are not exposed to a guest.
 - Update the commit message: a1 carries the opaque value passed to
   hart_start() for secondary vCPUs, describe the clearing of the GPRs,
   drop the comparison with a real CPU and the reference to a later
   implementation of idle_loop().
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/domain.c              | 28 +++++++++++++++++---
 xen/arch/riscv/entry.S               | 39 ++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/current.h |  4 +++
 3 files changed, 68 insertions(+), 3 deletions(-)

diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index 66fa14c89eaf..65d582aa8fe0 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -252,12 +252,29 @@ static void vcpu_csr_init(struct vcpu *v)
     }
 }
 
+static void schedule_tail(struct vcpu *prev);
+static void noreturn idle_loop(void);
+void asmlinkage noreturn return_to_new_vcpu(void);
+
 static void continue_new_vcpu(struct vcpu *prev)
 {
-    /* Avoid an unused-function error until this function is implemented. */
-    (void)vcpu_set_vsxl;
+    schedule_tail(prev);
+
+    if ( is_idle_vcpu(current) )
+        reset_stack_and_jump(idle_loop);
 
-    BUG_ON("unimplemented\n");
+    vcpu_set_vsxl(current);
+
+    /*
+     * return_to_new_vcpu() sets up hstatus.SPV, sstatus.SPP and sepc so
+     * that sret enters the guest in VS-mode. A trap taken in HS-mode
+     * overwrites all of them (trap entry clears hstatus.SPV in particular),
+     * so interrupts have to stay disabled until sret. They are re-enabled by
+     * sret itself, as return_to_new_vcpu() also sets sstatus.SPIE.
+     */
+    local_irq_disable();
+
+    reset_stack_and_jump(return_to_new_vcpu);
 }
 
 int arch_vcpu_create(struct vcpu *v)
@@ -629,3 +646,8 @@ static void __init __maybe_unused build_assertions(void)
 
 #undef CHECK_GPR_INDEX
 }
+
+static void noreturn idle_loop(void)
+{
+    BUG_ON("unimplemented");
+}
diff --git a/xen/arch/riscv/entry.S b/xen/arch/riscv/entry.S
index 017fbb06262c..99bc0f4974c2 100644
--- a/xen/arch/riscv/entry.S
+++ b/xen/arch/riscv/entry.S
@@ -147,3 +147,42 @@ FUNC(__context_switch)
 
         ret
 END(__context_switch)
+
+/*
+ * Enter a vCPU for the first time. Must be called with interrupts disabled,
+ * see continue_new_vcpu().
+ */
+FUNC(return_to_new_vcpu)
+        REG_L   t0, CPU_USER_REGS_HSTATUS(sp)
+        csrw    CSR_HSTATUS, t0
+
+        REG_L   t0, CPU_USER_REGS_SEPC(sp)
+        csrw    CSR_SEPC, t0
+
+        /* .a0 holds the hart id */
+        REG_L   a0, CPU_USER_REGS_A0(sp)
+
+        /*
+         * .a1 holds the DTB address for the boot vCPU, or the opaque value
+         * passed to SBI HSM hart_start() for secondary vCPUs
+         */
+        REG_L   a1, CPU_USER_REGS_A1(sp)
+
+        /* Return to (V)S-mode, with interrupts re-enabled by sret */
+        li      t0, SSTATUS_SPP | SSTATUS_SPIE
+        csrs    CSR_SSTATUS, t0
+
+        /*
+         * sret doesn't switch stacks and leaves the GPRs alone, so every
+         * register which isn't meaningful to the vCPU being started has to be
+         * cleared here: otherwise the guest would see Xen's values, sp (this
+         * vCPU's Xen stack) and ra among them.
+         */
+        .irp reg, ra, sp, gp, tp, t0, t1, t2, s0, s1, a2, a3, a4, a5, a6, a7, \
+                  s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, t3, t4, t5, t6
+        mv      \reg, zero
+        .endr
+
+        /* Enter guest */
+        sret
+END(return_to_new_vcpu)
diff --git a/xen/arch/riscv/include/asm/current.h b/xen/arch/riscv/include/asm/current.h
index 1f1010e5864f..9cc5e050ced8 100644
--- a/xen/arch/riscv/include/asm/current.h
+++ b/xen/arch/riscv/include/asm/current.h
@@ -49,6 +49,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)
@@ -60,6 +62,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__ */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 25/42] xen/riscv: add basic VGEIN management for AIA guests
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (23 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 24/42] xen/riscv: implement continue_new_vcpu() Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 26/42] xen/riscv: map IMSIC interrupt file for vCPUs Oleksii Kurochko
                   ` (16 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

It was decided to add support for IMSIC from the start instead of having APLIC
operate in direct delivery mode, as it requires a trap-and-emulation approach,
which is not optimal from a performance standpoint.

AIA provides a hardware-accelerated mechanism for delivering external
interrupts to domains via "guest interrupt files" located in IMSIC.
A single physical hart can implement multiple such files (up to GEILEN),
allowing several virtual harts to receive interrupts directly from hardware.

Introduce per-CPU tracking of guest interrupt file identifiers (VGEIN)
for systems implementing AIA specification. Each CPU maintains
a bitmap describing which guest interrupt files are currently in use.

Implement helpers to initialize the bitmap based on the number of available
guest interrupt files (GEILEN), assign a VGEIN to a vCPU, and release it
when no longer needed.

vgein_release() takes the pCPU the VGEIN belongs to explicitly rather
than relying on v->processor, as the two may differ: a vCPU moved to
another pCPU has to release the VGEIN of the pCPU it leaves, while
v->processor already names the new one. As the bitmap of a pCPU may thus
be changed from another pCPU, it is protected by a lock.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Acked-by: Jan Beulich <jbeulich@suse.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
vgein_assign() gets its first user in "xen/riscv: introduce IMSIC h/w
interrupt file attaching to vcpu", and vgein_release() one taking the
VGEIN of another pCPU in "xen/riscv: save and clear the old IMSIC
VS-file on vCPU migration".
---
Changes in v4:
 - Include <xen/sched.h> here, as this is where v gets dereferenced.
 - Move ahead of the patches using vgein_assign() and vgein_release(),
   introducing them here instead of replacing stubs, and explain in the
   commit message why vgein_release() takes the pCPU and the bitmap is
   protected by a lock.
---
Changes in v3:
 - Add Acked-by: Jan Beulich <jbeulich@suse.com>.
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>.
---
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             | 147 +++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aia.h |   5 ++
 2 files changed, 152 insertions(+)

diff --git a/xen/arch/riscv/aia.c b/xen/arch/riscv/aia.c
index e31c9c2d24b6..b330da918154 100644
--- a/xen/arch/riscv/aia.c
+++ b/xen/arch/riscv/aia.c
@@ -1,11 +1,31 @@
 /* SPDX-License-Identifier: GPL-2.0-only */
 
+#include <xen/bitops.h>
+#include <xen/cpu.h>
 #include <xen/errno.h>
 #include <xen/init.h>
+#include <xen/sched.h>
 #include <xen/sections.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;
 
@@ -14,10 +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)
+{
+    unsigned int vgein_id;
+    struct vgein_ctrl *vgein = &per_cpu(vgein, v->processor);
+    unsigned long *bmp = &vgein->bmp;
+    unsigned long flags;
+
+    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)
+{
+    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
 }
diff --git a/xen/arch/riscv/include/asm/aia.h b/xen/arch/riscv/include/asm/aia.h
index aaa4bf91fc75..8e4eb2f6b14e 100644
--- a/xen/arch/riscv/include/asm/aia.h
+++ b/xen/arch/riscv/include/asm/aia.h
@@ -3,8 +3,13 @@
 #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);
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu);
+
 #endif /* RISCV_AIA_H */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 26/42] xen/riscv: map IMSIC interrupt file for vCPUs
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (24 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 25/42] xen/riscv: add basic VGEIN management for AIA guests Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 27/42] xen/riscv: introduce vaplic_reconfigure_target() Oleksii Kurochko
                   ` (15 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

A guest running in VS-mode expects its own IMSIC S-file at offset 0 of its
guest-physical IMSIC block. Physically, the guest-file (G-file) assigned to
this vCPU lives at a hart-relative offset given by guest_file_id (assigned
via the vGEIN allocator). Therefore, imsic_map_guest_file() uses stage-2
translation to redirect the guest's fixed per-vCPU GPA page (offset 0) to
the specific physical guest-file page.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
Acked-by: Jan Beulich <jbeulich@suse.com>
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
imsic_map_guest_file() gets its user in "xen/riscv: introduce IMSIC h/w
interrupt file attaching to vcpu".
---
Changes in v4:
 - Move ahead of the patch using imsic_map_guest_file(), introducing it
   here instead of replacing a stub.
---
Changes in v3:
 - Add Acked-by: Jan Beulich <jbeulich@suse.com>
 - Use dprintk() instead of printk() for the IMSIC_DEBUG message in
   imsic_map_guest_file().
 - Add Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
---
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             | 69 ++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/imsic.h |  2 +
 2 files changed, 71 insertions(+)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index 8f29c5d2eec1..a17aae7b6ffa 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -26,6 +26,7 @@
 #include <xen/xvmalloc.h>
 
 #include <asm/imsic.h>
+#include <asm/p2m.h>
 
 #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
 
@@ -342,6 +343,74 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
     return 0;
 }
 
+/*
+ * 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)
+{
+    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
+    dprintk(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)
 {
     struct vimsic_state *imsic_state;
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index 11e1e3950f42..0f68e8e89496 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -96,4 +96,6 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
 int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
+
 #endif /* RISCV_IMSIC_H */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 27/42] xen/riscv: introduce vaplic_reconfigure_target()
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (25 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 26/42] xen/riscv: map IMSIC interrupt file for vCPUs Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 28/42] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu Oleksii Kurochko
                   ` (14 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

When a vCPU is migrated to a different pCPU, its IMSIC guest interrupt
file changes. Any APLIC interrupt previously configured to deliver an
MSI to the old interrupt file must be retargeted to the new one.

Implement vaplic_reconfigure_target() to walk the h/w interrupts routed
to the domain and rewrite the APLIC TARGET register of every one whose
guest-programmed target names the vCPU, building the new value with
aplic_msi_target_gen(). Each source is rewritten under its vaplic_source
lock, so that it can't race with a guest write of the same target
register. Nothing calls it yet.

This is correct only as part of step 3 of the sequence in the AIA spec's
"Migrating a virtual hart to a different guest interrupt file". Before
it is called, the new file must be cleared, with eidelivery set to 0,
and recorded in the vCPU's IMSIC state, which aplic_msi_target_gen()
takes the new target from. Once it returns, Xen must synchronize with
the APLIC.

That is also why an interrupt raised mid-retarget isn't lost. An MSI
sent before its source's TARGET register is rewritten is latched in the
old file's eip, the synchronization ensures it has arrived there, and
steps 4 and 5 merge that eip into the new file. One sent after the
rewrite lands in the new file and stays pending there until eidelivery
is restored (step 6).

Also assert in aplic_msi_target_gen() that the physical APLIC is in MSI
delivery mode, which all of its callers rely on.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
vaplic_reconfigure_target() gets its first user in "xen/riscv: introduce
IMSIC h/w interrupt file attaching to vcpu", and is then used by
"xen/riscv: remap interrupts to new IMSIC VS-file" too.
---
Changes in v4:
 - Walk hw_irqs rather than used_irqs: only a h/w source has a physical
   TARGET register to rewrite. The MSIs of a virtual source are injected
   by Xen into whichever interrupt file the vCPU has at that moment, so
   such a source needs no retargeting.
 - Explain in the commit message why an interrupt raised mid-retarget
   isn't lost.
 - Word the comment above aplic_msi_target_gen() as a requirement on
   whoever publishes a new interrupt file, as nothing calls
   vaplic_reconfigure_target() yet.
 - Move right before "xen/riscv: introduce IMSIC h/w interrupt file
   attaching to vcpu", its first user.
 - Don't call the zero value of target[] a reset value, as the AIA spec
   doesn't define one, and mention that skipping EIID 0 also keeps
   unprogrammed sources from being retargeted along with vCPU0.
---
Changes in v3:
 - Update the commit message.
 - Replace aplic_reconfigure_target() in aplic.c with
   vaplic_reconfigure_target() in vaplic.c: the sources to retarget are
   chosen from the guest's view of the target registers, decoded by the
   new vaplic_target_decode_vcpu(), instead of by matching the h/w
   registers against the old guest file id and pCPU, which drops the
   old_guest_file_id and old_cpu parameters. Each source is rewritten
   under its vaplic_source lock, so it can't race with a guest write of the
   same target register.
 - Hold vsfile_lock for reading while retargeting, as aplic_msi_target_gen()
   requires. Lock order is the vaplic_source lock, then vsfile_lock, then
   aplic.lock (taken by aplic_hw_write_reg()).
 - Replace the BUG_ON() on MSI delivery mode with an ASSERT() in
   aplic_msi_target_gen(), so that none of its callers can miss it; direct
   delivery mode isn't supported, so there's no way to get there in
   release builds either.
 - Update the comment above aplic_msi_target_gen() about why vsfile_lock
   has to be held.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/aplic.c              | 13 ++++++-
 xen/arch/riscv/include/asm/vaplic.h |  3 ++
 xen/arch/riscv/vaplic.c             | 60 +++++++++++++++++++++++++++++
 3 files changed, 75 insertions(+), 1 deletion(-)

diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
index 51d7eae4617a..825eb60bf444 100644
--- a/xen/arch/riscv/aplic.c
+++ b/xen/arch/riscv/aplic.c
@@ -129,7 +129,11 @@ static unsigned long aplic_hart_index(unsigned int cpu)
 /*
  * v->processor can't be used here: during a migration it names the new pCPU
  * before the interrupt file is moved there. The caller has to hold
- * vsfile_lock until the result is written to the h/w.
+ * vsfile_lock, so that the guest file id and the pCPU owning it are read as
+ * a consistent pair. A value may still be built from the old file just
+ * before a migration publishes the new one, so whoever publishes a new file
+ * has to call vaplic_reconfigure_target() afterwards, to rewrite every
+ * source targeting the vCPU.
  */
 uint32_t aplic_msi_target_gen(const struct vcpu *v, uint32_t base_val)
 {
@@ -140,6 +144,13 @@ uint32_t aplic_msi_target_gen(const struct vcpu *v, uint32_t base_val)
     ASSERT(rw_is_locked(&vimsic_state->vsfile_lock));
     ASSERT(vimsic_state->vsfile_cpu < NR_CPUS);
 
+    /*
+     * The callers rely on the physical APLIC being in MSI delivery mode.
+     * Checking that here rather than in each of them means none can be
+     * missed should direct delivery mode ever be supported.
+     */
+    ASSERT(aplic_msi_mode());
+
     hart_index = aplic_hart_index(vimsic_state->vsfile_cpu);
 
     base_val &= APLIC_TARGET_EIID;
diff --git a/xen/arch/riscv/include/asm/vaplic.h b/xen/arch/riscv/include/asm/vaplic.h
index 9a121904a346..843b78e80ad8 100644
--- a/xen/arch/riscv/include/asm/vaplic.h
+++ b/xen/arch/riscv/include/asm/vaplic.h
@@ -17,6 +17,7 @@
 #include <asm/intc.h>
 
 struct domain;
+struct vcpu;
 
 #define to_vaplic(d) container_of((d)->arch.vintc, struct vaplic, vintc)
 
@@ -50,4 +51,6 @@ struct vaplic {
 int domain_vaplic_init(struct domain *d);
 void domain_vaplic_deinit(struct domain *d);
 
+void vaplic_reconfigure_target(const struct vcpu *v);
+
 #endif /* RISCV_VAPLIC_H */
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index 7898455b4934..42489bf299b9 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -169,6 +169,66 @@ static void vaplic_target_write(const struct domain *d, unsigned int irqn,
     spin_unlock_irqrestore(&src->lock, flags);
 }
 
+/* Decode the target vCPU from a TARGET snapshot (NULL if none). */
+static struct vcpu *vaplic_target_decode_vcpu(const struct domain *d,
+                                              uint32_t target)
+{
+    unsigned int hart_idx = MASK_EXTR(target, APLIC_TARGET_HART_IDX);
+
+    /*
+     * Skip a source whose EIID is 0: interrupt identity 0 is never valid at
+     * an IMSIC, so such a source delivers nothing and needs no retargeting.
+     * The AIA spec leaves target[] UNSPECIFIED after reset, but the vAPLIC
+     * state is zero-initialized, so this also covers every source the guest
+     * hasn't programmed yet, which would otherwise decode as targeting vCPU0
+     * (hart index 0) and have its h/w TARGET register needlessly rewritten
+     * on every vCPU0 migration.
+     * The hart index range check is only a guard: the write path refuses to
+     * record values with an out-of-range hart index.
+     */
+    if ( !(target & APLIC_TARGET_EIID) || hart_idx >= d->max_vcpus )
+        return NULL;
+
+    return d->vcpu[hart_idx];
+}
+
+void vaplic_reconfigure_target(const struct vcpu *v)
+{
+    struct domain *d = v->domain;
+    struct vaplic *vaplic = to_vaplic(d);
+    struct vimsic_state *vimsic_state = v->arch.vimsic_state;
+    unsigned int irqn;
+
+    bitmap_for_each ( irqn, d->arch.vintc->hw_irqs, d->arch.vintc->nr_virqs )
+    {
+        struct vaplic_source *src = &vaplic->regs.sources[irqn];
+        unsigned long flags;
+        uint32_t target;
+
+        /* APLIC interrupt sources start from 1, there is no source 0. */
+        if ( !irqn )
+            continue;
+
+        spin_lock_irqsave(&src->lock, flags);
+
+        target = read_atomic(&src->target);
+
+        if ( vaplic_target_decode_vcpu(d, target) == v )
+        {
+            /*
+             * IRQs are already off under src->lock so no need for *_irqsave
+             * here.
+             */
+            read_lock(&vimsic_state->vsfile_lock);
+            aplic_hw_write_reg(offsetof(struct aplic_regs, target[irqn - 1]),
+                               aplic_msi_target_gen(v, target));
+            read_unlock(&vimsic_state->vsfile_lock);
+        }
+
+        spin_unlock_irqrestore(&src->lock, flags);
+    }
+}
+
 static uint32_t generate_auth_mask(const struct domain *currd,
                                    unsigned int word_idx)
 {
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 28/42] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (26 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 27/42] xen/riscv: introduce vaplic_reconfigure_target() Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 29/42] xen/riscv: wake up a descheduled vCPU on a guest external interrupt Oleksii Kurochko
                   ` (13 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Introduce imsic_vsfile_attach() to give a vCPU a working guest
interrupt file.

A guest (VS) interrupt file has to be backed by one of the hardware
guest interrupt files of the pCPU the vCPU runs on, so that pCPU has to
be known first. arch_vcpu_create() is therefore not a suitable place:
the pCPU assigned to a vCPU can still change before the vCPU is first
scheduled, which would mean taking another file and remapping the
guest's IMSIC page to it. Call imsic_vsfile_attach() from
continue_new_vcpu() instead, i.e. when the vCPU is scheduled for the
first time; as that isn't an __init context, neither is
imsic_vsfile_attach().

imsic_vsfile_acquire() assigns the file with vgein_assign(), clears it,
maps it into the guest's G-stage and records it in the vCPU's IMSIC
state. The clearing is needed as the file may still hold the state of
its previous owner, and has to be done by the hart the file belongs to,
as an IMSIC VS-file is reachable only through that hart's hstatus.VGEIN.
A vCPU gets its file on the pCPU it runs on, so imsic_vsfile_local_clear()
is called directly, with IRQs disabled for the time hstatus.VGEIN selects
the file.

A vCPU which can't be given a h/w guest interrupt file crashes its
domain, as s/w guest interrupt files aren't supported yet. If the file
can't be mapped into the guest, the guest external interrupt number
taken for it is released again rather than leaked.

imsic_update_state() records the vCPU's guest interrupt file id together
with the pCPU owning the file. The two are read as a pair, so they are
updated under vsfile_lock as a single unit.

The relevant translation tables at all IOMMUs would also have to be
updated, so that MSIs which devices send to the vCPU's interrupt file at
its guest-physical address reach the h/w guest interrupt file backing
it, but that is skipped for now as there is no IOMMU support for RISC-V.

The guest may program the vAPLIC target register of a h/w source for a
vCPU which hasn't run yet. That vCPU has no h/w guest interrupt file
yet, so there is nothing to point the h/w target register at, and
vaplic_target_write() only stores the value. Hence imsic_vsfile_attach()
calls vaplic_reconfigure_target(), which writes the stored value to the
h/w APLIC, pointing it at the newly acquired file.

The vCPU has never run at that point, so the freshly acquired and zeroed
file is all the interrupt state it has, and hstatus.VGEIN can be pointed
at it right away.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - s/HSTATUS.VGEIN/hstatus.VGEIN/ in a comment.
 - Reword the commit message paragraph on reconfiguring the vAPLIC
   target registers on the first attach.
 - Move ahead of the vCPU migration patches, so that the attach no longer
   has to be fitted into the finished migration code: imsic_vsfile_move()
   and its first_attach argument are gone, and imsic_vsfile_attach() is
   a plain sequence of its own.
 - Take over imsic_vsfile_acquire() and imsic_update_state() from
   "xen/riscv: remap interrupts to new IMSIC VS-file", and the clearing of
   the file, together with the helpers it needs, from "xen/riscv: prepare
   new IMSIC VS-file", which is gone. They come with the changes made to
   them in v4: imsic_eix_check() and imsic_vs_csr_write() used directly
   instead of the switchcase expansion pyramid, and the switch of
   hstatus.VGEIN factored out into imsic_vsfile_select() and
   imsic_vsfile_deselect().
 - Move the IOMMU TODO into imsic_vsfile_acquire(), next to the G-stage
   mapping it is the counterpart of.
 - Introduce imsic_vsfile_set_vgein(), to be shared with
   imsic_migrate_vcpu().
 - Clear the file with a direct call: the file is taken on the pCPU the
   vCPU runs on, so imsic_call_on_cpu() is left to "xen/riscv: remap
   interrupts to new IMSIC VS-file", which first needs another pCPU.
   Give imsic_vsfile_local_clear() a typed pointer, drop its cf_check.
---
Changes in v3:
 - imsic_update_state() is now implemented by "xen/riscv: remap
   interrupts to new IMSIC VS-file".
 - Share the code of imsic_vsfile_attach() and imsic_migrate_vcpu() in
   imsic_vsfile_move(), whose first_attach argument skips the part moving
   state out of the old file.
 - Call vaplic_reconfigure_target() on the first attach as well, so that
   vAPLIC targets the guest wrote for the vCPU before it got its file reach
   the h/w.
 - Replace panic() for a vCPU left without a h/w file by domain_crash():
   it can only happen to a vCPU whose first imsic_vsfile_acquire() failed
   and crashed its domain, and such a vCPU can still be migrated.
 - imsic_vsfile_acquire(), together with the vgein_release() on a
   mapping failure, is now introduced by "xen/riscv: remap interrupts to
   new IMSIC VS-file", without the cpu argument (the file is always
   taken on v->processor).
 - Include asm/imsic.h for imsic_vsfile_attach().
 - Drop imsic_nr_eix() in favour of imsic_cfg.nr_eix.
 - Drop vcpu_set_vgein(): with the code shared in imsic_vsfile_move(),
   hstatus.VGEIN is updated in one place only.
 - Rework the commit message: drop the stale vcpu_aia_init() name and
   the claim that the IMSIC state has no concurrent readers yet.
---
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 parentheses around 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            |   3 +
 xen/arch/riscv/imsic.c             | 221 +++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/imsic.h |   9 ++
 xen/arch/riscv/vaplic.c            |   3 +-
 4 files changed, 235 insertions(+), 1 deletion(-)

diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index 65d582aa8fe0..1b2ab7ab468c 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -13,6 +13,7 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/gpr-num.h>
+#include <asm/imsic.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
@@ -265,6 +266,8 @@ static void continue_new_vcpu(struct vcpu *prev)
 
     vcpu_set_vsxl(current);
 
+    imsic_vsfile_attach(current);
+
     /*
      * return_to_new_vcpu() sets up hstatus.SPV, sstatus.SPP and sepc so
      * that sret enters the guest in VS-mode. A trap taken in HS-mode
diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index a17aae7b6ffa..bc757ef62636 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -25,8 +25,10 @@
 #include <xen/spinlock.h>
 #include <xen/xvmalloc.h>
 
+#include <asm/aia.h>
 #include <asm/imsic.h>
 #include <asm/p2m.h>
+#include <asm/vaplic.h>
 
 #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
 
@@ -77,11 +79,51 @@ do {                            \
     csr_clear(CSR_SIREG, v);    \
 } while (0)
 
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, c);    \
+    csr_write(CSR_VSIREG, v);       \
+} while (0)
+
+/*
+ * On RV64 a 64-bit EIx group is the even-numbered register alone, whereas on
+ * RV32 it is split into the even-numbered (low half) and the following
+ * odd-numbered (high half) register. ireg names the first, even-numbered
+ * register of such a group, among eip0..eip63 or eie0..eie63.
+ */
+static void imsic_eix_check(unsigned int ireg)
+{
+    ASSERT(!(ireg & 1));
+    ASSERT((ireg >= IMSIC_EIP0 && ireg < IMSIC_EIP0 + 64) ||
+           (ireg >= IMSIC_EIE0 && ireg < IMSIC_EIE0 + 64));
+}
+
+/* Write a whole 64-bit EIx group (see imsic_eix_check()). */
+static void imsic_eix_write64(unsigned int ireg, uint64_t val)
+{
+    imsic_eix_check(ireg);
+    imsic_vs_csr_write(ireg, val);
+    if ( IS_ENABLED(CONFIG_RISCV_32) )
+        imsic_vs_csr_write(ireg + 1, val >> 32);
+}
+
 unsigned int vcpu_guest_file_id(const struct vcpu *v)
 {
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
 }
 
+static void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    unsigned long flags;
+    struct vimsic_state *vimsic_state = v->arch.vimsic_state;
+    unsigned int cpu = guest_file_id ? v->processor : CPU_NONE;
+
+    write_lock_irqsave(&vimsic_state->vsfile_lock, flags);
+    vimsic_state->guest_file_id = guest_file_id;
+    vimsic_state->vsfile_cpu = cpu;
+    write_unlock_irqrestore(&vimsic_state->vsfile_lock, flags);
+}
+
 void __init imsic_ids_local_delivery(bool enable)
 {
     if ( enable )
@@ -318,6 +360,8 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
         return -ENOENT;
     }
 
+    imsic_cfg.nr_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1, 64);
+
     /* Compute base address */
     *nr_mmios = 0;
     rc = dt_device_get_address(node, *nr_mmios, &base_addr, NULL);
@@ -435,6 +479,77 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
     return 0;
 }
 
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which work on a guest
+ * interrupt file of the pCPU they run on.
+ */
+struct imsic_vsfile_data {
+    /* Guest interrupt file to work on, i.e. the hstatus.VGEIN selecting it. */
+    unsigned int hgei;
+    /* Number of 64-bit EIx groups to cover, see imsic_cfg.nr_eix. */
+    unsigned int nr_eix;
+};
+
+/* The state of this hart imsic_vsfile_select() changes. */
+struct imsic_vsfile_ctx {
+    unsigned long hstatus;
+    unsigned long vsiselect;
+};
+
+/*
+ * vsiselect/vsireg only reach the guest interrupt file selected by
+ * hstatus.VGEIN, so point VGEIN at file @hgei of this hart for the accesses
+ * which follow. hstatus and vsiselect hold the state of the vCPU running on
+ * this pCPU: save them into @ctx, for imsic_vsfile_deselect() to restore.
+ */
+static void imsic_vsfile_select(unsigned int hgei,
+                                struct imsic_vsfile_ctx *ctx)
+{
+    unsigned long hstatus;
+
+    ctx->vsiselect = csr_read(CSR_VSISELECT);
+    ctx->hstatus = csr_read(CSR_HSTATUS);
+
+    hstatus = ctx->hstatus & ~HSTATUS_VGEIN;
+    hstatus |= MASK_INSR(hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, hstatus);
+}
+
+static void imsic_vsfile_deselect(const struct imsic_vsfile_ctx *ctx)
+{
+    csr_write(CSR_HSTATUS, ctx->hstatus);
+    csr_write(CSR_VSISELECT, ctx->vsiselect);
+}
+
+static void imsic_vsfile_local_clear(const struct imsic_vsfile_data *idata)
+{
+    unsigned int i;
+    struct imsic_vsfile_ctx ctx;
+    unsigned long flags;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;
+
+    /* Nothing on this pCPU is to run with the file selected meanwhile. */
+    local_irq_save(flags);
+
+    imsic_vsfile_select(idata->hgei, &ctx);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write64(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write64(IMSIC_EIE0 + i * 2, 0);
+    }
+
+    imsic_vsfile_deselect(&ctx);
+
+    local_irq_restore(flags);
+}
+
 void cf_check vcpu_imsic_deinit(struct vcpu *v)
 {
     XVFREE(v->arch.vimsic_state);
@@ -736,3 +851,109 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
     return fdt_end_node(fdt);
 }
+
+/*
+ * Take a h/w guest interrupt file on the pCPU @v runs on and make it the
+ * vCPU's one.
+ *
+ * hstatus.VGEIN is deliberately left alone: it must only point at a file
+ * which already holds the vCPU's interrupt state, and the file taken here is
+ * zeroed, which is all the state only a vCPU which hasn't run yet has. Hence
+ * it is up to the caller to set hstatus.VGEIN at the right moment, see
+ * imsic_vsfile_set_vgein().
+ *
+ * Returns the id of the file, or 0, with the domain crashed, if none could be
+ * taken.
+ */
+static unsigned int imsic_vsfile_acquire(struct vcpu *v)
+{
+    unsigned int cpu = v->processor;
+    struct imsic_vsfile_data vsfile_data = { .nr_eix = imsic_cfg.nr_eix };
+    unsigned int vsfile_id;
+    int rc;
+
+    /* @v gets a file of the pCPU it runs on, which clears it below. */
+    ASSERT(cpu == smp_processor_id());
+
+    vsfile_id = vgein_assign(v);
+    if ( !vsfile_id )
+    {
+        /*
+         * vgein_assign() returns 0 when no free h/w guest interrupt file is
+         * available. s/w guest interrupt files aren't supported yet, so such
+         * a vCPU can't be run.
+         */
+        domain_crash(v->domain,
+                     "%pv: no free h/w guest interrupt file on CPU%u\n",
+                     v, cpu);
+        return 0;
+    }
+
+    vsfile_data.hgei = vsfile_id;
+
+    /* The file could still hold the state of its previous owner */
+    imsic_vsfile_local_clear(&vsfile_data);
+
+    rc = imsic_map_guest_file(v, vsfile_id);
+    if ( rc )
+    {
+        vgein_release(v, vsfile_id, cpu);
+
+        /* Can't continue w/o correctly mapped IMSIC interrupt file */
+        domain_crash(v->domain,
+                     "%pv: failed to map h/w guest interrupt file %u: %d\n",
+                     v, vsfile_id, rc);
+        return 0;
+    }
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are sent to this physical one.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
+
+    imsic_update_state(v, vsfile_id);
+
+    return vsfile_id;
+}
+
+/* Make guest interrupt file @hgei the source of @v's VS-level interrupts. */
+static void imsic_vsfile_set_vgein(struct vcpu *v, unsigned int hgei)
+{
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(v);
+
+    regs->hstatus &= ~HSTATUS_VGEIN;
+    regs->hstatus |= MASK_INSR(hgei, HSTATUS_VGEIN);
+}
+
+/*
+ * Give a vCPU which is about to run for the first time its first h/w guest
+ * interrupt file, on the pCPU it runs on.
+ */
+void imsic_vsfile_attach(struct vcpu *v)
+{
+    unsigned int hgei;
+
+    if ( !aia_usable() )
+        return;
+
+    ASSERT(v->arch.vimsic_state->vsfile_cpu == CPU_NONE);
+
+    /* Zero-out, map and start to use the IMSIC VS-file */
+    hgei = imsic_vsfile_acquire(v);
+    if ( !hgei )
+        return;
+
+    /*
+     * A target the guest has programmed for the vCPU so far reached only the
+     * stored copy, as there was no file to point the h/w register at.
+     */
+    vaplic_reconfigure_target(v);
+
+    /*
+     * The vCPU has never run yet, so the just zeroed out file is all the
+     * interrupt state it has and hstatus.VGEIN can be pointed at it at once.
+     */
+    imsic_vsfile_set_vgein(v, hgei);
+}
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index 0f68e8e89496..be45a11cce22 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -55,6 +55,13 @@ struct imsic_config {
     /* Number off interrupt identities */
     unsigned int nr_ids;
 
+    /*
+     * Number of 64-bit EIx groups needed to cover all the interrupt
+     * identities, which are 0 (never valid, but it still occupies a bit) up
+     * to and including nr_ids.
+     */
+    unsigned int nr_eix;
+
     /* MSI */
     const struct imsic_msi *msi;
 
@@ -98,4 +105,6 @@ int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
 int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
 
+void imsic_vsfile_attach(struct vcpu *v);
+
 #endif /* RISCV_IMSIC_H */
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index 42489bf299b9..464a8a142798 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -153,7 +153,8 @@ static void vaplic_target_write(const struct domain *d, unsigned int irqn,
      * The h/w register names the hart and the guest interrupt file MSIs are
      * sent to, and there is none of either until the target vCPU is given a
      * h/w guest interrupt file, so until then only the stored copy is
-     * updated.
+     * updated. imsic_vsfile_attach() writes it to the h/w, through
+     * vaplic_reconfigure_target(), once there is such a file.
      *
      * TODO: once s/w guest interrupt files are supported, a vCPU using one
      * still needs its MSIs, so the h/w register will have to be written for
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 29/42] xen/riscv: wake up a descheduled vCPU on a guest external interrupt
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (27 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 28/42] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 30/42] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration Oleksii Kurochko
                   ` (12 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

While a vCPU is running, MSIs written to its h/w IMSIC guest interrupt
file are delivered straight to VS-mode. Once the vCPU is descheduled
nobody observes that file anymore, so a guest blocked on such an
interrupt would stay blocked until some unrelated event happens to
schedule it again.

Let Xen observe the file in that window: on deschedule set the vCPU's
bit in HGEIE, which turns an interrupt pending in its VS-file into an
HS-level SGEI, and clear the bit again on schedule-in. HGEIP only
reports an interrupt file number, so to find the vCPU to kick, keep a
per-pCPU owners[] array indexed by file number and updated in
vgein_assign()/vgein_release() together with the VGEIN bitmap. The SGEI
handler clears the HGEIE bits it has seen before kicking their owners,
so that the interrupt doesn't keep firing until the vCPU is switched in.

This is enough for a descheduled vCPU never to miss a wake-up. An
interrupt a VS-file signals (pending, enabled and above the threshold,
with eidelivery on) always shows up in HGEIP, but it reaches VS-mode
only while hstatus.VGEIN selects that file, and raises an SGEI only
while the file's HGEIE bit is set. Once the vCPU is descheduled,
hstatus.VGEIN no longer selects its file, so HGEIE is Xen's only way to
notice the interrupt. And as HGEIP reflects the current state of the
file rather than being latched, an interrupt which became pending before
the HGEIE bit got set still raises the SGEI as soon as it is.

SGEIs are enabled per vCPU through v->arch.hie: vcpu_csr_init() sets
IRQ_S_GEXT in it and csrs_ctxt_switch_to() loads it into the CSR.

Both hooks (imsic_ctxt_switch_from/to) touch HGEIE only while the file
belongs to the pCPU they run on. A vCPU can be switched in on a pCPU before
its file has been moved there, and the file's bit in that pCPU's HGEIE
then names a file of that pCPU's own IMSIC, possibly another vCPU's:
clearing it would lose that vCPU's wake-ups. The file's bit in HGEIE of
the pCPU owning it was set when the vCPU left that pCPU and stays set until
the file is moved, so the file remains observed. Neither hook changes the
IMSIC state, so the read side of vsfile_lock is enough.

Nothing frees the VGEIN slot of a vCPU going away, nor drops its
owners[] entry, as there is no vCPU teardown path to hook it into yet.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Explain in the commit message why arming HGEIE is enough for a
   descheduled vCPU never to miss a wake-up.
 - Drop the ASSERT() on bit 0 of the HGEIP/HGEIE mask in
   hgei_interrupt(): the bit is read-only zero, and owners[0] is never
   set anyway.
 - Check in vgein_release() that the file is released by its owner.
 - Reword the comment in imsic_ctxt_switch_from(): HGEIP reports the
   interrupt whether the vCPU runs or not, it's hstatus.VGEIN no longer
   selecting the file and the HGEIE bit which make the difference.
 - Fold in "xen/riscv: add IMSIC vCPU context switch handlers", whose
   handlers had nothing to do on their own:
   imsic_ctxt_switch_{from,to}() and their hook-up now come with their
   first use. Unlike there, imsic_ctxt_switch_from() doesn't record the
   pCPU: imsic_update_state() records it together with the file.
 - Touch HGEIE only on the pCPU owning the vCPU's file, under the read
   side of vsfile_lock.
 - Move right after "xen/riscv: introduce IMSIC h/w interrupt file
   attaching to vcpu", so that a descheduled vCPU can be woken up as soon
   as it has a h/w guest interrupt file. The handling of HGEIE on a vCPU
   migration moves to "xen/riscv: save and clear the old IMSIC VS-file
   on vCPU migration".
 - Add cf_check to the declarations of imsic_ctxt_switch_{from,to}().
 - Explain in csrs_ctxt_switch_{from,to}() why hie isn't saved and why
   vsie is written after it.
---
Changes in v3:
 - Drop the unrelated cpu_callback() change.
 - Read HGEIP and HGEIE in separate statements (MISRA C Rule 13.2).
 - Check that guest interrupt file ID 0 isn't reported once, ahead of
   the loop in hgei_interrupt(), instead of on every iteration.
 - Drop the VGEIN_DEBUG print from hgei_interrupt().
 - Explain in imsic_ctxt_switch_from() why setting the HGEIE bit last
   doesn't lose an interrupt.
 - Initialise hie with BIT(IRQ_S_GEXT, UL) and explain why SGEIs are
   enabled.
 - Arm HGEIE of the new interrupt file on v->processor, as the
   new_vsfile_cpu local variable is gone from imsic_migrate_vcpu().
 - Describe in the commit message why HGEIE is armed for a vCPU which
   is migrated while it isn't running.
 - Correct the commit message: vgein_release() is called on vCPU
   migration.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/aia.c                | 33 +++++++++++++++
 xen/arch/riscv/domain.c             | 19 +++++++--
 xen/arch/riscv/imsic.c              | 66 +++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aia.h    |  2 +
 xen/arch/riscv/include/asm/domain.h |  1 +
 xen/arch/riscv/include/asm/imsic.h  |  3 ++
 xen/arch/riscv/traps.c              |  7 ++-
 xen/arch/riscv/vaplic.c             |  6 +++
 8 files changed, 133 insertions(+), 4 deletions(-)

diff --git a/xen/arch/riscv/aia.c b/xen/arch/riscv/aia.c
index b330da918154..0e9104d7ef4c 100644
--- a/xen/arch/riscv/aia.c
+++ b/xen/arch/riscv/aia.c
@@ -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;
 };
 
@@ -138,7 +145,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 +171,8 @@ 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();
+    ASSERT(vgein->owners[vgein_id] == v);
+    vgein->owners[vgein_id] = NULL;
     spin_unlock_irqrestore(&vgein->lock, flags);
 
 #ifdef VGEIN_DEBUG
@@ -168,3 +180,24 @@ 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);
+    hgei_mask &= 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 )
+    {
+        if ( vgein->owners[guest_file_id] )
+            vcpu_kick(vgein->owners[guest_file_id]);
+    }
+
+    spin_unlock_irqrestore(&vgein->lock, flags);
+}
diff --git a/xen/arch/riscv/domain.c b/xen/arch/riscv/domain.c
index 1b2ab7ab468c..2e130608b34f 100644
--- a/xen/arch/riscv/domain.c
+++ b/xen/arch/riscv/domain.c
@@ -251,6 +251,12 @@ static void vcpu_csr_init(struct vcpu *v)
         v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                             csr_masks.ro_one.hstateen0;
     }
+
+    /*
+     * Enable SGEIs, so that a guest interrupt file marked in HGEIE while
+     * the vCPU is descheduled can raise an interrupt to Xen.
+     */
+    v->arch.hie = BIT(IRQ_S_GEXT, UL);
 }
 
 static void schedule_tail(struct vcpu *prev);
@@ -498,10 +504,12 @@ static bool vcpu_can_access_vsiselect(const struct vcpu *v)
 static void csrs_ctxt_switch_from(struct vcpu *p)
 {
     /*
-     * hedeleg, hideleg, henvcfg, hcounteren, htimedelta and hstateen0 aren't
-     * saved: neither the guest nor Xen changes them other than by
+     * hedeleg, hideleg, hie, henvcfg, hcounteren, htimedelta and hstateen0
+     * aren't saved: neither the guest nor Xen changes them other than by
      * csrs_ctxt_switch_to() writing them from v->arch.*, which is left
-     * unchanged after vcpu_csr_init().
+     * unchanged after vcpu_csr_init(). The exception are the VS-level bits
+     * of hie, which alias bits of vsie: the guest changes them through vsie,
+     * and they are saved and restored as part of it.
      */
 
     p->arch.hvip = csr_read(CSR_HVIP);
@@ -523,6 +531,7 @@ static void csrs_ctxt_switch_to(struct vcpu *n)
     csr_write(CSR_HEDELEG, n->arch.hedeleg);
     csr_write(CSR_HIDELEG, n->arch.hideleg);
     csr_write(CSR_HVIP, n->arch.hvip);
+    csr_write(CSR_HIE, n->arch.hie);
     csr_write64(HENVCFG, n->arch.henvcfg);
     csr_write(CSR_HCOUNTEREN, n->arch.hcounteren);
     csr_write64(HTIMEDELTA, n->arch.htimedelta);
@@ -531,6 +540,10 @@ static void csrs_ctxt_switch_to(struct vcpu *n)
         csr_write(CSR_HSTATEEN0, n->arch.hstateen0);
 
     csr_write(CSR_VSSTATUS, n->arch.vsstatus);
+    /*
+     * Has to come after hideleg and hie: the bits of vsie delegated by
+     * hideleg alias the VS-level bits of hie, which n->arch.hie has clear.
+     */
     csr_write64(VSIE, n->arch.vsie);
     csr_write(CSR_VSTVEC, n->arch.vstvec);
     csr_write(CSR_VSSCRATCH, n->arch.vsscratch);
diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index bc757ef62636..259cf7418f00 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -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>
@@ -387,6 +388,71 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
     return 0;
 }
 
+void cf_check imsic_ctxt_switch_from(struct vcpu *p)
+{
+    struct vimsic_state *imsic_state = p->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 nothing to observe.
+     */
+    if ( !vcpu_guest_file_id(p) )
+        return;
+
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * The file may still belong to another pCPU. Its bit in this pCPU's
+     * HGEIE would name a file of this pCPU, so leave HGEIE alone.
+     */
+    if ( imsic_state->vsfile_cpu != smp_processor_id() )
+    {
+        read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+        return;
+    }
+
+    /*
+     * Start to observe the VS-file from HS-mode. HGEIP reports a
+     * pending-and-enabled interrupt of the VS-file whether the vCPU runs or
+     * not, but once it is switched out hstatus.VGEIN no longer selects the
+     * file, so the interrupt isn't delivered to VS-mode. Setting the file's
+     * bit in HGEIE turns it into an SGEI instead, which lets Xen wake the
+     * vCPU up.
+     *
+     * An MSI is recorded in the VS-file's eip[] array until the guest claims
+     * it, and HGEIP isn't latched but reflects whether the file currently
+     * has a pending-and-enabled interrupt. Hence an interrupt which arrived
+     * before this point raises an SGEI as soon as the bit is set in HGEIE;
+     * nothing is lost in between.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+}
+
+void cf_check imsic_ctxt_switch_to(struct vcpu *n)
+{
+    struct vimsic_state *imsic_state = n->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(n) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     *
+     * The file may still belong to another pCPU. Its bit in this pCPU's
+     * HGEIE would name a file of this pCPU, so leave HGEIE alone.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    if ( imsic_state->vsfile_cpu == smp_processor_id() )
+        csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    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.
diff --git a/xen/arch/riscv/include/asm/aia.h b/xen/arch/riscv/include/asm/aia.h
index 8e4eb2f6b14e..6a05bdd8c236 100644
--- a/xen/arch/riscv/include/asm/aia.h
+++ b/xen/arch/riscv/include/asm/aia.h
@@ -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 */
diff --git a/xen/arch/riscv/include/asm/domain.h b/xen/arch/riscv/include/asm/domain.h
index 005553648a3b..2274ac2ab1e9 100644
--- a/xen/arch/riscv/include/asm/domain.h
+++ b/xen/arch/riscv/include/asm/domain.h
@@ -68,6 +68,7 @@ struct arch_vcpu {
     register_t hstateen0;
     uint64_t   htimedelta;
     register_t hvip;
+    register_t hie;
 
     register_t vsatp;
     register_t vscause;
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index be45a11cce22..090e902e4579 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -103,6 +103,9 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
 int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
+void cf_check imsic_ctxt_switch_from(struct vcpu *p);
+void cf_check imsic_ctxt_switch_to(struct vcpu *n);
+
 int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
 
 void imsic_vsfile_attach(struct vcpu *v);
diff --git a/xen/arch/riscv/traps.c b/xen/arch/riscv/traps.c
index 97e604091458..93996580cccf 100644
--- a/xen/arch/riscv/traps.c
+++ b/xen/arch/riscv/traps.c
@@ -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;
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index 464a8a142798..eb2a263ceecb 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -617,6 +617,12 @@ 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, 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)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 30/42] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (28 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 29/42] xen/riscv: wake up a descheduled vCPU on a guest external interrupt Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 31/42] xen/riscv: introduce imsic_migrate_vcpu() Oleksii Kurochko
                   ` (11 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

When a vCPU is moved to a different guest interrupt file, MSIs that the
APLIC has already sent towards the old file may still be in flight. They
must land before the old file's state is saved and the switch is done,
otherwise they would be lost.

To wait for them, use the APLIC's genmsi register. Writing it makes the
APLIC itself send an MSI (an "extempore" MSI) with a given interrupt
identity to a given hart. genmsi can only target the hart's hypervisor-
level interrupt file, not a guest one, but the AIA spec guarantees that
all MSIs previously sent by the same APLIC to the same hart become
visible at the hart's IMSIC before the extempore MSI does. So once the
extempore MSI has been delivered, no older MSI from this APLIC to the
hart can still be in flight, whichever interrupt file it targets.

genmsi's Busy bit clearing only tells that the APLIC has sent the
extempore MSI, not that it has arrived, so the sequence described in the
AIA spec under "Synchronizing interactions between a hart and the APLIC"
is split in two. aplic_genmsi_barrier() does the APLIC side, while
imsic_aplic_sync() does the hart side: it clears the pending bit of the
reserved identity before the genmsi write and spins on it afterwards,
which is what tells that the extempore MSI, and hence every older MSI
from this APLIC to this hart, has really arrived. Keeping the hart side
in imsic.c leaves the APLIC code free of the IMSIC local CSR accessors.

The last interrupt identity (nr_ids) is reserved for this purpose. As
Xen gives each APLIC source the EIID equal to its number, the sources
from nr_ids on are left unused, so that none of them can satisfy the
barrier early.

Migration doesn't use the barrier at this stage, so imsic_aplic_sync()
is marked __maybe_unused for now.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Order the pending bit clear before the genmsi write with
   RISCV_FENCE(o, o).
 - Replace the sync_id field of struct imsic_config with imsic_sync_id(),
   as it always equals nr_ids.
 - Limit the APLIC sources Xen uses to the identities below the reserved
   ones, as told by the new imsic_nr_free_ids(), and turn the sync_id
   check in imsic_irq_enable() into an ASSERT().
 - Mark imsic_aplic_sync() __maybe_unused rather than referencing it
   from imsic_migrate_vcpu(), which now comes after this patch.
---
Changes in v3:
 - Rename from "xen/riscv: implement APLIC-hart sync barrier for vCPU
   migration", as the barrier waits for the MSIs to reach the hart's IMSIC.
 - Re-word the commit message, describing in it how the sequence is split
   between aplic_genmsi_barrier() and imsic_aplic_sync().
 - Move imsic_aplic_sync(), imsic_local_is_pending() and imsic_csr_read()
   here from "xen/riscv: remap interrupts to new IMSIC VS-file", so that
   both halves of the synchronization sequence are introduced together.
 - s/aplic_hart_field/aplic_hart_index/ following the rename of the helper
   in "xen/riscv: implement virtual APLIC MMIO emulation".
 - Drop masking of sync_id with APLIC_TARGET_EIID, which could silently
   chop off bits; instead add BUILD_BUG_ON() and ASSERT() to make it
   explicit that sync_id always fits into the EIID field.
 - Drop the redundant parentheses around the macro argument in
   imsic_csr_read().
 - Use unsigned int for isel in imsic_local_is_pending() and drop the
   redundant !! as the function returns bool.
 - Rename the unused argument of imsic_aplic_sync() to unused.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/aplic.c             | 51 ++++++++++++++++++++++++++++++
 xen/arch/riscv/imsic.c             | 47 +++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aplic.h |  3 ++
 xen/arch/riscv/include/asm/imsic.h | 23 ++++++++++++++
 4 files changed, 124 insertions(+)

diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
index 825eb60bf444..0be62c9d90f1 100644
--- a/xen/arch/riscv/aplic.c
+++ b/xen/arch/riscv/aplic.c
@@ -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,
@@ -185,6 +187,37 @@ 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;
+
+    /*
+     * imsic_sync_id() is nr_ids, which imsic_parse_node() limits to
+     * IMSIC_MAX_ID, so it always fits into the EIID field.
+     */
+    BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
+    ASSERT(imsic_sync_id(imsic) <= IMSIC_MAX_ID);
+
+    val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
+          imsic_sync_id(imsic);
+
+    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;
@@ -215,6 +248,7 @@ static int __init cf_check aplic_init(void)
     uint64_t size, paddr;
     const struct dt_device_node *imsic_node;
     const struct dt_device_node *node = aplic_info.node;
+    const struct imsic_config *imsic;
     int rc;
 
     /* Check for associated imsic node */
@@ -239,6 +273,23 @@ static int __init cf_check aplic_init(void)
         panic("%s: failed to get number of interrupt sources\n",
               node->full_name);
 
+    /*
+     * Xen drives the APLIC in MSI delivery mode only, mapping each source 1:1
+     * to an interrupt identity of its own IMSIC interrupt file: source i is
+     * given EIID i (see aplic_set_irq_affinity()). Hence only the sources
+     * numbered up to imsic_nr_free_ids() can be used: the identities above
+     * are either reserved or not implemented.
+     */
+    imsic = imsic_get_config();
+    if ( aplic_info.num_irqs > imsic_nr_free_ids(imsic) )
+    {
+        printk(XENLOG_WARNING
+               "%s: only %u of %u interrupt sources usable with %u IMSIC identities\n",
+               node->full_name, imsic_nr_free_ids(imsic), aplic_info.num_irqs,
+               imsic->nr_ids);
+        aplic_info.num_irqs = imsic_nr_free_ids(imsic);
+    }
+
     guest_aplic_num_sources = min(GUEST_APLIC_MAX_SOURCES, aplic_info.num_irqs);
 
     if ( aplic_info.num_irqs > ARRAY_SIZE(aplic.regs->sourcecfg) )
diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index 259cf7418f00..3d947226f371 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -27,6 +27,7 @@
 #include <xen/xvmalloc.h>
 
 #include <asm/aia.h>
+#include <asm/aplic.h>
 #include <asm/imsic.h>
 #include <asm/p2m.h>
 #include <asm/vaplic.h>
@@ -62,6 +63,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); \
@@ -178,6 +185,8 @@ void imsic_irq_enable(unsigned int irq)
      * spin_lock_irqsave() should be used instead of spin_lock().
      */
     ASSERT(!local_irq_is_enabled());
+    /* aplic_init() keeps the APLIC sources off the reserved identities. */
+    ASSERT(irq && irq <= imsic_nr_free_ids(&imsic_cfg));
 
     spin_lock(&imsic_cfg.lock);
     /*
@@ -217,6 +226,15 @@ void imsic_irq_disable(unsigned int irq)
     spin_unlock(&imsic_cfg.lock);
 }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned int 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)
 {
@@ -587,6 +605,35 @@ static void imsic_vsfile_deselect(const struct imsic_vsfile_ctx *ctx)
     csr_write(CSR_VSISELECT, ctx->vsiselect);
 }
 
+/*
+ * 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 __maybe_unused imsic_aplic_sync(void *unused)
+{
+    imsic_local_eix_update(imsic_sync_id(&imsic_cfg), 1, true, false);
+
+    /*
+     * For FENCE, a CSR write counts as device output, which neither
+     * spin_lock() nor writel() in aplic_genmsi_barrier() orders before the
+     * write to genmsi: should the IMSIC see the clear after the extempore
+     * MSI, the loop below would never end.
+     */
+    RISCV_FENCE(o, o);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_sync_id(&imsic_cfg)) )
+        cpu_relax();
+}
+
 static void imsic_vsfile_local_clear(const struct imsic_vsfile_data *idata)
 {
     unsigned int i;
diff --git a/xen/arch/riscv/include/asm/aplic.h b/xen/arch/riscv/include/asm/aplic.h
index b2f1d140f6f8..37584039107b 100644
--- a/xen/arch/riscv/include/asm/aplic.h
+++ b/xen/arch/riscv/include/asm/aplic.h
@@ -89,6 +89,7 @@
 #define APLIC_SETIPNUM_BE               0x2004
 
 #define APLIC_GENMSI                    0x3000
+#define APLIC_GENMSI_BUSY               BIT(12, U)
 
 #define APLIC_TARGET_BASE               0x3004
 #define APLIC_TARGET_LAST               0x3ffc
@@ -173,4 +174,6 @@ 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_genmsi_barrier(void);
+
 #endif /* RISCV_APLIC_H */
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index 090e902e4579..1f3ccfbccd1e 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -69,6 +69,29 @@ struct imsic_config {
     spinlock_t lock;
 };
 
+/*
+ * The identities of Xen's own interrupt file are allocated statically:
+ *  - the reserved ones are taken from the top down; so far that's only the
+ *    last one, nr_ids, for APLIC-to-hart synchronization;
+ *  - 1 .. imsic_nr_free_ids(), i.e. all those below the reserved ones, are
+ *    left for the APLIC sources, as Xen gives source N the EIID N
+ *    (aplic_init() drops the sources which don't fit).
+ * A new reserved identity has to be taken below the lowest one reserved so
+ * far, with imsic_nr_free_ids() lowered accordingly.
+ */
+
+/* Interrupt identity reserved for APLIC-to-hart synchronization. */
+static inline unsigned int imsic_sync_id(const struct imsic_config *cfg)
+{
+    return cfg->nr_ids;
+}
+
+/* Interrupt identities 1 .. imsic_nr_free_ids() aren't reserved. */
+static inline unsigned int imsic_nr_free_ids(const struct imsic_config *cfg)
+{
+    return imsic_sync_id(cfg) - 1;
+}
+
 struct vimsic_state {
     /* IMSIC VS-file */
     rwlock_t vsfile_lock;
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 31/42] xen/riscv: introduce imsic_migrate_vcpu()
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (29 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 30/42] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 32/42] xen/riscv: remap interrupts to new IMSIC VS-file Oleksii Kurochko
                   ` (10 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Moving a vCPU's guest interrupt file to the pCPU the vCPU has been
moved to follows "Migrating a virtual hart to a different guest
interrupt file" in the AIA spec: take a new file, retarget the
interrupt producers to it, synchronize with them, move the state of the
old file into the new one and point hstatus.VGEIN at it. That is a
sizeable sequence, so it is implemented step by step, and
imsic_migrate_vcpu(), introduced here as its entry point, is
deliberately a stub for now: the move itself is left as
BUG_ON("unimplemented").

The function has to be called by the vCPU itself, right before it
enters the guest: as long as a vCPU runs on a pCPU, it can neither run
on nor be moved to any other one, so its file can't be in use elsewhere
while it is moved. An ASSERT() checks that the vCPU is the current one.

What these requirements already allow is to tell whether there is
anything to move at all: the file has to be moved only once the
scheduler has moved the vCPU, not on every entry to the guest. Return
early unless the vCPU's h/w interrupt file belongs to a pCPU other than
the one the vCPU runs on, as told by the new imsic_vsfile_needs_move().
A vCPU without a h/w file has nothing to move, as s/w guest interrupt
files aren't supported yet: such a vCPU is one which couldn't be given
a h/w file, e.g. as imsic_vsfile_attach() failed and crashed its
domain. vsfile_cpu is read without the lock: once a vCPU runs, nothing
but the vCPU itself changes it.

Nothing calls imsic_migrate_vcpu() yet.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - New patch, replacing "xen/riscv: handle the case when no vCPU
   migration is needed": the vCPU's interrupt file is now moved by the
   vCPU itself on its way back to the guest rather than from
   arch_move_irqs(), so what has to be told first is whether the file
   belongs to another pCPU, rather than whether the vCPU has run yet.
   Why the file isn't moved from arch_move_irqs() is explained in more
   detail in "xen/riscv: introduce arch_move_irqs()".
---
---
 xen/arch/riscv/imsic.c             | 37 ++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/imsic.h |  2 ++
 2 files changed, 39 insertions(+)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index 3d947226f371..48214ab0d363 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -1070,3 +1070,40 @@ void imsic_vsfile_attach(struct vcpu *v)
      */
     imsic_vsfile_set_vgein(v, hgei);
 }
+
+/*
+ * Whether the h/w guest interrupt file of @v, the vCPU running on this pCPU,
+ * belongs to another pCPU, i.e. has to be moved here by imsic_migrate_vcpu().
+ * A vCPU without a h/w file has none to move.
+ *
+ * No lock is needed: vsfile_cpu of a running vCPU is changed only by the vCPU
+ * itself, when it acquires a file in imsic_vsfile_attach().
+ *
+ * TODO: a s/w file, once supported, has to be moved too.
+ */
+static bool imsic_vsfile_needs_move(const struct vcpu *v)
+{
+    unsigned int cpu = ACCESS_ONCE(v->arch.vimsic_state->vsfile_cpu);
+
+    ASSERT(v == current);
+
+    return cpu != CPU_NONE && cpu != smp_processor_id();
+}
+
+/*
+ * Make the h/w guest interrupt file of @v belong to the pCPU @v runs on.
+ *
+ * Has to be called by @v itself (see the ASSERT() below), right before it
+ * enters the guest: as long as @v runs on this pCPU, it can neither run on
+ * nor be moved to another one, so its file can't be in use elsewhere while
+ * it is moved.
+ */
+void imsic_migrate_vcpu(struct vcpu *v)
+{
+    ASSERT(v == current);
+
+    if ( !imsic_vsfile_needs_move(v) )
+        return;
+
+    BUG_ON("unimplemented");
+}
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index 1f3ccfbccd1e..f7e537be29b4 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -133,4 +133,6 @@ int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
 
 void imsic_vsfile_attach(struct vcpu *v);
 
+void imsic_migrate_vcpu(struct vcpu *v);
+
 #endif /* RISCV_IMSIC_H */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 32/42] xen/riscv: remap interrupts to new IMSIC VS-file
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (30 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 31/42] xen/riscv: introduce imsic_migrate_vcpu() Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 33/42] xen/riscv: save and clear the old IMSIC VS-file on vCPU migration Oleksii Kurochko
                   ` (9 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Implement the first steps of migrating a vCPU to a different guest
interrupt file: take a new one on the vCPU's new pCPU with
imsic_vsfile_acquire(), which brings it to a clean state, maps it into
the guest's G-stage in place of the old one and records it in the
vCPU's IMSIC state. Then, 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.

Synchronize with the APLIC to ensure that no straggler MSIs will arrive
at the old interrupt file by running imsic_aplic_sync() on the pCPU
which owns that file, through the new imsic_call_on_cpu(): unlike the
new file, the old one belongs to another pCPU, which an IPI has to be
sent to.

The move maps the new file into the guest's G-stage, which takes the
p2m lock, and sends IPIs to the pCPU owning the old file, both of which
need IRQs enabled, while imsic_migrate_vcpu() is called with them
disabled. So do it in the new imsic_vsfile_move() and have
imsic_migrate_vcpu() enable IRQs around it, only when there is
something to move, which takes them to be disabled on entry, as an
ASSERT() checks.

Only a h/w file of another pCPU is moved: imsic_vsfile_needs_move()
keeps imsic_vsfile_move() from being reached for any other, as an
ASSERT() there checks.

Keep the BUG_ON("unimplemented") placeholder at the end of
imsic_vsfile_move() to guard against silent incorrect behaviour or
unexpected panics in guest VMs until the move is fully implemented.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Fold in "xen/riscv: prepare new IMSIC VS-file": with
   imsic_vsfile_acquire() already introduced by "xen/riscv: introduce
   IMSIC h/w interrupt file attaching to vcpu", taking and zeroing out
   the new file is a single call.
 - Move imsic_vsfile_acquire(), imsic_update_state(), the stubs of
   imsic_map_guest_file() and vgein_release() and the IOMMU TODO out of
   this patch, as they come with the attach now.
 - Move the file in the new imsic_vsfile_move(), which
   imsic_migrate_vcpu() runs with IRQs enabled, as imsic_migrate_vcpu()
   is now called with them disabled, by the vCPU itself on its way back
   to the guest.
 - Introduce imsic_call_on_cpu() here rather than in "xen/riscv:
   introduce IMSIC h/w interrupt file attaching to vcpu", as the old
   file is the first one to belong to another pCPU.
 - Don't panic() for a vCPU without a h/w file:
   imsic_vsfile_needs_move() keeps such a vCPU from being moved at all,
   so just ASSERT() it.
 - Update the commit message accordingly.
---
Changes in v3:
 - Update the commit message.
 - Move imsic_aplic_sync() and imsic_local_is_pending() to "xen/riscv:
   implement APLIC-IMSIC-hart sync barrier for vCPU migration" and only
   call the helper here.
 - compare old_vsfile_cpu against CPU_NONE instead of NR_CPUS.
 - Call vaplic_reconfigure_target() instead of aplic_reconfigure_target().
 - Update the comment at the start of the migration: at that point the new
   IMSIC VS-file is only being prepared, the interrupt producers are moved
   to it later.
 - Factor taking a h/w guest interrupt file (assign, zero out, map into
   G-stage and record in the per-vCPU IMSIC state) out of
   imsic_migrate_vcpu() into imsic_vsfile_acquire(), introduced here
   instead of in "xen/riscv: introduce IMSIC h/w interrupt file attaching
   to vcpu".
 - Crash the domain instead of BUG_ON()ing when no h/w guest interrupt
   file is free, and report which file could not be mapped.
 - Introduce the vgein_release() stub here, together with its first
   user: release the h/w guest interrupt file taken by
   imsic_vsfile_acquire() if mapping it into the guest fails. Drop the
   stray "\n" from its BUG_ON().
 - Clarify the comment ahead of imsic_vsfile_acquire() on why setting
   hstatus.VGEIN is left to the caller.
 - Implement imsic_update_state() here instead of leaving it a stub until
   "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu": all
   it needs, vsfile_lock and CPU_NONE, is available already. The s/w
   IMSIC VS-file is recorded with vsfile_cpu == CPU_NONE rather than
   NR_CPUS.
 - Make imsic_update_state() static and drop its declaration from
   asm/imsic.h: imsic_vsfile_acquire() is its only user.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/imsic.c | 103 +++++++++++++++++++++++++++++++++++++++--
 1 file changed, 99 insertions(+), 4 deletions(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index 48214ab0d363..690a83fd6866 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -565,7 +565,9 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
 
 /*
  * Arguments of the imsic_vsfile_local_*() helpers, which work on a guest
- * interrupt file of the pCPU they run on.
+ * interrupt file of the pCPU they run on. Those run on another pCPU go
+ * through imsic_call_on_cpu(), which passes a single pointer, hence the
+ * arguments are bundled.
  */
 struct imsic_vsfile_data {
     /* Guest interrupt file to work on, i.e. the hstatus.VGEIN selecting it. */
@@ -605,6 +607,33 @@ static void imsic_vsfile_deselect(const struct imsic_vsfile_ctx *ctx)
     csr_write(CSR_VSISELECT, ctx->vsiselect);
 }
 
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              struct imsic_vsfile_data *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
+    }
+    else
+        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.
@@ -616,7 +645,7 @@ static void imsic_vsfile_deselect(const struct imsic_vsfile_ctx *ctx)
  * any other hart, it has to be executed by the pCPU owning the interrupt file
  * the MSIs were being sent to.
  */
-static void __maybe_unused imsic_aplic_sync(void *unused)
+static void cf_check imsic_aplic_sync(void *unused)
 {
     imsic_local_eix_update(imsic_sync_id(&imsic_cfg), 1, true, false);
 
@@ -1077,7 +1106,8 @@ void imsic_vsfile_attach(struct vcpu *v)
  * A vCPU without a h/w file has none to move.
  *
  * No lock is needed: vsfile_cpu of a running vCPU is changed only by the vCPU
- * itself, when it acquires a file in imsic_vsfile_attach().
+ * itself, when it acquires a file in imsic_vsfile_attach() or
+ * imsic_migrate_vcpu().
  *
  * TODO: a s/w file, once supported, has to be moved too.
  */
@@ -1090,6 +1120,63 @@ static bool imsic_vsfile_needs_move(const struct vcpu *v)
     return cpu != CPU_NONE && cpu != smp_processor_id();
 }
 
+/*
+ * Move the h/w guest interrupt file of @v to the pCPU @v runs on, following
+ * "Migrating a virtual hart to a different guest interrupt file" in the AIA
+ * spec. Only called by imsic_migrate_vcpu(), see the requirements there.
+ */
+static void imsic_vsfile_move(struct vcpu *v)
+{
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = imsic_cfg.nr_eix,
+    };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
+
+    ASSERT(local_irq_is_enabled());
+    ASSERT(imsic_vsfile_needs_move(v));
+
+    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);
+
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file. Allocate and clear the new one before redirecting anything
+     * to it.
+     */
+
+    /* Zero-out, map and start to use the new IMSIC VS-file */
+    vsfile_data.hgei = imsic_vsfile_acquire(v);
+    if ( !vsfile_data.hgei )
+        return;
+
+    /*
+     * 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.
+     */
+    vaplic_reconfigure_target(v);
+
+    /*
+     * 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");
+}
+
 /*
  * Make the h/w guest interrupt file of @v belong to the pCPU @v runs on.
  *
@@ -1101,9 +1188,17 @@ static bool imsic_vsfile_needs_move(const struct vcpu *v)
 void imsic_migrate_vcpu(struct vcpu *v)
 {
     ASSERT(v == current);
+    ASSERT(!local_irq_is_enabled());
 
     if ( !imsic_vsfile_needs_move(v) )
         return;
 
-    BUG_ON("unimplemented");
+    /*
+     * The move maps the new file into the guest's G-stage, which takes the
+     * p2m lock, and sends IPIs to the pCPU owning the old file: both need
+     * IRQs enabled.
+     */
+    local_irq_enable();
+    imsic_vsfile_move(v);
+    local_irq_disable();
 }
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 33/42] xen/riscv: save and clear the old IMSIC VS-file on vCPU migration
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (31 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 32/42] xen/riscv: remap interrupts to new IMSIC VS-file Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 34/42] xen/riscv: restore register state in the new IMSIC VS-file Oleksii Kurochko
                   ` (8 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

When a vCPU migrates to another pCPU, its guest interrupt file has to
move as well: the eidelivery, eithreshold and eip/eie state of the old
IMSIC VS-file has to be carried over to the newly acquired one.

Once all interrupt producers have been retargeted to the new VS-file,
so that nothing can reach the old one anymore, read the state of the
old one and clear it at the same time. This has to be done on the pCPU
owning the old VS-file, as a guest interrupt file is only accessible
through vsiselect/vsireg with hstatus.VGEIN selecting it. After that
the old VS-file is no longer in use and its guest external interrupt
number can be released.

The synchronization with the APLIC has to be done by that very pCPU
too, right before, so do both from the new imsic_vsfile_local_drain(),
in a single IPI: the move is done by the vCPU on its way back to the
guest, which each IPI delays.

imsic_ctxt_switch_from() armed HGEIE for the old VS-file when the vCPU
was switched out, but once the file is left there is nothing for Xen to
observe in it. Hence clear its bit with the new
imsic_local_hgeie_clear(), from imsic_vsfile_local_read_clear(), which
already runs on the pCPU owning the file.

The state is saved into struct imsic_mrif. Its eix[] array follows the
layout of a memory-resident interrupt file (MRIF) as defined by the AIA
specification: pairs of 64-bit interrupt-pending and interrupt-enable
doublewords, each pair covering 64 interrupt identities. eithreshold and
eidelivery aren't part of an MRIF and are stored next to it as they
belong to the interrupt file state too. Using the MRIF layout allows the
same structure to hold the interrupt file of a vCPU which doesn't own a
hardware guest interrupt file, which is how the AIA specification
describes MRIFs being used by a hypervisor.

Here the structure is only a temporary copy of a guest interrupt file:
it is filled and consumed by Xen alone and its address is never given
to an IOMMU, so no MSI is ever recorded into it. Hence plain
(non-atomic) accesses are sufficient and it can live on the stack.

The saved state still has to be restored into the new VS-file, so keep
the BUG_ON("unimplemented") placeholder at the end of
imsic_vsfile_move() to avoid silently losing the guest's interrupt
state.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Drop imsic_switchcase_ret() and imsic_eix_swap(), following the
   removal of the switchcase expansion pyramid: imsic_eix_swap64() uses
   imsic_vs_csr_swap() directly.
 - Name imsic_eix_check() in the comment above imsic_eix_swap64() rather
   than saying "above".
 - Use imsic_vsfile_select() and imsic_vsfile_deselect().
 - Say "hardware guest interrupt file" in the commit message, to make
   clear which vCPUs an MRIF can serve.
 - Clear the HGEIE bit of the old interrupt file in
   imsic_vsfile_local_read_clear(), through the new
   imsic_local_hgeie_clear(), moved here from "xen/riscv: wake up a
   descheduled vCPU on a guest external interrupt".
 - Save and clear the old file in imsic_vsfile_move(), which now does
   the move for imsic_migrate_vcpu().
 - Synchronize with the APLIC and save and clear the old file in a
   single IPI, from the new imsic_vsfile_local_drain(), which replaces
   imsic_vsfile_read_clear(). imsic_vsfile_local_read_clear(), no longer
   an IPI callback itself, takes a typed pointer and drops cf_check.
---
Changes in v3:
 - Reword the commit message: explain why the MRIF layout is used and
   why the copy isn't an MSI target, drop references to later patches.
 - Compare vsfile_cpu against CPU_NONE instead of NR_CPUS.
 - Introduce imsic_switchcase_ret() here, together with its first user,
   drop its unused variadic form and leave the trailing semicolon to
   its users.
 - Introduce the mrif member of struct imsic_vsfile_data here, together
   with its first user.
 - Initialise vsfile_data.mrif in imsic_migrate_vcpu() with a compound
   literal instead of adding a separate tmrif local variable, so the MRIF
   the old interrupt file is dumped into is visibly the one later
   restored from.
 - Drop the redundant parentheses around the arguments of
   imsic_vs_csr_swap() and its unnecessary local variable.
 - Use plain 64 instead of BITS_PER_TYPE(uint64_t) for the number of
   interrupt identities covered by an EIx group, and explain in the
   comment ahead of IMSIC_MAX_EIX where it comes from (the MRIF layout
   from the AIA spec).
 - Keep each EIx group of the MRIF as a uint64_t and introduce
   imsic_eix_swap64() to swap a whole group, which lets the
   #ifdef CONFIG_RISCV_32 in imsic_vsfile_local_read_clear() go.
 - Add missing break after ASSERT_UNREACHABLE() in the default case of
   imsic_eix_swap().
 - Use MASK_INSR() to set HSTATUS.VGEIN in
   imsic_vsfile_local_read_clear().
 - Explain in imsic_vsfile_local_read_clear() why hstatus and vsiselect
   are saved and restored.
 - Reword the comment on why no atomic accessors are needed to store
   the values into the MRIF.
 - Take the number of EIx groups from vsfile_data.nr_eix, as the
   nr_hw_eix local variable is gone from imsic_migrate_vcpu().
 - Move the vgein_release() stub to "xen/riscv: remap interrupts to new
   IMSIC VS-file", where it gains its first user.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/imsic.c | 118 +++++++++++++++++++++++++++++++++++++----
 1 file changed, 107 insertions(+), 11 deletions(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index 690a83fd6866..c705b287c7ff 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -58,6 +58,28 @@ static unsigned int __ro_after_init guest_num_msis;
  */
 #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ *
+ * Each EIx group covers 64 identities, matching the memory-resident interrupt
+ * file (MRIF) layout from the AIA spec, where pending and enable bits are
+ * stored as pairs of 64-bit doublewords.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, 64)
+
+struct imsic_mrif_eix {
+    uint64_t eip;
+    uint64_t eie;
+};
+
+struct imsic_mrif {
+    struct imsic_mrif_eix eix[IMSIC_MAX_EIX];
+    unsigned long eithreshold;
+    unsigned long eidelivery;
+};
+
 #define IMSIC_DISABLE_EIDELIVERY    0
 #define IMSIC_ENABLE_EIDELIVERY     1
 #define IMSIC_DISABLE_EITHRESHOLD   1
@@ -87,6 +109,12 @@ do {                            \
     csr_clear(CSR_SIREG, v);    \
 } while (0)
 
+#define imsic_vs_csr_swap(c, v)     \
+({                                  \
+    csr_write(CSR_VSISELECT, c);    \
+    csr_swap(CSR_VSIREG, v);        \
+})
+
 #define imsic_vs_csr_write(c, v)    \
 do {                                \
     csr_write(CSR_VSISELECT, c);    \
@@ -115,6 +143,19 @@ static void imsic_eix_write64(unsigned int ireg, uint64_t val)
         imsic_vs_csr_write(ireg + 1, val >> 32);
 }
 
+/* Swap a whole 64-bit EIx group (see imsic_eix_check()). */
+static uint64_t imsic_eix_swap64(unsigned int ireg, uint64_t val)
+{
+    uint64_t old;
+
+    imsic_eix_check(ireg);
+    old = imsic_vs_csr_swap(ireg, val);
+    if ( IS_ENABLED(CONFIG_RISCV_32) )
+        old |= (uint64_t)imsic_vs_csr_swap(ireg + 1, val >> 32) << 32;
+
+    return old;
+}
+
 unsigned int vcpu_guest_file_id(const struct vcpu *v)
 {
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -574,6 +615,8 @@ struct imsic_vsfile_data {
     unsigned int hgei;
     /* Number of 64-bit EIx groups to cover, see imsic_cfg.nr_eix. */
     unsigned int nr_eix;
+    /* Where the interrupt file state is saved to or restored from. */
+    struct imsic_mrif *mrif;
 };
 
 /* The state of this hart imsic_vsfile_select() changes. */
@@ -692,6 +735,56 @@ static void imsic_vsfile_local_clear(const struct imsic_vsfile_data *idata)
     local_irq_restore(flags);
 }
 
+/*
+ * Stop observing an interrupt file which a vCPU leaves when it moves to
+ * another pCPU, by clearing the bit imsic_ctxt_switch_from() set.
+ */
+static void imsic_local_hgeie_clear(unsigned int hgei)
+{
+    csr_clear(CSR_HGEIE, BIT(hgei, UL));
+}
+
+static void
+imsic_vsfile_local_read_clear(const struct imsic_vsfile_data *idata)
+{
+    unsigned int i;
+    struct imsic_mrif *mrif = idata->mrif;
+    struct imsic_vsfile_ctx ctx;
+
+    imsic_local_hgeie_clear(idata->hgei);
+
+    imsic_vsfile_select(idata->hgei, &ctx);
+
+    /*
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_move() always passes it a pointer to a temporary MRIF
+     * on the stack.
+     */
+
+    mrif->eidelivery = imsic_vs_csr_swap(IMSIC_EIDELIVERY, 0);
+    mrif->eithreshold = imsic_vs_csr_swap(IMSIC_EITHRESHOLD, 0);
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        mrif->eix[i].eip = imsic_eix_swap64(IMSIC_EIP0 + i * 2, 0);
+        mrif->eix[i].eie = imsic_eix_swap64(IMSIC_EIE0 + i * 2, 0);
+    }
+
+    imsic_vsfile_deselect(&ctx);
+}
+
+/*
+ * Make sure that the MSIs already sent to the interrupt file @data names have
+ * arrived there, then save and clear the file. Both have to be done by the
+ * pCPU owning the file, and doing them together takes a single IPI.
+ */
+static void cf_check imsic_vsfile_local_drain(void *data)
+{
+    const struct imsic_vsfile_data *idata = data;
+
+    imsic_aplic_sync(data);
+    imsic_vsfile_local_read_clear(idata);
+}
+
 void cf_check vcpu_imsic_deinit(struct vcpu *v)
 {
     XVFREE(v->arch.vimsic_state);
@@ -1129,6 +1222,7 @@ static void imsic_vsfile_move(struct vcpu *v)
 {
     struct imsic_vsfile_data vsfile_data = {
         .nr_eix = imsic_cfg.nr_eix,
+        .mrif = &(struct imsic_mrif){ },
     };
     struct vimsic_state *imsic_state = v->arch.vimsic_state;
     unsigned long flags;
@@ -1161,18 +1255,20 @@ static void imsic_vsfile_move(struct vcpu *v)
     vaplic_reconfigure_target(v);
 
     /*
-     * 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.
+     * Synchronize with the APLIC, so that no straggler MSI reaches the old
+     * interrupt file anymore, then read and clear the old file's register
+     * state into the MRIF. Both have to be done by the pCPU owning the old
+     * file.
      */
+    imsic_call_on_cpu(old_vsfile_cpu, imsic_vsfile_local_drain,
+                      &(struct imsic_vsfile_data){
+                          .hgei = old_vsfile_id,
+                          .nr_eix = vsfile_data.nr_eix,
+                          .mrif = vsfile_data.mrif,
+                      });
+
+    /* Free-up old IMSIC VS-file */
+    vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
     BUG_ON("unimplemented");
 }
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 34/42] xen/riscv: restore register state in the new IMSIC VS-file
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (32 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 33/42] xen/riscv: save and clear the old IMSIC VS-file on vCPU migration Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 35/42] xen/riscv: move a vCPU's guest interrupt file on its way to the guest Oleksii Kurochko
                   ` (7 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

Complete the migration of a vCPU's guest interrupt file: move the state
saved from the old IMSIC VS-file into the new one and make the vCPU use
the new VS-file.

The interrupt producers have already been retargeted to the new
VS-file, so MSIs may land in it before the saved state is restored.
Hence the saved eip/eie bits are ORed into the new VS-file rather than
written to it, so that such MSIs aren't lost. eithreshold and
eidelivery are restored last: the new VS-file was cleared when it was
acquired, so it doesn't deliver interrupts until its pending and enable
bits are complete.

As with reading the old VS-file, this has to be done on the pCPU owning
the new VS-file, with hstatus.VGEIN temporarily selecting it. That is
v->processor, the pCPU the vCPU runs on.

Finally, point hstatus.VGEIN in the registers restored when the vCPU
enters the guest at the new VS-file, so that it becomes the source of
the vCPU's VS-level external interrupts and the file the guest accesses
through its siselect/sireg. With that the migration is complete, so
drop the BUG_ON("unimplemented") placeholder from imsic_vsfile_move().

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Drop imsic_eix_set(), following the removal of the switchcase
   expansion pyramid: imsic_eix_set64() uses imsic_vs_csr_set() directly.
 - Name imsic_eix_check() in the comment above imsic_eix_set64() rather
   than saying "above".
 - Use imsic_vsfile_select() and imsic_vsfile_deselect().
 - Make mrif in imsic_vsfile_local_update() a pointer to const.
 - Don't arm HGEIE for the new interrupt file: the file is now moved by
   the vCPU itself, which runs meanwhile, and imsic_ctxt_switch_from()
   arms it once the vCPU is switched out.
 - Restore the state in imsic_vsfile_move(), which now does the move for
   imsic_migrate_vcpu().
 - Restore the new file with a direct call rather than through
   imsic_call_on_cpu(), as it belongs to the pCPU the vCPU runs on. Give
   imsic_vsfile_local_update() a typed pointer and drop its cf_check.
 - Update the commit message accordingly.
 - Point hstatus.VGEIN at the new file with imsic_vsfile_set_vgein(),
   which replaces the open-coded update and its comment.
---
Changes in v3:
 - Reword the commit message: explain why the saved state is ORed into
   the new VS-file and why eithreshold and eidelivery are restored last,
   drop the note about explanatory comments.
 - Leave the trailing semicolon of the switchcase macros to their users.
 - Drop the redundant parentheses around the arguments of
   imsic_vs_csr_set() as they are passed to csr_*() as whole
   expressions.
 - Add missing break after ASSERT_UNREACHABLE() in the default case of
   imsic_eix_set().
 - Restore the state on v->processor and take the id of the new IMSIC
   VS-file from vsfile_data.hgei, as imsic_migrate_vcpu() no longer has
   separate local variables for the new VS-file.
 - Explain why hstatus and vsiselect are saved and restored with a short
   comment in imsic_vsfile_local_update().
 - Introduce imsic_eix_set64() to set bits of a whole 64-bit EIx group,
   which lets the #ifdef CONFIG_RISCV_32 in imsic_vsfile_local_update()
   go.
 - Move the MASK_INSR() conversion and the comment rewording in
   imsic_vsfile_local_read_clear() to the patch introducing that
   function.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/imsic.c | 56 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 55 insertions(+), 1 deletion(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index c705b287c7ff..adacac5c7268 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -115,6 +115,12 @@ do {                            \
     csr_swap(CSR_VSIREG, v);        \
 })
 
+#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);    \
@@ -156,6 +162,15 @@ static uint64_t imsic_eix_swap64(unsigned int ireg, uint64_t val)
     return old;
 }
 
+/* Set bits of a whole 64-bit EIx group (see imsic_eix_check()). */
+static void imsic_eix_set64(unsigned int ireg, uint64_t val)
+{
+    imsic_eix_check(ireg);
+    imsic_vs_csr_set(ireg, val);
+    if ( IS_ENABLED(CONFIG_RISCV_32) )
+        imsic_vs_csr_set(ireg + 1, val >> 32);
+}
+
 unsigned int vcpu_guest_file_id(const struct vcpu *v)
 {
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -1087,6 +1102,42 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
     return fdt_end_node(fdt);
 }
 
+static void imsic_vsfile_local_update(const struct imsic_vsfile_data *idata)
+{
+    unsigned int i;
+    const struct imsic_mrif *mrif = idata->mrif;
+    struct imsic_vsfile_ctx ctx;
+    unsigned long flags;
+
+    /* 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.
+     */
+
+    /* Nothing on this pCPU is to run with the file selected meanwhile. */
+    local_irq_save(flags);
+
+    imsic_vsfile_select(idata->hgei, &ctx);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_set64(IMSIC_EIP0 + i * 2, mrif->eix[i].eip);
+        imsic_eix_set64(IMSIC_EIE0 + i * 2, mrif->eix[i].eie);
+    }
+
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, mrif->eithreshold);
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, mrif->eidelivery);
+
+    imsic_vsfile_deselect(&ctx);
+
+    local_irq_restore(flags);
+}
+
 /*
  * Take a h/w guest interrupt file on the pCPU @v runs on and make it the
  * vCPU's one.
@@ -1270,7 +1321,10 @@ static void imsic_vsfile_move(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 */
+    imsic_vsfile_local_update(&vsfile_data);
+
+    imsic_vsfile_set_vgein(v, vsfile_data.hgei);
 }
 
 /*
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 35/42] xen/riscv: move a vCPU's guest interrupt file on its way to the guest
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (33 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 34/42] xen/riscv: restore register state in the new IMSIC VS-file Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 36/42] xen/riscv: send MSIs to a vCPU's guest interrupt file Oleksii Kurochko
                   ` (6 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

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

Replace the static inline BUG_ON placeholder in asm/irq.h with a real
implementation in intc.c dispatching through a new move_irqs vintc_ops
callback, which a vINTC may leave unset.

vAPLIC does leave it unset. arch_move_irqs() is called once the
scheduler has moved a vCPU to another pCPU, but not necessarily from
either of the two pCPUs, and in sched_unit_migrate_finish() only after
the scheduler locks have been dropped: by then any vcpu_wake() can have
the vCPU picked up by its new pCPU and switched in. Moving the vCPU's
guest interrupt file from there would race with the vCPU running, which
could then enter the guest with hstatus.VGEIN still naming the old
file, i.e. a file of the new pCPU's IMSIC which may belong to another
vCPU. Worse, the hstatus.VGEIN written at the end of the move would go
into the saved context of a running vCPU, which the next trap from the
guest overwrites.

With a and b being the old and the new interrupt file of v:

    pCPU migrating v                  new pCPU of v
    ----------------                  -------------
    sched_unit_migrate_finish():
      move v to the new pCPU,
      drop the scheduler locks
                                      vcpu_wake(v)
    arch_move_irqs(v):                v switched in, enters the guest
      take, clear and map file b      with hstatus.VGEIN still naming
      retarget the APLIC to file b    file a, i.e. a file of this
      sync, save and clear file a     pCPU's IMSIC
      fill file b
      hstatus.VGEIN = b  ---------->  lost: the next trap from the
                                      guest overwrites the frame

The file is thus moved by the vCPU itself, on its way back to the
guest: as long as a vCPU runs on a pCPU, it can neither run on nor be
moved to any other one. For that, add a vintc_ops.enter_guest callback,
which a vINTC may leave unset too, run by the new vintc_enter_guest()
from check_for_pcpu_work() for the vCPU about to enter the guest. Wire
it up in vAPLIC with imsic_migrate_vcpu(). A move then goes as follows:

    old pCPU of v                     new pCPU of v
    -------------                     -------------
    v switched out: HGEIE[a] = 1
    v moved to the new pCPU,
    arch_move_irqs(v): no .move_irqs
                                      v switched in, on its way to the
                                      guest in check_for_pcpu_work():
                                      vintc_enter_guest(v):
                                        take, clear and map file b
                                        retarget the APLIC to file b
    sync, save and clear file a  <-IPI-
    HGEIE[a] = 0
                                        fill file b
                                        hstatus.VGEIN = b
                                      sret: the guest uses file b

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - Don't implement vintc_ops.move_irqs for vAPLIC: arch_move_irqs() can
   be called with the vCPU free to run on its new pCPU, so moving the
   vCPU's guest interrupt file from there would race with the vCPU
   running. Add vintc_ops.enter_guest instead, run by
   vintc_enter_guest() from check_for_pcpu_work(), and implement it for
   vAPLIC with imsic_migrate_vcpu().
 - Let a vINTC leave vintc_ops.move_irqs unset.
 - Make imsic_migrate_vcpu() cf_check, as it is an indirect call target.
 - Move right after "xen/riscv: restore register state in the new IMSIC
   VS-file", so that the hooks are wired up to a complete move of the
   vCPU's guest interrupt file.
 - Drop the Acked-by and the Reviewed-by, as the patch changed.
 - Rename from "xen/riscv: introduce arch_move_irqs()", as the
   vCPU's guest interrupt file is moved on its way to the guest
   rather than by arch_move_irqs().
 - Update the commit message accordingly.
---
Changes in v3:
 - Update the commit message: drop the two last paragraphs as they are
   stale.
---
Changes in v2:
 - New patch.
---
---
 xen/arch/riscv/imsic.c             |  2 +-
 xen/arch/riscv/include/asm/imsic.h |  2 +-
 xen/arch/riscv/include/asm/intc.h  | 11 +++++++++++
 xen/arch/riscv/include/asm/irq.h   |  5 +----
 xen/arch/riscv/intc.c              | 20 ++++++++++++++++++++
 xen/arch/riscv/traps.c             |  2 ++
 xen/arch/riscv/vaplic.c            |  7 +++++++
 7 files changed, 43 insertions(+), 6 deletions(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index adacac5c7268..49b2d8cbb004 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -1335,7 +1335,7 @@ static void imsic_vsfile_move(struct vcpu *v)
  * nor be moved to another one, so its file can't be in use elsewhere while
  * it is moved.
  */
-void imsic_migrate_vcpu(struct vcpu *v)
+void cf_check imsic_migrate_vcpu(struct vcpu *v)
 {
     ASSERT(v == current);
     ASSERT(!local_irq_is_enabled());
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index f7e537be29b4..488ce652f0b6 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -133,6 +133,6 @@ int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
 
 void imsic_vsfile_attach(struct vcpu *v);
 
-void imsic_migrate_vcpu(struct vcpu *v);
+void cf_check imsic_migrate_vcpu(struct vcpu *v);
 
 #endif /* RISCV_IMSIC_H */
diff --git a/xen/arch/riscv/include/asm/intc.h b/xen/arch/riscv/include/asm/intc.h
index 58196927aab2..d188a45b3fe1 100644
--- a/xen/arch/riscv/include/asm/intc.h
+++ b/xen/arch/riscv/include/asm/intc.h
@@ -70,6 +70,15 @@ struct vintc_ops {
 
     /* Restore vINTC state of the vCPU being switched in */
     void (*ctxt_switch_to)(struct vcpu *n);
+
+    /* Move interrupts of vCPU to a different pCPU */
+    void (*move_irqs)(struct vcpu *v);
+
+    /*
+     * Update vINTC state of the current vCPU, which is about to enter the
+     * guest.
+     */
+    void (*enter_guest)(struct vcpu *v);
 };
 
 struct vintc {
@@ -103,4 +112,6 @@ int vintc_reserve_virq(const struct domain *d, unsigned int virq);
 void vintc_ctxt_switch_from(struct vcpu *p);
 void vintc_ctxt_switch_to(struct vcpu *n);
 
+void vintc_enter_guest(struct vcpu *v);
+
 #endif /* RISCV_INTC_H */
diff --git a/xen/arch/riscv/include/asm/irq.h b/xen/arch/riscv/include/asm/irq.h
index 2eb68a5baf04..38277d94c7cf 100644
--- a/xen/arch/riscv/include/asm/irq.h
+++ b/xen/arch/riscv/include/asm/irq.h
@@ -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);
 
diff --git a/xen/arch/riscv/intc.c b/xen/arch/riscv/intc.c
index 70dfe6cd6f34..449f6b252414 100644
--- a/xen/arch/riscv/intc.c
+++ b/xen/arch/riscv/intc.c
@@ -204,3 +204,23 @@ void vintc_ctxt_switch_to(struct vcpu *n)
 
     ops->ctxt_switch_to(n);
 }
+
+/* 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;
+
+    if ( ops->move_irqs )
+        ops->move_irqs(v);
+}
+
+/* Update vINTC state of @v, the vCPU about to enter the guest. */
+void vintc_enter_guest(struct vcpu *v)
+{
+    const struct vintc_ops *ops = v->domain->arch.vintc->ops;
+
+    ASSERT(v == current);
+
+    if ( ops->enter_guest )
+        ops->enter_guest(v);
+}
diff --git a/xen/arch/riscv/traps.c b/xen/arch/riscv/traps.c
index 93996580cccf..aea57595c1ab 100644
--- a/xen/arch/riscv/traps.c
+++ b/xen/arch/riscv/traps.c
@@ -177,6 +177,8 @@ static void check_for_pcpu_work(void)
 {
     struct vcpu *curr = current;
 
+    vintc_enter_guest(curr);
+
     vcpu_sync_interrupts(curr);
 
     vcpu_flush_interrupts(curr);
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index eb2a263ceecb..b849ea1c97e8 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -623,6 +623,13 @@ static const struct vintc_ops vintc_ops = {
      */
     .ctxt_switch_from = imsic_ctxt_switch_from,
     .ctxt_switch_to = imsic_ctxt_switch_to,
+    /*
+     * No .move_irqs: the scheduler calls arch_move_irqs() from any pCPU, and
+     * in sched_unit_migrate_finish() with the vCPU free to run on its new
+     * pCPU meanwhile, while a guest interrupt file can only be moved safely
+     * by the vCPU itself. It moves it on its way to the guest instead.
+     */
+    .enter_guest = imsic_migrate_vcpu,
 };
 
 int domain_vaplic_init(struct domain *d)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 36/42] xen/riscv: send MSIs to a vCPU's guest interrupt file
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (34 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 35/42] xen/riscv: move a vCPU's guest interrupt file on its way to the guest Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 37/42] xen/riscv: sync with IMSIC VS-file injections on vCPU migration Oleksii Kurochko
                   ` (5 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

vAPLIC has to send some MSIs itself, i.e. make an interrupt identity
pending in a vCPU's guest interrupt file, as an MSI addressed to that
file would.

Unlike the VS-level CSRs, which reach only the interrupt file of the
pCPU they are accessed on, a write to the SETIPNUM_LE register of an
interrupt file works from any pCPU. So map the interrupt files of each
hart in imsic_init(), and add vcpu_imsic_inject(), which writes an
identity to that register of the h/w guest interrupt file a vCPU owns.

vcpu_imsic_inject() holds the read side of vsfile_lock across the write,
so that a migration, which publishes the new file under the write side
and drains the old one only afterwards, can't drain the file between
the choice of the file and the write. A fence keeps the write ahead of
the release of the read side, whose own barrier orders only memory
accesses. Even so, the AIA spec lets the write take effect in the old
file only after the drain has read it.

A vCPU has no h/w guest interrupt file until it runs for the first time,
and s/w guest interrupt files aren't supported yet, so an injection into
such a vCPU fails with -EOPNOTSUPP.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
vcpu_imsic_inject() gets its users in "xen/riscv: emulate the vAPLIC
genmsi register", for the MSIs a guest asks for through genmsi, and in
"xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC
sources", for the MSIs of virtual vAPLIC sources.

Regarding the FENCE(o,w) after writel() in the injection function:
wouldn't it be better to just update the __io_aw() definition with
FENCE(o,w), so that such cases can never be missed? Would that lead to
an extra performance drop? Is writel() expected to be used only with
MMIO addresses?

Also, I checked the Linux implementation: __io_aw() indirectly *can*
lead to RISCV_FENCE(o, w) through MMIOWB, which is selected
unconditionally for RISC-V. Interestingly, with __io_aw() defined as:
  #define __io_aw()	mmiowb_set_pending()
RISCV_FENCE(o, w) is applied for a spinlock when it's unlocked, but not
for rwlocks, so in Linux FENCE(o,w) is still needed after writel() when
an rwlock is used.

---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/imsic.c             | 67 +++++++++++++++++++++++++++++-
 xen/arch/riscv/include/asm/imsic.h |  8 ++++
 2 files changed, 74 insertions(+), 1 deletion(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index 49b2d8cbb004..e2b3bfbd6619 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -24,11 +24,13 @@
 #include <xen/sched.h>
 #include <xen/smp.h>
 #include <xen/spinlock.h>
+#include <xen/vmap.h>
 #include <xen/xvmalloc.h>
 
 #include <asm/aia.h>
 #include <asm/aplic.h>
 #include <asm/imsic.h>
+#include <asm/io.h>
 #include <asm/p2m.h>
 #include <asm/vaplic.h>
 
@@ -181,10 +183,16 @@ static void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
     unsigned long flags;
     struct vimsic_state *vimsic_state = v->arch.vimsic_state;
     unsigned int cpu = guest_file_id ? v->processor : CPU_NONE;
+    void __iomem *vsfile_va = NULL;
+
+    if ( guest_file_id )
+        vsfile_va = imsic_cfg.msi[cpu].files_va +
+                    guest_file_id * IMSIC_MMIO_PAGE_SZ;
 
     write_lock_irqsave(&vimsic_state->vsfile_lock, flags);
     vimsic_state->guest_file_id = guest_file_id;
     vimsic_state->vsfile_cpu = cpu;
+    vimsic_state->vsfile_va = vsfile_va;
     write_unlock_irqrestore(&vimsic_state->vsfile_lock, flags);
 }
 
@@ -721,6 +729,45 @@ static void cf_check imsic_aplic_sync(void *unused)
         cpu_relax();
 }
 
+/*
+ * Make interrupt identity @iid pending in @v's IMSIC interrupt file, as an MSI
+ * addressed to that file would.
+ *
+ * An identity an IMSIC would ignore is ignored here too, and reported as
+ * success. -EOPNOTSUPP means that @v has no h/w guest interrupt file (a vCPU
+ * is given one only when it runs for the first time), and s/w guest interrupt
+ * files aren't supported yet.
+ */
+int vcpu_imsic_inject(const struct vcpu *v, unsigned int iid)
+{
+    struct vimsic_state *imsic = v->arch.vimsic_state;
+    unsigned long flags;
+    int rc = 0;
+
+    /* Identity 0 and identities the file doesn't implement are ignored. */
+    if ( !iid || iid > guest_num_msis )
+        return 0;
+
+    read_lock_irqsave(&imsic->vsfile_lock, flags);
+
+    if ( imsic->vsfile_cpu != CPU_NONE )
+    {
+        writel(iid, imsic->vsfile_va + IMSIC_MMIO_SETIPNUM_LE);
+
+        /*
+         * Keep the write ahead of the release of the read side, whose barrier
+         * orders only memory accesses.
+         */
+        RISCV_FENCE(o, w);
+    }
+    else
+        rc = -EOPNOTSUPP;
+
+    read_unlock_irqrestore(&imsic->vsfile_lock, flags);
+
+    return rc;
+}
+
 static void imsic_vsfile_local_clear(const struct imsic_vsfile_data *idata)
 {
     unsigned int i;
@@ -959,6 +1006,18 @@ int __init imsic_init(const struct dt_device_node *node)
         msi[cpu].base_addr = mmios[index].base_addr;
         msi[cpu].offset = reloff;
 
+        msi[cpu].files_va =
+            ioremap(msi[cpu].base_addr + msi[cpu].offset,
+                    IMSIC_HART_SIZE(imsic_cfg.guest_index_bits));
+        if ( !msi[cpu].files_va )
+        {
+            printk(XENLOG_ERR
+                   "%s: failed to map the interrupt files of cpu%u\n",
+                   node->name, cpu);
+            rc = -ENOMEM;
+            goto imsic_init_err;
+        }
+
         nr_handlers++;
     }
 
@@ -980,7 +1039,13 @@ int __init imsic_init(const struct dt_device_node *node)
 
  imsic_init_err:
     xvfree(mmios);
-    xvfree(msi);
+    if ( msi )
+    {
+        for ( unsigned int i = 0; i < nr_cpu_ids; i++ )
+            if ( msi[i].files_va )
+                iounmap(msi[i].files_va);
+        xvfree(msi);
+    }
 
     return rc;
 }
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index 488ce652f0b6..8245ec6eb695 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -19,6 +19,8 @@
 #define IMSIC_MMIO_PAGE_SHIFT   12
 #define IMSIC_MMIO_PAGE_SZ      (1UL << IMSIC_MMIO_PAGE_SHIFT)
 
+#define IMSIC_MMIO_SETIPNUM_LE  0x00
+
 #define IMSIC_MIN_ID            63
 #define IMSIC_MAX_ID            2047
 
@@ -34,6 +36,8 @@
 struct imsic_msi {
     paddr_t base_addr;
     unsigned long offset;
+    /* Xen's mapping of this hart's interrupt files, to send MSIs to them. */
+    void __iomem *files_va;
 };
 
 struct imsic_config {
@@ -105,6 +109,8 @@ struct vimsic_state {
      * h/w IMSIC VS-file -> vsfile_cpu < NR_CPUS
      */
     unsigned int vsfile_cpu;
+    /* Xen's mapping of the h/w IMSIC VS-file, NULL while there is none. */
+    void __iomem *vsfile_va;
 };
 
 struct dt_device_node;
@@ -135,4 +141,6 @@ void imsic_vsfile_attach(struct vcpu *v);
 
 void cf_check imsic_migrate_vcpu(struct vcpu *v);
 
+int vcpu_imsic_inject(const struct vcpu *v, unsigned int iid);
+
 #endif /* RISCV_IMSIC_H */
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 37/42] xen/riscv: sync with IMSIC VS-file injections on vCPU migration
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (35 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 36/42] xen/riscv: send MSIs to a vCPU's guest interrupt file Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:48 ` [PATCH v4 38/42] xen/riscv: emulate the vAPLIC genmsi register Oleksii Kurochko
                   ` (4 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

vcpu_imsic_inject() writes an interrupt identity to the SETIPNUM_LE
register of a vCPU's h/w guest interrupt file under the read side of
vsfile_lock, and makes the write visible before releasing it. A
migration publishes the new file under the write side and drains the
old file only afterwards, so an injection either starts after the
publish and goes to the new file, or writes to the old file before the
publish. In the latter case, the write has to have taken effect in the
old file by the time the file is drained, but nothing ensures that:
even a completed write to an interrupt file may take effect in it only
later, as the AIA spec allows that to be delayed arbitrarily. So the
pending bit may be set only after imsic_vsfile_local_drain() has saved
and cleared the old file, which loses the interrupt, or even after the
file has been handed out to another vCPU.

What the AIA spec does guarantee is that the effects of the writes to
a single interrupt file occur in the global memory order of the writes.
So reserve the last identity of every guest interrupt file, which the
guest isn't given any more, and before draining the old file, write
that identity to it from the pCPU owning it and wait for it to become
pending. The injections which came before the publish precede that
write in the global memory order, so by then they have taken effect in
the file too.

As riscv,num-guest-ids is now used for the reserved identity, a missing
property is taken to mean as many identities as riscv,num-ids, which is
what the DT binding says, rather than GUEST_IMSIC_MAX_MSIS of them.

The AIA spec requires the number of identities of an interrupt file to
be one less than a multiple of 64, and Linux refuses an IMSIC which
doesn't follow that. So the guest is told about the largest such number
of identities below the reserved one, e.g. 191 of the 255 identities
QEMU provides, rather than about all the others.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Before making a final decision on this patch, please review:
https://github.com/riscv/riscv-aia/issues/172

At the time this patch was submitted, there had been no response from the
AIA specification maintainers. Therefore, for now, I consider the approach
proposed in this patch to be a viable solution.

The way this is implemented will prevent the V100 platform from booting.
Let's discuss it first.

If this synchronization is actually needed, then let's go back to making V100
tolerate MSI reservation failures for the VS-file instead of panicking.
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/imsic.c             | 106 +++++++++++++++++++++++++----
 xen/arch/riscv/include/asm/imsic.h |   7 ++
 2 files changed, 101 insertions(+), 12 deletions(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index e2b3bfbd6619..e72a710b2d28 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -129,6 +129,18 @@ do {                                \
     csr_write(CSR_VSIREG, v);       \
 } while (0)
 
+#define imsic_vs_csr_read(c)        \
+({                                  \
+    csr_write(CSR_VSISELECT, c);    \
+    csr_read(CSR_VSIREG);           \
+})
+
+#define imsic_vs_csr_clear(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, c);    \
+    csr_clear(CSR_VSIREG, v);       \
+} while (0)
+
 /*
  * On RV64 a 64-bit EIx group is the even-numbered register alone, whereas on
  * RV32 it is split into the even-numbered (low half) and the following
@@ -430,11 +442,6 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
         return -ENOENT;
     }
 
-    if ( dt_property_read_u32(node, "riscv,num-guest-ids", &tmp) )
-        guest_num_msis = min(GUEST_IMSIC_MAX_MSIS, tmp);
-    else
-        guest_num_msis = GUEST_IMSIC_MAX_MSIS;
-
     if ( (imsic_cfg.nr_ids < IMSIC_MIN_ID) ||
          (imsic_cfg.nr_ids > IMSIC_MAX_ID) )
     {
@@ -443,6 +450,39 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
         return -ENOENT;
     }
 
+    /*
+     * A guest interrupt file implements as many identities as
+     * riscv,num-guest-ids says, or as many as the S-file does if it is
+     * absent.
+     */
+    if ( !dt_property_read_u32(node, "riscv,num-guest-ids", &tmp) )
+        tmp = imsic_cfg.nr_ids;
+
+    /*
+     * One identity more than the minimum is needed, as the last one is
+     * reserved below.
+     */
+    if ( (tmp <= IMSIC_MIN_ID) || (tmp > IMSIC_MAX_ID) )
+    {
+        printk(XENLOG_ERR
+               "%s: invalid number of guest interrupt identities\n",
+               node->name);
+        return -ENOENT;
+    }
+
+    /*
+     * Reserve the last identity of a guest interrupt file for synchronizing
+     * with the injections into the file (see imsic_vsfile_local_sync()), and
+     * give the guest at most GUEST_IMSIC_MAX_MSIS of the others. The AIA
+     * spec requires the number of identities to be one less than a multiple
+     * of 64, so round it down to the largest such number below
+     * guest_sync_id.
+     */
+    BUILD_BUG_ON((GUEST_IMSIC_MAX_MSIS & IMSIC_MIN_ID) != IMSIC_MIN_ID);
+    imsic_cfg.guest_sync_id = tmp;
+    guest_num_msis = min(GUEST_IMSIC_MAX_MSIS,
+                         ROUNDDOWN(tmp, IMSIC_MIN_ID + 1) - 1);
+
     imsic_cfg.nr_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1, 64);
 
     /* Compute base address */
@@ -701,18 +741,58 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
 }
 
 /*
- * Ensure that all the MSIs the APLIC has already generated for the hart this
- * runs on have really reached the hart's IMSIC.
+ * Wait until the writes made to guest interrupt file @hgei of this hart through
+ * SETIPNUM_LE before this call have taken effect in it.
+ */
+static void imsic_vsfile_local_sync(unsigned int hgei)
+{
+    unsigned int id = imsic_cfg.guest_sync_id;
+    unsigned int isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+    void __iomem *va = imsic_cfg.msi[smp_processor_id()].files_va +
+                       hgei * IMSIC_MMIO_PAGE_SZ;
+    struct imsic_vsfile_ctx ctx;
+
+    imsic_vsfile_select(hgei, &ctx);
+
+    imsic_vs_csr_clear(isel, bit);
+
+    /*
+     * For FENCE, a CSR write counts as device output, which writel() doesn't
+     * order before its own write: should the IMSIC see the two the other way
+     * round, the clear would undo the write and the loop would never end.
+     */
+    RISCV_FENCE(o, o);
+    writel(id, va + IMSIC_MMIO_SETIPNUM_LE);
+
+    while ( !(imsic_vs_csr_read(isel) & bit) )
+        cpu_relax();
+
+    /* The identity is Xen's, so it mustn't be left pending in the file. */
+    imsic_vs_csr_clear(isel, bit);
+
+    imsic_vsfile_deselect(&ctx);
+}
+
+/*
+ * Ensure that all the MSIs already sent to the guest interrupt file @data names
+ * on the hart this runs on, by the h/w APLIC or by vAPLIC, have reached it.
  *
- * 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
+ * For the h/w APLIC, 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.
+ *
+ * vAPLIC sends its MSIs through SETIPNUM_LE, which that barrier doesn't cover,
+ * so they are waited for separately.
  */
-static void cf_check imsic_aplic_sync(void *unused)
+static void cf_check imsic_aplic_sync(void *data)
 {
+    const struct imsic_vsfile_data *idata = data;
+
     imsic_local_eix_update(imsic_sync_id(&imsic_cfg), 1, true, false);
 
     /*
@@ -727,6 +807,8 @@ static void cf_check imsic_aplic_sync(void *unused)
 
     while ( !imsic_local_is_pending(imsic_sync_id(&imsic_cfg)) )
         cpu_relax();
+
+    imsic_vsfile_local_sync(idata->hgei);
 }
 
 /*
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index 8245ec6eb695..f372761b8853 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -66,6 +66,13 @@ struct imsic_config {
      */
     unsigned int nr_eix;
 
+    /*
+     * Interrupt identity reserved in every h/w guest interrupt file for
+     * synchronizing with the injections into the file. It is never given to a
+     * guest.
+     */
+    unsigned int guest_sync_id;
+
     /* MSI */
     const struct imsic_msi *msi;
 
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 38/42] xen/riscv: emulate the vAPLIC genmsi register
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (36 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 37/42] xen/riscv: sync with IMSIC VS-file injections on vCPU migration Oleksii Kurochko
@ 2026-11-13 15:48 ` Oleksii Kurochko
  2026-11-13 15:49 ` [PATCH v4 39/42] xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE Oleksii Kurochko
                   ` (3 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:48 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

So far, a guest's access to genmsi has ended up in the default case of
the vAPLIC emulation and got the domain crashed.

In MSI delivery mode, a write to genmsi makes an APLIC send an extempore
MSI, with EIID as its data, to the hart named by the Hart Index field.
A guest may want to use it when it reconfigures where a target register
points to, though Linux at least doesn't do so at the moment, so an
access to genmsi should be emulated.

The physical genmsi can't be used on the guest's behalf, as it has no
Guest Index field: its MSI always goes to a hart's supervisor-level
interrupt file. So emulate genmsi in software: wait for the MSIs the
h/w APLIC and vAPLIC have already sent to the target vCPU's h/w guest
interrupt file, using Xen's own APLIC-hart barrier, and then make the
identity pending in the file through vcpu_imsic_inject().

The barrier has to be executed by the pCPU owning the file, and reaching
another pCPU through an IPI takes IRQs enabled, while a trap taken from
a guest is handled with them disabled. Enable them for the time of the
barrier: no lock is held at that point, and the CSRs describing the trap
have been read already.

An MSI to a vCPU without a h/w guest interrupt file, e.g. one which
hasn't run yet, is lost.

Busy always reads as zero, as the MSI is sent before the write to genmsi
completes. genmsi takes the value written just before the MSI is sent,
both under a new domain-wide vaplic->lock, so that concurrent writes
take effect in the order their MSIs are sent.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/imsic.c              | 40 ++++++++++++++
 xen/arch/riscv/include/asm/aplic.h  |  4 +-
 xen/arch/riscv/include/asm/imsic.h  |  2 +
 xen/arch/riscv/include/asm/vaplic.h |  6 +++
 xen/arch/riscv/vaplic.c             | 82 +++++++++++++++++++++++++----
 5 files changed, 124 insertions(+), 10 deletions(-)

diff --git a/xen/arch/riscv/imsic.c b/xen/arch/riscv/imsic.c
index e72a710b2d28..e7627dd48041 100644
--- a/xen/arch/riscv/imsic.c
+++ b/xen/arch/riscv/imsic.c
@@ -811,6 +811,46 @@ static void cf_check imsic_aplic_sync(void *data)
     imsic_vsfile_local_sync(idata->hgei);
 }
 
+/*
+ * Make sure that all the MSIs the h/w APLIC or vAPLIC has already sent to @v's
+ * IMSIC interrupt file have arrived there.
+ *
+ * The barrier has to be executed by the pCPU owning the file, so for a file
+ * owned by another pCPU an IPI is sent, which has to be done with IRQs
+ * enabled.
+ *
+ * vsfile_lock can't be held across the barrier: the IPI takes IRQs enabled,
+ * while the write side is taken with IRQs disabled, by imsic_update_state()
+ * when @v acquires a file on the very pCPU the IPI goes to, so the two would
+ * wait for each other. Nor is it needed, should @v be migrated meanwhile:
+ *  - the migration does the barrier for the old file itself before moving its
+ *    state into the new one, and it is done by @v itself before it enters the
+ *    guest again;
+ *  - MSIs are redirected to the new file only after it has been published,
+ *    so whatever reaches the new file was sent after the lookup done here;
+ *  - should the file have been handed to another vCPU meanwhile, the wait
+ *    touches only the identity Xen reserves in it.
+ */
+void vcpu_imsic_aplic_barrier(const struct vcpu *v)
+{
+    struct vimsic_state *imsic = v->arch.vimsic_state;
+    struct imsic_vsfile_data idata = { };
+    unsigned long flags;
+    unsigned int cpu;
+
+    /* The file and the pCPU owning it have to be read together. */
+    read_lock_irqsave(&imsic->vsfile_lock, flags);
+    cpu = imsic->vsfile_cpu;
+    idata.hgei = imsic->guest_file_id;
+    read_unlock_irqrestore(&imsic->vsfile_lock, flags);
+
+    /* With no interrupt file, there is nothing an MSI can be on its way to. */
+    if ( cpu == CPU_NONE )
+        return;
+
+    imsic_call_on_cpu(cpu, imsic_aplic_sync, &idata);
+}
+
 /*
  * Make interrupt identity @iid pending in @v's IMSIC interrupt file, as an MSI
  * addressed to that file would.
diff --git a/xen/arch/riscv/include/asm/aplic.h b/xen/arch/riscv/include/asm/aplic.h
index 37584039107b..5b4ae0d91f50 100644
--- a/xen/arch/riscv/include/asm/aplic.h
+++ b/xen/arch/riscv/include/asm/aplic.h
@@ -89,7 +89,9 @@
 #define APLIC_SETIPNUM_BE               0x2004
 
 #define APLIC_GENMSI                    0x3000
-#define APLIC_GENMSI_BUSY               BIT(12, U)
+#define  APLIC_GENMSI_HART_IDX          GENMASK(31, 18)
+#define  APLIC_GENMSI_BUSY              BIT(12, U)
+#define  APLIC_GENMSI_EIID              GENMASK(10, 0)
 
 #define APLIC_TARGET_BASE               0x3004
 #define APLIC_TARGET_LAST               0x3ffc
diff --git a/xen/arch/riscv/include/asm/imsic.h b/xen/arch/riscv/include/asm/imsic.h
index f372761b8853..5fc8f8067fcf 100644
--- a/xen/arch/riscv/include/asm/imsic.h
+++ b/xen/arch/riscv/include/asm/imsic.h
@@ -150,4 +150,6 @@ void cf_check imsic_migrate_vcpu(struct vcpu *v);
 
 int vcpu_imsic_inject(const struct vcpu *v, unsigned int iid);
 
+void vcpu_imsic_aplic_barrier(const struct vcpu *v);
+
 #endif /* RISCV_IMSIC_H */
diff --git a/xen/arch/riscv/include/asm/vaplic.h b/xen/arch/riscv/include/asm/vaplic.h
index 843b78e80ad8..360ad3021751 100644
--- a/xen/arch/riscv/include/asm/vaplic.h
+++ b/xen/arch/riscv/include/asm/vaplic.h
@@ -33,6 +33,9 @@ struct vaplic_source {
 struct vaplic_regs {
     uint32_t domaincfg;
 
+    /* Register to generate an extempore MSI. */
+    uint32_t genmsi;
+
     /*
      * Indexed by source number. The array holds d->arch.vintc->nr_virqs
      * elements; sources[0] is unused as APLIC interrupt sources start from 1.
@@ -44,6 +47,9 @@ struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
 
+    /* Protects access to the vAPLIC registers. */
+    spinlock_t lock;
+
     paddr_t regs_start;
     unsigned int regs_size;
 };
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index b849ea1c97e8..1ab87b8aee1a 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -251,6 +251,69 @@ static uint32_t generate_auth_mask(const struct domain *currd,
            (first_bit % BITS_PER_LONG);
 }
 
+static uint32_t vaplic_genmsi_read(const struct domain *d)
+{
+    /*
+     * Busy always reads as zero, as the MSI is sent before the write to genmsi
+     * completes.
+     *
+     * No lock is needed: a read racing with a write may return the new value
+     * before the MSI has been sent, which looks the same to the guest as an
+     * MSI of an APLIC which hasn't taken effect at the IMSIC yet.
+     */
+    return read_atomic(&to_vaplic(d)->regs.genmsi);
+}
+
+static void vaplic_genmsi_write(const struct domain *d, uint32_t value)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    const struct vcpu *v;
+    unsigned long flags;
+
+    /*
+     * Hart Index and EIID behave as in a target register, Busy is read-only
+     * and all the other bits are reserved.
+     */
+    value &= APLIC_GENMSI_HART_IDX | APLIC_GENMSI_EIID;
+
+    v = domain_vcpu(d, MASK_EXTR(value, APLIC_GENMSI_HART_IDX));
+    if ( !v )
+    {
+        gdprintk(XENLOG_ERR, "Invalid vCPU id in genmsi\n");
+
+        /* Ignore such writes */
+        return;
+    }
+
+    /*
+     * According to the AIA spec:
+     *   All MSIs previously sent from this APLIC to the same hart must be
+     *   visible at the hart's IMSIC before the extempore MSI becomes visible
+     *   at the hart's IMSIC.
+     *
+     * The physical genmsi can't send an MSI to a guest interrupt file, so
+     * wait for the MSIs already sent to @v's file to arrive there.
+     *
+     * The barrier may need an IPI, which takes IRQs enabled, while a trap
+     * taken from a guest is handled with them disabled. Enable them for the
+     * time of the barrier: no lock is held here, and the CSRs describing the
+     * trap have been read already.
+     */
+    ASSERT(!local_irq_is_enabled());
+    local_irq_enable();
+    vcpu_imsic_aplic_barrier(v);
+    local_irq_disable();
+
+    spin_lock_irqsave(&vaplic->lock, flags);
+
+    write_atomic(&vaplic->regs.genmsi, value);
+
+    if ( vcpu_imsic_inject(v, MASK_EXTR(value, APLIC_GENMSI_EIID)) )
+        gdprintk(XENLOG_DEBUG, "genmsi: %pv has no h/w interrupt file\n", v);
+
+    spin_unlock_irqrestore(&vaplic->lock, flags);
+}
+
 static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
                                 uint32_t *out)
 {
@@ -335,15 +398,11 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
 
         return true;
 
-    /*
-     * TODO: emulate genmsi. A write to it has to send an extempore MSI to
-     * the target vCPU, and a guest typically waits for that MSI to become
-     * pending in its interrupt file. Just recording the written value would
-     * leave such a guest waiting forever, so until genmsi is emulated, an
-     * access to it is treated as an unhandled one, which gets the domain
-     * crashed.
-     */
     case APLIC_GENMSI:
+        *out = vaplic_genmsi_read(currd);
+
+        return true;
+
     default:
         gdprintk(XENLOG_WARNING, "Unhandled APLIC read at offset %#x\n",
                  offset);
@@ -472,8 +531,11 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
 
         return true;
 
-    /* TODO: emulate genmsi, see vaplic_emulate_load(). */
     case APLIC_GENMSI:
+        vaplic_genmsi_write(currd, value);
+
+        return true;
+
     default:
         gdprintk(XENLOG_WARNING,
                  "Unhandled APLIC write at offset %#x (value %#x)\n",
@@ -670,6 +732,8 @@ int domain_vaplic_init(struct domain *d)
     for ( i = 0; i < d->arch.vintc->nr_virqs; i++ )
         spin_lock_init(&vaplic->regs.sources[i].lock);
 
+    spin_lock_init(&vaplic->lock);
+
     vaplic->regs_start = GUEST_APLIC_S_BASE;
     /*
      * IDC structures are used only in direct delivery mode, so the control
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 39/42] xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (37 preceding siblings ...)
  2026-11-13 15:48 ` [PATCH v4 38/42] xen/riscv: emulate the vAPLIC genmsi register Oleksii Kurochko
@ 2026-11-13 15:49 ` Oleksii Kurochko
  2026-11-13 15:49 ` [PATCH v4 40/42] xen/riscv: emulate target[] of virtual vAPLIC sources Oleksii Kurochko
                   ` (2 subsequent siblings)
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:49 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

So far, vAPLIC has kept no state of an interrupt source but its
target[]. The guest's domaincfg.IE could be set, but not cleared, as
nothing could honour IE = 0: the h/w forwards the MSIs of a h/w source
straight to the guest's interrupt file, whatever the guest's IE is.

So keep the guest's view of sourcecfg[] and of the enable bits of both
kinds of source, following the AIA spec for MSI delivery mode. Reads of
them no longer access the h/w: the guest's view of sourcecfg[] starts
inactive, as does the h/w register of a h/w source, which
intc_route_irq_to_guest() leaves inactive, and every write which may
change a h/w register keeps the guest's view in step with it.

With the enable bits kept in regs.ie[], the guest's domaincfg.IE can be
honoured for the h/w sources. The h/w domaincfg.IE can't be used for
that, as it is shared with the sources of Xen and of other domains, so
while the guest's IE is 0, the h/w enable bits of its h/w sources are
kept clear, and they are restored from regs.ie[] once IE is set again.
What becomes pending meanwhile stays pending in the h/w, which forwards
it once the enable bit is restored. At its reset value of 0, IE needs
those bits to be clear, and they are, as a h/w source starts inactive.
So let a write clear IE.

The pending bits and target[] of a virtual source aren't emulated here,
and neither is sending its MSIs: what they need from the registers
emulated here is left as TODOs.

Factor vaplic_bitmap_word() out of generate_auth_mask(), renamed to
vaplic_hw_sources(), to get the word of the virtual sources as well.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/include/asm/vaplic.h |  28 +-
 xen/arch/riscv/vaplic.c             | 491 ++++++++++++++++++++++------
 2 files changed, 422 insertions(+), 97 deletions(-)

diff --git a/xen/arch/riscv/include/asm/vaplic.h b/xen/arch/riscv/include/asm/vaplic.h
index 360ad3021751..e2e4611f69c2 100644
--- a/xen/arch/riscv/include/asm/vaplic.h
+++ b/xen/arch/riscv/include/asm/vaplic.h
@@ -23,11 +23,22 @@ struct vcpu;
 
 /* State of one vAPLIC interrupt source. */
 struct vaplic_source {
-    /* Protects target together with the h/w target register of the source. */
+    /*
+     * Protects target and sourcecfg, together with the corresponding h/w
+     * registers of a h/w source.
+     */
     spinlock_t lock;
 
     /* Guest's view of the APLIC target register. */
     uint32_t target;
+
+    /*
+     * sourcecfg register as the guest sees it:
+     *  - for a virtual source, this is the only place it is kept;
+     *  - for a h/w source, it is a copy of the h/w register, which only the
+     *    guest changes.
+     */
+    uint32_t sourcecfg;
 };
 
 struct vaplic_regs {
@@ -36,6 +47,15 @@ struct vaplic_regs {
     /* Register to generate an extempore MSI. */
     uint32_t genmsi;
 
+    /*
+     * Interrupt-enable bits as the guest sees them, a word per 32 sources:
+     *  - for a virtual source, this is the only place its bit is kept;
+     *  - for a h/w source, it is a copy of the h/w bit, which only the guest
+     *    changes. While domaincfg.IE is 0, the h/w bit is kept clear and the
+     *    guest's view is kept here only.
+     */
+    uint32_t *ie;
+
     /*
      * Indexed by source number. The array holds d->arch.vintc->nr_virqs
      * elements; sources[0] is unused as APLIC interrupt sources start from 1.
@@ -47,7 +67,11 @@ struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
 
-    /* Protects access to the vAPLIC registers. */
+    /*
+     * Protects access to the vAPLIC registers. A vaplic_source.lock, where
+     * needed too, is taken first, to avoid an ABBA deadlock (see
+     * vaplic_sourcecfg_write()).
+     */
     spinlock_t lock;
 
     paddr_t regs_start;
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index 1ab87b8aee1a..edf9c5a3512a 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -32,8 +32,17 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 /*
  * Only a h/w source of a domain, one a h/w IRQ is routed to (see
  * vintc.hw_irqs), may be accessed in the h/w. A virtual source has nothing
- * there: until its state is emulated, it reads as zero and ignores writes,
- * like a source not assigned to the domain.
+ * there: its sourcecfg[] and its enable bit are emulated, and the rest of
+ * its registers, until they are emulated too, read as zero and ignore
+ * writes, like those of a source not assigned to the domain.
+ *
+ * A write passed through to the h/w can thus affect only the h/w sources of
+ * the domain: a write to setip[], clrip[], setie[] or clrie[] is masked
+ * with them, which leaves the bits of the other sources at 0, i.e. untouched,
+ * and {set,clr}ipnum, setipnum_le and sourcecfg[] name a source checked to
+ * be one of them. route_irq_to_guest() never assigns a source to more than
+ * one domain, or to both a domain and Xen, and as virq == pirq, no
+ * translation is needed either.
  */
 static bool vaplic_is_hw_source(const struct domain *d, unsigned int irqn)
 {
@@ -44,33 +53,44 @@ static bool vaplic_is_hw_source(const struct domain *d, unsigned int irqn)
                     vintc->hw_irqs);
 }
 
+/* Whether source @irqn is assigned to @d, be it a h/w or a virtual one. */
+static bool vaplic_is_assigned(const struct domain *d, unsigned int irqn)
+{
+    const struct vintc *vintc = d->arch.vintc;
+
+    return (irqn < vintc->nr_virqs) &&
+           test_bit(array_index_nospec(irqn, vintc->nr_virqs),
+                    vintc->used_irqs);
+}
+
 /*
  * Convert a byte offset (within a SETIP/CLRIP/SETIE/CLRIE register group) to
- * a 32-bit word index into the hw_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.
+ * a 32-bit word index, each word covering 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))
 
+/* Number of interrupt sources covered by a SETIP/CLRIP/SETIE/CLRIE word. */
+#define IRQS_PER_WORD 32U
+
 /*
- * vAPLIC keeps no shadow copy of sourcecfg[], and a guest's writes to it go
- * straight to the h/w register, so it is the h/w register which tells whether
- * a source is active.
+ * Whether source @irqn of @d is active, as the guest's view of its
+ * sourcecfg[] says. For a h/w source, that is what the h/w register reads.
  */
-static bool vaplic_source_is_active(unsigned int irqn)
+static bool vaplic_source_is_active(const struct domain *d, unsigned int irqn)
 {
-    uint32_t sourcecfg = aplic_hw_read_reg(APLIC_SOURCECFG_BASE +
-                                           (irqn - 1) * sizeof(uint32_t));
+    const struct vaplic *vaplic = to_vaplic(d);
+    uint32_t sourcecfg = read_atomic(&vaplic->regs.sources[irqn].sourcecfg);
 
     /*
-     * A source is inactive if it is delegated to a child domain (D = 1), in
-     * which case the low bits hold the Child Index rather than SM, or if it
-     * isn't delegated and SM is Inactive.
+     * vAPLIC is a leaf domain: a write with D set zeroes the register (see
+     * vaplic_sourcecfg_write()).
      */
-    return !(sourcecfg & APLIC_SOURCECFG_D) &&
-           (MASK_EXTR(sourcecfg, APLIC_SOURCECFG_SM) !=
-            APLIC_SOURCECFG_SM_INACTIVE);
+    ASSERT(!(sourcecfg & APLIC_SOURCECFG_D));
+
+    return MASK_EXTR(sourcecfg, APLIC_SOURCECFG_SM) !=
+           APLIC_SOURCECFG_SM_INACTIVE;
 }
 
 static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
@@ -94,7 +114,7 @@ static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
     spin_lock_irqsave(&src->lock, flags);
 
     /* target[i] is read-only zero while source i is inactive. */
-    if ( vaplic_source_is_active(irqn) )
+    if ( vaplic_source_is_active(d, irqn) )
         val = src->target;
 
     spin_unlock_irqrestore(&src->lock, flags);
@@ -118,7 +138,7 @@ static void vaplic_target_write(const struct domain *d, unsigned int irqn,
     irqn = array_index_nospec(irqn, d->arch.vintc->nr_virqs);
 
     /* target[i] is read-only zero while source i is inactive. */
-    if ( !vaplic_source_is_active(irqn) )
+    if ( !vaplic_source_is_active(d, irqn) )
         return;
 
     target_vcpu = domain_vcpu(d, MASK_EXTR(value, APLIC_TARGET_HART_IDX));
@@ -230,11 +250,18 @@ void vaplic_reconfigure_target(const struct vcpu *v)
     }
 }
 
-static uint32_t generate_auth_mask(const struct domain *currd,
+/* Number of setie[] words covering the sources of @d. */
+static unsigned int vaplic_nr_words(const struct domain *d)
+{
+    return DIV_ROUND_UP(d->arch.vintc->nr_virqs, IRQS_PER_WORD);
+}
+
+/* Word @word_idx, in the setie[] layout, of @bitmap of @d's sources. */
+static uint32_t vaplic_bitmap_word(const struct domain *d,
+                                   const unsigned long *bitmap,
                                    unsigned int word_idx)
 {
-    unsigned int nr_words = DIV_ROUND_UP(currd->arch.vintc->nr_virqs,
-                                         sizeof(uint32_t) * BITS_PER_BYTE);
+    unsigned int nr_words = vaplic_nr_words(d);
     unsigned int first_bit;
 
     if ( word_idx >= nr_words )
@@ -244,11 +271,297 @@ static uint32_t generate_auth_mask(const struct domain *currd,
         return 0;
     }
 
-    first_bit = array_index_nospec(word_idx, nr_words) *
-                sizeof(uint32_t) * BITS_PER_BYTE;
+    first_bit = array_index_nospec(word_idx, nr_words) * IRQS_PER_WORD;
+
+    return bitmap[first_bit / BITS_PER_LONG] >> (first_bit % BITS_PER_LONG);
+}
+
+/* The h/w sources of @d in word @word_idx, in the setie[] layout. */
+static uint32_t vaplic_hw_sources(const struct domain *d,
+                                  unsigned int word_idx)
+{
+    return vaplic_bitmap_word(d, d->arch.vintc->hw_irqs, word_idx);
+}
+
+/* The virtual sources of @d in word @word_idx, in the setie[] layout. */
+static uint32_t vaplic_virtual_sources(const struct domain *d,
+                                       unsigned int word_idx)
+{
+    return vaplic_bitmap_word(d, d->arch.vintc->used_irqs, word_idx) &
+           ~vaplic_bitmap_word(d, d->arch.vintc->hw_irqs, word_idx);
+}
+
+/* The bits of @mask, a subset of setie[@word_idx], of the active sources. */
+static uint32_t vaplic_active_sources(const struct domain *d,
+                                      unsigned int word_idx, uint32_t mask)
+{
+    uint32_t active = 0;
+
+    for_each_set_bit ( bit, mask )
+        if ( vaplic_source_is_active(d, word_idx * IRQS_PER_WORD + bit) )
+            active |= BIT(bit, U);
+
+    return active;
+}
+
+/* Emulate a read of sourcecfg[@irqn]. */
+static uint32_t vaplic_sourcecfg_read(const struct domain *d, unsigned int irqn)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    struct vaplic_source *src;
+    unsigned long flags;
+    uint32_t val;
+
+    /*
+     * A source not assigned to @d appears not to be implemented, and
+     * sourcecfg[] of such a source is read-only zero.
+     */
+    if ( !vaplic_is_assigned(d, irqn) )
+        return 0;
+
+    irqn = array_index_nospec(irqn, d->arch.vintc->nr_virqs);
+    src = &vaplic->regs.sources[irqn];
+
+    /*
+     * src->lock makes the read atomic as a whole, against a write to
+     * sourcecfg[] which changes the h/w register, this copy and the enable
+     * and pending bits.
+     */
+    spin_lock_irqsave(&src->lock, flags);
+    val = src->sourcecfg;
+    spin_unlock_irqrestore(&src->lock, flags);
+
+    return val;
+}
+
+/* Emulate a write of @value to sourcecfg[@irqn]. */
+static void vaplic_sourcecfg_write(const struct domain *d, unsigned int irqn,
+                                   uint32_t value)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    unsigned int offset = offsetof(struct aplic_regs, sourcecfg[irqn - 1]);
+    struct vaplic_source *src;
+    unsigned long flags;
+
+    if ( !vaplic_is_assigned(d, irqn) )
+        return;
+
+    /*
+     * vAPLIC is a leaf domain: it has no child domain a source could be
+     * delegated to. With D = 1, the low bits of the value would hold a
+     * Child Index rather than SM, and for a leaf domain the AIA spec makes
+     * such a write set the entire register to zero instead.
+     */
+    if ( value & APLIC_SOURCECFG_D )
+    {
+        gdprintk(XENLOG_DEBUG, "sourcecfg[%u] write with D set, zeroing it\n",
+                 irqn);
+
+        value = 0;
+    }
+
+    /*
+     * SM is the only field left, the other bits are reserved and read as
+     * zero, so ignore what a guest writes to them.
+     */
+    value &= APLIC_SOURCECFG_SM;
+
+    irqn = array_index_nospec(irqn, d->arch.vintc->nr_virqs);
+    src = &vaplic->regs.sources[irqn];
+
+    spin_lock_irqsave(&src->lock, flags);
+
+    /*
+     * SM is WARL. For a h/w source, it is the h/w which substitutes a legal
+     * value for an illegal one, so the guest's view is read back from the
+     * h/w register. For a virtual source, it is vAPLIC which has to: the
+     * reserved values 0x2 and 0x3 are taken as Inactive, and any other value
+     * is a legal one and is kept as written.
+     */
+    if ( vaplic_is_hw_source(d, irqn) )
+    {
+        aplic_hw_write_reg(offset, value);
+        value = aplic_hw_read_reg(offset);
+    }
+    else if ( value == 0x2 || value == 0x3 )
+        value = APLIC_SOURCECFG_SM_INACTIVE;
+
+    /*
+     * The enable bit of an inactive source is read-only zero, and stays zero
+     * when the source becomes active again, so making the source inactive
+     * clears it: the h/w does so for a h/w source, and the guest's view has
+     * to follow. vaplic->lock keeps a concurrent write to an enable register
+     * from setting the bit meanwhile: such a write sees either the source
+     * still active, and then its bit is cleared here afterwards, or the
+     * source inactive, and then it doesn't set the bit. IRQs are already off
+     * under src->lock.
+     */
+    spin_lock(&vaplic->lock);
+
+    write_atomic(&src->sourcecfg, value);
 
-    return currd->arch.vintc->hw_irqs[first_bit / BITS_PER_LONG] >>
-           (first_bit % BITS_PER_LONG);
+    if ( !vaplic_source_is_active(d, irqn) )
+        write_atomic(&vaplic->regs.ie[irqn / IRQS_PER_WORD],
+                     vaplic->regs.ie[irqn / IRQS_PER_WORD] &
+                     ~BIT(irqn % IRQS_PER_WORD, U));
+
+    spin_unlock(&vaplic->lock);
+
+    /*
+     * TODO: when the pending bit and target[] of a virtual source are
+     * emulated:
+     *  - making the source inactive has to clear the pending bit too, and
+     *    target[] has to read as zero while the source is inactive;
+     *  - a write which leaves the source active may change its rectified
+     *    input value, which may set its pending bit (or, for a
+     *    level-sensitive source, clear it). If domaincfg.IE is 1, a source
+     *    which is then pending and enabled has to get its MSI sent.
+     */
+
+    spin_unlock_irqrestore(&src->lock, flags);
+}
+
+/* Emulate a read of setie[@word_idx]. */
+static uint32_t vaplic_setie_read(const struct domain *d, unsigned int word_idx)
+{
+    const struct vaplic *vaplic = to_vaplic(d);
+    uint32_t srcs = vaplic_hw_sources(d, word_idx) |
+                    vaplic_virtual_sources(d, word_idx);
+
+    if ( !srcs )
+        return 0;
+
+    word_idx = array_index_nospec(word_idx, vaplic_nr_words(d));
+
+    /*
+     * A word of regs.ie[] is updated in one go, so a read sees either all of
+     * a write to setie[] or none of it, as with a single register in the h/w.
+     */
+    return read_atomic(&vaplic->regs.ie[word_idx]) & srcs;
+}
+
+/* Emulate a write of @value to setie[@word_idx]. */
+static void vaplic_setie_write(const struct domain *d, unsigned int word_idx,
+                               uint32_t value)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    uint32_t hw_srcs = vaplic_hw_sources(d, word_idx);
+    unsigned long flags;
+
+    value &= hw_srcs | vaplic_virtual_sources(d, word_idx);
+    if ( !value )
+        return;
+
+    word_idx = array_index_nospec(word_idx, vaplic_nr_words(d));
+
+    spin_lock_irqsave(&vaplic->lock, flags);
+
+    /* The enable bit of an inactive source is read-only zero. */
+    value = vaplic_active_sources(d, word_idx, value);
+
+    /* Ahead of the h/w, so a guest which gets the MSI reads the bit set. */
+    write_atomic(&vaplic->regs.ie[word_idx],
+                 vaplic->regs.ie[word_idx] | value);
+
+    /* While domaincfg.IE is 0, the h/w bits are kept clear. */
+    if ( (value & hw_srcs) && (vaplic->regs.domaincfg & APLIC_DOMAINCFG_IE) )
+        aplic_hw_write_reg(offsetof(struct aplic_regs, setie[word_idx]),
+                           value & hw_srcs);
+
+    /*
+     * TODO: when the pending bits of a virtual source are emulated, if
+     * domaincfg.IE is 1, a source this write has enabled which is pending
+     * has to get its MSI sent.
+     */
+
+    spin_unlock_irqrestore(&vaplic->lock, flags);
+}
+
+/* Emulate a write of @value to clrie[@word_idx]. */
+static void vaplic_clrie_write(const struct domain *d, unsigned int word_idx,
+                               uint32_t value)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    uint32_t hw_srcs = vaplic_hw_sources(d, word_idx);
+    uint32_t virt_srcs = vaplic_virtual_sources(d, word_idx);
+    unsigned long flags;
+
+    value &= hw_srcs | virt_srcs;
+    if ( !value )
+        return;
+
+    word_idx = array_index_nospec(word_idx, vaplic_nr_words(d));
+
+    spin_lock_irqsave(&vaplic->lock, flags);
+
+    /* While domaincfg.IE is 0, the h/w bits are clear already. */
+    if ( (value & hw_srcs) && (vaplic->regs.domaincfg & APLIC_DOMAINCFG_IE) )
+        aplic_hw_write_reg(offsetof(struct aplic_regs, clrie[word_idx]),
+                           value & hw_srcs);
+
+    write_atomic(&vaplic->regs.ie[word_idx],
+                 vaplic->regs.ie[word_idx] & ~value);
+
+    spin_unlock_irqrestore(&vaplic->lock, flags);
+}
+
+static uint32_t vaplic_domaincfg_read(const struct domain *d)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    unsigned long flags;
+    uint32_t val;
+
+    /*
+     * vaplic->lock makes the read atomic as a whole, against a write to
+     * domaincfg which changes IE and the h/w enable bits of the h/w sources.
+     */
+    spin_lock_irqsave(&vaplic->lock, flags);
+    val = vaplic->regs.domaincfg;
+    spin_unlock_irqrestore(&vaplic->lock, flags);
+
+    return val;
+}
+
+static void vaplic_domaincfg_write(const struct domain *d, uint32_t value)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    uint32_t domaincfg = APLIC_DOMAINCFG_RO | APLIC_DOMAINCFG_DM |
+                         (value & APLIC_DOMAINCFG_WMASK);
+    unsigned long flags;
+    unsigned int i;
+    uint32_t old;
+
+    spin_lock_irqsave(&vaplic->lock, flags);
+
+    old = vaplic->regs.domaincfg;
+    vaplic->regs.domaincfg = domaincfg;
+
+    /* Only a change of IE has anything to do with the h/w. */
+    if ( (old ^ domaincfg) & APLIC_DOMAINCFG_IE )
+    {
+        for ( i = 0; i < vaplic_nr_words(d); i++ )
+        {
+            uint32_t hw_srcs = vaplic_hw_sources(d, i);
+
+            if ( !hw_srcs )
+                continue;
+
+            if ( domaincfg & APLIC_DOMAINCFG_IE )
+                aplic_hw_write_reg(offsetof(struct aplic_regs, setie[i]),
+                                   vaplic->regs.ie[i] & hw_srcs);
+            else
+                aplic_hw_write_reg(offsetof(struct aplic_regs, clrie[i]),
+                                   hw_srcs);
+        }
+    }
+
+    /*
+     * TODO: when the pending bits of a virtual source are forwarded by MSI,
+     * setting IE has to get the MSI of each pending and enabled virtual
+     * source sent.
+     */
+
+    spin_unlock_irqrestore(&vaplic->lock, flags);
 }
 
 static uint32_t vaplic_genmsi_read(const struct domain *d)
@@ -320,7 +633,7 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
     const struct domain *currd = curr->domain;
     const struct vaplic *vaplic = to_vaplic(currd);
     const unsigned int offset = addr - vaplic->regs_start;
-    uint32_t auth_mask;
+    uint32_t hw_srcs;
     unsigned int i;
 
     ASSERT(curr == current);
@@ -328,7 +641,7 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
     switch ( offset )
     {
     case APLIC_DOMAINCFG:
-        *out = vaplic->regs.domaincfg;
+        *out = vaplic_domaincfg_read(currd);
 
         return true;
 
@@ -338,18 +651,23 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
          * is subtracted.
          */
         i = regoffset_to_word_idx(offset - APLIC_DOMAINCFG);
-        *out = vaplic_is_hw_source(currd, i) ? aplic_hw_read_reg(offset) : 0;
+        *out = vaplic_sourcecfg_read(currd, i);
 
         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);
+        hw_srcs = vaplic_hw_sources(currd, i);
 
         break;
 
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+        i = regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+        *out = vaplic_setie_read(currd, i);
+
+        return true;
+
     case APLIC_SETIPNUM:
     case APLIC_CLRIPNUM:
     case APLIC_SETIENUM:
@@ -410,7 +728,7 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
         return false;
     }
 
-    *out = aplic_hw_read_reg(offset) & auth_mask;
+    *out = aplic_hw_read_reg(offset) & hw_srcs;
 
     return true;
 }
@@ -427,50 +745,11 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
     switch ( offset )
     {
     case APLIC_DOMAINCFG:
-        /*
-         * TODO: domaincfg.IE isn't honoured: the h/w forwards the MSIs of the
-         * h/w sources whatever its value is. Linux as a guest sets IE before
-         * it enables any source and never clears it, so a write may set IE,
-         * but not clear it.
-         */
-        vaplic->regs.domaincfg |= value & APLIC_DOMAINCFG_WMASK;
+        vaplic_domaincfg_write(currd, value);
 
         return true;
 
     case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
-        /*
-         * vAPLIC is a leaf domain: it has no child domain a source could be
-         * delegated to. With D = 1, the low bits of the value would hold a
-         * Child Index rather than SM, and for a leaf domain the AIA spec
-         * makes such a write set the entire register to zero instead.
-         */
-        if ( value & APLIC_SOURCECFG_D )
-        {
-            gdprintk(XENLOG_DEBUG,
-                     "sourcecfg write with D set at offset %#x, zeroing it\n",
-                     offset);
-
-            value = 0;
-        }
-
-        /*
-         * SM is the only field left, the other bits are reserved and read as
-         * zero, so ignore what a guest writes to them.
-         */
-        value &= APLIC_SOURCECFG_SM;
-
-        /*
-         * 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
@@ -481,31 +760,55 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
          * It is necessary to calculate an interrupt number by subtracting
          * APLIC_DOMAINCFG instead of APLIC_SOURCECFG_BASE.
          */
-        if ( !vaplic_is_hw_source(currd,
-                                  regoffset_to_word_idx(offset -
-                                                        APLIC_DOMAINCFG)) )
-            /* Interrupt not enabled, ignore it */
+        vaplic_sourcecfg_write(currd,
+                               regoffset_to_word_idx(offset - APLIC_DOMAINCFG),
+                               value);
+
+        return true;
+
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+        vaplic_setie_write(currd,
+                           regoffset_to_word_idx(offset &
+                                                 APLIC_SETCLR_OFFSET_MASK),
+                           value);
+
+        return true;
+
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+        vaplic_clrie_write(currd,
+                           regoffset_to_word_idx(offset &
+                                                 APLIC_SETCLR_OFFSET_MASK),
+                           value);
+
+        return true;
+
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+        if ( !vaplic_is_assigned(currd, value) )
             return true;
 
-        break;
+        if ( offset == APLIC_SETIENUM )
+            vaplic_setie_write(currd, value / IRQS_PER_WORD,
+                               BIT(value % IRQS_PER_WORD, U));
+        else
+            vaplic_clrie_write(currd, value / IRQS_PER_WORD,
+                               BIT(value % IRQS_PER_WORD, U));
+
+        return true;
 
     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);
+        value &= vaplic_hw_sources(currd, word_idx);
 
         break;
     }
 
     case APLIC_SETIPNUM:
     case APLIC_CLRIPNUM:
-    case APLIC_SETIENUM:
-    case APLIC_CLRIENUM:
     case APLIC_SETIPNUM_LE:
         if ( !value || !vaplic_is_hw_source(currd, value) )
             return true;
@@ -544,18 +847,7 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
         return false;
     }
 
-    /*
-     * What is left is passed through to the h/w, which can affect only the
-     * h/w sources of currd:
-     *  - setip, clrip, setie and clrie are write-1-to-set/clear, and the
-     *    value was masked with currd's h/w sources above, so the bits of
-     *    the other sources are written as 0, which leaves them untouched;
-     *  - {set,clr}i{p,e}num, setipnum_le and sourcecfg[] name one source,
-     *    which was checked above to be a h/w source of currd.
-     * route_irq_to_guest() never assigns a source to more than one domain,
-     * or to both a domain and Xen, and as virq == pirq, no translation is
-     * needed either.
-     */
+    /* Passed through to the h/w, see vaplic_is_hw_source(). */
     aplic_hw_write_reg(offset, value);
 
     return true;
@@ -732,6 +1024,14 @@ int domain_vaplic_init(struct domain *d)
     for ( i = 0; i < d->arch.vintc->nr_virqs; i++ )
         spin_lock_init(&vaplic->regs.sources[i].lock);
 
+    vaplic->regs.ie = xvzalloc_array(uint32_t, vaplic_nr_words(d));
+    if ( !vaplic->regs.ie )
+    {
+        domain_vaplic_deinit(d);
+
+        return -ENOMEM;
+    }
+
     spin_lock_init(&vaplic->lock);
 
     vaplic->regs_start = GUEST_APLIC_S_BASE;
@@ -762,6 +1062,7 @@ void domain_vaplic_deinit(struct domain *d)
 
     vaplic = to_vaplic(d);
     d->arch.vintc = NULL;
+    xvfree(vaplic->regs.ie);
     xvfree(vaplic->regs.sources);
     xvfree(vaplic);
 }
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 40/42] xen/riscv: emulate target[] of virtual vAPLIC sources
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (38 preceding siblings ...)
  2026-11-13 15:49 ` [PATCH v4 39/42] xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE Oleksii Kurochko
@ 2026-11-13 15:49 ` Oleksii Kurochko
  2026-11-13 15:49 ` [PATCH v4 41/42] xen/riscv: emulate the pending bits and MSIs " Oleksii Kurochko
  2026-11-13 15:49 ` [PATCH v4 42/42] xen/riscv: drive the line of a virtual vAPLIC source Oleksii Kurochko
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:49 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

So far, target[] of a virtual source has read as zero and ignored
writes, like that of a source not assigned to the domain. Let it be
accessed like that of a h/w source: as it has no h/w register, only the
stored copy is updated.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/vaplic.c | 67 +++++++++++++++++++++--------------------
 1 file changed, 35 insertions(+), 32 deletions(-)

diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index edf9c5a3512a..e2995375a98a 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -32,8 +32,8 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 /*
  * Only a h/w source of a domain, one a h/w IRQ is routed to (see
  * vintc.hw_irqs), may be accessed in the h/w. A virtual source has nothing
- * there: its sourcecfg[] and its enable bit are emulated, and the rest of
- * its registers, until they are emulated too, read as zero and ignore
+ * there: its sourcecfg[], target[] and enable bit are emulated, and the rest
+ * of its registers, until they are emulated too, read as zero and ignore
  * writes, like those of a source not assigned to the domain.
  *
  * A write passed through to the h/w can thus affect only the h/w sources of
@@ -93,6 +93,7 @@ static bool vaplic_source_is_active(const struct domain *d, unsigned int irqn)
            APLIC_SOURCECFG_SM_INACTIVE;
 }
 
+/* Emulate a read of target[@irqn]. */
 static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
 {
     struct vaplic *vaplic = to_vaplic(d);
@@ -100,8 +101,8 @@ static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
     unsigned long flags;
     uint32_t val = 0;
 
-    /* target[0] doesn't exist so irqn == 0 should be impossible */
-    if ( !irqn || irqn >= vaplic->vintc.nr_virqs )
+    /* target[] of a source not assigned to @d is read-only zero. */
+    if ( !vaplic_is_assigned(d, irqn) )
         return 0;
 
     irqn = array_index_nospec(irqn, vaplic->vintc.nr_virqs);
@@ -127,12 +128,11 @@ static void vaplic_target_write(const struct domain *d, unsigned int irqn,
                                 uint32_t value)
 {
     struct vaplic *vaplic = to_vaplic(d);
-    struct vimsic_state *vimsic_state;
     const struct vcpu *target_vcpu;
     struct vaplic_source *src;
     unsigned long flags;
 
-    if ( !vaplic_is_hw_source(d, irqn) )
+    if ( !vaplic_is_assigned(d, irqn) )
         return;
 
     irqn = array_index_nospec(irqn, d->arch.vintc->nr_virqs);
@@ -154,38 +154,43 @@ static void vaplic_target_write(const struct domain *d, unsigned int irqn,
      * spec makes it read-only zero unless the domain's harts implement the
      * H extension, which a guest's harts don't. Bit 11 is reserved and reads
      * as zero, so only Hart Index and EIID are kept.
-     * What ends up in the h/w register is Xen's own value anyway:
-     * aplic_msi_target_gen() takes only EIID from it.
+     * What ends up in the h/w register of a h/w source is Xen's own value
+     * anyway: aplic_msi_target_gen() takes only EIID from it.
      */
     value &= APLIC_TARGET_HART_IDX | APLIC_TARGET_EIID;
 
     src = &vaplic->regs.sources[irqn];
-    vimsic_state = target_vcpu->arch.vimsic_state;
 
     spin_lock_irqsave(&src->lock, flags);
 
     write_atomic(&src->target, value);
 
-    /* IRQs are already off under src->lock. */
-    read_lock(&vimsic_state->vsfile_lock);
+    /* Only a h/w source has a h/w register to update. */
+    if ( vaplic_is_hw_source(d, irqn) )
+    {
+        struct vimsic_state *vimsic_state = target_vcpu->arch.vimsic_state;
 
-    /*
-     * The h/w register names the hart and the guest interrupt file MSIs are
-     * sent to, and there is none of either until the target vCPU is given a
-     * h/w guest interrupt file, so until then only the stored copy is
-     * updated. imsic_vsfile_attach() writes it to the h/w, through
-     * vaplic_reconfigure_target(), once there is such a file.
-     *
-     * TODO: once s/w guest interrupt files are supported, a vCPU using one
-     * still needs its MSIs, so the h/w register will have to be written for
-     * it too, pointing at an interrupt file Xen receives them in on the
-     * vCPU's behalf.
-     */
-    if ( vimsic_state->vsfile_cpu != CPU_NONE )
-        aplic_hw_write_reg(offsetof(struct aplic_regs, target[irqn - 1]),
-                           aplic_msi_target_gen(target_vcpu, value));
+        /* IRQs are already off under src->lock. */
+        read_lock(&vimsic_state->vsfile_lock);
+
+        /*
+         * The h/w register names the hart and the guest interrupt file MSIs
+         * are sent to, and there is none of either until the target vCPU is
+         * given a h/w guest interrupt file, so until then only the stored
+         * copy is updated. imsic_vsfile_attach() writes it to the h/w, through
+         * vaplic_reconfigure_target(), once there is such a file.
+         *
+         * TODO: once s/w guest interrupt files are supported, a vCPU using
+         * one still needs its MSIs, so the h/w register will have to be
+         * written for it too, pointing at an interrupt file Xen receives
+         * them in on the vCPU's behalf.
+         */
+        if ( vimsic_state->vsfile_cpu != CPU_NONE )
+            aplic_hw_write_reg(offsetof(struct aplic_regs, target[irqn - 1]),
+                               aplic_msi_target_gen(target_vcpu, value));
 
-    read_unlock(&vimsic_state->vsfile_lock);
+        read_unlock(&vimsic_state->vsfile_lock);
+    }
 
     spin_unlock_irqrestore(&src->lock, flags);
 }
@@ -408,10 +413,8 @@ static void vaplic_sourcecfg_write(const struct domain *d, unsigned int irqn,
     spin_unlock(&vaplic->lock);
 
     /*
-     * TODO: when the pending bit and target[] of a virtual source are
-     * emulated:
-     *  - making the source inactive has to clear the pending bit too, and
-     *    target[] has to read as zero while the source is inactive;
+     * TODO: when the pending bit of a virtual source is emulated:
+     *  - making the source inactive has to clear it too;
      *  - a write which leaves the source active may change its rectified
      *    input value, which may set its pending bit (or, for a
      *    level-sensitive source, clear it). If domaincfg.IE is 1, a source
@@ -712,7 +715,7 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
          */
         i = regoffset_to_word_idx(offset - APLIC_GENMSI);
 
-        *out = vaplic_is_hw_source(currd, i) ? vaplic_target_read(currd, i) : 0;
+        *out = vaplic_target_read(currd, i);
 
         return true;
 
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 41/42] xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC sources
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (39 preceding siblings ...)
  2026-11-13 15:49 ` [PATCH v4 40/42] xen/riscv: emulate target[] of virtual vAPLIC sources Oleksii Kurochko
@ 2026-11-13 15:49 ` Oleksii Kurochko
  2026-11-13 15:49 ` [PATCH v4 42/42] xen/riscv: drive the line of a virtual vAPLIC source Oleksii Kurochko
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:49 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

A virtual source, one which is reserved for a domain but which no h/w
IRQ is routed to, is the interrupt line of a device emulated by Xen. It
has nothing in the physical APLIC, so vAPLIC has to keep the state of
its registers and send its MSIs itself. Its sourcecfg[], enable bit and
target[] are emulated already, but its pending bit has so far read as
zero and ignored writes, and nothing has sent its MSIs.

So, following the AIA spec for MSI delivery mode, keep the pending bits
of the virtual sources in a new regs.ip[], and the level of their lines,
on which their rectified input values depend, in a new
vaplic_source.level, and send their MSIs from a new
vaplic_forward_msis(). The pending bits of the h/w sources aren't
copied, as the h/w changes them by itself.

Nothing changes vaplic_source.level yet: that is left as a TODO for the
emulators of devices with an interrupt line.

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/include/asm/vaplic.h |  16 ++
 xen/arch/riscv/vaplic.c             | 314 +++++++++++++++++++++++-----
 2 files changed, 275 insertions(+), 55 deletions(-)

diff --git a/xen/arch/riscv/include/asm/vaplic.h b/xen/arch/riscv/include/asm/vaplic.h
index e2e4611f69c2..f2c768e84b11 100644
--- a/xen/arch/riscv/include/asm/vaplic.h
+++ b/xen/arch/riscv/include/asm/vaplic.h
@@ -39,6 +39,15 @@ struct vaplic_source {
      *    guest changes.
      */
     uint32_t sourcecfg;
+
+    /*
+     * Level of the line of a virtual source, protected by vaplic->lock.
+     *
+     * TODO: nothing drives it yet. The emulator of a device with an interrupt
+     * line will have to, and to call vaplic_forward_msis() for a source a
+     * change of the level makes pending.
+     */
+    bool level;
 };
 
 struct vaplic_regs {
@@ -56,6 +65,13 @@ struct vaplic_regs {
      */
     uint32_t *ie;
 
+    /*
+     * Interrupt-pending bits of the virtual sources, a word per 32 sources.
+     * Those of the h/w sources change in the h/w by themselves, so they are
+     * read from the h/w instead.
+     */
+    uint32_t *ip;
+
     /*
      * Indexed by source number. The array holds d->arch.vintc->nr_virqs
      * elements; sources[0] is unused as APLIC interrupt sources start from 1.
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index e2995375a98a..ba0a867f6988 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -32,17 +32,14 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 /*
  * Only a h/w source of a domain, one a h/w IRQ is routed to (see
  * vintc.hw_irqs), may be accessed in the h/w. A virtual source has nothing
- * there: its sourcecfg[], target[] and enable bit are emulated, and the rest
- * of its registers, until they are emulated too, read as zero and ignore
- * writes, like those of a source not assigned to the domain.
+ * there: all its registers are emulated.
  *
  * A write passed through to the h/w can thus affect only the h/w sources of
- * the domain: a write to setip[], clrip[], setie[] or clrie[] is masked
+ * the domain: a write to setip[], in_clrip[], setie[] or clrie[] is masked
  * with them, which leaves the bits of the other sources at 0, i.e. untouched,
- * and {set,clr}ipnum, setipnum_le and sourcecfg[] name a source checked to
- * be one of them. route_irq_to_guest() never assigns a source to more than
- * one domain, or to both a domain and Xen, and as virq == pirq, no
- * translation is needed either.
+ * and sourcecfg[] names a source checked to be one of them.
+ * route_irq_to_guest() never assigns a source to more than one domain, or to
+ * both a domain and Xen, and as virq == pirq, no translation is needed either.
  */
 static bool vaplic_is_hw_source(const struct domain *d, unsigned int irqn)
 {
@@ -93,6 +90,37 @@ static bool vaplic_source_is_active(const struct domain *d, unsigned int irqn)
            APLIC_SOURCECFG_SM_INACTIVE;
 }
 
+/* Whether virtual source @src is level-sensitive. */
+static bool vaplic_is_level(const struct vaplic_source *src)
+{
+    unsigned int sm = MASK_EXTR(src->sourcecfg, APLIC_SOURCECFG_SM);
+
+    return (sm == APLIC_SOURCECFG_SM_LEVEL_HIGH) ||
+           (sm == APLIC_SOURCECFG_SM_LEVEL_LOW);
+}
+
+/*
+ * The rectified input value of virtual source @src: the level of its line,
+ * inverted for an Edge0 or Level0 source, and zero for an inactive or
+ * Detached one.
+ */
+static bool vaplic_rectified_input(const struct vaplic_source *src)
+{
+    switch ( MASK_EXTR(src->sourcecfg, APLIC_SOURCECFG_SM) )
+    {
+    case APLIC_SOURCECFG_SM_EDGE_RISE:
+    case APLIC_SOURCECFG_SM_LEVEL_HIGH:
+        return src->level;
+
+    case APLIC_SOURCECFG_SM_EDGE_FALL:
+    case APLIC_SOURCECFG_SM_LEVEL_LOW:
+        return !src->level;
+
+    default:
+        return false;
+    }
+}
+
 /* Emulate a read of target[@irqn]. */
 static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
 {
@@ -392,36 +420,102 @@ static void vaplic_sourcecfg_write(const struct domain *d, unsigned int irqn,
         value = APLIC_SOURCECFG_SM_INACTIVE;
 
     /*
-     * The enable bit of an inactive source is read-only zero, and stays zero
-     * when the source becomes active again, so making the source inactive
-     * clears it: the h/w does so for a h/w source, and the guest's view has
-     * to follow. vaplic->lock keeps a concurrent write to an enable register
-     * from setting the bit meanwhile: such a write sees either the source
-     * still active, and then its bit is cleared here afterwards, or the
-     * source inactive, and then it doesn't set the bit. IRQs are already off
-     * under src->lock.
+     * vaplic->lock keeps a concurrent write to an enable or pending register
+     * from setting a bit of the source while it is made inactive: such a
+     * write sees either the source still active, and then its bit is cleared
+     * below afterwards, or the source inactive, and then it doesn't set the
+     * bit. IRQs are already off under src->lock.
      */
     spin_lock(&vaplic->lock);
 
     write_atomic(&src->sourcecfg, value);
 
+    /*
+     * According to the AIA spec:
+     *   Whenever interrupt source i is inactive in an interrupt domain, the
+     *   corresponding interrupt-pending and interrupt-enable bits within the
+     *   domain are read-only zeros, [...]. If source i is changed from
+     *   inactive to an active mode, the interrupt source's pending and
+     *   enable bits remain zeros, unless set automatically [...].
+     *
+     * So making the source inactive clears them. For a h/w source, the h/w
+     * clears its own bits and regs.ie[] follows; regs.ip[] holds none of
+     * them.
+     */
     if ( !vaplic_source_is_active(d, irqn) )
+    {
         write_atomic(&vaplic->regs.ie[irqn / IRQS_PER_WORD],
                      vaplic->regs.ie[irqn / IRQS_PER_WORD] &
                      ~BIT(irqn % IRQS_PER_WORD, U));
+        vaplic->regs.ip[irqn / IRQS_PER_WORD] &= ~BIT(irqn % IRQS_PER_WORD, U);
+    }
+    /*
+     * The pending bit of a level-sensitive source is cleared whenever its
+     * rectified input value is low, which the new source mode may make it.
+     * The AIA spec permits a write to sourcecfg[] not to set the pending bit
+     * when the value is high under the new source mode, so it is left alone
+     * then. The h/w takes care of all that for a h/w source.
+     */
+    else if ( !vaplic_is_hw_source(d, irqn) && vaplic_is_level(src) &&
+              !vaplic_rectified_input(src) )
+        vaplic->regs.ip[irqn / IRQS_PER_WORD] &= ~BIT(irqn % IRQS_PER_WORD, U);
 
     spin_unlock(&vaplic->lock);
 
+    /* No MSI to send: this write can only clear the enable and pending bits. */
+
+    spin_unlock_irqrestore(&src->lock, flags);
+}
+
+/*
+ * Forward by MSI the pending and enabled virtual sources among @srcs, word
+ * @word_idx in the setip[] layout.
+ */
+static void vaplic_forward_msis(const struct domain *d, unsigned int word_idx,
+                                uint32_t srcs)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    uint32_t ready;
+
+    ASSERT(spin_is_locked(&vaplic->lock));
+
     /*
-     * TODO: when the pending bit of a virtual source is emulated:
-     *  - making the source inactive has to clear it too;
-     *  - a write which leaves the source active may change its rectified
-     *    input value, which may set its pending bit (or, for a
-     *    level-sensitive source, clear it). If domaincfg.IE is 1, a source
-     *    which is then pending and enabled has to get its MSI sent.
+     * According to the AIA spec:
+     *   An MSI is sent for a specific source only when the source's
+     *   corresponding pending and enable bits are both one and the IE field
+     *   of register domaincfg is also one.
      */
+    if ( !(vaplic->regs.domaincfg & APLIC_DOMAINCFG_IE) )
+        return;
 
-    spin_unlock_irqrestore(&src->lock, flags);
+    /* The h/w forwards the MSIs of the h/w sources by itself. */
+    ready = srcs & vaplic_virtual_sources(d, word_idx) &
+            vaplic->regs.ie[word_idx] & vaplic->regs.ip[word_idx];
+
+    for_each_set_bit ( bit, ready )
+    {
+        const struct vaplic_source *src =
+            &vaplic->regs.sources[word_idx * IRQS_PER_WORD + bit];
+        /*
+         * src->lock can't be taken under vaplic->lock (see the lock order in
+         * struct vaplic), so target is read without it, but only once, so
+         * that the hart index and the EIID come from the same value. An MSI
+         * racing with a write to target[] may reach the old target, which the
+         * AIA spec allows an APLIC too.
+         */
+        uint32_t target = read_atomic(&src->target);
+        const struct vcpu *v = vaplic_target_decode_vcpu(d, target);
+
+        if ( v )
+            vcpu_imsic_inject(v, MASK_EXTR(target, APLIC_TARGET_EIID));
+    }
+
+    /*
+     * According to the AIA spec:
+     *   If and when an MSI is sent, the source's interrupt pending bit is
+     *   cleared.
+     */
+    vaplic->regs.ip[word_idx] &= ~ready;
 }
 
 /* Emulate a read of setie[@word_idx]. */
@@ -471,11 +565,8 @@ static void vaplic_setie_write(const struct domain *d, unsigned int word_idx,
         aplic_hw_write_reg(offsetof(struct aplic_regs, setie[word_idx]),
                            value & hw_srcs);
 
-    /*
-     * TODO: when the pending bits of a virtual source are emulated, if
-     * domaincfg.IE is 1, a source this write has enabled which is pending
-     * has to get its MSI sent.
-     */
+    /* A pending virtual source this write has enabled gets its MSI now. */
+    vaplic_forward_msis(d, word_idx, value & ~hw_srcs);
 
     spin_unlock_irqrestore(&vaplic->lock, flags);
 }
@@ -537,15 +628,20 @@ static void vaplic_domaincfg_write(const struct domain *d, uint32_t value)
     spin_lock_irqsave(&vaplic->lock, flags);
 
     old = vaplic->regs.domaincfg;
+
+    /* vaplic_forward_msis() below has to see the new IE. */
     vaplic->regs.domaincfg = domaincfg;
 
-    /* Only a change of IE has anything to do with the h/w. */
+    /* Only a change of IE needs more than storing the new value. */
     if ( (old ^ domaincfg) & APLIC_DOMAINCFG_IE )
     {
         for ( i = 0; i < vaplic_nr_words(d); i++ )
         {
             uint32_t hw_srcs = vaplic_hw_sources(d, i);
 
+            /* The pending and enabled virtual sources get their MSIs now. */
+            vaplic_forward_msis(d, i, ~0U);
+
             if ( !hw_srcs )
                 continue;
 
@@ -558,11 +654,127 @@ static void vaplic_domaincfg_write(const struct domain *d, uint32_t value)
         }
     }
 
+    spin_unlock_irqrestore(&vaplic->lock, flags);
+}
+
+/*
+ * The bits of @srcs, virtual sources in setip[@word_idx], whose pending bits
+ * a write to setip[] can set.
+ */
+static uint32_t vaplic_pendable_sources(const struct domain *d,
+                                        unsigned int word_idx, uint32_t srcs)
+{
+    const struct vaplic *vaplic = to_vaplic(d);
+    uint32_t pendable = 0;
+
+    ASSERT(spin_is_locked(&vaplic->lock));
+
+    for_each_set_bit ( bit, srcs )
+    {
+        unsigned int irqn = word_idx * IRQS_PER_WORD + bit;
+        const struct vaplic_source *src = &vaplic->regs.sources[irqn];
+
+        /*
+         * The pending bit of an inactive source is read-only zero. For a
+         * level-sensitive one in MSI delivery mode, according to the AIA spec:
+         *   The pending bit may also be set by a relevant write to a setip or
+         *   setipnum register when the rectified input value is high, but not
+         *   when the rectified input value is low.
+         */
+        if ( vaplic_source_is_active(d, irqn) &&
+             (!vaplic_is_level(src) || vaplic_rectified_input(src)) )
+            pendable |= BIT(bit, U);
+    }
+
+    return pendable;
+}
+
+/*
+ * Emulate a read of setip[@word_idx] (@setip) or of in_clrip[@word_idx]: the
+ * pending bits or the rectified input values of the sources.
+ */
+static uint32_t vaplic_ip_read(const struct domain *d, unsigned int word_idx,
+                               bool setip)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    uint32_t hw_srcs = vaplic_hw_sources(d, word_idx);
+    uint32_t virt_srcs = vaplic_virtual_sources(d, word_idx);
+    unsigned long flags;
+    uint32_t val = 0;
+
+    if ( !hw_srcs && !virt_srcs )
+        return 0;
+
+    word_idx = array_index_nospec(word_idx, vaplic_nr_words(d));
+
     /*
-     * TODO: when the pending bits of a virtual source are forwarded by MSI,
-     * setting IE has to get the MSI of each pending and enabled virtual
-     * source sent.
+     * vaplic->lock makes the read atomic as a whole, against a write to
+     * setip[] or in_clrip[] which changes both kinds of bits.
      */
+    spin_lock_irqsave(&vaplic->lock, flags);
+
+    if ( hw_srcs )
+        val = aplic_hw_read_reg(setip ? offsetof(struct aplic_regs,
+                                                 setip[word_idx])
+                                      : offsetof(struct aplic_regs,
+                                                 in_clrip[word_idx])) &
+              hw_srcs;
+
+    if ( setip )
+        val |= vaplic->regs.ip[word_idx] & virt_srcs;
+    else
+    {
+        for_each_set_bit ( bit, virt_srcs )
+        {
+            const struct vaplic_source *src =
+                &vaplic->regs.sources[word_idx * IRQS_PER_WORD + bit];
+
+            if ( vaplic_rectified_input(src) )
+                val |= BIT(bit, U);
+        }
+    }
+
+    spin_unlock_irqrestore(&vaplic->lock, flags);
+
+    return val;
+}
+
+/*
+ * Emulate a write of @value to setip[@word_idx] (@setip) or to
+ * in_clrip[@word_idx].
+ */
+static void vaplic_ip_write(const struct domain *d, unsigned int word_idx,
+                            uint32_t value, bool setip)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    uint32_t hw_srcs = vaplic_hw_sources(d, word_idx);
+    uint32_t virt_srcs = vaplic_virtual_sources(d, word_idx);
+    unsigned long flags;
+
+    value &= hw_srcs | virt_srcs;
+    if ( !value )
+        return;
+
+    word_idx = array_index_nospec(word_idx, vaplic_nr_words(d));
+
+    spin_lock_irqsave(&vaplic->lock, flags);
+
+    if ( value & hw_srcs )
+        aplic_hw_write_reg(setip ? offsetof(struct aplic_regs, setip[word_idx])
+                                 : offsetof(struct aplic_regs,
+                                            in_clrip[word_idx]),
+                           value & hw_srcs);
+
+    if ( setip )
+    {
+        vaplic->regs.ip[word_idx] |=
+            vaplic_pendable_sources(d, word_idx, value & virt_srcs);
+
+        /* An enabled source this write has made pending gets its MSI now. */
+        vaplic_forward_msis(d, word_idx, value & virt_srcs);
+    }
+    else
+        vaplic->regs.ip[word_idx] &= ~(value & virt_srcs);
 
     spin_unlock_irqrestore(&vaplic->lock, flags);
 }
@@ -636,7 +848,6 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
     const struct domain *currd = curr->domain;
     const struct vaplic *vaplic = to_vaplic(currd);
     const unsigned int offset = addr - vaplic->regs_start;
-    uint32_t hw_srcs;
     unsigned int i;
 
     ASSERT(curr == current);
@@ -661,9 +872,9 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
     case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
     case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
         i = regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
-        hw_srcs = vaplic_hw_sources(currd, i);
+        *out = vaplic_ip_read(currd, i, offset <= APLIC_SETIP_LAST);
 
-        break;
+        return true;
 
     case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
         i = regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
@@ -730,10 +941,6 @@ static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
 
         return false;
     }
-
-    *out = aplic_hw_read_reg(offset) & hw_srcs;
-
-    return true;
 }
 
 static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
@@ -801,22 +1008,22 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
 
     case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
     case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
-    {
-        unsigned int word_idx =
-            regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+        vaplic_ip_write(currd,
+                        regoffset_to_word_idx(offset &
+                                              APLIC_SETCLR_OFFSET_MASK),
+                        value, offset <= APLIC_SETIP_LAST);
 
-        value &= vaplic_hw_sources(currd, word_idx);
-
-        break;
-    }
+        return true;
 
     case APLIC_SETIPNUM:
     case APLIC_CLRIPNUM:
     case APLIC_SETIPNUM_LE:
-        if ( !value || !vaplic_is_hw_source(currd, value) )
-            return true;
+        if ( vaplic_is_assigned(currd, value) )
+            vaplic_ip_write(currd, value / IRQS_PER_WORD,
+                            BIT(value % IRQS_PER_WORD, U),
+                            offset != APLIC_CLRIPNUM);
 
-        break;
+        return true;
 
     /* Not implemented by vAPLIC, see vaplic_emulate_load(). */
     case APLIC_MMSICFGADDR:
@@ -849,11 +1056,6 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
 
         return false;
     }
-
-    /* Passed through to the h/w, see vaplic_is_hw_source(). */
-    aplic_hw_write_reg(offset, value);
-
-    return true;
 }
 
 static int __init cf_check vaplic_make_domu_dt_node(struct kernel_info *kinfo)
@@ -1028,7 +1230,8 @@ int domain_vaplic_init(struct domain *d)
         spin_lock_init(&vaplic->regs.sources[i].lock);
 
     vaplic->regs.ie = xvzalloc_array(uint32_t, vaplic_nr_words(d));
-    if ( !vaplic->regs.ie )
+    vaplic->regs.ip = xvzalloc_array(uint32_t, vaplic_nr_words(d));
+    if ( !vaplic->regs.ie || !vaplic->regs.ip )
     {
         domain_vaplic_deinit(d);
 
@@ -1065,6 +1268,7 @@ void domain_vaplic_deinit(struct domain *d)
 
     vaplic = to_vaplic(d);
     d->arch.vintc = NULL;
+    xvfree(vaplic->regs.ip);
     xvfree(vaplic->regs.ie);
     xvfree(vaplic->regs.sources);
     xvfree(vaplic);
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* [PATCH v4 42/42] xen/riscv: drive the line of a virtual vAPLIC source
       [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
                   ` (40 preceding siblings ...)
  2026-11-13 15:49 ` [PATCH v4 41/42] xen/riscv: emulate the pending bits and MSIs " Oleksii Kurochko
@ 2026-11-13 15:49 ` Oleksii Kurochko
  41 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-13 15:49 UTC (permalink / raw)
  To: xen-devel
  Cc: Romain Caritey, Oleksii Kurochko, Alistair Francis,
	Baptiste Le Duc, Connor Davis, Andrew Cooper, Anthony PERARD,
	Michal Orzel, Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

The line of a virtual vAPLIC source is driven by the emulator of a device
in Xen, but nothing lets such an emulator do it yet: vaplic_source.level is
never set.

Introduce vintc_set_irq_level(), which an emulator calls whenever the level
of its interrupt line changes, and implement it for vAPLIC as a new
vintc_ops.set_irq_level callback.

vAPLIC supports MSI delivery mode only, where, according to the AIA spec, a
low-to-high transition of the rectified input value of a source makes it
pending, whether it is edge- or level-sensitive, and the pending bit of a
level-sensitive source is cleared whenever the value is low. A source made
pending and enabled gets its MSI right away, through vaplic_forward_msis().

Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
---
All the patches connected to virtual interrupts support for vAPLIC/vIMSIC
were tested on [1]. This branch is based on Denis M's framework which should
be soon sent to ML. Note that in [1] RISC-V is only draft version and
it has been ported in a quick way just to verify virtual interrupts are
working.

[1] https://gitlab.com/xen-project/people/olkur/xen/-/tree/riscv-vuart-support-wip?ref_type=heads
---
Changes in v4:
 - New patch.
---
---
 xen/arch/riscv/include/asm/intc.h   |  9 +++++
 xen/arch/riscv/include/asm/vaplic.h |  8 ++---
 xen/arch/riscv/intc.c               | 14 ++++++++
 xen/arch/riscv/vaplic.c             | 51 +++++++++++++++++++++++++++++
 4 files changed, 77 insertions(+), 5 deletions(-)

diff --git a/xen/arch/riscv/include/asm/intc.h b/xen/arch/riscv/include/asm/intc.h
index d188a45b3fe1..a332838bea17 100644
--- a/xen/arch/riscv/include/asm/intc.h
+++ b/xen/arch/riscv/include/asm/intc.h
@@ -8,6 +8,8 @@
 #ifndef RISCV_INTC_H
 #define RISCV_INTC_H
 
+#include <xen/types.h>
+
 struct dt_device_node;
 
 enum intc_variant {
@@ -79,6 +81,10 @@ struct vintc_ops {
      * guest.
      */
     void (*enter_guest)(struct vcpu *v);
+
+    /* Set the level of the line of a virtual source */
+    void (*set_irq_level)(const struct domain *d, unsigned int virq,
+                          bool level);
 };
 
 struct vintc {
@@ -114,4 +120,7 @@ void vintc_ctxt_switch_to(struct vcpu *n);
 
 void vintc_enter_guest(struct vcpu *v);
 
+void vintc_set_irq_level(const struct domain *d, unsigned int virq,
+                         bool level);
+
 #endif /* RISCV_INTC_H */
diff --git a/xen/arch/riscv/include/asm/vaplic.h b/xen/arch/riscv/include/asm/vaplic.h
index f2c768e84b11..1d5b9840be6c 100644
--- a/xen/arch/riscv/include/asm/vaplic.h
+++ b/xen/arch/riscv/include/asm/vaplic.h
@@ -41,11 +41,9 @@ struct vaplic_source {
     uint32_t sourcecfg;
 
     /*
-     * Level of the line of a virtual source, protected by vaplic->lock.
-     *
-     * TODO: nothing drives it yet. The emulator of a device with an interrupt
-     * line will have to, and to call vaplic_forward_msis() for a source a
-     * change of the level makes pending.
+     * Level of the line of a virtual source, as the emulator of the device
+     * in Xen drives it through vintc_set_irq_level(). Protected by
+     * vaplic->lock.
      */
     bool level;
 };
diff --git a/xen/arch/riscv/intc.c b/xen/arch/riscv/intc.c
index 449f6b252414..630c6d2ae730 100644
--- a/xen/arch/riscv/intc.c
+++ b/xen/arch/riscv/intc.c
@@ -224,3 +224,17 @@ void vintc_enter_guest(struct vcpu *v)
     if ( ops->enter_guest )
         ops->enter_guest(v);
 }
+
+/*
+ * Set the level of the line of virtual source @virq of @d. To be used by the
+ * emulator of a device in Xen, the line of which is connected to @virq: such
+ * a source has to be reserved with vintc_reserve_virq(), and no h/w IRQ may be
+ * routed to it.
+ */
+void vintc_set_irq_level(const struct domain *d, unsigned int virq,
+                         bool level)
+{
+    const struct vintc_ops *ops = d->arch.vintc->ops;
+
+    ops->set_irq_level(d, virq, level);
+}
diff --git a/xen/arch/riscv/vaplic.c b/xen/arch/riscv/vaplic.c
index ba0a867f6988..023f5116ec93 100644
--- a/xen/arch/riscv/vaplic.c
+++ b/xen/arch/riscv/vaplic.c
@@ -779,6 +779,56 @@ static void vaplic_ip_write(const struct domain *d, unsigned int word_idx,
     spin_unlock_irqrestore(&vaplic->lock, flags);
 }
 
+/*
+ * Set the level of the line of virtual source @virq of @d, as the emulator of
+ * the device in Xen driving it does.
+ */
+static void cf_check vaplic_set_irq_level(const struct domain *d,
+                                          unsigned int virq, bool level)
+{
+    struct vaplic *vaplic = to_vaplic(d);
+    struct vaplic_source *src;
+    unsigned int word_idx;
+    unsigned long flags;
+    uint32_t bit;
+    bool was_high;
+
+    /* Only a virtual source of @d has its line driven by an emulator. */
+    if ( !vaplic_is_assigned(d, virq) || vaplic_is_hw_source(d, virq) )
+    {
+        ASSERT_UNREACHABLE();
+        return;
+    }
+
+    virq = array_index_nospec(virq, d->arch.vintc->nr_virqs);
+    src = &vaplic->regs.sources[virq];
+    word_idx = virq / IRQS_PER_WORD;
+    bit = BIT(virq % IRQS_PER_WORD, U);
+
+    spin_lock_irqsave(&vaplic->lock, flags);
+
+    was_high = vaplic_rectified_input(src);
+    src->level = level;
+
+    /*
+     * According to the AIA spec, in MSI delivery mode a low-to-high
+     * transition of the rectified input value sets the pending bit of an
+     * edge- as well as of a level-sensitive source, and the pending bit of a
+     * level-sensitive one is cleared whenever the value is low. Neither
+     * happens to an inactive or a Detached source, whose rectified input
+     * value is always low.
+     */
+    if ( !was_high && vaplic_rectified_input(src) )
+        vaplic->regs.ip[word_idx] |= bit;
+    else if ( vaplic_is_level(src) && !vaplic_rectified_input(src) )
+        vaplic->regs.ip[word_idx] &= ~bit;
+
+    /* An enabled source the new level has made pending gets its MSI now. */
+    vaplic_forward_msis(d, word_idx, bit);
+
+    spin_unlock_irqrestore(&vaplic->lock, flags);
+}
+
 static uint32_t vaplic_genmsi_read(const struct domain *d)
 {
     /*
@@ -1189,6 +1239,7 @@ static const struct vintc_ops vintc_ops = {
      * by the vCPU itself. It moves it on its way to the guest instead.
      */
     .enter_guest = imsic_migrate_vcpu,
+    .set_irq_level = vaplic_set_irq_level,
 };
 
 int domain_vaplic_init(struct domain *d)
-- 
2.56.1



^ permalink raw reply related	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 02/42] xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64()
  2026-11-13 15:48 ` [PATCH v4 02/42] xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64() Oleksii Kurochko
@ 2026-11-18  9:50   ` Baptiste Le Duc
  2026-11-18 10:51     ` Jan Beulich
  0 siblings, 1 reply; 57+ messages in thread
From: Baptiste Le Duc @ 2026-11-18  9:50 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Baptiste Le Duc,
	Connor Davis, Andrew Cooper, Anthony PERARD, Michal Orzel,
	Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

On Fri, 13 Nov 2026 16:48:23 +0100, Oleksii Kurochko <oleksii.kurochko@gmail.com> wrote:
> csr_write64() uses its csr parameter both as an operand of ## (to form the
> name of the CSR holding the upper half on RV32) and in ordinary,
> macro-expanded context. As the CSR_* constants are macros themselves, this
> violates MISRA C Rule 20.12.
> 
> Make csr_write64() take the CSR name without the CSR_ prefix and paste the
> prefix as well, so that the parameter is used as an operand of ## only.
> 
> [...]

Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

-- 
Baptiste Le Duc <baptiste.le-duc@vates.tech>


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()
  2026-11-13 15:48 ` [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64() Oleksii Kurochko
@ 2026-11-18  9:50   ` Baptiste Le Duc
  2026-11-18 10:49     ` Jan Beulich
  0 siblings, 1 reply; 57+ messages in thread
From: Baptiste Le Duc @ 2026-11-18  9:50 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Baptiste Le Duc,
	Connor Davis, Andrew Cooper, Anthony PERARD, Michal Orzel,
	Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

> On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading
> the halves with two separate instructions isn't always safe: for a CSR
> which hardware increments, a carry from the low half into the high one can
> happen in between, 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.
> 
> Only CSRs which change under Xen's feet need that, hence the name. The
> majority can be read with a plain pair of csr_read()s, so no helper for
> those is introduced here as there would be no user for it.
> 
> 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.
> 
> No functional change on RV64.
> 
> Fixes: a541ddadec0a ("xen/riscv: introduce time.h")
> Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
> ---
> Changes in v4:
>  - Take the CSR name without the CSR_ prefix, so that the macro parameter
>    is used as an operand of ## only (MISRA C Rule 20.12).
>  - Drop the (void) of the ...H constant on RV64.
>  - Initialise hi_ in its declaration.

Jan gave his Reviewed-by on v3. It is gone in v4. Dropping it may be
fine given the macro rework, but please say so in the changelog :)

> [ ... 45 lines skipped ... ]
>  #else
>  #define csr_write64(name, val) csr_write(CSR_ ## name, val)
> +
> +#define csr_volatile_read64(name) csr_read(CSR_ ## name)

Nit: On v3 Jan suggested "#define csr_volatile_read64 csr_read64", and you
answered you would then move csr_read64() into this patch. In v4
csr_read64() still only comes with "xen/riscv: implement vCPU context
switching".

On RV64 I think it would read better like that:
#define csr_read64(name) csr_read(CSR_ ## name)
#define csr_volatile_read64(name) csr_read64(name)

Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

-- 
Baptiste Le Duc <baptiste.le-duc@vates.tech>


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()
  2026-11-18  9:50   ` Baptiste Le Duc
@ 2026-11-18 10:49     ` Jan Beulich
  2026-11-18 10:57       ` Jan Beulich
  0 siblings, 1 reply; 57+ messages in thread
From: Jan Beulich @ 2026-11-18 10:49 UTC (permalink / raw)
  To: Baptiste Le Duc, Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Julien Grall,
	Roger Pau Monné, Stefano Stabellini

On 18.11.2026 10:50, Baptiste Le Duc wrote:
>> On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading
>> the halves with two separate instructions isn't always safe: for a CSR
>> which hardware increments, a carry from the low half into the high one can
>> happen in between, 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.
>>
>> Only CSRs which change under Xen's feet need that, hence the name. The
>> majority can be read with a plain pair of csr_read()s, so no helper for
>> those is introduced here as there would be no user for it.
>>
>> 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.
>>
>> No functional change on RV64.
>>
>> Fixes: a541ddadec0a ("xen/riscv: introduce time.h")
>> Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
>> ---
>> Changes in v4:
>>  - Take the CSR name without the CSR_ prefix, so that the macro parameter
>>    is used as an operand of ## only (MISRA C Rule 20.12).
>>  - Drop the (void) of the ...H constant on RV64.
>>  - Initialise hi_ in its declaration.
> 
> Jan gave his Reviewed-by on v3. It is gone in v4. Dropping it may be
> fine given the macro rework, but please say so in the changelog :)
> 
>> [ ... 45 lines skipped ... ]
>>  #else
>>  #define csr_write64(name, val) csr_write(CSR_ ## name, val)
>> +
>> +#define csr_volatile_read64(name) csr_read(CSR_ ## name)
> 
> Nit: On v3 Jan suggested "#define csr_volatile_read64 csr_read64", and you
> answered you would then move csr_read64() into this patch. In v4
> csr_read64() still only comes with "xen/riscv: implement vCPU context
> switching".
> 
> On RV64 I think it would read better like that:
> #define csr_read64(name) csr_read(CSR_ ## name)
> #define csr_volatile_read64(name) csr_read64(name)

#define csr_read64(name) csr_read(CSR_ ## name)
#define csr_volatile_read64 csr_read64

i.e. matching what I suggested earlier. Otherwise what is passed into
csr_volatile_read64() would be macro-expanded before further
expanding csr_read64(), thus prepending CSR_ only to the result of
that expansion. (In the common case there'll be no difference, but
things can go wrong if some unexpected new #define appears.)

Jan


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 02/42] xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64()
  2026-11-18  9:50   ` Baptiste Le Duc
@ 2026-11-18 10:51     ` Jan Beulich
  0 siblings, 0 replies; 57+ messages in thread
From: Jan Beulich @ 2026-11-18 10:51 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Julien Grall,
	Roger Pau Monné, Stefano Stabellini, Baptiste Le Duc

On 18.11.2026 10:50, Baptiste Le Duc wrote:
> On Fri, 13 Nov 2026 16:48:23 +0100, Oleksii Kurochko <oleksii.kurochko@gmail.com> wrote:
>> csr_write64() uses its csr parameter both as an operand of ## (to form the
>> name of the CSR holding the upper half on RV32) and in ordinary,
>> macro-expanded context. As the CSR_* constants are macros themselves, this
>> violates MISRA C Rule 20.12.
>>
>> Make csr_write64() take the CSR name without the CSR_ prefix and paste the
>> prefix as well, so that the parameter is used as an operand of ## only.
>>
>> [...]
> 
> Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

Acked-by: Jan Beulich <jbeulich@suse.com>



^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()
  2026-11-18 10:49     ` Jan Beulich
@ 2026-11-18 10:57       ` Jan Beulich
  2026-11-25  8:48         ` Oleksii Kurochko
  0 siblings, 1 reply; 57+ messages in thread
From: Jan Beulich @ 2026-11-18 10:57 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Julien Grall,
	Roger Pau Monné, Stefano Stabellini, Baptiste Le Duc

On 18.11.2026 11:49, Jan Beulich wrote:
> On 18.11.2026 10:50, Baptiste Le Duc wrote:
>>> On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading
>>> the halves with two separate instructions isn't always safe: for a CSR
>>> which hardware increments, a carry from the low half into the high one can
>>> happen in between, 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.
>>>
>>> Only CSRs which change under Xen's feet need that, hence the name. The
>>> majority can be read with a plain pair of csr_read()s, so no helper for
>>> those is introduced here as there would be no user for it.
>>>
>>> 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.
>>>
>>> No functional change on RV64.
>>>
>>> Fixes: a541ddadec0a ("xen/riscv: introduce time.h")
>>> Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
>>> ---
>>> Changes in v4:
>>>  - Take the CSR name without the CSR_ prefix, so that the macro parameter
>>>    is used as an operand of ## only (MISRA C Rule 20.12).
>>>  - Drop the (void) of the ...H constant on RV64.
>>>  - Initialise hi_ in its declaration.
>>
>> Jan gave his Reviewed-by on v3. It is gone in v4. Dropping it may be
>> fine given the macro rework, but please say so in the changelog :)
>>
>>> [ ... 45 lines skipped ... ]
>>>  #else
>>>  #define csr_write64(name, val) csr_write(CSR_ ## name, val)
>>> +
>>> +#define csr_volatile_read64(name) csr_read(CSR_ ## name)
>>
>> Nit: On v3 Jan suggested "#define csr_volatile_read64 csr_read64", and you
>> answered you would then move csr_read64() into this patch. In v4
>> csr_read64() still only comes with "xen/riscv: implement vCPU context
>> switching".
>>
>> On RV64 I think it would read better like that:
>> #define csr_read64(name) csr_read(CSR_ ## name)
>> #define csr_volatile_read64(name) csr_read64(name)
> 
> #define csr_read64(name) csr_read(CSR_ ## name)
> #define csr_volatile_read64 csr_read64
> 
> i.e. matching what I suggested earlier. Otherwise what is passed into
> csr_volatile_read64() would be macro-expanded before further
> expanding csr_read64(), thus prepending CSR_ only to the result of
> that expansion. (In the common case there'll be no difference, but
> things can go wrong if some unexpected new #define appears.)

Oh, and - happy to fold this in while committing (perhaps with an adjustment
to subject and description), if you agree. With that
Acked-by: Jan Beulich <jbeulich@suse.com>

Jan


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()
  2026-11-18 10:57       ` Jan Beulich
@ 2026-11-25  8:48         ` Oleksii Kurochko
  0 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-25  8:48 UTC (permalink / raw)
  To: Jan Beulich
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Julien Grall,
	Roger Pau Monné, Stefano Stabellini, Baptiste Le Duc



On 11/18/26 11:57 AM, Jan Beulich wrote:
> On 18.11.2026 11:49, Jan Beulich wrote:
>> On 18.11.2026 10:50, Baptiste Le Duc wrote:
>>>> On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading
>>>> the halves with two separate instructions isn't always safe: for a CSR
>>>> which hardware increments, a carry from the low half into the high one can
>>>> happen in between, 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.
>>>>
>>>> Only CSRs which change under Xen's feet need that, hence the name. The
>>>> majority can be read with a plain pair of csr_read()s, so no helper for
>>>> those is introduced here as there would be no user for it.
>>>>
>>>> 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.
>>>>
>>>> No functional change on RV64.
>>>>
>>>> Fixes: a541ddadec0a ("xen/riscv: introduce time.h")
>>>> Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
>>>> ---
>>>> Changes in v4:
>>>>   - Take the CSR name without the CSR_ prefix, so that the macro parameter
>>>>     is used as an operand of ## only (MISRA C Rule 20.12).
>>>>   - Drop the (void) of the ...H constant on RV64.
>>>>   - Initialise hi_ in its declaration.
>>>
>>> Jan gave his Reviewed-by on v3. It is gone in v4. Dropping it may be
>>> fine given the macro rework, but please say so in the changelog :)
>>>
>>>> [ ... 45 lines skipped ... ]
>>>>   #else
>>>>   #define csr_write64(name, val) csr_write(CSR_ ## name, val)
>>>> +
>>>> +#define csr_volatile_read64(name) csr_read(CSR_ ## name)
>>>
>>> Nit: On v3 Jan suggested "#define csr_volatile_read64 csr_read64", and you
>>> answered you would then move csr_read64() into this patch. In v4
>>> csr_read64() still only comes with "xen/riscv: implement vCPU context
>>> switching".
>>>
>>> On RV64 I think it would read better like that:
>>> #define csr_read64(name) csr_read(CSR_ ## name)
>>> #define csr_volatile_read64(name) csr_read64(name)
>>
>> #define csr_read64(name) csr_read(CSR_ ## name)
>> #define csr_volatile_read64 csr_read64
>>
>> i.e. matching what I suggested earlier. Otherwise what is passed into
>> csr_volatile_read64() would be macro-expanded before further
>> expanding csr_read64(), thus prepending CSR_ only to the result of
>> that expansion. (In the common case there'll be no difference, but
>> things can go wrong if some unexpected new #define appears.)
> 
> Oh, and - happy to fold this in while committing (perhaps with an adjustment
> to subject and description), if you agree. With that
> Acked-by: Jan Beulich <jbeulich@suse.com>
Sorry, for the so long response.

I will be happy if it could be done while committing.

Thanks.

~ Oleksii


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register
  2026-11-13 15:48 ` [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register Oleksii Kurochko
@ 2026-11-27 15:23   ` Baptiste Le Duc
  2026-12-02  8:27     ` Oleksii Kurochko
  0 siblings, 1 reply; 57+ messages in thread
From: Baptiste Le Duc @ 2026-11-27 15:23 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Baptiste Le Duc,
	Connor Davis, Andrew Cooper, Anthony PERARD, Michal Orzel,
	Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

> aplic_init_hw_interrupts() initialises the IPRIO field of the target
> registers with APLIC_DEFAULT_PRIORITY, a constant private to aplic.c,
> whereas, since commit 60004aa6da75 ("xen/riscv: add missing APLIC
> register offsets, masks to asm/aplic.h"), the fields of each APLIC
> register and the values they take are defined in <asm/aplic.h>, right
> below the register's offset, as described at the top of that header.
> 
> Define APLIC_TARGET_IPRIO and APLIC_TARGET_IPRIO_DEFAULT there
> accordingly and use the latter instead of APLIC_DEFAULT_PRIORITY. As
> the layout of the target register depends on the delivery mode, and
> IPRIO overlaps with EIID, also note which fields exist in which mode.
> 
> No functional change.
> 
> Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>

Unlike v2, where the vAPLIC emulated direct delivery mode and used
it too, nothing in this series uses either macro outside of
aplic.c anymore. Is there a reason to move them beyond the header
convention?

> [ ... 10 lines skipped ... ]
> diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
> index 79bbc0e864..bffa29bb21 100644
> --- a/xen/arch/riscv/aplic.c
> +++ b/xen/arch/riscv/aplic.c
> @@ -28,8 +28,6 @@
>  #include <asm/io.h>
>  #include <asm/riscv_encoding.h>
>  
> -#define APLIC_DEFAULT_PRIORITY  1
> -
>  static struct aplic_priv aplic = {
>      .lock = SPIN_LOCK_UNLOCKED,
>  };
> @@ -58,9 +56,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);
>
Furthermore, is the write needed at all? sourcecfg[i] is set to 0
just above, i.e. D = 0 and SM = Inactive, and AIA 4.5.16 says: "If
interrupt source i is inactive in this domain, register target[i]
is read-only zero." So the write is ignored. Also, domaincfg.DM is
forced to 1 (MSI delivery mode) right after, where IPRIO does not
exist and the low bits are EIID. As Xen doesn't use direct delivery
mode, is a default priority needed at all? (Btw, a comment saying
that MSI mode is forced there would help.)

Wouldn't it be simpler to drop the write, the comment and
APLIC_TARGET_IPRIO{,_DEFAULT} instead of moving the constant?

Another question: is the clrie loop needed? Making a source inactive
already makes its enable bit read-only zero. If the intention is to
not have an interrupt fire before its sourcecfg[] is cleared, then
clearing domaincfg.IE first looks simpler. Something like:

@@ -222,21 +222,18 @@ static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
 
-    /* Disable all interrupts */
-    for ( i = 0; i < ARRAY_SIZE(aplic.regs->clrie); i++)
-        writel(~0U, &aplic.regs->clrie[i]);
+    /*
+     * Stop delivery so that no source left active by firmware can raise
+     * an interrupt while the sources are being made inactive.
+     */
+    writel(0, &aplic.regs->domaincfg);
 
-    /* Set interrupt type and default priority for all interrupts */
+    /*
+     * Make all sources inactive by writing 0 to sourcecfg[i]. Per the AIA
+     * spec, target[i] then becomes read-only zero.
+     */
     for ( i = 0; i < aplic_info.num_irqs; i++ )
-    {
         writel(0, &aplic.regs->sourcecfg[i]);
-        /*
-         * Low bits of target register contains Interrupt Priority bits which
-         * can't be zero according to AIA spec.
-         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
-         */
-        writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
-    }
 
     writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);
 }

-- 
Baptiste Le Duc <baptiste.le-duc@vates.tech>


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index()
  2026-11-13 15:48 ` [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index() Oleksii Kurochko
@ 2026-11-27 16:00   ` Baptiste Le Duc
  2026-11-30  8:40     ` Jan Beulich
  0 siblings, 1 reply; 57+ messages in thread
From: Baptiste Le Duc @ 2026-11-27 16:00 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Baptiste Le Duc,
	Connor Davis, Andrew Cooper, Anthony PERARD, Michal Orzel,
	Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

> [ ... 129 lines skipped ... ]
> +static unsigned long aplic_hart_index(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
Very small nit: too keep being consistant with above wording and with
the spec, it should be better to use "The Hart Index bits are...." to
not confuse with "h" again...

I think it doesn't need an extra version. Jan, if you acked this patch,
could you please do it while commiting?
Thanks in advance.

Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

-- 
Baptiste Le Duc <baptiste.le-duc@vates.tech>


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 06/42] xen/riscv: introduce CPU_NONE
  2026-11-13 15:48 ` [PATCH v4 06/42] xen/riscv: introduce CPU_NONE Oleksii Kurochko
@ 2026-11-27 16:08   ` Baptiste Le Duc
  2026-11-30  8:41     ` Jan Beulich
  0 siblings, 1 reply; 57+ messages in thread
From: Baptiste Le Duc @ 2026-11-27 16:08 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Baptiste Le Duc,
	Connor Davis, Andrew Cooper, Anthony PERARD, Michal Orzel,
	Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

On Fri, 13 Nov 2026 16:48:27 +0100, Oleksii Kurochko <oleksii.kurochko@gmail.com> wrote:
> Introduce CPU_NONE, a CPU number which doesn't identify any physical
> CPU, to be used wherever a pCPU has to be recorded but there may be
> none.
> 
> NR_CPUS has been used for that so far: hartid_to_cpuid() returns it for
> a hart Xen doesn't know, pcpu_info[] uses it for an entry whose
> processor_id isn't valid yet, and vsfile_cpu in struct vimsic_state,
> which records the pCPU whose h/w guest interrupt file backs the vCPU's
> IMSIC VS-file, uses it to mean that no h/w guest interrupt file is
> attached. NR_CPUS is however the number of possible CPUs, i.e. an upper
> bound, and a comparison against it reads like a range check rather than
> like a test for "no pCPU". Use CPU_NONE in all these places instead,
> which states that meaning explicitly.
> 
> [...]

Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

-- 
Baptiste Le Duc <baptiste.le-duc@vates.tech>


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 07/42] xen/riscv: introduce device-agnostic MMIO emulation dispatch
  2026-11-13 15:48 ` [PATCH v4 07/42] xen/riscv: introduce device-agnostic MMIO emulation dispatch Oleksii Kurochko
@ 2026-11-27 16:42   ` Baptiste Le Duc
  0 siblings, 0 replies; 57+ messages in thread
From: Baptiste Le Duc @ 2026-11-27 16:42 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Baptiste Le Duc,
	Connor Davis, Andrew Cooper, Anthony PERARD, Michal Orzel,
	Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

> [ ... 206 lines skipped ... ]
> --- /dev/null
> +++ b/xen/arch/riscv/mmio.c
> @@ -0,0 +1,205 @@
> +/* 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 <xen/xvmalloc.h>
> +
> +#include <asm/current.h>
> +#include <asm/mmio.h>
> +
> +#define MAX_IO_HANDLER  16
Nit: Only one blank is needed here.
> [ ... 70 lines skipped ... ]
> +/*
> + * 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.
> + */
Nit: As do_mmio() is non-static, this comment would better live on its
prototype in asm/mmio.h.
> [ ... 45 lines skipped ... ]
> +    /*
> +     * The array is kept sorted by base address, so rather than appending and
> +     * re-sorting, find the slot the new region belongs to and shift the tail
> +     * up by one.
> +     */
> +    for ( i = vmmio->num_entries;
> +          i > 0 && handlers[i - 1].addr > addr;
> +          i-- )
Nit: This fits on a single line.

Preferably with these adjusted:
Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

-- 
Baptiste Le Duc <baptiste.le-duc@vates.tech>


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index()
  2026-11-27 16:00   ` Baptiste Le Duc
@ 2026-11-30  8:40     ` Jan Beulich
  2026-11-30  9:25       ` Oleksii Kurochko
  0 siblings, 1 reply; 57+ messages in thread
From: Jan Beulich @ 2026-11-30  8:40 UTC (permalink / raw)
  To: Baptiste Le Duc, Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Julien Grall,
	Roger Pau Monné, Stefano Stabellini

On 27.11.2026 17:00, Baptiste Le Duc wrote:
>> [ ... 129 lines skipped ... ]
>> +static unsigned long aplic_hart_index(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
> Very small nit: too keep being consistant with above wording and with
> the spec, it should be better to use "The Hart Index bits are...." to
> not confuse with "h" again...
> 
> I think it doesn't need an extra version. Jan, if you acked this patch,
> could you please do it while commiting?

Sure, I can make that adjustment; it's not quite clear to me though where
the possible confusion lies. Oleksii, thoughts?

> Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

Acked-by: Jan Beulich <jbeulich@suse.com>

Jan


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 06/42] xen/riscv: introduce CPU_NONE
  2026-11-27 16:08   ` Baptiste Le Duc
@ 2026-11-30  8:41     ` Jan Beulich
  0 siblings, 0 replies; 57+ messages in thread
From: Jan Beulich @ 2026-11-30  8:41 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Julien Grall,
	Roger Pau Monné, Stefano Stabellini, Baptiste Le Duc

On 27.11.2026 17:08, Baptiste Le Duc wrote:
> On Fri, 13 Nov 2026 16:48:27 +0100, Oleksii Kurochko <oleksii.kurochko@gmail.com> wrote:
>> Introduce CPU_NONE, a CPU number which doesn't identify any physical
>> CPU, to be used wherever a pCPU has to be recorded but there may be
>> none.
>>
>> NR_CPUS has been used for that so far: hartid_to_cpuid() returns it for
>> a hart Xen doesn't know, pcpu_info[] uses it for an entry whose
>> processor_id isn't valid yet, and vsfile_cpu in struct vimsic_state,
>> which records the pCPU whose h/w guest interrupt file backs the vCPU's
>> IMSIC VS-file, uses it to mean that no h/w guest interrupt file is
>> attached. NR_CPUS is however the number of possible CPUs, i.e. an upper
>> bound, and a comparison against it reads like a range check rather than
>> like a test for "no pCPU". Use CPU_NONE in all these places instead,
>> which states that meaning explicitly.
>>
>> [...]
> 
> Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>

Acked-by: Jan Beulich <jbeulich@suse.com>



^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index()
  2026-11-30  8:40     ` Jan Beulich
@ 2026-11-30  9:25       ` Oleksii Kurochko
  0 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-11-30  9:25 UTC (permalink / raw)
  To: Jan Beulich, Baptiste Le Duc
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Julien Grall,
	Roger Pau Monné, Stefano Stabellini



On 11/30/26 9:40 AM, Jan Beulich wrote:
> On 27.11.2026 17:00, Baptiste Le Duc wrote:
>>> [ ... 129 lines skipped ... ]
>>> +static unsigned long aplic_hart_index(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
>> Very small nit: too keep being consistant with above wording and with
>> the spec, it should be better to use "The Hart Index bits are...." to
>> not confuse with "h" again...
>>
>> I think it doesn't need an extra version. Jan, if you acked this patch,
>> could you please do it while commiting?
> 
> Sure, I can make that adjustment; it's not quite clear to me though where
> the possible confusion lies. Oleksii, thoughts?

I will be happy with that!

> 
>> Reviewed-by: Baptiste Le Duc <baptiste.le-duc@vates.tech>
> 
> Acked-by: Jan Beulich <jbeulich@suse.com>

Thanks.

~ Oleksii


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 08/42] xen/riscv: distinguish h/w and virtual vINTC sources
  2026-11-13 15:48 ` [PATCH v4 08/42] xen/riscv: distinguish h/w and virtual vINTC sources Oleksii Kurochko
@ 2026-12-01 12:54   ` Baptiste Le Duc
  0 siblings, 0 replies; 57+ messages in thread
From: Baptiste Le Duc @ 2026-12-01 12:54 UTC (permalink / raw)
  To: Oleksii Kurochko
  Cc: xen-devel, Romain Caritey, Alistair Francis, Baptiste Le Duc,
	Connor Davis, Andrew Cooper, Anthony PERARD, Michal Orzel,
	Jan Beulich, Julien Grall, Roger Pau Monné,
	Stefano Stabellini

> A vIRQ of a domain's vINTC is either a h/w source, one a physical IRQ is
> routed to by route_irq_to_guest(), or a virtual source, whose line is
> driven by the emulator of a device in Xen and whose state exists in the
> vINTC only. used_irqs only tells that a vIRQ is taken, not which of the
> two it is, whereas they have to be told apart: only a h/w source has a
> physical IRQ to release when the domain goes away, and h/w registers to
> keep in line with the guest's view.
> 
> Track the h/w sources in a new hw_irqs bitmap, the subset of used_irqs
> a h/w IRQ is routed to. intc_route_irq_to_guest() sets the vIRQ's bit
> there, so it now takes the domain and the vIRQ, and
> domain_vintc_deinit() releases the h/w sources only.
> 
> An IRQ shared between devices is routed to the domain once per device,
> so vintc_reserve_virq() legitimately fails with -EEXIST for all but the
> first of them. map_irq_to_domain() now accepts -EEXIST only for a vIRQ
> which is a h/w source already, so that a vIRQ reserved for a virtual
> source can't be taken over by a h/w IRQ.
>

The commit message says what the patch adds, but not why used_irqs alone
isn't enough, so I had to dig into the diff and the notes below the ---
to understand why hw_irqs is needed.

It turns out that the two problems it fixes are latent: map_irq_to_domain()
routing a h/w IRQ to a vIRQ reserved for a virtual source, and
domain_vintc_deinit() calling release_guest_irq() on a virtual source.
Neither can happen in this series, as no virtual source is ever reserved:
map_irq_to_domain() is the only caller of vintc_reserve_virq(), up to the
end of the series, and vintc_set_irq_level() has no caller at all.

So the message should state both problems, and that they only show up
once a device emulator in Xen reserves a vIRQ. Alternatively, the
map_irq_to_domain() hunk could come together with the first such
emulator.

Suggested wording:

xen/riscv: distinguish h/w and virtual vINTC sources

A vIRQ of a domain's vINTC is either a h/w source, to which a physical
IRQ is routed by route_irq_to_guest(), or a virtual source, whose line
is driven by a device emulator in Xen and whose state lives in the vINTC
only. used_irqs only tells that a vIRQ is taken, not which of the two it
is, whereas they have to be told apart:

    - map_irq_to_domain() accepts -EEXIST from vintc_reserve_virq() and
      goes on calling route_irq_to_guest(). That is expected for an IRQ
      shared between h/w sources, but would be wrong for a vIRQ reserved for
      a virtual source, as the h/w IRQ would then get routed to it.

    - domain_vintc_deinit() calls release_guest_irq() for every vIRQ in
      used_irqs, which would include virtual sources, while they have no
      physical IRQ routed to them.

No virtual source is reserved yet, so it can't happen currently.
They will once a device emulator in Xen reserves a vIRQ.

Track the h/w sources in a new hw_irqs bitmap, the subset of used_irqs a
physical IRQ is routed to. intc_route_irq_to_guest() sets the bit, which
requires passing it the domain and the vIRQ, as hw_irqs is per-domain
and indexed by vIRQ. On -EEXIST, map_irq_to_domain() now goes on only if
the vIRQ is already a h/w source and fails if it is a virtual one, and
domain_vintc_deinit() releases h/w sources only.

Suggested wording:

xen/riscv: distinguish h/w and virtual vINTC sources

A vIRQ of a domain's vINTC is either a h/w source, to which a physical
IRQ is routed by route_irq_to_guest(), or a virtual source, whose line
is driven by a device emulator in Xen and whose state lives in the vINTC
only. used_irqs only tells that a vIRQ is taken, not which of the two it
is, whereas they have to be told apart:

    - map_irq_to_domain() accepts -EEXIST from vintc_reserve_virq() and
      goes on calling route_irq_to_guest(). That is expected for an IRQ
      shared between h/w sources, but would be wrong for a vIRQ reserved for
      a virtual source, as the h/w IRQ would then get routed to it.

    - domain_vintc_deinit() calls release_guest_irq() for every vIRQ in
      used_irqs, which would include virtual sources, while they have no
      physical IRQ routed to them.

No virtual source is reserved yet, so it can't happen currently.
They will once a device emulator in Xen reserves a vIRQ.

Track the h/w sources in a new hw_irqs bitmap, the subset of used_irqs a
physical IRQ is routed to. intc_route_irq_to_guest() sets the bit, which
requires passing it the domain and the vIRQ, as hw_irqs is per-domain
and indexed by vIRQ. On -EEXIST, map_irq_to_domain() now goes on only if
the vIRQ is already a h/w source and fails if it is a virtual one, and
domain_vintc_deinit() releases h/w sources only.

> [ ... 29 lines skipped ... ]
> @@ -25,14 +25,21 @@ int __overlay_init map_irq_to_domain(struct domain *d, unsigned int irq,
>      {
>          /*
>           * -EEXIST merely means that the IRQ has already been reserved, which
> -         * legitimately happens when the IRQ is shared between devices. Any
> -         * other failure has to be fatal: the IRQ would otherwise be routed to
> -         * the domain without domain_vintc_deinit() ever releasing it again.
> +         * legitimately happens when the IRQ is shared between devices: the
> +         * vIRQ is then a h/w source already, route_irq_to_guest() having
> +         * connected it to the IRQ for the first of them. A vIRQ reserved for
> +         * a virtual source, whose line an emulator in Xen drives, mustn't be
> +         * taken over by a h/w IRQ, though. Any other failure has to be fatal
> +         * too: the IRQ would otherwise be routed to the domain without
> +         * domain_vintc_deinit() ever releasing it again.
>           */
The wording implicitly says "-EEXIST means the vIRQ is a h/w source",
while what you mean (and what the check below does) is "-EEXIST on a vIRQ
which is a h/w source already means the IRQ was mapped for an earlier
device".

Suggested rewording:

/*
 * An IRQ shared between devices is mapped once per device: for the first
 * of them, vintc_reserve_virq() reserved the vIRQ and route_irq_to_guest()
 * connected it to the IRQ, so for the next ones -EEXIST on a h/w source is
 * expected and harmless. A vIRQ reserved for a virtual source, whose line
 * an emulator in Xen drives, mustn't be taken over by a h/w IRQ, though.
 * Any other failure has to be fatal too: the IRQ would otherwise be routed
 * to the domain without domain_vintc_deinit() ever releasing it again.
 */

-- 
Baptiste Le Duc <baptiste.le-duc@vates.tech>


^ permalink raw reply	[flat|nested] 57+ messages in thread

* Re: [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register
  2026-11-27 15:23   ` Baptiste Le Duc
@ 2026-12-02  8:27     ` Oleksii Kurochko
  0 siblings, 0 replies; 57+ messages in thread
From: Oleksii Kurochko @ 2026-12-02  8:27 UTC (permalink / raw)
  To: Baptiste Le Duc
  Cc: xen-devel, Romain Caritey, Alistair Francis, Connor Davis,
	Andrew Cooper, Anthony PERARD, Michal Orzel, Jan Beulich,
	Julien Grall, Roger Pau Monné, Stefano Stabellini



On 11/27/26 4:23 PM, Baptiste Le Duc wrote:
>> aplic_init_hw_interrupts() initialises the IPRIO field of the target
>> registers with APLIC_DEFAULT_PRIORITY, a constant private to aplic.c,
>> whereas, since commit 60004aa6da75 ("xen/riscv: add missing APLIC
>> register offsets, masks to asm/aplic.h"), the fields of each APLIC
>> register and the values they take are defined in <asm/aplic.h>, right
>> below the register's offset, as described at the top of that header.
>>
>> Define APLIC_TARGET_IPRIO and APLIC_TARGET_IPRIO_DEFAULT there
>> accordingly and use the latter instead of APLIC_DEFAULT_PRIORITY. As
>> the layout of the target register depends on the delivery mode, and
>> IPRIO overlaps with EIID, also note which fields exist in which mode.
>>
>> No functional change.
>>
>> Signed-off-by: Oleksii Kurochko <oleksii.kurochko@gmail.com>
> 
> Unlike v2, where the vAPLIC emulated direct delivery mode and used
> it too, nothing in this series uses either macro outside of
> aplic.c anymore. Is there a reason to move them beyond the header
> convention?

Probably, it isn't. Lets keep it in *.c file while it won't be a really 
sense to move it to header.

> 
>> [ ... 10 lines skipped ... ]
>> diff --git a/xen/arch/riscv/aplic.c b/xen/arch/riscv/aplic.c
>> index 79bbc0e864..bffa29bb21 100644
>> --- a/xen/arch/riscv/aplic.c
>> +++ b/xen/arch/riscv/aplic.c
>> @@ -28,8 +28,6 @@
>>   #include <asm/io.h>
>>   #include <asm/riscv_encoding.h>
>>   
>> -#define APLIC_DEFAULT_PRIORITY  1
>> -
>>   static struct aplic_priv aplic = {
>>       .lock = SPIN_LOCK_UNLOCKED,
>>   };
>> @@ -58,9 +56,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);
>>
> Furthermore, is the write needed at all? sourcecfg[i] is set to 0
> just above, i.e. D = 0 and SM = Inactive, and AIA 4.5.16 says: "If
> interrupt source i is inactive in this domain, register target[i]
> is read-only zero." So the write is ignored. Also, domaincfg.DM is
> forced to 1 (MSI delivery mode) right after, where IPRIO does not
> exist and the low bits are EIID. As Xen doesn't use direct delivery
> mode, is a default priority needed at all? (Btw, a comment saying
> that MSI mode is forced there would help.)
> 
> Wouldn't it be simpler to drop the write, the comment and
> APLIC_TARGET_IPRIO{,_DEFAULT} instead of moving the constant?

I thought about that. It would be really simpler. So lets drop it + ...

> 
> Another question: is the clrie loop needed? Making a source inactive
> already makes its enable bit read-only zero. If the intention is to
> not have an interrupt fire before its sourcecfg[] is cleared, then
> clearing domaincfg.IE first looks simpler. Something like:
> 
> @@ -222,21 +222,18 @@ static void __init aplic_init_hw_interrupts(void)
>   {
>       unsigned int i;
>   
> -    /* Disable all interrupts */
> -    for ( i = 0; i < ARRAY_SIZE(aplic.regs->clrie); i++)
> -        writel(~0U, &aplic.regs->clrie[i]);
> +    /*
> +     * Stop delivery so that no source left active by firmware can raise
> +     * an interrupt while the sources are being made inactive.
> +     */
> +    writel(0, &aplic.regs->domaincfg);
>   
> -    /* Set interrupt type and default priority for all interrupts */
> +    /*
> +     * Make all sources inactive by writing 0 to sourcecfg[i]. Per the AIA
> +     * spec, target[i] then becomes read-only zero.
> +     */
>       for ( i = 0; i < aplic_info.num_irqs; i++ )
> -    {
>           writel(0, &aplic.regs->sourcecfg[i]);
> -        /*
> -         * Low bits of target register contains Interrupt Priority bits which
> -         * can't be zero according to AIA spec.
> -         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
> -         */
> -        writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
> -    }
>   
>       writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);
>   }
> 

... apply this suggestion.

I will send a separate patch outside of this patch series as it doesn't 
affect the work of virtual interrupt controller at all.

Thanks.

~ Oleksii


^ permalink raw reply	[flat|nested] 57+ messages in thread

end of thread, other threads:[~2026-12-02  8:28 UTC | newest]

Thread overview: 57+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
     [not found] <cover.1794562488.git.oleksii.kurochko@gmail.com>
2026-11-13 15:48 ` [PATCH v4 01/42] xen/riscv: add helper to check APLIC MSI mode Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 02/42] xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64() Oleksii Kurochko
2026-11-18  9:50   ` Baptiste Le Duc
2026-11-18 10:51     ` Jan Beulich
2026-11-13 15:48 ` [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64() Oleksii Kurochko
2026-11-18  9:50   ` Baptiste Le Duc
2026-11-18 10:49     ` Jan Beulich
2026-11-18 10:57       ` Jan Beulich
2026-11-25  8:48         ` Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register Oleksii Kurochko
2026-11-27 15:23   ` Baptiste Le Duc
2026-12-02  8:27     ` Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index() Oleksii Kurochko
2026-11-27 16:00   ` Baptiste Le Duc
2026-11-30  8:40     ` Jan Beulich
2026-11-30  9:25       ` Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 06/42] xen/riscv: introduce CPU_NONE Oleksii Kurochko
2026-11-27 16:08   ` Baptiste Le Duc
2026-11-30  8:41     ` Jan Beulich
2026-11-13 15:48 ` [PATCH v4 07/42] xen/riscv: introduce device-agnostic MMIO emulation dispatch Oleksii Kurochko
2026-11-27 16:42   ` Baptiste Le Duc
2026-11-13 15:48 ` [PATCH v4 08/42] xen/riscv: distinguish h/w and virtual vINTC sources Oleksii Kurochko
2026-12-01 12:54   ` Baptiste Le Duc
2026-11-13 15:48 ` [PATCH v4 09/42] xen/riscv: implement virtual APLIC MMIO emulation Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 10/42] xen/riscv: leave the h/w source of an IRQ routed to a guest inactive Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 11/42] xen/riscv: implement vCPU context switching Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 12/42] xen/riscv: save and restore vsiselect on vCPU context switch Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 13/42] xen/riscv: introduce vintc_ctxt_switch_{from,to}() Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 14/42] xen/riscv: extend exception tables with type and data fields Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 15/42] xen/riscv: add guest page fault handling stub Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 16/42] xen/riscv: implement trap redirection to a guest Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 17/42] xen/riscv: detect Shtvala Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 18/42] xen/riscv: resolve the faulting guest physical address Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 19/42] xen/riscv: add guest memory read helper Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 20/42] xen/riscv: add helpers for decoding a trapped load or store Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 21/42] xen/riscv: add guest load emulation for trapped MMIO accesses Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 22/42] xen/riscv: add guest store " Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 23/42] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 24/42] xen/riscv: implement continue_new_vcpu() Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 25/42] xen/riscv: add basic VGEIN management for AIA guests Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 26/42] xen/riscv: map IMSIC interrupt file for vCPUs Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 27/42] xen/riscv: introduce vaplic_reconfigure_target() Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 28/42] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 29/42] xen/riscv: wake up a descheduled vCPU on a guest external interrupt Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 30/42] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 31/42] xen/riscv: introduce imsic_migrate_vcpu() Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 32/42] xen/riscv: remap interrupts to new IMSIC VS-file Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 33/42] xen/riscv: save and clear the old IMSIC VS-file on vCPU migration Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 34/42] xen/riscv: restore register state in the new IMSIC VS-file Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 35/42] xen/riscv: move a vCPU's guest interrupt file on its way to the guest Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 36/42] xen/riscv: send MSIs to a vCPU's guest interrupt file Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 37/42] xen/riscv: sync with IMSIC VS-file injections on vCPU migration Oleksii Kurochko
2026-11-13 15:48 ` [PATCH v4 38/42] xen/riscv: emulate the vAPLIC genmsi register Oleksii Kurochko
2026-11-13 15:49 ` [PATCH v4 39/42] xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE Oleksii Kurochko
2026-11-13 15:49 ` [PATCH v4 40/42] xen/riscv: emulate target[] of virtual vAPLIC sources Oleksii Kurochko
2026-11-13 15:49 ` [PATCH v4 41/42] xen/riscv: emulate the pending bits and MSIs " Oleksii Kurochko
2026-11-13 15:49 ` [PATCH v4 42/42] xen/riscv: drive the line of a virtual vAPLIC source Oleksii Kurochko

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.