Skip to contentSkip to conversation

virtual interrupt controller (vAPLIC/vIMSIC) support

PATCH Superseded Oleksii Kurochko 3 participants 152 messages Sep 30 – Nov 12 1 message not in the archive RISC-V Page 2 of 2

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#111 lore raw

Re: [PATCH v3 29/39] xen/riscv: prepare new IMSIC VS-file

In reply to Oleksii Kurochko

xen/arch/riscv/aia.c line 7

Quoted 13 lines

[ ... 64 lines skipped ... ]

xen/arch/riscv/aia.c +2 -0
index e31c9c2d24..229ab4b867 100644
@@ -1,8 +1,10 @@
 /* SPDX-License-Identifier: GPL-2.0-only */
 
+#include <xen/bug.h>
 #include <xen/errno.h>
 #include <xen/init.h>
 #include <xen/sections.h>
+#include <xen/sched.h>

Nit: Why xen/sched.h? The stub doesn't dereference v, and asm/aia.h already forward-declares struct vcpu. If it stays: sched < sections, so it goes one line up.

Quoted 45 lines

[ ... 30 lines skipped ... ]

xen/arch/riscv/aia.c +44 -0
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, c);    \
+    csr_write(CSR_VSIREG, v);       \
+} while (0)
+
+/*
+ * Leaf macros for the switchcase expansion pyramid below:
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg, v); break"
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Extra args (e.g. an operation and/or a value) are forwarded to F via
+ * __VA_ARGS__.
+ */
+#define imsic_switchcase_2(F, ireg, ...)             \
+    F((ireg) + 0, __VA_ARGS__);                      \
+    F((ireg) + 1, __VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)             \
+    imsic_switchcase_2(F, (ireg) + 0, __VA_ARGS__);  \
+    imsic_switchcase_2(F, (ireg) + 2, __VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)             \
+    imsic_switchcase_4(F, (ireg) + 0, __VA_ARGS__);  \
+    imsic_switchcase_4(F, (ireg) + 4, __VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)            \
+    imsic_switchcase_8(F, (ireg) + 0, __VA_ARGS__);  \
+    imsic_switchcase_8(F, (ireg) + 8, __VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)            \
+    imsic_switchcase_16(F, (ireg) + 0, __VA_ARGS__); \
+    imsic_switchcase_16(F, (ireg) + 16, __VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)            \
+    imsic_switchcase_32(F, (ireg) + 0, __VA_ARGS__); \
+    imsic_switchcase_32(F, (ireg) + 32, __VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {

xen/arch/riscv/aia.c

Quoted 10 lines
xen/arch/riscv/aia.c +10 -0
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val);
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val);
+    default:
+        ASSERT_UNREACHABLE();
+        break;
+    }
+}
+

What does the switch buy? ireg only ends up as the value written to vsiselect, not as a CSR number, so it doesn't need to be a compile-time constant. imsic_vs_csr_write(ireg, val) does the same, without the 128 case labels and the macro pyramid. If there's a reason, it wants stating in a comment; otherwise please drop the pyramid (an ASSERT() on the range can stay if you want one).

Typo (only if the macros stay): "Leaf macros" - there's only one here. And case ireg: / op(ireg, v) as well as c and v in imsic_vs_csr_write() want parenthesizing (MISRA 20.7).

xen/arch/riscv/aia.c

Quoted 8 lines

[ ... 67 lines skipped ... ]

xen/arch/riscv/aia.c +7 -0
+static void cf_check imsic_vsfile_local_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */

Typo: s/a IMSIC/an IMSIC/

Quoted 16 lines

[ ... 31 lines skipped ... ]
void imsic_migrate_vcpu(struct vcpu *v)
{

xen/arch/riscv/aia.c +6 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = imsic_cfg.nr_eix,
+    };
+
     /*
      * The scheduler can mark a freshly created vCPU's unit as migrated and
      * invoke this before the vCPU has ever run (see the migrated branch in
@@ -703,5 +849,18 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == CPU_NONE )
         return;
 
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC

xen/arch/riscv/aia.c void imsic_migrate_vcpu(struct vcpu *v) · line 863

Quoted 10 lines
xen/arch/riscv/aia.c +10 -0
+     * VS-file.
+     */
+
+    vsfile_data.hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!vsfile_data.hgei);
+
+    /* Zero-out new IMSIC VS-file */
+    imsic_call_on_cpu(v->processor, imsic_vsfile_local_clear, &vsfile_data);

Nit: The comment restates the call; drop it.

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

Re: [PATCH v3 30/39] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration

In reply to Oleksii Kurochko
Quoted 343 lines · Oleksii Kurochko
Quoted 245 lines · Oleksii Kurochko

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.

Migration doesn't use the barrier at this stage, so imsic_migrate_vcpu() only references imsic_aplic_sync() to keep the compiler from complaining about it being unused.

---
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             | 33 +++++++++++++++++++
  xen/arch/riscv/imsic.c             | 52 ++++++++++++++++++++++++++++++
  xen/arch/riscv/include/asm/aplic.h |  3 ++
  xen/arch/riscv/include/asm/imsic.h |  8 +++++
  4 files changed, 96 insertions(+)
xen/arch/riscv/aplic.c +33 -0
index 283e5d6046a6..5f9a894b5a76 100644
@@ -27,7 +27,9 @@
  #include <asm/imsic.h>
  #include <asm/intc.h>
  #include <asm/io.h>
