Skip to contentSkip to conversation

virtual interrupt controller (vAPLIC/vIMSIC) support

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

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#108 lore raw

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

In reply to Oleksii Kurochko
Quoted 78 lines · Oleksii Kurochko
Quoted 11 lines · Baptiste Le Duc
Quoted 9 lines

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

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Selecting just one pair with where a guest running with VSXL=32 and Sv32 in vsatp produces the 4-byte

Sentence is broken. Guess you mean "Selecting just one pair based on Xen's XLEN misses the case where …".

Likely it is becuase of my low level English but it seems that original version wast okay and what you added is just a part from prev. sentence but I will add your suggestion for better clearness. Thanks for noticing that!

Quoted 48 lines
Quoted 48 lines

forms. Such an htinst would not be recognized as a pseudoinstruction and the fault would be mistaken for an ordinary MMIO trap: Xen would fetch and decode whatever instruction sepc happens to point at (unrelated to the access which faulted) and emulate it against a guest physical address derived from htval, which for an implicit access holds the address of a VS-stage PTE rather than of any access the guest performed.

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN. On RV32 the 8-byte forms simply never occur, so recognizing them costs nothing.

Dropping the ladder loses no build-time coverage: a build for an XLEN other than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user yet.

xen/arch/riscv/include/asm/riscv_encoding.h +3 -7
index c63e5e3046..2d2e7e11b3 100644
@@ -839,25 +839,17 @@
  #define INSN_MASK_FENCE_TSO		0xffffffff
  #define INSN_MATCH_FENCE_TSO		0x8330000f
 
-#if __riscv_xlen == 64
-
  /* 64-bit read for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_LOAD		0x00003000
+#define INSN_PSEUDO_VS_LOAD64		0x00003000
 
  /* 64-bit write for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_STORE	0x00003020
-
-#elif __riscv_xlen == 32
+#define INSN_PSEUDO_VS_STORE64		0x00003020
 
  /* 32-bit read for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_LOAD		0x00002000
+#define INSN_PSEUDO_VS_LOAD32		0x00002000
 
Quoted 9 lines

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

Quoted 3 lines
xen/arch/riscv/include/asm/riscv_encoding.h +0 -2
  /* 32-bit write for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_STORE	0x00002020
-

Whole point of patch is these no longer depend on build XLEN, yet comments still say "(RV64)"/"(RV32)" which could be confusing. Maybe it should be better to indicate, as the spec does, that RV32 values are used when VSXLEN=32 (only sv32 paging mode) and RV64 values when VSXLEN=64 (sv39+ paging modes).

Quoted 1 line

Could you please clarify to me what in the spec it is?

It is the same table as you indicated below (but mine is Table 56, so it seems we don't have the same spec version, I'm using the version 20260120).

When I found unclear is that "RV32" or "RV64" alone is ambiguous, since host and guest can differ (e.g. RV64 host running an RV32 guest). Saying it depends on VSXLEN instead makes clear which one is meant.

Quoted 15 lines

This comments are just copy from the spec:

Table 39. Special pseudoinstruction values for guest-page faults. The RV32 values are used when VSXLEN=32, and the RV64 values when VSXLEN=64.

Value           Meaning
0x00002000      32-bit read for VS-stage address translation (RV32)
0x00002020      32-bit write for VS-stage address translation (RV32)
Value           Meaning
0x00003000      64-bit read for VS-stage address translation (RV64)
0x00003020      64-bit write for VS-stage address translation (RV64)

So the comments are just copy of "Meaning" column from the spec.

Quoted 9 lines

And I think that Meaning column is fine here as we could have a case of when hypervisor has XLEN=64 but guests could be on it RV32 and RV64 and if a guest is RV32 (what means VSXLEN=32) then the comment above defintion mean that we hav 32-bit read/write VS-stage address translation for (RV32) guest and the similar is for RV64.

Do I miss something? Is a comments make more sense now or I have to still update them in some way?

I think it would be more clear to modify the comment by that:
/* 32-bit read for VS-stage address translation (VSXLEN=32) */

But now with your explanation, your comment is more clear as it specify VS-stage address, so the guest. Feel free to adopt my version or not.

Quoted 8 lines

Thanks!

~ Oleksii

#100 lore raw

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

In reply to Oleksii Kurochko
Quoted 310 lines · Oleksii Kurochko
Quoted 297 lines · Baptiste Le Duc
Quoted 237 lines

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

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

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

Add EX_TYPE_TRAP_INFO to allow handlers to retrieve trap state (sepc/scause/stval) and pass it to the fixup path. The data field is used to encode which GPR contains a pointer to a struct trap_info.

Provide ASM_EXTABLE_TRAP_INFO() as a convenience wrapper for this case.

Also add gpr-num.h, providing symbolic GPR numbers for use in assembly and inline asm. This is derived from Linux 6.16 with minor adjustments such as using .irp instead of open-coding the same using a set of .equ.

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

xen/arch/riscv/extable.c +68 -2
index 5b89c4278c..6470198d01 100644
@@ -6,8 +6,10 @@
  #include <xen/sort.h>
  #include <xen/virtual_region.h>
 
+#include <asm/csr.h>
  #include <asm/extable.h>
  #include <asm/processor.h>
+#include <asm/traps.h>
 
  #define EX_FIELD(ptr, field) ((unsigned long)&(ptr)->field + (ptr)->field)
 
@@ -32,6 +34,12 @@ static void __init cf_check swap_ex(void *a, void *b)
 
      x->fixup = y->fixup + delta;
      y->fixup = tmp.fixup - delta;
+
+    x->type = y->type;
+    y->type = tmp.type;
+
+    x->data = y->data;
+    y->data = tmp.data;
  }
 
  static int cf_check cmp_ex(const void *a, const void *b)
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
      regs->sepc = ex_fixup(ex);
  }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));
+
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)
+
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];
+}
+
+#undef CHECK_GPR_INDEX
+
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
+    BUG_ON(!trap_info);
+
+    /*
+     * Only stval still needs a CSR read: sepc and scause were already
+     * captured by the trap entry path and do_trap() respectively. Latch
+     * trap_info->sepc before regs->sepc is pointed at the fixup code.
+     */
+    trap_info->sepc = regs->sepc;
+    trap_info->scause = cause;
+    trap_info->stval = csr_read(CSR_STVAL);
+
+    regs->sepc = ex_fixup(ex);
+}
+
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause)
  {
      unsigned long pc = regs->sepc;
      const struct virtual_region *region = find_text_region(pc);
@@ -77,7 +127,23 @@ bool fixup_exception(struct cpu_user_regs *regs)
      if ( !ex )
          return false;
 
-    ex_handler_fixup(ex, regs);
+    switch ( ex->type )
+    {
+    case EX_TYPE_FIXUP:
+        ex_handler_fixup(ex, regs);
+        break;
+
+    case EX_TYPE_TRAP_INFO:
+        ex_handler_trap_info(ex, regs, cause);
+        break;
+
+    default:
+        printk(XENLOG_ERR
+               "Unsupported exception table entry type %u for pc %#lx\n",
+               ex->type, pc);
+
+        return false;
+    }
 
      return true;
  }
xen/arch/riscv/include/asm/extable.h +44 -20
index c0128a9181..7378f86e7e 100644
@@ -3,17 +3,24 @@
  #ifndef ASM__RISCV__ASM_EXTABLE_H
  #define ASM__RISCV__ASM_EXTABLE_H
 
+#include <asm/gpr-num.h>
+
+#define EX_TYPE_FIXUP       0
+#define EX_TYPE_TRAP_INFO   1
+
  #ifdef __ASSEMBLER__
 
-#define ASM_EXTABLE(insn, fixup) \
-    .pushsection .ex_table, "a"; \
-    .balign     4;               \
-    .word       (insn) - .;      \
-    .word       (fixup) - .;     \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    .pushsection .ex_table, "a";                    \
+    .balign     4;                                  \
+    .word       (insn) - .;                         \
+    .word       (fixup) - .;                        \
+    .half       (type);                             \
+    .half       (data);                             \
      .popsection
 
-.macro asm_extable, insn, fixup
-    ASM_EXTABLE(\insn, \fixup)
+.macro _asm_extable, insn, fixup
+    ASM_EXTABLE_RAW(\insn, \fixup, EX_TYPE_FIXUP, 0)
  .endm
 
  #else /* __ASSEMBLER__ */
@@ -23,20 +30,36 @@
 
  struct cpu_user_regs;
 
-#define ASM_EXTABLE(insn, fixup)      \
-    ".pushsection .ex_table, \"a\"\n" \
-    ".balign    4\n"                  \
-    ".word      (" #insn " - .)\n"    \
-    ".word      (" #fixup " - .)\n"   \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    ".pushsection .ex_table, \"a\"\n"               \
+    ".balign    4\n"                                \
+    ".word      (" insn ") - .\n"                   \
+    ".word      (" fixup ") - .\n"                  \
+    ".half      (" type ")\n"                       \
+    ".half      (" data ")\n"                       \
      ".popsection\n"
 
+#define ASM_EXTABLE(insn, fixup)    \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_FIXUP), "0")
+
+#define EX_TRAP_INFO_REG(gpr)   \
+    "(.L_gpr_num_" #gpr ")"
+
+#define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
+    DEFINE_ASM_GPR_NUMS                                             \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
+                    EX_TRAP_INFO_REG(data))
+
  /*
- * The exception table consists of pairs of relative offsets: the first
- * is the relative offset to an instruction that is allowed to fault,
- * and the second is the relative offset at which the program should
- * continue. No general-purpose registers are modified by the exception
- * handling mechanism itself, so it is up to the fixup code to handle
- * any necessary state cleanup.
+ * Each exception table entry consists of two relative offsets and a
+ * handler description: `insn` is the relative offset to an instruction
+ * that is allowed to fault, `fixup` is the relative offset at which the
+ * program should continue, `type` selects how the exception is handled
+ * (EX_TYPE_*), and `data` holds auxiliary information for the handler
+ * (e.g. for EX_TYPE_TRAP_INFO, the number of the GPR that contains a
+ * pointer to a struct trap_info). No general-purpose registers are
+ * modified by the exception handling mechanism itself, so it is up to
+ * the fixup code to handle any necessary state cleanup.
   *
   * The exception table and fixup code live out of line with the main
   * instruction path. This means when everything is well, we don't even
@@ -45,14 +68,15 @@ struct cpu_user_regs;
   */
  struct exception_table_entry {
      int32_t insn, fixup;
+    uint16_t type, data;
  };
 
  extern struct exception_table_entry __start___ex_table[];
  extern struct exception_table_entry __stop___ex_table[];
 
  void sort_exception_tables(void);
-bool fixup_exception(struct cpu_user_regs *regs);
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause);
 
-#endif /* __ASSEMBLY__ */
+#endif /* __ASSEMBLER__ */
 
  #endif /* ASM__RISCV__ASM_EXTABLE_H */
xen/arch/riscv/include/asm/gpr-num.h new file +0 -0
new file mode 100644
index 0000000000..3b97a72e6c

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

Quoted 3 lines
xen/arch/riscv/include/asm/gpr-num.h new file +3 -0
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H

Nit: commit message says this is derived from Linux 6.16. Other imported RISC-V headers here carry an in-file note (bitops.h: "Based on linux/arch/.../bitops.h") but this file doesn't.

Quoted 54 lines
xen/arch/riscv/include/asm/gpr-num.h new file +33 -0
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping: it generates the
+ * .L_gpr_num_<name> assembler symbols used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU
+
+#else /* __ASSEMBLER__ */
+
+#define GPR_NUM_EQU(num, name)  ".equ .L_gpr_num_" #name ", " #num "\n"
+#define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
+
+#endif /* __ASSEMBLER__ */
+
+#endif /* RISCV_GPR_NUM_H */
xen/arch/riscv/include/asm/processor.h +12 -1
index b1745c1071..e7b0f2321a 100644
@@ -12,7 +12,19 @@
 
  #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order: code which resolves a register number to its saved
+ * value indexes this structure directly (instruction emulation via
+ * REG_PTR() from asm/riscv_encoding.h, exception table fixups via
+ * regs_get_gpr()). ->zero therefore has to stay at offset 0 and must always
+ * read as 0, since it supplies the value of x0 when x0 is used as a source
+ * operand. The layout is checked against GPR_LIST() at build time; see
+ * regs_get_gpr() in extable.c. Do not reorder these fields or insert
+ * anything between them.
Quoted 9 lines

xen/arch/riscv/include/asm/processor.h line 30

Quoted 3 lines
xen/arch/riscv/include/asm/processor.h +1 -0
+ */
  {
      unsigned long zero;

Comment claims ->zero "must always read as 0" as it's hard-wired to zero by the HW, but nothing enforces that, it's still a plain writable unsigned long. Maybe a write-side counterpart that special-cases num==0 as a no-op, or with a minimum ASSERT(num != 0) / BUG_ON(num == 0) to anticipate any future forbidden writes.

Quoted 3 lines

Could you please clarify where do you want me to put this check in this patch? In regs_get_gpr()? There is no write-side in this patch. Am i missing something?

Honestly, I don't know where it would be most appropriate. But I'd like to highlight that nothing strictly forbids Xen code from writing a value != 0 into regs->zero.

I saw that in emulate_load(), which is introduced later, you used a branch to avoid an incorrect load into regs->zero:
/*
* A load into x0 discards its result: writing regs->zero would break
* the invariant that it reads as zero when x0 is a source operand
* elsewhere.
*/

One solution could be to make cpu_user_regs private and add get/set methods, with a check in the setter that forbids this type of write, but that would imply some big changes, so it may not be the appropriate fix.

Quoted 8 lines

Thanks in advance.

~ Oleksii

author Applied
#102 lore raw

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

In reply to Jan Beulich
Quoted 13 lines · Jan Beulich

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 72

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +3 -1
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
      regs->sepc = ex_fixup(ex);
  }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));

Nit: Placement of the !=. Also there should be no semicolon here; it wants to ...

Quoted 11 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 81

Quoted 9 lines
(quoted diff) +9 -0
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)

... appear here instead, for this to actually look like a statement.

I will apply that.

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 84

Quoted 4 lines
(quoted diff) +3 -0
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];

What about release builds? You'd happily overrun the array there. Maybe (ab)use array_index_nospec() here?

num is coming not from guest, not from calculation in runtume, it is generated by assembler at the build time. So it should be always correct.

So just having the following looks okay to me:

static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
unsigned int num)
{
#define CHECK_GPR_INDEX(num, name) \
BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) != \
(num) * sizeof(unsigned long))

#define GPR_CASE(nr, name) case nr: return regs->name;

/*
* The GPR number -> struct index mapping below relies on x0..x31 being
* laid out at the start of struct cpu_user_regs in architectural
order,

     * matching the register numbers GPR_LIST() hands to the assembler.
     */
    GPR_LIST(CHECK_GPR_INDEX);

#undef CHECK_GPR_INDEX

    switch ( num )
    {
    GPR_LIST(GPR_CASE)
    }

#undef GPR_CASE

    ASSERT_UNREACHABLE();

    return 0;
}

Any thoughts on that regard?

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 87

Quoted 3 lines
(quoted diff) +3 -0
+}
+
+#undef CHECK_GPR_INDEX

If the sole use of the macro is in a single function, it wants #define-ing (and #undef-ing) there, not outside of it.

I will move inside.

Quoted 7 lines
Quoted 7 lines
(quoted diff) +7 -0
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
Quoted 9 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 95

Quoted 1 line
(quoted diff) +1 -0
+    BUG_ON(!trap_info);

This feels extremely weak. As you're fetching from a GPR, the majority of possible values stored in GPRs is going to be invalid, not just NULL. And while the accesses below would trap on NULL anyway, whether other bogus values would trap is pretty hard to predict. If trap_info is expected to always live on the stack, why not check for that (perhaps also check that the low few bits are clear)?

Considering the nature if how trap_info is filled I think we could just drop BUG_ON(), it is guaranteed by compilation that trap_info will be correct.

I think it could be also hard to force trap_info be always allocated on the stack.

Quoted 18 lines
Quoted 18 lines
(quoted diff) +7 -5
@@ -23,20 +30,36 @@
 
  struct cpu_user_regs;
 
-#define ASM_EXTABLE(insn, fixup)      \
-    ".pushsection .ex_table, \"a\"\n" \
-    ".balign    4\n"                  \
-    ".word      (" #insn " - .)\n"    \
-    ".word      (" #fixup " - .)\n"   \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    ".pushsection .ex_table, \"a\"\n"               \
+    ".balign    4\n"                                \
+    ".word      (" insn ") - .\n"                   \
+    ".word      (" fixup ") - .\n"                  \
+    ".half      (" type ")\n"                       \
+    ".half      (" data ")\n"                       \
      ".popsection\n"
 
Quoted 7 lines

Review line 46

Quoted 5 lines
(quoted diff) +5 -0
+#define ASM_EXTABLE(insn, fixup)    \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_FIXUP), "0")
+
+#define EX_TRAP_INFO_REG(gpr)   \
+    "(.L_gpr_num_" #gpr ")"

This doesn't need to be wrapped across lines, does it?

Oh, really, it could be one line.

Quoted 11 lines

Review line 50

Quoted 5 lines
(quoted diff) +4 -0
+#define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
+    DEFINE_ASM_GPR_NUMS                                             \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
+                    EX_TRAP_INFO_REG(data))

There's no visible statement separator between DEFINE_ASM_GPR_NUMS and ASM_EXTABLE_RAW(), which only works because DEFINE_ASM_GPR_NUMS appends a separator also at the very end of its expansion. I think that better would be changed, such that at use sites such as this one a separator becomes mandatory.

I will do the following then:

 #define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
-    DEFINE_ASM_GPR_NUMS                                             \
+    DEFINE_ASM_GPR_NUMS "\n"                                        \
     ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
                     EX_TRAP_INFO_REG(data))
xen/arch/riscv/include/asm/gpr-num.h +8 -2
index 3b97a72e6c30..d497bd501e87 100644
@@ -23,13 +23,19 @@
 
 #ifdef __ASSEMBLER__
 
-#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+/*
+ * The separator is emitted ahead of each entry rather than after it, so that
+ * the expansion doesn't end with one: whatever follows a use of the list has
+ * to supply its own separator, instead of silently relying on a trailing one.
+ */
+#define GPR_NUM_EQU(num, name)  ; .equ .L_gpr_num_##name, num
 GPR_LIST(GPR_NUM_EQU)
 #undef GPR_NUM_EQU
 
 #else /* __ASSEMBLER__ */
 
-#define GPR_NUM_EQU(num, name)  ".equ .L_gpr_num_" #name ", " #num "\n"
+/* See the comment ahead of the __ASSEMBLER__ flavour above. */
+#define GPR_NUM_EQU(num, name)  "\n.equ .L_gpr_num_" #name ", " #num
 #define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
 
Quoted 13 lines

Review line 55

Quoted 12 lines
(quoted diff) +4 -6
  /*
- * The exception table consists of pairs of relative offsets: the first
- * is the relative offset to an instruction that is allowed to fault,
- * and the second is the relative offset at which the program should
- * continue. No general-purpose registers are modified by the exception
- * handling mechanism itself, so it is up to the fixup code to handle
- * any necessary state cleanup.
+ * Each exception table entry consists of two relative offsets and a
+ * handler description: `insn` is the relative offset to an instruction
+ * that is allowed to fault, `fixup` is the relative offset at which the
+ * program should continue,
Quoted 1 line

"... in case of a fault, ..."

Applied.

Quoted 15 lines

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

Quoted 12 lines
xen/arch/riscv/include/asm/gpr-num.h new file +8 -0
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H
+
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping:

True until here, but ...

Quoted 4 lines
Quoted 2 lines

it generates the
+ * .L_gpr_num_<name> assembler symbols

... no, it doesn't. It's ...

I will update the comment to:
/*
* GPRs by ABI name, together with their register number (x0 .. x31). *
* This is the single source of truth for the mapping; users expand it with
* their own per-register macro. Among them, struct cpu_user_regs is
checked
* against this list at build time (see regs_get_gpr()), so neither
list can
* be changed without the other.
*/

#define GPR_LIST(x)                                 \
    ...

and then ...

Quoted 16 lines
Quoted 16 lines

used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */

xen/arch/riscv/include/asm/gpr-num.h new file +10 -0
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
Quoted 9 lines

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

Quoted 5 lines
xen/arch/riscv/include/asm/gpr-num.h new file +5 -0
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU

... this construct which does. This is relevant to separate, since GPR_LIST() is also used elsewhere.

... here:

/*
* Generate the .L_gpr_num_<name> assembler symbols, used to turn a
register
* name emitted by the compiler into a register number.
*
* The separator is emitted ahead of each entry rather than after it,
so that

Quoted 6 lines
Quoted 6 lines
xen/arch/riscv/include/asm/processor.h +0 -0
@@ -12,7 +12,19 @@
 
  #ifndef __ASSEMBLER__
 
Quoted 10 lines

xen/arch/riscv/include/asm/processor.h line 19

Quoted 6 lines
xen/arch/riscv/include/asm/processor.h +5 -1
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order:

I understand that the order need retaining. But why would it being at the start of the struct be (overly) relevant? You could use the "zero" field as the anchor for calculations.

You're right.

The placement requirement comes only from REG_PTR() computing a byte offset from the struct base. Anchoring it on ->zero instead removes the need for the block to sit at the start:

#define REG_PTR(insn, pos, regs) \
    (&(regs)->zero + (REG_OFFSET(insn, pos) / REGBYTES))

I'll do that and reword the comment to state the actual invariants: the x0..x31 fields have to stay contiguous and in ascending register-number order, and ->zero has to read as 0.

Thanks.

~ Oleksii

#132 lore raw

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

In reply to Oleksii Kurochko
Quoted 8 lines

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

Quoted 7 lines

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

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

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

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

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

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

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

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

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

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

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

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

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

In reply to Oleksii Kurochko
Quoted 43 lines

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

In reply to Oleksii Kurochko
Quoted 65 lines · Oleksii Kurochko
Quoted 13 lines · Jan Beulich

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 72

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +3 -1
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
      regs->sepc = ex_fixup(ex);
  }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));

Nit: Placement of the !=. Also there should be no semicolon here; it wants to ...

Quoted 11 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 81

Quoted 9 lines
(quoted diff) +9 -0
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)

... appear here instead, for this to actually look like a statement.

I will apply that.

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 84

Quoted 4 lines
(quoted diff) +3 -0
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];

What about release builds? You'd happily overrun the array there. Maybe (ab)use array_index_nospec() here?

num is coming not from guest, not from calculation in runtume, it is generated by assembler at the build time. So it should be always correct.

So just having the following looks okay to me:

static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
unsigned int num)
{
#define CHECK_GPR_INDEX(num, name) \
BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) != \
(num) * sizeof(unsigned long))

#define GPR_CASE(nr, name) case nr: return regs->name;

/*
* The GPR number -> struct index mapping below relies on x0..x31 being
* laid out at the start of struct cpu_user_regs in architectural
order,

      * matching the register numbers GPR_LIST() hands to the assembler.
      */
     GPR_LIST(CHECK_GPR_INDEX);

#undef CHECK_GPR_INDEX

     switch ( num )
     {
     GPR_LIST(GPR_CASE)
     }
Quoted 8 lines

#undef GPR_CASE

     ASSERT_UNREACHABLE();

     return 0;
}

Any thoughts on that regard?

Depends very much on how efficiently the compiler translates this (as opposed to the other variant).

Jan

#104 lore raw

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

Quoted 70 lines · Jan Beulich
Quoted 69 lines · Oleksii Kurochko
Quoted 13 lines · Jan Beulich

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 72

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +3 -1
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
       regs->sepc = ex_fixup(ex);
   }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));

Nit: Placement of the !=. Also there should be no semicolon here; it wants to ...

Quoted 11 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 81

Quoted 9 lines
(quoted diff) +9 -0
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)

... appear here instead, for this to actually look like a statement.

I will apply that.

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 84

Quoted 4 lines
(quoted diff) +3 -0
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];

What about release builds? You'd happily overrun the array there. Maybe (ab)use array_index_nospec() here?

num is coming not from guest, not from calculation in runtume, it is generated by assembler at the build time. So it should be always correct.

So just having the following looks okay to me:

static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
unsigned int num)
{
#define CHECK_GPR_INDEX(num, name) \
BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) != \
(num) * sizeof(unsigned long))

#define GPR_CASE(nr, name) case nr: return regs->name;

/*
* The GPR number -> struct index mapping below relies on x0..x31 being
* laid out at the start of struct cpu_user_regs in architectural
order,

       * matching the register numbers GPR_LIST() hands to the assembler.
       */
      GPR_LIST(CHECK_GPR_INDEX);

#undef CHECK_GPR_INDEX

      switch ( num )
      {
      GPR_LIST(GPR_CASE)
      }

#undef GPR_CASE

      ASSERT_UNREACHABLE();
Quoted 7 lines
Quoted 4 lines
      return 0;
}

Any thoughts on that regard?

Depends very much on how efficiently the compiler translates this (as opposed to the other variant).

It is worthier. I will follow then your original suggestion and use array_index_nospec().

~ Oleksii

#109 lore raw

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

In reply to Baptiste Le Duc
Quoted 109 lines · Baptiste Le Duc
Quoted 78 lines · Oleksii Kurochko
Quoted 11 lines · Baptiste Le Duc
Quoted 9 lines

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

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Selecting just one pair with where a guest running with VSXL=32 and Sv32 in vsatp produces the 4-byte

Sentence is broken. Guess you mean "Selecting just one pair based on Xen's XLEN misses the case where …".

Likely it is becuase of my low level English but it seems that original version wast okay and what you added is just a part from prev. sentence but I will add your suggestion for better clearness. Thanks for noticing that!

Quoted 48 lines
Quoted 48 lines

forms. Such an htinst would not be recognized as a pseudoinstruction and the fault would be mistaken for an ordinary MMIO trap: Xen would fetch and decode whatever instruction sepc happens to point at (unrelated to the access which faulted) and emulate it against a guest physical address derived from htval, which for an implicit access holds the address of a VS-stage PTE rather than of any access the guest performed.

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN. On RV32 the 8-byte forms simply never occur, so recognizing them costs nothing.

Dropping the ladder loses no build-time coverage: a build for an XLEN other than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user yet.

xen/arch/riscv/include/asm/riscv_encoding.h +3 -7
index c63e5e3046..2d2e7e11b3 100644
@@ -839,25 +839,17 @@
   #define INSN_MASK_FENCE_TSO		0xffffffff
   #define INSN_MATCH_FENCE_TSO		0x8330000f
 
-#if __riscv_xlen == 64
-
   /* 64-bit read for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_LOAD		0x00003000
+#define INSN_PSEUDO_VS_LOAD64		0x00003000
 
   /* 64-bit write for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_STORE	0x00003020
-
-#elif __riscv_xlen == 32
+#define INSN_PSEUDO_VS_STORE64		0x00003020
 
   /* 32-bit read for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_LOAD		0x00002000
+#define INSN_PSEUDO_VS_LOAD32		0x00002000
 
Quoted 9 lines

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

Quoted 3 lines
xen/arch/riscv/include/asm/riscv_encoding.h +0 -2
   /* 32-bit write for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_STORE	0x00002020
-

Whole point of patch is these no longer depend on build XLEN, yet comments still say "(RV64)"/"(RV32)" which could be confusing. Maybe it should be better to indicate, as the spec does, that RV32 values are used when VSXLEN=32 (only sv32 paging mode) and RV64 values when VSXLEN=64 (sv39+ paging modes).

Quoted 1 line

Could you please clarify to me what in the spec it is?

It is the same table as you indicated below (but mine is Table 56, so it seems we don't have the same spec version, I'm using the version 20260120).

When I found unclear is that "RV32" or "RV64" alone is ambiguous, since host and guest can differ (e.g. RV64 host running an RV32 guest). Saying it depends on VSXLEN instead makes clear which one is meant.

Quoted 21 lines

This comments are just copy from the spec:

Table 39. Special pseudoinstruction values for guest-page faults. The RV32 values are used when VSXLEN=32, and the RV64 values when VSXLEN=64.

Value           Meaning
0x00002000      32-bit read for VS-stage address translation (RV32)
0x00002020      32-bit write for VS-stage address translation (RV32)
Value           Meaning
0x00003000      64-bit read for VS-stage address translation (RV64)
0x00003020      64-bit write for VS-stage address translation (RV64)

So the comments are just copy of "Meaning" column from the spec.

And I think that Meaning column is fine here as we could have a case of when hypervisor has XLEN=64 but guests could be on it RV32 and RV64 and if a guest is RV32 (what means VSXLEN=32) then the comment above defintion mean that we hav 32-bit read/write VS-stage address translation for (RV32) guest and the similar is for RV64.

Quoted 8 lines
Quoted 3 lines

Do I miss something? Is a comments make more sense now or I have to still update them in some way?

I think it would be more clear to modify the comment by that:
/* 32-bit read for VS-stage address translation (VSXLEN=32) */

But now with your explanation, your comment is more clear as it specify VS-stage address, so the guest. Feel free to adopt my version or not.

Agree your suggestion here will be more clear. I will apply it.

Thanks.

~ Oleksii

#43 lore raw

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

?

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

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

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

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

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

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

Jan

#44 lore raw

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

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

xen/arch/riscv/mmio.c line 82

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

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

It make sense. I will do then:

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

xen/arch/riscv/mmio.c line 112

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

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

I will apply this.

Quoted 4 lines

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

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

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

xen/arch/riscv/mmio.c line 130

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

?

It seems like it will break the code after it.

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

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

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

Quoted 13 lines

xen/arch/riscv/mmio.c line 142

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

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

Then probably EADDRINUSE() would be better.

Thanks.

~ Oleksii

#52 lore raw

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

In reply to Oleksii Kurochko

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

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

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

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

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

Please can this have const alongside volatile?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

gdprintk()?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

... what's here.