+#include <asm/processor.h>
  #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
 
  static struct aplic_priv aplic = {
      .lock = SPIN_LOCK_UNLOCKED,
@@ -183,6 +185,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;
+
+    /*
+     * sync_id is nr_ids, which imsic_parse_node() limits to IMSIC_MAX_ID,
+     * so it always fits into the EIID field.
+     */
+    BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
+    ASSERT(imsic->sync_id <= IMSIC_MAX_ID);
+
+    val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
+          imsic->sync_id;
+
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
  static void __init aplic_init_hw_interrupts(void)
  {
      unsigned int i;
xen/arch/riscv/imsic.c +52 -0
index f1e44dc56bb8..8e0273eab902 100644
@@ -27,6 +27,7 @@
  #include <xen/xvmalloc.h>
 
  #include <asm/aia.h>
+#include <asm/aplic.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)       \
+({                              \
+    csr_write(CSR_SISELECT, c); \
+    csr_read(CSR_SIREG);        \
+})
+
  #define imsic_csr_write(c, v)   \
  do {                            \
      csr_write(CSR_SISELECT, c); \
@@ -203,6 +210,15 @@ void imsic_irq_enable(unsigned int irq)
       */
      ASSERT(!local_irq_is_enabled());
 
+    if ( irq == imsic_cfg.sync_id )
+    {
+        printk(XENLOG_WARNING
+               "irq%u is reserved for APLIC sync so shouldn't be set by %s\n",
+               irq, __func__);
+
+        return;
+    }
+
      spin_lock(&imsic_cfg.lock);
      /*
       * There is no irq - 1 here (look at aplic_set_irq_type()) because:
@@ -241,6 +257,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)
  {
@@ -387,6 +412,9 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
 
      imsic_cfg.nr_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1, 64);
 
+    /* Reserve last identity for APLIC-to-hart synchronization */
+    imsic_cfg.sync_id = imsic_cfg.nr_ids;
+
      /* Compute base address */
      *nr_mmios = 0;
      rc = dt_device_get_address(node, *nr_mmios, &base_addr, NULL);
@@ -497,6 +525,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *unused)
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
  static void cf_check imsic_vsfile_local_clear(void *data)
  {
      unsigned int i;
@@ -862,5 +911,8 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(v->processor, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Avoid an unused-function error until the barrier has a user. */
+    (void)imsic_aplic_sync;
+
      BUG_ON("unimplemented");
  }
xen/arch/riscv/include/asm/aplic.h +3 -0
index 9018936ca95a..bfb510b2ae5e 100644
@@ -94,6 +94,7 @@
  #define APLIC_SETIPNUM_LE               0x2000
 
  #define APLIC_GENMSI                    0x3000
+#define APLIC_GENMSI_BUSY               BIT(12, U)
 
  #define APLIC_TARGET_BASE               0x3004
  #define APLIC_TARGET_LAST               0x3ffc
@@ -177,4 +178,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 /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +1 -0
index 8130d125f5c3..f86407e21765 100644
@@ -62,6 +62,14 @@ struct imsic_config {
       */
      unsigned int nr_eix;
 
+    /*

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

Quoted 10 lines
xen/arch/riscv/include/asm/imsic.h +7 -0
+     * Interrupt identity reserved exclusively for APLIC-to-hart
+     * synchronization.
+     *
+     * Must not be allocated to any interrupt source.
+     */
+    unsigned int sync_id;
+
      /* MSI */
      const struct imsic_msi *msi;
 

I think it also makes sense here to apply the following fixup patch:

commit db57e94ed8405c98d7a21f4f88764fa5e0ea2d04
(riscv-next-upstreaming-fixups)

Author: Oleksii Kurochko <[email protected]>
Date:   Tue Oct 6 15:59:52 2026 +0200

fixup! xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU
migration

In MSI delivery mode the MSI of APLIC source N carries identity N, by which Xen recognises it in its own IMSIC interrupt file. A source numbered sync_id or higher can't be told apart: its identity either isn't implemented, so its MSIs are dropped, or is the one reserved for the sync barrier, which it would satisfy early and whose pending bit would swallow its interrupt. Limit the usable sources to those below sync_id, and document how the identities of Xen's interrupt file are allocated.

xen/arch/riscv/aplic.c +3 -0
index 96aa4edb3958..86ff3cae984d 100644
@@ -246,6 +246,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 */
@@ -270,6 +271,22 @@ static int __init cf_check aplic_init(void)
          panic("%s: failed to get number of interrupt sources\n",
                node->full_name);
 
+    /*
+     * In MSI delivery mode the MSI of source N carries identity N, by 

which

xen/arch/riscv/aplic.c +2 -0
+     * Xen recognises it in its own IMSIC interrupt file. Hence the sources
+     * numbered from sync_id on can't be used: their identities either 

aren't
+ * implemented or are the one reserved for the APLIC-IMSIC sync
barrier.

xen/arch/riscv/aplic.c +6 -0
+     */
+    imsic = imsic_get_config();
+    if ( aplic_info.num_irqs >= imsic->sync_id )
+    {
+        printk(XENLOG_WARNING
+               "%s: only %u of %u interrupt sources usable with %u 

IMSIC identities\n",

xen/arch/riscv/aplic.c +5 -0
+               node->full_name, imsic->sync_id - 1, aplic_info.num_irqs,
+               imsic->nr_ids);
+        aplic_info.num_irqs = imsic->sync_id - 1;
+    }
+
      guest_aplic_num_sources = min(GUEST_APLIC_MAX_SOURCES, 

aplic_info.num_irqs);

      if ( aplic_info.num_irqs > ARRAY_SIZE(aplic.regs->sourcecfg) )
xen/arch/riscv/imsic.c +3 -1
index ca5243826726..408b94b22ee9 100644
@@ -533,7 +533,15 @@ static int __init imsic_parse_node(const struct 
 dt_device_node *node,
 
      imsic_cfg.nr_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1, 64);
 
-    /* Reserve last identity for APLIC-to-hart synchronization */
+    /*
+     * The identities of Xen's own interrupt file are allocated statically:
+     *  - the APLIC sources take 1 .. riscv,num-sources, as the MSI of 

source
+ * N carries identity N (aplic_init() drops the sources which
don't fit

xen/arch/riscv/imsic.c +2 -0
+     *    below sync_id);
+     *  - the last one, nr_ids, is reserved for APLIC-to-hart 

synchronization.

xen/arch/riscv/imsic.c +3 -0
+     * Anything else taking identities from this file has to stay clear of
+     * both.
+     */
      imsic_cfg.sync_id = imsic_cfg.nr_ids;
 
      /* Compute base address */
Quoted 1 line

Any thoughts about it?

LGTM, but I wonder why, as I said in the original patch, sync_id is really needed.

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

Re: [PATCH v3 31/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 28 lines

Once the new IMSIC VS-file has been zeroed out, it has to be mapped into the guest's G-stage in place of the old one. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Taking a h/w guest interrupt file (assigning it, zeroing it out, mapping it into G-stage and recording it in the vCPU's IMSIC state) is factored out into imsic_vsfile_acquire().

The relevant translation tables at all IOMMUs would also have to be updated so that MSIs for this virtual interrupt file are sent to the new physical interrupt file, but that is skipped for now as there is no IOMMU support for RISC-V.

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.

If the new file can't be mapped into the guest, release the guest external interrupt number imsic_vsfile_acquire() took for it instead of leaking it. vgein_release() takes the pCPU explicitly instead of relying on v->processor, as on migration v->processor already refers to the new pCPU while the number to be released may belong to the old one.

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

Quoted 6 lines

Implement imsic_update_state(), which records the vCPU's guest interrupt file id together with the pCPU owning the file. The two are read as a pair, e.g. by imsic_migrate_vcpu() and the IMSIC context switch hooks, so they are updated under vsfile_lock as a single unit.

imsic_map_guest_file() and vgein_release() are stubs for now.

I have the feeling this patch does more than its subject says: besides retargeting the APLIC and adding the sync, it introduces imsic_vsfile_acquire() (assign + clear + G-stage map + state update), imsic_update_state() and the error path, which relies on two stubs, imsic_map_guest_file() and vgein_release(). At this point vgein_assign() is still BUG_ON("unimplemented") too, so none of the new code can actually run, and the error path can't be reviewed against the real vgein_release().

Also, until "introduce IMSIC h/w interrupt file attaching to vcpu", no vCPU ever owns a h/w file, so imsic_migrate_vcpu() can only hit the CPU_NONE check.

Wouldn't it be simpler to move the two already-acked patches and the attach first, so that no stubs are needed and each migration step is written against its real callees when it lands:
- Add basic VGEIN management for AIA guests (real vgein_assign() and vgein_release(); the reason for the explicit cpu argument of vgein_release() would then have to go into this commit message)
- Map IMSIC interrupt file for vCPUs (real imsic_map_guest_file())
- Implement continue_new_vcpu() and set hstatus.VSXL
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user (acquire, vaplic_reconfigure_target(), set hstatus.VGEIN)
- Prepare new IMSIC VS-file (on top of imsic_vsfile_acquire())
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file (APLIC retarget + sync)
- Save/clear old VS-file, restore, SGEI wake-up as today

A side benefit: attach no longer has to be squeezed into the finished migration code, so imsic_vsfile_move() with its first_attach argument and the goto set_vgein go away. Attach stays a plain sequence, and imsic_migrate_vcpu() simply reuses imsic_vsfile_acquire().

Migrating a vCPU which has already run would still hit the trailing BUG_ON("unimplemented") until the restore patch, but that is no worse than the panic() it hits today.

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

Re: [PATCH v3 32/39] xen/riscv: save and clear the old IMSIC VS-file on vCPU migration

In reply to Oleksii Kurochko
Quoted 12 lines

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.

Quoted 9 lines

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 guest interrupt file, which is how the AIA specification describes MRIFs being used by a hypervisor.

I think it's worth mentioning that this MRIF structure could be reused for software interrupt files later.

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_clear(void *data) · line 674

Quoted 13 lines

[ ... 172 lines skipped ... ]

xen/arch/riscv/imsic.c +12 -0
+static void cf_check imsic_vsfile_local_read_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /*
+     * The file is reached by retargeting hstatus.VGEIN, and
+     * imsic_vs_csr_swap() alters vsiselect. Both belong to the vCPU running
+     * on this pCPU, so restore them before returning.
+     */

You're saving the registers here, not restoring them. I'd use something like:
/*
* vsiselect/vsireg only reach the guest interrupt file selected by
* hstatus.VGEIN, so point VGEIN at this file for the access.
* hstatus and vsiselect hold the state of the vCPU running on this
* pCPU; save them here and restore them before returning. */

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_clear(void *data) · line 685

Quoted 11 lines
xen/arch/riscv/imsic.c +11 -0
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    /*
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
+     */

Nit: is this blank line really needed?

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

Re: [PATCH v3 33/39] xen/riscv: restore register state in the new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 6 lines

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.

Could we send an extempore MSI to the hart of the new file once the interrupt producers have been retargeted, and spin until it is received? That would guarantee that no more MSIs land once we have received it.

Quoted 6 lines

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.

Quoted 8 lines

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 is migrating to.

Finally, point hstatus.VGEIN in the vCPU's saved context 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")

Great!

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

Quoted 6 lines

[ ... 82 lines skipped ... ]

xen/arch/riscv/imsic.c +5 -0
+static void cf_check imsic_vsfile_local_update(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;

mrif is only read here, so it can be const:

    const struct imsic_mrif *mrif = idata->mrif;
Quoted 7 lines
xen/arch/riscv/imsic.c +7 -0
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*

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

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+     * 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.
+     */
+
+    /*
+     * The file is reached by retargeting hstatus.VGEIN, and the
+     * imsic_vs_csr_*() accessors alter vsiselect. Both belong to the vCPU
+     * running on this pCPU, so restore them before returning.
+     */

Same comment as on the previous patch: you are not restoring the CSRs here but saving them, as imsic_vs_csr_*() will alter vsiselect. Please update the comment accordingly.

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1228

Quoted 10 lines

[ ... 32 lines skipped ... ]

xen/arch/riscv/imsic.c +4 -1
@@ -1152,5 +1222,11 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Free-up old IMSIC VS-file */
     vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    imsic_call_on_cpu(v->processor, imsic_vsfile_local_update, &vsfile_data);
+
+    /* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */

Nit: s/VCPU/vCPU/

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

Re: [PATCH v3 35/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Oleksii Kurochko
Quoted 6 lines

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

Quoted 8 lines

Let Xen observe the file in that window: on deschedule set the vCPU's bit in HGEIE, which turns an interrupt pending in its VS-file into an HS-level SGEI, and clear the bit again on schedule-in. HGEIP only reports 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.

Please explain why this is enough for a descheduled
vCPU to never miss a wake-up: an interrupt pending in a VS-file always shows up in HGEIP, but it reaches VS-mode only if hstatus.VGEIN selects that file, and traps to Xen as an SGEI only if the file's HGEIE bit is set. While the vCPU is descheduled, HGEIE is therefore Xen's only way to notice it. And as HGEIP reflects the file's current state rather than being latched, an interrupt which arrived before the bit got set still raises the SGEI once it is.

Quoted 5 lines

[ ... 49 lines skipped ... ]

xen/arch/riscv/aia.c struct vgein_ctrl { · line 27

Quoted 10 lines
xen/arch/riscv/aia.c +7 -0
@@ -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];

It looks like owners[] already carries the information bmp provides. Couldn't we drop bmp and use owners[] alone, with owners[i] == NULL meaning that file i is free? That would avoid having to keep the two in sync, and vgein_release() could then check ASSERT(owners[id] == v) rather than just that the bit was set. A linear scan over 1..geilen in vgein_assign() should be fine given geilen < BITS_PER_LONG.

If you agree, it would probably be cleaner to introduce owners[] in place of bmp in the earlier "add basic VGEIN management" patch, rather than adding bmp there and replacing it here.

Quoted 9 lines

[ ... 26 lines skipped ... ]

xen/arch/riscv/aia.c +8 -0
+
+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);

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 199

Quoted 10 lines
xen/arch/riscv/aia.c +10 -0
+
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    /*
+     * Bit 0 of HGEIP/HGEIE is read-only zero: guest interrupt file ID 0
+     * means that no guest external interrupt source is selected.
+     */
+    ASSERT(!(hgei_mask & 1));

Is this ASSERT() really needed? Bit 0 of HGEIP/HGEIE is read-only zero per the spec, and vgein_init() already relies on that when computing geilen. Even if it were ever reported, owners[0] is never assigned, so the loop below would simply skip it.

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *p) · line 561

Quoted 11 lines

[ ... 35 lines skipped ... ]

xen/arch/riscv/imsic.c +4 -0
@@ -555,12 +555,37 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *p)
 
     write_lock_irqsave(&imsic_state->vsfile_lock, flags);
     imsic_state->vsfile_cpu = p->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.

"instead of" reads as if HGEIP only reports it while the vCPU isn't running. It always does; what changes is that VGEIN no longer selects the file and the HGEIE bit set below turns it into an SGEI.

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 726

Quoted 10 lines

[ ... 29 lines skipped ... ]
int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)

xen/arch/riscv/imsic.c +4 -0
@@ -695,6 +720,12 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     struct imsic_mrif *mrif = idata->mrif;
     unsigned long new_hstatus, old_hstatus, old_vsiselect;
 
+    /*
+     * The HGEIE bit imsic_ctxt_switch_from() armed belongs to the old owner
+     * only.
+     */

"Old owner" is ambiguous: it reads like another vCPU, but it's the same vCPU on the file it is leaving. To mirror imsic_local_hgeie_set(), I'd rather have an imsic_local_hgeie_clear() called from here, documenting the pairing the same way, e.g.:

/*
* Stop observing an interrupt file which a vCPU leaves when it moves to
* another pCPU by clearing the bit imsic_ctxt_switch_from() set. *
* Counterpart of imsic_local_hgeie_set() for the new file. */

In that case ...

Quoted 6 lines
xen/arch/riscv/imsic.c +2 -0
+    csr_clear(CSR_HGEIE, BIT(idata->hgei, UL));
+
     /*
      * The file is reached by retargeting hstatus.VGEIN, and
      * imsic_vs_csr_swap() alters vsiselect. Both belong to the vCPU running

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

Quoted 10 lines
xen/arch/riscv/imsic.c +7 -0
@@ -1044,6 +1075,21 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
     return fdt_end_node(fdt);
 }
 
+/*
+ * Start to observe the interrupt file from HS-mode, the same way
+ * imsic_ctxt_switch_from() does it for a vCPU which is switched out.
+ *
+ * The counterpart, clearing the bit of the interrupt file which is left
+ * behind, is done by imsic_vsfile_local_read_clear(), which already runs on
+ * the pCPU owning that file.

... this wouldn't be needed at all.

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

Re: [PATCH v3 15/39] xen/riscv: extend exception tables with type and data fields

In reply to Baptiste Le Duc
Quoted 89 lines · Baptiste Le Duc
Quoted 75 lines
  
  static void __init __maybe_unused build_assertions(void)
  {
xen/arch/riscv/domain.c +21 -0
+/*
+ * 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
  }
xen/arch/riscv/include/asm/gpr-num.h new file +37 -0
new file mode 100644
index 0000000000..867ee172c0
@@ -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

xen/arch/riscv/include/asm/gpr-num.h line 47

Quoted 10 lines
xen/arch/riscv/include/asm/gpr-num.h new file +10 -0
+ * 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 ahead of the __ASSEMBLER__ flavour above. */

It's hard to understand which comment you're talking about, if you are talking about the separator comment above GPR_NUM_EQU, may I suggest something like:

Quoted 1 line
     /* See the GPR_NUM_EQU()'s comment about separator use */

Agree, I will apply this suggestion. Maybe a little but more precise:

/* See the comment above the assembler GPR_NUM_EQU() about the separator. */

Quoted 30 lines
Quoted 15 lines
xen/arch/riscv/include/asm/gpr-num.h new file +6 -0
+#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 */
xen/arch/riscv/include/asm/riscv_encoding.h +0 -0
index 647268e6d0..599ae3cd60 100644
@@ -911,8 +911,13 @@
  #define REG_OFFSET(insn, pos)		\

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

Quoted 10 lines
xen/arch/riscv/include/asm/riscv_encoding.h +6 -1
  	(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))

I don't see why this hunk is needed here. Nothing in the tree uses REG_PTR() (nor GET_RS*() / SET_RD()), and ->zero is the first member of struct cpu_user_regs, so this is a no-op today. It is also unrelated to the extable change.

Quoted 6 lines

If you want REG_PTR() to follow the same layout assumption as regs_gpr_ptr(), I'd rather see it built on top of it, e.g. regs_gpr_ptr(regs, REG_OFFSET(insn, pos) >> LOG_REGBYTES), in a separate patch together with its first user. Otherwise please drop the hunk (and the matching sentence in the commit message).

I'd rather keep it here. It isn't a standalone change waiting for a user: it follows from this patch relaxing the layout requirement. Until now the requirement wasn't written down anywhere, and REG_PTR() implicitly relied on the stricter form of it, x0..x31 starting at offset 0 of struct cpu_user_regs. This patch documents the requirement as "contiguous and in register-number order, anchored at ->zero", with the BUILD_BUG_ON()s anchored the same way (look at build_assertions() above). Leaving REG_PTR() as is would make that comment untrue for the one other piece of code in the tree that resolves a register number to its saved value. Moving the block would then still build, and REG_PTR() would silently compute wrong addresses. It's a no-op today simply because the block still sits at the start of the structure.

~ Oleksii

#68 lore raw

Re: [PATCH v3 17/39] xen/riscv: add guest page fault handling stub

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

Add a handler for guest page faults and hook it into the trap path, providing the trap-side entry point which will later feed the MMIO dispatch.

Based on your comments below I will update here to:

Add a handler for guest page faults and hook it into the trap path,
-providing the trap-side entry point which will later feed the MMIO -dispatch.
+providing the trap-side entry point for the MMIO dispatch.

Quoted 11 lines
Quoted 11 lines

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.

Quoted 6 lines
Quoted 2 lines

- Load fault / Store fault: left undecided by this patch, this is where MMIO emulation will hook in later.

Nit: should drop "in later" as it would be stale in the future. I'd suggest:
- Load fault / Store fault: this is where MMIO emulation will hook. Not in scope of this patch.

I will re-use your option with small remark:

"this is where MMIO emulation *hooks in*. Not in scope of this patch."

'hooks in' instead of 'will hook'.

Quoted 14 lines
Quoted 7 lines

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

(a) the fault occurred on an implicit access Xen made to walk a VS-stage page table, and

Xen doesn't access the VS-stage page tables here: the implicit access is done by the hardware page-table walker, while translating a guest access through the guest's VS-stage page tables. I'd suggest to use spec's wording. Moreover, "and" is not needed between both conditions as you said above "when both" which already indicates that both should be true.

Here is a proposition:

Quoted 8 lines
```
     Any of these three faults can instead be reported via a
     pseudoinstruction in htinst, 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.
```

This option better. I will use it.

Quoted 17 lines
Quoted 17 lines

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().

Cache the "trap came from the guest" test in a local, as the guest page fault case needs it too.

Quoted 6 lines

xen/arch/riscv/emulate.c line 97

Quoted 4 lines
xen/arch/riscv/emulate.c new file +3 -0
+    default:
+        domain_crash(current->domain, "Impossible cause (%#lx) in %s?\n",
+                     gf->cause, __func__);

Nit: please drop __func__, the message is unique enough to find where it comes from.

Agree, not to much sense. It will be dropped.

Quoted 30 lines
Quoted 18 lines
xen/arch/riscv/emulate.c new file +17 -0
+        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);

xen/arch/riscv/emulate.c line 124

Quoted 10 lines
xen/arch/riscv/emulate.c new file +10 -0
+    gf.stval = csr_read(CSR_STVAL);
+
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)

Nit: I think this paragraph could be re-written by using what you said in the commit message.

Quoted 12 lines
```
     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.
```

I will use then your option.

Quoted 52 lines
Quoted 52 lines
xen/arch/riscv/emulate.c new file +51 -0
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     *
+     * 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;
Quoted 8 lines

xen/arch/riscv/emulate.c line 182

Quoted 7 lines
xen/arch/riscv/emulate.c new file +7 -0
+    }
+
+ out:
+    if ( rc )
+        domain_crash(current->domain,
+                     "%s: unable to handle guest page fault (cause=%#lx) at gpa %#"PRIpaddr"\n",
+                     __func__, cause, gf.gpa);

Probably __func__ can be dropped as the message is unique enough.

Agree with dropping of __func__.

Quoted 14 lines

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

Quoted 11 lines
(quoted diff) +1 -0
+}
xen/arch/riscv/traps.c +3 -0
@@ -193,6 +194,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
  {
      register_t pc = cpu_regs->sepc;
      unsigned long cause = csr_read(CSR_SCAUSE);
+    bool from_guest = cpu_regs->hstatus & HSTATUS_SPV;
@@ -275,3 +289,9 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
+
+/* Redirect trap to Guest. */

This duplicates the comment on the prototype in traps.h, so I'd drop it here.

Agree, it is enough to have the comment only in prototype.

Thanks!

~ Oleksii

#73 lore raw

Re: [PATCH v3 18/39] xen/riscv: implement trap redirection to a guest

In reply to Baptiste Le Duc
Quoted 15 lines · Baptiste Le Duc
Quoted 12 lines · Baptiste Le Duc

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

Quoted 8 lines

[ ... 54 lines skipped ... ]

xen/arch/riscv/include/asm/riscv_encoding.h +4 -0
@@ -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)

Nit: STVEC_MODE_MASK needs a third tab for its value to line up with the other two (and with the surrounding #define-s).

Quoted 1 line

Instead of this small Nit, everything LGTM:

I suppose here you meant "Except of ...". I will apply your Nit.

Quoted 1 line

Thanks!

~ Oleksii

#79 lore raw

Re: [PATCH v3 20/39] xen/riscv: resolve the faulting guest physical address

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

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

Nit: "The shift" reads as the right shift just described, while what is meant is shifting htval back left by 2 to recover the address. Could you say so explicitly?

Sure, I'll update it accordingly. Thanks for clarifying!

Quoted 10 lines

Something like:

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

Thanks.

~ Oleksii

#82 lore raw

Re: [PATCH v3 21/39] xen/riscv: add guest memory read helper

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

[ ... 75 lines skipped ... ]
+/*
+ * 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.
Quoted 15 lines

+ *
+ * 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.
+ */

Quoted 1 line

Shouldn't docstring belong to header file?

I don't know if we have such rule but I think that I will move this to header to be in sync with other functions in asm/traps.h.

But in the matter of taste it seems to me that having such explanation in C code is more useful as it at some point explains a code.

Quoted 29 lines
Quoted 15 lines
xen/arch/riscv/guestcopy.c +15 -0
+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.

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

Quoted 10 lines
xen/arch/riscv/guestcopy.c +10 -0
+     */
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1: hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bnez %[tmp], 3f\n"
+            "   addi %[addr], %[addr], 2\n"

Could you add a short comment explaining that the andi/addi/bnez sequence checks the low two bits of the first halfword to tell a compressed instruction from a 32-bit one? It is not obvious on first read. Something like:

Quoted 7 lines
```
     /*
      * bits[1:0] != 0b11: 16-bit (compressed) instruction, nothing more
      * to read.
      */
```

I thought that the last paragraph of the comment above read_guest() explains it but I am okay to add the suggested small comment. I will put it immediately after ASM_EXTABLE:

            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
            /*
             * bits[1:0] != 0b11: 16-bit (compressed) instruction, nothing
             * more to read.
             */
            "   andi %[tmp], %[val], 3\n"

Thanks!

~ Oleksii

#84 lore raw

Re: [PATCH v3 21/39] xen/riscv: add guest memory read helper

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

Sorry I forgot one thing.> +unsigned long read_guest(unsigned long guest_addr, bool read_insn,

Quoted 7 lines

+                         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-

Quoted 1 line

scause.

Quoted 15 lines

+     */
+    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"

I think this would need asm_inline instead...> +            "1: hlvx.hu %[val], (%[addr])\n"

Quoted 21 lines

+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bnez %[tmp], 3f\n"
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2: hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   slli %[tmp], %[tmp], 16\n"
+            "   or %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "+&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr),
+          "+m" (*trap)
+        : [ti] "r" (trap) );
+
+        /*
+         * Although HLVX instructions' explicit memory accesses require execute
+         * permissions, they still raise the same exceptions as other load

Quoted 8 lines

+         * instructions, rather than raising fetch exceptions instead. +         */
+        if ( trap->scause == CAUSE_LOAD_PAGE_FAULT )
+            trap->scause = CAUSE_FETCH_PAGE_FAULT;
+    }
+    else
+    {
+        asm volatile ( "\n"

Quoted 1 line

... same for here.

read_guest() is an out-of-line function with its only caller in another translation unit, so asm_inline wouldn't change any inlining decision here.

volatile is still needed, as the asm may trap and reads memory which can change behind the compiler's back.

~ Oleksii

#85 lore raw

Re: [PATCH v3 21/39] xen/riscv: add guest memory read helper

Quoted 58 lines · Oleksii Kurochko
Quoted 55 lines · Baptiste Le Duc

Sorry I forgot one thing.> +unsigned long read_guest(unsigned long guest_addr, bool read_insn,

Quoted 7 lines

+                         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-

Quoted 1 line

scause.

Quoted 15 lines

+     */
+    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"

I think this would need asm_inline instead...> +            "1: hlvx.hu %[val], (%[addr])\n"

Quoted 29 lines

+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bnez %[tmp], 3f\n"
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2: hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   slli %[tmp], %[tmp], 16\n"
+            "   or %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "+&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr),
+          "+m" (*trap)
+        : [ti] "r" (trap) );
+
+        /*
+         * Although HLVX instructions' explicit memory accesses require execute
+         * permissions, they still raise the same exceptions as other load
+         * instructions, rather than raising fetch exceptions instead. +         */
+        if ( trap->scause == CAUSE_LOAD_PAGE_FAULT )
+            trap->scause = CAUSE_FETCH_PAGE_FAULT;
+    }
+    else
+    {
+        asm volatile ( "\n"

Quoted 7 lines
Quoted 1 line

... same for here.

read_guest() is an out-of-line function with its only caller in another translation unit, so asm_inline wouldn't change any inlining decision here.

volatile is still needed, as the asm may trap and reads memory which can change behind the compiler's back.

Yet that's not expressed by volatile, but by a memory clobber.

Jan

Reviewed-by on v3 37/39
#144 lore raw

Re: [PATCH v3 37/39] xen/riscv: implement continue_new_vcpu()

In reply to Oleksii Kurochko
Quoted 10 lines

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, which restores hstatus and sepc, passes the hart id in a0 and, in a1, either the DTB address (boot vCPU, as expected by the RISC-V boot protocol) or the opaque value passed to SBI HSM hart_start() (secondary vCPUs), clears the remaining GPRs, sets sstatus.SPP and sstatus.SPIE and executes sret.

Nit: the guest vCPU sentence is hard to follow in one go. Maybe split it:

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

Quoted 6 lines

[ ... 94 lines skipped ... ]

xen/arch/riscv/entry.S +0 -0
@@ -147,3 +147,42 @@ FUNC(__context_switch)
 
         ret

xen/arch/riscv/entry.S FUNC(__context_switch) · line 158

Quoted 10 lines
xen/arch/riscv/entry.S +9 -0
 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
+

At this point regs->hstatus only has SPV | SPVP (arch_vcpu_create()), so VSXL is written as 0, which is a reserved encoding. That only gets fixed by "xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL", which comes later in the series. Wouldn't it be better to move that one ahead of this patch?

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

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

In reply to Oleksii Kurochko
Quoted 15 lines

[ ... 97 lines skipped ... ]

xen/arch/riscv/domain.c +8 -0
@@ -51,6 +51,119 @@ 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().
+ *
+ * The switch() deliberately has no default case, so that adding a new
+ * domain_type (a 128-bit one, in particular) fails to build until this
+ * mapping is updated.

xen/arch/riscv/domain.c static struct csr_masks __ro_after_init csr_masks; · line 71

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+ */
+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;

Couldn't we add to avoid having to explain why there is no default in the comment above, and to respect MISRA rules?
default:
break

xen/arch/riscv/domain.c static struct csr_masks __ro_after_init csr_masks; · line 77

Quoted 6 lines
xen/arch/riscv/domain.c +6 -0
+    }
+
+    ASSERT_UNREACHABLE();
+
+    /* A reserved encoding, which hstatus_vsxl_settable() never accepts. */
+    return 0;

Could this get a name next to XLEN_FIELD_{32,64,128} in riscv_encoding.h, e.g.:

#define XLEN_FIELD_RESERVED _UL(0)
so the comment isn't the only thing explaining the 0?

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

Quoted 13 lines

[ ... 88 lines skipped ... ]

xen/arch/riscv/domain.c +5 -0
+
 void __init init_csr_masks(void)
 {
     /*
@@ -91,6 +204,10 @@ static void vcpu_csr_init(struct vcpu *v)
 {
     v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
+    /*
+     * hstatus.VSXL is left zero here: the domain's type, and hence the
+     * guest's XLEN, is only known once its kernel image has been probed.
+     */

"Probe" refers to two different things in this series: the hardware probe of the settable hstatus.VSXL values (init_hstatus_vsxl_settable_mask()) and the guest kernel header parsing (kernel_probe()). This comment is about the latter, but it is easy to read it as the former, which already ran at boot. Could you name it explicitly and state the ordering that actually matters? I'd suggest:

/*
* 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.
*/

Signature · 1 line
Baptiste Le Duc <[email protected]>
Reviewed-by on v3 39/39
#151 lore raw

Re: [PATCH v3 39/39] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu

In reply to Oleksii Kurochko
Quoted 21 lines

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().

Giving a vCPU its first file shares most of the steps with moving it to a new one on migration, so move the body of imsic_migrate_vcpu() to imsic_vsfile_move() and use it for both. Its first_attach argument skips the part which moves the interrupt state out of the old 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.

Quoted 4 lines

vAPLIC target registers are reconfigured on the first attach as well: a target the guest writes for a vCPU which has no h/w guest interrupt file yet only updates the stored copy, which reaches the h/w at this point.

Nit: I didn't quite understand this paragraph, "only updates" leaves out that the h/w APLIC write is skipped, because there is no file to point the target at yet. Maybe something like:

The guest may program a vAPLIC TARGET register for a vCPU which has not run yet. That vCPU has no h/w guest interrupt file yet, so vaplic_mmio_write() only stores the value. imsic_vsfile_move() then writes it to the h/w APLIC on the first attach, pointing to the newly acquired file.

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

Re: [PATCH v3 21/39] xen/riscv: add guest memory read helper

In reply to Jan Beulich
Quoted 61 lines · Jan Beulich
Quoted 60 lines · Oleksii Kurochko
Quoted 56 lines · Baptiste Le Duc

Sorry I forgot one thing.> +unsigned long read_guest(unsigned long guest_addr, bool read_insn,

Quoted 7 lines

+                         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-

Quoted 1 line

scause.

Quoted 15 lines

+     */
+    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"

I think this would need asm_inline instead...> +            "1: hlvx.hu %[val], (%[addr])\n"

Quoted 21 lines

+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bnez %[tmp], 3f\n"
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2: hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   slli %[tmp], %[tmp], 16\n"
+            "   or %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "+&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr),
+          "+m" (*trap)
+        : [ti] "r" (trap) );
+
+        /*
+         * Although HLVX instructions' explicit memory accesses require execute
+         * permissions, they still raise the same exceptions as other load

Quoted 8 lines

+         * instructions, rather than raising fetch exceptions instead. +         */
+        if ( trap->scause == CAUSE_LOAD_PAGE_FAULT )
+            trap->scause = CAUSE_FETCH_PAGE_FAULT;
+    }
+    else
+    {
+        asm volatile ( "\n"

... same for here.

Quoted 7 lines
Quoted 5 lines

read_guest() is an out-of-line function with its only caller in another translation unit, so asm_inline wouldn't change any inlining decision here.

volatile is still needed, as the asm may trap and reads memory which can change behind the compiler's back.

Yet that's not expressed by volatile, but by a memory clobber.

Agree, this was incorrect justification of volatile. Volatile still is needed I think as suppose the calling code looks like this:
read_guest(guest_addr, false, trap);
In other words, the return value is ignored.

Theoretically, if volatile is removed, GCC may determine that:
val is not used;
tmp is not used;
guest_addr is not used after the asm block;
trap is not accessed after the function call.
If the compiler can also prove that modifications to *trap are not observable, it may eliminate the entire asm block. So to avoid that volatile will be better to keep here.

Memory clobber still seems like isn't needed here as the only Xen object written behind its back, by the fixup path, is *trap, which is already an "+m" operand.

~ Oleksii

#91 lore raw

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

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

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

Quoted 5 lines
Quoted 4 lines

---
How these helpers are used can be seen in the patches adding emulate_load() and emulate_store().

Appreciate this precision, thanks!

Welcome!

Quoted 8 lines
Quoted 8 lines

[ ... 116 lines skipped ... ]
+/*
+ * The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a
+ * trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode.
+ *
+ * VSXL is consulted whichever mode the trap came from, as it also gives the
+ * width of vsstatus itself: where VSXL says 32, that register has no UXL field
+ * to consult and VU-mode is 32-bit as well, there being nothing to configure.

Quoted 8 lines

Reading "it also gives the width of vsstatus itself", one might understand that VSXL equals UXL in all cases, while, as you mentioned, this only holds when VSXL says 32. I would slightly reword it, e.g.:

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

Agreed. I'll use your suggested wording.

Quoted 10 lines
Quoted 10 lines

+ *
+ * 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.

Quoted 8 lines

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

Quoted 7 lines

+ */

xen/arch/riscv/emulate.c +6 -0
+static unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);

xl only ever holds a 2-bit field, so unsigned int would be better here.

MASK_EXTR() yields the type of its operands, unsigned long here (and unsigned long long for the UXL extraction), as do the XLEN_FIELD_* constants xl is compared against. Making xl unsigned int would add an implicit narrowing conversion: harmless value-wise but I think it will violate one of MISRA rules at least if build everything with -Wconversion then it will tell: conversion from 'long unsigned int' to 'unsigned int' may change value.

Quoted 10 lines

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

Quoted 9 lines

[ ... 49 lines skipped ... ]

xen/arch/riscv/emulate.c +8 -0
+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));

Nit: the parentheses around the division aren't needed.

I can drop them but I think it improves readability here a little bit.

Quoted 37 lines
Quoted 22 lines

[ ... 14 lines skipped ... ]