Jan

#45 lore raw

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

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

xen/arch/riscv/mmio.c line 82

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

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

Quoted 3 lines

It make sense. I will do then:

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

With more parentheses added, I suppose.

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

xen/arch/riscv/mmio.c line 112

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

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

I will apply this.

Quoted 1 line
Quoted 6 lines
Quoted 2 lines

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

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

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

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

xen/arch/riscv/mmio.c line 130

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

?

It seems like it will break the code after it.

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

Quoted 8 lines

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

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

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

Jan

Acked-by
#61 lore raw

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

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

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

Quoted 8 lines
Quoted 6 lines

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

[...]

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

Jan

#62 lore raw

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

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

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

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

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

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

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

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

Jan

#114 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

In reply to Jan Beulich
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c new file +19 -0
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>
+#include <asm/traps.h>
+
+/*
+ * The hardware-reported details of a guest page fault, gathered once by
Quoted 8 lines

xen/arch/riscv/emulate.c line 25

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+ * handle_guest_page_fault() and passed down to the emulation of the faulted
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state as saved on entry to do_trap(). */
+    struct cpu_user_regs *regs;

If the comment was true, this could be pointer-to-const.

I think it can't be pointer-to-const as emulate_load/store functions wants to change PC register after MMIO access emulation is finished to not trap again.

Regarding the comment itself I agree that it isn't fully true right now because there is no trap from guest and so no guest registers save/restore but it will for sure be and we can't not to save/restore guest registers when do_trap() happens.

I will re-word it to:

/* The guest register state */

Quoted 36 lines
Quoted 36 lines
xen/arch/riscv/emulate.c new file +35 -0
+    /* scause: a fetch, a load or a store/AMO guest page fault. */
+    unsigned long cause;
+    /*
+     * htinst: the trapped instruction in its transformed form, or one of the
+     * special values (zero, or a pseudoinstruction).
+     */
+    unsigned long htinst;
+    /* htval: as written by hardware; see resolve_faulting_gpa(). */
+    unsigned long htval;
+    /* stval: the guest virtual address of the faulting access. */
+    unsigned long stval;
+    /* The faulting guest physical address, filled by resolve_faulting_gpa(). */
+    paddr_t gpa;
+};
+
+/*
+ * Is @htinst one of the pseudoinstructions reported for a guest page fault
+ * taken on an implicit memory access done for VS-stage address translation?
+ *
+ * All four values are recognized regardless of the hypervisor's XLEN: the
+ * width they encode is that of a VS-stage PTE, i.e. it follows the guest's
+ * paging mode (4 bytes for Sv32, 8 otherwise). On RV32 the 64-bit forms
+ * simply never occur.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    switch ( htinst )
+    {
+    case INSN_PSEUDO_VS_LOAD32:
+    case INSN_PSEUDO_VS_STORE32:
+    case INSN_PSEUDO_VS_LOAD64:
+    case INSN_PSEUDO_VS_STORE64:
+        return true;
+
+    default:
Quoted 8 lines

xen/arch/riscv/emulate.c line 63

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        return false;
+    }
+}

This feels fragile. New pseudo-insns can appear at any time. If the value as a whole is non-zero, aiui the low two bits being zero indicate a pseudo-insn. In which case enumerating pseudo-insns we are currently aware of isn't necessary.

I will write it simpler then:

/*
* Is @htinst one of the special pseudoinstruction values, reported for
a guest
* page fault taken on an implicit memory access done for VS-stage address
* translation?
*
* It is enough to check only bits[1:0] as according to the spec:
*
* The value is one of the special pseudoinstructions defined later, all of
* which have bits 1:0 equal to 00.
*/
static bool htinst_is_pseudo(unsigned long htinst)

{
    return htinst && ((htinst & 3) == 0);
}
Quoted 21 lines
Quoted 21 lines
xen/arch/riscv/emulate.c new file +20 -0
+static void inject_access_fault(const struct guest_fault *gf)
+{
+    struct trap_info utrap = {};
+
+    switch ( gf->cause )
+    {
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_FETCH_ACCESS;
+        break;
+
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_LOAD_ACCESS;
+        break;
+
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_STORE_ACCESS;
+        break;
+
+    default:
+        domain_crash(current->domain, "Impossible cause (%#lx) in %s?\n",
Quoted 8 lines

xen/arch/riscv/emulate.c line 106

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+                     gf->cause, __func__);
+        return;
+    }
+
+    utrap.sepc = gf->regs->sepc;
+    utrap.stval = gf->stval;

Would there be anything wrong with putting these in utrap's initializer?

It could be initializers. I will use utrap's initializer.

Quoted 11 lines
Quoted 11 lines
xen/arch/riscv/emulate.c new file +10 -0
+    trap_redirect(&utrap);
+}
+
+void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause)
+{
+    struct guest_fault gf = {
+        .regs = regs,
+        .cause = cause,
+        .htinst = csr_read(CSR_HTINST),
+        .htval = csr_read(CSR_HTVAL),
Quoted 8 lines

xen/arch/riscv/emulate.c line 120

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        .stval = csr_read(CSR_STVAL),
+        .gpa = INVALID_PADDR,
+    };

At some point RISC-V code will (very likely) also be scanned for Misra violations. The csr_read()s here violate rule 13.1 ("Initializer lists shall not contain persistent side effects"), and I think it would be better if such was avoided from the start.

I will do the following then:

struct guest_fault gf = {
.regs = regs,
.cause = cause,
.gpa = INVALID_PADDR,
};
int rc;

gf.htinst = csr_read(CSR_HTINST);
gf.htval = csr_read(CSR_HTVAL);
gf.stval = csr_read(CSR_STVAL);

Quoted 22 lines
Quoted 22 lines
xen/arch/riscv/emulate.c new file +21 -0
+    int rc;
+
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
Quoted 8 lines

xen/arch/riscv/emulate.c line 145

Quoted 4 lines
xen/arch/riscv/emulate.c new file +4 -0
+        inject_access_fault(&gf);
+
+        return;
+    }

I.e. you imply that guests won't put their page tables in MMIO? That's fragile imo; I have seen OSes to use video frame buffers for all kinds of (transient) purposes, for example.

I think it is okay for now and if it will a real use case then an update of this code will be needed.

Quoted 5 lines

xen/arch/riscv/emulate.c line 147

Quoted 2 lines
xen/arch/riscv/emulate.c new file +1 -0
+    resolve_faulting_gpa(&gf);

Since the function is only a stub right now - how is one to tell whether this indeed can never fail?

It can't be tell. But what is wrong if it could fail? (Actually with current implementation introduced in later patches you can find it can fail if a necessary extension or software page walk isn't introduced).

If we can't resolve faulting GPA address then we can't continue to work and so at least domain should be crashed.

Quoted 10 lines
Quoted 10 lines
xen/arch/riscv/emulate.c new file +9 -0
+    switch ( cause )
+    {
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        rc = emulate_load(&gf);
+        break;
+
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        rc = emulate_store(&gf);
+        break;
Quoted 8 lines

xen/arch/riscv/emulate.c line 163

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+        /*
+         * Guest is trying to reach unmapped/unpopulated or G-stage PTE doesn't
+         * allow execution (X=0). Generate fetch fault in this case.
+         */

Is there perhaps a comma missing before "or", to help parsing the sentence?

I will add one.

Quoted 6 lines

xen/arch/riscv/emulate.c line 166

Quoted 4 lines
xen/arch/riscv/emulate.c new file +3 -0
+        inject_access_fault(&gf);
+        rc = 0;
+        break;

Simply "return" instead of the latter two statements?

It makes sense. I will do just return.

Thanks.

~ Oleksii

#115 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

Quoted 33 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c new file +19 -0
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>
+#include <asm/traps.h>
+
+/*
+ * The hardware-reported details of a guest page fault, gathered once by
Quoted 8 lines

xen/arch/riscv/emulate.c line 25

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+ * handle_guest_page_fault() and passed down to the emulation of the faulted
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state as saved on entry to do_trap(). */
+    struct cpu_user_regs *regs;

If the comment was true, this could be pointer-to-const.

Quoted 3 lines

I think it can't be pointer-to-const as emulate_load/store functions wants to change PC register after MMIO access emulation is finished to not trap again.

Of course, hence how I started the sentence.

Quoted 58 lines
Quoted 35 lines
Quoted 35 lines
xen/arch/riscv/emulate.c new file +35 -0
+    /* scause: a fetch, a load or a store/AMO guest page fault. */
+    unsigned long cause;
+    /*
+     * htinst: the trapped instruction in its transformed form, or one of the
+     * special values (zero, or a pseudoinstruction).
+     */
+    unsigned long htinst;
+    /* htval: as written by hardware; see resolve_faulting_gpa(). */
+    unsigned long htval;
+    /* stval: the guest virtual address of the faulting access. */
+    unsigned long stval;
+    /* The faulting guest physical address, filled by resolve_faulting_gpa(). */
+    paddr_t gpa;
+};
+
+/*
+ * Is @htinst one of the pseudoinstructions reported for a guest page fault
+ * taken on an implicit memory access done for VS-stage address translation?
+ *
+ * All four values are recognized regardless of the hypervisor's XLEN: the
+ * width they encode is that of a VS-stage PTE, i.e. it follows the guest's
+ * paging mode (4 bytes for Sv32, 8 otherwise). On RV32 the 64-bit forms
+ * simply never occur.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    switch ( htinst )
+    {
+    case INSN_PSEUDO_VS_LOAD32:
+    case INSN_PSEUDO_VS_STORE32:
+    case INSN_PSEUDO_VS_LOAD64:
+    case INSN_PSEUDO_VS_STORE64:
+        return true;
+
+    default:
Quoted 8 lines

xen/arch/riscv/emulate.c line 63

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        return false;
+    }
+}

This feels fragile. New pseudo-insns can appear at any time. If the value as a whole is non-zero, aiui the low two bits being zero indicate a pseudo-insn. In which case enumerating pseudo-insns we are currently aware of isn't necessary.

I will write it simpler then:

/*
* Is @htinst one of the special pseudoinstruction values, reported for
a guest
* page fault taken on an implicit memory access done for VS-stage address
* translation?
*
* It is enough to check only bits[1:0] as according to the spec:
*
* The value is one of the special pseudoinstructions defined later, all of
* which have bits 1:0 equal to 00.
*/
static bool htinst_is_pseudo(unsigned long htinst)

Quoted 3 lines
{
     return htinst && ((htinst & 3) == 0);
}

And preferably

     return htinst && !(htinst & 3);

to be self-consistent.

Quoted 24 lines
Quoted 24 lines
Quoted 23 lines
xen/arch/riscv/emulate.c new file +23 -0
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
+        inject_access_fault(&gf);
+
+        return;
+    }
Quoted 6 lines
Quoted 3 lines

I.e. you imply that guests won't put their page tables in MMIO? That's fragile imo; I have seen OSes to use video frame buffers for all kinds of (transient) purposes, for example.

I think it is okay for now and if it will a real use case then an update of this code will be needed.

May I then ask that you leave a remark (maybe even fixme) to this effect?

Quoted 8 lines
Quoted 4 lines

xen/arch/riscv/emulate.c line 147

Quoted 1 line
xen/arch/riscv/emulate.c new file +1 -0
+    resolve_faulting_gpa(&gf);

Since the function is only a stub right now - how is one to tell whether this indeed can never fail?

It can't be tell. But what is wrong if it could fail? (Actually with current implementation introduced in later patches you can find it can fail if a necessary extension or software page walk isn't introduced).

Well, quite obviously if it can fail, its return value would need checking here.

Jan

#53 lore raw

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

In reply to Jan Beulich
Quoted 9 lines · Jan Beulich

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

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

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

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

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

Quoted 2 lines

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

I will use just v then here.

Quoted 12 lines

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

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

Please can this have const alongside volatile?

Sure, I will add.

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

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

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

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

I will fix that for APLIC_xMSICFGADDR_PPN_HHX_MASK, APLIC_xMSICFGADDR_PPN_LHX_MASK and APLIC_xMSICFGADDR_PPN_LHX_SHIFT.

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

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

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

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

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

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

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

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

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

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

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

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

Probably not too much sense. I will drop it.

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

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

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

gdprintk()?

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

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

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

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

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

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

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

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

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

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

I will re-word the comment to:

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

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

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

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

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

I will do that.

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

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

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

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

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

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

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

... what's here.

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

Thanks!

~ Oleksii

#63 lore raw

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

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

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

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

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

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

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

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

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

Would it be better to:

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

?

Thanks.

~ Oleksii

#54 lore raw

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

In reply to Oleksii Kurochko
Quoted 11 lines · Oleksii Kurochko
Quoted 9 lines · Jan Beulich

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

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

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

Quoted 8 lines

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

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

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

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

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

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

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

Quoted 5 lines

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

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

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

Jan

#64 lore raw

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

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

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

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

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

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

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

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

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

Would it be better to:

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Jan

Jan

#65 lore raw

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

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

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

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

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

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

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

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

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

Would it be better to:

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Jan

Jan

#66 lore raw

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

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

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

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

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

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

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

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

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

Would it be better to:

Quoted 7 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

Then BUILD_BUG_on should be updated to:

/* desc->irq < NR_IRQS, so it always fits the EIID field */

    BUILD_BUG_ON(NR_IRQS - 1 > MASK_EXTR(~0U, APLIC_TARGET_EIID));
Quoted 4 lines

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Device MSIs never pass through the APLIC. They are written straight into an IMSIC interrupt file. The ID space belongs to each file, so each hart has up to 2047 IDs (IMSIC_MAX_ID).

1k it is limitation for wired interrupts (which could be delivered in MSI mode where APLIC + IMSIC is needed) which are going through APLIC.

~ Oleksii

#67 lore raw

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

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

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

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

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

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

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

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

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

Would it be better to:

Quoted 7 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

Then BUILD_BUG_on should be updated to:

  /* desc->irq < NR_IRQS, so it always fits the EIID field */
     BUILD_BUG_ON(NR_IRQS - 1 > MASK_EXTR(~0U, APLIC_TARGET_EIID));
Quoted 4 lines

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Quoted 6 lines

Device MSIs never pass through the APLIC. They are written straight into an IMSIC interrupt file. The ID space belongs to each file, so each hart has up to 2047 IDs (IMSIC_MAX_ID).

1k it is limitation for wired interrupts (which could be delivered in MSI mode where APLIC + IMSIC is needed) which are going through APLIC.

But desc->irq and NR_IRQS have to represent both. Which then puts the BUILD_BUG_ON() above under question.

Jan

#81 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

In reply to Oleksii Kurochko
Quoted 26 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +26 -0
+static void ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to save the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(p) )
+        return;
+
+    p2m_ctxt_switch_from(p);
+
+    vtimer_ctxt_switch_from(p);
+
+    save_csr_regs(p);
+}
+
+static void ctxt_switch_to(struct vcpu *n)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to restore the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(n) )
+        return;

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

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+
+    /*
+     * If this vCPU last ran on a different pCPU, invalidate its VMID so
+     * vmid_handle_vmenter() assigns a fresh one from the current pCPU's pool.
+     * Without this, two pCPUs could independently assign the same
+     * (generation, vmid) pair, generation counters start at the same value
+     * on all pCPUs and increment independently, causing TLB contamination.
+     */
+    if ( n->arch.last_cpu != smp_processor_id() )
+        vmid_flush_vcpu(n);

I wonder why you need this, when we don't have anything similar in x86/HVM (and at the first glance Arm doesn't have anything similar either).

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

Quoted 6 lines
xen/arch/riscv/domain.c +6 -0
+    vtimer_ctxt_switch_to(n);
+
+    restore_csr_regs(n);
+
+    p2m_ctxt_switch_to(n);
+}

In the absenmce of a comment towards the need for this specific order I'd expect these three calls to be ordered the opposite of their counterparts in ctxt_switch_from().

Quoted 58 lines
xen/arch/riscv/domain.c +58 -0
+static void schedule_tail(struct vcpu *prev)
+{
+    unsigned int cpu = smp_processor_id();
+
+    ASSERT(prev != current);
+
+    ctxt_switch_from(prev);
+
+    /*
+     * Mark this CPU in next domain's dirty cpumasks before calling
+     * ctxt_switch_to(). This avoids a race on things like p2m flushing,
+     * which is synchronised on that function.
+     */
+    if ( prev->domain != current->domain )
+    {
+        cpumask_set_cpu(cpu, current->domain->dirty_cpumask);
+
+        /*
+         * Once this hart drops out of prev's dirty_cpumask it stops being a
+         * target of p2m_tlb_flush(), while its TLB may still hold G-stage
+         * translations of prev's domain: neither the vCPU which just ran nor
+         * any other vCPU of that domain which ran here earlier has had its
+         * VMID invalidated. Move the hart to a new VMID generation so that
+         * none of them can be reached again.
+         *
+         * Switching away from the idle vCPU needs no bump: the idle domain
+         * has no p2m of its own, and whatever G-stage entries this hart may
+         * still hold (or speculatively create while HGATP keeps pointing at
+         * the last guest's p2m) are tagged with a VMID which was already made
+         * stale when that guest was switched out. Skipping the bump here also
+         * avoids burning a generation on every pass through idle.
+         */
+        if ( !is_idle_vcpu(prev) )
+            vmid_flush_hart();
+
+        cpumask_clear_cpu(cpu, prev->domain->dirty_cpumask);
+    }
+    write_atomic(&current->dirty_cpu, cpu);
+
+    ctxt_switch_to(current);
+
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
+    current->arch.last_cpu = cpu;
+
+    /*
+     * sched_context_switched() internally uses a spinlock,
+     * which requires interrupts to be enabled.
+     */
+    local_irq_enable();
+
+    sched_context_switched(prev, current);
+}
+
+void context_switch(struct vcpu *prev, struct vcpu *next)
+{
+    ASSERT(local_irq_is_enabled());
+    ASSERT(prev != next);

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

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+    ASSERT(!vcpu_cpu_dirty(next));
+
+    local_irq_disable();
+
+    set_current(next);
+
+    prev = __context_switch(prev, next);
+
+    schedule_tail(prev);
+}

__context_switch() switches stacks, which can easily collide with code the compiler has emitted. For example, the call to schedule_tail() may not be a tail call, and context_switch()'s return address may have been spilled to the stack (or into one of the s<N> registers). There's a reason Arm and x86 have reset_stack_and_jump().

xen/arch/riscv/entry.S restore_registers: · line 106

Quoted 11 lines
xen/arch/riscv/entry.S +5 -0
@@ -99,3 +99,47 @@ restore_registers:
 
         sret
 END(handle_trap)
+
+/*
+ * struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next)
+ *
+ * This is called on prev's stack, and returns on next's.

With ra being switched it may also return to other than the caller. If that's really intended, I think it also needs calling out here.

Quoted 28 lines
xen/arch/riscv/entry.S +28 -0
+ * a0 - prev
+ * a1 - next
+ *
+ * Returns prev in a0
+ */
+FUNC(__context_switch)
+        REG_S   s0, VCPU_XEN_SAVED_CONTEXT_S0(a0)
+        REG_S   s1, VCPU_XEN_SAVED_CONTEXT_S1(a0)
+        REG_S   s2, VCPU_XEN_SAVED_CONTEXT_S2(a0)
+        REG_S   s3, VCPU_XEN_SAVED_CONTEXT_S3(a0)
+        REG_S   s4, VCPU_XEN_SAVED_CONTEXT_S4(a0)
+        REG_S   s5, VCPU_XEN_SAVED_CONTEXT_S5(a0)
+        REG_S   s6, VCPU_XEN_SAVED_CONTEXT_S6(a0)
+        REG_S   s7, VCPU_XEN_SAVED_CONTEXT_S7(a0)
+        REG_S   s8, VCPU_XEN_SAVED_CONTEXT_S8(a0)
+        REG_S   s9, VCPU_XEN_SAVED_CONTEXT_S9(a0)
+        REG_S   s10, VCPU_XEN_SAVED_CONTEXT_S10(a0)
+        REG_S   s11, VCPU_XEN_SAVED_CONTEXT_S11(a0)
+        REG_S   sp, VCPU_XEN_SAVED_CONTEXT_SP(a0)
+        REG_S   ra, VCPU_XEN_SAVED_CONTEXT_RA(a0)
+
+        REG_L   s0, VCPU_XEN_SAVED_CONTEXT_S0(a1)
+        REG_L   s1, VCPU_XEN_SAVED_CONTEXT_S1(a1)
+        REG_L   s2, VCPU_XEN_SAVED_CONTEXT_S2(a1)
+        REG_L   s3, VCPU_XEN_SAVED_CONTEXT_S3(a1)
+        REG_L   s4, VCPU_XEN_SAVED_CONTEXT_S4(a1)
+        REG_L   s5, VCPU_XEN_SAVED_CONTEXT_S5(a1)
+        REG_L   s6, VCPU_XEN_SAVED_CONTEXT_S6(a1)

xen/arch/riscv/entry.S restore_registers: · line 145

Quoted 10 lines
xen/arch/riscv/entry.S +10 -0
+        REG_L   s7, VCPU_XEN_SAVED_CONTEXT_S7(a1)
+        REG_L   s8, VCPU_XEN_SAVED_CONTEXT_S8(a1)
+        REG_L   s9, VCPU_XEN_SAVED_CONTEXT_S9(a1)
+        REG_L   s10, VCPU_XEN_SAVED_CONTEXT_S10(a1)
+        REG_L   s11, VCPU_XEN_SAVED_CONTEXT_S11(a1)
+        REG_L   sp, VCPU_XEN_SAVED_CONTEXT_SP(a1)
+        REG_L   ra, VCPU_XEN_SAVED_CONTEXT_RA(a1)
+
+        ret
+END(__context_switch)

What about gp and tp?

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

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

I don't think this is needed, as ...

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

Quoted 1 line
xen/arch/riscv/include/asm/system.h +1 -0
+struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next);

... parsing of the return type will make the struct known (before parameters are parsed).

Also - can't next be pointer-to-const?

Jan

#55 lore raw

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

In reply to Jan Beulich
Quoted 21 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko
Quoted 9 lines · Jan Beulich

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

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

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

Quoted 8 lines

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

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

Quoted 6 lines

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

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

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

Any better option I have now?

~ Oleksii

Acked-by on v2 14/39
#89 lore raw

Re: [PATCH v2 14/39] xen/riscv: introduce vintc_ctxt_switch_{from,to}()

In reply to Oleksii Kurochko
Quoted 8 lines · Oleksii Kurochko

Virtual interrupt controller state must be preserved across vCPU context switches.

Introduce vintc_ctxt_switch_{from,to}() wrappers around new ctxt_switch_{from,to}() hooks in struct vintc_ops, and call them from the context switch path, so that this state can be saved/restored without knowing which vINTC variant a domain uses.

Quoted 4 lines

No vINTC variant implements the hooks yet: the vAPLIC implementation is added separately.

Also in case you decide to ...

Quoted 6 lines

---
Changes in v2:
- Update the commit message.
- s/vintc_state_{save,restore}/vintc_ctxt_switch_{to,from}.
- s/{re}store_state/ctxt_switch_{to,from} for vintc_ops.
- s/vcpu/v for vintc_ctxt_switch_{to,from}() arguments.

... rename them again to n / p.

Jan

#93 lore raw

Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers

In reply to Oleksii Kurochko
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/vaplic.c +0 -0
@@ -422,6 +422,13 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
 static const struct vintc_ops vintc_ops = {

xen/arch/riscv/vaplic.c static const struct mmio_handler_ops vaplic_mmio_ops = { · line 432

Quoted 10 lines
xen/arch/riscv/vaplic.c +7 -0
     .vcpu_init = vcpu_imsic_init,
     .vcpu_deinit = vcpu_imsic_deinit,
+    /*
+     * MSI delivery is the only supported mode: aplic_init() panics on an
+     * APLIC without an "msi-parent", so the vAPLIC state to save and restore
+     * is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
+    .ctxt_switch_to = imsic_ctxt_switch_to,
 };

As previously expressed, I'm not happy with comments like this. aplic_init() isn't related to vAPLIC behavior. We're doing virtualization, so at least conceptually host and guest behavior want properly separating. Then it may still be that for the time being only a certain subset of possibilities is supported.

Jan

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

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

In reply to Oleksii Kurochko
Quoted 28 lines · Oleksii Kurochko

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

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

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

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

Quoted 1 line
#137 lore raw

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

In reply to Baptiste Le Duc
Quoted 63 lines · Baptiste Le Duc
Quoted 43 lines

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

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

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

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

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

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

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

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

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

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

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

Jan

#142 lore raw

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

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

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

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

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

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

Jan

Acked-by on v2 23/39
#147 lore raw

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

In reply to Oleksii Kurochko
Quoted 21 lines · Oleksii Kurochko

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

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

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

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

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

Quoted 8 lines

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

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

#68 lore raw

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

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

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

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

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

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

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

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

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

Quoted 8 lines

Review

Quoted 4 lines

Would it be better to:

(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

Then BUILD_BUG_on should be updated to:

   /* desc->irq < NR_IRQS, so it always fits the EIID field */
      BUILD_BUG_ON(NR_IRQS - 1 > MASK_EXTR(~0U, APLIC_TARGET_EIID));
Quoted 3 lines

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Quoted 8 lines
Quoted 6 lines

Device MSIs never pass through the APLIC. They are written straight into an IMSIC interrupt file. The ID space belongs to each file, so each hart has up to 2047 IDs (IMSIC_MAX_ID).

1k it is limitation for wired interrupts (which could be delivered in MSI mode where APLIC + IMSIC is needed) which are going through APLIC.

But desc->irq and NR_IRQS have to represent both. Which then puts the BUILD_BUG_ON() above under question.

Agreed. Right now desc->irq, the APLIC source number and the IMSIC EIID are all the same number: aplic_set_irq_affinity() writes desc->irq into EIID, and aplic_handle_interrupt() hands the IMSIC identity from stopei straight to do_IRQ(). That only works because there's no MSI support on RISC-V yet, so NR_IRQS covers wired interrupts only.

Once device MSIs are supported, that identity mapping can't stay anyway. IMSIC IDs are per interrupt file and shared between wired and MSI interrupts, so we'll need to allocate EIIDs and map desc->irq to (hart, EIID). target[] will then get the allocated EIID rather than desc->irq, and NR_IRQS will grow beyond 1024.

So for this patch I'll tie the check to the APLIC source range instead of NR_IRQS:

BUILD_BUG_ON(ARRAY_SIZE(aplic.regs->target) >

             MASK_EXTR(~0U, APLIC_TARGET_EIID));

ASSERT(desc->irq && desc->irq <= aplic_info.num_irqs);

The ASSERT also covers the target[desc->irq - 1] indexing.

~ Oleksii

#82 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

In reply to Jan Beulich
Quoted 32 lines · Jan Beulich
Quoted 31 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +31 -0
+static void ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to save the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(p) )
+        return;
+
+    p2m_ctxt_switch_from(p);
+
+    vtimer_ctxt_switch_from(p);
+
+    save_csr_regs(p);
+}
+
+static void ctxt_switch_to(struct vcpu *n)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to restore the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(n) )
+        return;
+
+    /*
+     * If this vCPU last ran on a different pCPU, invalidate its VMID so
+     * vmid_handle_vmenter() assigns a fresh one from the current pCPU's pool.
+     * Without this, two pCPUs could independently assign the same
Quoted 8 lines

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

Quoted 5 lines
xen/arch/riscv/domain.c +5 -0
+     * (generation, vmid) pair, generation counters start at the same value
+     * on all pCPUs and increment independently, causing TLB contamination.
+     */
+    if ( n->arch.last_cpu != smp_processor_id() )
+        vmid_flush_vcpu(n);

I wonder why you need this, when we don't have anything similar in x86/HVM (and at the first glance Arm doesn't have anything similar either).

x86 does have the equivalent: vmx_do_resume() calls hvm_asid_flush_vcpu() in the active_cpu != smp_processor_id() branch, and svm_do_resume() does the same when launch_core != smp_processor_id() ("Migrating to another ASID domain. Request a new ASID."). The RISC-V VMID allocator follows the x86 ASID scheme: VMIDs are a per-pCPU resource with a per-pCPU generation, so a (generation, vmid) pair obtained on one pCPU means nothing on another. Arm doesn't need this because it allocates a single VMID per domain from a global bitmap.

Also, note that I've update a little bit how VMIDs are flushed here [1] but this check still present IIURC.

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

Quoted 11 lines

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

Quoted 7 lines
xen/arch/riscv/domain.c +6 -0
+    vtimer_ctxt_switch_to(n);
+
+    restore_csr_regs(n);
+
+    p2m_ctxt_switch_to(n);
+}

In the absenmce of a comment towards the need for this specific order I'd expect these three calls to be ordered the opposite of their counterparts in ctxt_switch_from().

I will put restore_csr_regs(n) (and rename it to csr_regs_ctxt_switch_to(n)) before vtimer_ctxt_switch_to(). There is no any specific requirement to be ordered in the way it is now.

Quoted 67 lines
Quoted 67 lines
xen/arch/riscv/domain.c +66 -0
+static void schedule_tail(struct vcpu *prev)
+{
+    unsigned int cpu = smp_processor_id();
+
+    ASSERT(prev != current);
+
+    ctxt_switch_from(prev);
+
+    /*
+     * Mark this CPU in next domain's dirty cpumasks before calling
+     * ctxt_switch_to(). This avoids a race on things like p2m flushing,
+     * which is synchronised on that function.
+     */
+    if ( prev->domain != current->domain )
+    {
+        cpumask_set_cpu(cpu, current->domain->dirty_cpumask);
+
+        /*
+         * Once this hart drops out of prev's dirty_cpumask it stops being a
+         * target of p2m_tlb_flush(), while its TLB may still hold G-stage
+         * translations of prev's domain: neither the vCPU which just ran nor
+         * any other vCPU of that domain which ran here earlier has had its
+         * VMID invalidated. Move the hart to a new VMID generation so that
+         * none of them can be reached again.
+         *
+         * Switching away from the idle vCPU needs no bump: the idle domain
+         * has no p2m of its own, and whatever G-stage entries this hart may
+         * still hold (or speculatively create while HGATP keeps pointing at
+         * the last guest's p2m) are tagged with a VMID which was already made
+         * stale when that guest was switched out. Skipping the bump here also
+         * avoids burning a generation on every pass through idle.
+         */
+        if ( !is_idle_vcpu(prev) )
+            vmid_flush_hart();
+
+        cpumask_clear_cpu(cpu, prev->domain->dirty_cpumask);
+    }
+    write_atomic(&current->dirty_cpu, cpu);
+
+    ctxt_switch_to(current);
+
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
+    current->arch.last_cpu = cpu;
+
+    /*
+     * sched_context_switched() internally uses a spinlock,
+     * which requires interrupts to be enabled.
+     */
+    local_irq_enable();
+
+    sched_context_switched(prev, current);
+}
+
+void context_switch(struct vcpu *prev, struct vcpu *next)
+{
+    ASSERT(local_irq_is_enabled());
+    ASSERT(prev != next);
+    ASSERT(!vcpu_cpu_dirty(next));
+
+    local_irq_disable();
+
+    set_current(next);
+
+    prev = __context_switch(prev, next);
+
Quoted 8 lines

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

Quoted 2 lines
xen/arch/riscv/domain.c +2 -0
+    schedule_tail(prev);
+}

__context_switch() switches stacks, which can easily collide with code the compiler has emitted. For example, the call to schedule_tail() may not be a tail call, and context_switch()'s return address may have been spilled to the stack (or into one of the s<N> registers). There's a reason Arm and x86 have reset_stack_and_jump().

RISC-V will have reset_stack_and_jump() that too but just introduced later and will be used for different use case (in continue_new_vcpu() introduced later in this patch series). But as the Arm RISC-V doesn't use reset_stack_and_jump() in context_switch().

This follows the Arm model: every vCPU has its own Xen stack, and from the incoming vCPU's point of view __context_switch() is ABI-conforming. It restores exactly the sp/ra/s0-s11 that vCPU had when it itself called __context_switch() from context_switch(). So after the return we are in next's own context_switch() frame, and anything the compiler spilled there (ra included) belongs to next. The only exception is a vCPU which has never run: its ra points at continue_new_vcpu() on an empty stack, and that's where reset_stack_and_jump() is needed, as on Arm. I'll make continue_new_vcpu() noreturn accordingly. x86 differs because its stacks are per-pCPU (IIUC), hence its context_switch() can't return.