xen/arch/riscv/emulate.c +21 -0
+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) )
+    {

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

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+        /*
+         * The transformation always yields the 32-bit format, with bits[1:0]
+         * holding a marker instead of the original opcode bits: bit[0] set to
+         * flag the transformation, bit[1] clear if the trapped instruction
+         * was a compressed one. Restoring the opcode bits makes the value the
+         * valid 32-bit encoding decode_ldst_insn() decodes. Its handling of
+         * compressed encodings exists for the branch below, where a
+         * compressed instruction is read from guest memory as is: a trapped
+         * one arrives here already expanded to its 32-bit equivalent, and the
+         * opcode bits just restored have it decoded as such.

Reading this, I first understood that something had to be done to recover the original compressed opcode. "Restoring the opcode bits" suggests going back to the trapped encoding, while it is only setting bits[1:0] to 0b11 of an already expanded instruction. Maybe say that first, e.g.:

Quoted 10 lines
```
     /*
      * A compressed instruction is reported already expanded to its
      * 32-bit equivalent by the hardware, so htinst always holds a
      * 32-bit encoding, apart from bits[1:0] which is holding 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
      * the original 32-bit encoding for decode_ldst_insn().
      */
```

Agree, it will be better.

Quoted 20 lines
Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+         *
+         * 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;
+    }

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

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

Nit: as the assert would disappears in release build, this comment is partially true. I would suggest something like:

```
          * Bit[0] == 0 implies trapped instruction value is zero or
          * special value. With the pseudoinstructions ruled out (see
          * comment above) only zero (or a custom value, see above) is
          * left: the instruction has to be read from guest memory.
```

Agree "ruled out" could be read incorrectly. I think it will be better then:

/*
* Bit[0] == 0 implies trapped instruction value is zero or
special

-         * value. With the pseudoinstructions ruled out above, only zero (or a
-         * custom value, see above) is left: the instruction has to be read from
-         * guest memory.
+         * 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.
          */
Quoted 14 lines

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

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

Typo: "Such faults ... are considered" (plural subject). Also "a fault happen" above should be "a fault happens", and "as bus error" -> "a bus error". Maybe:

Quoted 8 lines

/*
* If a G-stage translation fault happens while fetching the
* trapped instruction, CAUSE_LOAD_GUEST_PAGE_FAULT is generated.
* Such faults are treated as an access fault.
*/
I used access fault instead of bus error because the code below sets CAUSE_FETCH_ACCESS which is more like an access fault.

Suggestion LGTM with one nit that "... instruction acccess fault" + mentioned of that it is because of hlvx instruction so:

             /*
-             * If during getting of trapped instruction a fault happen in
-             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
-             * generated. Such faults during this operation is considered as
-             * bus error.
+             * If 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;
Quoted 10 lines
Quoted 10 lines

[ ... 54 lines skipped ... ]
+/*
+ * 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.

Quoted 2 lines

Nit: odd wrapping, "the encodings" fits on the line above.

Missed that, it could be really on the prev line.

Quoted 9 lines
Quoted 4 lines

+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.

Nit: maybe reword for clarity:

* Returns false if the instruction is not a load or store, or cannot be
* emulated here.

Agree, your option is better

Quoted 49 lines
Quoted 34 lines

+ */

xen/arch/riscv/emulate.c +33 -0
+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 )

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

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+                return false;
+        }
+    }
+    else
+    {
+        /*
+         * funct3[1:0] is log2 of the width in bytes, and funct3[2] selects
+         * zero-extension for a load, while being reserved for a store.
+         */
+        funct3 = RV_X(insn, 12, 3);

Nit: the RVC branch above says where funct3 lives (bits[15:13]), this one doesn't. Maybe mention bits[14:12] as well, so the reader doesn't wonder why 12 here vs 13 above:

Quoted 7 lines
```
         /*
          * 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.
          */
```

Agreed. Will apply your comment.

Quoted 10 lines
Quoted 10 lines

[ ... 51 lines skipped ... ]

xen/arch/riscv/include/asm/riscv_encoding.h +0 -0
index b01da95f7e..1af309aa4a 100644
@@ -65,6 +65,14 @@
  #define SSTATUS64_UXL			MSTATUS_UXL
  #define SSTATUS64_SD			MSTATUS64_SD
 
Quoted 9 lines

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

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

Do we really need long here? int wouldn't be enough?

Good question.

These are values of fields living at bits 33:32 (VSXL, UXL, SXL), so a plain int would overflow if one were ever shifted into place. That isn't the case at the moment, but I think it's worth looking beyond the current uses: this header is included all over arch/riscv, and we can't know how these definitions will be used in the future. Using UL also keeps them in line with the other field values in this header, e.g. SATP_MODE_* and STVEC_MODE_*.

Thanks for review!

~ Oleksii

#98 lore raw

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

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

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

Quoted 8 lines

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

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

This part of commit message should be updated. Suggestion look below...

Quoted 5 lines

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.

Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

---

[...]

Sorry I don't understand, did you forget to put the suggestion?

Sorry for confusion, I put it here to drop the code which isn't necessary for my suggestion. and my suggestion was just at the end of my original reply (I will just copy it here):

Quoted 26 lines
  static int emulate_load(const struct guest_fault *gf)
  {
xen/arch/riscv/emulate.c +17 -6
-    /* 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 = 0;
+    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;
+
+    if ( !di.is_unsigned )
+        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",

xen/arch/riscv/emulate.c static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen) · line 448

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+             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) = (long)(info.data << shift) >> shift;

It would be more correct to have here:

    shift = BITS_PER_BYTE * (sizeof(info.data) - di.len);
    ...
    if ( di.reg )
        *guest_gpr(regs, &di) = di.is_unsigned
                                ? (info.data << shift) >> shift
                                : (long)(info.data << shift) >> shift;

and update the commit message part "Sign extension is done here…" to:

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.

xen/arch/riscv/emulate.c static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen) · line 453

Quoted 6 lines
xen/arch/riscv/emulate.c +4 -0
+
+    advance_pc(regs, di.insn_len);
+
+    return 0;
  }

~ Oleksii

#100 lore raw

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

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

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

Quoted 8 lines

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

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

This part of commit message should be updated. Suggestion look below...

Quoted 5 lines

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.

Quoted 17 lines
Quoted 2 lines

---

[...]

Quoted 12 lines
   static int emulate_load(const struct guest_fault *gf)
   {
xen/arch/riscv/emulate.c +4 -6
-    /* 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 = 0;
Quoted 1 line

As shift is always computed, I don't think it makes sense to init it.

Good point!
I think that originally I took that into account when tried to the suggestion but missed to sent here. I will double check!

Quoted 35 lines
Quoted 35 lines
Quoted 15 lines
xen/arch/riscv/emulate.c +13 -1
+    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;
+
+    if ( !di.is_unsigned )
+        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",

xen/arch/riscv/emulate.c static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen) · line 448

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+             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) = (long)(info.data << shift) >> shift;

It would be more correct to have here:

      shift = BITS_PER_BYTE * (sizeof(info.data) - di.len);
      ...
      if ( di.reg )
          *guest_gpr(regs, &di) = di.is_unsigned
                                  ? (info.data << shift) >> shift
                                  : (long)(info.data << shift) >> shift;
Quoted 7 lines
Quoted 6 lines

and update the commit message part "Sign extension is done here…" to:

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.

this LGTM.

Thanks for checking that!

~ Oleksii

#103 lore raw

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

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

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().

Quoted 4 lines

At the moment only virtual interrupt controller (vINTC) traps are expected to occur, since it is currently the only backend registered with the MMIO handler dispatch, so in practice the store is emulated via the vINTC backend.

Quoted 8 lines

Nit: the wording is unclear because "emulated via the vINTC backend" sounds like the vINTC does the decoding, I'd suggest:

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

Instead of that,

Good suggestion, it is really better!

Quoted 3 lines

everything LGTM, so:

Thanks!

~ Oleksii

#92 lore raw

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

In reply to Oleksii Kurochko
Quoted 18 lines · Oleksii Kurochko
Quoted 8 lines · Baptiste Le Duc
Quoted 8 lines

+ * 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.

Quoted 8 lines

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

Quoted 7 lines

+ */

xen/arch/riscv/emulate.c +6 -0
+static unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);

xl only ever holds a 2-bit field, so unsigned int would be better here.

Quoted 7 lines

MASK_EXTR() yields the type of its operands, unsigned long here (and unsigned long long for the UXL extraction), as do the XLEN_FIELD_* constants xl is compared against. Making xl unsigned int would add an implicit narrowing conversion: harmless value-wise but I think it will violate one of MISRA rules at least if build everything with -Wconversion then it will tell: conversion from 'long unsigned int' to 'unsigned int' may change value.

If we were to follow that Misra rule, we'd have violations all over the place. Hence imo where unsigned int is sufficient for a value, that's what should be used.

Quoted 11 lines
Quoted 10 lines

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

Quoted 9 lines

[ ... 49 lines skipped ... ]

xen/arch/riscv/emulate.c +8 -0
+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));

Nit: the parentheses around the division aren't needed.

Quoted 1 line

I can drop them but I think it improves readability here a little bit.

That's subjective. Personally I agree with Baptiste, yet project-wide we don't do things consistently in this regard, and hence either form is (supposedly) okay.

Jan

#93 lore raw

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

Quoted 27 lines · Jan Beulich
Quoted 18 lines · Oleksii Kurochko
Quoted 8 lines · Baptiste Le Duc
Quoted 8 lines

+ * 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.

Quoted 8 lines

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

Quoted 7 lines

+ */

xen/arch/riscv/emulate.c +6 -0
+static unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);

xl only ever holds a 2-bit field, so unsigned int would be better here.

Quoted 7 lines

MASK_EXTR() yields the type of its operands, unsigned long here (and unsigned long long for the UXL extraction), as do the XLEN_FIELD_* constants xl is compared against. Making xl unsigned int would add an implicit narrowing conversion: harmless value-wise but I think it will violate one of MISRA rules at least if build everything with -Wconversion then it will tell: conversion from 'long unsigned int' to 'unsigned int' may change value.

Quoted 3 lines

If we were to follow that Misra rule, we'd have violations all over the place. Hence imo where unsigned int is sufficient for a value, that's what should be used.

Fair enough, I'll switch xl to unsigned int.

The one thing which isn't fully clear IMO is that in misra/rules.rst it is mentioned for Rule 10.3:
- Please beware that this rule has many violations in the Xen
codebase today, and its adoption is aspirational. However, when
submitting new patches please try to decrease the number of
violations when possible.
then it isn't clear when it is needed to apply second sentence and when no.

Quoted 12 lines
Quoted 12 lines
Quoted 11 lines

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

Quoted 10 lines

[ ... 49 lines skipped ... ]

xen/arch/riscv/emulate.c +8 -0
+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));

Nit: the parentheses around the division aren't needed.

Quoted 5 lines
Quoted 1 line

I can drop them but I think it improves readability here a little bit.

That's subjective. Personally I agree with Baptiste, yet project-wide we don't do things consistently in this regard, and hence either form is (supposedly) okay.

Probably then it will be nice to update CODING_STYLE document.

~ Oleksii

#94 lore raw

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

In reply to Oleksii Kurochko
Quoted 31 lines · Oleksii Kurochko

[ ... 147 lines skipped ... ]

Quoted 5 lines

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

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+        /*
+         * Bit[0] == 0 implies trapped instruction value is zero or special
+         * value. With the pseudoinstructions ruled out above, only zero (or a
+         * custom value, see above) is left: the instruction has to be read from
+         * guest memory.
Quoted 9 lines

Nit: as the assert would disappears in release build, this comment is partially true. I would suggest something like:

```
          * Bit[0] == 0 implies trapped instruction value is zero or
          * special value. With the pseudoinstructions ruled out (see
          * comment above) only zero (or a custom value, see above) is
          * left: the instruction has to be read from guest memory.
```

Agree "ruled out" could be read incorrectly. I think it will be better then:

/*
* Bit[0] == 0 implies trapped instruction value is zero or
special
- * value. With the pseudoinstructions ruled out above, only
zero (or a
- * custom value, see above) is left: the instruction has to be
read from

(quoted diff) +1 -1
-         * guest memory.
+         * 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.

Quoted 1 line
           */

Agree.

Quoted 30 lines

[ ... 6 lines skipped ... ]

Quoted 9 lines

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

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+            /*
+             * If during getting of trapped instruction a fault happen in
+             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
+             * generated. Such faults during this operation is considered as
+             * bus error.

Typo: "Such faults ... are considered" (plural subject). Also "a fault happen" above should be "a fault happens", and "as bus error" -> "a bus error". Maybe:

Quoted 8 lines

/*
* If a G-stage translation fault happens while fetching the
* trapped instruction, CAUSE_LOAD_GUEST_PAGE_FAULT is generated.
* Such faults are treated as an access fault.
*/
I used access fault instead of bus error because the code below sets CAUSE_FETCH_ACCESS which is more like an access fault.

Suggestion LGTM with one nit that "... instruction acccess fault" + mentioned of that it is because of hlvx instruction so:

              /*
(quoted diff) +0 -3
-             * If during getting of trapped instruction a fault happen in
-             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
-             * generated. Such faults during this operation is 

considered as

(quoted diff) +2 -1
-             * bus error.
+             * If a G-stage translation fault happens while fetching the
+             * trapped instruction, CAUSE_LOAD_GUEST_PAGE_FAULT is 
Quoted 4 lines

generated,
+ * hlvx being a load. Such a fault is reported to the guest
as an
+ * instruction access fault.

Agree.

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

Re: [PATCH v3 28/39] xen/riscv: introduce vaplic_reconfigure_target()

In reply to Baptiste Le Duc
Quoted 11 lines · Baptiste Le Duc
Quoted 4 lines

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.

Jan's first question on v2 was how this avoids losing interrupts that are raised mid-retarget. You answered it on the list (step 3 of the AIA VS-level migration sequence; in-flight MSIs still land in the old file's eip and get merged into the new file later), but neither the description nor a comment says so. Please put it in the description, since this function is only correct as one step of that sequence.

I will add the following:

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

Quoted 8 lines
Quoted 8 lines

[ ... 43 lines skipped ... ]

xen/arch/riscv/aplic.c +0 -1
@@ -128,7 +128,10 @@ 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.
Quoted 9 lines

xen/arch/riscv/aplic.c static unsigned long aplic_hart_index(unsigned int cpu) · line 134

Quoted 4 lines
xen/arch/riscv/aplic.c +4 -0
+ * vsfile_lock, so that the guest file id and the pCPU owning it are read as
+ * a consistent pair. A value built from the old file just before a migration
+ * publishes the new one isn't lost: vaplic_reconfigure_target() runs after
+ * the publication and rewrites every source targeting the vCPU.

At this point in the series nothing calls vaplic_reconfigure_target(), so "runs after the publication" describes a caller that doesn't exist yet. Either move this sentence to the patch that adds the call, or word it as a requirement on that caller.

Agreed, I'll word it as a requirement on that caller:

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.

Quoted 25 lines
Quoted 5 lines

[ ... 43 lines skipped ... ]

xen/arch/riscv/aplic.c +3 -0
+/* 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)

xen/arch/riscv/aplic.c

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+{
+    unsigned int hart_idx = MASK_EXTR(target, APLIC_TARGET_HART_IDX);
+
+    /*
+     * Skip a source whose EIID is 0, e.g. one still holding its reset
+     * value: interrupt identity 0 isn't valid at any IMSIC interrupt file,
+     * so such a source delivers nothing and needs no retargeting.
+     * The hart index range check is only a guard: the write path refuses to
+     * record values with an out-of-range hart index.
+     */

"Reset value" reads as if the AIA spec defined one, but it doesn't: APLIC state other than domaincfg, the MSI address config registers and the genmsi Busy bit is UNSPECIFIED after reset. The 0 here only comes from xvzalloc_array() in domain_vaplic_init(). Could this be made explicit? It may also be worth saying that this check keeps unprogrammed sources from decoding as targeting vCPU0 (hart index 0), which would otherwise cause pointless physical TARGET rewrites on every vCPU0 migration.

Something like:

Quoted 9 lines

/*
* Skip a source whose EIID is 0 (not yet programmed, vAPLIC state
* is zero-initialised): identity 0 is reserved at every IMSIC, so
* it can't fire. Otherwise it would also decode as targeting
* vCPU0 and get 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. */

Agreed on both points. I'd word it slightly differently though: the write path doesn't reject EIID 0, so a guest can program it itself and "not yet programmed" is only one of the cases; the spec calls identity 0 never valid rather than reserved; and such a source can still become pending and have its MSI sent, it's the IMSIC that ignores it. So:

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.

Quoted 26 lines
Quoted 26 lines

[ ... 6 lines skipped ... ]

xen/arch/riscv/aplic.c +25 -0
+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->used_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
Quoted 8 lines

xen/arch/riscv/aplic.c

Quoted 6 lines
xen/arch/riscv/aplic.c +5 -0
+             * here.
+             */
+            read_lock(&vimsic_state->vsfile_lock);
+            aplic_hw_write_reg(offsetof(struct aplic_regs, target[irqn - 1]),
+                               aplic_msi_target_gen(v, target));

Doesn't this need the same vsfile_cpu != CPU_NONE check as vaplic_emulate_store()?

The case with the similar place in vaplic_emulate_store() is slightly different, as a guest could write to the target register using a vCPU for which the h/w interrupt file hasn't been assigned yet. Since we support only h/w interrupt files, we should simply ignore such writes, as the vCPU isn't ready for some reason.

Quoted 4 lines

Because it seems that, for a vCPU on a s/w
VS-file, aplic_msi_target_gen() calls aplic_hart_index(CPU_NONE) and indexes imsic->msi[] out of bounds; the ASSERT() in aplic_msi_target_gen() doesn't help in release builds.

I think ASSERT() should be sufficient to catch this situation. Since software interrupt file support is not included in this patch series, vaplic_reconfigure_target() cannot be called for a vCPU with a software interrupt file. The ASSERT() in aplic_hw_write_reg() will catch such cases. Therefore, even in a release build, we will never encounter a vCPU with a software interrupt file so we shouldn't care that ASSERT() is do nothing in release built.

When it comes to adding software interrupt file support, debug builds will be used during development, so the need to update aplic_msi_target_gen() to handle this case properly won't be overlooked.

Quoted 4 lines

Since both
callers now do the same lock/check/generate/write sequence, a helper for it would make sense.

Looking at my current implementation of the software interrupt file support, aplic_msi_target_gen() has been updated so that there is no longer a need to check vsfile_cpu != CPU_NONE before calling it. Therefore, this check will be removed from vaplic_emulate_store() and both the places will look the same.

~ Oleksii

#112 lore raw

Re: [PATCH v3 29/39] xen/riscv: prepare new IMSIC VS-file

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

[ ... 64 lines skipped ... ]

xen/arch/riscv/aia.c +0 -0
index e31c9c2d24..229ab4b867 100644
@@ -1,8 +1,10 @@
  /* SPDX-License-Identifier: GPL-2.0-only */
 
Quoted 8 lines

xen/arch/riscv/aia.c line 7

Quoted 5 lines
xen/arch/riscv/aia.c +2 -0
+#include <xen/bug.h>
  #include <xen/errno.h>
  #include <xen/init.h>
  #include <xen/sections.h>
+#include <xen/sched.h>

Nit: Why xen/sched.h? The stub doesn't dereference v, and asm/aia.h already forward-declares struct vcpu. If it stays: sched < sections, so it goes one line up.

Indeed, nothing needs it here. I'll include <asm/aia.h> instead, which
aia.c doesn't include yet: without that the stub's struct vcpu would only be declared inside the parameter list. <xen/sched.h> then moves to the patch where v gets dereferenced first.

Quoted 53 lines
Quoted 53 lines

[ ... 30 lines skipped ... ]

xen/arch/riscv/aia.c +52 -0
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, c);    \
+    csr_write(CSR_VSIREG, v);       \
+} while (0)
+
+/*
+ * Leaf macros for the switchcase expansion pyramid below:
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg, v); break"
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Extra args (e.g. an operation and/or a value) are forwarded to F via
+ * __VA_ARGS__.
+ */
+#define imsic_switchcase_2(F, ireg, ...)             \
+    F((ireg) + 0, __VA_ARGS__);                      \
+    F((ireg) + 1, __VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)             \
+    imsic_switchcase_2(F, (ireg) + 0, __VA_ARGS__);  \
+    imsic_switchcase_2(F, (ireg) + 2, __VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)             \
+    imsic_switchcase_4(F, (ireg) + 0, __VA_ARGS__);  \
+    imsic_switchcase_4(F, (ireg) + 4, __VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)            \
+    imsic_switchcase_8(F, (ireg) + 0, __VA_ARGS__);  \
+    imsic_switchcase_8(F, (ireg) + 8, __VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)            \
+    imsic_switchcase_16(F, (ireg) + 0, __VA_ARGS__); \
+    imsic_switchcase_16(F, (ireg) + 16, __VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)            \
+    imsic_switchcase_32(F, (ireg) + 0, __VA_ARGS__); \
+    imsic_switchcase_32(F, (ireg) + 32, __VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val);
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val);
+    default:
+        ASSERT_UNREACHABLE();
+        break;
+    }
Quoted 8 lines

xen/arch/riscv/aia.c

Quoted 2 lines
xen/arch/riscv/aia.c +2 -0
+}
+

What does the switch buy? ireg only ends up as the value written to vsiselect, not as a CSR number, so it doesn't need to be a compile-time constant. imsic_vs_csr_write(ireg, val) does the same, without the 128 case labels and the macro pyramid. If there's a reason, it wants stating in a comment; otherwise please drop the pyramid (an ASSERT() on the range can stay if you want one).

Good point.

I will drop it and use the following instead:

/*
* 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, laid out as described above. */ 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);
}

I will applt the similar patter to other patches where the pyramid was used.

Quoted 4 lines

Typo (only if the macros stay): "Leaf macros" - there's only one here. And case ireg: / op(ireg, v) as well as c and v in imsic_vs_csr_write() want parenthesizing (MISRA 20.7).

As to c and v in imsic_vs_csr_write(): they're passed as whole arguments
to csr_write() and the other csr_*() macros, which is covered by the
R20.7 deviation for macro parameters used as macro arguments. That's also why the parentheses were dropped in v3.

Quoted 23 lines

xen/arch/riscv/aia.c

Quoted 8 lines

[ ... 67 lines skipped ... ]

xen/arch/riscv/aia.c +7 -0
+static void cf_check imsic_vsfile_local_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */

Typo: s/a IMSIC/an IMSIC/

Quoted 14 lines

[ ... 31 lines skipped ... ]
void imsic_migrate_vcpu(struct vcpu *v)
{

xen/arch/riscv/aia.c +4 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = imsic_cfg.nr_eix,
+    };
+
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
       * invoke this before the vCPU has ever run (see the migrated branch in
@@ -703,5 +849,18 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == CPU_NONE )
          return;
 
Quoted 14 lines

xen/arch/riscv/aia.c void imsic_migrate_vcpu(struct vcpu *v) · line 863

Quoted 12 lines
xen/arch/riscv/aia.c +12 -0
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    vsfile_data.hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!vsfile_data.hgei);
+
+    /* Zero-out new IMSIC VS-file */
+    imsic_call_on_cpu(v->processor, imsic_vsfile_local_clear, &vsfile_data);

Nit: The comment restates the call; drop it.

Agreed, I will drop.

Thanks!

~ Oleksii

#118 lore raw

Re: [PATCH v3 30/39] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration

In reply to Baptiste Le Duc
Quoted 342 lines · Baptiste Le Duc
Quoted 341 lines · Oleksii Kurochko
Quoted 245 lines · Oleksii Kurochko

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.

Migration doesn't use the barrier at this stage, so imsic_migrate_vcpu() only references imsic_aplic_sync() to keep the compiler from complaining about it being unused.

---
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             | 33 +++++++++++++++++++
   xen/arch/riscv/imsic.c             | 52 ++++++++++++++++++++++++++++++
   xen/arch/riscv/include/asm/aplic.h |  3 ++
   xen/arch/riscv/include/asm/imsic.h |  8 +++++
   4 files changed, 96 insertions(+)
xen/arch/riscv/aplic.c +33 -0
index 283e5d6046a6..5f9a894b5a76 100644
@@ -27,7 +27,9 @@
   #include <asm/imsic.h>
   #include <asm/intc.h>
   #include <asm/io.h>
+#include <asm/processor.h>
   #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
 
   static struct aplic_priv aplic = {
       .lock = SPIN_LOCK_UNLOCKED,
@@ -183,6 +185,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;
+
+    /*
+     * sync_id is nr_ids, which imsic_parse_node() limits to IMSIC_MAX_ID,
+     * so it always fits into the EIID field.
+     */
+    BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
+    ASSERT(imsic->sync_id <= IMSIC_MAX_ID);
+
+    val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
+          imsic->sync_id;
+
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
   static void __init aplic_init_hw_interrupts(void)
   {
       unsigned int i;
xen/arch/riscv/imsic.c +52 -0
index f1e44dc56bb8..8e0273eab902 100644
@@ -27,6 +27,7 @@
   #include <xen/xvmalloc.h>
 
   #include <asm/aia.h>
+#include <asm/aplic.h>
   #include <asm/imsic.h>
 
   #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
   #define IMSIC_DISABLE_EITHRESHOLD   1
   #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)       \
+({                              \
+    csr_write(CSR_SISELECT, c); \
+    csr_read(CSR_SIREG);        \
+})
+
   #define imsic_csr_write(c, v)   \
   do {                            \
       csr_write(CSR_SISELECT, c); \
@@ -203,6 +210,15 @@ void imsic_irq_enable(unsigned int irq)
        */
       ASSERT(!local_irq_is_enabled());
 
+    if ( irq == imsic_cfg.sync_id )
+    {
+        printk(XENLOG_WARNING
+               "irq%u is reserved for APLIC sync so shouldn't be set by %s\n",
+               irq, __func__);
+
+        return;
+    }
+
       spin_lock(&imsic_cfg.lock);
       /*
        * There is no irq - 1 here (look at aplic_set_irq_type()) because:
@@ -241,6 +257,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)
   {
@@ -387,6 +412,9 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
 
       imsic_cfg.nr_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1, 64);
 
+    /* Reserve last identity for APLIC-to-hart synchronization */
+    imsic_cfg.sync_id = imsic_cfg.nr_ids;
+
       /* Compute base address */
       *nr_mmios = 0;
       rc = dt_device_get_address(node, *nr_mmios, &base_addr, NULL);
@@ -497,6 +525,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
           on_selected_cpus(cpumask_of(cpu), func, data, 1);
   }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *unused)
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
   static void cf_check imsic_vsfile_local_clear(void *data)
   {
       unsigned int i;
@@ -862,5 +911,8 @@ void imsic_migrate_vcpu(struct vcpu *v)
       /* Zero-out new IMSIC VS-file */
       imsic_call_on_cpu(v->processor, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Avoid an unused-function error until the barrier has a user. */
+    (void)imsic_aplic_sync;
+
       BUG_ON("unimplemented");
   }
xen/arch/riscv/include/asm/aplic.h +3 -0
index 9018936ca95a..bfb510b2ae5e 100644
@@ -94,6 +94,7 @@
   #define APLIC_SETIPNUM_LE               0x2000
 
   #define APLIC_GENMSI                    0x3000
+#define APLIC_GENMSI_BUSY               BIT(12, U)
 
   #define APLIC_TARGET_BASE               0x3004
   #define APLIC_TARGET_LAST               0x3ffc
@@ -177,4 +178,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 /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +1 -0
index 8130d125f5c3..f86407e21765 100644
@@ -62,6 +62,14 @@ struct imsic_config {
        */
       unsigned int nr_eix;
 
+    /*

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

Quoted 10 lines
xen/arch/riscv/include/asm/imsic.h +7 -0
+     * Interrupt identity reserved exclusively for APLIC-to-hart
+     * synchronization.
+     *
+     * Must not be allocated to any interrupt source.
+     */
+    unsigned int sync_id;
+
       /* MSI */
       const struct imsic_msi *msi;
 

I think it also makes sense here to apply the following fixup patch:

commit db57e94ed8405c98d7a21f4f88764fa5e0ea2d04
(riscv-next-upstreaming-fixups)

Author: Oleksii Kurochko <[email protected]>
Date:   Tue Oct 6 15:59:52 2026 +0200

fixup! xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU
migration

In MSI delivery mode the MSI of APLIC source N carries identity N, by which Xen recognises it in its own IMSIC interrupt file. A source numbered sync_id or higher can't be told apart: its identity either isn't implemented, so its MSIs are dropped, or is the one reserved for the sync barrier, which it would satisfy early and whose pending bit would swallow its interrupt. Limit the usable sources to those below sync_id, and document how the identities of Xen's interrupt file are allocated.

xen/arch/riscv/aplic.c +3 -0
index 96aa4edb3958..86ff3cae984d 100644
@@ -246,6 +246,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 */
@@ -270,6 +271,22 @@ static int __init cf_check aplic_init(void)
           panic("%s: failed to get number of interrupt sources\n",
                 node->full_name);
 
+    /*
+     * In MSI delivery mode the MSI of source N carries identity N, by

which

xen/arch/riscv/aplic.c +2 -0
+     * Xen recognises it in its own IMSIC interrupt file. Hence the sources
+     * numbered from sync_id on can't be used: their identities either

aren't
+ * implemented or are the one reserved for the APLIC-IMSIC sync
barrier.

xen/arch/riscv/aplic.c +6 -0
+     */
+    imsic = imsic_get_config();
+    if ( aplic_info.num_irqs >= imsic->sync_id )
+    {
+        printk(XENLOG_WARNING
+               "%s: only %u of %u interrupt sources usable with %u

IMSIC identities\n",

xen/arch/riscv/aplic.c +5 -0
+               node->full_name, imsic->sync_id - 1, aplic_info.num_irqs,
+               imsic->nr_ids);
+        aplic_info.num_irqs = imsic->sync_id - 1;
+    }
+
       guest_aplic_num_sources = min(GUEST_APLIC_MAX_SOURCES,

aplic_info.num_irqs);

       if ( aplic_info.num_irqs > ARRAY_SIZE(aplic.regs->sourcecfg) )
xen/arch/riscv/imsic.c +3 -1
index ca5243826726..408b94b22ee9 100644
@@ -533,7 +533,15 @@ static int __init imsic_parse_node(const struct
 dt_device_node *node,
 
       imsic_cfg.nr_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1, 64);
 
-    /* Reserve last identity for APLIC-to-hart synchronization */
+    /*
+     * The identities of Xen's own interrupt file are allocated statically:
+     *  - the APLIC sources take 1 .. riscv,num-sources, as the MSI of

source
+ * N carries identity N (aplic_init() drops the sources which
don't fit

xen/arch/riscv/imsic.c +2 -0
+     *    below sync_id);
+     *  - the last one, nr_ids, is reserved for APLIC-to-hart

synchronization.

xen/arch/riscv/imsic.c +3 -0
+     * Anything else taking identities from this file has to stay clear of
+     * both.
+     */
       imsic_cfg.sync_id = imsic_cfg.nr_ids;
Quoted 6 lines
Quoted 3 lines
       /* Compute base address */

Any thoughts about it?

LGTM, but I wonder why, as I said in the original patch, sync_id is really needed.

I think that I am not understand your response. Could you please re-phrase it?

~ Oleksii

#113 lore raw

Re: [PATCH v3 29/39] xen/riscv: prepare new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 21 lines · Oleksii Kurochko

[ ... 79 lines skipped ... ]

Quoted 7 lines
Quoted 1 line

+

What does the switch buy? ireg only ends up as the value written to vsiselect, not as a CSR number, so it doesn't need to be a compile-time constant. imsic_vs_csr_write(ireg, val) does the same, without the 128 case labels and the macro pyramid. If there's a reason, it wants stating in a comment; otherwise please drop the pyramid (an ASSERT() on the range can stay if you want one).

Good point.

I will drop it and use the following instead:

/*
* 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)

Quoted 7 lines
{
     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, laid out as described above. */

Nit: "above" may go stale if the code moves. Better to name the function you are referring to.

Also, the parameter isn't an *ireg value. It is the register number written to *iselect; *ireg is only the data window. Per AIA (IMSIC chapter, "Interrupt files"), values 0x80-0xFF of *iselect select eip0-63/eie0-63, and imsic_csr_write() uses its first argument that way:

#define imsic_csr_write(c, v) \

do {                            \
    csr_write(CSR_SISELECT, c); \
    csr_write(CSR_SIREG, v);    \
} while (0)

So I'd rename it to "iselect" (here and in the other helpers taking the same argument).

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

Re: [PATCH v3 30/39] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration

In reply to Oleksii Kurochko
Quoted 7 lines · Oleksii Kurochko

[ ... 348 lines skipped ... ]

Quoted 3 lines

LGTM, but I wonder why, as I said in the original patch, sync_id is really needed.

I think that I am not understand your response. Could you please re-phrase it?

I'm questionning the need of the sync_id field as it will always be equal to imsic_cfg.nr_ids, couldn't we drop it?

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

Re: [PATCH v3 30/39] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration

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

[ ... 348 lines skipped ... ]

Quoted 3 lines

LGTM, but I wonder why, as I said in the original patch, sync_id is really needed.

I think that I am not understand your response. Could you please re-phrase it?

I'm questionning the need of the sync_id field as it will always be equal to imsic_cfg.nr_ids, couldn't we drop it?

It's equal to nr_ids by choice rather than by necessity: which identity gets reserved is decided in a single place, imsic_parse_node(), and all the users (the genmsi write, the pending bit the barrier spins on, the limit on the APLIC sources and the ASSERT() in imsic_irq_enable()) refer to it by its role rather than as "the last identity".

Basically if one day someone will decide to come up with EIID allocator instead of using static allocation then it will be harder to find a places where to change.

So yes, it could be drooped but at the moment I think it is useful to have separate field or ,at least, as an option in asm/imsic.h:

static inline unsigned int imsic_sync_id(const struct imsic_config *cfg)

{
    return cfg->nr_ids;
}

~ Oleksii

#121 lore raw

Re: [PATCH v3 30/39] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration

Quoted 21 lines · Oleksii Kurochko
Quoted 11 lines · Baptiste Le Duc
Quoted 7 lines · Oleksii Kurochko

[ ... 348 lines skipped ... ]

Quoted 3 lines

LGTM, but I wonder why, as I said in the original patch, sync_id is really needed.

I think that I am not understand your response. Could you please re-phrase it?

I'm questionning the need of the sync_id field as it will always be equal to imsic_cfg.nr_ids, couldn't we drop it?

It's equal to nr_ids by choice rather than by necessity: which identity gets reserved is decided in a single place, imsic_parse_node(), and all the users (the genmsi write, the pending bit the barrier spins on, the limit on the APLIC sources and the ASSERT() in imsic_irq_enable()) refer to it by its role rather than as "the last identity".

Quoted 8 lines

Basically if one day someone will decide to come up with EIID allocator instead of using static allocation then it will be harder to find a places where to change.

So yes, it could be drooped but at the moment I think it is useful to have separate field or ,at least, as an option in asm/imsic.h:

static inline unsigned int imsic_sync_id(const struct imsic_config *cfg) {
    return cfg->nr_ids;
}

I prefer this as it would save space in imsic_config struct.

Quoted 1 line

~ Oleksii

#122 lore raw

Re: [PATCH v3 30/39] xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration

Quoted 26 lines · Baptiste Le Duc
Quoted 23 lines · Oleksii Kurochko
Quoted 11 lines · Baptiste Le Duc
Quoted 7 lines · Oleksii Kurochko

[ ... 348 lines skipped ... ]

Quoted 3 lines

LGTM, but I wonder why, as I said in the original patch, sync_id is really needed.

I think that I am not understand your response. Could you please re-phrase it?

I'm questionning the need of the sync_id field as it will always be equal to imsic_cfg.nr_ids, couldn't we drop it?

It's equal to nr_ids by choice rather than by necessity: which identity gets reserved is decided in a single place, imsic_parse_node(), and all the users (the genmsi write, the pending bit the barrier spins on, the limit on the APLIC sources and the ASSERT() in imsic_irq_enable()) refer to it by its role rather than as "the last identity".

Basically if one day someone will decide to come up with EIID allocator instead of using static allocation then it will be harder to find a places where to change.

Quoted 9 lines
Quoted 6 lines

So yes, it could be drooped but at the moment I think it is useful to have separate field or ,at least, as an option in asm/imsic.h:

static inline unsigned int imsic_sync_id(const struct imsic_config *cfg) {
     return cfg->nr_ids;
}

I prefer this as it would save space in imsic_config struct.

Thanks for the clarification. I'll go with that approach, then.

~ Oleksii

#114 lore raw

Re: [PATCH v3 29/39] xen/riscv: prepare new IMSIC VS-file

In reply to Baptiste Le Duc
Quoted 28 lines · Baptiste Le Duc
Quoted 27 lines · Oleksii Kurochko

[ ... 79 lines skipped ... ]

Quoted 7 lines
Quoted 1 line

+

What does the switch buy? ireg only ends up as the value written to vsiselect, not as a CSR number, so it doesn't need to be a compile-time constant. imsic_vs_csr_write(ireg, val) does the same, without the 128 case labels and the macro pyramid. If there's a reason, it wants stating in a comment; otherwise please drop the pyramid (an ASSERT() on the range can stay if you want one).

Good point.

I will drop it and use the following instead:

/*
* 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));
}
Quoted 4 lines
Quoted 1 line

/* Write a whole 64-bit EIx group, laid out as described above. */

Nit: "above" may go stale if the code moves. Better to name the function you are referring to.

Agree with that.

Quoted 5 lines

Also, the parameter isn't an *ireg value. It is the register number written to *iselect; *ireg is only the data window. Per AIA (IMSIC chapter, "Interrupt files"), values 0x80-0xFF of *iselect select eip0-63/eie0-63, and imsic_csr_write() uses its first argument that way:

Quoted 9 lines

#define imsic_csr_write(c, v) \

do {                            \
     csr_write(CSR_SISELECT, c); \
     csr_write(CSR_SIREG, v);    \
} while (0)

So I'd rename it to "iselect" (here and in the other helpers taking the same argument).

As to the name: I'd rather keep ireg. The value does go into *iselect, but what it denotes is a register of the interrupt file: per the AIA spec, values of *iselect in the range 0x70-0xFF select the registers of the interrupt file (eidelivery, eithreshold, eip0-63, eie0-63), and ireg is the number of such a register, eip0-63/eie0-63 here.

~ Oleksii

#125 lore raw

Re: [PATCH v3 31/39] xen/riscv: remap interrupts to new IMSIC VS-file

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

Once the new IMSIC VS-file has been zeroed out, it has to be mapped into the guest's G-stage in place of the old one. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Taking a h/w guest interrupt file (assigning it, zeroing it out, mapping it into G-stage and recording it in the vCPU's IMSIC state) is factored out into imsic_vsfile_acquire().

The relevant translation tables at all IOMMUs would also have to be updated so that MSIs for this virtual interrupt file are sent to the new physical interrupt file, but that is skipped for now as there is no IOMMU support for RISC-V.

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.

If the new file can't be mapped into the guest, release the guest external interrupt number imsic_vsfile_acquire() took for it instead of leaking it. vgein_release() takes the pCPU explicitly instead of relying on v->processor, as on migration v->processor already refers to the new pCPU while the number to be released may belong to the old one.

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

Implement imsic_update_state(), which records the vCPU's guest interrupt file id together with the pCPU owning the file. The two are read as a pair, e.g. by imsic_migrate_vcpu() and the IMSIC context switch hooks, so they are updated under vsfile_lock as a single unit.

Quoted 7 lines
Quoted 1 line

imsic_map_guest_file() and vgein_release() are stubs for now.

I have the feeling this patch does more than its subject says: besides retargeting the APLIC and adding the sync, it introduces imsic_vsfile_acquire() (assign + clear + G-stage map + state update), imsic_update_state() and the error path, which relies on two stubs, imsic_map_guest_file() and vgein_release().

These are the steps the AIA spec lists for moving the interrupt producers to the new file: map the new file into G-stage in place of the old one, retarget the APLIC and synchronize with it. imsic_vsfile_acquire() and imsic_update_state() are just how the "take and map a new file" part is split out, so I'd still say they belong to this patch. Your point below, that none of this can run yet, is the real issue though.

Quoted 9 lines

At this point vgein_assign()
is still BUG_ON("unimplemented") too, so none of the new code can actually run, and the error path can't be reviewed against the real vgein_release().

Also, until "introduce IMSIC h/w interrupt file attaching to vcpu", no vCPU ever owns a h/w file, so imsic_migrate_vcpu() can only hit the CPU_NONE check.

Quoted 7 lines

Wouldn't it be simpler to move the two already-acked patches and the attach first, so that no stubs are needed and each migration step is written against its real callees when it lands:
- Add basic VGEIN management for AIA guests (real vgein_assign() and vgein_release(); the reason for the explicit cpu argument of vgein_release() would then have to go into this commit message)
- Map IMSIC interrupt file for vCPUs (real imsic_map_guest_file())

I think I have such order before and it was changed becuase for locks in the first patch it wasn't enough context to understand if they are needed or not.

Quoted 9 lines

- Implement continue_new_vcpu() and set hstatus.VSXL
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user (acquire, vaplic_reconfigure_target(), set hstatus.VGEIN)
- Prepare new IMSIC VS-file (on top of imsic_vsfile_acquire())
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file (APLIC retarget + sync)
- Save/clear old VS-file, restore, SGEI wake-up as today

Quoted 4 lines

A side benefit: attach no longer has to be squeezed into the finished migration code, so imsic_vsfile_move() with its first_attach argument and the goto set_vgein go away. Attach stays a plain sequence, and imsic_migrate_vcpu() simply reuses imsic_vsfile_acquire().

I'm fine with that order. It does mean that "add basic VGEIN management" and "map IMSIC interrupt file for vCPUs" introduce functions whose first user only comes with the attach patch a few patches later. If that's acceptable, I'll add a post-commit note to each of them saying where the functions get used (as IIUC, they will first introduced and then used in later patches).

Quoted 5 lines

Migrating a vCPU which has already run would still hit the trailing BUG_ON("unimplemented") until the restore patch, but that is no worse than the panic() it hits today.

~ Oleksii

#132 lore raw

Re: [PATCH v3 32/39] xen/riscv: save and clear the old IMSIC VS-file on vCPU migration

In reply to Baptiste Le Duc
Quoted 22 lines · Baptiste Le Duc
Quoted 12 lines

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.

Quoted 9 lines

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 guest interrupt file, which is how the AIA specification describes MRIFs being used by a hypervisor.

Quoted 2 lines

I think it's worth mentioning that this MRIF structure could be reused for software interrupt files later.

I'm fine with making that explicit. I tried to cover it with "... a vCPU which doesn't own a guest interrupt file ...", and adding "hardware" should make it clearer: "... a vCPU which doesn't own a hardware guest interrupt file ...". I think that covers your suggestion as well, so I'll add it.

To be honest, I'm a bit unsure how much to say about software interrupt files at this point: some earlier commit messages mentioned them, and I was asked to drop that, as they are neither introduced nor used yet. That's why I'd rather keep the wording implicit as above, but if you
still prefer them to be named explicitly, I can add a sentence.

At this point, I'm honestly getting a bit confused about how commit messages are supposed to be written.

Quoted 6 lines
Quoted 6 lines

[ ... 172 lines skipped ... ]

xen/arch/riscv/imsic.c +5 -0
+static void cf_check imsic_vsfile_local_read_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;
Quoted 8 lines

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_clear(void *data) · line 674

Quoted 7 lines
xen/arch/riscv/imsic.c +7 -0
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /*
+     * The file is reached by retargeting hstatus.VGEIN, and
+     * imsic_vs_csr_swap() alters vsiselect. Both belong to the vCPU running
+     * on this pCPU, so restore them before returning.
+     */

You're saving the registers here, not restoring them.

It was about CSR_HSTATUS, and CSR_VSISELECT which are stored and restored:

+ csr_write(CSR_HSTATUS, old_hstatus);
+ csr_write(CSR_VSISELECT, old_vsiselect);

Quoted 8 lines

I'd use something
like:
/*
* vsiselect/vsireg only reach the guest interrupt file selected by
* hstatus.VGEIN, so point VGEIN at this file for the access.
* hstatus and vsiselect hold the state of the vCPU running on this
* pCPU; save them here and restore them before returning. */

I agree that this option is clearer.

Also, as the same switch to a guest interrupt file is done in
three more places (in the prev patches), I'll factor it out into imsic_vsfile_select() and imsic_vsfile_deselect(), with your wording as the comment on them.

Quoted 12 lines

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_clear(void *data) · line 685

Quoted 12 lines
xen/arch/riscv/imsic.c +11 -0
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    /*
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
+     */
Quoted 2 lines

Nit: is this blank line really needed?

No real need. Lets drop it.

Thanks for review!

~ Oleksii

#136 lore raw

Re: [PATCH v3 33/39] xen/riscv: restore register state in the new IMSIC VS-file

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

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.

Could we send an extempore MSI to the hart of the new file once the interrupt producers have been retargeted, and spin until it is received? That would guarantee that no more MSIs land once we have received it.

I don't think it's needed. The barrier is there so that nothing gets lost from the old file: once the extempore MSI sent to the hart of the old file has arrived, every MSI the APLIC sent towards the old file before the retargeting has landed there, so what's read out of the old file is complete.

MSIs sent after the retargeting go to the new file, and they can keep arriving at any time, including while the saved state is being restored, so an extempore MSI to the hart of the new file wouldn't stop them anyway: it would only tell that the MSIs sent before it have arrived. That's why the saved eip/eie bits are ORed into the new file rather than written to it, so that whatever lands there in the meantime is kept, and why eidelivery is restored last, so that the new file doesn't deliver anything until its state is complete.

Quoted 15 lines
Quoted 6 lines

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.

Quoted 8 lines

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 is migrating to.

Finally, point hstatus.VGEIN in the vCPU's saved context 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")

Great!

Quoted 8 lines

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

Quoted 6 lines

[ ... 82 lines skipped ... ]

xen/arch/riscv/imsic.c +5 -0
+static void cf_check imsic_vsfile_local_update(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;

mrif is only read here, so it can be const:

     const struct imsic_mrif *mrif = idata->mrif;

Good point. I will apply that.

Quoted 12 lines
Quoted 12 lines
xen/arch/riscv/imsic.c +12 -0
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*
+     * No atomic accessors are needed to read the values out of the MRIF here,
+     * as this is always called with a pointer to a temporary MRIF on the
+     * stack.
+     */
+
Quoted 8 lines

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

Quoted 5 lines
xen/arch/riscv/imsic.c +5 -0
+    /*
+     * The file is reached by retargeting hstatus.VGEIN, and the
+     * imsic_vs_csr_*() accessors alter vsiselect. Both belong to the vCPU
+     * running on this pCPU, so restore them before returning.
+     */

Same comment as on the previous patch: you are not restoring the CSRs here but saving them, as imsic_vs_csr_*() will alter vsiselect. Please update the comment accordingly.

Sure! As I mentioned in reply to prev. patch I think that it would be better to factor out the sequence of work with hstatus&vsiselect to separate helpers, put your comment suggestion above the helpers once.

Quoted 5 lines
Quoted 5 lines

[ ... 32 lines skipped ... ]

xen/arch/riscv/imsic.c +0 -0
@@ -1152,5 +1222,11 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Free-up old IMSIC VS-file */
      vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
Quoted 7 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1228

Quoted 5 lines
xen/arch/riscv/imsic.c +4 -1
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    imsic_call_on_cpu(v->processor, imsic_vsfile_local_update, &vsfile_data);
+
+    /* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */

Nit: s/VCPU/vCPU/

Acked.

Thanks for review.

~ Oleksii

#141 lore raw

Re: [PATCH v3 35/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Baptiste Le Duc
Quoted 15 lines · Baptiste Le Duc
Quoted 6 lines

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

Quoted 8 lines

Let Xen observe the file in that window: on deschedule set the vCPU's bit in HGEIE, which turns an interrupt pending in its VS-file into an HS-level SGEI, and clear the bit again on schedule-in. HGEIP only reports 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.

Quoted 8 lines

Please explain why this is enough for a descheduled
vCPU to never miss a wake-up: an interrupt pending in a VS-file always shows up in HGEIP, but it reaches VS-mode only if hstatus.VGEIN selects that file, and traps to Xen as an SGEI only if the file's HGEIE bit is set. While the vCPU is descheduled, HGEIE is therefore Xen's only way to notice it. And as HGEIP reflects the file's current state rather than being latched, an interrupt which arrived before the bit got set still raises the SGEI once it is.

Will add, thanks.

Quoted 23 lines
Quoted 5 lines

[ ... 49 lines skipped ... ]

xen/arch/riscv/aia.c struct vgein_ctrl { · line 27

Quoted 10 lines
xen/arch/riscv/aia.c +7 -0
@@ -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];

It looks like owners[] already carries the information bmp provides. Couldn't we drop bmp and use owners[] alone, with owners[i] == NULL meaning that file i is free? That would avoid having to keep the two in sync, and vgein_release() could then check ASSERT(owners[id] == v) rather than just that the bit was set. A linear scan over 1..geilen in vgein_assign() should be fine given geilen < BITS_PER_LONG.

Quoted 3 lines

If you agree, it would probably be cleaner to introduce owners[] in place of bmp in the earlier "add basic VGEIN management" patch, rather than adding bmp there and replacing it here.

It would work, but I'd rather keep bmp: it's updated together with
owners[], under the same lock, in vgein_assign() and vgein_release()
only, so there isn't much to keep in sync. It also keeps the state of
all the files in a single word, so a free VGEIN ID is found with a
single find_next_zero_bit() rather than by iterating over owners[] (but I could agree that likely not a big win), and the debug output can print it as is.

The stronger check in vgein_release() is a good idea regardless, so I'll add ASSERT(vgein->owners[vgein_id] == v) here.

Quoted 16 lines
Quoted 16 lines

[ ... 26 lines skipped ... ]

xen/arch/riscv/aia.c +15 -0
+
+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);
+
+    /*
+     * Bit 0 of HGEIP/HGEIE is read-only zero: guest interrupt file ID 0
Quoted 8 lines

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 199

Quoted 3 lines
xen/arch/riscv/aia.c +3 -0
+     * means that no guest external interrupt source is selected.
+     */
+    ASSERT(!(hgei_mask & 1));

Is this ASSERT() really needed? Bit 0 of HGEIP/HGEIE is read-only zero per the spec, and vgein_init() already relies on that when computing geilen. Even if it were ever reported, owners[0] is never assigned, so the loop below would simply skip it.

Agreed, lets drop it.

Quoted 5 lines
Quoted 5 lines

[ ... 35 lines skipped ... ]

xen/arch/riscv/imsic.c +0 -0
@@ -555,12 +555,37 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *p)
 
Quoted 11 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *p) · line 561

Quoted 6 lines
xen/arch/riscv/imsic.c +4 -0
      write_lock_irqsave(&imsic_state->vsfile_lock, flags);
      imsic_state->vsfile_cpu = p->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.

"instead of" reads as if HGEIP only reports it while the vCPU isn't running. It always does; what changes is that VGEIN no longer selects the file and the HGEIE bit set below turns it into an SGEI.

Right, I'll reword it accordingly.

Quoted 32 lines

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 726

Quoted 10 lines

[ ... 29 lines skipped ... ]
int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)

xen/arch/riscv/imsic.c +4 -0
@@ -695,6 +720,12 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
      struct imsic_mrif *mrif = idata->mrif;
      unsigned long new_hstatus, old_hstatus, old_vsiselect;
 
+    /*
+     * The HGEIE bit imsic_ctxt_switch_from() armed belongs to the old owner
+     * only.
+     */

"Old owner" is ambiguous: it reads like another vCPU, but it's the same vCPU on the file it is leaving. To mirror imsic_local_hgeie_set(), I'd rather have an imsic_local_hgeie_clear() called from here, documenting the pairing the same way, e.g.:

/*
* Stop observing an interrupt file which a vCPU leaves when it moves to
* another pCPU by clearing the bit imsic_ctxt_switch_from() set. *
* Counterpart of imsic_local_hgeie_set() for the new file. */

In that case ...

Quoted 9 lines
xen/arch/riscv/imsic.c +2 -0
+    csr_clear(CSR_HGEIE, BIT(idata->hgei, UL));
+
      /*
       * The file is reached by retargeting hstatus.VGEIN, and
       * imsic_vs_csr_swap() alters vsiselect. Both belong to the vCPU running
@@ -1044,6 +1075,21 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
      return fdt_end_node(fdt);
  }
 
Quoted 9 lines

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

Quoted 7 lines
xen/arch/riscv/imsic.c +7 -0
+/*
+ * Start to observe the interrupt file from HS-mode, the same way
+ * imsic_ctxt_switch_from() does it for a vCPU which is switched out.
+ *
+ * The counterpart, clearing the bit of the interrupt file which is left
+ * behind, is done by imsic_vsfile_local_read_clear(), which already runs on
+ * the pCPU owning that file.

... this wouldn't be needed at all.

Agreed, I'll introduce imsic_local_hgeie_clear() next to imsic_local_hgeie_set(), with your comment. It'll take the file number rather than void *, though, as it's called directly from imsic_vsfile_local_read_clear() and not through imsic_call_on_cpu().

~ Oleksii

#145 lore raw

Re: [PATCH v3 37/39] xen/riscv: implement continue_new_vcpu()

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

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, which restores hstatus and sepc, passes the hart id in a0 and, in a1, either the DTB address (boot vCPU, as expected by the RISC-V boot protocol) or the opaque value passed to SBI HSM hart_start() (secondary vCPUs), clears the remaining GPRs, sets sstatus.SPP and sstatus.SPIE and executes sret.

Nit: the guest vCPU sentence is hard to follow in one go. Maybe split it:

Quoted 7 lines

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

Thanks for the suggestion. I'll use this wording.

Quoted 5 lines
Quoted 5 lines

[ ... 94 lines skipped ... ]

xen/arch/riscv/entry.S +0 -0
@@ -147,3 +147,42 @@ FUNC(__context_switch)
 
Quoted 16 lines

xen/arch/riscv/entry.S FUNC(__context_switch) · line 158

Quoted 11 lines
xen/arch/riscv/entry.S +9 -0
          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
+

At this point regs->hstatus only has SPV | SPVP (arch_vcpu_create()), so VSXL is written as 0, which is a reserved encoding. That only gets fixed by "xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL", which comes later in the series. Wouldn't it be better to move that one ahead of this patch?

Agreed. I'll move "xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL" before this patch.

Quoted 3 lines

Thanks!

~ Oleksii

#148 lore raw

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

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

[ ... 97 lines skipped ... ]

xen/arch/riscv/domain.c +14 -0
@@ -51,6 +51,119 @@ 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().
+ *
+ * The switch() deliberately has no default case, so that adding a new
+ * domain_type (a 128-bit one, in particular) fails to build until this
+ * mapping is updated.
+ */
+unsigned int domain_vsxl(const struct domain *d)
+{
+    switch ( d->type )
+    {
+    case DOMAIN_32BIT:
Quoted 8 lines

xen/arch/riscv/domain.c static struct csr_masks __ro_after_init csr_masks; · line 71

Quoted 4 lines
xen/arch/riscv/domain.c +4 -0
+        return XLEN_FIELD_32;
+
+    case DOMAIN_64BIT:
+        return XLEN_FIELD_64;

Couldn't we add to avoid having to explain why there is no default in the comment above, and to respect MISRA rules?
default:
break

I'd rather not: d->type is an enum, and for those Xen deliberately omits the default label, as -Wall enables -Wswitch, which breaks the build (-Werror) if one of the enum's values isn't handled. A default label would silence exactly that check. MISRA-wise this is covered by the R16.4 deviation for switches on enums.

I'll move the explanation into the switch() itself, though, and mention -Wswitch there, which should make the intent clearer:

...

    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.
     */
    }

...

Quoted 11 lines

xen/arch/riscv/domain.c static struct csr_masks __ro_after_init csr_masks; · line 77

Quoted 6 lines
xen/arch/riscv/domain.c +6 -0
+    }
+
+    ASSERT_UNREACHABLE();
+
+    /* A reserved encoding, which hstatus_vsxl_settable() never accepts. */
+    return 0;

Could this get a name next to XLEN_FIELD_{32,64,128} in riscv_encoding.h, e.g.:

#define XLEN_FIELD_RESERVED _UL(0)
so the comment isn't the only thing explaining the 0?

Sure, I'll add XLEN_FIELD_RESERVED and return it there.

Quoted 21 lines

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

Quoted 13 lines

[ ... 88 lines skipped ... ]

xen/arch/riscv/domain.c +5 -0
+
  void __init init_csr_masks(void)
  {
      /*
@@ -91,6 +204,10 @@ static void vcpu_csr_init(struct vcpu *v)
  {
      v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
+    /*
+     * hstatus.VSXL is left zero here: the domain's type, and hence the
+     * guest's XLEN, is only known once its kernel image has been probed.
+     */

"Probe" refers to two different things in this series: the hardware probe of the settable hstatus.VSXL values (init_hstatus_vsxl_settable_mask()) and the guest kernel header parsing (kernel_probe()). This comment is about the latter, but it is easy to read it as the former, which already ran at boot. Could you name it explicitly and state the ordering that actually matters? I'd suggest:

Quoted 6 lines

/*
* 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.
*/

Your suggested rewording looks good to me. I'll take your wording, and name kernel_probe() in the commit message as well, which has the same ambiguity.

Thanks.

~ Oleksii

#152 lore raw

Re: [PATCH v3 39/39] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu

In reply to Baptiste Le Duc
Quoted 29 lines · Baptiste Le Duc
Quoted 21 lines

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().

Giving a vCPU its first file shares most of the steps with moving it to a new one on migration, so move the body of imsic_migrate_vcpu() to imsic_vsfile_move() and use it for both. Its first_attach argument skips the part which moves the interrupt state out of the old 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.

Quoted 4 lines

vAPLIC target registers are reconfigured on the first attach as well: a target the guest writes for a vCPU which has no h/w guest interrupt file yet only updates the stored copy, which reaches the h/w at this point.

Nit: I didn't quite understand this paragraph, "only updates" leaves out that the h/w APLIC write is skipped, because there is no file to point the target at yet. Maybe something like:

Quoted 6 lines

The guest may program a vAPLIC TARGET register for a vCPU which has not run yet. That vCPU has no h/w guest interrupt file yet, so vaplic_mmio_write() only stores the value. imsic_vsfile_move() then writes it to the h/w APLIC on the first attach, pointing to the newly acquired file.

Agreed, I'll reword it along those lines, naming vaplic_target_write(), which is where the value gets stored, and vaplic_reconfigure_target(), which is what writes it to the h/w APLIC on the first attach:

```
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_move()
calls vaplic_reconfigure_target() on the first attach as well, which
writes the stored value to the h/w APLIC, pointing it at the newly
acquired file.
```
Quoted 2 lines

Thanks for the review!

~ Oleksii

#126 lore raw

Re: [PATCH v3 31/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 37 lines · Oleksii Kurochko

[ ... 52 lines skipped ... ]

Quoted 9 lines

At this point vgein_assign()
is still BUG_ON("unimplemented") too, so none of the new code can actually run, and the error path can't be reviewed against the real vgein_release().

Also, until "introduce IMSIC h/w interrupt file attaching to vcpu", no vCPU ever owns a h/w file, so imsic_migrate_vcpu() can only hit the CPU_NONE check.

Quoted 7 lines

Wouldn't it be simpler to move the two already-acked patches and the attach first, so that no stubs are needed and each migration step is written against its real callees when it lands:
- Add basic VGEIN management for AIA guests (real vgein_assign() and vgein_release(); the reason for the explicit cpu argument of vgein_release() would then have to go into this commit message)
- Map IMSIC interrupt file for vCPUs (real imsic_map_guest_file())

I think I have such order before and it was changed becuase for locks in the first patch it wasn't enough context to understand if they are needed or not.

Quoted 9 lines

- Implement continue_new_vcpu() and set hstatus.VSXL
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user (acquire, vaplic_reconfigure_target(), set hstatus.VGEIN)
- Prepare new IMSIC VS-file (on top of imsic_vsfile_acquire())
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file (APLIC retarget + sync)
- Save/clear old VS-file, restore, SGEI wake-up as today

Quoted 4 lines

A side benefit: attach no longer has to be squeezed into the finished migration code, so imsic_vsfile_move() with its first_attach argument and the goto set_vgein go away. Attach stays a plain sequence, and imsic_migrate_vcpu() simply reuses imsic_vsfile_acquire().

Quoted 7 lines

I'm fine with that order. It does mean that "add basic VGEIN management" and "map IMSIC interrupt file for vCPUs" introduce functions whose first user only comes with the attach patch a few patches later. If that's acceptable, I'll add a post-commit note to each of them saying where the functions get used (as IIUC, they will first introduced and then used in later patches).

Yes, the post-commit notes are fine with me. IMO it's better to introduce the real functions before their first caller, even if that caller only lands a few patches later, than to write callers against stubs. That way each migration step is written against its real callees, and the order follows how IMSIC actually works: a vCPU gets a file on its first run, and only then can that file be migrated.

The locks in the VGEIN patch would then get a real user a few patches later (the attach patch), and that patch's commit message can explain why they are needed.

What do you think of something like this, after "introduce vaplic_reconfigure_target()"?

- Set the guest's XLEN explicitly in hstatus.VSXL (moved before continue_new_vcpu(), with the vcpu_set_vsxl() call added to its stub, so that no commit enters a guest with an undefined VSXL)
- Implement continue_new_vcpu()
- Add basic VGEIN management for AIA guests (acked; the commit message would have to explain the explicit cpu argument of vgein_release())
- Map IMSIC interrupt file for vCPUs (acked)
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user
=== migration
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file ("Prepare new IMSIC VS-file" folded in, as with imsic_vsfile_acquire() already there it is reduced to a single call)
- Save and clear the old IMSIC VS-file on vCPU migration
- Restore register state in the new IMSIC VS-file
- Wake up a descheduled vCPU on a guest external interrupt (last, as it arms HGEIE in imsic_migrate_vcpu() and clears it in imsic_vsfile_local_read_clear())

But I'm not an expert in patch series management, so I may be wrong.

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

Re: [PATCH v3 32/39] xen/riscv: save and clear the old IMSIC VS-file on vCPU migration

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko

[ ... 25 lines skipped ... ]

Quoted 2 lines

I think it's worth mentioning that this MRIF structure could be reused for software interrupt files later.

I'm fine with making that explicit. I tried to cover it with "... a vCPU which doesn't own a guest interrupt file ...", and adding "hardware" should make it clearer: "... a vCPU which doesn't own a hardware guest interrupt file ...". I think that covers your suggestion as well, so I'll add it.

Quoted 5 lines

To be honest, I'm a bit unsure how much to say about software interrupt files at this point: some earlier commit messages mentioned them, and I was asked to drop that, as they are neither introduced nor used yet. That's why I'd rather keep the wording implicit as above, but if you still prefer them to be named explicitly, I can add a sentence.

Agreed, keep it implicit.

Quoted 3 lines

At this point, I'm honestly getting a bit confused about how commit messages are supposed to be written.

Sorry for the confusion. I'm generally not a fan of mentioning things which don't exist yet, but here the commit message explains why the MRIF layout is used, and the spec ties MRIFs closely to s/w interrupt files, so I wondered whether a short hint would help. The implicit wording is fine too.

I should have marked it as a nit. As I said before, your commit messages are great, and this was just my subjective opinion, possibly partly because I'm not a native English speaker. Feel free to discard such remarks whenever you don't find them accurate ;)

Quoted 7 lines

[ ... 49 lines skipped ... ]

Quoted 2 lines

Nit: is this blank line really needed?

No real need. Lets drop it.

Thanks for review!

You're wecome!

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

Re: [PATCH v3 33/39] xen/riscv: restore register state in the new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 7 lines · Oleksii Kurochko

[ ... 13 lines skipped ... ]
I don't think it's needed. The barrier is there so that nothing gets lost from the old file: once the extempore MSI sent to the hart of the old file has arrived, every MSI the APLIC sent towards the old file before the retargeting has landed there, so what's read out of the old file is complete.

Quoted 9 lines

MSIs sent after the retargeting go to the new file, and they can keep arriving at any time, including while the saved state is being restored, so an extempore MSI to the hart of the new file wouldn't stop them anyway: it would only tell that the MSIs sent before it have arrived. That's why the saved eip/eie bits are ORed into the new file rather than written to it, so that whatever lands there in the meantime is kept, and why eidelivery is restored last, so that the new file doesn't deliver anything until its state is complete.

Ok it's more clear thanks!

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

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

In reply to Oleksii Kurochko
Quoted 4 lines · Oleksii Kurochko

[ ... 33 lines skipped ... ]
I'd rather not: d->type is an enum, and for those Xen deliberately omits the default label, as -Wall enables -Wswitch, which breaks the build (-Werror) if one of the enum's values isn't handled.

I didn't know that, so yes, you're right it's better to keep without default.

Quoted 11 lines

A default label
would silence exactly that check. MISRA-wise this is covered by the R16.4 deviation for switches on enums.

I'll move the explanation into the switch() itself, though, and mention -Wswitch there, which should make the intent clearer:

...
case DOMAIN_64BIT:
return XLEN_FIELD_64;

Quoted 5 lines

/*
* 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.
*/

More clear, thanks.

Quoted 4 lines

[ ... 44 lines skipped ... ]
Your suggested rewording looks good to me. I'll take your wording, and name kernel_probe() in the commit message as well, which has the same ambiguity.

Agree, thanks.

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

Re: [PATCH v3 31/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Baptiste Le Duc
Quoted 79 lines · Baptiste Le Duc
Quoted 37 lines · Oleksii Kurochko

[ ... 52 lines skipped ... ]

Quoted 9 lines

At this point vgein_assign()
is still BUG_ON("unimplemented") too, so none of the new code can actually run, and the error path can't be reviewed against the real vgein_release().

Also, until "introduce IMSIC h/w interrupt file attaching to vcpu", no vCPU ever owns a h/w file, so imsic_migrate_vcpu() can only hit the CPU_NONE check.

Quoted 7 lines

Wouldn't it be simpler to move the two already-acked patches and the attach first, so that no stubs are needed and each migration step is written against its real callees when it lands:
- Add basic VGEIN management for AIA guests (real vgein_assign() and vgein_release(); the reason for the explicit cpu argument of vgein_release() would then have to go into this commit message)
- Map IMSIC interrupt file for vCPUs (real imsic_map_guest_file())

I think I have such order before and it was changed becuase for locks in the first patch it wasn't enough context to understand if they are needed or not.

Quoted 9 lines

- Implement continue_new_vcpu() and set hstatus.VSXL
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user (acquire, vaplic_reconfigure_target(), set hstatus.VGEIN)
- Prepare new IMSIC VS-file (on top of imsic_vsfile_acquire())
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file (APLIC retarget + sync)
- Save/clear old VS-file, restore, SGEI wake-up as today

Quoted 4 lines

A side benefit: attach no longer has to be squeezed into the finished migration code, so imsic_vsfile_move() with its first_attach argument and the goto set_vgein go away. Attach stays a plain sequence, and imsic_migrate_vcpu() simply reuses imsic_vsfile_acquire().

Quoted 7 lines

I'm fine with that order. It does mean that "add basic VGEIN management" and "map IMSIC interrupt file for vCPUs" introduce functions whose first user only comes with the attach patch a few patches later. If that's acceptable, I'll add a post-commit note to each of them saying where the functions get used (as IIUC, they will first introduced and then used in later patches).

Yes, the post-commit notes are fine with me. IMO it's better to introduce the real functions before their first caller, even if that caller only lands a few patches later, than to write callers against stubs. That way each migration step is written against its real callees, and the order follows how IMSIC actually works: a vCPU gets a file on its first run, and only then can that file be migrated.

The locks in the VGEIN patch would then get a real user a few patches later (the attach patch), and that patch's commit message can explain why they are needed.

What do you think of something like this, after "introduce vaplic_reconfigure_target()"?

- Set the guest's XLEN explicitly in hstatus.VSXL (moved before continue_new_vcpu(), with the vcpu_set_vsxl() call added to its stub, so that no commit enters a guest with an undefined VSXL)
- Implement continue_new_vcpu()
- Add basic VGEIN management for AIA guests (acked; the commit message would have to explain the explicit cpu argument of vgein_release())
- Map IMSIC interrupt file for vCPUs (acked)
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user
=== migration
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file ("Prepare new IMSIC VS-file" folded in, as with imsic_vsfile_acquire() already there it is reduced to a single call)
- Save and clear the old IMSIC VS-file on vCPU migration
- Restore register state in the new IMSIC VS-file
- Wake up a descheduled vCPU on a guest external interrupt (last, as it arms HGEIE in imsic_migrate_vcpu() and clears it in imsic_vsfile_local_read_clear())

Quoted 1 line

But I'm not an expert in patch series management, so I may be wrong.

Let's see how it works. I'll try to reshuffle the patches as suggested.

Thanks for the suggestion!

~ Oleksii

#128 lore raw

Re: [PATCH v3 31/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 62 lines · Oleksii Kurochko
Quoted 59 lines · Baptiste Le Duc
Quoted 37 lines · Oleksii Kurochko

[ ... 52 lines skipped ... ]

Quoted 9 lines

At this point vgein_assign()
is still BUG_ON("unimplemented") too, so none of the new code can actually run, and the error path can't be reviewed against the real vgein_release().

Also, until "introduce IMSIC h/w interrupt file attaching to vcpu", no vCPU ever owns a h/w file, so imsic_migrate_vcpu() can only hit the CPU_NONE check.

Quoted 7 lines

Wouldn't it be simpler to move the two already-acked patches and the attach first, so that no stubs are needed and each migration step is written against its real callees when it lands:
- Add basic VGEIN management for AIA guests (real vgein_assign() and vgein_release(); the reason for the explicit cpu argument of vgein_release() would then have to go into this commit message)
- Map IMSIC interrupt file for vCPUs (real imsic_map_guest_file())

I think I have such order before and it was changed becuase for locks in the first patch it wasn't enough context to understand if they are needed or not.

Quoted 9 lines

- Implement continue_new_vcpu() and set hstatus.VSXL
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user (acquire, vaplic_reconfigure_target(), set hstatus.VGEIN)
- Prepare new IMSIC VS-file (on top of imsic_vsfile_acquire())
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file (APLIC retarget + sync)
- Save/clear old VS-file, restore, SGEI wake-up as today

Quoted 4 lines

A side benefit: attach no longer has to be squeezed into the finished migration code, so imsic_vsfile_move() with its first_attach argument and the goto set_vgein go away. Attach stays a plain sequence, and imsic_migrate_vcpu() simply reuses imsic_vsfile_acquire().

Quoted 7 lines

I'm fine with that order. It does mean that "add basic VGEIN management" and "map IMSIC interrupt file for vCPUs" introduce functions whose first user only comes with the attach patch a few patches later. If that's acceptable, I'll add a post-commit note to each of them saying where the functions get used (as IIUC, they will first introduced and then used in later patches).

Yes, the post-commit notes are fine with me. IMO it's better to introduce the real functions before their first caller, even if that caller only lands a few patches later, than to write callers against stubs. That way each migration step is written against its real callees, and the order follows how IMSIC actually works: a vCPU gets a file on its first run, and only then can that file be migrated.

The locks in the VGEIN patch would then get a real user a few patches later (the attach patch), and that patch's commit message can explain why they are needed.

What do you think of something like this, after "introduce vaplic_reconfigure_target()"?

Quoted 6 lines
Quoted 6 lines

- Set the guest's XLEN explicitly in hstatus.VSXL (moved before continue_new_vcpu(), with the vcpu_set_vsxl() call added to its stub, so that no commit enters a guest with an undefined VSXL)
- Implement continue_new_vcpu()
- Add basic VGEIN management for AIA guests (acked; the commit message would have to explain the explicit cpu argument of vgein_release())

Would you be okay with such explanation:

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.

I tried to write in the way as it is requirement to API rather than a description of the code which will be introduced later somewhere in "=== migration"

~ Oleksii

Quoted 19 lines
Quoted 14 lines

- Map IMSIC interrupt file for vCPUs (acked)
- Attach a h/w interrupt file to a vCPU on its first run, introducing imsic_vsfile_acquire() and imsic_update_state() with their first user === migration
- Implement APLIC-IMSIC-hart sync barrier for vCPU migration
- Remap interrupts to the new IMSIC VS-file ("Prepare new IMSIC VS-file" folded in, as with imsic_vsfile_acquire() already there it is reduced to a single call)
- Save and clear the old IMSIC VS-file on vCPU migration
- Restore register state in the new IMSIC VS-file
- Wake up a descheduled vCPU on a guest external interrupt (last, as it arms HGEIE in imsic_migrate_vcpu() and clears it in imsic_vsfile_local_read_clear())

Quoted 1 line

But I'm not an expert in patch series management, so I may be wrong.

Let's see how it works. I'll try to reshuffle the patches as suggested.

Thanks for the suggestion!

#129 lore raw

Re: [PATCH v3 31/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 9 lines · Oleksii Kurochko

Would you be okay with such explanation:

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.

I tried to write in the way as it is requirement to API rather than a description of the code which will be introduced later somewhere in "=== migration"

LGTM!

Quoted 1 line

~ Oleksii

#48 lore raw

Re: [PATCH v3 11/39] xen/riscv: implement vCPU context switching

In reply to Oleksii Kurochko
Quoted 11 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +7 -0
@@ -323,6 +326,130 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+static void csr_regs_ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * csr_regs_ctxt_switch_to() and guest can't access them so they shouldn't
+     * be stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 345

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+     *
+     * p->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * p->arch.hideleg = csr_read(CSR_HIDELEG);
+     * p->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * p->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * p->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     p->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */

I don't understand this comment. Whether the guest can access a CSR doesn't matter very much. If Xen modifies it on the guest's behalf, it may still need saving/restoring. The question for each individual one is: Can its value (or the guest-affecting fields of it) be reconstructed from other state? Or is what it holds global state? Or are p->arch.* fields reliably kept in sync with what is stored in the hw register?

Quoted 21 lines
xen/arch/riscv/domain.c +21 -0
+    p->arch.hvip = csr_read(CSR_HVIP);
+
+    p->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    p->arch.vsie = csr_read64(CSR_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 csr_regs_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(CSR_HENVCFG, n->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, n->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, n->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 377

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+        csr_write(CSR_HSTATEEN0, n->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, n->arch.vsstatus);
+    csr_write64(CSR_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);
+}

Btw, for both function names possibly s/csr_regs/csrs/ ? Or even just singular?

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

Quoted 8 lines
xen/arch/riscv/include/asm/csr.h +4 -0
@@ -72,6 +79,12 @@
     (void)csr ## H;                 \
     csr_read(csr);                  \
 })
+
+#define csr_read64(csr)             \
+({                                  \
+    (void)csr ## H;                 \

I continue to not really understand what use this is.

xen/arch/riscv/include/asm/system.h static inline bool local_irq_is_enabled(void) · line 79

Quoted 7 lines
xen/arch/riscv/include/asm/system.h +1 -0
@@ -76,6 +76,8 @@ static inline bool local_irq_is_enabled(void)
 
 #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
+struct vcpu *__context_switch(struct vcpu *prev, const struct vcpu *next);

asmlinkage (at least for Misra's sake)?

Jan

Acked-by
#53 lore raw

Re: [PATCH v3 12/39] xen/riscv: save and restore vsiselect on vCPU context switch

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

vsiselect is a per-hart CSR which a guest changes on its own: when V=1, VS-mode accesses to siselect are really accesses to vsiselect. Architecturally a vCPU has to find there the value it last wrote, but as long as the CSR isn't part of the vCPU context it finds whatever selector the vCPU which ran on the hart before it left behind. A guest which writes siselect, is descheduled and then reads sireg without rewriting siselect therefore reaches a register it never selected, and it can also observe another guest's selector value.

Nit: I'd suggest a more tighter version that might be more clear. Feel free to use it:

    ```
    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.
    ```
Quoted 13 lines

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.

Quoted 6 lines
Quoted 4 lines

Without Smstateen no bit controls access to the CSR, so it is saved and restored whenever Ssaia is available.

Acked-by on v3 14/39
#59 lore raw

Re: [PATCH v3 14/39] xen/riscv: add IMSIC vCPU context switch handlers

In reply to Oleksii Kurochko
Quoted 15 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +11 -0
@@ -342,6 +343,28 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
     return 0;
 }
 
+void cf_check imsic_ctxt_switch_from(struct vcpu *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 no location to record.
+     */
+    if ( !vcpu_guest_file_id(p) )
+        return;

xen/arch/riscv/imsic.c static int __init imsic_parse_node(const struct dt_device_node *node, · line 366

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+
+    write_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    imsic_state->vsfile_cpu = p->processor;
+    write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+}
+
+void cf_check imsic_ctxt_switch_to(struct vcpu *n)
+{
+    /* Nothing to do */
+}

Unlike most other function attributes, cf_check needs to be present not only on the definitions, but also ...

xen/arch/riscv/include/asm/imsic.h unsigned int vcpu_guest_file_id(const struct vcpu *v); · line 100

Quoted 8 lines
xen/arch/riscv/include/asm/imsic.h +2 -0
@@ -96,4 +96,7 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
 int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
+void imsic_ctxt_switch_from(struct vcpu *p);
+void imsic_ctxt_switch_to(struct vcpu *n);

... on the declarations. Then:

Jan

Acked-by on v3 16/39
#65 lore raw

Re: [PATCH v3 16/39] xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN

In reply to Oleksii Kurochko
Quoted 12 lines · Oleksii Kurochko

htinst reports a pseudoinstruction when a guest page fault is taken on an implicit memory access done for VS-stage address translation. Four such values are defined, differing in the access type (read or write) and in the access width: 4 bytes (0x2000/0x2020) or 8 bytes (0x3000/0x3020).

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Yet only one pair is defined, selected by Xen's XLEN and named as if it were the only one, so the 4-byte forms, which a guest running with VSXL=32 and Sv32 in vsatp produces, can't be named at all on RV64.

Quoted 4 lines

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN.

Dropping the ladder loses no build-time coverage: a build for an XLEN other

Nit: "latter" (no matter that some Americans may pronounce it like "ladder")

Quoted 10 lines

than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user.

Acked-by
#76 lore raw

Re: [PATCH v3 19/39] xen/riscv: detect Shtvala

In reply to Baptiste Le Duc
Quoted 7 lines · Baptiste Le Duc
Quoted 6 lines · Oleksii Kurochko

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.

Quoted 8 lines
Quoted 6 lines

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.

[...]

#49 lore raw

Re: [PATCH v3 11/39] xen/riscv: implement vCPU context switching

In reply to Jan Beulich
Quoted 21 lines · Jan Beulich
Quoted 20 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +16 -0
@@ -323,6 +326,130 @@ int arch_domain_create(struct domain *d,
      return rc;
  }
 
+static void csr_regs_ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * csr_regs_ctxt_switch_to() and guest can't access them so they shouldn't
+     * be stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * p->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * p->arch.hideleg = csr_read(CSR_HIDELEG);
+     * p->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * p->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * p->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     p->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
Quoted 8 lines

Review int arch_domain_create(struct domain *d, · line 345

Quoted 1 line
(quoted diff) +1 -0
+     */

I don't understand this comment. Whether the guest can access a CSR doesn't matter very much. If Xen modifies it on the guest's behalf, it may still need saving/restoring. The question for each individual one is: Can its value (or the guest-affecting fields of it) be reconstructed from other state? Or is what it holds global state? Or are p->arch.* fields reliably kept in sync with what is stored in the hw register?

The value of none of them can change behind Xen's back: they are HS-mode CSRs, which the guest can't access, and Xen writes them only in csr_regs_ctxt_switch_to(), from v->arch.* fields which don't change after vcpu_csr_init(). So the h/w registers always hold what v->arch.* does, and reading them back would be a no-op. The one exception is hie, whose VS-level bits alias the vsie ones the guest can change; these are covered by saving and restoring vsie (hie being written first).

I'll replace the commented-out code with a comment saying this:

static void csr_regs_ctxt_switch_from(struct vcpu *p)
{
/*
* Not saved: hedeleg, hideleg, hie, henvcfg, hcounteren,
htimedelta and
* hstateen0 only ever hold what csr_regs_ctxt_switch_to() writes there
* from v->arch.*, which vcpu_csr_init() sets up once. Neither Xen nor
* the guest changes them otherwise, but for the VS-level bits of hie,
* aliases of the vsie bits, which the guest changes through vsie: they
* are saved and restored as part of vsie.
*/

p->arch.hvip = csr_read(CSR_HVIP);
...

Quoted 26 lines
Quoted 26 lines
xen/arch/riscv/domain.c +25 -0
+    p->arch.hvip = csr_read(CSR_HVIP);
+
+    p->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    p->arch.vsie = csr_read64(CSR_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 csr_regs_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(CSR_HENVCFG, n->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, n->arch.hcounteren);
+    csr_write64(CSR_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(CSR_VSIE, n->arch.vsie);
Quoted 8 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 377

Quoted 6 lines
xen/arch/riscv/domain.c +6 -0
+    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);
+}

Btw, for both function names possibly s/csr_regs/csrs/ ? Or even just singular?

Good point. Use csrs_ctxt_switch_*() sounds good for me.

Quoted 11 lines

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

Quoted 9 lines
xen/arch/riscv/include/asm/csr.h +4 -0
@@ -72,6 +79,12 @@
      (void)csr ## H;                 \
      csr_read(csr);                  \
  })
+
+#define csr_read64(csr)             \
+({                                  \
+    (void)csr ## H;                 \

I continue to not really understand what use this is.

It will be dropped in the v4.

Quoted 10 lines

xen/arch/riscv/include/asm/system.h static inline bool local_irq_is_enabled(void) · line 79

Quoted 8 lines
xen/arch/riscv/include/asm/system.h +1 -0
@@ -76,6 +76,8 @@ static inline bool local_irq_is_enabled(void)
 
  #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
+struct vcpu *__context_switch(struct vcpu *prev, const struct vcpu *next);

asmlinkage (at least for Misra's sake)?

I will add.

Thanks.

~ Oleksii