Here is some diagram for better understanding:
vCPU A (stack A) vCPU B (stack B, switched out earlier)
schedule() schedule()
- context_switch(A, B) - context_switch(B, X)
[A's frame: ra, s-regs] [B's frame: ra, s-regs]
`- __context_switch() --------> "returns" here
(save A, load B) schedule_tail(prev = A)
ld ra <- B's frame (B's own ra) ret -> B's sched_context_switch()
-> ... -> back into B

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/entry.S +0 -0
@@ -99,3 +99,47 @@ restore_registers:
 
Quoted 10 lines

xen/arch/riscv/entry.S restore_registers: · line 106

Quoted 7 lines
xen/arch/riscv/entry.S +5 -0
          sret
  END(handle_trap)
+
+/*
+ * struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next)
+ *
+ * This is called on prev's stack, and returns on next's.

With ra being switched it may also return to other than the caller. If that's really intended, I think it also needs calling out here.

Yes, it's intended. Normally it returns into next's own context_switch() (where next itself last called __context_switch()), and for a vCPU which has never run it returns to continue_new_vcpu(). I'll update the comment to:

* This is called on prev's stack, and returns on next's. As ra is
* switched too, it doesn't return to its caller: it returns to where
* next last called it from, i.e. into next's own context_switch(), or,
* for a vCPU which has never run, to continue_new_vcpu() with an empty
* stack.

Quoted 33 lines
Quoted 33 lines
xen/arch/riscv/entry.S +32 -0
+ * a0 - prev
+ * a1 - next
+ *
+ * Returns prev in a0
+ */
+FUNC(__context_switch)
+        REG_S   s0, VCPU_XEN_SAVED_CONTEXT_S0(a0)
+        REG_S   s1, VCPU_XEN_SAVED_CONTEXT_S1(a0)
+        REG_S   s2, VCPU_XEN_SAVED_CONTEXT_S2(a0)
+        REG_S   s3, VCPU_XEN_SAVED_CONTEXT_S3(a0)
+        REG_S   s4, VCPU_XEN_SAVED_CONTEXT_S4(a0)
+        REG_S   s5, VCPU_XEN_SAVED_CONTEXT_S5(a0)
+        REG_S   s6, VCPU_XEN_SAVED_CONTEXT_S6(a0)
+        REG_S   s7, VCPU_XEN_SAVED_CONTEXT_S7(a0)
+        REG_S   s8, VCPU_XEN_SAVED_CONTEXT_S8(a0)
+        REG_S   s9, VCPU_XEN_SAVED_CONTEXT_S9(a0)
+        REG_S   s10, VCPU_XEN_SAVED_CONTEXT_S10(a0)
+        REG_S   s11, VCPU_XEN_SAVED_CONTEXT_S11(a0)
+        REG_S   sp, VCPU_XEN_SAVED_CONTEXT_SP(a0)
+        REG_S   ra, VCPU_XEN_SAVED_CONTEXT_RA(a0)
+
+        REG_L   s0, VCPU_XEN_SAVED_CONTEXT_S0(a1)
+        REG_L   s1, VCPU_XEN_SAVED_CONTEXT_S1(a1)
+        REG_L   s2, VCPU_XEN_SAVED_CONTEXT_S2(a1)
+        REG_L   s3, VCPU_XEN_SAVED_CONTEXT_S3(a1)
+        REG_L   s4, VCPU_XEN_SAVED_CONTEXT_S4(a1)
+        REG_L   s5, VCPU_XEN_SAVED_CONTEXT_S5(a1)
+        REG_L   s6, VCPU_XEN_SAVED_CONTEXT_S6(a1)
+        REG_L   s7, VCPU_XEN_SAVED_CONTEXT_S7(a1)
+        REG_L   s8, VCPU_XEN_SAVED_CONTEXT_S8(a1)
+        REG_L   s9, VCPU_XEN_SAVED_CONTEXT_S9(a1)
+        REG_L   s10, VCPU_XEN_SAVED_CONTEXT_S10(a1)
Quoted 8 lines

xen/arch/riscv/entry.S restore_registers: · line 145

Quoted 6 lines
xen/arch/riscv/entry.S +6 -0
+        REG_L   s11, VCPU_XEN_SAVED_CONTEXT_S11(a1)
+        REG_L   sp, VCPU_XEN_SAVED_CONTEXT_SP(a1)
+        REG_L   ra, VCPU_XEN_SAVED_CONTEXT_RA(a1)
+
+        ret
+END(__context_switch)

What about gp and tp?

tp points to this hart's pcpu_info (set up once per hart by setup_tp()), i.e. it's per-pCPU rather than per-vCPU state. __context_switch() starts and ends on the same hart, so tp has to be left alone.

gp isn't used by Xen at all: there's no __global_pointer$ in the linker script, so no gp-relative relaxation happens, and the compiler never allocates gp.

Neither of them is callee-saved per the psABI, so there's nothing to preserve across the call. The guest's gp/tp are part of the guest state and are going to be saved/restored via cpu_user_regs by the trap entry/exit path.

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/include/asm/system.h +0 -0
@@ -76,6 +76,10 @@ static inline bool local_irq_is_enabled(void)
 
  #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
Quoted 8 lines

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

Quoted 1 line
xen/arch/riscv/include/asm/system.h +1 -0
+struct vcpu;

I don't think this is needed, as ...

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

Quoted 1 line
xen/arch/riscv/include/asm/system.h +1 -0
+struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next);

... parsing of the return type will make the struct known (before parameters are parsed).

Make sense to me. I will drop forward declaration.

Quoted 2 lines

Also - can't next be pointer-to-const?

It could be. I will add const.

Thanks!

~ Oleksii

#94 lore raw

Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers

In reply to Jan Beulich
Quoted 13 lines · Jan Beulich
Quoted 12 lines · Oleksii Kurochko
xen/arch/riscv/vaplic.c +6 -0
@@ -422,6 +422,13 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
  static const struct vintc_ops vintc_ops = {
      .vcpu_init = vcpu_imsic_init,
      .vcpu_deinit = vcpu_imsic_deinit,
+    /*
+     * MSI delivery is the only supported mode: aplic_init() panics on an
+     * APLIC without an "msi-parent", so the vAPLIC state to save and restore
+     * is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
Quoted 8 lines

xen/arch/riscv/vaplic.c static const struct mmio_handler_ops vaplic_mmio_ops = { · line 432

Quoted 2 lines
xen/arch/riscv/vaplic.c +1 -0
+    .ctxt_switch_to = imsic_ctxt_switch_to,
  };

As previously expressed, I'm not happy with comments like this. aplic_init() isn't related to vAPLIC behavior. We're doing virtualization, so at least conceptually host and guest behavior want properly separating. Then it may still be that for the time being only a certain subset of possibilities is supported.

I will drop the part "aplic_init() panics on an APLIC without an "msi-parent". It is really not very relevant here.

Thanks.

~ Oleksii

#116 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

In reply to Jan Beulich
Quoted 102 lines · Jan Beulich
Quoted 33 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c new file +19 -0
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>
+#include <asm/traps.h>
+
+/*
+ * The hardware-reported details of a guest page fault, gathered once by
Quoted 8 lines

xen/arch/riscv/emulate.c line 25

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+ * handle_guest_page_fault() and passed down to the emulation of the faulted
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state as saved on entry to do_trap(). */
+    struct cpu_user_regs *regs;

If the comment was true, this could be pointer-to-const.

Quoted 3 lines

I think it can't be pointer-to-const as emulate_load/store functions wants to change PC register after MMIO access emulation is finished to not trap again.

Of course, hence how I started the sentence.

Quoted 58 lines
Quoted 35 lines
Quoted 35 lines
xen/arch/riscv/emulate.c new file +35 -0
+    /* scause: a fetch, a load or a store/AMO guest page fault. */
+    unsigned long cause;
+    /*
+     * htinst: the trapped instruction in its transformed form, or one of the
+     * special values (zero, or a pseudoinstruction).
+     */
+    unsigned long htinst;
+    /* htval: as written by hardware; see resolve_faulting_gpa(). */
+    unsigned long htval;
+    /* stval: the guest virtual address of the faulting access. */
+    unsigned long stval;
+    /* The faulting guest physical address, filled by resolve_faulting_gpa(). */
+    paddr_t gpa;
+};
+
+/*
+ * Is @htinst one of the pseudoinstructions reported for a guest page fault
+ * taken on an implicit memory access done for VS-stage address translation?
+ *
+ * All four values are recognized regardless of the hypervisor's XLEN: the
+ * width they encode is that of a VS-stage PTE, i.e. it follows the guest's
+ * paging mode (4 bytes for Sv32, 8 otherwise). On RV32 the 64-bit forms
+ * simply never occur.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    switch ( htinst )
+    {
+    case INSN_PSEUDO_VS_LOAD32:
+    case INSN_PSEUDO_VS_STORE32:
+    case INSN_PSEUDO_VS_LOAD64:
+    case INSN_PSEUDO_VS_STORE64:
+        return true;
+
+    default:
Quoted 8 lines

xen/arch/riscv/emulate.c line 63

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        return false;
+    }
+}

This feels fragile. New pseudo-insns can appear at any time. If the value as a whole is non-zero, aiui the low two bits being zero indicate a pseudo-insn. In which case enumerating pseudo-insns we are currently aware of isn't necessary.

I will write it simpler then:

/*
* Is @htinst one of the special pseudoinstruction values, reported for
a guest
* page fault taken on an implicit memory access done for VS-stage address
* translation?
*
* It is enough to check only bits[1:0] as according to the spec:
*
* The value is one of the special pseudoinstructions defined later, all of
* which have bits 1:0 equal to 00.
*/
static bool htinst_is_pseudo(unsigned long htinst)

Quoted 3 lines
{
      return htinst && ((htinst & 3) == 0);
}
Quoted 6 lines

And preferably

      return htinst && !(htinst & 3);

to be self-consistent.

Good point. I will apply your suggestion.

Quoted 24 lines
Quoted 24 lines
Quoted 24 lines
Quoted 23 lines
xen/arch/riscv/emulate.c new file +23 -0
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
+        inject_access_fault(&gf);
+
+        return;
+    }
Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

I.e. you imply that guests won't put their page tables in MMIO? That's fragile imo; I have seen OSes to use video frame buffers for all kinds of (transient) purposes, for example.

I think it is okay for now and if it will a real use case then an update of this code will be needed.

May I then ask that you leave a remark (maybe even fixme) to this effect?

Sure, I will then add the following to the comment above if ():

* FIXME: This assumes that guest page tables never reside in an
emulated
* MMIO region, i.e. that an implicit access faulting at G-stage always
* targets an unpopulated GPA. Guests may (even transiently) place page
* tables in MMIO-backed memory, e.g. a video frame buffer. Supporting
* that would require walking the VS-stage page tables in software,
* accessing the PTEs (including A/D updates) through the MMIO
handlers,
* and then emulating the original access, instead of injecting a
fault.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

xen/arch/riscv/emulate.c line 147

Quoted 2 lines
xen/arch/riscv/emulate.c new file +1 -0
+    resolve_faulting_gpa(&gf);

Since the function is only a stub right now - how is one to tell whether this indeed can never fail?

Quoted 7 lines
Quoted 3 lines

It can't be tell. But what is wrong if it could fail? (Actually with current implementation introduced in later patches you can find it can fail if a necessary extension or software page walk isn't introduced).

Well, quite obviously if it can fail, its return value would need checking here.

That what I thought about after I sent my e-mail as a possible option.

I will update the prototype to:

+static int resolve_faulting_gpa(struct guest_fault *gf)
{
- BUG_ON("unimplemented");
+ return -EOPNOTSUPP;
}

And handle an error code in the following way:

@@ -136,7 +144,8 @@ void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause )

         return;
     }

- resolve_faulting_gpa(&gf);
+ if ( rc = resolve_faulting_gpa(&gf) )
+ goto out;

switch ( cause )
{
@@ -163,6 +172,7 @@ void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause )

         break;
     }

+ out:
if ( rc )
domain_crash(current->domain,

and then in the next patch "[PATCH v2 21/39] xen/riscv: resolve the faulting guest physical address" I will do "return -EOPNOTSUPP" instead of panic():

- panic("Shtvala isn't supported by h/w; s/w VS-stage walk
required\n");
++ {
++ printk_once(XENLOG_WARNING
++ "Shtvala isn't supported by h/w; s/w VS-stage walk required\n");
++ return -EOPNOTSUPP;
++ }

~ Oleksii

#133 lore raw

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

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

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

Quoted 7 lines

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

Quoted 2 lines

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

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

Quoted 6 lines

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

... here.

Quoted 5 lines

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

Quoted 7 lines

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

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

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

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

So here I think we want to clarify then:

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

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

Quoted 32 lines

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

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

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

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

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

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

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

Thanks.

~ Oleksii

#138 lore raw

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

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

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

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

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

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

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

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

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

Agree not to much sense. I will drop it.

Quoted 11 lines

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

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

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

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

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

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

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

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

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

Yes.

~ Oleksii

#139 lore raw

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

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

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

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

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

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

  }

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

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

Quoted 8 lines
Quoted 5 lines

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

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

Quoted 1 line

Agree not to much sense. I will drop it.

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

So I think we could keep riscv_ prefix.

~ Oleksii

#140 lore raw

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

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

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

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

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

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

  }

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

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

Quoted 8 lines

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

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

Quoted 7 lines
Quoted 1 line

Agree not to much sense. I will drop it.

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

So I think we could keep riscv_ prefix.

Please may I suggest to avoid unnecessary prefixes?

Jan

#141 lore raw

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

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

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

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

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

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

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

Quoted 8 lines
Quoted 5 lines

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

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

Agree not to much sense. I will drop it.

Quoted 7 lines
Quoted 5 lines

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

So I think we could keep riscv_ prefix.

Please may I suggest to avoid unnecessary prefixes?

Sure then I will drop it as originally suggested.

~ Oleksii

#143 lore raw

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

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

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

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

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

Quoted 5 lines

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

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

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

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

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

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

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

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

Thanks.

~ Oleksii

#144 lore raw

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

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

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

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

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

Quoted 4 lines

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

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

Jan

Quoted 7 lines

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

Thanks.

~ Oleksii

#145 lore raw

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

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

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

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

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

Quoted 8 lines
Quoted 4 lines

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

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

Agree, struct cpu_user_regs * will be required.

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

I think it is enough just to have:

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

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

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

~ Oleksii

#56 lore raw

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

In reply to Oleksii Kurochko

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

Quoted 11 lines

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

Any better option I have now?

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

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

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

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

Thanks,
SeungJu

#151 lore raw

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

In reply to Oleksii Kurochko
Quoted 11 lines · Oleksii Kurochko

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

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

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

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

   (void)is_load_guest_page_fault;

etc in e.g. emulate_load()?

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

xen/arch/riscv/emulate.c line 38

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Jan

#157 lore raw

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

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

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

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

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

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

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

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

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

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

Jan

#162 lore raw

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

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

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

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

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

Jan

Acked-by on v2 27/39
#169 lore raw

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

In reply to Oleksii Kurochko
Quoted 9 lines · Oleksii Kurochko

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

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

Quoted 9 lines

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

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

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

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

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

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

Jan

#173 lore raw

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

In reply to Oleksii Kurochko
Quoted 9 lines · Oleksii Kurochko

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

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

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

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

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

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

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

Jan

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

Re: [PATCH v2 29/39] xen/riscv: introduce aplic_reconfigure_target()

In reply to Oleksii Kurochko
Quoted 8 lines · Oleksii Kurochko

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

Implement aplic_reconfigure_target() to scan all interrupts allocated to the domain and update their APLIC TARGET registers accordingly.

First of all I'd like to understand how this "reconfigure" works without losing interrupts and at the same time without other possible races. An interrupt can be raised at any time, after all.

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 147

Quoted 13 lines
xen/arch/riscv/aplic.c +7 -0
@@ -138,6 +138,48 @@ uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
     return base_val;
 }
 
+void aplic_reconfigure_target(const struct vcpu *v,
+                              unsigned int old_guest_file_id,
+                              unsigned int old_cpu)
+{
+    const struct vintc *vintc = v->domain->arch.vintc;
+    const unsigned long *auth_irq_bmp = vintc->used_irqs;
+    unsigned long old_hart_field = aplic_hart_field(old_cpu);

Once again a question you may already recognize: What extra value does "field" in the variable name add?

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 154

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+    unsigned long flags;
+    unsigned int irqn;
+
+    /* Support only MSI mode at the moment */
+    BUG_ON(!aplic_msi_mode());
+
+    spin_lock_irqsave(&aplic.lock, flags);

Taking a global lock for a per-vCPU operation isn't going to scale very well. Even more so when then ...

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 156

Quoted 1 line
xen/arch/riscv/aplic.c +1 -0
+    bitmap_for_each ( irqn, auth_irq_bmp, vintc->nr_virqs )

... you run a loop with perhaps many (hundreds? thousands?) iterations.

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+    {
+        volatile uint32_t __iomem *ptarget;
+        uint32_t target_val;
+        unsigned int guest_index, hart_index;
+
+        if ( !irqn )
+            continue;

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 173

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+
+        ptarget = &aplic.regs->target[irqn - 1];
+        target_val = readl(ptarget);
+
+        guest_index = MASK_EXTR(target_val, APLIC_TARGET_GUEST_IDX);
+        hart_index = MASK_EXTR(target_val, APLIC_TARGET_HART_IDX);
+
+        if ( (guest_index != old_guest_file_id) ||
+             (hart_index != old_hart_field) )
+            continue;

Along the lines of the naming comment above: This would be more logical to follow if it was

        if ( (guest_id != old_guest_id) ||
             (hart != old_hart) )
            continue;

i.e. names on each side of the != suitably matching up.

Jan

#185 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

In reply to Oleksii Kurochko

xen/arch/riscv/imsic.c do { \ · line 84

Quoted 8 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +4 -0
@@ -77,6 +78,64 @@ do {                            \
     csr_clear(CSR_SIREG, v);    \
 } while (0)
 
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \

As patch context also tells: Excess parentheses.

xen/arch/riscv/imsic.c do { \ · line 91

Quoted 7 lines
xen/arch/riscv/imsic.c +7 -0
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are forwarded to F
+ * via __VA_ARGS__.

Just that there's no F below.

Quoted 7 lines
xen/arch/riscv/imsic.c +7 -0
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \

xen/arch/riscv/imsic.c do { \ · line 109

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)

Ah, there is an F here.

This (recurring below) shows another problem: The two F invocations look syntacticlly incorrect, due to the missing semicolon. Semicolon use wants redoing everywhere here.

Further (and again throughout) I think we'd be better off using either standard C constructs (e.g. __VA_ARGS__) or the gcc extension permitting use of ## after a comma. A mix of both always looks odd (to me at least).

Finally, unlike further up, here (and below) ireg wants parenthesizing.

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 458

Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
     return 0;
 }
 
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;

I can't spot any use of this field (and hence I also can't judge whether const wants adding).

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 474

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)

If this is supposed to be passed struct imsic_vsfile_data *, why not say so here? Be as type-safe as possible. Of course the callback function has to use void *.

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 496

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

Wouldn't it make sense to avoid the call here altogether then?

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 498

Quoted 1 line
xen/arch/riscv/imsic.c +1 -0
+    old_vsiselect = csr_read(CSR_VSISELECT);

Likely obvious to you, but I can't spot why vsiselect would need saving here. If you want me to ack such code, please add at least brief comments.

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 514

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif

In asm/imsic.h I see

#define IMSIC_EIPx_BITS 32

Why is the number of CSR writes different here for RV32 vs RV64? And if so, why would you not use the 64-bit write function, allowing the #ifdef to be omitted?

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

Quoted 8 lines
xen/arch/riscv/imsic.c +4 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
 void imsic_migrate_vcpu(struct vcpu *v)
 {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

As written, this could also be 64. uint64_t is a fixed-width type after all. The question here is: Which variable's type do you really mean here?

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

Quoted 2 lines
xen/arch/riscv/imsic.c +2 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = nr_hw_eix,

The local variable looks to be used only here. Is there really a need for such a local variable?

Quoted 5 lines
xen/arch/riscv/imsic.c +1 -0
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == NR_CPUS )
         return;
 
+    /*

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

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;

Same here: Is this variable really needed? And what exactly is the comment telling me?

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

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    new_vsfile_hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;

And again - any real need for the separate local variable?

Jan

#193 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

In reply to Oleksii Kurochko
Quoted 8 lines · Oleksii Kurochko

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

Hmm. As indicated, I'm learning RISC-V as I'm reviewing patches. This paragraph, if left as is, would make sure I simply can't ack the patch. I just don't understand what is being talked about. I can guess parts, but for example I don't know what "genmsi" is.

Quoted 7 lines
xen/arch/riscv/aplic.c +3 -0
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
     spin_unlock_irqrestore(&aplic.lock, flags);
 }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 222

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);

Along the lines of a question on an earlier patch: What if this ANDing actually chops off bits?

Jan

#201 lore raw

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

In reply to Oleksii Kurochko

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 66

Quoted 7 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +3 -0
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
 #define IMSIC_DISABLE_EITHRESHOLD   1
 #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \

Nit: Excess parentheses again.

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 9 lines
xen/arch/riscv/imsic.c +5 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
     spin_unlock(&imsic_cfg.lock);
 }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 2 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

Quoted 6 lines
xen/arch/riscv/imsic.c +2 -0
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
         on_selected_cpus(cpumask_of(cpu), func, data, 1);
 }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

If the parameter isn't used, maybe best to name it "unused"?

Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == NR_CPUS )
         return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case

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

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
     /*
      * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
      * VS-file.
      */

Isn't the new part of the comment premature? Moving doesn't start until ...

Quoted 17 lines
xen/arch/riscv/imsic.c +13 -0
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Zero-out new IMSIC VS-file */
     imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical

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

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);

... here, as it looks.

Jan

#212 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko

At the old interrupt file, dump to memory all the eip and eie arrays). After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to deal with that.

Beside this being difficult to parse, it looks like it is inapplicable? As said ...

Quoted 5 lines

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

vgein_release() is stub for now and will be introduced later.

... also here?

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 64

Quoted 12 lines
xen/arch/riscv/imsic.c +6 -0
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
  */
 #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))

As before - plain 64 please, or it needs to become clear where the uint64_t is actually coming from.

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 68

Quoted 3 lines
xen/arch/riscv/imsic.c +3 -0
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];

Same here. Yet better may be to use DECLARE_BITMAP()?

xen/arch/riscv/imsic.c do { \ · line 113

Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -85,6 +103,15 @@ do {                            \
     csr_clear(CSR_SIREG, v);    \
 } while (0)
 
+#define imsic_vs_csr_swap(c, v)     \
+({                                  \
+    unsigned long r_;               \
+                                    \
+    csr_write(CSR_VSISELECT, (c));  \
+    r_ = csr_swap(CSR_VSIREG, (v)); \
+    r_;                             \
+})

Excess parentheses again. Plus - what use is r_ here?

Quoted 5 lines
xen/arch/riscv/imsic.c +1 -0
@@ -130,6 +157,21 @@ do {                                \
     imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
     imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
 
+static unsigned long imsic_eix_swap(unsigned int ireg, unsigned long val)

xen/arch/riscv/imsic.c do { \ · line 170

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIP0,
+                        imsic_vs_csr_swap, val)
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIE0,
+                        imsic_vs_csr_swap, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }

There still wants to "break" in the default case.

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

Quoted 6 lines
xen/arch/riscv/imsic.c +2 -0
@@ -973,5 +1071,11 @@ void imsic_migrate_vcpu(struct vcpu *v)
      * to the new IMSIC VS-file.
      */
 
+    /* Read and clear register state from old IMSIC VS-file */
+    imsic_vsfile_read_clear(old_vsfile_id, old_vsfile_cpu, nr_hw_eix, &tmrif);

Why is &tmrif being passed into the function, when it's not otherwise used here? The function could itself have a suitable local var.

Jan

#219 lore raw

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

In reply to Oleksii Kurochko

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

Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +1 -1
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
     new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);

Please put into final shape upon introduction.

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

Quoted 10 lines
xen/arch/riscv/imsic.c +3 -3
     csr_write(CSR_HSTATUS, new_hstatus);
 
     /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
      */

Same for this comment perhaps.

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

Quoted 7 lines
xen/arch/riscv/imsic.c +2 -1
@@ -1077,5 +1140,12 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Free-up old IMSIC VS-file */
     vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    vsfile_data.mrif = &tmrif;

Ah, here &tmrif is used a 2nd time.

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

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_update, &vsfile_data);
+
+    /* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */
+    vcpu_guest_cpu_user_regs(v)->hstatus &= ~HSTATUS_VGEIN;
+    vcpu_guest_cpu_user_regs(v)->hstatus |=
+            MASK_INSR(new_vsfile_hgei, HSTATUS_VGEIN);

Nit: Indentation.

Other comments on earlier patches apply here (and possibly elsewhere) as well. Just ftaod.

Jan

#152 lore raw

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

In reply to Jan Beulich
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

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

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

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

Quoted 6 lines

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

    (void)is_load_guest_page_fault;

etc in e.g. emulate_load()?

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

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

xen/arch/riscv/emulate.c line 38

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

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

We could compress the structure into 8 bytes:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

good point. I'll apply.

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

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

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

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

I think that no as according to the spec:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

I will re-word in the following way:

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

Quoted 7 lines

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

Quoted 4 lines
xen/arch/riscv/emulate.c +3 -0
+        if ( !INSN_IS_16BIT(di->insn) && !INSN_IS_32BIT(di->insn) )
+        {
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

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

Quoted 7 lines

xen/arch/riscv/emulate.c

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

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

Right, I'll mention that as well:

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

Quoted 11 lines

xen/arch/riscv/emulate.c

Quoted 7 lines
xen/arch/riscv/emulate.c +6 -0

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

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

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

        di->insn_len = INSN_LEN(di->insn);
...
        if ( !di->insn_len )
Quoted 28 lines
Quoted 28 lines
xen/arch/riscv/emulate.c +28 -0

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Quoted 8 lines

xen/arch/riscv/emulate.c

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

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

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

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

Quoted 30 lines

xen/arch/riscv/emulate.c

Quoted 29 lines
xen/arch/riscv/emulate.c +28 -0

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Quoted 2 lines

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

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

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

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

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

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

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

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

        if ( !(insn & 2) )
            di->reg = RVC_RS2S(insn);
        else if ( di->is_write )
            di->reg = RVC_RS2(insn);
        else
        {
            di->reg = RV_RD(insn);
            /* C.LWSP and C.LDSP are reserved with rd being x0. */
            if ( !di->reg )
                return false;
        }
    }

46 lines not shown · raw message

38 lines not shown · raw message

Parts of this message are not shown here. View the raw message.

#153 lore raw

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

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

xen/arch/riscv/emulate.c line 38

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

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

We could compress the structure into 8 bytes:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

         default:
             return false;
         }
     }

     di->len = 1U << width_log2;

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

     return true;


     return true;
}
Quoted 1 line

But I am not sure this is what you meant.

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

Quoted 37 lines
Quoted 8 lines

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

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

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

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

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

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

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

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

Would it be better?

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

Jan

#158 lore raw

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

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

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

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

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

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

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

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

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

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

Quoted 3 lines

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

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

THanks.

~ Oleksii

#163 lore raw

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

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

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

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

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

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

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

+ /*

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

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

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

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

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

Thanks.

~ Oleksii

#164 lore raw

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

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

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

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

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

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

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

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

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

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

for a

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

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

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

Quoted 8 lines

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

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

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

Jan

#165 lore raw

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

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

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

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

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

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

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

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

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

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

for a

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

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

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

Quoted 8 lines

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

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

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

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

Thanks.

~ Oleksii

#170 lore raw

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

In reply to Jan Beulich
Quoted 26 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko

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

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

Quoted 9 lines

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

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

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

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

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

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

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

Quoted 1 line

Thanks.

~ Oleksii

Quoted 2 lines

Jan

#174 lore raw

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

In reply to Jan Beulich
Quoted 7 lines · Jan Beulich
Quoted 6 lines · Oleksii Kurochko

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

Quoted 6 lines
Quoted 3 lines

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

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

Agree, it should be just:

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

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

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

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

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

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

static inline unsigned int smp_processor_id(void)

{
    unsigned int id = tp->processor_id;

    BUG_ON(id >= NR_CPUS);

    return id;
}

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

Thanks.

~ Oleksii

#175 lore raw

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

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

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

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

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

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

static inline unsigned int smp_processor_id(void)

{
     unsigned int id = tp->processor_id;

     BUG_ON(id >= NR_CPUS);

     return id;
}
Quoted 2 lines

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

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

Jan

#183 lore raw

Re: [PATCH v2 29/39] xen/riscv: introduce aplic_reconfigure_target()

In reply to Jan Beulich
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko

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

Quoted 8 lines
Quoted 4 lines

Implement aplic_reconfigure_target() to scan all interrupts allocated to the domain and update their APLIC TARGET registers accordingly.

First of all I'd like to understand how this "reconfigure" works without losing interrupts and at the same time without other possible races. An interrupt can be raised at any time, after all.

The RISC-V AIA specification relies on this separation for the 6-step vCPU migration sequence:

Step 1. Setting eidelivery = 0 at the old interrupt file stops new traps on the host CPU.

Step 3: Reconfiguring APLIC/IOMMU and flushing the interconnect forces all in-flight "straggler" MSIs to reach the old interrupt file.

Step 4: Because eidelivery = 0 did not block incoming MSIs from setting bits in eip, those straggler MSIs safely landed in the old eip array.

Step 5: The hypervisor reads/dumps the old eip array and bitwise ORs it into the new interrupt file, guaranteeing that no in-flight MSIs are lost during the transition.

(Note that I re-word some steps and skipped some for simplicity. Here you can find full text: https://github.com/riscv/riscv-aia/blob/main/src/VSLevel.adoc?plain=1#L134)

Does it make sense now?

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/aplic.c +0 -0
@@ -138,6 +138,48 @@ uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
      return base_val;
  }
 
Quoted 10 lines

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 147

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+void aplic_reconfigure_target(const struct vcpu *v,
+                              unsigned int old_guest_file_id,
+                              unsigned int old_cpu)
+{
+    const struct vintc *vintc = v->domain->arch.vintc;
+    const unsigned long *auth_irq_bmp = vintc->used_irqs;
+    unsigned long old_hart_field = aplic_hart_field(old_cpu);

Once again a question you may already recognize: What extra value does "field" in the variable name add?

Because aplic_hart_field() construct target's part of hart field which isn't contains only pure hart value (apparently, thanks to the way how spec is written and things are done).

Note that based on other reviews from this patch series it is renamed to:
unsigned long old_hart_index = aplic_hart_index(old_cpu);
(and here _index for the same reason it is basically how AIA spec calls this part of the target register)

Quoted 12 lines

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 154

Quoted 8 lines
xen/arch/riscv/aplic.c +7 -0
+    unsigned long flags;
+    unsigned int irqn;
+
+    /* Support only MSI mode at the moment */
+    BUG_ON(!aplic_msi_mode());
+
+    spin_lock_irqsave(&aplic.lock, flags);

Taking a global lock for a per-vCPU operation isn't going to scale very well. Even more so when then ...

Quoted 4 lines

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 156

Quoted 1 line
xen/arch/riscv/aplic.c +1 -0
+    bitmap_for_each ( irqn, auth_irq_bmp, vintc->nr_virqs )

... you run a loop with perhaps many (hundreds? thousands?) iterations.

I agree.

Then per vcpu's target register lock (or per-irq lock) + APLIC's global lock mention here only for a short period when APLIC register would be needed.

I've done such change for support of IMSIC software interrupt file but it seems like it is started to need earlier.

Quoted 22 lines
Quoted 8 lines
xen/arch/riscv/aplic.c +7 -0
+    {
+        volatile uint32_t __iomem *ptarget;
+        uint32_t target_val;
+        unsigned int guest_index, hart_index;
+
+        if ( !irqn )
+            continue;

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 173

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+
+        ptarget = &aplic.regs->target[irqn - 1];
+        target_val = readl(ptarget);
+
+        guest_index = MASK_EXTR(target_val, APLIC_TARGET_GUEST_IDX);
+        hart_index = MASK_EXTR(target_val, APLIC_TARGET_HART_IDX);
+
+        if ( (guest_index != old_guest_file_id) ||
+             (hart_index != old_hart_field) )
+            continue;

Along the lines of the naming comment above: This would be more logical to follow if it was

Quoted 5 lines
         if ( (guest_id != old_guest_id) ||
              (hart != old_hart) )
             continue;

i.e. names on each side of the != suitably matching up.

I agree with guest_id suggestion but hart_index should be left as according to the spec what is stored in hart index field of target register isn't pure hart cpu id but it is a combination of hart cpu id + group index (check the comment above aplic_hart_field() for better context).

Thanks.

~ Oleksii

#176 lore raw

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

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

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

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

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

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

static inline unsigned int smp_processor_id(void)

{
      unsigned int id = tp->processor_id;

      BUG_ON(id >= NR_CPUS);

      return id;
}
Quoted 8 lines
Quoted 2 lines

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

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

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

I will introduce then

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

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

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

For

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

and

struct vimsic_state {
...

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

I can continue to use NR_CPUS, right?

~ Oleksii

#177 lore raw

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

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

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

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

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

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

static inline unsigned int smp_processor_id(void)

{
      unsigned int id = tp->processor_id;

      BUG_ON(id >= NR_CPUS);

      return id;
}
Quoted 8 lines
Quoted 2 lines

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

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

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

I will introduce then

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

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

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

For

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

and

struct vimsic_state {
...

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

I can continue to use NR_CPUS, right?

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

Jan

#178 lore raw

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

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

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

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

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

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

static inline unsigned int smp_processor_id(void)

{
       unsigned int id = tp->processor_id;

       BUG_ON(id >= NR_CPUS);

       return id;
}
Quoted 8 lines
Quoted 2 lines

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

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

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

I will introduce then

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

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

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

For

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

and

struct vimsic_state {
...

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

I can continue to use NR_CPUS, right?

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

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

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

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

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

~ Oleksii

#179 lore raw

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

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

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

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

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

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

static inline unsigned int smp_processor_id(void)

{
       unsigned int id = tp->processor_id;

       BUG_ON(id >= NR_CPUS);

       return id;
}
Quoted 8 lines
Quoted 2 lines

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

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

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

I will introduce then

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

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

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

For

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

and

struct vimsic_state {
...

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

I can continue to use NR_CPUS, right?

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

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

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

Quoted 6 lines

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

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

I fear you may not like the answer: Depends. IOW I can't give a concrete reply unless seeing the concrete use(s).

Jan

#186 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

In reply to Jan Beulich
Quoted 11 lines · Jan Beulich

Review do { \ · line 84

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +4 -0
@@ -77,6 +78,64 @@ do {                            \
      csr_clear(CSR_SIREG, v);    \
  } while (0)
 
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \

As patch context also tells: Excess parentheses.

I will drop them then.

Quoted 10 lines

Review do { \ · line 91

Quoted 8 lines
(quoted diff) +7 -0
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are forwarded to F
+ * via __VA_ARGS__.

Just that there's no F below.

Oh, right. I will move this comment a little bit down.

Quoted 21 lines
Quoted 8 lines
(quoted diff) +7 -0
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \

Review do { \ · line 108

Quoted 10 lines
(quoted diff) +10 -0
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)

Ah, there is an F here.

Quoted 3 lines

This (recurring below) shows another problem: The two F invocations look syntacticlly incorrect, due to the missing semicolon. Semicolon use wants redoing everywhere here.

I will drop then ';' from imsic_switchcase_{break,ret}.

Quoted 5 lines

Further (and again throughout) I think we'd be better off using either standard C constructs (e.g. __VA_ARGS__) or the gcc extension permitting use of ## after a comma. A mix of both always looks odd (to me at least).

I will follow C standard here.

Quoted 2 lines

Finally, unlike further up, here (and below) ireg wants parenthesizing.

I will add some.

Quoted 5 lines
Quoted 5 lines
(quoted diff) +0 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
      return 0;
  }
 
Quoted 11 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 458

Quoted 8 lines
(quoted diff) +8 -0
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;

I can't spot any use of this field (and hence I also can't judge whether const wants adding).

It should be introduced later in the another patch.

Quoted 13 lines
Quoted 13 lines
(quoted diff) +12 -0
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
Quoted 8 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 474

Quoted 4 lines
(quoted diff) +4 -0
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)

If this is supposed to be passed struct imsic_vsfile_data *, why not say so here? Be as type-safe as possible. Of course the callback function has to use void *.

At the moment, I don't see where I am using void * so I will use struct imsic_vsfile_data * instead.

Quoted 12 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 483

Quoted 10 lines
(quoted diff) +9 -0
+static void cf_check imsic_vsfile_local_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;

Wouldn't it make sense to avoid the call here altogether then?

I think it is better to have this if () here instead of the caller side as this function one day could be just directly (w/ imsic_call_on_cpu) and even the way how it is called now and in the case of imsic_call_on_cpu() is executed on local cpu then it will be basically just direct call of imsic_vsfile_local_clear(). So in the case I am not missing something I prefer to have a check here.

Quoted 5 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 484

Quoted 2 lines
(quoted diff) +1 -0
+    old_vsiselect = csr_read(CSR_VSISELECT);

Likely obvious to you, but I can't spot why vsiselect would need saving here. If you want me to ack such code, please add at least brief comments.

I think then it will be better to put the comment once above struct imsic_vsfile_data and then just point here to that comment as basically it will be needed for all imsic_vsfile_local_* helpers.

So basically I am suggesting:

xen/arch/riscv/imsic.c +0 -0
@@ ... @@
 /*
  * Arguments of the imsic_vsfile_local_*() helpers, which are executed 

by the
* pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ *
+ * The helpers interrupt whatever vCPU context is loaded on that pCPU, which
+ * generally isn't the vCPU the interrupt file belongs to. To reach the file
+ * they retarget hstatus.VGEIN and select the file's registers through
+ * vsiselect. Both CSRs are live state of the interrupted vCPU (vsiselect is
+ * saved to struct arch_vcpu only on context switch, but the interrupted vCPU
+ * may resume guest execution without one), hence the helpers have to restore
+ * them before returning.
*/

 struct imsic_vsfile_data {
     unsigned int hgei;
     unsigned int nr_eix;
     struct imsic_mrif *mrif;
 };
@@ ... @@ static void cf_check imsic_vsfile_local_clear(void *data)
     /* We can only zero-out if we have a IMSIC VS-file */
     if ( !idata->hgei )
         return;

+ /* See the comment ahead of struct imsic_vsfile_data. */

     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
@@ ... @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     csr_clear(CSR_HGEIE, BIT(idata->hgei, UL));

+ /* See the comment ahead of struct imsic_vsfile_data. */

     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);

@@ ... @@ static void cf_check imsic_vsfile_local_update(void *data)
* stack.
*/

+ /* See the comment ahead of struct imsic_vsfile_data. */

     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);

Does it look clear now?

Quoted 20 lines
Quoted 7 lines
(quoted diff) +6 -0
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 500

Quoted 10 lines
(quoted diff) +10 -0
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif

In asm/imsic.h I see

Quoted 3 lines

#define IMSIC_EIPx_BITS 32

Why is the number of CSR writes different here for RV32 vs RV64?

IMSIC_EIPx_BITS is the unit the AIA spec numbers the eip<k>/eie<k> registers by. On RV32 all of eip0..eip63 exist and are 32 bits wide. On RV64 only the even-numbered ones exist, each being 64 bits wide and covering what eip<k> and eip<k+1> cover on RV32; accessing an odd-numbered one is an illegal instruction. Hence one 64-bit group of interrupt identities takes one register on RV64, but two on RV32.

I will add some small comments:

    for ( i = 0; i < idata->nr_eix; i++ )
    {
        /* On RV64 a 64-bit EIx group is the even-numbered register 
alone. */
        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
#ifdef CONFIG_RISCV_32
        /*
         * On RV32 it is split into the even-numbered (low half) and the
         * following odd-numbered (high half) register.
         */
        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
#endif
    }
Quoted 3 lines

And
if so, why would you not use the 64-bit write function, allowing the #ifdef to be omitted?

I can introduce something like:

/*
* On RV64 a 64-bit EIx group is the even-numbered register alone, whereas
* on RV32 it is split into the even-numbered (low half) and the following
* odd-numbered (high half) register.
*/
static void imsic_eix_write64(unsigned int ireg, uint64_t val)

{
    imsic_eix_write(ireg, val);
    if ( IS_ENABLED(CONFIG_RISCV_32) )
        imsic_eix_write(ireg + 1, val >> 32);
}

And then:

    for ( i = 0; i < idata->nr_eix; i++ )
    {
        imsic_eix_write64(IMSIC_EIP0 + i * 2, 0);
        imsic_eix_write64(IMSIC_EIE0 + i * 2, 0);
    }

Would it be better?

Or instead of imsic_eix_write64() I could just have a combination of imisc_vsfile_local_clear():

    imsic_eix_write(ireg, 0);
    if ( IS_ENABLED(CONFIG_RISCV_32) )
        imsic_eix_write(ireg + 1, 0);
Quoted 13 lines

Review int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 824

Quoted 9 lines
(quoted diff) +4 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
  void imsic_migrate_vcpu(struct vcpu *v)
  {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

As written, this could also be 64. uint64_t is a fixed-width type after all. The question here is: Which variable's type do you really mean here?

The minimum number of hardware EIx groups is 1 (for the minimum 63 supported interrupt identities, i.e. DIV_ROUND_UP(63 + 1, 64) = 1), and the maximum is 32 (for 2047 identities), on both RV32 and RV64.You are right regarding BITS_PER_TYPE(uint64_t). Since an architectural EIx group always covers 64 interrupt identities regardless of XLEN, using BITS_PER_TYPE(uint64_t) is unnecessarily indirect when we mean a constant 64-bit group size.I will simplify this in v3 to use 64.

Quoted 6 lines

Review int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 826

Quoted 3 lines
(quoted diff) +2 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = nr_hw_eix,

The local variable looks to be used only here. Is there really a need for such a local variable?

No, I will drop nr_hw_eix.

Quoted 5 lines
Quoted 5 lines
(quoted diff) +0 -0
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
Quoted 13 lines

Review void imsic_migrate_vcpu(struct vcpu *v) · line 849

Quoted 11 lines
(quoted diff) +11 -0
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;

Same here: Is this variable really needed?

Technically no, it could be used v->processor everywhere but just for readability (to how spec is wording migration process) I think I will prefer to have new_vsfile_cpu here. But if it doesn't make sense I can agree to drop it.

Quoted 2 lines

And what exactly is the comment
telling me?

I am re-reading it now and it looks just useless.

I think that initially I thought that for some reason v->processor could change during the end of migration and so by that I wanted to fix new vsfile cpu so all the interrupts will go there before migration functon for that vcpu will be called again and reschedule all the interrupt to new v->processor.

I think it isn't real case so the comment could be dropped.

Quoted 9 lines

Review void imsic_migrate_vcpu(struct vcpu *v) · line 855

Quoted 7 lines
(quoted diff) +6 -0
+    new_vsfile_hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;

And again - any real need for the separate local variable?

Here I agree, we could have only vsfile_data.hgei.

Thanks.

~ Oleksii

#187 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

Quoted 17 lines · Oleksii Kurochko
Quoted 16 lines · Jan Beulich

Review

Quoted 12 lines · Oleksii Kurochko
(quoted diff) +12 -0
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)

Ah, there is an F here.

Quoted 5 lines
Quoted 3 lines

This (recurring below) shows another problem: The two F invocations look syntacticlly incorrect, due to the missing semicolon. Semicolon use wants redoing everywhere here.

I will drop then ';' from imsic_switchcase_{break,ret}.

Provided that works, i.e. you have no cae where __VA_ARGS__ expands to nothing.

Quoted 75 lines
Quoted 11 lines

Review

Quoted 9 lines
(quoted diff) +9 -0
+static void cf_check imsic_vsfile_local_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;

Wouldn't it make sense to avoid the call here altogether then?

I think it is better to have this if () here instead of the caller side as this function one day could be just directly (w/ imsic_call_on_cpu) and even the way how it is called now and in the case of imsic_call_on_cpu() is executed on local cpu then it will be basically just direct call of imsic_vsfile_local_clear(). So in the case I am not missing something I prefer to have a check here.

Quoted 5 lines
Quoted 2 lines

+ old_vsiselect = csr_read(CSR_VSISELECT);

Likely obvious to you, but I can't spot why vsiselect would need saving here. If you want me to ack such code, please add at least brief comments.

I think then it will be better to put the comment once above struct imsic_vsfile_data and then just point here to that comment as basically it will be needed for all imsic_vsfile_local_* helpers.

So basically I am suggesting:

xen/arch/riscv/imsic.c +0 -0

@@ ... @@
/*
* Arguments of the imsic_vsfile_local_*() helpers, which are executed
by the
* pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ *
+ * The helpers interrupt whatever vCPU context is loaded on that pCPU, which
+ * generally isn't the vCPU the interrupt file belongs to. To reach the file
+ * they retarget hstatus.VGEIN and select the file's registers through
+ * vsiselect. Both CSRs are live state of the interrupted vCPU (vsiselect is
+ * saved to struct arch_vcpu only on context switch, but the interrupted vCPU
+ * may resume guest execution without one), hence the helpers have to restore
+ * them before returning.
*/

  struct imsic_vsfile_data {
      unsigned int hgei;
      unsigned int nr_eix;
      struct imsic_mrif *mrif;
  };
@@ ... @@ static void cf_check imsic_vsfile_local_clear(void *data)
      /* We can only zero-out if we have a IMSIC VS-file */
      if ( !idata->hgei )
          return;

+ /* See the comment ahead of struct imsic_vsfile_data. */

      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);
@@ ... @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
      csr_clear(CSR_HGEIE, BIT(idata->hgei, UL));

+ /* See the comment ahead of struct imsic_vsfile_data. */

      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);

@@ ... @@ static void cf_check imsic_vsfile_local_update(void *data)
* stack.
*/

Quoted 6 lines

+ /* See the comment ahead of struct imsic_vsfile_data. */

      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);

Does it look clear now?

Not really, I'm afraid. A much shorter comment mentioning that imsic_..._write() alter vsiselect (if I got things right) would imo be both more direct, more clear, and could easily live at all three sites individually.

Quoted 68 lines
Quoted 19 lines
Quoted 6 lines
(quoted diff) +6 -0
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);

Review

Quoted 10 lines
(quoted diff) +10 -0
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif

In asm/imsic.h I see

Quoted 3 lines

#define IMSIC_EIPx_BITS 32

Why is the number of CSR writes different here for RV32 vs RV64?

IMSIC_EIPx_BITS is the unit the AIA spec numbers the eip<k>/eie<k> registers by. On RV32 all of eip0..eip63 exist and are 32 bits wide. On RV64 only the even-numbered ones exist, each being 64 bits wide and covering what eip<k> and eip<k+1> cover on RV32; accessing an odd-numbered one is an illegal instruction. Hence one 64-bit group of interrupt identities takes one register on RV64, but two on RV32.

I will add some small comments:

     for ( i = 0; i < idata->nr_eix; i++ )
     {
         /* On RV64 a 64-bit EIx group is the even-numbered register 
alone. */
         imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
         imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
#ifdef CONFIG_RISCV_32
         /*
          * On RV32 it is split into the even-numbered (low half) and the
          * following odd-numbered (high half) register.
          */
         imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
         imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
#endif
     }
Quoted 3 lines

And
if so, why would you not use the 64-bit write function, allowing the #ifdef to be omitted?

I can introduce something like:

/*
* On RV64 a 64-bit EIx group is the even-numbered register alone, whereas
* on RV32 it is split into the even-numbered (low half) and the following
* odd-numbered (high half) register.
*/
static void imsic_eix_write64(unsigned int ireg, uint64_t val)

{
     imsic_eix_write(ireg, val);
     if ( IS_ENABLED(CONFIG_RISCV_32) )
         imsic_eix_write(ireg + 1, val >> 32);
}

And then:

Quoted 7 lines
     for ( i = 0; i < idata->nr_eix; i++ )
     {
         imsic_eix_write64(IMSIC_EIP0 + i * 2, 0);
         imsic_eix_write64(IMSIC_EIE0 + i * 2, 0);
     }

Would it be better?

Imo yes. That said, when making the original comment, I was (apparently wrongly, as per the stuff further up) assuming these are direct CSR writes.

Jan

#148 lore raw

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

In reply to Oleksii Kurochko
Quoted 18 lines

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

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

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

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

Quoted 6 lines

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

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

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

Quoted 3 lines

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

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

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

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

In reply to Oleksii Kurochko
Quoted 7 lines

emulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().

The mask/match chain is adapted from Linux's KVM RISC-V implementation.

Nit: maybe you could add the Origin: trailer as mentioned in the sending-patches.adoc.

Quoted 284 lines

Nothing calls any of this yet, so tag the functions __maybe_unused to keep the build going; the tags go away once emulate_load() and emulate_store() gain their bodies later.

xen/arch/riscv/emulate.c +21 -0
index ff530ef2df..81a50643a5 100644
@@ -5,6 +5,7 @@
  */
 
 #include <xen/bug.h>
+#include <xen/compiler.h>
 #include <xen/errno.h>
 #include <xen/sched.h>
 #include <xen/types.h>
@@ -13,9 +14,29 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
 
+/*
+ * Determine the trapped load or store instruction which caused a guest MMIO
+ * trap.
+ */
+struct decoded_insn {
+    /* The instruction itself, and its length in bytes. */
+    unsigned long insn;
+    unsigned int insn_len;
+    /* Width of the memory access, in bytes. */
+    unsigned int len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    unsigned int reg;
+    /* The access is a store rather than a load. */
+    bool is_write;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned;
+};
 
 
+
 /*

* The hardware-reported details of a guest page fault, gathered once by
* handle_guest_page_fault() and passed down to the emulation of the faulted

xen/arch/riscv/emulate.c +202 -0
@@ -39,6 +60,71 @@ struct guest_fault {
     paddr_t gpa;
 };
 
+static bool is_load_guest_page_fault(unsigned long scause)
+{
+    return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
+}
 
 
+
+static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
+                                      unsigned int step)
+{
+    regs->sepc += step;
+}
+
+/*
+ * The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a
+ * trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode.
+ *
+ * VSXL is consulted whichever mode the trap came from, as it also gives the
+ * width of vsstatus itself: where VSXL says 32, that register has no UXL field
+ * to consult and VU-mode is 32-bit as well, there being nothing to configure.
+ *
+ * It is needed to decode a trapped instruction: the encodings which exist only
+ * for XLEN=64 must not be recognized for a 32-bit guest. Besides those simply
+ * being reserved there, the compressed ones are ambiguous: C.LD and C.FLW
+ * share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW,
+ * C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
+ *
+ * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
+ * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
+ */
+static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);
+
+    if ( (xl == XLEN_FIELD_64) && !(regs->sstatus & SSTATUS_SPP) )
 
 
+        xl = MASK_EXTR(csr_read(CSR_VSSTATUS), SSTATUS64_UXL);
+
+    switch ( xl )
+    {
+    case XLEN_FIELD_32:
+        return 32;
+
+    case XLEN_FIELD_64:
+        return 64;
+
+    default:
+        /*
+         * The field holds nothing else in practice: XLEN_FIELD_128 would mean
+         * RV128, which no implementation provides, and the only value left is
+         * reserved. ASSERT_UNREACHABLE() being debug-only, a width still has
+         * to be answered in release builds.
+         *
+         * Answer 32, that being the safe way to be wrong: the decoder then
+         * fails to recognize the RV64-only encodings and emulation gives up.
+         * Answering 64 for what may well be a 32-bit guest would instead have
+         * it take C.FLW for C.LD and C.FSW for C.SD (see above), i.e. quietly
+         * emulate an access of the wrong width against the wrong register.
+         */
+        ASSERT_UNREACHABLE();
+        return 32;
+    }
+#endif
+}
+
 /*
  * Is @htinst one of the pseudoinstructions reported for a guest page fault
  * taken on an implicit memory access done for VS-stage address translation?
@@ -87,6 +173,250 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
               (htinst_is_pseudo(gf->htinst) ? 0 : (gf->stval & 3));
 }
 
+/*
+ * Where the value of a decoded instruction's register operand is held.
+ *
+ * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
+ * architectural register-number order; see the comment there.
+ */
+static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
+                                               unsigned int reg)
+{
+    ASSERT(reg < 32);
+
+    return REG_PTR(reg, 0, regs);
+}
 
 
+
+/*
+ * Obtain the instruction which caused a guest MMIO trap, filling in
+ * @di->insn and @di->insn_len. It either comes transformed in htinst, or has
+ * to be fetched from guest memory.
+ *
+ * Returns true if the fetch faulted in turn; the resulting trap has then
+ * already been redirected to the guest and there is nothing further for the
+ * caller to do. Where it returns false, @di has been filled in and emulation
+ * is to continue.
+ */
+static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,
+                                              struct decoded_insn *di)
+{
+    unsigned long htinst = gf->htinst;
+
+    /*
+     * A pseudoinstruction says nothing about the instruction the guest was
+     * executing, and comes with a guest physical address which isn't the one
+     * that instruction accessed. handle_guest_page_fault() deals with such a
+     * fault on its own, so no emulation can ever start for one.
+     */
+    ASSERT(!htinst_is_pseudo(htinst));
+
+    if ( htinst & BIT(0, UL) )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         *
+         * The transformation always yields the 32-bit format, with bits[1:0]
+         * holding a marker instead of the original opcode bits: bit[0] set to
+         * flag the transformation, bit[1] clear if the trapped instruction
+         * was a compressed one. Restoring the opcode bits makes the value the
+         * valid 32-bit encoding decode_ldst_insn() matches against. Its
+         * INSN_MASK_C_* cases exist for the branch below, where a compressed
+         * instruction is read from guest memory as is: a trapped one arrives
+         * here already expanded to its 32-bit equivalent, and the opcode bits
+         * just restored keep it from matching those cases anyway.
+         *
+         * The length then cannot come from the value anymore, only from
+         * bit[1]. And only a 16- or a 32-bit instruction is ever reported
+         * this way: the standard load and store instructions the hardware
+         * transforms are all of one of these two lengths, anything else comes
+         * as the zero special value handled below.
+         */
+        di->insn = htinst | INSN_16BIT_MASK;
+        di->insn_len = (htinst & BIT(1, UL)) ? 4 : 2;
 
 
+    }
+    else
+    {
+        const struct cpu_user_regs *regs = gf->regs;
+        struct trap_info utrap = {};
+
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value. With the pseudoinstructions ruled out
+         * above, only zero is left: the instruction has to be read from
+         * guest memory.
+         */
+
+        di->insn = riscv_read_guest(regs->sepc, true, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * If during getting of trapped instruction a fault happen in
+             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
+             * generated. Such faults during this operation is considered as
+             * bus error.
+             */
+            if ( is_load_guest_page_fault(utrap.scause) )
+                utrap.scause = CAUSE_FETCH_ACCESS;
+
+            utrap.sepc = regs->sepc;
 
 
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        /*
+         * riscv_read_guest() fetches at most two halfwords, so a wider
+         * encoding has been read in part only and cannot be decoded here.
+         *
+         * Report an illegal instruction, which is what the guest would have
+         * got for such an encoding anyway: the ISA defines no instruction
+         * wider than 32 bits.
+         */
 
 
+        if ( !INSN_IS_16BIT(di->insn) && !INSN_IS_32BIT(di->insn) )
+        {
+            utrap.sepc = regs->sepc;
 
 
+            utrap.scause = CAUSE_ILLEGAL_INSTRUCTION;
+            /*
+             * stval is left zero: the spec allows that for an illegal
+             * instruction, and only part of the instruction is in hand.
+             */
 
 
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        di->insn_len = INSN_LEN(di->insn);
 
 
+    }
+
+    return false;
+}
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()).
+ *
+ * @xlen is the effective XLEN of the guest, needed as
+ * the encodings which exist for XLEN=64 only must not be recognized for a
+ * 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.
+ */
+static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
+                                            unsigned int xlen)
+{
+    unsigned long insn = di->insn;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 322

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    /* Register fields of the uncompressed forms ... */
+    unsigned int rd = RV_RD(insn);
+    unsigned int rs2 = RV_RS2(insn);
+    /*
+     * ... and of the compressed ones, where the 3-bit field selects one of
+     * x8..x15, while the stack-pointer-relative forms have a full-width one.
+     */
+    unsigned int rs2s = RVC_RS2S(insn);
+    unsigned int rs2c = RVC_RS2(insn);
+

This naming are confusing because above you described di->reg to be rd for load and rs2 for store but here ...

Quoted 25 lines
xen/arch/riscv/emulate.c +23 -0
+    di->is_write = false;
+    di->is_unsigned = false;
 
 
+    di->reg = rd;
+
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 351

Quoted 10 lines
xen/arch/riscv/emulate.c +6 -0
+        di->is_unsigned = true;
+    }
 
 
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
 
 
+        di->reg = rs2s;

... you assigned rs2s for a load. According to the spec, it should be rd'.

I would suggest something generic to load and store. Maybe rxs with a comment to explain it concerns rs2' for store and rd' for load.

127 lines not shown · raw message

Part of this message is not shown here. View the raw message.

#159 lore raw

Re: [PATCH v2 25/39] xen/riscv: add guest load emulation for trapped MMIO accesses

In reply to Oleksii Kurochko
Quoted 61 lines

Implement emulate_load() on top of the decoding interface introduced by the previous patch: fetch the trapped instruction, decode it, dispatch the access to a registered MMIO handler via do_mmio(), write the result back into the destination register and step over the instruction.

Xen dispatches MMIO synchronously to an in-hypervisor handler, so unlike KVM RISC-V there is no userspace exit/return step and no equivalent of the kvm_io_bus_read() / KVM_EXIT_MMIO / kvm_riscv_vcpu_mmio_return() split; the result is consumed in place.

Sign extension is done here rather than in the handlers: a signed load is normalized by a shift pair, so a handler need only report the value it read.

At the moment vINTC is the only backend registered with the MMIO dispatch, so in practice this only covers vINTC traps. An access which no handler claims currently crashes the domain; injecting an access fault into the guest instead is left for later.

xen/arch/riscv/emulate.c +3 -4
index 81a50643a5..e52f285180 100644
@@ -5,7 +5,6 @@
  */
 
 #include <xen/bug.h>
-#include <xen/compiler.h>
 #include <xen/errno.h>
 #include <xen/sched.h>
 #include <xen/types.h>
@@ -15,6 +14,7 @@
 #include <asm/current.h>
 #include <asm/emulate.h>
 #include <asm/guest_access.h>
+#include <asm/mmio.h>
 #include <asm/processor.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
@@ -65,8 +65,7 @@ static bool is_load_guest_page_fault(unsigned long scause)
     return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
 }
 
-static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
-                                      unsigned int step)
+static void advance_pc(struct cpu_user_regs *regs, unsigned int step)
 {
     regs->sepc += step;
 }
@@ -88,7 +87,7 @@ static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
  * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
  * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
  */
-static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+static unsigned int guest_xlen(const struct cpu_user_regs *regs)
 {
 #ifdef CONFIG_RISCV_32
     return 32;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 183

Quoted 5 lines
xen/arch/riscv/emulate.c +0 -2
@@ -179,8 +178,7 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
  * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
  * architectural register-number order; see the comment there.
  */
-static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
-                                               unsigned int reg)

Could we unified this function with regs_get_gpr()?

Signature · 1 line
Baptiste Le Duc <[email protected]>
#166 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

In reply to Oleksii Kurochko
Quoted 10 lines

Extend the guest page fault handler with store emulation to support MMIO write accesses.

The instruction decode mirrors emulate_load() and, like it, is adapted from Linux's KVM RISC-V implementation. As with the load path, the completion is synchronous through try_handle_mmio() rather than KVM's userspace exit/return split, since Xen's MMIO handlers run in the hypervisor. Faults taken while re-reading the trapped instruction are handled by decode_ldst_insn(), shared with the load path.

Quoted 2 lines

When a guest store instruction faults, the trapped instruction is decoded using HTINST or, if unavailable, fetched via unprivileged access. At the

Nit: commit message restates the HTINST-or-unprivileged-fetch decode mechanism, which is already described in the prep patch introducing decode_ldst_insn()/insn_fetch_faulted(), and isn't repeated in emulate_load()'s commit message. Suggest trimming for symmetry with the load commit, e.g.:

When a guest store instruction faults, the trapped instruction is decoded via decode_ldst_insn(), shared with the load path. At the moment only virtual interrupt controller (vINTC) traps are expected to occur, since it is currently the only backend registered with the MMIO handler dispatch, so in practice the store is emulated via the vINTC backend.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#180 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

In reply to Jan Beulich
Quoted 19 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko

The IMSIC vsfile mapping is performed in continue_new_vcpu(), since the target pCPU must be known at that point. It is therefore possible for imsic_migrate_vcpu() to be called before continue_new_vcpu() has executed, in which case v->arch.last_pcpu is NR_CPUS and there is nothing to migrate.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

This doesn't adequately describe the change made: The BUG_ON() was already there.

Quoted 4 lines
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
 void imsic_migrate_vcpu(struct vcpu *v)
 {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I also agree that ~0 would be better.

Quoted 2 lines

Jan

#194 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

In reply to Jan Beulich
Quoted 10 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

Quoted 4 lines

Hmm. As indicated, I'm learning RISC-V as I'm reviewing patches. This paragraph, if left as is, would make sure I simply can't ack the patch. I just don't understand what is being talked about. I can guess parts, but for example I don't know what "genmsi" is.

I will reword then commit message in the following way:

```
When a vCPU is moved to a different guest interrupt file, MSIs that the
APLIC has already sent towards the old file may still be in flight. They
must land before the old file's state is saved and the switch is done,
otherwise they would be lost.

To wait for them, use the APLIC's genmsi register. Writing it makes the
APLIC itself send an MSI (an "extempore" MSI) with a given interrupt
identity to a given hart. genmsi can only target the hart's supervisor-
level interrupt file, not a guest one, but the AIA spec guarantees that
all MSIs previously sent by the same APLIC to the same hart become
visible at the hart's IMSIC before the extempore MSI does. So once the
extempore MSI has been delivered, no older MSI from this APLIC to the
hart can still be in flight, whichever interrupt file it targets.

The last interrupt identity (nr_ids) is reserved for this purpose.
```
Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/aplic.c +0 -0
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
      spin_unlock_irqrestore(&aplic.lock, flags);
  }
 
Quoted 16 lines

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 222

Quoted 13 lines
xen/arch/riscv/aplic.c +13 -0
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);

Along the lines of a question on an earlier patch: What if this ANDing actually chops off bits?

I will do then the same as I did in aplic_set_irq_affinity() (i mentioned that in the one of the replies connected to this function in this patch series):

    /*
     * sync_id is nr_ids, which imsic_parse_node() limits to IMSIC_MAX_ID,
     * so it always fits into the EIID field.
     */
    BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
    ASSERT(imsic->sync_id <= IMSIC_MAX_ID);

    val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
          imsic->sync_id;

Thanks.

~ Oleksii

Acked-by on v2 35/39
#225 lore raw

Re: [PATCH v2 35/39] xen/riscv: add basic VGEIN management for AIA guests

In reply to Oleksii Kurochko
Quoted 13 lines · Oleksii Kurochko

It was decided to add support for IMSIC from the start instead of having APLIC operate in direct delivery mode, as it requires a trap-and-emulation approach, which is not optimal from a performance standpoint.

AIA provides a hardware-accelerated mechanism for delivering external interrupts to domains via "guest interrupt files" located in IMSIC. A single physical hart can implement multiple such files (up to GEILEN), allowing several virtual harts to receive interrupts directly from hardware.

Introduce per-CPU tracking of guest interrupt file identifiers (VGEIN) for systems implementing AIA specification. Each CPU maintains a bitmap describing which guest interrupt files are currently in use.

Quoted 5 lines

Implement helpers to initialize the bitmap based on the number of available guest interrupt files (GEILEN), assign a VGEIN to a vCPU, and release it when no longer needed.

#228 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Oleksii Kurochko
Quoted 17 lines · Oleksii Kurochko
xen/arch/riscv/aia.c +3 -2
@@ -62,23 +69,25 @@ static int cf_check cpu_callback(struct notifier_block *nfb,
                                  unsigned long action, void *hcpu)
 {
     unsigned int cpu = (unsigned long)hcpu;
-    int rc = 0;
 
     switch ( action )
     {
     case CPU_STARTING:
-        rc = vgein_init();
+    {
+        int rc = vgein_init();
+
         if ( rc )
             printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
                    cpu, rc);
         break;

xen/arch/riscv/aia.c static int cf_check cpu_callback(struct notifier_block *nfb, · line 91

Quoted 10 lines
xen/arch/riscv/aia.c +2 -1
+    }
 
     case CPU_DYING:
         vgein_deinit();
         break;
     }
 
-    return notifier_from_errno(rc);
+    return NOTIFY_DONE;
 }

What is this hunk doing in this patch? Was this meant to be merged into the prior one? But then - why?

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 190

Quoted 11 lines
xen/arch/riscv/aia.c +7 -0
@@ -168,3 +181,36 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
             __func__, v, vgein_id, cpu, vgein->bmp);
 #endif
 }
+
+void hgei_interrupt(void)
+{
+    unsigned long hgei_mask, flags;
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    hgei_mask = csr_read(CSR_HGEIP) & csr_read(CSR_HGEIE);

Misra, aiui, isn't going to like this. You may want to split it up.

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 202

Quoted 12 lines
xen/arch/riscv/aia.c +12 -0
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    for_each_set_bit ( guest_file_id, hgei_mask )
+    {
+        /*
+         * guest_file_id shouldn't be zero, as it will indicate that no
+         * guest external interrupt source is selected for VS-level external
+         * interrupts.
+         */
+        ASSERT(guest_file_id);

While it only affects debug builds, this check still needlessly is done on every loop iteration, when doing it once ahead of the loop would suffice.

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 209

Quoted 6 lines
xen/arch/riscv/aia.c +6 -0
+        if ( vgein->owners[guest_file_id] )
+        {
+#ifdef VGEIN_DEBUG
+            gprintk(XENLOG_DEBUG, "%s: kick ->%pv, hgei_mask(%#lx)\n",
+                    __func__, vgein->owners[guest_file_id], hgei_mask);
+#endif

This can ocur very frequently (when VGEIN_DEBUG is defined). A trace record may be a better alternative.

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 140

Quoted 8 lines
xen/arch/riscv/domain.c +2 -0
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
         v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                             csr_masks.ro_one.hstateen0;
     }
+
+    v->arch.hie = MIP_SGEIP;

Neither part of the rhs identifier has anything to do with the CSR having its default value set here. That's perhaps again a piece of RISC-V I'm missing, but I can't make sense of this.

Quoted 4 lines
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
     write_lock_irqsave(&imsic_state->vsfile_lock, flags);
     imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
     write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

Quoted 8 lines
xen/arch/riscv/imsic.c +5 -1
 void cf_check imsic_ctxt_switch_to(struct vcpu *v)
 {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 10 lines
xen/arch/riscv/imsic.c +9 -0
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }

How can this be a read-lock when you write a CSR? Or else - why is locking here necessary in the firt place?

Jan

#202 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Jan Beulich
Quoted 10 lines · Jan Beulich

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 66

Quoted 7 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +3 -0
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \

Nit: Excess parentheses again.

I will drop them.

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
Quoted 7 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 5 lines
xen/arch/riscv/imsic.c +5 -0
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

Yes, agreed. Both isel and bit fit within unsigned int. I will update them in the next version.

Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 3 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

No, the IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):

- CSR Accesses (imsic_csr_read): Indirect CSR accesses (siselect/sireg or miselect/mireg) operate using standard RISC-V CSR instructions at current XLEN width. Values are read and written directly into architectural GPRs without byte-swapping.

- MMIO Ports: For incoming device MSIs, IMSIC uses fixed memory-mapped offsets: offset 0x000 (seteipnum_le) always expects Little-Endian, while offset 0x004 (seteipnum_be) expects Big-Endian.

- Memory-Resident Interrupt Files (MRIF): For virtualized environments, MRIF structures in memory are strictly defined in Little-Endian byte order regardless of whether the CPU harts operate in Big-Endian or Little-Endian mode.

Quoted 3 lines

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

It signifies that local (on which code is executed now) hart's IMSIC CSRs (isel and ireg in the case of imsic_csr_read()) are touched.

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
Quoted 14 lines

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 12 lines
xen/arch/riscv/imsic.c +12 -0
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

If the parameter isn't used, maybe best to name it "unused"?

Makes sense to me. I will do that in the next version + I will update the type to 'struct imsic_vsfile_data *' as it was suggested for imsic_call_on_cpu() in "Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file".

Quoted 47 lines
Quoted 13 lines
xen/arch/riscv/imsic.c +8 -0
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 919

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */

Isn't the new part of the comment premature? Moving doesn't start until ...

Quoted 21 lines
xen/arch/riscv/imsic.c +17 -0
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 960

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);

... here, as it looks.

At some point I agree but the steps before are preparation of moving and is a part of moving process.

Then probably it make sense to reword the comment to:

/*
* At this point, all interrupt producers are still using the old IMSIC
* VS-file. Allocate and clear the new one before redirecting anything
* to it.
*/

Would it be better?

~ Oleksii

#203 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 26 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
Quoted 7 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 5 lines
xen/arch/riscv/imsic.c +5 -0
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

Yes, agreed. Both isel and bit fit within unsigned int. I will update them in the next version.

Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 3 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

Quoted 7 lines

No, the IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):

- CSR Accesses (imsic_csr_read): Indirect CSR accesses (siselect/sireg or miselect/mireg) operate using standard RISC-V CSR instructions at current XLEN width. Values are read and written directly into architectural GPRs without byte-swapping.

I.e. you need you add endianness conversion.

Quoted 5 lines
Quoted 2 lines

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

It signifies that local (on which code is executed now) hart's IMSIC CSRs (isel and ireg in the case of imsic_csr_read()) are touched.

That's the expected thing for CSR access, though.

Quoted 60 lines
Quoted 46 lines
Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 919

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */

Isn't the new part of the comment premature? Moving doesn't start until ...

Quoted 21 lines
xen/arch/riscv/imsic.c +17 -0
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 960

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);

... here, as it looks.

At some point I agree but the steps before are preparation of moving and is a part of moving process.

Then probably it make sense to reword the comment to:

Quoted 7 lines

/*
* At this point, all interrupt producers are still using the old IMSIC
* VS-file. Allocate and clear the new one before redirecting anything
* to it.
*/

Would it be better?

Imo yes.

Jan

#204 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 7 lines · Jan Beulich
Quoted 6 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
       spin_unlock(&imsic_cfg.lock);
   }
 
Quoted 8 lines
Quoted 8 lines
Quoted 6 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 5 lines
xen/arch/riscv/imsic.c +5 -0
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

Yes, agreed. Both isel and bit fit within unsigned int. I will update them in the next version.

Sorry for not noticing that in first reply but local variable bit should be unsigned long as if id % 64 >= 32 we will have overflow of 'unsigned int'.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 3 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

Quoted 8 lines
Quoted 7 lines

No, the IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):

- CSR Accesses (imsic_csr_read): Indirect CSR accesses (siselect/sireg or miselect/mireg) operate using standard RISC-V CSR instructions at current XLEN width. Values are read and written directly into architectural GPRs without byte-swapping.

I.e. you need you add endianness conversion.

I think I don't really get why. My understanding is that endianness is about an access to memory. We don't have here load/store instruction or an explicit access to memory. We have here only CSR instruction which loads value from IMSIC register to GPR w/ an access to any memory.

Probably I wasn't clear here "he IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):" and it would be better to reply as:

```
endianness (mstatus.SBE/MBE) only governs memory accesses, whereas
eipK is accessed via CSR instructions, which transfer an XLEN-wide
value between the CSR and a GPR with no notion of byte order. The AIA
spec defines eipK in terms of bit significance (bit i of eipK is
identity K*32+i), so BIT(id % BITS_PER_LONG) is correct regardless of
the CPU's data endianness. Endianness only matters for the memory-mapped
seteipnum register, which is why the spec provides both seteipnum_le
and seteipnum_be.
```
Quoted 6 lines
Quoted 5 lines
Quoted 3 lines

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

It signifies that local (on which code is executed now) hart's IMSIC CSRs (isel and ireg in the case of imsic_csr_read()) are touched.

That's the expected thing for CSR access, though.

Fair enough. I'll drop both the "imsic_" prefix and "local" and rename it to irq_is_pending().

~ Oleksii

#213 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

In reply to Jan Beulich
Quoted 15 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko

At the old interrupt file, dump to memory all the eip and eie arrays). After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to deal with that.

Beside this being difficult to parse, it looks like it is inapplicable? As said ...

Quoted 7 lines
Quoted 5 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

... also here?

Agree that paragraph should be dropped, it ins't applicable anymore.

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/imsic.c +0 -0
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
   */
  #define GUEST_IMSIC_MAX_MSIS 255U
 
Quoted 9 lines

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 64

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))

As before - plain 64 please, or it needs to become clear where the uint64_t is actually coming from.

I will use plain 64.

Quoted 6 lines

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 68

Quoted 4 lines
xen/arch/riscv/imsic.c +3 -0
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];

Same here. Yet better may be to use DECLARE_BITMAP()?

It will be better. I'll use:

    DECLARE_BITMAP(eip, 64);
    DECLARE_BITMAP(eie, 64);
Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -85,6 +103,15 @@ do {                            \
      csr_clear(CSR_SIREG, v);    \
  } while (0)
 
Quoted 10 lines

xen/arch/riscv/imsic.c do { \ · line 113

Quoted 8 lines
xen/arch/riscv/imsic.c +8 -0
+#define imsic_vs_csr_swap(c, v)     \
+({                                  \
+    unsigned long r_;               \
+                                    \
+    csr_write(CSR_VSISELECT, (c));  \
+    r_ = csr_swap(CSR_VSIREG, (v)); \
+    r_;                             \
+})

Excess parentheses again. Plus - what use is r_ here?

r_ stands for return value but it should be dropped as it could be done so imsic_vs_csr_swap() just returns a value directly:

#define imsic_vs_csr_swap(c, v)     \
({                                  \
    csr_write(CSR_VSISELECT, c);    \
    csr_swap(CSR_VSIREG, v);        \

})

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -130,6 +157,21 @@ do {                                \
      imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
      imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
 
Quoted 14 lines

xen/arch/riscv/imsic.c do { \ · line 170

Quoted 11 lines
xen/arch/riscv/imsic.c +11 -0
+static unsigned long imsic_eix_swap(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIP0,
+                        imsic_vs_csr_swap, val)
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIE0,
+                        imsic_vs_csr_swap, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }

There still wants to "break" in the default case.

I'll add.

Quoted 10 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1075

Quoted 6 lines
xen/arch/riscv/imsic.c +2 -0
@@ -973,5 +1071,11 @@ void imsic_migrate_vcpu(struct vcpu *v)
       * to the new IMSIC VS-file.
       */
 
+    /* Read and clear register state from old IMSIC VS-file */
+    imsic_vsfile_read_clear(old_vsfile_id, old_vsfile_cpu, nr_hw_eix, &tmrif);

Why is &tmrif being passed into the function, when it's not otherwise used here? The function could itself have a suitable local var.

tmrif isn't a scratch buffer local to the read: it carries the register state of the old interrupt file over to the new one. In this patch it's only filled in, but the next patch ("restore register state in the new IMSIC VS-file") passes the same buffer, via vsfile_data.mrif, to imsic_vsfile_local_update() on the new pCPU. By then the old file has been cleared and released, so the state has to live in the caller. I'll add a sentence to this patch's description saying the dumped state is consumed by the following patch:

The state is dumped into a buffer provided by the caller rather than one
local to imsic_vsfile_read_clear(), as it has to outlive the old interrupt file: once that file is released, the state is still needed to be restored into the new interrupt file.

Just to emphasize that in code I will use vsfile_data.mrif instead of &tmrif:

imsic_vsfile_read_clear(old_vsfile_id, old_vsfile_cpu,
vsfile_data.nr_eix, vsfile_data.mrif);

Thanks.

~ Oleksii

#220 lore raw

Re: [PATCH v2 34/39] xen/riscv: restore register state in the new IMSIC VS-file

In reply to Jan Beulich
Quoted 9 lines · Jan Beulich

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 652

Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +1 -1
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);
      new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);

Please put into final shape upon introduction.

Oh, right, this ...

Quoted 12 lines

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 659

Quoted 11 lines
xen/arch/riscv/imsic.c +3 -3
      csr_write(CSR_HSTATUS, new_hstatus);
 
      /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
       */
Quoted 1 line

Same for this comment perhaps.

... and this should be part of prev. patch.

Quoted 10 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1144

Quoted 8 lines
xen/arch/riscv/imsic.c +2 -1
@@ -1077,5 +1140,12 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Free-up old IMSIC VS-file */
      vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    vsfile_data.mrif = &tmrif;

Ah, here &tmrif is used a 2nd time.

I think it could be dropped and just properly init vsfile_data.mrif during declaration:

    struct imsic_vsfile_data vsfile_data = {
        .nr_eix = imsic_nr_eix(),
        .mrif = &(struct imsic_mrif){ },
    };

and then use vsfile.mrif instead of &tmrif.

Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1150

Quoted 7 lines
xen/arch/riscv/imsic.c +6 -0
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_update, &vsfile_data);
+
+    /* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */
+    vcpu_guest_cpu_user_regs(v)->hstatus &= ~HSTATUS_VGEIN;
+    vcpu_guest_cpu_user_regs(v)->hstatus |=
+            MASK_INSR(new_vsfile_hgei, HSTATUS_VGEIN);
Quoted 4 lines

Nit: Indentation.

Other comments on earlier patches apply here (and possibly elsewhere) as well. Just ftaod.

I will fix them.

Thanks.

~ Oleksii

Acked-by on v2 37/39
#235 lore raw

Re: [PATCH v2 37/39] xen/riscv: map IMSIC interrupt file for vCPUs

In reply to Oleksii Kurochko
Quoted 8 lines · Oleksii Kurochko

A guest running in VS-mode expects its own IMSIC S-file at offset 0 of its guest-physical IMSIC block. Physically, the guest-file (G-file) assigned to this vCPU lives at a hart-relative offset given by guest_file_id (assigned via the vGEIN allocator). Therefore, imsic_map_guest_file() uses stage-2 translation to redirect the guest's fixed per-vCPU GPA page (offset 0) to the specific physical guest-file page.

perhaps with ...

Quoted 50 lines
xen/arch/riscv/imsic.c +43 -1
@@ -537,9 +538,72 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
     read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }
 
+/*
+ * Map the physical IMSIC guest interrupt file (G-file) assigned to vCPU
+ * into the domain's stage-2 guest-physical address space.
+ *
+ * In the machine's physical address space (SPA), each hart's IMSIC
+ * supervisor-level file (S-file) is located at offset 0 of its address block,
+ * followed contiguously by GEILEN guest files at offsets of 1, 2, ..., N pages.
+ *
+ * Because a guest OS running in VS-mode expects its own supervisor-level
+ * interrupt file to be at offset 0 of its guest-physical IMSIC block, the
+ * hypervisor must use stage-2 address translation to map the vCPU's
+ * guest-physical "supervisor" page (GPA offset 0) to the specific
+ * physical guest file page (SPA offset guest_file_id) on the physical hart.
+ *
+ * A vCPU runs on the pCPU the scheduler picked for it (v->processor), and
+ * the guest file it is given (guest_file_id, from the vGEIN allocator)
+ * belongs to that very pCPU's IMSIC. A guest_file_id of 0 indicates that no
+ * hardware guest file is selected (matching the architectural behavior where
+ * vGEIN = 0 in the hstatus CSR selects no guest external interrupt source),
+ * requiring the VS-file to be emulated in software.
+ *
+ * Consequently the mapping installed here is only valid as long as the vCPU
+ * stays on that pCPU. When it migrates, a VS-file is acquired on the new
+ * pCPU and mapped at the very same GFN, so the stale mapping needs no
+ * explicit tear-down: it is simply replaced.
+ *
+ * The base guest-physical address advertised to the guest in the device
+ * tree matches offset 0 of the vCPU's virtual IMSIC block. Stage-2
+ * translation ensures that guest supervisor accesses to this page are
+ * transparently routed to the real hardware VS-file granted to it on
+ * the pCPU it currently runs on.
+ */
 int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
 {
-    return -EOPNOTSUPP;
+    struct domain *d = v->domain;
+    unsigned int cpu = v->processor;
+    paddr_t gaddr = GUEST_IMSIC_S_BASE + (IMSIC_MMIO_PAGE_SZ * v->vcpu_id);
+    paddr_t paddr, guest_offset;
+    int res;
+
+    /* Nothing to map in the case of sw interrupt file. */
+    if ( !vsfile_id )
+        return 0;
+
+    guest_offset = vsfile_id * IMSIC_MMIO_PAGE_SZ;

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_to(struct vcpu *v) · line 595

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+
+    paddr = imsic_cfg.msi[cpu].base_addr + imsic_cfg.msi[cpu].offset +
+            guest_offset;
+
+#ifdef IMSIC_DEBUG
+    printk(XENLOG_DEBUG
+           "%s: %pv: ga(%#"PRIpaddr") -> pa(%#"PRIpaddr"), cpu(%u), "
+           "guest_file_id(%u) base_addr(%#"PRIpaddr") offset(%#lx)\n",
+           __func__, v, gaddr, paddr, cpu, vsfile_id,
+           imsic_cfg.msi[cpu].base_addr, imsic_cfg.msi[cpu].offset);

... this also converted to dprintk(), or at least using XENLOG_G_DEBUG.

Jan

#239 lore raw

Re: [PATCH v2 38/39] xen/riscv: implement continue_new_vcpu()

In reply to Oleksii Kurochko
Quoted 7 lines · Oleksii Kurochko

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, restore hstatus and enter the guest through the new return_to_new_vcpu() path in entry.S, which loads sepc, passes the hart id in a0 and the DTB address in a1 as expected by the RISC-V boot protocol, sets sstatus.SPP and executes sret.

Is this a requirement for all CPUs, or just for the boot one? (I can't quite see why secondary processors would need passing a DTB address.)

Quoted 6 lines

Interrupts have to stay disabled across the restore. The trap entry logic implicitly clears hstatus.SPV, so an interrupt taken between the write of hstatus and sret would make sret return to HS-mode instead of VS-mode, and restoring SPV afterwards is non-trivial. Instead interrupts are simply kept off and sstatus.SPIE is set, so that SIE is restored from SPIE once sret has been executed.

As written this reads as if the guest would be responsible for doing this. Isn't it rather SRET itself which does this?

Quoted 2 lines

Also, it follows what hardware will do
with real CPU which is also started with interrupts disabled.

Further up, aiui, you talk about the host's interrupt state. How vCPU-s are started, however, is virtual interrupt state. Mixing both isn't very helpful.

Quoted 4 lines

Introduce get_cpu_info() and reset_stack_and_jump() in asm/current.h, needed by the above. get_cpu_info() is a macro rather than a static inline because asm/current.h is pulled in by <xen/percpu.h> before this_cpu() is defined and before <xen/sched.h> completes struct vcpu.

This is odd, given the similarity to Arm. They get away without using "current", and hence without using this_cpu().

Quoted 6 lines
xen/arch/riscv/domain.c +0 -0
@@ -8,10 +8,13 @@
 #include <xen/smp.h>
 #include <xen/vmap.h>
 

xen/arch/riscv/domain.c line 20

Quoted 10 lines
xen/arch/riscv/domain.c +3 -0
+#include <asm/aia.h>
+#include <asm/aplic.h>
 #include <asm/bitops.h>
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/current.h>
+#include <asm/imsic.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>

What makes these additions necessary here?

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 148

Quoted 7 lines
xen/arch/riscv/domain.c +3 -0
@@ -140,9 +143,43 @@ static void vcpu_csr_init(struct vcpu *v)
     v->arch.hie = MIP_SGEIP;
 }
 
+static void schedule_tail(struct vcpu *prev);
+static void noreturn idle_loop(void);
+void noreturn return_to_new_vcpu(void);

For this last one: asmlinkage?

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 156

Quoted 8 lines
xen/arch/riscv/domain.c +5 -1
 static void continue_new_vcpu(struct vcpu *prev)
 {
-    BUG_ON("unimplemented\n");
+    schedule_tail(prev);
+
+    if ( is_idle_vcpu(current) )
+        reset_stack_and_jump(idle_loop);
+    else

This is the kind of "else" which I consider particularly confusing: It suggests that the if() body can actually be exited at the bottom, when (by the name "reset_stack_and_jump") it hopefully cannot.

Quoted 15 lines
xen/arch/riscv/domain.c +15 -0
+    {
+        /*
+         * During a context switch to a new vCPU, interrupts must be disabled
+         * to guarantee that the vCPU's CSR state can be safely restored into
+         * the hart without being clobbered by an interrupt trap.
+         *
+         * For example, when return_to_new_vcpu() finishes, it executes sret.
+         * At that point, the hart checks hstatus.SPV=1 and sstatus.SPP=1 in
+         * order to return from HS-mode into VS-mode. If an interrupt were to
+         * arrive before sret, the trap entry logic would implicitly clear
+         * hstatus.SPV to 0. Correctly restoring it afterwards is non-trivial,
+         * and if left as 0, sret would incorrectly return to HS-mode instead
+         * of VS-mode.
+         *
+         * To avoid this, interrupts are kept disabled during the restore.

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 181

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+         * Additionally, setting sstatus.SPIE=1 ensures that after sret is
+         * executed (as sstatus.SIE will be loaded from SPIE), HS-mode will
+         * continue to receive interrupts normally.
+         */
+        local_irq_disable();
+        csr_set(CSR_SSTATUS, SSTATUS_SPIE);
+
+        csr_write(CSR_HSTATUS, vcpu_guest_cpu_user_regs(current)->hstatus);
+
+        reset_stack_and_jump(return_to_new_vcpu);

What are the criteria by which you split CSR accesses between doing some here and some in return_to_new_vcpu()? In particular you set sstatus.SPIE here but sstatus.SPP there, when both could - I think - be done with a single CSR access.

xen/arch/riscv/entry.S FUNC(__context_switch) · line 150

Quoted 11 lines
xen/arch/riscv/entry.S +5 -0
@@ -143,3 +143,26 @@ FUNC(__context_switch)
 
         ret
 END(__context_switch)
+
+/* t0 is used as a temporary reg and is clobbered to oblivion */
+FUNC(return_to_new_vcpu)
+        /* Swap tp with sscratch */
+        csrrw   tp, CSR_SSCRATCH, tp

What is this about? I'm not aware of any counterpart code, yet all on its own this I can't see it being overly useful.

xen/arch/riscv/entry.S FUNC(__context_switch) · line 160

Quoted 9 lines
xen/arch/riscv/entry.S +9 -0
+        /* Set vCPU registers */
+        REG_L   t0, CPU_USER_REGS_SEPC(sp)
+        csrw    sepc, t0
+
+        /* Hartid goes to a0 */
+        REG_L   a0, CPU_USER_REGS_A0(sp)
+
+        /* DTB goes to a1 */
+        REG_L   a1, CPU_USER_REGS_A1(sp)

The fields loaded are merely .a0 and .a1 of the register struct. There's nothing here making sure (all on its own) that what is loaded is what is said by the comments. If e.g. the first comment was /* .a0 holds the hart id */ or some such to remind readers what is being loaded without giving the impression that the correct value is _established_ here, that may be better.

xen/arch/riscv/entry.S FUNC(__context_switch) · line 168

Quoted 7 lines
xen/arch/riscv/entry.S +7 -0
+        /* Set guest mode to supervisor */
+        li      t0, SSTATUS_SPP
+        csrs    CSR_SSTATUS, t0
+
+        /* Enter guest */
+        sret
+END(return_to_new_vcpu)

Aiui SRET does not switch stacks. Shouldn't you therefore clear sp here? And perhaps also other GPRs, not the least ra? Exposing hypervisor register values to guests is, well, a bit of a problem.

Jan

#246 lore raw

Re: [PATCH v2 39/39] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu

In reply to Oleksii Kurochko
Quoted 11 lines · Oleksii Kurochko

Introduce imsic_vsfile_attach() to initialize the AIA-related state needed for a vCPU to have a working guest interrupt file.

A guest (VS) interrupt file must be mapped to one of a pCPU's hardware interrupt files (if they exist), so the pCPU a vCPU will actually run on needs to be known first. arch_vcpu_create() is therefore not a suitable place to call vcpu_aia_init(), since the pCPU assigned to a vCPU can still change before it is first scheduled. To avoid reassigning the VS interrupt file id and remapping it to a different pCPU's hardware interrupt file, imsic_vsfile_attach() is called from a later point in the scheduling path (e.g. continue_new_vcpu()).

Hmm, why does first-time handling need to be this different from the handling of a vCPU moving across pCPU-s? The sole difference should be "no state to load" vs "load state that was saved on the old pCPU".

Jan

#229 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Jan Beulich
Quoted 25 lines · Jan Beulich
Quoted 24 lines · Oleksii Kurochko
xen/arch/riscv/aia.c +4 -2
@@ -62,23 +69,25 @@ static int cf_check cpu_callback(struct notifier_block *nfb,
                                   unsigned long action, void *hcpu)
  {
      unsigned int cpu = (unsigned long)hcpu;
-    int rc = 0;
 
      switch ( action )
      {
      case CPU_STARTING:
-        rc = vgein_init();
+    {
+        int rc = vgein_init();
+
          if ( rc )
              printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
                     cpu, rc);
          break;
+    }
 
      case CPU_DYING:
          vgein_deinit();
          break;
      }
 
Quoted 6 lines

xen/arch/riscv/aia.c static int cf_check cpu_callback(struct notifier_block *nfb, · line 91

Quoted 3 lines
xen/arch/riscv/aia.c +1 -1
-    return notifier_from_errno(rc);
+    return NOTIFY_DONE;
  }

What is this hunk doing in this patch? Was this meant to be merged into the prior one?

Yes, it was meant to be a part of prev. patch.

Quoted 1 line

But then - why?

I had a case with what rc returns but looking at my downstream branches I don't face this case anymore so this hunk should be just dropped.

Quoted 14 lines

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 190

Quoted 12 lines
xen/arch/riscv/aia.c +7 -0
@@ -168,3 +181,36 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
              __func__, v, vgein_id, cpu, vgein->bmp);
  #endif
  }
+
+void hgei_interrupt(void)
+{
+    unsigned long hgei_mask, flags;
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    hgei_mask = csr_read(CSR_HGEIP) & csr_read(CSR_HGEIE);

Misra, aiui, isn't going to like this. You may want to split it up.

I will write in the following way then:

    hgei_mask = csr_read(CSR_HGEIP);
    hgei_mask &= csr_read(CSR_HGEIE);
Quoted 17 lines

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 202

Quoted 13 lines
xen/arch/riscv/aia.c +12 -0
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    for_each_set_bit ( guest_file_id, hgei_mask )
+    {
+        /*
+         * guest_file_id shouldn't be zero, as it will indicate that no
+         * guest external interrupt source is selected for VS-level external
+         * interrupts.
+         */
+        ASSERT(guest_file_id);

While it only affects debug builds, this check still needlessly is done on every loop iteration, when doing it once ahead of the loop would suffice.

Good point. I will do in the following way then before the loop:

    /*
     * Bit 0 of HGEIP/HGEIE is read-only zero: guest interrupt file ID 0
     * means that no guest external interrupt source is selected.
     */
    ASSERT(!(hgei_mask & 1));
Quoted 10 lines

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 209

Quoted 7 lines
xen/arch/riscv/aia.c +6 -0
+        if ( vgein->owners[guest_file_id] )
+        {
+#ifdef VGEIN_DEBUG
+            gprintk(XENLOG_DEBUG, "%s: kick ->%pv, hgei_mask(%#lx)\n",
+                    __func__, vgein->owners[guest_file_id], hgei_mask);
+#endif

This can ocur very frequently (when VGEIN_DEBUG is defined). A trace record may be a better alternative.

Agree, it would be nice but tracing isn't ready for RISC-V.

Considering that we haven't had any issue with hgei interrupt for a long time I will just drop gprintk() for now and use trace record when functionality will be ready.

Quoted 13 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 140

Quoted 9 lines
xen/arch/riscv/domain.c +2 -0
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
          v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                              csr_masks.ro_one.hstateen0;
      }
+
+    v->arch.hie = MIP_SGEIP;

Neither part of the rhs identifier has anything to do with the CSR having its default value set here. That's perhaps again a piece of RISC-V I'm missing, but I can't make sense of this.

All interrupt pending/enable CSRs share one bit layout (bit N corresponds to interrupt cause N), which is why MIP_SGEIP happened to be numerically right. I'll use BIT(IRQ_S_GEXT, UL) instead and add a comment: hie.SGEIE is what allows the SGEI raised through hgeie to be taken by Xen at all, while hie's VS-level bits alias the guest's vsie and are left cleared. I will apply the following change:

- v->arch.hie = MIP_SGEIP;
+ /*

+     * Enable SGEIs, so that a guest interrupt file marked in HGEIE while
+     * the vCPU is descheduled can raise an interrupt to Xen.
+     *
+     * The VS-level bits of hie alias the guest's vsie, which is saved and
+     * restored separately, so they are left clear here.
+     */

+ v->arch.hie = BIT(IRQ_S_GEXT, UL);

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 
Quoted 14 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
      write_lock_irqsave(&imsic_state->vsfile_lock, flags);
      imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
      write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

There's no window: a guest interrupt file's hgeip bit is level-sensitive, i.e. it reflects whether the file currently has a pending-and-enabled interrupt (the MSI itself stays latched in the file's eip[] until the guest claims it), and hip.SGEIP is simply (hgeip & hgeie) != 0. So an MSI arriving after the vCPU stopped running but before hgeie is set raises an SGEI as soon as the bit is set, taken once interrupts are re-enabled. I'll extend the comment to say so:

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through
HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the
vCPU up.
*
* HGEIP is level-sensitive, reflecting the VS-file's current state, so
* an interrupt that became pending before this point raises an SGEI as
* soon as the bit is set in HGEIE; nothing is lost in between. */

Does it make sense?

Quoted 13 lines
Quoted 13 lines
xen/arch/riscv/imsic.c +9 -1
  void cf_check imsic_ctxt_switch_to(struct vcpu *v)
  {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 6 lines
xen/arch/riscv/imsic.c +5 -0
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

How can this be a read-lock when you write a CSR?

But here is a protection of ->guest_file_id not of write to a CSR and we want to not have a change of ->guest_file_id during an update of CSR_HGEIE.

Quoted 2 lines

Or else - why is locking
here necessary in the firt place?

Strictly speaking no locking is needed with the current implementation: HGEIE is local to this pCPU, and guest_file_id can't change concurrently. It's updated either by this very pCPU ahead of switching the vCPU in (imsic_migrate_vcpu() called from schedule(), imsic_vsfile_attach() right after), or while the vCPU can't be scheduled: sched_unit_migrate_finish() defers to unit_context_saved() while the unit is running, and sched_move_domain() pauses the domain.

(and the similar are true for imsic_ctxt_switch_from())

But IMO we should keep around ->vsfile_lock to not miss the case where some case will update ->guest_file_id in parallel with imsic_ctxt_switch_to().

Does it make to continue to have read_lock_irqsave(...->vsfile_lock, ...) here just for potential future cases?

Thanks.

~ Oleksii

#236 lore raw

Re: [PATCH v2 37/39] xen/riscv: map IMSIC interrupt file for vCPUs

In reply to Jan Beulich
Quoted 11 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko

A guest running in VS-mode expects its own IMSIC S-file at offset 0 of its guest-physical IMSIC block. Physically, the guest-file (G-file) assigned to this vCPU lives at a hart-relative offset given by guest_file_id (assigned via the vGEIN allocator). Therefore, imsic_map_guest_file() uses stage-2 translation to redirect the guest's fixed per-vCPU GPA page (offset 0) to the specific physical guest-file page.

Thanks.

Quoted 56 lines

perhaps with ...

Quoted 54 lines
xen/arch/riscv/imsic.c +47 -1
@@ -537,9 +538,72 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
      read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }
 
+/*
+ * Map the physical IMSIC guest interrupt file (G-file) assigned to vCPU
+ * into the domain's stage-2 guest-physical address space.
+ *
+ * In the machine's physical address space (SPA), each hart's IMSIC
+ * supervisor-level file (S-file) is located at offset 0 of its address block,
+ * followed contiguously by GEILEN guest files at offsets of 1, 2, ..., N pages.
+ *
+ * Because a guest OS running in VS-mode expects its own supervisor-level
+ * interrupt file to be at offset 0 of its guest-physical IMSIC block, the
+ * hypervisor must use stage-2 address translation to map the vCPU's
+ * guest-physical "supervisor" page (GPA offset 0) to the specific
+ * physical guest file page (SPA offset guest_file_id) on the physical hart.
+ *
+ * A vCPU runs on the pCPU the scheduler picked for it (v->processor), and
+ * the guest file it is given (guest_file_id, from the vGEIN allocator)
+ * belongs to that very pCPU's IMSIC. A guest_file_id of 0 indicates that no
+ * hardware guest file is selected (matching the architectural behavior where
+ * vGEIN = 0 in the hstatus CSR selects no guest external interrupt source),
+ * requiring the VS-file to be emulated in software.
+ *
+ * Consequently the mapping installed here is only valid as long as the vCPU
+ * stays on that pCPU. When it migrates, a VS-file is acquired on the new
+ * pCPU and mapped at the very same GFN, so the stale mapping needs no
+ * explicit tear-down: it is simply replaced.
+ *
+ * The base guest-physical address advertised to the guest in the device
+ * tree matches offset 0 of the vCPU's virtual IMSIC block. Stage-2
+ * translation ensures that guest supervisor accesses to this page are
+ * transparently routed to the real hardware VS-file granted to it on
+ * the pCPU it currently runs on.
+ */
  int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
  {
-    return -EOPNOTSUPP;
+    struct domain *d = v->domain;
+    unsigned int cpu = v->processor;
+    paddr_t gaddr = GUEST_IMSIC_S_BASE + (IMSIC_MMIO_PAGE_SZ * v->vcpu_id);
+    paddr_t paddr, guest_offset;
+    int res;
+
+    /* Nothing to map in the case of sw interrupt file. */
+    if ( !vsfile_id )
+        return 0;
+
+    guest_offset = vsfile_id * IMSIC_MMIO_PAGE_SZ;
+
+    paddr = imsic_cfg.msi[cpu].base_addr + imsic_cfg.msi[cpu].offset +
+            guest_offset;
+
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_to(struct vcpu *v) · line 595

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+#ifdef IMSIC_DEBUG
+    printk(XENLOG_DEBUG
+           "%s: %pv: ga(%#"PRIpaddr") -> pa(%#"PRIpaddr"), cpu(%u), "
+           "guest_file_id(%u) base_addr(%#"PRIpaddr") offset(%#lx)\n",
+           __func__, v, gaddr, paddr, cpu, vsfile_id,
+           imsic_cfg.msi[cpu].base_addr, imsic_cfg.msi[cpu].offset);

... this also converted to dprintk(), or at least using XENLOG_G_DEBUG.

I will convert to dprintk().

~ Oleksii

#230 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Oleksii Kurochko
Quoted 22 lines · Oleksii Kurochko
Quoted 13 lines · Jan Beulich

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 140

Quoted 8 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +2 -0
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
          v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                              csr_masks.ro_one.hstateen0;
      }
+
+    v->arch.hie = MIP_SGEIP;

Neither part of the rhs identifier has anything to do with the CSR having its default value set here. That's perhaps again a piece of RISC-V I'm missing, but I can't make sense of this.

All interrupt pending/enable CSRs share one bit layout (bit N corresponds to interrupt cause N), which is why MIP_SGEIP happened to be numerically right. I'll use BIT(IRQ_S_GEXT, UL) instead and add a
comment: hie.SGEIE is what allows the SGEI raised through hgeie to be taken by Xen at all, while hie's VS-level bits alias the guest's vsie and are left cleared. I will apply the following change:

Review

Quoted 9 lines
(quoted diff) +8 -1
-    v->arch.hie = MIP_SGEIP;
+    /*
+     * Enable SGEIs, so that a guest interrupt file marked in HGEIE while
+     * the vCPU is descheduled can raise an interrupt to Xen.
+     *
+     * The VS-level bits of hie alias the guest's vsie, which is saved and
+     * restored separately, so they are left clear here.
+     */
+    v->arch.hie = BIT(IRQ_S_GEXT, UL);

It's somewhat better this way, yes. And as said - in not looking great to me (doc-wise) is likely an issue of mine, not of yours.

Quoted 39 lines
Quoted 4 lines
Quoted 4 lines
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 
Quoted 14 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
      write_lock_irqsave(&imsic_state->vsfile_lock, flags);
      imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
      write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

There's no window: a guest interrupt file's hgeip bit is level-sensitive, i.e. it reflects whether the file currently has a pending-and-enabled interrupt (the MSI itself stays latched in the file's eip[] until the guest claims it), and hip.SGEIP is simply (hgeip & hgeie) != 0. So an MSI arriving after the vCPU stopped running but before hgeie is set raises an SGEI as soon as the bit is set, taken once interrupts are re-enabled. I'll extend the comment to say so:

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through
HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the
vCPU up.
*
* HGEIP is level-sensitive, reflecting the VS-file's current state, so
* an interrupt that became pending before this point raises an SGEI as
* soon as the bit is set in HGEIE; nothing is lost in between. */

Quoted 1 line

Does it make sense?

I think I get what you're trying to explain, but the term "level-sensitive" here doesn't really help. I'm unconvinced you actually mean that, as it requires pins / physical signals, which don't exist with MSI. It feels like you may mean "sticky" instead.

Quoted 35 lines
Quoted 12 lines
Quoted 12 lines
xen/arch/riscv/imsic.c +9 -1
  void cf_check imsic_ctxt_switch_to(struct vcpu *v)
  {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 6 lines
xen/arch/riscv/imsic.c +5 -0
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

How can this be a read-lock when you write a CSR?

But here is a protection of ->guest_file_id not of write to a CSR and we want to not have a change of ->guest_file_id during an update of CSR_HGEIE.

Quoted 2 lines

Or else - why is locking
here necessary in the firt place?

Strictly speaking no locking is needed with the current implementation:
HGEIE is local to this pCPU, and guest_file_id can't change concurrently. It's updated either by this very pCPU ahead of switching the vCPU in (imsic_migrate_vcpu() called from schedule(), imsic_vsfile_attach() right after), or while the vCPU can't be
scheduled: sched_unit_migrate_finish() defers to unit_context_saved() while the unit is running, and sched_move_domain() pauses the domain.

Quoted 8 lines

(and the similar are true for imsic_ctxt_switch_from())

But IMO we should keep around ->vsfile_lock to not miss the case where some case will update ->guest_file_id in parallel with imsic_ctxt_switch_to().

Does it make to continue to have read_lock_irqsave(...->vsfile_lock, ...) here just for potential future cases?

You get to judge. If the lock typically is uncontended, keeping things as-is may indeed be fine. Introducing a bottleneck "just for potential future cases" otoh wouldn't look overly nice to me.

Jan

#188 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 163 lines · Oleksii Kurochko

Implement first steps of migration a vCPU to a different guest interrupt file procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).

The following steps will be introduced in follow-up patches.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_assign() will be introduced later in a separate patch, for not it is only stub.

---
Changes in v2:
- New patch.
---

---
  xen/arch/riscv/aia.c             |   9 ++
  xen/arch/riscv/imsic.c           | 159 +++++++++++++++++++++++++++++++
  xen/arch/riscv/include/asm/aia.h |   4 +
  xen/include/xen/config.h         |   1 +
  4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
index e31c9c2d24b6..75c82bcfa1b3 100644
@@ -1,8 +1,10 @@
  /* SPDX-License-Identifier: GPL-2.0-only */
 
+#include <xen/bug.h>
  #include <xen/errno.h>
  #include <xen/init.h>
  #include <xen/sections.h>
+#include <xen/sched.h>
  #include <xen/types.h>
 
  #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void)
 
      _aia_usable = true;
  }
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    BUG_ON("unimplemented\n");
+
+    return 0;
+}
xen/arch/riscv/imsic.c +87 -0
index ad7fbe708bfd..516f0105352a 100644
@@ -26,6 +26,7 @@
  #include <xen/spinlock.h>
  #include <xen/xvmalloc.h>
 
+#include <asm/aia.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -77,6 +78,64 @@ do {                            \
      csr_clear(CSR_SIREG, v);    \
  } while (0)
 
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are forwarded to F
+ * via __VA_ARGS__.
+ *
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)    \
+    imsic_switchcase_2(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_2(F, ireg + 2, ##__VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)    \
+    imsic_switchcase_4(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_4(F, ireg + 4, ##__VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)   \
+    imsic_switchcase_8(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_8(F, ireg + 8, ##__VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)   \
+    imsic_switchcase_16(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_16(F, ireg + 16, ##__VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)   \
+    imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+
  unsigned int vcpu_guest_file_id(const struct vcpu *v)
  {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
      return 0;
  }
 
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 488

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

Quoted 36 lines
xen/arch/riscv/imsic.c +32 -0
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;
+
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif
+    }
+
+    csr_write(CSR_HSTATUS, old_hstatus);
+    csr_write(CSR_VSISELECT, old_vsiselect);
+}
+
  void cf_check vcpu_imsic_deinit(struct vcpu *v)
  {
      XVFREE(v->arch.vimsic_state);

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 824

Quoted 7 lines
xen/arch/riscv/imsic.c +4 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
  void imsic_migrate_vcpu(struct vcpu *v)
  {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

This value appears to remain constant after initialization, since it depends directly on the hw, so it is not necessary to calculate it each time.

Quoted 64 lines
xen/arch/riscv/imsic.c +26 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = nr_hw_eix,
+    };
+
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
       * invoke this before the vCPU has ever run (see the migrated branch in
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;
+
+    new_vsfile_hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;
+
+    /* Zero-out new IMSIC VS-file */
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
+
      BUG_ON("unimplemented");
  }
xen/arch/riscv/include/asm/aia.h +4 -0
index aaa4bf91fc75..53a1efb042f8 100644
@@ -3,8 +3,12 @@
  #ifndef RISCV_AIA_H
  #define RISCV_AIA_H
 
+struct vcpu;
+
  bool aia_usable(void);
 
  void aia_init(void);
 
+unsigned int vgein_assign(struct vcpu *v);
+
  #endif /* RISCV_AIA_H */
xen/include/xen/config.h +1 -0
index dddc8e1920fe..0e29976e8203 100644
@@ -100,6 +100,7 @@
  #define BITS_PER_INT    (BITS_PER_BYTE * __SIZEOF_INT__)
  #define BITS_PER_LONG   (BITS_PER_BYTE * BYTES_PER_LONG)
  #define BITS_PER_LLONG  (BITS_PER_BYTE * __SIZEOF_LONG_LONG__)
+#define BITS_PER_TYPE(type) (sizeof(type) * BITS_PER_BYTE)
 
  /* It is assumed that sizeof(void *) == __alignof(void *) */
  #define POINTER_ALIGN   __SIZEOF_POINTER__
#189 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

Quoted 37 lines · Baptiste Le Duc
Quoted 36 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +32 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
      return 0;
  }
 
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
Quoted 8 lines

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 488

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

No, the function pointer is passed to ...

Quoted 17 lines
Quoted 17 lines
xen/arch/riscv/imsic.c +13 -0
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;
+
+    new_vsfile_hgei = vgein_assign(v);
Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 859

Quoted 8 lines
xen/arch/riscv/imsic.c +8 -0
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;
+
+    /* Zero-out new IMSIC VS-file */
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);

... imsic_call_on_cpu() here, which in turn passes it to on_selected_cpus().

Jan

#240 lore raw

Re: [PATCH v2 38/39] xen/riscv: implement continue_new_vcpu()

In reply to Jan Beulich
Quoted 11 lines · Jan Beulich
Quoted 7 lines · Oleksii Kurochko

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, restore hstatus and enter the guest through the new return_to_new_vcpu() path in entry.S, which loads sepc, passes the hart id in a0 and the DTB address in a1 as expected by the RISC-V boot protocol, sets sstatus.SPP and executes sret.

Is this a requirement for all CPUs, or just for the boot one? (I can't quite see why secondary processors would need passing a DTB address.)

It is requirement for boot one. For secondary processors it is HSM boot data which is passed to sbi_hsm_hart_start() and then intercpeted by Xen.

At the moment of writing of this commit message we have only boot CPU and so only DTB could be passed.

I can update the commit message and the comment in return_to_new_vcpu() to tell that it could be DTB address for boot cpu and/or for secondary CPUs HSM boot data or it will be better to add info about HSM boot data during and an introduction of secondary CPUs support?

Quoted 10 lines
Quoted 7 lines

Interrupts have to stay disabled across the restore. The trap entry logic implicitly clears hstatus.SPV, so an interrupt taken between the write of hstatus and sret would make sret return to HS-mode instead of VS-mode, and restoring SPV afterwards is non-trivial. Instead interrupts are simply kept off and sstatus.SPIE is set, so that SIE is restored from SPIE once sret has been executed.

As written this reads as if the guest would be responsible for doing this. Isn't it rather SRET itself which does this?

IIUC to which part you refer then yes, it is SRET itself which does this. So some re-wording should be done ...

Quoted 7 lines
Quoted 3 lines

Also, it follows what hardware will do
with real CPU which is also started with interrupts disabled.

Further up, aiui, you talk about the host's interrupt state. How vCPU-s are started, however, is virtual interrupt state. Mixing both isn't very helpful.

...:

Interrupts have to stay disabled across the restore. The trap entry
logic implicitly clears hstatus.SPV, so an interrupt taken between the
write of hstatus and sret would make sret return to HS-mode instead of
VS-mode, and restoring SPV afterwards is non-trivial. Hence interrupts
are kept disabled, and sstatus.SPIE is set so that sret itself re-enables them (SIE := SPIE) as part of entering the guest.

Then it will be also need to update the comment inside continue_new_vcpu() to:

-         * To avoid this, interrupts are kept disabled during the restore.
-         * Additionally, setting sstatus.SPIE=1 ensures that after sret is
-         * executed (as sstatus.SIE will be loaded from SPIE), HS-mode will
-         * continue to receive interrupts normally.
+         * To avoid this, interrupts are kept disabled during the restore,
+         * and sstatus.SPIE is set so that sret itself re-enables them
+         * (SIE := SPIE) as part of entering the guest.
          */

Would it be the wording okay for you now?

Quoted 8 lines
Quoted 5 lines

Introduce get_cpu_info() and reset_stack_and_jump() in asm/current.h, needed by the above. get_cpu_info() is a macro rather than a static inline because asm/current.h is pulled in by <xen/percpu.h> before this_cpu() is defined and before <xen/sched.h> completes struct vcpu.

This is odd, given the similarity to Arm. They get away without using "current", and hence without using this_cpu().

Arm calculates struct cpu_info * based on sp register + STACK_SIZE:

static inline struct cpu_info *get_cpu_info(void)
{

#ifdef __clang__
    unsigned long sp;

    asm ("mov %0, sp" : "=r" (sp));
#else
    register unsigned long sp asm ("sp");

#endif

    return (struct cpu_info *)((sp & ~(STACK_SIZE - 1)) +
                               STACK_SIZE - sizeof(struct cpu_info));
}

what is equal to current->arch.cpu_info as I can see based on how both arch-es are initializing v->arch.cpu_info what is used in RISC-V.

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/domain.c +0 -0
@@ -8,10 +8,13 @@
  #include <xen/smp.h>
  #include <xen/vmap.h>
 
Quoted 12 lines

xen/arch/riscv/domain.c line 20

Quoted 10 lines
xen/arch/riscv/domain.c +3 -0
+#include <asm/aia.h>
+#include <asm/aplic.h>
  #include <asm/bitops.h>
  #include <asm/cpufeature.h>
  #include <asm/csr.h>
  #include <asm/current.h>
+#include <asm/imsic.h>
  #include <asm/intc.h>
  #include <asm/mmio.h>
  #include <asm/riscv_encoding.h>

What makes these additions necessary here?

None, they are leftovers from an earlier version of this patch. I'll drop them; <asm/imsic.h> will be added by the patch which starts using imsic_vsfile_attach().

Quoted 10 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 148

Quoted 8 lines
xen/arch/riscv/domain.c +3 -0
@@ -140,9 +143,43 @@ static void vcpu_csr_init(struct vcpu *v)
      v->arch.hie = MIP_SGEIP;
  }
 
+static void schedule_tail(struct vcpu *prev);
+static void noreturn idle_loop(void);
+void noreturn return_to_new_vcpu(void);

For this last one: asmlinkage?

Will add.

Quoted 10 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 156

Quoted 9 lines
xen/arch/riscv/domain.c +5 -1
  static void continue_new_vcpu(struct vcpu *prev)
  {
-    BUG_ON("unimplemented\n");
+    schedule_tail(prev);
+
+    if ( is_idle_vcpu(current) )
+        reset_stack_and_jump(idle_loop);
+    else
Quoted 3 lines

This is the kind of "else" which I consider particularly confusing: It suggests that the if() body can actually be exited at the bottom, when (by the name "reset_stack_and_jump") it hopefully cannot.

Agreed, the "else" isn't needed here. I kept it only because it looked more symmetric to me, but I'll drop it and move its body out to the same level as the if().

Quoted 23 lines
Quoted 23 lines
xen/arch/riscv/domain.c +22 -0
+    {
+        /*
+         * During a context switch to a new vCPU, interrupts must be disabled
+         * to guarantee that the vCPU's CSR state can be safely restored into
+         * the hart without being clobbered by an interrupt trap.
+         *
+         * For example, when return_to_new_vcpu() finishes, it executes sret.
+         * At that point, the hart checks hstatus.SPV=1 and sstatus.SPP=1 in
+         * order to return from HS-mode into VS-mode. If an interrupt were to
+         * arrive before sret, the trap entry logic would implicitly clear
+         * hstatus.SPV to 0. Correctly restoring it afterwards is non-trivial,
+         * and if left as 0, sret would incorrectly return to HS-mode instead
+         * of VS-mode.
+         *
+         * To avoid this, interrupts are kept disabled during the restore.
+         * Additionally, setting sstatus.SPIE=1 ensures that after sret is
+         * executed (as sstatus.SIE will be loaded from SPIE), HS-mode will
+         * continue to receive interrupts normally.
+         */
+        local_irq_disable();
+        csr_set(CSR_SSTATUS, SSTATUS_SPIE);
+
Quoted 8 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 181

Quoted 3 lines
xen/arch/riscv/domain.c +3 -0
+        csr_write(CSR_HSTATUS, vcpu_guest_cpu_user_regs(current)->hstatus);
+
+        reset_stack_and_jump(return_to_new_vcpu);

What are the criteria by which you split CSR accesses between doing some here and some in return_to_new_vcpu()? In particular you set sstatus.SPIE here but sstatus.SPP there, when both could - I think - be done with a single CSR access.

There was no real criterion (and SPIE is set here only for better explanation of the comment). I'll move all the CSR setup sret depends on (hstatus, sepc, sstatus.SPP and sstatus.SPIE) into return_to_new_vcpu(),
like the regular return-to-guest path in entry.S already does, and set SPP and SPIE with a single CSR access there. Only local_irq_disable() will stay in continue_new_vcpu().

I will do the following:

+     * return_to_new_vcpu() sets up hstatus.SPV, sstatus.SPP and sepc so
+     * that sret enters the guest in VS-mode. A trap taken in HS-mode
+     * overwrites all of them (trap entry clears hstatus.SPV in particular),
+     * so interrupts have to stay disabled until sret. They are re-enabled by
+     * sret itself, as return_to_new_vcpu() also sets sstatus.SPIE.
      */
     local_irq_disable();

- csr_set(CSR_SSTATUS, SSTATUS_SPIE);
-
- csr_write(CSR_HSTATUS, vcpu_guest_cpu_user_regs(current)->hstatus);

     reset_stack_and_jump(return_to_new_vcpu);

and then:

-/* t0 is used as a temporary reg and is clobbered to oblivion */ +/*
+ * Enter a vCPU for the first time. Must be called with interrupts disabled,
+ * see continue_new_vcpu().
+ *
+ * t0 is used as a temporary reg and is clobbered to oblivion.
+ */
FUNC(return_to_new_vcpu)

         /* Swap tp with sscratch */
         csrrw   tp, CSR_SSCRATCH, tp

         /* Set vCPU registers */
+        REG_L   t0, CPU_USER_REGS_HSTATUS(sp)
+        csrw    CSR_HSTATUS, t0
+
         REG_L   t0, CPU_USER_REGS_SEPC(sp)
-        csrw    sepc, t0
+        csrw    CSR_SEPC, t0
         /* Hartid goes to a0 */
         REG_L   a0, CPU_USER_REGS_A0(sp)

         /* DTB goes to a1 */
         REG_L   a1, CPU_USER_REGS_A1(sp)
-        /* Set guest mode to supervisor */
-        li      t0, SSTATUS_SPP
+        /* Return to (V)S-mode, with interrupts re-enabled by sret */
+        li      t0, SSTATUS_SPP | SSTATUS_SPIE

csrs CSR_SSTATUS, t0

/* Enter guest */
sret
END(return_to_new_vcpu)

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/entry.S +0 -0
@@ -143,3 +143,26 @@ FUNC(__context_switch)
 
Quoted 10 lines

xen/arch/riscv/entry.S FUNC(__context_switch) · line 150

Quoted 7 lines
xen/arch/riscv/entry.S +5 -0
          ret
  END(__context_switch)
+
+/* t0 is used as a temporary reg and is clobbered to oblivion */
+FUNC(return_to_new_vcpu)
+        /* Swap tp with sscratch */
+        csrrw   tp, CSR_SSCRATCH, tp

What is this about? I'm not aware of any counterpart code, yet all on its own this I can't see it being overly useful.

It will be needed later when a guest will be able to launch to distinguish in handle_trap() [1] if a trap is from guest or not. I can drop it for now and re-introduce it with the code of handle_trap() or as an option I could update the comment above to:

/*
* SSCRATCH holds this hart's struct pcpu_info while a guest
runs and
* is zero while Xen runs, so that a trap handler can tell the two
* apart: tp is Xen's pointer to pcpu_info in Xen context, but
belongs
* to the guest once sret has been executed. Establish that by
swapping
* the two here; the trap path swaps them back.
*/
csrrw tp, CSR_SSCRATCH, tp

(but then the last part will point to the part which isn't yet introduced so probably it will be better to drop this line for now)

[1] https://gitlab.com/xen-project/people/olkur/xen/-/blob/riscv-next-upstreaming/xen/arch/riscv/entry.S?ref_type=heads&blame=1#L15

Quoted 17 lines

xen/arch/riscv/entry.S FUNC(__context_switch) · line 160

Quoted 10 lines
xen/arch/riscv/entry.S +9 -0
+        /* Set vCPU registers */
+        REG_L   t0, CPU_USER_REGS_SEPC(sp)
+        csrw    sepc, t0
+
+        /* Hartid goes to a0 */
+        REG_L   a0, CPU_USER_REGS_A0(sp)
+
+        /* DTB goes to a1 */
+        REG_L   a1, CPU_USER_REGS_A1(sp)

The fields loaded are merely .a0 and .a1 of the register struct. There's nothing here making sure (all on its own) that what is loaded is what is said by the comments. If e.g. the first comment was /* .a0 holds the hart id */ or some such to remind readers what is being loaded without giving the impression that the correct value is _established_ here, that may be better.

I will re-word the comments in suggested way:

- /* Hartid goes to a0 */
+ /* .a0 holds the hart id */

         REG_L   a0, CPU_USER_REGS_A0(sp)

- /* DTB goes to a1 */
+ /* .a1 holds the address of the DTB */

         REG_L   a1, CPU_USER_REGS_A1(sp)
Quoted 12 lines

xen/arch/riscv/entry.S FUNC(__context_switch) · line 168

Quoted 8 lines
xen/arch/riscv/entry.S +7 -0
+        /* Set guest mode to supervisor */
+        li      t0, SSTATUS_SPP
+        csrs    CSR_SSTATUS, t0
+
+        /* Enter guest */
+        sret
+END(return_to_new_vcpu)

Aiui SRET does not switch stacks. Shouldn't you therefore clear sp here? And perhaps also other GPRs, not the least ra? Exposing hypervisor register values to guests is, well, a bit of a problem.

Good point, sret leaves all GPRs as they are, so the guest would indeed see Xen's sp, ra and friends. Only a0 and a1 are architecturally meaningful for a booting hart, so I'll clear every other GPR right before sret.

I will add the following before sret:

/*
* sret doesn't switch stacks and leaves the GPRs alone, so every
* register which isn't meaningful to the vCPU being started
has to be
* cleared here: otherwise the guest would see Xen's values, sp
(this

         * vCPU's Xen stack) and ra among them.
         */
        .irp reg, ra, sp, gp, tp, t0, t1, t2, s0, s1, a2, a3, a4, a5, 

a6, a7, \
s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, t3, t4, t5, t6
mv \reg, zero
.endr

Thanks.

~ Oleksii

#247 lore raw

Re: [PATCH v2 39/39] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu

In reply to Jan Beulich
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

Introduce imsic_vsfile_attach() to initialize the AIA-related state needed for a vCPU to have a working guest interrupt file.

A guest (VS) interrupt file must be mapped to one of a pCPU's hardware interrupt files (if they exist), so the pCPU a vCPU will actually run on needs to be known first. arch_vcpu_create() is therefore not a suitable place to call vcpu_aia_init(), since the pCPU assigned to a vCPU can still change before it is first scheduled. To avoid reassigning the VS interrupt file id and remapping it to a different pCPU's hardware interrupt file, imsic_vsfile_attach() is called from a later point in the scheduling path (e.g. continue_new_vcpu()).

Quoted 4 lines

Hmm, why does first-time handling need to be this different from the handling of a vCPU moving across pCPU-s? The sole difference should be "no state to load" vs "load state that was saved on the old pCPU".

Generally I think it could be the same but not all the steps done in migration functions aren't needed for new vCPU (despite of the fact they aren't harmful). For new vCPU it seems to me it is enough only to attach h/w interrupt file to vCPU.

~ Oleksii

#57 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

In reply to SeungJu Cheon
Quoted 33 lines · SeungJu Cheon

On Thu, Sep 10, 2026 at 04:24:06PM +0200, Oleksii Kurochko wrote:
[...]

Quoted 11 lines

In v3 I'll (a) stop using ->processor and take the (guest_file_id, vsfile_cpu) pair, which imsic_update_state() updates atomically under vsfile_lock, and (b) do the snapshot plus the h/w TARGET write under aplic.lock, which aplic_reconfigure_target() also holds. As imsic_update_state() completes before aplic_reconfigure_target() (also that could be checked in this patch series and is introduced a little bit later. Probably I have to re-order some patches again) takes the lock, the emulated write either happens before the scan (and gets fixed up, or skipped as already correct) or after it (and sees the new location).

Any better option I have now?

Unless I am missing something, the snapshot also needs to handle the case where the target vCPU has not been attached yet:
vcpu_guest_file_id() returns zero until the vCPU has gone through imsic_vsfile_attach(), i.e. until it is scheduled for the first time, and vsfile_cpu is NR_CPUS until then.

With the current code, a write targeting such a vCPU makes aplic_msi_target_gen() program Guest Index 0 into the physical APLIC target register. According to AIA section 4.5.16, Guest Index 0 selects the hart's supervisor-level interrupt file rather than a VS-level guest interrupt file. Could this cause the MSI to be delivered to Xen's own interrupt file with the EIID supplied by the guest?

I also could not find where such a target would be updated once the VS-file is attached. imsic_migrate_vcpu() reprograms the relevant targets during migration, but the initial imsic_vsfile_attach() path does not appear to replay targets which were written before the attachment.

Quoted 6 lines

Whether a write targeting an unattached vCPU should be supported seems like a separate question. Independently of that choice, would it make sense to avoid programming the physical TARGET register while guest_file_id is zero? The virtual target could either be rejected, or retained in the shadow target[] and programmed once the VS-file is attached.

If the target vCPU hasn't attached yet it means that continue_to_new_vcpu() for it wasn't called so it will be rejected by target register emulated code:

...
target_vcpu = domain_vcpu(currd, guest_hart_idx);

if ( !target_vcpu )
{
gdprintk(XENLOG_ERR, "Invalid vCPU id in target
register\n");

                /* Ignore such writings */
                return true;
            }

...

(probably we should back to this question in v3 of this patch as several things were updated and some of your concerns mentioned here looks to me not really possible)

Thanks.

~ Oleksii

#149 lore raw

Re: [PATCH v2 23/39] xen/riscv: look up the exception table for any trap taken in Xen context

In reply to Baptiste Le Duc
Quoted 18 lines · Baptiste Le Duc
Quoted 18 lines

do_trap() consulted the exception table only for CAUSE_ILLEGAL_INSTRUCTION, which covers csr_read_safe() but not the hlv/hlvx sequences reading guest
memory: those fault with load/store (guest) page fault causes and would reach do_unexpected_trap() instead of their fixup.

Move the lookup ahead of the cause switch, and gate it on the trap having been taken in Xen context and not being an interrupt:

- sepc of a trap taken from the guest is a guest VA/PA, which the guest can point at an address listed in the exception table; Xen would then act on that entry and, for EX_TYPE_TRAP_INFO, write through a pointer fully under guest control. Entries are matched by exact address, so this needs no more than a numerical collision.

- an interrupt taken at an address listed in the table would otherwise be "fixed up" as if the access itself had faulted, silently skipping it and handing the caller the interrupt's scause as a fault cause.

Quoted 8 lines
Quoted 6 lines

Returning early skips check_for_pcpu_work(), which is correct: that only runs for traps taken from the guest.

With that in place a G-stage fault reaching the switch can no longer have been caused by an hlv/hlvx covered by an entry, so anything left must have come from the guest; assert as much.

What means assert as much here? As you referencing any assert in the code, because in this patch, I couldn't find any.

It refers to the BUG_ON(!from_guest) in the guest page fault case of do_trap(). That BUG_ON() (and the comment above it) ended up in "xen/riscv: add guest page fault handling stub" when the series was reordered, so this sentence is stale.

I will drop 'assert as much' from commit message.

Quoted 7 lines
Quoted 3 lines

Cache the "trap came from the guest" test in a local, it is now used four times.

Nit: By reading this sentence, I would expect to have the introduction of from_guest local here instead of in patch cc2d3b97e8 xen/riscv: add guest page fault handling stub

from_guest is introduced in "xen/riscv: add guest page fault handling stub" so it is a stale part of the commit message.

Thanks!

~ Oleksii

#241 lore raw

Re: [PATCH v2 38/39] xen/riscv: implement continue_new_vcpu()

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko
Quoted 9 lines · Jan Beulich
Quoted 7 lines · Oleksii Kurochko

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, restore hstatus and enter the guest through the new return_to_new_vcpu() path in entry.S, which loads sepc, passes the hart id in a0 and the DTB address in a1 as expected by the RISC-V boot protocol, sets sstatus.SPP and executes sret.

Quoted 8 lines
Quoted 2 lines

Is this a requirement for all CPUs, or just for the boot one? (I can't quite see why secondary processors would need passing a DTB address.)

It is requirement for boot one. For secondary processors it is HSM boot data which is passed to sbi_hsm_hart_start() and then intercpeted by Xen.

At the moment of writing of this commit message we have only boot CPU and so only DTB could be passed.

That you're talking about Xen. Despite Xen being UP only right now, guests still can have more than one vCPU, can't they?

Quoted 4 lines

I can update the commit message and the comment in return_to_new_vcpu() to tell that it could be DTB address for boot cpu and/or for secondary CPUs HSM boot data or it will be better to add info about HSM boot data during and an introduction of secondary CPUs support?

As per above you want to deal with multi-vCPU guests right now.

Quoted 42 lines
Quoted 9 lines
Quoted 6 lines

Interrupts have to stay disabled across the restore. The trap entry logic implicitly clears hstatus.SPV, so an interrupt taken between the write of hstatus and sret would make sret return to HS-mode instead of VS-mode, and restoring SPV afterwards is non-trivial. Instead interrupts are simply kept off and sstatus.SPIE is set, so that SIE is restored from SPIE once sret has been executed.

As written this reads as if the guest would be responsible for doing this. Isn't it rather SRET itself which does this?

IIUC to which part you refer then yes, it is SRET itself which does this. So some re-wording should be done ...

Quoted 7 lines
Quoted 3 lines

Also, it follows what hardware will do
with real CPU which is also started with interrupts disabled.

Further up, aiui, you talk about the host's interrupt state. How vCPU-s are started, however, is virtual interrupt state. Mixing both isn't very helpful.

...:

Interrupts have to stay disabled across the restore. The trap entry logic implicitly clears hstatus.SPV, so an interrupt taken between the write of hstatus and sret would make sret return to HS-mode instead of VS-mode, and restoring SPV afterwards is non-trivial. Hence interrupts are kept disabled, and sstatus.SPIE is set so that sret itself re-enables them (SIE := SPIE) as part of entering the guest.

Then it will be also need to update the comment inside continue_new_vcpu() to:

(quoted diff) +3 -4
-         * To avoid this, interrupts are kept disabled during the restore.
-         * Additionally, setting sstatus.SPIE=1 ensures that after sret is
-         * executed (as sstatus.SIE will be loaded from SPIE), HS-mode will
-         * continue to receive interrupts normally.
+         * To avoid this, interrupts are kept disabled during the restore,
+         * and sstatus.SPIE is set so that sret itself re-enables them
+         * (SIE := SPIE) as part of entering the guest.
           */
Quoted 1 line

Would it be the wording okay for you now?

I think so, yes.

Quoted 32 lines
Quoted 4 lines
Quoted 4 lines
xen/arch/riscv/entry.S +0 -0
@@ -143,3 +143,26 @@ FUNC(__context_switch)
 
Quoted 10 lines

xen/arch/riscv/entry.S FUNC(__context_switch) · line 150

Quoted 7 lines
xen/arch/riscv/entry.S +5 -0
          ret
  END(__context_switch)
+
+/* t0 is used as a temporary reg and is clobbered to oblivion */
+FUNC(return_to_new_vcpu)
+        /* Swap tp with sscratch */
+        csrrw   tp, CSR_SSCRATCH, tp

What is this about? I'm not aware of any counterpart code, yet all on its own this I can't see it being overly useful.

It will be needed later when a guest will be able to launch to distinguish in handle_trap() [1] if a trap is from guest or not. I can drop it for now and re-introduce it with the code of handle_trap() or as an option I could update the comment above to:

/*
* SSCRATCH holds this hart's struct pcpu_info while a guest
runs and
* is zero while Xen runs, so that a trap handler can tell the two
* apart: tp is Xen's pointer to pcpu_info in Xen context, but
belongs
* to the guest once sret has been executed. Establish that by
swapping
* the two here; the trap path swaps them back.
*/
csrrw tp, CSR_SSCRATCH, tp

Quoted 2 lines

(but then the last part will point to the part which isn't yet introduced so probably it will be better to drop this line for now)

Yes, introducing it together with the other related pieces is going to be more consistent and easier to follow.

Quoted 25 lines
Quoted 11 lines

xen/arch/riscv/entry.S FUNC(__context_switch) · line 168

Quoted 7 lines
xen/arch/riscv/entry.S +7 -0
+        /* Set guest mode to supervisor */
+        li      t0, SSTATUS_SPP
+        csrs    CSR_SSTATUS, t0
+
+        /* Enter guest */
+        sret
+END(return_to_new_vcpu)

Aiui SRET does not switch stacks. Shouldn't you therefore clear sp here? And perhaps also other GPRs, not the least ra? Exposing hypervisor register values to guests is, well, a bit of a problem.

Good point, sret leaves all GPRs as they are, so the guest would indeed see Xen's sp, ra and friends. Only a0 and a1 are architecturally meaningful for a booting hart, so I'll clear every other GPR right before sret.

I will add the following before sret:

/*
* sret doesn't switch stacks and leaves the GPRs alone, so every
* register which isn't meaningful to the vCPU being started
has to be
* cleared here: otherwise the guest would see Xen's values, sp
(this

Quoted 7 lines
          * vCPU's Xen stack) and ra among them.
          */
         .irp reg, ra, sp, gp, tp, t0, t1, t2, s0, s1, a2, a3, a4, a5, 

a6, a7, \
s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, t3, t4, t5, t6
mv \reg, zero
.endr

At which point discussing the clobbering of t0 in the comment ahead of the function also isn't needed anymore.

Jan

#248 lore raw

Re: [PATCH v2 39/39] xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu

In reply to Oleksii Kurochko
Quoted 14 lines · Oleksii Kurochko
Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

Introduce imsic_vsfile_attach() to initialize the AIA-related state needed for a vCPU to have a working guest interrupt file.

A guest (VS) interrupt file must be mapped to one of a pCPU's hardware interrupt files (if they exist), so the pCPU a vCPU will actually run on needs to be known first. arch_vcpu_create() is therefore not a suitable place to call vcpu_aia_init(), since the pCPU assigned to a vCPU can still change before it is first scheduled. To avoid reassigning the VS interrupt file id and remapping it to a different pCPU's hardware interrupt file, imsic_vsfile_attach() is called from a later point in the scheduling path (e.g. continue_new_vcpu()).

Quoted 8 lines
Quoted 3 lines

Hmm, why does first-time handling need to be this different from the handling of a vCPU moving across pCPU-s? The sole difference should be "no state to load" vs "load state that was saved on the old pCPU".

Generally I think it could be the same but not all the steps done in migration functions aren't needed for new vCPU (despite of the fact they aren't harmful). For new vCPU it seems to me it is enough only to attach h/w interrupt file to vCPU.

Sure, yet still imo you want to aim at re-using as much code as possible, especially when otherwise you introduce multiple very similar but not exactly identical variants of logic.

Jan

#155 lore raw

Re: [PATCH v2 24/39] xen/riscv: add helpers for decoding a trapped load or store

In reply to Baptiste Le Duc
Quoted 9 lines · Baptiste Le Duc
Quoted 7 lines

emulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().

The mask/match chain is adapted from Linux's KVM RISC-V implementation.

Nit: maybe you could add the Origin: trailer as mentioned in the sending-patches.adoc.

I think that I will drop that sentense as the code in v3 is changed pretty significantly so it doesn't too much sense to mention that it was derived from Linux's KVM RISC-V.

Basically even if I will put Origin: now here then it will be still pretty hard to undestand what was used or not as I mentioned above there are a lot of changes done in comparison with original.

I will take it in mind for my future patches.

[...]

Quoted 68 lines
Quoted 17 lines
xen/arch/riscv/emulate.c +17 -0
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()).
+ *
+ * @xlen is the effective XLEN of the guest, needed as
+ * the encodings which exist for XLEN=64 only must not be recognized for a
+ * 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.
+ */
+static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
+                                            unsigned int xlen)
+{
+    unsigned long insn = di->insn;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 322

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    /* Register fields of the uncompressed forms ... */
+    unsigned int rd = RV_RD(insn);
+    unsigned int rs2 = RV_RS2(insn);
+    /*
+     * ... and of the compressed ones, where the 3-bit field selects one of
+     * x8..x15, while the stack-pointer-relative forms have a full-width one.
+     */
+    unsigned int rs2s = RVC_RS2S(insn);
+    unsigned int rs2c = RVC_RS2(insn);
+

This naming are confusing because above you described di->reg to be rd for load and rs2 for store but here ...

Quoted 25 lines
xen/arch/riscv/emulate.c +23 -0
+    di->is_write = false;
+    di->is_unsigned = false;
 
 
+    di->reg = rd;
+
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 351

Quoted 10 lines
xen/arch/riscv/emulate.c +6 -0
+        di->is_unsigned = true;
+    }
 
 
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
 
 
+        di->reg = rs2s;

... you assigned rs2s for a load. According to the spec, it should be rd'.

I would suggest something generic to load and store. Maybe rxs with a comment to explain it concerns rs2' for store and rd' for load.

Quoted 7 lines

/*
* ... and of the compressed ones, where the 3-bit field selects one of
* x8..x15, while the stack-pointer-relative forms have a full-width one.
* rxs is named after that field's spec mnemonic, rd'/rs2': rd' for
* compressed loads, rs2' for compressed stores.
*/
unsigned int rxs = RVC_RS2S(insn);

Good point. It isn't partly applied to what I suggested in one of the reply to Jan B. but I will try to re-use part of your suggestion there.

It will look like:

static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)

{
    uint32_t insn = di->insn;
    unsigned int funct3, width_log2;

    if ( INSN_IS_16BIT(insn) )
    {
        /*
         * C.LW, C.LD, C.SW and C.SD (bits[1:0] == 00), and their 
sp-relative
         * C.*SP forms (bits[1:0] == 10), have bits[15:13] of the form x1y:
         * x is set for a store, and y selects a width of 4 or 8 bytes.
         */
        funct3 = RV_X(insn, 13, 3);

        if ( (insn & 1) || !(funct3 & 2) )
            return false;

        di->is_write = funct3 & 4;
        width_log2 = 2 + (funct3 & 1);

        /*
         * The register operand is rd' of a load or rs2' of a store for the
         * register-relative forms, both being bits[4:2], and rs2 of a 
store
         * or rd of a load for the sp-relative ones.
         */
        if ( !(insn & 2) )
            /* Quadrant 0: bits[4:2] encode rd' (load) or rs2' (store) */
            di->reg = RVC_RS2S(insn);
        else if ( di->is_write )
            /* Quadrant 2 (CSS): bits[6:2] encode rs2 for C.SWSP / 
C.SDSP */
            di->reg = RVC_RS2(insn);
        else
        {
            /* Quadrant 2 (CI): bits[11:7] encode rd for C.LWSP / C.LDSP */
            di->reg = RV_RD(insn);

            /* C.LWSP and C.LDSP are reserved with rd being x0. */
            if ( !di->reg )
                return false;
        }
    }
    else
    {
        /*
         * funct3[1:0] is log2 of the width in bytes, and funct3[2] selects
         * zero-extension for a load, while being reserved for a store.
         */
        funct3 = RV_X(insn, 12, 3);
        width_log2 = funct3 & 3;

        switch ( insn & INSN_OPCODE_MASK )
        {
        case INSN_OPCODE_LOAD:
            di->is_unsigned = funct3 & 4;
            di->reg = RV_RD(insn);
            break;

        case INSN_OPCODE_STORE:
            if ( funct3 & 4 )
                return false;
            di->is_write = true;
            di->reg = RV_RS2(insn);
            break;

        default:
            return false;
        }
    }

    di->len = 1U << width_log2;

    /*
     * No access is wider than XLEN, and one as wide as XLEN exists only in
     * its sign-extending form: this rules out the encodings which 
exist for
     * XLEN=64 only on a 32-bit guest, including C.FLW for C.LD (and 
alike).
     */
    if ( (di->len * BITS_PER_BYTE > xlen) ||
         (di->is_unsigned && di->len * BITS_PER_BYTE == xlen) )
        return false;

    return true;
}
Quoted 69 lines
Quoted 69 lines
xen/arch/riscv/emulate.c +68 -0
+    }
+    /* c.lwsp and c.ldsp are reserved with rd being x0. */
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP && rd )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LD) == INSN_MATCH_LD )
+        di->len = 8;
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LD) == INSN_MATCH_C_LD )
+    {
+        di->len = 8;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LDSP) == INSN_MATCH_C_LDSP &&
+              rd )
+        di->len = 8;
+    else if ( (insn & INSN_MASK_SB) == INSN_MATCH_SB )
+    {
+        di->len = 1;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SH) == INSN_MATCH_SH )
+    {
+        di->len = 2;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SW) == INSN_MATCH_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_C_SW) == INSN_MATCH_C_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( (insn & INSN_MASK_C_SWSP) == INSN_MATCH_C_SWSP )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_SD) == INSN_MATCH_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SD) == INSN_MATCH_C_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SDSP) == INSN_MATCH_C_SDSP )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else
+        return false;
+
+    return true;
+}
+

[...]

Quoted 10 lines
Quoted 10 lines
xen/arch/riscv/include/asm/riscv_encoding.h +8 -0
+/*
+ * Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one
+ * encoding. 0 is reserved.
+ */
+#define XLEN_FIELD_32			_UL(1)
+#define XLEN_FIELD_64			_UL(2)
+#define XLEN_FIELD_128			_UL(3)
+
  #if __riscv_xlen == 64
  #define HSTATUS_VSXL			_UL(0x300000000)
Quoted 9 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 908

Quoted 7 lines
  #define HSTATUS_VSXL_SHIFT		32
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
@@ -896,6 +904,8 @@
  					 (RV_X(x, 7, 2) << 6))
  #define RVC_SDSP_IMM(x)			((RV_X(x, 10, 3) << 3) | \
  					 (RV_X(x, 7, 3) << 6))
+#define RV_RD(insn)			RV_X(insn, SH_RD, 5)
+#define RV_RS2(insn)			RV_X(insn, SH_RS2, 5)

Nit: format

I think it looks like that because tabs are used there instead of spaces and tabs are there because it was orignally taken from the project which uses tabs.

Thanks!

~ Oleksii

#160 lore raw

Re: [PATCH v2 25/39] xen/riscv: add guest load emulation for trapped MMIO accesses

In reply to Baptiste Le Duc
Quoted 8 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 183

Quoted 6 lines
xen/arch/riscv/emulate.c +0 -2
@@ -179,8 +178,7 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
   * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
   * architectural register-number order; see the comment there.
   */
-static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
-                                               unsigned int reg)

Could we unified this function with regs_get_gpr()?

I think it could. I will try to do in the unified way.

Thanks!

~ Oleksii

#167 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

In reply to Baptiste Le Duc
Quoted 18 lines · Baptiste Le Duc
Quoted 10 lines

Extend the guest page fault handler with store emulation to support MMIO write accesses.

The instruction decode mirrors emulate_load() and, like it, is adapted from Linux's KVM RISC-V implementation. As with the load path, the completion is synchronous through try_handle_mmio() rather than KVM's userspace exit/return split, since Xen's MMIO handlers run in the hypervisor. Faults taken while re-reading the trapped instruction are handled by decode_ldst_insn(), shared with the load path.

Quoted 2 lines

When a guest store instruction faults, the trapped instruction is decoded using HTINST or, if unavailable, fetched via unprivileged access. At the

Nit: commit message restates the HTINST-or-unprivileged-fetch decode mechanism, which is already described in the prep patch introducing decode_ldst_insn()/insn_fetch_faulted(), and isn't repeated in emulate_load()'s commit message. Suggest trimming for symmetry with the load commit, e.g.:

Quoted 7 lines

When a guest store instruction faults, the trapped instruction is decoded via decode_ldst_insn(), shared with the load path. At the moment only virtual interrupt controller (vINTC) traps are expected to occur, since it is currently the only backend registered with the MMIO handler dispatch, so in practice the store is emulated via the vINTC backend.

I will update the commit message.

Thanks.

~ Oleksii

#190 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

In reply to Baptiste Le Duc
Quoted 172 lines · Baptiste Le Duc
Quoted 169 lines · Oleksii Kurochko

Implement first steps of migration a vCPU to a different guest interrupt file procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).

The following steps will be introduced in follow-up patches.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_assign() will be introduced later in a separate patch, for not it is only stub.

---
Changes in v2:
  - New patch.
---
---
  xen/arch/riscv/aia.c             |   9 ++ xen/arch/riscv/imsic.c           | 159 +++++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/aia.h |   4 + xen/include/xen/config.h         |   1 +

  4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
index e31c9c2d24b6..75c82bcfa1b3 100644
@@ -1,8 +1,10 @@
   /* SPDX-License-Identifier: GPL-2.0-only */
+#include <xen/bug.h>
   #include <xen/errno.h>
   #include <xen/init.h>
   #include <xen/sections.h>
+#include <xen/sched.h>
   #include <xen/types.h>
   #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void)
       _aia_usable = true;
   }
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    BUG_ON("unimplemented\n");
+
+    return 0;
+}
xen/arch/riscv/imsic.c +11 -0
index ad7fbe708bfd..516f0105352a 100644
@@ -26,6 +26,7 @@
   #include <xen/spinlock.h>
   #include <xen/xvmalloc.h>
+#include <asm/aia.h>
   #include <asm/imsic.h>
   #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -77,6 +78,64 @@ do {                            \
       csr_clear(CSR_SIREG, v);    \
   } while (0)
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are 

forwarded to F
+ * via __VA_ARGS__.
+ *
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */

xen/arch/riscv/imsic.c +41 -0
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)    \
+    imsic_switchcase_2(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_2(F, ireg + 2, ##__VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)    \
+    imsic_switchcase_4(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_4(F, ireg + 4, ##__VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)   \
+    imsic_switchcase_8(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_8(F, ireg + 8, ##__VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)   \
+    imsic_switchcase_16(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_16(F, ireg + 16, ##__VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)   \
+    imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+

  unsigned int vcpu_guest_file_id(const struct vcpu *v) {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);

xen/arch/riscv/imsic.c +2 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
       return 0;
   }
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are 

executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */

xen/arch/riscv/imsic.c +8 -0
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file 

func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */

xen/arch/riscv/imsic.c +10 -0
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
Quoted 8 lines

xen/arch/riscv/imsic.c

Quoted 6 lines

+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);

xen/arch/riscv/imsic.c +3 -0
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

I think it can't because of how function pointer is passed to on_selected_cpus() through imsic_call_on_cpu().

Quoted 37 lines
Quoted 37 lines
xen/arch/riscv/imsic.c +32 -0
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;
+
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif
+    }
+
+    csr_write(CSR_HSTATUS, old_hstatus);
+    csr_write(CSR_VSISELECT, old_vsiselect);
+}
+

  void cf_check vcpu_imsic_deinit(struct vcpu *v)
  {
      XVFREE(v->arch.vimsic_state);

xen/arch/riscv/imsic.c +0 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct 
 kernel_info *kinfo,
Quoted 8 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct · line 824

Quoted 6 lines
xen/arch/riscv/imsic.c +4 -0
   void imsic_migrate_vcpu(struct vcpu *v)
   {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

This value appears to remain constant after initialization, since it depends directly on the hw, so it is not necessary to calculate it each time.

I will add then:

xen/arch/riscv/include/asm/imsic.h +0 -0
@@ struct imsic_config {
     /* Number off interrupt identities */
     unsigned int nr_ids;

+ /*

+     * Number of 64-bit EIx groups needed to cover all the interrupt
+     * identities, which are 0 (never valid, but it still occupies a bit) up
+     * to and including nr_ids.
+     */

+ unsigned int nr_eix;
+

and init it once in imsic_parse_node().

Thanks.

~ Oleksii

#231 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Jan Beulich
Quoted 42 lines · Jan Beulich
Quoted 41 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 
Quoted 14 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
       write_lock_irqsave(&imsic_state->vsfile_lock, flags);
       imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
       write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
   }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

There's no window: a guest interrupt file's hgeip bit is level-sensitive, i.e. it reflects whether the file currently has a pending-and-enabled interrupt (the MSI itself stays latched in the file's eip[] until the guest claims it), and hip.SGEIP is simply (hgeip & hgeie) != 0. So an MSI arriving after the vCPU stopped running but before hgeie is set raises an SGEI as soon as the bit is set, taken once interrupts are re-enabled. I'll extend the comment to say so:

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through
HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the
vCPU up.
*
* HGEIP is level-sensitive, reflecting the VS-file's current state, so
* an interrupt that became pending before this point raises an SGEI as
* soon as the bit is set in HGEIE; nothing is lost in between. */

Quoted 6 lines
Quoted 1 line

Does it make sense?

I think I get what you're trying to explain, but the term "level-sensitive" here doesn't really help. I'm unconvinced you actually mean that, as it requires pins / physical signals, which don't exist with MSI. It feels like you may mean "sticky" instead.

Fair point regarding the terminology: 'level-sensitive' usually implies physical signal lines, whereas here MSIs are memory writes latched in the file's eip[] array. I meant that HGEIP dynamically reflects whether the VS-file currently has any pending-and-enabled interrupt latched.

I'll update the comment to clarify this without using 'level-sensitive':

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the vCPU up. *
* An MSI is recorded in the VS-file's eip[] array until the guest claims
* it, and HGEIP isn't latched but reflects whether the file currently
* has a pending-and-enabled interrupt. Hence an interrupt which arrived
* before this point raises an SGEI as soon as the bit is set in HGEIE;
* nothing is lost in between.
*/

Quoted 42 lines
Quoted 42 lines
Quoted 13 lines
Quoted 13 lines
xen/arch/riscv/imsic.c +9 -1
   void cf_check imsic_ctxt_switch_to(struct vcpu *v)
   {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 6 lines
xen/arch/riscv/imsic.c +5 -0
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
   }

How can this be a read-lock when you write a CSR?

But here is a protection of ->guest_file_id not of write to a CSR and we want to not have a change of ->guest_file_id during an update of CSR_HGEIE.

Quoted 2 lines

Or else - why is locking
here necessary in the firt place?

Strictly speaking no locking is needed with the current implementation:
HGEIE is local to this pCPU, and guest_file_id can't change concurrently. It's updated either by this very pCPU ahead of switching the vCPU in (imsic_migrate_vcpu() called from schedule(), imsic_vsfile_attach() right after), or while the vCPU can't be
scheduled: sched_unit_migrate_finish() defers to unit_context_saved() while the unit is running, and sched_move_domain() pauses the domain.

(and the similar are true for imsic_ctxt_switch_from())

But IMO we should keep around ->vsfile_lock to not miss the case where some case will update ->guest_file_id in parallel with imsic_ctxt_switch_to().

Quoted 7 lines
Quoted 2 lines

Does it make to continue to have read_lock_irqsave(...->vsfile_lock, ...) here just for potential future cases?

You get to judge. If the lock typically is uncontended, keeping things as-is may indeed be fine. Introducing a bottleneck "just for potential future cases" otoh wouldn't look overly nice to me.

For the moment, I prefer to have a lock here as it is expected to be cheap. If one day it won't be true anymore it will be easier to spot all the places and remove it where it will be necessary.

~ Oleksii

#242 lore raw

Re: [PATCH v2 38/39] xen/riscv: implement continue_new_vcpu()

In reply to Jan Beulich
Quoted 14 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
Quoted 11 lines · Jan Beulich
Quoted 7 lines · Oleksii Kurochko

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, restore hstatus and enter the guest through the new return_to_new_vcpu() path in entry.S, which loads sepc, passes the hart id in a0 and the DTB address in a1 as expected by the RISC-V boot protocol, sets sstatus.SPP and executes sret.

Is this a requirement for all CPUs, or just for the boot one? (I can't quite see why secondary processors would need passing a DTB address.)

Quoted 8 lines
Quoted 5 lines

It is requirement for boot one. For secondary processors it is HSM boot data which is passed to sbi_hsm_hart_start() and then intercpeted by Xen.

At the moment of writing of this commit message we have only boot CPU and so only DTB could be passed.

That you're talking about Xen. Despite Xen being UP only right now, guests still can have more than one vCPU, can't they?

They can.

Quoted 7 lines
Quoted 5 lines

I can update the commit message and the comment in return_to_new_vcpu() to tell that it could be DTB address for boot cpu and/or for secondary CPUs HSM boot data or it will be better to add info about HSM boot data during and an introduction of secondary CPUs support?

As per above you want to deal with multi-vCPU guests right now.

Then I will update the commit message and the comment in return_to_new_vcpu() to say that a1 holds the DTB address for the boot vCPU, and for secondary vCPUs the opaque value the guest passed to SBI HSM hart_start().

For commit message:

- for a guest vCPU, restore hstatus and enter the guest through the new return_to_new_vcpu() path in entry.S, which loads sepc, passes the
hart id in a0 and, in a1, either the DTB address (boot vCPU) or the
opaque argument of SBI HSM hart_start() (secondary vCPUs), as
required by the RISC-V boot protocol and the SBI specification, sets sstatus.SPP and executes sret.

In the code:

/*
* .a1 holds the DTB address for the boot vCPU, or the opaque value
* passed to SBI HSM hart_start() for secondary vCPUs */

Quoted 33 lines
Quoted 25 lines
Quoted 11 lines

xen/arch/riscv/entry.S FUNC(__context_switch) · line 168

Quoted 7 lines
xen/arch/riscv/entry.S +7 -0
+        /* Set guest mode to supervisor */
+        li      t0, SSTATUS_SPP
+        csrs    CSR_SSTATUS, t0
+
+        /* Enter guest */
+        sret
+END(return_to_new_vcpu)

Aiui SRET does not switch stacks. Shouldn't you therefore clear sp here? And perhaps also other GPRs, not the least ra? Exposing hypervisor register values to guests is, well, a bit of a problem.

Good point, sret leaves all GPRs as they are, so the guest would indeed see Xen's sp, ra and friends. Only a0 and a1 are architecturally meaningful for a booting hart, so I'll clear every other GPR right before sret.

I will add the following before sret:

/*
* sret doesn't switch stacks and leaves the GPRs alone, so every
* register which isn't meaningful to the vCPU being started
has to be
* cleared here: otherwise the guest would see Xen's values, sp
(this

Quoted 7 lines
           * vCPU's Xen stack) and ra among them.
           */
          .irp reg, ra, sp, gp, tp, t0, t1, t2, s0, s1, a2, a3, a4, a5,

a6, a7, \
s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, t3, t4, t5, t6
mv \reg, zero
.endr

Quoted 2 lines

At which point discussing the clobbering of t0 in the comment ahead of the function also isn't needed anymore.

Indeed, I'll drop it.

~ Oleksii

#191 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 249 lines · Oleksii Kurochko
Quoted 177 lines · Baptiste Le Duc
Quoted 174 lines · Oleksii Kurochko

Implement first steps of migration a vCPU to a different guest interrupt file
procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).

The following steps will be introduced in follow-up patches.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard
against silent incorrect behaviour or unexpected panics in guest VMs until
the function is fully implemented.

vgein_assign() will be introduced later in a separate patch, for not it is
only stub.

---
Changes in v2:
  - New patch.
---
---
  xen/arch/riscv/aia.c             |   9 ++ xen/arch/riscv/imsic.c           | 159 +++++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/aia.h |   4 + xen/include/xen/config.h         |   1 +

  4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
index e31c9c2d24b6..75c82bcfa1b3 100644
@@ -1,8 +1,10 @@
   /* SPDX-License-Identifier: GPL-2.0-only */
+#include <xen/bug.h>
   #include <xen/errno.h>
   #include <xen/init.h>
   #include <xen/sections.h>
+#include <xen/sched.h>
   #include <xen/types.h>
   #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void)
       _aia_usable = true;
   }
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    BUG_ON("unimplemented\n");
+
+    return 0;
+}
xen/arch/riscv/imsic.c +11 -0
index ad7fbe708bfd..516f0105352a 100644
@@ -26,6 +26,7 @@
   #include <xen/spinlock.h>
   #include <xen/xvmalloc.h>
+#include <asm/aia.h>
   #include <asm/imsic.h>
   #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * 
 IMSIC_MMIO_PAGE_SZ)
@@ -77,6 +78,64 @@ do {                            \
       csr_clear(CSR_SIREG, v);    \
   } while (0)
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are 

forwarded to F
+ * via __VA_ARGS__.
+ *
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */

xen/arch/riscv/imsic.c +41 -0
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)    \
+    imsic_switchcase_2(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_2(F, ireg + 2, ##__VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)    \
+    imsic_switchcase_4(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_4(F, ireg + 4, ##__VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)   \
+    imsic_switchcase_8(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_8(F, ireg + 8, ##__VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)   \
+    imsic_switchcase_16(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_16(F, ireg + 16, ##__VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)   \
+    imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+

  unsigned int vcpu_guest_file_id(const struct vcpu *v) {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);

xen/arch/riscv/imsic.c +2 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
       return 0;
   }
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are 

executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */

xen/arch/riscv/imsic.c +8 -0
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file 

func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */

xen/arch/riscv/imsic.c +10 -0
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
Quoted 8 lines

xen/arch/riscv/imsic.c

Quoted 6 lines

+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);

xen/arch/riscv/imsic.c +3 -0
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

I think it can't because of how function pointer is passed to on_selected_cpus() through imsic_call_on_cpu().

Quoted 38 lines
Quoted 38 lines
xen/arch/riscv/imsic.c +32 -0
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;
+
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif
+    }
+
+    csr_write(CSR_HSTATUS, old_hstatus);
+    csr_write(CSR_VSISELECT, old_vsiselect);
+}
+

  void cf_check vcpu_imsic_deinit(struct vcpu *v)
  {
      XVFREE(v->arch.vimsic_state);

xen/arch/riscv/imsic.c +0 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct 
 kernel_info *kinfo,
   void imsic_migrate_vcpu(struct vcpu *v)
Quoted 8 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct · line 824

Quoted 5 lines
xen/arch/riscv/imsic.c +4 -0
   {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

This value appears to remain constant after initialization, since it depends directly on the hw,
so it is not necessary to calculate it each time.

I will add then:

xen/arch/riscv/include/asm/imsic.h +0 -0
@@ struct imsic_config {
      /* Number off interrupt identities */
      unsigned int nr_ids;
xen/arch/riscv/include/asm/imsic.h +3 -0
+    /*
+     * Number of 64-bit EIx groups needed to cover all the interrupt
+     * identities, which are 0 (never valid, but it still occupies a 

bit) up

xen/arch/riscv/include/asm/imsic.h

Quoted 4 lines
xen/arch/riscv/include/asm/imsic.h +4 -0
+     * to and including nr_ids.
+     */
+    unsigned int nr_eix;
+

Thanks! Maybe use registers instead of groups wording.

Quoted 5 lines

and init it once in imsic_parse_node().

Thanks.

~ Oleksii

#196 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

In reply to Oleksii Kurochko
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +16 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
 #include <asm/imsic.h>
 #include <asm/intc.h>
 #include <asm/io.h>
+#include <asm/processor.h>
 #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
 
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
     spin_unlock_irqrestore(&aplic.lock, flags);
 }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 235

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay). Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to provide.

Signature · 1 line
Baptiste Le Duc <[email protected]>
Reviewed-by on v2 27/39
#171 lore raw

Re: [PATCH v2 27/39] xen/riscv: introduce arch_move_irqs()

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko

When migrating a vCPU between pCPUs the hypervisor must also migrate the associated virtual interrupt state. arch_move_irqs() is the per-arch hook called by generic code to trigger that.

Replace the static inline BUG_ON placeholder in asm/irq.h with a real implementation in intc.c dispatching through a new move_irqs vintc_ops callback. Wire it up in vAPLIC, which delegates to imsic_migrate_vcpu() which itself still a stub to be implemented in follow-up patches.

[...]

Signature · 1 line
Baptiste Le Duc <[email protected]>
#195 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

In reply to Oleksii Kurochko
Quoted 17 lines · Oleksii Kurochko
Quoted 6 lines · Jan Beulich

On 27.08.2026 17:21, Oleksii Kurochko wrote:

Hmm. As indicated, I'm learning RISC-V as I'm reviewing patches. This paragraph, if left as is, would make sure I simply can't ack the patch. I just don't understand what is being talked about. I can guess parts, but for example I don't know what "genmsi" is.

I will reword then commit message in the following way:

```
When a vCPU is moved to a different guest interrupt file, MSIs that the APLIC has already sent towards the old file may still be in flight. They must land before the old file's state is saved and the switch is done, otherwise they would be lost.

Quoted 3 lines

To wait for them, use the APLIC's genmsi register. Writing it makes the APLIC itself send an MSI (an "extempore" MSI) with a given interrupt identity to a given hart. genmsi can only target the hart's supervisor-

Nit: supervisor = hypervisor in our pov

Quoted 29 lines

level interrupt file, not a guest one, but the AIA spec guarantees that all MSIs previously sent by the same APLIC to the same hart become visible at the hart's IMSIC before the extempore MSI does. So once the extempore MSI has been delivered, no older MSI from this APLIC to the hart can still be in flight, whichever interrupt file it targets.

The last interrupt identity (nr_ids) is reserved for this purpose. ```

Quoted 2 lines

Along the lines of a question on an earlier patch: What if this ANDing actually chops off bits?

I will do then the same as I did in aplic_set_irq_affinity() (i mentioned that in the one of the replies connected to this function in this patch series):

     /*
      * sync_id is nr_ids, which imsic_parse_node() limits to IMSIC_MAX_ID,
      * so it always fits into the EIID field.
      */
     BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
     ASSERT(imsic->sync_id <= IMSIC_MAX_ID);

     val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
           imsic->sync_id;

Thanks.

~ Oleksii

#197 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

In reply to Baptiste Le Duc
Quoted 59 lines · Baptiste Le Duc
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +16 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
  #include <asm/imsic.h>
  #include <asm/intc.h>
  #include <asm/io.h>
+#include <asm/processor.h>
  #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
 
  static struct aplic_priv aplic = {
      .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
      spin_unlock_irqrestore(&aplic.lock, flags);
  }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 235

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

Quoted 7 lines

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay). Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to provide.

It is really missed but it exists in riscv-next-upstream branch (https://gitlab.com/xen-project/people/olkur/xen/-/blob/riscv-next-upstreaming/xen/arch/riscv/imsic.c#L723).

I will re-check why it is missed here.

Thanks for noticing that.

~ Oleksii

#198 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 67 lines · Oleksii Kurochko
Quoted 64 lines · Baptiste Le Duc
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +5 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
   #include <asm/imsic.h>
   #include <asm/intc.h>
   #include <asm/io.h>
+#include <asm/processor.h>
   #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
   static struct aplic_priv aplic = {
       .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, 
 uint32_t value)
       spin_unlock_irqrestore(&aplic.lock, flags);
   }
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this 

step.
+ */

xen/arch/riscv/aplic.c +10 -0
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 233

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Quoted 8 lines
Quoted 4 lines

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay). Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to provide.

It is really missed but it exists in riscv-next-upstream branch (https://gitlab.com/xen-project/people/olkur/xen/-/blob/riscv-next- upstreaming/xen/arch/riscv/imsic.c#L723).

I will re-check why it is missed here.

Step 1 and step 6 are not missing, they are just not part of
aplic_genmsi_barrier() itself. They are done by its caller, which is added in "xen/riscv: remap interrupts to new IMSIC VS-file":

    static void cf_check imsic_aplic_sync(void *unused)
    {
        imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);

        aplic_genmsi_barrier();

        while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
            cpu_relax();
    }

I did consider doing all six steps inside aplic_genmsi_barrier(), but that would make aplic.c reach into IMSIC internals (the local EIx CSR accessors, which are private to imsic.c), and I would rather not add that dependency. Keeping the APLIC half (write genmsi, wait for Busy to clear) in aplic.c and the IMSIC half (clear the pending bit of sync_id before, poll it until set afterwards) in imsic.c keeps the layering clean.

You are right, though, that nothing in this patch says so, and that the
helper on its own is not the full barrier its name suggests. I will spell the split out in the commit message and in the comment above the function.

Probably it will be better to introduce function imsic_aplic_sync() as a part of this patch.

~ Oleksii

#199 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 108 lines · Oleksii Kurochko
Quoted 78 lines · Oleksii Kurochko
Quoted 66 lines · Baptiste Le Duc
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +5 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
   #include <asm/imsic.h>
   #include <asm/intc.h>
   #include <asm/io.h>
+#include <asm/processor.h>
   #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
   static struct aplic_priv aplic = {
       .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, 
 uint32_t value)
       spin_unlock_irqrestore(&aplic.lock, flags);
   }
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this 

step.
+ */

xen/arch/riscv/aplic.c +10 -0
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 233

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Quoted 8 lines

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay).
Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to
provide.

Quoted 5 lines

It is really missed but it exists in riscv-next-upstream branch
(https://gitlab.com/xen-project/people/olkur/xen/-/blob/riscv-next-
upstreaming/xen/arch/riscv/imsic.c#L723).

I will re-check why it is missed here.

Step 1 and step 6 are not missing, they are just not part of aplic_genmsi_barrier() itself. They are done by its caller, which is added in "xen/riscv: remap interrupts to new IMSIC VS-file":

     static void cf_check imsic_aplic_sync(void *unused)
     {
         imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);

         aplic_genmsi_barrier();

         while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
             cpu_relax();
     }

I did consider doing all six steps inside aplic_genmsi_barrier(), but that would make aplic.c reach into IMSIC internals (the local EIx CSR accessors, which are private to imsic.c), and I would rather not add that dependency. Keeping the APLIC half (write genmsi, wait for Busy to clear) in aplic.c and the IMSIC half (clear the pending bit of sync_id before, poll it until set afterwards) in imsic.c keeps the layering clean.

Quoted 7 lines

You are right, though, that nothing in this patch says so, and that the helper on its own is not the full barrier its name suggests. I will spell the split out in the commit message and in the comment above the function.

Probably it will be better to introduce function imsic_aplic_sync() as a part of this patch.

Yes it would make sense as function imsic_aplic_sync() is introduced in next patch so reviewer couldn't know the existence of it when reading this patch. Thanks for that!

Quoted 5 lines

~ Oleksii

#205 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 25 lines

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU

first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Quoted 6 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

"will be introduced later" would be stale in the future.

Quoted 76 lines
xen/arch/riscv/imsic.c +28 -0
index 5de4594961..5e9f6995e4 100644
@@ -27,6 +27,7 @@
 #include <xen/xvmalloc.h>
 
 #include <asm/aia.h>
+#include <asm/aplic.h>
 #include <asm/imsic.h>
 
 #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
 #define IMSIC_DISABLE_EITHRESHOLD   1
 #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
 #define imsic_csr_write(c, v)   \
 do {                            \
     csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
 }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
 void __init imsic_ids_local_delivery(bool enable)
 {
     if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
     spin_unlock(&imsic_cfg.lock);
 }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
 /* Callers aren't intended to changed imsic_cfg so return const. */
 const struct imsic_config *imsic_get_config(void)
 {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
     /* Nothing to do */
 }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
 int cf_check vcpu_imsic_init(struct vcpu *v)
 {
     struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
         on_selected_cpus(cpumask_of(cpu), func, data, 1);
 }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

It seems data arg is not used here

Quoted 49 lines
xen/arch/riscv/imsic.c +27 -0
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
 static void cf_check imsic_vsfile_local_clear(void *data)
 {
     unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
     struct imsic_vsfile_data vsfile_data = {
         .nr_eix = nr_hw_eix,
     };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
     /*
      * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == NR_CPUS )
         return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
     /*
      * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
      * VS-file.
      */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Zero-out new IMSIC VS-file */
     imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 946

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+

This gets rewritten later in the series by "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu", which moves the clear/map/update sequence into imsic_vsfile_acquire() (and adds vgein_release() on the error path).

Could imsic_vsfile_acquire() be introduced here (or in a prep patch) instead, so that the later patch only adds imsic_vsfile_attach()? That would avoid the churn.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#214 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

In reply to Oleksii Kurochko
Quoted 1 line

At the old interrupt file, dump to memory all the eip and eie arrays).

Typo )

Quoted 10 lines

After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to

The sentence miss a verb, here is a proposal:

```
There are cases where the cpu on which the VGEIN is released needs to
be specified, so update vgein_release() to deal with that.
```

Moreover, could you explain me the cases you are talking about? It's not clear by reading the commit message in the first place.

Quoted 55 lines

deal with that.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard

against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

xen/arch/riscv/aia.c +5 -0
index 75c82bcfa1..be3901ec0c 100644
@@ -30,3 +30,8 @@ unsigned int vgein_assign(struct vcpu *v)
 
     return 0;
 }
+
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
+{
+    BUG_ON("unimplemented\n");
+}
xen/arch/riscv/imsic.c +10 -0
index 5e9f6995e4..3cba58e0c1 100644
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
  */
 #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))
 
 
+
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 76

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
 
 
+};
+
+struct imsic_mrif {
+    struct imsic_mrif_eix eix[IMSIC_MAX_EIX];
+    unsigned long eithreshold;
+    unsigned long eidelivery;
+};
+

Maybe I didn't get something but I couldn't find anything in the commit message explaining why do we use mrif here.

Moreover, mrif, as described in aia spec (8.3 Memory-resident interrupt files), seems to be only usable with IOMMU that Xen doesn't support.

If you want to have something in memory that could store some interrupt file info, we should take another name to not be confusing.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#208 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 1 line

xen/riscv: remap interrupts to new IMSIC VS-file

Nit: The next patch uses "restore" in its title, we might want to use "save" terminology here for symmetry? e.g.:
"xen/riscv: save old interrupt file state to memory"

Quoted 229 lines · Oleksii Kurochko

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

---
Changes in v2:
- New patch.
---

---
  xen/arch/riscv/imsic.c             | 103 +++++++++++++++++++++++++++++
  xen/arch/riscv/include/asm/imsic.h |   3 +
  2 files changed, 106 insertions(+)
xen/arch/riscv/imsic.c +103 -0
index 5de45949610d..5e9f6995e443 100644
@@ -27,6 +27,7 @@
  #include <xen/xvmalloc.h>
 
  #include <asm/aia.h>
+#include <asm/aplic.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
  #define imsic_csr_write(c, v)   \
  do {                            \
      csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
  }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
  void __init imsic_ids_local_delivery(bool enable)
  {
      if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
  /* Callers aren't intended to changed imsic_cfg so return const. */
  const struct imsic_config *imsic_get_config(void)
  {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
      /* Nothing to do */
  }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
  int cf_check vcpu_imsic_init(struct vcpu *v)
  {
      struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
  static void cf_check imsic_vsfile_local_clear(void *data)
  {
      unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
      struct imsic_vsfile_data vsfile_data = {
          .nr_eix = nr_hw_eix,
      };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);
+
+    /*
+     * Synchronizing interactions between a hart and the APLIC.
+     *
+     * The MSIs to be flushed are the ones still on their way to the old
+     * interrupt file, so the barrier has to be done by the pCPU which owns
+     * that file.
+     */
+    imsic_call_on_cpu(old_vsfile_cpu, imsic_aplic_sync, NULL);
+
+    /*
+     * At this point, all interrupt producers have been moved
+     * to the new IMSIC VS-file.
+     */
+
      BUG_ON("unimplemented");
  }
xen/arch/riscv/include/asm/imsic.h +3 -0
index 6ea2e4b8ca12..6395b539c52d 100644
@@ -114,12 +114,15 @@ void imsic_ids_local_delivery(bool enable);
  int vcpu_imsic_init(struct vcpu *v);
  void vcpu_imsic_deinit(struct vcpu *v);
  unsigned int vcpu_guest_file_id(const struct vcpu *v);
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id);
 
  int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
  void imsic_ctxt_switch_from(struct vcpu *v);
  void imsic_ctxt_switch_to(struct vcpu *v);
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
+
  void imsic_migrate_vcpu(struct vcpu *v);
 
  #endif /* ASM_RISCV_IMSIC_H */
#221 lore raw

Re: [PATCH v2 34/39] xen/riscv: restore register state in the new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 82 lines

At this point, all interrupt producers have been moved to the new IMSIC VS-file so we move register state from the old IMSIC VS/SW-file to the new IMSIC VS-file.

As new IMSIC VS-file is ready to be used update vCPU's hstatus with new VGEIN.

As the whole migration procedure is finished add some extra explanatory comments.

xen/arch/riscv/imsic.c +23 -4
index 3cba58e0c1..d7b137a1f5 100644
@@ -112,6 +112,12 @@ do {                            \
     r_;                             \
 })
 
+#define imsic_vs_csr_set(c, v)      \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_set(CSR_VSIREG, (v));       \
+} while ( 0 )
+
 #define imsic_vs_csr_write(c, v)    \
 do {                                \
     csr_write(CSR_VSISELECT, (c));  \
@@ -185,6 +191,19 @@ static void imsic_eix_write(unsigned int ireg, unsigned long val)
     }
 }
 
+static void imsic_eix_set(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_set, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_set, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+
 unsigned int vcpu_guest_file_id(const struct vcpu *v)
 {
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
     new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
 
 
     csr_write(CSR_HSTATUS, new_hstatus);
 
     /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
      */

 
     mrif->eidelivery = imsic_vs_csr_swap(IMSIC_EIDELIVERY, 0);
xen/arch/riscv/imsic.c +7 -0
@@ -972,6 +991,49 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
     return fdt_end_node(fdt);
 }
 
+static void cf_check imsic_vsfile_local_update(void *data)
+{
+    unsigned int i;
+    struct imsic_mrif_eix *eix;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 1010

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*
+     * No atomic accessors are needed to read the values out of the MRIF here,
+     * as this is always called with a pointer to a temporary MRIF on the
+     * stack.
+     */

idata->mrif may point anywhere, so what the comment really states is a requirement on callers. It also only makes full sense next to KVM, where a shared SW-file MRIF is accessed atomically; Xen has neither of those (yet). Either explicitely explain that callers must declare mrif on their stack or move the comment directly in call sites.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#206 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Baptiste Le Duc
Quoted 25 lines · Baptiste Le Duc
Quoted 25 lines

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU

first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Quoted 7 lines
Quoted 6 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

"will be introduced later" would be stale in the future.

I will drop that part from the commit message.

Quoted 74 lines
Quoted 74 lines
xen/arch/riscv/imsic.c +26 -0
index 5de4594961..5e9f6995e4 100644
@@ -27,6 +27,7 @@
  #include <xen/xvmalloc.h>
 
  #include <asm/aia.h>
+#include <asm/aplic.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
  #define imsic_csr_write(c, v)   \
  do {                            \
      csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
  }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
  void __init imsic_ids_local_delivery(bool enable)
  {
      if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
  /* Callers aren't intended to changed imsic_cfg so return const. */
  const struct imsic_config *imsic_get_config(void)
  {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
      /* Nothing to do */
  }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
  int cf_check vcpu_imsic_init(struct vcpu *v)
  {
      struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
Quoted 13 lines

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 12 lines
xen/arch/riscv/imsic.c +12 -0
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

It seems data arg is not used here

It will be renamed to unused in the v3 but we still need to have it becuase how this function is called through imsic_call_on_cpu().

Quoted 63 lines
Quoted 49 lines
xen/arch/riscv/imsic.c +27 -0
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
  static void cf_check imsic_vsfile_local_clear(void *data)
  {
      unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
      struct imsic_vsfile_data vsfile_data = {
          .nr_eix = nr_hw_eix,
      };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 946

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+

This gets rewritten later in the series by "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu", which moves the clear/map/update sequence into imsic_vsfile_acquire() (and adds vgein_release() on the error path).

Quoted 4 lines

Could imsic_vsfile_acquire() be introduced here (or in a prep patch) instead, so that the later patch only adds imsic_vsfile_attach()? That would avoid the churn.

It could, I just thought that it will be easier to justify necessity of it by introduction in "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu". But I am okay to move it to this patch.

Thanks.

~ Oleksii

#209 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Baptiste Le Duc
Quoted 5 lines · Baptiste Le Duc
Quoted 1 line

xen/riscv: remap interrupts to new IMSIC VS-file

Nit: The next patch uses "restore" in its title, we might want to use "save" terminology here for symmetry? e.g.:
    "xen/riscv: save old interrupt file state to memory"

Not only saving old interrupt file state happens here but also moving of all interrupts to new IMSIC VS-file. That why remap sounds okay here to me. If it is Nit: and no one else are against that I prefer to still have the commit subject as it is written now.

~ Oleksii