Skip to contentSkip to conversation

xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64()

PATCH In review Oleksii Kurochko 3 participants 52 messages Nov 13 – Nov 27 1 message not in the archive RISC-V

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): [email protected]

#1 lore raw

PATCH v4 1/42 xen/riscv: add helper to check APLIC MSI mode

Use convenient helper instead of open-coding the things.

---
Changes in v4:
- Nothing changed. Only move this patch first in patch series to merge it faster.
---
Changes in v3:
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
- Add Acked-by: Jan Beulich <[email protected]>.
---
Changes in v2:
- Rename helper.
- Update the commit message.
---

---
 xen/arch/riscv/aplic.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
xen/arch/riscv/aplic.c +7 -2
index 17c96177a3b1..79bbc0e864d5 100644
@@ -38,6 +38,11 @@ static struct intc_info __ro_after_init aplic_info = {
     .hw_variant = INTC_APLIC,
 };
 
+static bool aplic_msi_mode(void)
+{
+    return readl(&aplic.regs->domaincfg) & APLIC_DOMAINCFG_DM;
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
@@ -130,7 +135,7 @@ static void cf_check aplic_irq_enable(struct irq_desc *desc)
      *       If APLIC without MSI interrupts is required in the future,
      *       this function will need to be updated accordingly.
      */
-    ASSERT(readl(&aplic.regs->domaincfg) & APLIC_DOMAINCFG_DM);
+    ASSERT(aplic_msi_mode());
 
     ASSERT(spin_is_locked(&desc->lock));
 
@@ -161,7 +166,7 @@ static void cf_check aplic_irq_disable(struct irq_desc *desc)
      *       If APLIC without MSI interrupts is required in the future,
      *       this function will need to be updated accordingly.
      */
-    ASSERT(readl(&aplic.regs->domaincfg) & APLIC_DOMAINCFG_DM);
+    ASSERT(aplic_msi_mode());
 
     ASSERT(spin_is_locked(&desc->lock));
 
Signature · 1 line
2.56.1
#2 lore raw

PATCH v4 2/42 xen/riscv: address violation of MISRA C Rule 20.12 in csr_write64()

In reply to a message not in the archive

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

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

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

No functional change.

---
Changes in v4:
- New patch.
---

---
 xen/arch/riscv/include/asm/csr.h | 16 ++++++----------
 xen/arch/riscv/time.c            |  4 ++--
 2 files changed, 8 insertions(+), 12 deletions(-)
xen/arch/riscv/include/asm/csr.h +6 -10
index a805f7ed0ba1..3cf8e1857ce2 100644
@@ -33,18 +33,14 @@
 })
 
 #ifdef CONFIG_RISCV_32
-#define csr_write64(csr, val)       \
-({                                  \
-    uint64_t v_ = (val);            \
-    csr_write(csr, v_);             \
-    csr_write(csr ## H, v_ >> 32);  \
+#define csr_write64(name, val)              \
+({                                          \
+    uint64_t v_ = (val);                    \
+    csr_write(CSR_ ## name, v_);            \
+    csr_write(CSR_ ## name ## H, v_ >> 32); \
 })
 #else
-#define csr_write64(csr, val)       \
-({                                  \
-    csr_write(csr, val);            \
-    (void)csr ## H;                 \
-})
+#define csr_write64(name, val) csr_write(CSR_ ## name, val)
 #endif
 
 #define csr_swap(csr, val)                                      \
xen/arch/riscv/time.c +2 -2
index 782d9cd450f3..97ebe402ae41 100644
@@ -15,7 +15,7 @@ uint64_t __ro_after_init boot_clock_cycles;
 
 static int cf_check sstc_set_xen_timer(uint64_t deadline)
 {
-    csr_write64(CSR_STIMECMP, deadline);
+    csr_write64(STIMECMP, deadline);
 
     return 0;
 }
@@ -103,6 +103,6 @@ void __init preinit_xen_time(void)
          * Thereby to avoid spurious VS-timer irqs set vstimecmp CSR to
          * ~0.
          */
-        csr_write64(CSR_VSTIMECMP, ~0);
+        csr_write64(VSTIMECMP, ~0);
     }
 }
Signature · 1 line
2.56.1
Reviewed-by on v4 2/42
#3 lore raw
Quoted 9 lines · Oleksii Kurochko

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

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

[...]

Signature · 1 line
Baptiste Le Duc <[email protected]>
Acked-by
#4 lore raw
Quoted 6 lines · Baptiste Le Duc
Quoted 5 lines · Oleksii Kurochko

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

Quoted 6 lines
Quoted 4 lines

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

[...]

#5 lore raw

PATCH v4 3/42 xen/riscv: introduce csr_volatile_read64()

In reply to a message not in the archive

On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading the halves with two separate instructions isn't always safe: for a CSR which hardware increments, a carry from the low half into the high one can happen in between, so a plain pair of reads can produce a value the CSR never held. Therefore the high half is re-read and the sequence retried if it changed in the meantime.

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

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

No functional change on RV64.

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

---
Changes in v4:
- Take the CSR name without the CSR_ prefix, so that the macro parameter is used as an operand of ## only (MISRA C Rule 20.12).
- Drop the (void) of the ...H constant on RV64.
- Initialise hi_ in its declaration.
---
Changes in v3:
- Rename csr_read64() to csr_volatile_read64(): only CSRs which change under Xen's feet need the retry, the majority can be read with a plain split access, which isn't introduced here as it would have no user.
- Carry the high half read at the end of an iteration over to the next one, instead of reading it twice per retry.
- Update the commit message.
---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/include/asm/csr.h  | 22 ++++++++++++++++++++++
 xen/arch/riscv/include/asm/time.h |  4 ++--
 2 files changed, 24 insertions(+), 2 deletions(-)
xen/arch/riscv/include/asm/csr.h +22 -0
index 3cf8e1857ce2..6df595e810ef 100644
@@ -39,8 +39,30 @@
     csr_write(CSR_ ## name, v_);            \
     csr_write(CSR_ ## name ## H, v_ >> 32); \
 })
+
+/*
+ * The two halves are read by separate instructions, so a CSR which hardware
+ * increments can carry from the low half into the high one in between,
+ * yielding a value the CSR never held. Re-read the high half and retry the
+ * sequence if it changed.
+ *
+ * Only needed for CSRs which change under Xen's feet.
+ */
+#define csr_volatile_read64(name)                            \
+({                                                           \
+    uint32_t lo_, old_, hi_ = csr_read(CSR_ ## name ## H);   \
+                                                             \
+    do {                                                     \
+        old_ = hi_;                                          \
+        lo_ = csr_read(CSR_ ## name);                        \
+    } while ( (hi_ = csr_read(CSR_ ## name ## H)) != old_ ); \
+                                                             \
+    ((uint64_t)hi_ << 32) | lo_;                             \
+})
 #else
 #define csr_write64(name, val) csr_write(CSR_ ## name, val)
+
+#define csr_volatile_read64(name) csr_read(CSR_ ## name)
 #endif
 
 #define csr_swap(csr, val)                                      \
xen/arch/riscv/include/asm/time.h +2 -2
index 0e5b96a8631c..02b9a03ed90d 100644
@@ -18,11 +18,11 @@ static inline void force_update_vcpu_system_time(struct vcpu *v)
     BUG_ON("unimplemented");
 }
 
-typedef unsigned long cycles_t;
+typedef uint64_t cycles_t;
 
 static inline cycles_t get_cycles(void)
 {
-    return csr_read(CSR_TIME);
+    return csr_volatile_read64(TIME);
 }
 
 void preinit_xen_time(void);
Signature · 1 line
2.56.1
Reviewed-by on v4 3/42
#6 lore raw

Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()

Quoted 17 lines

On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading the halves with two separate instructions isn't always safe: for a CSR which hardware increments, a carry from the low half into the high one can happen in between, so a plain pair of reads can produce a value the CSR never held. Therefore the high half is re-read and the sequence retried if it changed in the meantime.

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

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

No functional change on RV64.

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

---
Changes in v4:
- Take the CSR name without the CSR_ prefix, so that the macro parameter is used as an operand of ## only (MISRA C Rule 20.12).
- Drop the (void) of the ...H constant on RV64.
- Initialise hi_ in its declaration.

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

Review

Quoted 5 lines

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

(quoted diff) +2 -0
+
+#define csr_volatile_read64(name) csr_read(CSR_ ## name)

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

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

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

Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()

Quoted 40 lines · Baptiste Le Duc
Quoted 17 lines

On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading the halves with two separate instructions isn't always safe: for a CSR which hardware increments, a carry from the low half into the high one can happen in between, so a plain pair of reads can produce a value the CSR never held. Therefore the high half is re-read and the sequence retried if it changed in the meantime.

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

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

No functional change on RV64.

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

---
Changes in v4:
- Take the CSR name without the CSR_ prefix, so that the macro parameter is used as an operand of ## only (MISRA C Rule 20.12).
- Drop the (void) of the ...H constant on RV64.
- Initialise hi_ in its declaration.

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

Review

Quoted 5 lines

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

(quoted diff) +2 -0
+
+#define csr_volatile_read64(name) csr_read(CSR_ ## name)

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

Quoted 3 lines

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

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

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

Jan

Acked-by
#8 lore raw

Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()

Quoted 45 lines · Jan Beulich
Quoted 40 lines · Baptiste Le Duc
Quoted 17 lines

On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading the halves with two separate instructions isn't always safe: for a CSR which hardware increments, a carry from the low half into the high one can happen in between, so a plain pair of reads can produce a value the CSR never held. Therefore the high half is re-read and the sequence retried if it changed in the meantime.

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

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

No functional change on RV64.

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

---
Changes in v4:
- Take the CSR name without the CSR_ prefix, so that the macro parameter is used as an operand of ## only (MISRA C Rule 20.12).
- Drop the (void) of the ...H constant on RV64.
- Initialise hi_ in its declaration.

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

Review

Quoted 5 lines

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

(quoted diff) +2 -0
+
+#define csr_volatile_read64(name) csr_read(CSR_ ## name)

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

Quoted 3 lines

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

Quoted 8 lines

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

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

Oh, and - happy to fold this in while committing (perhaps with an adjustment to subject and description), if you agree. With that

Jan

#9 lore raw

Re: [PATCH v4 03/42] xen/riscv: introduce csr_volatile_read64()

Quoted 55 lines · Jan Beulich
Quoted 45 lines · Jan Beulich
Quoted 40 lines · Baptiste Le Duc
Quoted 17 lines

On RV32 a 64-bit CSR is accessed as two halves, <csr> and <csr>H. Reading the halves with two separate instructions isn't always safe: for a CSR which hardware increments, a carry from the low half into the high one can happen in between, so a plain pair of reads can produce a value the CSR never held. Therefore the high half is re-read and the sequence retried if it changed in the meantime.

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

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

No functional change on RV64.

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

---
Changes in v4:
- Take the CSR name without the CSR_ prefix, so that the macro parameter is used as an operand of ## only (MISRA C Rule 20.12).
- Drop the (void) of the ...H constant on RV64.
- Initialise hi_ in its declaration.

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

Review

Quoted 5 lines

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

(quoted diff) +2 -0
+
+#define csr_volatile_read64(name) csr_read(CSR_ ## name)

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

Quoted 3 lines

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

Quoted 8 lines

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

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

Quoted 3 lines

Oh, and - happy to fold this in while committing (perhaps with an adjustment to subject and description), if you agree. With that

Sorry, for the so long response.

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

Thanks.

~ Oleksii

#10 lore raw

PATCH v4 4/42 xen/riscv: define the IPRIO field of the APLIC target register

In reply to a message not in the archive

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

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

No functional change.

---
Changes in v4:
- New patch, split out of "xen/riscv: implement virtual APLIC MMIO emulation".
---

---
 xen/arch/riscv/aplic.c             | 6 ++----
 xen/arch/riscv/include/asm/aplic.h | 4 ++++
 2 files changed, 6 insertions(+), 4 deletions(-)
xen/arch/riscv/aplic.c +2 -4
index 79bbc0e864d5..bffa29bb21ac 100644
@@ -28,8 +28,6 @@
 #include <asm/io.h>
 #include <asm/riscv_encoding.h>
 
-#define APLIC_DEFAULT_PRIORITY  1
-
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
 };
@@ -58,9 +56,9 @@ static void __init aplic_init_hw_interrupts(void)
         /*
          * Low bits of target register contains Interrupt Priority bits which
          * can't be zero according to AIA spec.
-         * Thereby they are initialized to APLIC_DEFAULT_PRIORITY.
+         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
          */
-        writel(APLIC_DEFAULT_PRIORITY, &aplic.regs->target[i]);
+        writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
     }
 
     writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);
xen/arch/riscv/include/asm/aplic.h +4 -0
index 51be469b69e5..6afdb9cae7a2 100644
@@ -86,9 +86,13 @@
 #define APLIC_TARGET_LAST               0x3ffc
 #define  APLIC_TARGET_HART_IDX          GENMASK(31, 18)
 #define  APLIC_TARGET_HART_IDX_SHIFT    18
+/* If target is in MSI delivery mode (domaincfg.DM = 1) */
 #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
 /* Bit 11 is reserved and reads as zero */
 #define  APLIC_TARGET_EIID              GENMASK(10, 0)
+/* If target is in direct delivery mode (domaincfg.DM = 0) */
+#define  APLIC_TARGET_IPRIO             GENMASK(7, 0)
+#define   APLIC_TARGET_IPRIO_DEFAULT    1U
 
 #define APLIC_IDC_SIZE                  32
 
Signature · 1 line
2.56.1
#11 lore raw

Re: [PATCH v4 04/42] xen/riscv: define the IPRIO field of the APLIC target register

Quoted 7 lines

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

Quoted 8 lines

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

No functional change.

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

Quoted 17 lines

[ ... 10 lines skipped ... ]

xen/arch/riscv/aplic.c +0 -2
index 79bbc0e864..bffa29bb21 100644
@@ -28,8 +28,6 @@
 #include <asm/io.h>
 #include <asm/riscv_encoding.h>
 
-#define APLIC_DEFAULT_PRIORITY  1
-
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
 };
@@ -58,9 +56,9 @@ static void __init aplic_init_hw_interrupts(void)
         /*

xen/arch/riscv/aplic.c static void __init aplic_init_hw_interrupts(void) · line 64

Quoted 10 lines
xen/arch/riscv/aplic.c +2 -2
          * Low bits of target register contains Interrupt Priority bits which
          * can't be zero according to AIA spec.
-         * Thereby they are initialized to APLIC_DEFAULT_PRIORITY.
+         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
          */
-        writel(APLIC_DEFAULT_PRIORITY, &aplic.regs->target[i]);
+        writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
     }
 
     writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);

Furthermore, is the write needed at all? sourcecfg[i] is set to 0 just above, i.e. D = 0 and SM = Inactive, and AIA 4.5.16 says: "If interrupt source i is inactive in this domain, register target[i] is read-only zero." So the write is ignored. Also, domaincfg.DM is forced to 1 (MSI delivery mode) right after, where IPRIO does not exist and the low bits are EIID. As Xen doesn't use direct delivery mode, is a default priority needed at all? (Btw, a comment saying that MSI mode is forced there would help.)

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

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

@@ -222,21 +222,18 @@ static void __init aplic_init_hw_interrupts(void)

 {
     unsigned int i;

- /* Disable all interrupts */
- for ( i = 0; i < ARRAY_SIZE(aplic.regs->clrie); i++)
- writel(~0U, &aplic.regs->clrie[i]);
+ /*

+     * Stop delivery so that no source left active by firmware can raise
+     * an interrupt while the sources are being made inactive.
+     */

+ writel(0, &aplic.regs->domaincfg);

- /* Set interrupt type and default priority for all interrupts */
+ /*

+     * Make all sources inactive by writing 0 to sourcecfg[i]. Per the AIA
+     * spec, target[i] then becomes read-only zero.
+     */
     for ( i = 0; i < aplic_info.num_irqs; i++ )
-    {
         writel(0, &aplic.regs->sourcecfg[i]);
-        /*
-         * Low bits of target register contains Interrupt Priority bits which
-         * can't be zero according to AIA spec.
-         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
-         */

- writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
- }

     writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);

}

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

PATCH v4 5/42 xen/riscv: build the target hart index via aplic_hart_index()

In reply to a message not in the archive

aplic_set_irq_affinity() computes the target register value by hand:

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

This is wrong in three ways:

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

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

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

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

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

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

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

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

---
 xen/arch/riscv/aplic.c             | 117 +++++++++++++++++++++++------
 xen/arch/riscv/include/asm/aplic.h |  10 ++-
 2 files changed, 103 insertions(+), 24 deletions(-)
xen/arch/riscv/aplic.c +94 -23
index bffa29bb21ac..29663bc29b7b 100644
@@ -41,6 +41,90 @@ static bool aplic_msi_mode(void)
     return readl(&aplic.regs->domaincfg) & APLIC_DOMAINCFG_DM;
 }
 
+/*
+ * The arrangement of IMSIC interrupt files in MMIO space follows a topology
+ * defined by the RISC-V AIA specification. An IMSIC group is a set of
+ * interrupt files (e.g., in a cluster or socket) co-located in memory.
+ *
+ * The physical address of an outgoing MSI is calculated by bitwise ORing a
+ * Base Physical Page Number (Base PPN) with the group number (g), the
+ * hart number relative to the group (h) and, for a supervisor-level
+ * interrupt domain, the Guest Index:
+ *
+ *   ( Base PPN | (g << (HHXS + 12)) | (h << LHXS) | Guest Index ) << 12
+ *
+ * where Base PPN, HHXS, LHXS, HHXW and LHXW come from the {m,s}msiaddrcfg[h]
+ * registers of the interrupt domain that sends the MSI:
+ *
+ * XLEN-1       HHXS+24          LHXS+12          12          0
+ * |            |                |                |           |
+ * ------------------------------------------------------------
+ * |xxxx|   g   |xxxxxxxx|   h   |xxxx|Guest Index|     0     |
+ * ------------------------------------------------------------
+ *
+ * - g: group number.
+ * - h: hart number relative to the group.
+ * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+ * - Guest Index: selects one of the 4 KiB pages right above the hart's own
+ *   supervisor-level file, i.e. it starts at bit 12; LHXS must therefore be
+ *   at least as large as the number of guest index bits.
+ * - Bits 11:0: always zero because IMSIC files are 4 KiB page-aligned.
+ *
+ * For wired interrupts in MSI delivery mode (domaincfg.DM = 1), the APLIC
+ * computes the MSI target address itself from the "Hart Index" field
+ * (bits 31:18) of the corresponding target[i] register. This 14-bit field
+ * holds both g and h:
+ *
+ * 13          lhxw+hhxw   lhxw       0
+ * |           |           |          |
+ * ------------------------------------
+ * |     0     |     g     |    h     |
+ * ------------------------------------
+ *
+ * - lhxw (Low Hart Index Width): the number of bits used for the hart number
+ *   within a group.
+ * - hhxw (High Hart Index Width): the number of bits used for the group
+ *   number; the remaining bits of the field must be zero.
+ *
+ * The Guest Index isn't a part of it: for a supervisor-level interrupt domain
+ * it has its own field (bits 17:12) in target[i].
+ *
+ * Because there are "xxxx" gaps (Base PPN bits) between the indices in the
+ * physical address (depending on HHXS and LHXS), software must extract the
+ * group and hart components separately and pack them into the APLIC-defined
+ * Hart Index format to ensure correct MSI targeting.
+ */
+static unsigned long aplic_hart_index(unsigned int cpu)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    const struct imsic_msi *msi = &imsic->msi[cpu];
+    /* Low Hart Index Shift */
+    unsigned int lhxs = imsic->guest_index_bits;
+    /* Low Hart Index Width */
+    unsigned int lhxw = imsic->hart_index_bits;
+    /* High Hart Index Width */
+    unsigned int hhxw = imsic->group_index_bits;
+    /* High Hart Index Shift */
+    unsigned int hhxs =
+        imsic->group_index_shift - APLIC_xMSICFGADDR_PPN_SHIFT * 2;
+    /*
+     * msi->base_addr is the base of the MMIO regset this CPU's interrupt
+     * files live in, and one regset can cover several harts; msi->offset
+     * selects this CPU's block inside it. The hart index bits are part of
+     * that offset, so both indexes have to be derived from the full address.
+     */
+    paddr_t target_addr = msi->base_addr + msi->offset;
+    unsigned long tppn = target_addr >> APLIC_xMSICFGADDR_PPN_SHIFT;
+    unsigned long g =
+        (tppn >> APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs)) &
+        APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw);
+    unsigned long h =
+        (tppn >> APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs)) &
+        APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw);
+
+    return (g << lhxw) | h;
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
@@ -207,10 +291,8 @@ static unsigned int aplic_get_cpu_from_mask(const cpumask_t *cpumask)
 
 static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask_t *mask)
 {
-    unsigned int cpu;
-    uint64_t group_index, base_ppn;
-    uint32_t hhxw, lhxw, hhxs, value;
-    const struct imsic_config *imsic = aplic.imsic_cfg;
+    unsigned int cpu = aplic_get_cpu_from_mask(mask);
+    uint32_t value;
 
     /*
      * TODO: Currently, APLIC is supported only with MSI interrupts.
@@ -223,27 +305,16 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
     ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
     /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
+     * desc->irq is used as the EIID as-is, which is only valid for APLIC
+     * sources: they are numbered 1..num_irqs, with at most ARRAY_SIZE(target).
      */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    BUILD_BUG_ON(ARRAY_SIZE(aplic.regs->target) >
+                 MASK_EXTR(~0U, APLIC_TARGET_EIID));
+    ASSERT(desc->irq && desc->irq <= aplic_info.num_irqs);
+
+    value = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
+            desc->irq;
 
     spin_lock(&aplic.lock);
 
xen/arch/riscv/include/asm/aplic.h +9 -1
index 6afdb9cae7a2..93f0033b52d0 100644
@@ -85,7 +85,6 @@
 #define APLIC_TARGET_BASE               0x3004
 #define APLIC_TARGET_LAST               0x3ffc
 #define  APLIC_TARGET_HART_IDX          GENMASK(31, 18)
-#define  APLIC_TARGET_HART_IDX_SHIFT    18
 /* If target is in MSI delivery mode (domaincfg.DM = 1) */
 #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
 /* Bit 11 is reserved and reads as zero */
@@ -102,6 +101,15 @@
 #define APLIC_SIZE(nr_cpus) \
     (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+#define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT
+
+#define APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw) (BIT(hhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs) \
+    ((hhxs) + APLIC_xMSICFGADDR_PPN_SHIFT)
+
+#define APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw) (BIT(lhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs) (lhxs)
+
 struct aplic_regs {
     uint32_t domaincfg;         /* 0x0000 */
     uint32_t sourcecfg[1023];   /* 0x0004 */
Signature · 1 line
2.56.1
Reviewed-by on v4 5/42
#13 lore raw

Re: [PATCH v4 05/42] xen/riscv: build the target hart index via aplic_hart_index()

Quoted 8 lines

[ ... 129 lines skipped ... ]

xen/arch/riscv/aplic.c +7 -0
+static unsigned long aplic_hart_index(unsigned int cpu)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    const struct imsic_msi *msi = &imsic->msi[cpu];
+    /* Low Hart Index Shift */
+    unsigned int lhxs = imsic->guest_index_bits;
+    /* Low Hart Index Width */

xen/arch/riscv/aplic.c static bool aplic_msi_mode(void) · line 113

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    unsigned int lhxw = imsic->hart_index_bits;
+    /* High Hart Index Width */
+    unsigned int hhxw = imsic->group_index_bits;
+    /* High Hart Index Shift */
+    unsigned int hhxs =
+        imsic->group_index_shift - APLIC_xMSICFGADDR_PPN_SHIFT * 2;
+    /*
+     * msi->base_addr is the base of the MMIO regset this CPU's interrupt
+     * files live in, and one regset can cover several harts; msi->offset
+     * selects this CPU's block inside it. The hart index bits are part of

Very small nit: too keep being consistant with above wording and with the spec, it should be better to use "The Hart Index bits are...." to not confuse with "h" again...

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

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

PATCH v4 6/42 xen/riscv: introduce CPU_NONE

In reply to a message not in the archive

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

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

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

---
CPU_NONE is also used later in this series:
- "xen/riscv: implement virtual APLIC MMIO emulation" checks vsfile_cpu against it to tell whether the target vCPU has a h/w guest interrupt file.
- "xen/riscv: implement vCPU context switching" initialises the new arch_vcpu.last_cpu with it.
- "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu", "xen/riscv: remap interrupts to new IMSIC VS-file" and "xen/riscv: save and clear the old IMSIC VS-file on vCPU migration" check vsfile_cpu against it to tell a vCPU without a h/w guest interrupt file.
- "xen/riscv: introduce imsic_migrate_vcpu()" checks vsfile_cpu against it to tell whether the vCPU has a h/w guest interrupt file to move.
---
Changes in v4:
- Switch hartid_to_cpuid() and pcpu_info[] over to CPU_NONE as well, and update the commit message accordingly.
- Add BUILD_BUG_ON(CPU_NONE < NR_CPUS) to smp_processor_id().
---
Changes in v3:
- New patch.
---

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

Re: [PATCH v4 06/42] xen/riscv: introduce CPU_NONE

Quoted 14 lines · Oleksii Kurochko

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

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

Quoted 1 line

[...]

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

PATCH v4 7/42 xen/riscv: introduce device-agnostic MMIO emulation dispatch

In reply to a message not in the archive

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

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

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

---
do_mmio() gets its first caller in "xen/riscv: add guest load emulation for trapped MMIO accesses" in this series.
---
Changes in v4:
- Put the opening brace of enum io_state on the same line as the enum's name.
- Drop the redundant else in try_handle_mmio().
- Allocate struct vmmio dynamically and make its definition, together with MAX_IO_HANDLER and struct mmio_handler, private to mmio.c, so that <asm/domain.h> doesn't need <asm/mmio.h> any more. As a result, domain_io_init() can fail again and domain_io_free() is reintroduced.
- Name the domain parameter of find_mmio_handler() currd (and constify it) and the vCPU variable of try_handle_mmio() curr, as both always refer to current.
- Drop the NULL check of ops and turn the checks of its callbacks into an ASSERT(), keeping -EINVAL for an empty or wrapping region.
---
Changes in v3:
- Update the commit message.
- Capitalize the comments inside mmio_info_t and drop the list of access widths from the one on len, as it could go stale.
- Drop the parentheses around the typedef names.
- Reject an access width which isn't a power of 2 in do_mmio().
- Fold the !size check of register_mmio_handler() into end <= addr.
- Return -EADDRINUSE instead of -EEXIST for an overlapping region.
- Drop setting d->arch.vmmio.num_entries to 0, as struct domain starts out zero-filled.
---
Changes in v2:
- Drop copyright from mmio.c as it will go stale anyway as code moves around.
- Drop the max_count parameter of domain_io_init() (MAX_IO_HANDLER is a global boundary) and embed the handler array directly in struct vmmio as struct mmio_handler handlers[MAX_IO_HANDLER]. This removes the xvzalloc_array() allocation, the max_num_entries field and domain_io_free() altogether; domain_io_init() consequently cannot fail any longer and now returns void. Note this goes slightly beyond the suggested variant in that max_num_entries is dropped as well, since ARRAY_SIZE(vmmio->handlers) serves the same purpose.
- Drop the separate register_t argument of mmio_read_t/mmio_write_t; handlers now produce and consume the value through info->data. handle_read()/handle_write() are gone as a result, with try_handle_mmio() invoking ops->read()/ops->write() directly.
- Turn mmio_read_t/mmio_write_t into function types rather than pointer-to-function types, so that pointer-ness is visible at the use sites in struct mmio_handler_ops. Constify the mmio_info_t * of the write callback, which has no reason to modify it any more.
- register_mmio_handler() returns int instead of BUG_ON()ing on a full
table: -ENOSPC now lets the caller fail domain creation. It also validates its inputs, rejecting a NULL ops (or one with a missing read/write callback) as well as zero-sized and address-wrapping regions with -EINVAL.
- Guarantee the non-overlap property that cmp_mmio_handler() relies on:
register_mmio_handler() checks the new region against both neighbours of its insertion slot and returns -EEXIST on overlap.
- Replace the sort() call per registration with an insertion into the already sorted array: locate the slot and memmove() the tail up by one. sort(), swap_mmio_handler() and <xen/sort.h> are gone.
- Extend cmp_mmio_handler()'s comment to state that it is a bsearch() comparator and to explain the key/elem asymmetry; document why the neighbours' addr + size cannot overflow.
- Fix over-long lines and a mis-indented label.
---

---
 xen/arch/riscv/Makefile             |   1 +
 xen/arch/riscv/domain.c             |   6 +
 xen/arch/riscv/include/asm/domain.h |   2 +
 xen/arch/riscv/include/asm/mmio.h   |  48 +++++++
 xen/arch/riscv/mmio.c               | 205 ++++++++++++++++++++++++++++
 5 files changed, 262 insertions(+)
 create mode 100644 xen/arch/riscv/include/asm/mmio.h
 create mode 100644 xen/arch/riscv/mmio.c
xen/arch/riscv/Makefile +1 -0
index 665ec2693335..5454517724bd 100644
@@ -14,6 +14,7 @@ obj-y += intc.o
 obj-y += irq.o
 obj-y += kernel.init.o
 obj-y += mm.o
+obj-y += mmio.o
 obj-y += p2m.o
 obj-y += paging.o
 obj-y += pt.o
xen/arch/riscv/domain.c +6 -0
index cfce8e91fa16..683c37c0ee5a 100644
@@ -12,6 +12,7 @@
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/intc.h>
+#include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
 #include <asm/vtimer.h>
 
@@ -294,6 +295,8 @@ void arch_domain_destroy(struct domain *d)
     printk(XENLOG_WARNING "%s: not fully implemented\n", __func__);
 
     domain_vintc_deinit(d);
+
+    domain_io_free(d);
 }
 
 int arch_domain_create(struct domain *d,
@@ -310,6 +313,9 @@ int arch_domain_create(struct domain *d,
     if ( (rc = p2m_init(d, config)) != 0)
         goto fail;
 
+    if ( (rc = domain_io_init(d)) )
+        goto fail;
+
     if ( (rc = domain_vintc_init(d)) )
         goto fail;
 
xen/arch/riscv/include/asm/domain.h +2 -0
index 98e5e72e58ba..8c48833353f5 100644
@@ -101,6 +101,8 @@ struct arch_domain {
     const unsigned long *isa;
 
     struct vintc *vintc;
+
+    struct vmmio *vmmio;
 };
 
 #include <xen/sched.h>
xen/arch/riscv/include/asm/mmio.h new file +48 -0

48 lines not on this page · raw message

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

205 lines not on this page · raw message

Signature · 1 line
2.56.1
Reviewed-by on v4 7/42
#17 lore raw

Re: [PATCH v4 07/42] xen/riscv: introduce device-agnostic MMIO emulation dispatch

Quoted 7 lines

[ ... 206 lines skipped ... ]

xen/arch/riscv/mmio.c new file +3 -0
@@ -0,0 +1,205 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <xen/bsearch.h>

xen/arch/riscv/mmio.c line 13

Quoted 10 lines
xen/arch/riscv/mmio.c new file +10 -0
+#include <xen/lib.h>
+#include <xen/rwlock.h>
+#include <xen/sched.h>
+#include <xen/string.h>
+#include <xen/xvmalloc.h>
+
+#include <asm/current.h>
+#include <asm/mmio.h>
+
+#define MAX_IO_HANDLER  16

Nit: Only one blank is needed here.

Quoted 10 lines

[ ... 70 lines skipped ... ]
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ *
+ * There is no "retry" outcome to handle: find_mmio_handler() returns a
+ * copy of the matching handler taken under vmmio->lock and the ops
+ * structures are never freed, so the lookup result cannot go stale
+ * between finding the handler and invoking it.
+ */

Nit: As do_mmio() is non-static, this comment would better live on its prototype in asm/mmio.h.

xen/arch/riscv/mmio.c line 146

Quoted 9 lines

[ ... 45 lines skipped ... ]

xen/arch/riscv/mmio.c new file +8 -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-- )

Nit: This fits on a single line.

Preferably with these adjusted:

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

PATCH v4 8/42 xen/riscv: distinguish h/w and virtual vINTC sources

In reply to a message not in the archive

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

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

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

---
More context on why the two kinds of sources have to be told apart is given by the patches relying on hw_irqs:
- "xen/riscv: implement virtual APLIC MMIO emulation", the next one, which accesses the registers of a source in the h/w APLIC only for a h/w source;
- "xen/riscv: introduce vaplic_reconfigure_target()", which retargets the h/w sources only;
- the patches introducing virtual sources to vAPLIC:
"xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE", "xen/riscv: emulate target[] of virtual vAPLIC sources", "xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC sources" and "xen/riscv: drive the line of a virtual vAPLIC source".
---
Changes in v4:
- New patch.
---

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

PATCH v4 9/42 xen/riscv: implement virtual APLIC MMIO emulation

In reply to a message not in the archive

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

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

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

---
The state of virtual sources, which devices emulated by Xen need, isn't emulated here. It is introduced at the end of this series, by "xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE", "xen/riscv: emulate target[] of virtual vAPLIC sources", "xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC sources" and "xen/riscv: drive the line of a virtual vAPLIC source".

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

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

---
 xen/arch/riscv/aplic-priv.h         |   2 +
 xen/arch/riscv/aplic.c              |  49 +++
 xen/arch/riscv/include/asm/aplic.h  |  28 +-
 xen/arch/riscv/include/asm/vaplic.h |  19 ++
 xen/arch/riscv/vaplic.c             | 504 +++++++++++++++++++++++++++-
 5 files changed, 591 insertions(+), 11 deletions(-)
xen/arch/riscv/aplic-priv.h +2 -0
index 009020c83fb9..9e85343cce0f 100644
@@ -47,4 +47,6 @@ struct aplic_priv {
  */
 extern unsigned int guest_aplic_num_sources;
 
+uint32_t aplic_msi_target_gen(const struct vcpu *v, uint32_t base_val);
+
 #endif /* RISCV_APLIC_PRIV_H */
xen/arch/riscv/aplic.c +49 -0

61 lines not on this page · raw message

xen/arch/riscv/include/asm/aplic.h +24 -4
index 93f0033b52d0..b2f1d140f6f8 100644
@@ -27,8 +27,6 @@
  * Blocks of related constants are sorted by register offset.
  */
 
-#define APLIC_CTRL_REGION_OFFSET_MASK       0x3fff
-
 #define APLIC_DOMAINCFG                     0x0000
 /*
  * domaincfg read-only fields (AIA spec):
@@ -39,6 +37,13 @@
 #define  APLIC_DOMAINCFG_IE             BIT(8, U)
 #define  APLIC_DOMAINCFG_DM             BIT(2, U)
 #define  APLIC_DOMAINCFG_BE             BIT(0, U)
+/*
+ * The bits a write may change. DM is WARL and hardwired to 1 as only MSI
+ * delivery mode is emulated. Everything else, including the read-only zero
+ * bit 7 and the reserved bits, has to read back as zero, and BE is WARL and
+ * hardwired to 0 as Xen is little-endian only.
+ */
+#define  APLIC_DOMAINCFG_WMASK          APLIC_DOMAINCFG_IE
 
 #define APLIC_SOURCECFG_BASE            0x0004
 #define APLIC_SOURCECFG_LAST            0x0ffc
@@ -59,6 +64,8 @@
 #define   APLIC_SOURCECFG_SM_LEVEL_HIGH 0x6
 #define   APLIC_SOURCECFG_SM_LEVEL_LOW  0x7
 
+#define APLIC_MMSICFGADDR               0x1bc0
+#define APLIC_MMSICFGADDRH              0x1bc4
 #define APLIC_SMSICFGADDR               0x1bc8
 #define APLIC_SMSICFGADDRH              0x1bcc
 
@@ -79,6 +86,7 @@
 #define APLIC_CLRIENUM                  0x1fdc
 
 #define APLIC_SETIPNUM_LE               0x2000
+#define APLIC_SETIPNUM_BE               0x2004
 
 #define APLIC_GENMSI                    0x3000
 
@@ -98,8 +106,17 @@
 #define APLIC_MIN_SIZE                  0x4000
 #define APLIC_SIZE_ALIGN(x)             ROUNDUP(x, APLIC_MIN_SIZE)
 
-#define APLIC_SIZE(nr_cpus) \
-    (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
+#define APLIC_SIZE(nr_idcs) \
+    (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_idcs)))
+
+/*
+ * Using setip is fine here, as all SET* and CLR* register groups consist of 32
+ * registers and therefore have identical sizes.
+ *
+ * Lowest 2 bits are always zero for SET* and CLR* registers.
+ */
+#define APLIC_SETCLR_OFFSET_MASK \
+    (sizeof_field(struct aplic_regs, setip) - sizeof(uint32_t))
 
 #define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT
 
@@ -153,4 +170,7 @@ struct aplic_regs {
     uint32_t target[1023];      /* 0x3004 */
 };
 
+uint32_t aplic_hw_read_reg(unsigned int offset);
+void aplic_hw_write_reg(unsigned int offset, uint32_t value);
+
 #endif /* RISCV_APLIC_H */
xen/arch/riscv/include/asm/vaplic.h +19 -0
index dcbe0d59a886..9a121904a346 100644
@@ -11,6 +11,7 @@
 #define RISCV_VAPLIC_H
 
 #include <xen/kernel.h>
+#include <xen/spinlock.h>
 #include <xen/types.h>
 
 #include <asm/intc.h>
@@ -19,13 +20,31 @@ struct domain;
 
 #define to_vaplic(d) container_of((d)->arch.vintc, struct vaplic, vintc)
 
+/* State of one vAPLIC interrupt source. */
+struct vaplic_source {
+    /* Protects target together with the h/w target register of the source. */
+    spinlock_t lock;
+
+    /* Guest's view of the APLIC target register. */
+    uint32_t target;
+};
+
 struct vaplic_regs {
     uint32_t domaincfg;
+
+    /*
+     * Indexed by source number. The array holds d->arch.vintc->nr_virqs
+     * elements; sources[0] is unused as APLIC interrupt sources start from 1.
+     */
+    struct vaplic_source *sources;
 };
 
 struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
+
+    paddr_t regs_start;
+    unsigned int regs_size;
 };
 
 int domain_vaplic_init(struct domain *d);
xen/arch/riscv/vaplic.c +497 -7

563 lines not on this page · raw message

Signature · 1 line
2.56.1
#20 lore raw

PATCH v4 10/42 xen/riscv: leave the h/w source of an IRQ routed to a guest inactive

In reply to a message not in the archive

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

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

---
This patch doesn't depend on the rest of the series, but what it prevents only shows up later in it:
- from "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu" on, the h/w target register of a guest's h/w source points at a real guest interrupt file, so a source left active could deliver an MSI there before the guest has configured it;
- "xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC sources" reads the h/w pending bits of h/w sources as they are, and these stay in line with the guest's view of the source being Inactive only if the h/w source is Inactive as well.
---
Changes in v4:
- New patch.
---

---
 xen/arch/riscv/intc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
xen/arch/riscv/intc.c +1 -1
index ac9c798ec36b..cdbc039d0258 100644
@@ -95,7 +95,7 @@ int intc_route_irq_to_guest(const struct domain *d, unsigned int virq,
     desc->handler = intc_hw_ops->guest_irq_type;
     desc->status |= IRQ_GUEST;
 
-    intc_set_irq_type(desc, desc->arch.type);
+    intc_set_irq_type(desc, IRQ_TYPE_NONE);
     intc_set_irq_priority(desc, priority);
 
     /* Connect @virq to the h/w IRQ: it isn't a virtual source. */
Signature · 1 line
2.56.1
#21 lore raw

PATCH v4 11/42 xen/riscv: implement vCPU context switching

In reply to a message not in the archive

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

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

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

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

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

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

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

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

---
 xen/arch/riscv/domain.c              | 118 ++++++++++++++++++++
 xen/arch/riscv/entry.S               |  48 ++++++++
 xen/arch/riscv/include/asm/csr.h     |   9 ++
 xen/arch/riscv/include/asm/domain.h  |  15 ++-
 xen/arch/riscv/include/asm/p2m.h     |   1 -
 xen/arch/riscv/include/asm/system.h  |   3 +
 xen/arch/riscv/p2m.c                 | 157 ++++++++++++++++++---------
 xen/arch/riscv/riscv64/asm-offsets.c |  19 +++-
 xen/arch/riscv/stubs.c               |   5 -
 xen/arch/riscv/traps.c               |   2 -
 10 files changed, 318 insertions(+), 59 deletions(-)
xen/arch/riscv/domain.c +118 -0
index 683c37c0ee5a..9feeaa59b887 100644
@@ -11,6 +11,7 @@
 #include <asm/bitops.h>
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
+#include <asm/current.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
@@ -152,6 +153,8 @@ int arch_vcpu_create(struct vcpu *v)
     if ( is_idle_vcpu(v) )
         return 0;
 
+    v->arch.last_cpu = CPU_NONE;
+
     vcpu_csr_init(v);
 
     if ( (rc = vcpu_vtimer_init(v)) )
@@ -326,6 +329,121 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+static void csrs_ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * hedeleg, hideleg, henvcfg, hcounteren, htimedelta and hstateen0 aren't
+     * saved: neither the guest nor Xen changes them other than by
+     * csrs_ctxt_switch_to() writing them from v->arch.*, which is left
+     * unchanged after vcpu_csr_init().
+     */
+
+    p->arch.hvip = csr_read(CSR_HVIP);
+
+    p->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    p->arch.vsie = csr_read64(VSIE);
+    p->arch.vstvec = csr_read(CSR_VSTVEC);
+    p->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    p->arch.vscause = csr_read(CSR_VSCAUSE);
+    p->arch.vstval = csr_read(CSR_VSTVAL);
+    p->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+static void csrs_ctxt_switch_to(struct vcpu *n)
+{
+    csr_write(CSR_HEDELEG, n->arch.hedeleg);
+    csr_write(CSR_HIDELEG, n->arch.hideleg);
+    csr_write(CSR_HVIP, n->arch.hvip);
+    csr_write64(HENVCFG, n->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, n->arch.hcounteren);
+    csr_write64(HTIMEDELTA, n->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, n->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, n->arch.vsstatus);
+    csr_write64(VSIE, n->arch.vsie);
+    csr_write(CSR_VSTVEC, n->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, n->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, n->arch.vscause);
+    csr_write(CSR_VSTVAL, n->arch.vstval);
+    csr_write(CSR_VSEPC, n->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to save the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(p) )
+        return;
+
+    p2m_ctxt_switch_from(p);
+
+    vtimer_ctxt_switch_from(p);
+
+    csrs_ctxt_switch_from(p);
+}
+
+static void ctxt_switch_to(struct vcpu *n)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to restore the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(n) )
+        return;
+
+    csrs_ctxt_switch_to(n);
+
+    vtimer_ctxt_switch_to(n);
+
+    p2m_ctxt_switch_to(n);
+}
+
+static void schedule_tail(struct vcpu *prev)
+{
+    unsigned int cpu = smp_processor_id();
+
+    ASSERT(prev != current);
+
+    ctxt_switch_from(prev);
+
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
+    ctxt_switch_to(current);
+
+    write_atomic(&current->dirty_cpu, cpu);
+
+    current->arch.last_cpu = cpu;
+
+    /*
+     * sched_context_switched() internally uses a spinlock,
+     * which requires interrupts to be enabled.
+     */
+    local_irq_enable();
+
+    sched_context_switched(prev, current);
+}
+
+void context_switch(struct vcpu *prev, struct vcpu *next)
+{
+    ASSERT(local_irq_is_enabled());
+    ASSERT(prev != next);
+    ASSERT(!vcpu_cpu_dirty(next));
+
+    local_irq_disable();
+
+    set_current(next);
+
+    prev = __context_switch(prev, next);
+
+    schedule_tail(prev);
+}
+
 static void __init __maybe_unused build_assertions(void)
 {
     /*
xen/arch/riscv/entry.S +48 -0

51 lines not on this page · raw message

xen/arch/riscv/include/asm/csr.h +9 -0
index 6df595e810ef..ef6c22a90e76 100644
@@ -40,6 +40,13 @@
     csr_write(CSR_ ## name ## H, v_ >> 32); \
 })
 
+#define csr_read64(name)                       \
+({                                             \
+    uint64_t v_ = csr_read(CSR_ ## name ## H); \
+                                               \
+    (v_ << 32) | csr_read(CSR_ ## name);       \
+})
+
 /*
  * The two halves are read by separate instructions, so a CSR which hardware
  * increments can carry from the low half into the high one in between,
@@ -63,6 +70,8 @@
 #define csr_write64(name, val) csr_write(CSR_ ## name, val)
 
 #define csr_volatile_read64(name) csr_read(CSR_ ## name)
+
+#define csr_read64(name) csr_read(CSR_ ## name)
 #endif
 
 #define csr_swap(csr, val)                                      \
xen/arch/riscv/include/asm/domain.h +14 -1
index 8c48833353f5..63e34c1a11ab 100644
@@ -28,6 +28,11 @@ struct arch_vcpu_io {
 struct arch_vcpu {
     struct vcpu_vmid vmid;
 
+    /*
+     * The last CPU this vCPU ran on. Initialised to CPU_NONE.
+     */
+    unsigned int last_cpu;
+
     /*
      * Callee saved registers for Xen's state used to switch from
      * prev's stack to the next's stack during context switch.
@@ -59,11 +64,19 @@ struct arch_vcpu {
     register_t hcounteren;
     register_t hedeleg;
     register_t hideleg;
-    register_t henvcfg;
+    uint64_t   henvcfg;
     register_t hstateen0;
+    uint64_t   htimedelta;
     register_t hvip;
 
     register_t vsatp;
+    register_t vscause;
+    register_t vsepc;
+    uint64_t   vsie;
+    register_t vsscratch;
+    register_t vsstatus;
+    register_t vstval;
+    register_t vstvec;
 
     /*
      * VCPU interrupts
xen/arch/riscv/include/asm/p2m.h +0 -1
index c0538281517f..1104854c4021 100644
@@ -262,7 +262,6 @@ struct page_info *p2m_get_page_from_gfn(struct p2m_domain *p2m, gfn_t gfn,
 
 void p2m_ctxt_switch_from(struct vcpu *p);
 void p2m_ctxt_switch_to(struct vcpu *n);
-void p2m_handle_vmenter(void);
 
 #endif /* RISCV_P2M_H */
 
xen/arch/riscv/include/asm/system.h +3 -0
index cb382487751c..50e2e369fcb6 100644
@@ -76,6 +76,9 @@ static inline bool local_irq_is_enabled(void)
 
 #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
+struct vcpu * asmlinkage __context_switch(struct vcpu *prev,
+                                          const struct vcpu *next);
+
 #endif /* __ASSEMBLER__ */
 
 #endif /* RISCV_SYSTEM_H */
xen/arch/riscv/p2m.c +108 -49

189 lines not on this page · raw message

xen/arch/riscv/riscv64/asm-offsets.c +18 -1
index 1290b9dbbe82..c1be1614ce94 100644
@@ -1,8 +1,10 @@
 #define COMPILE_OFFSETS
 
+#include <xen/sched.h>
+#include <xen/types.h>
+
 #include <asm/current.h>
 #include <asm/processor.h>
-#include <xen/types.h>
 
 #define DEFINE(_sym, _val)                                                 \
     asm volatile ( "\n.ascii\"==>#define " #_sym " %0 /* " #_val " */<==\""\
@@ -53,4 +55,19 @@ void asm_offsets(void)
     BLANK();
     DEFINE(PCPU_INFO_SIZE, sizeof(struct pcpu_info));
     BLANK();
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S0, struct vcpu, arch.xen_saved_context.s0);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S1, struct vcpu, arch.xen_saved_context.s1);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S2, struct vcpu, arch.xen_saved_context.s2);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S3, struct vcpu, arch.xen_saved_context.s3);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S4, struct vcpu, arch.xen_saved_context.s4);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S5, struct vcpu, arch.xen_saved_context.s5);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S6, struct vcpu, arch.xen_saved_context.s6);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S7, struct vcpu, arch.xen_saved_context.s7);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S8, struct vcpu, arch.xen_saved_context.s8);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S9, struct vcpu, arch.xen_saved_context.s9);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S10, struct vcpu, arch.xen_saved_context.s10);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S11, struct vcpu, arch.xen_saved_context.s11);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_SP, struct vcpu, arch.xen_saved_context.sp);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_RA, struct vcpu, arch.xen_saved_context.ra);
+    BLANK();
 }
xen/arch/riscv/stubs.c +0 -5
index 3a7953593d93..e0febae432b2 100644
@@ -81,11 +81,6 @@ void smp_send_state_dump(unsigned int cpu)
 
 DEFINE_PER_CPU(struct vcpu *, curr_vcpu);
 
-void context_switch(struct vcpu *prev, struct vcpu *next)
-{
-    BUG_ON("unimplemented");
-}
-
 void continue_running(struct vcpu *same)
 {
     BUG_ON("unimplemented");
xen/arch/riscv/traps.c +0 -2
index dd53454f23f4..2db3b74f95cf 100644
@@ -178,8 +178,6 @@ static void check_for_pcpu_work(void)
     vcpu_sync_interrupts(curr);
 
     vcpu_flush_interrupts(curr);
-
-    p2m_handle_vmenter();
 }
 
 static void timer_interrupt(void)
Signature · 1 line
2.56.1
#22 lore raw

PATCH v4 12/42 xen/riscv: save and restore vsiselect on vCPU context switch

In reply to a message not in the archive

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

When Smstateen is implemented, access to vsiselect and vsireg is gated by hstateen0.CSRIND (bit 60, SMSTATEEN0_SVSLCT in Xen's headers), and v->arch.hstateen0 holds the bits vcpu_csr_init() ended up with. A clear bit there covers the two cases in which the CSR has to be skipped:

- Xen didn't hand the guest access to it, so the guest can't have changed the CSR and there is no state to preserve;
- M-mode denied the state altogether. Smstateen makes a bit which is zero in mstateen0 read-only zero in hstateen0, and a zero bit in mstateen0 traps accesses from every privilege mode less privileged than M-mode, HS-mode included, so Xen couldn't even read the CSR to save it.

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

---
Changes in v4:
- Reword the commit message.
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
- Add Acked-by: Jan Beulich <[email protected]>.
---
Changes in v3:
- Rename from "xen/riscv: save and restore AIA state on vCPU context switch", as only vsiselect is switched now.
- Save and restore only vsiselect: drop hviprio1 and hviprio2.
- Rename vcpu_has_aia_state() to vcpu_can_access_vsiselect() and drop its hstateen0 bit argument.
- Move switching vsie to uint64_t and csr_{read,write}64() to "xen/riscv:
implement vCPU context switching".
- Update the commit message.
---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/domain.c             | 28 ++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/domain.h |  1 +
 2 files changed, 29 insertions(+)
xen/arch/riscv/domain.c +28 -0
index 9feeaa59b887..089d968ace27 100644
@@ -329,6 +329,28 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+/*
+ * vsiselect is a per-hart CSR, but a guest changes it on its own: when V=1,
+ * VS-mode accesses to siselect are really accesses to vsiselect. Hence it is
+ * part of the vCPU context.
+ *
+ * When Smstateen is implemented, hstateen0.CSRIND (SMSTATEEN0_SVSLCT) gates
+ * that access, and a bit staying clear in v->arch.hstateen0 (see
+ * vcpu_csr_init()) means either that the guest was never given access to the
+ * CSR, and so can't have changed it, or that M-mode denied the state
+ * altogether, in which case the CSR can't be accessed from HS-mode either.
+ */
+static bool vcpu_can_access_vsiselect(const struct vcpu *v)
+{
+    if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_ssaia) )
+        return false;
+
+    if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        return true;
+
+    return v->arch.hstateen0 & SMSTATEEN0_SVSLCT;
+}
+
 static void csrs_ctxt_switch_from(struct vcpu *p)
 {
     /*
@@ -347,6 +369,9 @@ static void csrs_ctxt_switch_from(struct vcpu *p)
     p->arch.vscause = csr_read(CSR_VSCAUSE);
     p->arch.vstval = csr_read(CSR_VSTVAL);
     p->arch.vsepc = csr_read(CSR_VSEPC);
+
+    if ( vcpu_can_access_vsiselect(p) )
+        p->arch.vsiselect = csr_read(CSR_VSISELECT);
 }
 
 static void csrs_ctxt_switch_to(struct vcpu *n)
@@ -368,6 +393,9 @@ static void csrs_ctxt_switch_to(struct vcpu *n)
     csr_write(CSR_VSCAUSE, n->arch.vscause);
     csr_write(CSR_VSTVAL, n->arch.vstval);
     csr_write(CSR_VSEPC, n->arch.vsepc);
+
+    if ( vcpu_can_access_vsiselect(n) )
+        csr_write(CSR_VSISELECT, n->arch.vsiselect);
 }
 
 static void ctxt_switch_from(struct vcpu *p)
xen/arch/riscv/include/asm/domain.h +1 -0
index 63e34c1a11ab..c424e2428f60 100644
@@ -73,6 +73,7 @@ struct arch_vcpu {
     register_t vscause;
     register_t vsepc;
     uint64_t   vsie;
+    register_t vsiselect;
     register_t vsscratch;
     register_t vsstatus;
     register_t vstval;
Signature · 1 line
2.56.1
#23 lore raw

PATCH v4 13/42 xen/riscv: introduce vintc_ctxt_switch_{from,to}()

In reply to a message not in the archive

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

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

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

---
Changes in v4:
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
---
Changes in v3:
- s/v/{p,n} for vintc_ctxt_switch_{from,to}() arguments and also for hook prototypes.
- Add Acked-by: Jan Beulich <[email protected]>.
---
Changes in v2:
- Update the commit message.
- s/vintc_state_{save,restore}/vintc_ctxt_switch_{to,from}.
- s/{re}store_state/ctxt_switch_{to,from} for vintc_ops.
- s/vcpu/v for vintc_ctxt_switch_{to,from}() arguments.
---

---
 xen/arch/riscv/domain.c           |  4 ++++
 xen/arch/riscv/include/asm/intc.h |  9 +++++++++
 xen/arch/riscv/intc.c             | 14 ++++++++++++++
 3 files changed, 27 insertions(+)
xen/arch/riscv/domain.c +4 -0
index 089d968ace27..a65de57e486f 100644
@@ -412,6 +412,8 @@ static void ctxt_switch_from(struct vcpu *p)
 
     vtimer_ctxt_switch_from(p);
 
+    vintc_ctxt_switch_from(p);
+
     csrs_ctxt_switch_from(p);
 }
 
@@ -427,6 +429,8 @@ static void ctxt_switch_to(struct vcpu *n)
 
     csrs_ctxt_switch_to(n);
 
+    vintc_ctxt_switch_to(n);
+
     vtimer_ctxt_switch_to(n);
 
     p2m_ctxt_switch_to(n);
xen/arch/riscv/include/asm/intc.h +9 -0
index 7a31c6a298a0..58196927aab2 100644
@@ -64,6 +64,12 @@ struct vintc_ops {
 
     /* Deinitialize some vINTC-related stuff for a vCPU */
     void (*vcpu_deinit)(struct vcpu *v);
+
+    /* Save vINTC state of the vCPU being switched out */
+    void (*ctxt_switch_from)(struct vcpu *p);
+
+    /* Restore vINTC state of the vCPU being switched in */
+    void (*ctxt_switch_to)(struct vcpu *n);
 };
 
 struct vintc {
@@ -94,4 +100,7 @@ void domain_vintc_deinit(struct domain *d);
 
 int vintc_reserve_virq(const struct domain *d, unsigned int virq);
 
+void vintc_ctxt_switch_from(struct vcpu *p);
+void vintc_ctxt_switch_to(struct vcpu *n);
+
 #endif /* RISCV_INTC_H */
xen/arch/riscv/intc.c +14 -0
index cdbc039d0258..70dfe6cd6f34 100644
@@ -190,3 +190,17 @@ int __overlay_init vintc_reserve_virq(const struct domain *d,
 
     return test_and_set_bit(virq, d->arch.vintc->used_irqs) ? -EEXIST : 0;
 }
+
+void vintc_ctxt_switch_from(struct vcpu *p)
+{
+    const struct vintc_ops *ops = p->domain->arch.vintc->ops;
+
+    ops->ctxt_switch_from(p);
+}
+
+void vintc_ctxt_switch_to(struct vcpu *n)
+{
+    const struct vintc_ops *ops = n->domain->arch.vintc->ops;
+
+    ops->ctxt_switch_to(n);
+}
Signature · 1 line
2.56.1
#24 lore raw

PATCH v4 14/42 xen/riscv: extend exception tables with type and data fields

In reply to a message not in the archive

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

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

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

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

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

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

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

---
Changes in v4:
- Pass the cause to the fixup_exception() call in do_trap(), which "xen/riscv: look up the exception table for any trap taken in Xen context" has moved ahead of the cause switch, and mention EX_TYPE_TRAP_INFO in the comment above it.
- Update the commit message.
- gpr-num.h: name the assembler GPR_NUM_EQU() in the comment of its C flavour instead of referring to "the __ASSEMBLER__ flavour above", which was hard to tie to a particular comment.
---
Changes in v3:
- Update the commit message.
- Keep the name of the asm_extable assembler macro: renaming it to _asm_extable was unrelated to this patch.
- Replace regs_get_gpr() in extable.c with regs_gpr_ptr() in asm/regs.h, returning where the register's value is saved rather than the value itself, so that a single helper serves code which reads a guest register as well as code which writes one. Anchor the array access at &regs->zero rather than casting regs itself, matching the relaxed layout requirement below, and bound the index with array_index_nospec() so that release builds, where the ASSERT() is compiled out, cannot read past the register frame. Add NR_GPRS instead of open-coding 32.
- Move the layout BUILD_BUG_ON()s out of regs_get_gpr() into build_assertions() in domain.c, so that they no longer sit in one particular consumer of the mapping.
- Anchor those checks at offsetof(struct cpu_user_regs, zero) rather than at offset 0: the x0..x31 block only has to be contiguous and in register-number order, it no longer has to sit at the start of the structure. Update the comment above struct cpu_user_regs accordingly, keeping the "->zero must read as 0" requirement as a separate point.
- REG_PTR(): anchor at &regs->zero for the same reason.
- gpr-num.h: move the part of the comment describing the generation of the .L_gpr_num_<name> symbols down to the construct which actually generates them; GPR_LIST() itself has other users.
- gpr-num.h: emit the separator ahead of each list entry instead of after it, so that the expansion doesn't end with one and whatever follows a use of the list has to supply its own; ASM_EXTABLE_TRAP_INFO() supplies the "\n" it needs.
- gpr-num.h: state in the file header what was changed compared to the Linux original.
- asm/extable.h: no functional change, put EX_TRAP_INFO_REG() on a single line and reflow the comment describing the exception table entry format.
- Drop BUG_ON() in ex_handler_trap_info() as trap_info pointer should be guaranteed properly filled by compilation process.
---
Changes in v2:
- regs_get_gpr(): take a GPR number instead of a byte offset, dropping the multiplication at the call site. A non-multiple-of-8 offset is now unrepresentable.
- regs_get_gpr(): ASSERT(num < 32) instead of a range check returning 0, which isn't usable as an error indicator. No num == 0 check: reading x0 is harmless out of context, and a NULL trap_info is caught by the existing BUG_ON() where the dereference happens.
- regs_get_gpr(): index the register frame as an array, constify regs and drop the pointless inline.
- Anchor the first BUILD_BUG_ON() at offsetof(..., zero) == 0 rather than at ra, pinning both ends of the x0..x31 range.
- Drop MAX_REG_OFFSET; asm/processor.h is no longer touched by this patch.
- ex_handler_trap_info(): use regs->sepc and the cause passed down from do_trap() instead of re-reading CSR_SEPC/CSR_SCAUSE; fixup_exception() gains a cause parameter. stval stays a CSR read as do_trap() doesn't read it.
- asm/extable.h: revert the .word -> .long change, the extra parens and the stray semicolon after .popsection; use .half for the new type and data fields to match .word.
- Make GPR_LIST() the single source of the ABI-name -> register-number mapping, and check struct cpu_user_regs against it at build time, so the two can no longer diverge.
- Add the explanatory comment above sturc cpu_user_regs to explain an ordering of x0-x31 registers.
---

---
 xen/arch/riscv/domain.c                     | 22 ++++++++
 xen/arch/riscv/extable.c                    | 48 +++++++++++++++-
 xen/arch/riscv/include/asm/extable.h        | 61 ++++++++++++++-------
 xen/arch/riscv/include/asm/gpr-num.h        | 53 ++++++++++++++++++
 xen/arch/riscv/include/asm/processor.h      | 14 ++++-
 xen/arch/riscv/include/asm/regs.h           | 23 +++++++-
 xen/arch/riscv/include/asm/riscv_encoding.h |  7 ++-
 xen/arch/riscv/include/asm/traps.h          |  6 ++
 xen/arch/riscv/traps.c                      |  5 +-
 9 files changed, 212 insertions(+), 27 deletions(-)
 create mode 100644 xen/arch/riscv/include/asm/gpr-num.h
xen/arch/riscv/domain.c +22 -0
index a65de57e486f..7be019e2ad12 100644
@@ -12,6 +12,7 @@
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/current.h>
+#include <asm/gpr-num.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
@@ -478,9 +479,30 @@ void context_switch(struct vcpu *prev, struct vcpu *next)
 
 static void __init __maybe_unused build_assertions(void)
 {
+/*
+ * GPR_LIST() puts nothing between its entries, so the separator has to come
+ * from here. It is emitted ahead of each entry rather than after it, so that
+ * the expansion doesn't end with one and its use below can be terminated like
+ * an ordinary statement.
+ */
+#define CHECK_GPR_INDEX(num, name)                          \
+    ; BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) !=  \
+                   offsetof(struct cpu_user_regs, zero) +   \
+                   (num) * sizeof(unsigned long))
+
     /*
      * Enforce the requirement documented in struct cpu_info that
      * guest_cpu_user_regs must be the first field.
      */
     BUILD_BUG_ON(offsetof(struct cpu_info, guest_cpu_user_regs));
+
+    /*
+     * Enforce the requirement documented in struct cpu_user_regs that the
+     * x0..x31 fields are contiguous and in architectural register-number
+     * order, which is what lets a register number be resolved to its saved
+     * value by indexing them as an array anchored at ->zero.
+     */
+    GPR_LIST(CHECK_GPR_INDEX);
+
+#undef CHECK_GPR_INDEX
 }
xen/arch/riscv/extable.c +46 -2

74 lines not on this page · raw message

xen/arch/riscv/include/asm/extable.h +42 -19

93 lines not on this page · raw message

xen/arch/riscv/include/asm/gpr-num.h new file +53 -0

53 lines not on this page · raw message

xen/arch/riscv/include/asm/processor.h +13 -1
index 007c22d2e611..83dd59a27295 100644
@@ -12,7 +12,19 @@
 
 #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * The x0..x31 fields must remain contiguous and in architectural
+ * register-number order: code which resolves a register number to its saved
+ * value indexes them as an array anchored at ->zero. Where that block sits
+ * within the structure is of no interest, but nothing may be inserted in
+ * between its fields. The layout is checked against GPR_LIST() at build
+ * time; see build_assertions() in domain.c.
+ *
+ * ->zero additionally has to always read as 0, since it supplies the value
+ * of x0 when x0 is used as a source operand.
+ */
 struct cpu_user_regs
 {
     unsigned long zero;
xen/arch/riscv/include/asm/regs.h +21 -2
index 24674d37cfe4..00aa6ff964e8 100644
@@ -5,16 +5,35 @@
 #ifndef __ASSEMBLER__
 
 #include <xen/bug.h>
+#include <xen/nospec.h>
 
-#define hyp_mode(r)     (0)
+#include <asm/gpr-num.h>
+#include <asm/processor.h>
 
-struct cpu_user_regs;
+#define hyp_mode(r)     (0)
 
 static inline bool guest_mode(const struct cpu_user_regs *r)
 {
     BUG_ON("unimplemented");
 }
 
+/*
+ * Resolve an architectural register number to where its value is saved in
+ * @regs. Relies on x0..x31 being laid out as an array anchored at ->zero; see
+ * the comment above struct cpu_user_regs.
+ */
+static inline unsigned long *regs_gpr_ptr(struct cpu_user_regs *regs,
+                                          unsigned int num)
+{
+    ASSERT(num < NR_GPRS);
+
+    /*
+     * Not a speculation concern, but a convenient way to keep the access in
+     * bounds in release builds, where the assertion above is compiled out.
+     */
+    return &(&regs->zero)[array_index_nospec(num, NR_GPRS)];
+}
+
 #endif /* __ASSEMBLER__ */
 
 #endif /* RISCV_REGS_H */
xen/arch/riscv/include/asm/riscv_encoding.h +6 -1
index 481ee2813b0e..887edce6b604 100644
@@ -903,8 +903,13 @@
 #define REG_OFFSET(insn, pos)		\
 	(SHIFT_RIGHT((insn), (pos) - LOG_REGBYTES) & REG_MASK)
 
+/*
+ * The x0..x31 block of struct cpu_user_regs is not required to sit at the
+ * start of the structure, so anchor the offset at ->zero (x0) rather than
+ * at the structure itself.
+ */
 #define REG_PTR(insn, pos, regs)	\
-	(unsigned long *)((unsigned long)(regs) + REG_OFFSET(insn, pos))
+	(unsigned long *)((unsigned long)&(regs)->zero + REG_OFFSET(insn, pos))
 
 #define GET_RM(insn)			(((insn) >> 12) & 7)
 
xen/arch/riscv/include/asm/traps.h +6 -0
index 08c6215e931a..3f2b5b7ccb5f 100644
@@ -7,6 +7,12 @@
 
 #ifndef __ASSEMBLER__
 
+struct trap_info {
+    register_t sepc;
+    register_t scause;
+    register_t stval;
+};
+
 void do_trap(struct cpu_user_regs *cpu_regs);
 void handle_trap(void);
 void trap_init(void);
xen/arch/riscv/traps.c +3 -2
index 2db3b74f95cf..efeba0a9ce03 100644
@@ -202,7 +202,8 @@ void do_trap(struct cpu_user_regs *cpu_regs)
      *
      * Traps taken from the guest must never be fixed up: sepc is then a guest
      * address, which the guest could point at an address listed in the
-     * exception table, making Xen act on an entry fully under guest control.
+     * exception table, making Xen act on an entry (and, for EX_TYPE_TRAP_INFO,
+     * write through a pointer) fully under guest control.
      *
      * Interrupts must be excluded too: one taken at an address which happens
      * to be listed in the exception table would otherwise be "fixed up" as if
@@ -212,7 +213,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
      * that only runs for traps taken from the guest.
      */
     if ( !from_guest && !(cause & CAUSE_IRQ_FLAG) &&
-         fixup_exception(cpu_regs) )
+         fixup_exception(cpu_regs, cause) )
         return;
 
     switch ( cause )
Signature · 1 line
2.56.1
#25 lore raw

PATCH v4 15/42 xen/riscv: add guest page fault handling stub

In reply to a message not in the archive

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

This will be used, for example, to trap accesses to APLIC registers so that a guest can initialize and drive an emulated interrupt controller.

A G-stage (stage-2) fault has one of three causes, reported via scause:
- Fetch fault: guest tried to execute from a guest-physical address that is unmapped or that G-stage marks non-executable. Never emulatable (nothing to emulate a fetch into). On real hardware this raises an instruction access fault, so Xen reflects the same fault back to the guest. Decided here.

- Load fault / Store fault: this is where MMIO emulation hooks in. Not in scope of this patch.

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

(a) the fault is caused by an implicit memory access for VS-stage address translation, and
(b) htval holds a nonzero value: the guest-physical address of that VS-stage PTE, not of the guest's original access.

However, none of these paths consult the p2m first, and the future MMIO path won't either: RISC-V has no populate-on-demand, no paging, and no mem_access, so every guest mapping is established eagerly. A G-stage fault therefore never indicates a mapping Xen could lazily resolve to let the access complete.

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

---
Changes in v4:
- Drop the from_guest local and the paragraph on it in the commit
message: "xen/riscv: look up the exception table for any trap taken in Xen context" introduces it now.
- Update the commit message.
- Rewrite the comment ahead of the htinst_is_pseudo() check along the lines of the commit message.
- Drop __func__ from the domain_crash() messages: they are unique enough.
- Drop the comment ahead of the definition of trap_redirect(): it duplicates the one on its declaration.
---
Changes in v3:
- Update the commit message.
- Make resolve_faulting_gpa() return an error, which the caller checks.
- Add a FIXME about guest page tables residing in emulated MMIO.
- Don't refer to fixup_exception() in the comment ahead of BUG_ON(!from_guest): it isn't consulted for guest page faults yet.
- Mention the from_guest local in the commit message.
- Say in the comment above resolve_faulting_gpa() that it stores the address in @gf->gpa.
- Make emulate_store() take a pointer to const, as emulate_load() does:
neither modifies *gf.
---
Changes in v2:
- Introduce struct guest_fault.
- Change the prototypes of emulate_{load,store}() to take a non-const struct guest_fault, as emulation has to write the destination register and advance sepc.
- Add handling of pseudoinstructions before the call of emulate_{load,store}.
- Rename get_fault_gpa to resolve_faulting_gpa and change its prototype to take struct guest_fault.
- Add handling of CAUSE_FETCH_GUEST_PAGE_FAULT now.
- Document why the p2m is not consulted before a fault is injected, and add a BUILD_BUG_ON() on CONFIG_VM_EVENT to catch that assumption breaking.
- Print the fault cause in the domain_crash() message rather than deriving an access type string which cannot cover every case.
- Move code to introduced emulate.c instead of having it in traps.c
---

---
 xen/arch/riscv/Makefile              |   1 +
 xen/arch/riscv/emulate.c             | 177 +++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/emulate.h |  10 ++
 xen/arch/riscv/include/asm/traps.h   |   3 +
 xen/arch/riscv/traps.c               |  18 +++
 5 files changed, 209 insertions(+)
 create mode 100644 xen/arch/riscv/emulate.c
 create mode 100644 xen/arch/riscv/include/asm/emulate.h
xen/arch/riscv/Makefile +1 -0
index 5454517724bd..2b84dace6bd5 100644
@@ -6,6 +6,7 @@ obj-y += domain.o
 obj-y += domain-build.init.o
 obj-$(CONFIG_DOM0LESS_BOOT) += dom0less-build.init.o
 obj-$(CONFIG_EARLY_PRINTK) += early_printk.o
+obj-y += emulate.o
 obj-y += entry.o
 obj-y += extable.o
 obj-y += guestcopy.o
xen/arch/riscv/emulate.c new file +177 -0

177 lines not on this page · raw message

xen/arch/riscv/include/asm/emulate.h new file +10 -0
new file mode 100644
index 000000000000..59e69ca6794c
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#ifndef RISCV_EMULATE_H
+#define RISCV_EMULATE_H
+
+struct cpu_user_regs;
+
+void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause);
+
+#endif /* RISCV_EMULATE_H */
xen/arch/riscv/include/asm/traps.h +3 -0
index 3f2b5b7ccb5f..a7c79ae6165b 100644
@@ -17,6 +17,9 @@ void do_trap(struct cpu_user_regs *cpu_regs);
 void handle_trap(void);
 void trap_init(void);
 
+/* Reflect @trap back to the guest, i.e. enter its VS-mode trap handler. */
+void trap_redirect(const struct trap_info *trap);
+
 #endif /* __ASSEMBLER__ */
 
 #endif /* RISCV_TRAPS_H */
xen/arch/riscv/traps.c +18 -0
index efeba0a9ce03..db8873d1e43f 100644
@@ -14,6 +14,7 @@
 
 #include <asm/extable.h>
 #include <asm/cpufeature.h>
+#include <asm/emulate.h>
 #include <asm/intc.h>
 #include <asm/processor.h>
 #include <asm/riscv_encoding.h>
@@ -225,6 +226,18 @@ void do_trap(struct cpu_user_regs *cpu_regs)
         vsbi_handle_ecall(cpu_regs);
         break;
 
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        /*
+         * Xen doesn't access guest memory, so it can't take a guest page
+         * fault itself: only a guest can get here.
+         */
+        BUG_ON(!from_guest);
+
+        handle_guest_page_fault(cpu_regs, cause);
+        break;
+
     case CAUSE_ILLEGAL_INSTRUCTION:
         if ( do_bug_frame(cpu_regs, pc) >= 0 )
         {
@@ -294,3 +307,8 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
     BUG_ON("unimplemented");
     return mc_continue;
 }
+
+void trap_redirect(const struct trap_info *trap)
+{
+    BUG_ON("unimplemented");
+}
Signature · 1 line
2.56.1
#26 lore raw

PATCH v4 16/42 xen/riscv: implement trap redirection to a guest

In reply to a message not in the archive

Two kinds of traps can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead:
- Traps Xen takes on the guest's behalf, such as those taken by the hlv/hlvx sequences Xen uses to access guest memory.
- Access faults handle_guest_page_fault() injects for a guest-page fault that can never become an emulated access.

Implement trap_redirect(), until now a BUG_ON() placeholder, for that purpose. It makes the trap appear to the guest as if it had been taken directly in VS-mode: the trap information is transferred to the guest's virtual supervisor CSRs and the vCPU is resumed at its exception vector in supervisor mode, following the trap entry rules of the RISC-V privileged specification.

The implementation is based on kvm_riscv_vcpu_trap_redirect() from Linux, with a few deviations:
- The function reads and writes physical VS-mode CSRs, so it is only meaningful for the currently running vCPU. Instead of taking a struct vcpu argument, it always operates on current.
- The MODE field of vstvec is masked off explicitly when computing the exception target PC (exceptions always vector to BASE), rather than relying on the hardwired zero bit of sepc to drop it on VM entry.
- Assertions document the preconditions: the trap must have been taken from virtualized mode (hstatus.SPV set), and only synchronous exceptions may be redirected - interrupts must be injected via hvip instead, so that the hardware performs VS-mode trap entry itself, respecting vsstatus.SIE and vectored vstvec dispatch.

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

---
Changes in v4:
- Add extra tab to definition of STVEC_MODE_MASK.
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
---
Changes in v3:
- Update the commit message.
- Drop STVEC_BASE_MASK for now and use ~STVEC_MODE_MASK instead.
---
Changes in v2:
- Add new defines STVEC_*. The STVEC_MODE_DIRECT/_VECTORED values are currently unused and were included because riscv encoding header is a spec mirror full of unused encodings.
- Use STVEC_BASE_MASK instead of open-coding it.
- Rename riscv_vcpu_trap_redirect() to trap_redirect(): unlike its KVM counterpart the function takes no vCPU argument, it implicitly operates on current, so "vcpu" in the name describes nothing.

---
 xen/arch/riscv/include/asm/riscv_encoding.h |  5 +++
 xen/arch/riscv/traps.c                      | 50 ++++++++++++++++++++-
 2 files changed, 54 insertions(+), 1 deletion(-)
xen/arch/riscv/include/asm/riscv_encoding.h +5 -0
index 887edce6b604..fa26f5a2eb86 100644
@@ -107,6 +107,11 @@
 #define SIP_SSIP			MIP_SSIP
 #define SIP_STIP			MIP_STIP
 
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
+#define STVEC_MODE_MASK			_UL(0x3)
+#define STVEC_MODE_DIRECT		_UL(0x0)
+#define STVEC_MODE_VECTORED		_UL(0x1)
+
 #define PRV_U				_UL(0)
 #define PRV_S				_UL(1)
 #define PRV_M				_UL(3)
xen/arch/riscv/traps.c +49 -1

54 lines not on this page · raw message

Signature · 1 line
2.56.1
#27 lore raw

PATCH v4 17/42 xen/riscv: detect Shtvala

In reply to a message not in the archive

The H extension allows htval, on a guest-page fault, to be written with either the faulting guest physical address or zero. The Shtvala extension removes the ambiguity of this zero-write by guaranteeing that htval is written with the faulting guest physical address in every circumstance permitted by the ISA.

Not offered to guests: Shtvala describes htval, an HS-mode-only trap register a VS-mode guest never touches, and the H extension it belongs to is already hidden from guests. The guest-visible equivalent is a separate extension, Shvstvala, covering vstval instead.

---
Changes in v4:
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
- Add Acked-by: Jan Beulich <[email protected]>.
---
Changes in v3:
- Update the commit message.
---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/cpufeature.c             | 1 +
 xen/arch/riscv/include/asm/cpufeature.h | 1 +
 2 files changed, 2 insertions(+)
xen/arch/riscv/cpufeature.c +1 -0
index b1c614867cd8..2cca5165804f 100644
@@ -196,6 +196,7 @@ static const struct riscv_isa_ext_entry __initconstrel riscv_isa_ext[] = {
     RISCV_ISA_EXT_ENTRY(zba,            ANY),
     RISCV_ISA_EXT_ENTRY(zbb,            ANY),
     RISCV_ISA_EXT_ENTRY(zbs,            ANY),
+    RISCV_ISA_EXT_ENTRY(shtvala,        NONE),
     RISCV_ISA_EXT_ENTRY(smaia,          ANY),
     RISCV_ISA_EXT_ENTRY(smstateen,      ANY),
     RISCV_ISA_EXT_ENTRY(ssaia,          ANY),
xen/arch/riscv/include/asm/cpufeature.h +1 -0
index d42189e8ebe7..f0f9b5ad72d2 100644
@@ -36,6 +36,7 @@ enum riscv_isa_ext_id {
     RISCV_ISA_EXT_zba,
     RISCV_ISA_EXT_zbb,
     RISCV_ISA_EXT_zbs,
+    RISCV_ISA_EXT_shtvala,
     RISCV_ISA_EXT_smaia,
     RISCV_ISA_EXT_smstateen,
     RISCV_ISA_EXT_ssaia,
Signature · 1 line
2.56.1
#28 lore raw

PATCH v4 18/42 xen/riscv: resolve the faulting guest physical address

In reply to a message not in the archive

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

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

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

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

---
Changes in v4:
- Update the commit message.
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
---
Changes in v3:
- Update the commit message.
- Drop panic() inside resolve_faulting_gpa() and return -EOPNOTSUPP + printk_once().
- Leave the comment above resolve_faulting_gpa() alone: it already says what the function does since "xen/riscv: add guest page fault handling stub".
- Document in docs/misc/riscv/booting.txt why Shtvala is recommended.
---
Changes in v2:
- New patch.
---

---
 docs/misc/riscv/booting.txt | 11 +++++++++++
 xen/arch/riscv/emulate.c    | 27 ++++++++++++++++++++++++++-
 2 files changed, 37 insertions(+), 1 deletion(-)
docs/misc/riscv/booting.txt +11 -0
index 14212ed62f99..283aa49a3b64 100644
@@ -35,3 +35,14 @@ Other extensions recognised by Xen are listed in riscv_isa_ext[] in
 xen/arch/riscv/cpufeature.c. Xen uses them when present, but they are not
 needed to boot. The second column of that table says whether the extension
 is also exposed to guests.
+
+Some of them are nevertheless recommended, as functionality depends on them:
+- Shtvala:
+  Guarantees that htval is written with the faulting guest physical address
+  on a guest-page fault. Without it an implementation may write zero instead,
+  which can't be told apart from a genuine fault on guest physical addresses
+  0-3. Xen needs that address to emulate a guest's MMIO accesses; recovering
+  it in software (by walking the guest's VS-stage page tables) isn't
+  implemented, so on such hardware a guest-page fault reported with a zero
+  htval crashes the domain. See resolve_faulting_gpa() in
+  xen/arch/riscv/emulate.c.
xen/arch/riscv/emulate.c +26 -1
index de8c09fe1505..d661ef0bf204 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>
@@ -58,7 +59,31 @@ static bool htinst_is_pseudo(unsigned long htinst)
  */
 static int resolve_faulting_gpa(struct guest_fault *gf)
 {
-    return -EOPNOTSUPP;
+    /*
+     * A zero htval is either a genuine fault on guest physical address 0-3, or
+     * an implementation which does not report the address at all; only Shtvala
+     * tells the two apart.
+     *
+     * TODO: where it is absent, recover the address in software rather than
+     * giving up.
+     */
+    if ( !gf->htval &&
+         !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_shtvala) )
+    {
+        printk_once(XENLOG_WARNING
+                    "Shtvala isn't supported by h/w; s/w VS-stage walk required\n");
+        return -EOPNOTSUPP;
+    }
+
+    /*
+     * htval does not carry the two low bits of the address: for an explicit
+     * access they are those of the faulting guest virtual address in stval,
+     * and for an implicit access made for VS-stage translation they are zero.
+     */
+    gf->gpa = ((paddr_t)gf->htval << 2) |
+              (htinst_is_pseudo(gf->htinst) ? 0 : (gf->stval & 3));
+
+    return 0;
 }
 
 static int emulate_load(const struct guest_fault *gf)
Signature · 1 line
2.56.1
#29 lore raw

PATCH v4 19/42 xen/riscv: add guest memory read helper

In reply to a message not in the archive

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

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

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

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

---
Changes in v4:
- Update the comments in do_trap() on the exception table lookup and on the guest page fault case. "xen/riscv: look up the exception table for any trap taken in Xen context" used to do that, but went to staging without it.
- Move the comment describing read_guest() to its declaration in asm/guest_access.h.
- Explain the check of bits[1:0] of the first halfword fetched by read_guest().
---
Changes in v3:
- Rename riscv_read_guest() to read_guest().
- Document that @trap must be zero-initialised by the caller: it is written only when an access faults, so trap->scause == 0 on return is what tells the caller that the read succeeded.
- Drop the ASSERT() on hstatus.SPV: vcpu_guest_cpu_user_regs(current) is the guest frame whatever context Xen is in, so SPV is always set in it and the check couldn't catch a call made from a nested trap. State in the comment above read_guest() that it must not be called from a nested trap taken in HS-mode instead.
- Declare read_guest() in asm/guest_access.h.
---
Changes in v2:
- Rename riscv_vcpu_unpriv_read() to riscv_read_guest() and make the guest address the first parameter. "unprivileged" described how hlv/hlvx perform the access rather than what the helper is for, and "unprivileged guest" reads as a synonym for DomU although the helper works for any domain.
- Drop the hstatus save/restore and the local_irq_save() protecting it:
hstatus already belongs to the vCPU which trapped, as Xen never installs a value of its own and does not reschedule before returning to the guest. ASSERT() hstatus.SPV in the saved copy instead, which also documents that the helper is only usable while handling a trap from a guest.
- Poison val with ~0UL and make [val] "+&r": the fixup for the first access resumes past the loads without writing it, so a caller which checks trap->scause is no longer handed an uninitialized value.
- Describe the trap_info write with a "+m" (*trap) operand instead of a "memory" clobber; the exception handler writes that structure and nothing else.
- Combine the two halfwords with slli/or instead of sll/add, and use bnez for the instruction length check.
- Turn the hlv.d/hlv.w selection into #if/#elif with an #error default, rather than silently using hlv.w for anything that is not RV64.
- Document that at most two halfwords are fetched, i.e. that encodings wider than 32 bits are unsupported and cannot be completed by calling the helper again at guest_addr + 4, since the length check would then be applied to a continuation halfword.
---

---
 xen/arch/riscv/guestcopy.c                | 68 +++++++++++++++++++++++
 xen/arch/riscv/include/asm/guest_access.h | 28 ++++++++++
 xen/arch/riscv/traps.c                    | 13 +++--
 3 files changed, 104 insertions(+), 5 deletions(-)
xen/arch/riscv/guestcopy.c +68 -0
index 8a89212e0bea..283a96322caa 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,70 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
     return copy_guest(buf, gpa, len, GPA_INFO(d),
                       COPY_to_guest | COPY_gpa);
 }
+
+unsigned long read_guest(unsigned long guest_addr, bool read_insn,
+                         struct trap_info *trap)
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;
+
+    /*
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     */
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1: hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            /*
+             * bits[1:0] != 0b11: 16-bit (compressed) instruction, nothing
+             * more to read.
+             */
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bnez %[tmp], 3f\n"
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2: hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   slli %[tmp], %[tmp], 16\n"
+            "   or %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "+&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr),
+          "+m" (*trap)
+        : [ti] "r" (trap) );
+
+        /*
+         * Although HLVX instructions' explicit memory accesses require execute
+         * permissions, they still raise the same exceptions as other load
+         * instructions, rather than raising fetch exceptions instead.
+         */
+        if ( trap->scause == CAUSE_LOAD_PAGE_FAULT )
+            trap->scause = CAUSE_FETCH_PAGE_FAULT;
+    }
+    else
+    {
+        asm volatile ( "\n"
+            "1: "
+#if defined(CONFIG_RISCV_64)
+            "hlv.d %[val], (%[addr])\n"
+#elif defined(CONFIG_RISCV_32)
+            "hlv.w %[val], (%[addr])\n"
+#else
+# error "unsupported RISC-V variant: no hlv for a machine word"
+#endif
+            "2:\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 2b, %[ti])
+        : [val] "+&r" (val), "+m" (*trap)
+        : [addr] "r" (guest_addr), [ti] "r" (trap) );
+    }
+
+    return val;
+}
xen/arch/riscv/include/asm/guest_access.h +28 -0
index e94aa838a3e7..77911bffbdbf 100644
@@ -5,6 +5,7 @@
 #include <xen/types.h>
 
 struct domain;
+struct trap_info;
 
 unsigned long raw_copy_to_guest(void *to, const void *from, unsigned len);
 unsigned long raw_copy_from_guest(void *to, const void *from, unsigned len);
@@ -25,6 +26,33 @@ unsigned long raw_clear_guest(void *to, unsigned int len);
 unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
                                  unsigned long len);
 
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read.
+ *        It must be zero-initialised by the caller: it is written only when
+ *        an access faults, so trap->scause == 0 on return is what tells the
+ *        caller that the read succeeded.
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU. It must therefore only be called
+ * while handling a trap taken from that vCPU, never from a nested trap
+ * taken in HS-mode, which may have interrupted Xen at a point where
+ * hstatus, vsatp or hgatp don't belong to the vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long read_guest(unsigned long guest_addr, bool read_insn,
+                         struct trap_info *trap);
+
 #endif /* RISCV_GUEST_ACCESS_H */
 /*
  * Local variables:
xen/arch/riscv/traps.c +8 -5
index 3672774271ff..97e604091458 100644
@@ -197,9 +197,11 @@ void do_trap(struct cpu_user_regs *cpu_regs)
     bool from_guest = cpu_regs->hstatus & HSTATUS_SPV;
 
     /*
-     * A synchronous trap taken in Xen context may come from a probing access
-     * like csr_read_safe(), covered by an exception table entry which resumes
-     * execution past the faulting instruction.
+     * A synchronous trap taken in Xen context may come from an access done on
+     * a vCPU's behalf, e.g. the hlv/hlvx sequences in read_guest(),
+     * or from a probing access like csr_read_safe(). Both are covered by
+     * exception table entries which record the fault details for the caller
+     * and resume execution past the faulting instruction.
      *
      * Traps taken from the guest must never be fixed up: sepc is then a guest
      * address, which the guest could point at an address listed in the
@@ -230,8 +232,9 @@ void do_trap(struct cpu_user_regs *cpu_regs)
     case CAUSE_LOAD_GUEST_PAGE_FAULT:
     case CAUSE_STORE_GUEST_PAGE_FAULT:
         /*
-         * Xen doesn't access guest memory, so it can't take a guest page
-         * fault itself: only a guest can get here.
+         * A guest page fault taken in Xen context comes from an hlv/hlvx
+         * access made on a vCPU's behalf and is dealt with by the
+         * fixup_exception() above, so only a guest can get here.
          */
         BUG_ON(!from_guest);
 
Signature · 1 line
2.56.1
#30 lore raw

PATCH v4 20/42 xen/riscv: add helpers for decoding a trapped load or store

In reply to a message not in the archive

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

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

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

---
 xen/arch/riscv/emulate.c                    | 335 ++++++++++++++++++++
 xen/arch/riscv/include/asm/riscv_encoding.h |  14 +
 2 files changed, 349 insertions(+)
xen/arch/riscv/emulate.c +335 -0
index d661ef0bf204..a30b2a7fadae 100644
@@ -13,9 +13,40 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
+#include <asm/regs.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
 
+/*
+ * Determine the trapped load or store instruction which caused a guest MMIO
+ * trap.
+ */
+struct decoded_insn {
+    /*
+     * The trapped instruction: as read from guest memory, or the 32-bit
+     * equivalent the hardware transformed it into (see insn_fetch_faulted()).
+     * None of the extensions exposed to guests has instructions wider than
+     * 32 bits, and insn_fetch_faulted() rejects anything longer.
+     */
+    uint32_t insn;
+    /*
+     * Length in bytes of the trapped instruction in guest memory: 2 or 4.
+     * This need not be the length of the encoding in insn, as a compressed
+     * instruction may have been transformed into its 32-bit equivalent.
+     */
+    uint8_t insn_len;
+    /* Width of the memory access, in bytes. */
+    uint8_t len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    uint8_t reg;
+    /* The access is a store rather than a load. */
+    bool is_write:1;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned:1;
+};
+
 /*
  * The hardware-reported details of a guest page fault, gathered once by
  * handle_guest_page_fault() and passed down to the emulation of the faulted
@@ -39,6 +70,65 @@ struct guest_fault {
     paddr_t gpa;
 };
 
+static void advance_pc(struct cpu_user_regs *regs, unsigned int step)
+{
+    regs->sepc += step;
+}
+
+/*
+ * The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a
+ * trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode.
+ *
+ * VSXL is consulted whichever mode the trap came from: if VSXL says 32,
+ * vsstatus has no UXL field, so VU-mode is 32-bit as well and there is
+ * nothing to configure.
+ *
+ * It is needed to decode a trapped instruction: the encodings which exist only
+ * for XLEN=64 must not be recognized for a 32-bit guest. Besides those simply
+ * being reserved there, the compressed ones are ambiguous: C.LD and C.FLW
+ * share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW,
+ * C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
+ *
+ * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
+ * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
+ */
+static unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned int xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);
+
+    if ( (xl > XLEN_FIELD_32) && !(regs->sstatus & SSTATUS_SPP) )
+        xl = MASK_EXTR(csr_read(CSR_VSSTATUS), SSTATUS64_UXL);
+
+    switch ( xl )
+    {
+    case XLEN_FIELD_32:
+        return 32;
+
+    case XLEN_FIELD_64:
+        return 64;
+
+    default:
+        /*
+         * The field holds nothing else in practice: XLEN_FIELD_128 would mean
+         * RV128, which no implementation provides, and the only value left is
+         * reserved. ASSERT_UNREACHABLE() being debug-only, a width still has
+         * to be answered in release builds.
+         *
+         * Answer 32, that being the safe way to be wrong: the decoder then
+         * fails to recognize the RV64-only encodings and emulation gives up.
+         * Answering 64 for what may well be a 32-bit guest would instead have
+         * it take C.FLW for C.LD and C.FSW for C.SD (see above), i.e. quietly
+         * emulate an access of the wrong width against the wrong register.
+         */
+        ASSERT_UNREACHABLE();
+        return 32;
+    }
+#endif
+}
+
 /*
  * Is @htinst one of the special pseudoinstruction values, reported for a guest
  * page fault taken on an implicit memory access done for VS-stage address
@@ -86,8 +176,253 @@ static int resolve_faulting_gpa(struct guest_fault *gf)
     return 0;
 }
 
+/*
+ * Where the value of a decoded instruction's register operand is held.
+ *
+ * The register is held at its full width, whatever the guest's XLEN is (see
+ * guest_xlen()). Where XLEN is narrower, the bits above it are not guaranteed
+ * to be zero, nor even a sign extension: hardware only ignores them in source
+ * operands, so they may have been left there by more privileged code running
+ * at a wider XLEN. Hence callers must not rely on those bits when reading a
+ * value, and must sign-extend what they write from bit XLEN-1, as hardware
+ * does for the result of an operation.
+ */
+static unsigned long *guest_gpr(struct cpu_user_regs *regs,
+                                const struct decoded_insn *di)
+{
+    /*
+     * decode_ldst_insn() is what fills @di in, and it rejects an access
+     * wider than a guest register.
+     */
+    ASSERT(di->len <= (guest_xlen(regs) / BITS_PER_BYTE));
+
+    return regs_gpr_ptr(regs, di->reg);
+}
+
+/*
+ * Obtain the instruction which caused a guest MMIO trap, filling in
+ * @di->insn and @di->insn_len. It either comes transformed in htinst, or has
+ * to be fetched from guest memory.
+ *
+ * Returns true if the fetch faulted in turn; the resulting trap has then
+ * already been redirected to the guest and there is nothing further for the
+ * caller to do. Where it returns false, @di has been filled in and emulation
+ * is to continue.
+ */
+static bool insn_fetch_faulted(const struct guest_fault *gf,
+                               struct decoded_insn *di)
+{
+    unsigned long htinst = gf->htinst;
+
+    /*
+     * A pseudoinstruction says nothing about the instruction the guest was
+     * executing, and comes with a guest physical address which isn't the one
+     * that instruction accessed. handle_guest_page_fault() deals with such a
+     * fault on its own, so no emulation can ever start for one.
+     */
+    ASSERT(!htinst_is_pseudo(htinst));
+
+    /*
+     * Bit[0] == 1 implies trapped instruction value is transformed instruction
+     * or custom value. A transformed instruction is a 32-bit encoding, so a
+     * value with any bit above bit[31] set is a custom one, which is of no use
+     * for decoding: fetch the instruction from guest memory then, as for zero.
+     */
+    if ( (htinst & BIT(0, UL)) && (htinst == (uint32_t)htinst) )
+    {
+        /*
+         * A compressed instruction is reported already expanded to its 32-bit
+         * equivalent, so htinst always holds a 32-bit encoding, except for
+         * bits[1:0], which hold a marker: bit[0] is set to flag the
+         * transformation and bit[1] is clear if the trapped instruction was
+         * compressed. Setting both bits gives a 32-bit encoding
+         * decode_ldst_insn() can decode. (Its handling of compressed
+         * encodings is for the branch below, which reads the instruction from
+         * guest memory as is.)
+         *
+         * The length then cannot come from the value anymore, only from
+         * bit[1]. And only a 16- or a 32-bit instruction is ever reported
+         * this way: the standard load and store instructions the hardware
+         * transforms are all of one of these two lengths, anything else comes
+         * as the zero special value handled below.
+         */
+        di->insn = htinst | 3;
+        di->insn_len = (htinst & BIT(1, UL)) ? 4 : 2;
+    }
+    else
+    {
+        const struct cpu_user_regs *regs = gf->regs;
+        struct trap_info utrap = {};
+
+        /*
+         * Bit[0] == 0 implies trapped instruction value is zero or special
+         * value. Pseudoinstructions never get here (see the comment ahead of
+         * the ASSERT() above), so only zero (or a custom value, see above) is
+         * left: the instruction has to be read from guest memory.
+         */
+
+        di->insn = read_guest(regs->sepc, true, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * If a G-stage translation fault happens while fetching the
+             * trapped instruction, CAUSE_LOAD_GUEST_PAGE_FAULT is generated,
+             * hlvx being a load. Such a fault is reported to the guest as an
+             * instruction access fault.
+             */
+            if ( utrap.scause == CAUSE_LOAD_GUEST_PAGE_FAULT )
+                utrap.scause = CAUSE_FETCH_ACCESS;
+
+            /*
+             * Not set in the initializer: on a fault read_guest() leaves in
+             * utrap.sepc the address of its own faulting access, whereas the
+             * trap is to be reported at the guest instruction.
+             */
+            utrap.sepc = regs->sepc;
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        di->insn_len = INSN_LEN(di->insn);
+
+        /*
+         * read_guest() fetches at most two halfwords, so a wider encoding has
+         * been read in part only and cannot be decoded here.
+         *
+         * Report an illegal instruction: none of the extensions exposed to
+         * guests has instructions wider than 32 bits, so such an encoding is
+         * not a valid instruction for the guest in the first place.
+         *
+         * The same goes for a compressed encoding where C isn't exposed to the
+         * guest. The instruction in guest memory may have changed since the
+         * trap, so what is read back must not be assumed to be what trapped,
+         * nor to be valid for the guest.
+         */
+        if ( !di->insn_len ||
+             (di->insn_len == 2 &&
+              !riscv_isa_extension_available(current->domain->arch.isa,
+                                             RISCV_ISA_EXT_c)) )
+        {
+            utrap.sepc = regs->sepc;
+            utrap.scause = CAUSE_ILLEGAL_INSTRUCTION;
+            /*
+             * stval is left zero, which the spec allows for an illegal
+             * instruction: only part of the instruction is in hand, and stval,
+             * being only XLEN bits wide, may not be able to hold all of it
+             * anyway.
+             */
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+    }
+
+    return false;
+}
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()). Fields which don't apply to the instruction are left
+ * alone, so @di is expected to start out zeroed.
+ *
+ * @xlen is the effective XLEN of the guest, needed as the encodings which
+ * exist for XLEN=64 only must not be recognized for a 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store, or cannot be
+ * emulated here.
+ */
+static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)
+{
+    uint32_t insn = di->insn;
+    unsigned int funct3, width_log2;
+
+    if ( INSN_IS_16BIT(insn) )
+    {
+        /*
+         * C.LW, C.LD, C.SW and C.SD (bits[1:0] == 00), and their sp-relative
+         * C.*SP forms (bits[1:0] == 10), have bits[15:13] of the form x1y:
+         * x is set for a store, and y selects a width of 4 or 8 bytes.
+         */
+        funct3 = RV_X(insn, 13, 3);
+
+        if ( (insn & 1) || !(funct3 & 2) )
+            return false;
+
+        di->is_write = funct3 & 4;
+        width_log2 = 2 + (funct3 & 1);
+
+        if ( !(insn & 2) )
+            /* Quadrant 0: bits[4:2] encode rd' (load) or rs2' (store) */
+            di->reg = RVC_RS2S(insn);
+        else if ( di->is_write )
+            /* Quadrant 2 (CSS): bits[6:2] encode rs2 for C.SWSP / C.SDSP */
+            di->reg = RVC_RS2(insn);
+        else
+        {
+            /* Quadrant 2 (CI): bits[11:7] encode rd for C.LWSP / C.LDSP */
+            di->reg = RV_RD(insn);
+
+            /* C.LWSP and C.LDSP are reserved with rd being x0. */
+            if ( !di->reg )
+                return false;
+        }
+    }
+    else
+    {
+        /*
+         * LOAD and STORE (I/S-type) have funct3 in bits[14:12]: funct3[1:0]
+         * is log2 of the width in bytes, and funct3[2] selects zero-extension
+         * for a load, while being reserved for a store.
+         */
+        funct3 = RV_X(insn, 12, 3);
+        width_log2 = funct3 & 3;
+
+        switch ( insn & INSN_OPCODE_MASK )
+        {
+        case INSN_OPCODE_LOAD:
+            di->is_unsigned = funct3 & 4;
+            di->reg = RV_RD(insn);
+            break;
+
+        case INSN_OPCODE_STORE:
+            if ( funct3 & 4 )
+                return false;
+            di->is_write = true;
+            di->reg = RV_RS2(insn);
+            break;
+
+        default:
+            return false;
+        }
+    }
+
+    di->len = 1U << width_log2;
+
+    /*
+     * No access is wider than XLEN, and one as wide as XLEN exists only in
+     * its sign-extending form: this rules out the encodings which exist for
+     * XLEN=64 only on a 32-bit guest, including C.FLW for C.LD (and alike).
+     */
+    if ( (di->len * BITS_PER_BYTE > xlen) ||
+         (di->is_unsigned && di->len * BITS_PER_BYTE == xlen) )
+        return false;
+
+    return true;
+}
+
 static int emulate_load(const struct guest_fault *gf)
 {
+    /* Transient, until the helpers gain their users. */
+    (void)advance_pc;
+    (void)guest_xlen;
+    (void)guest_gpr;
+    (void)insn_fetch_faulted;
+    (void)decode_ldst_insn;
+
     return -EOPNOTSUPP;
 }
 
xen/arch/riscv/include/asm/riscv_encoding.h +14 -0
index fa26f5a2eb86..4529bef856b1 100644
@@ -65,6 +65,14 @@
 #define SSTATUS64_UXL			MSTATUS_UXL
 #define SSTATUS64_SD			MSTATUS64_SD
 
+/*
+ * Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one
+ * encoding. 0 is reserved.
+ */
+#define XLEN_FIELD_32			_UL(1)
+#define XLEN_FIELD_64			_UL(2)
+#define XLEN_FIELD_128			_UL(3)
+
 #if __riscv_xlen == 64
 #define HSTATUS_VSXL			_UL(0x300000000)
 #define HSTATUS_VSXL_SHIFT		32
@@ -854,6 +862,10 @@
 /* 32-bit write for VS-stage address translation (VSXLEN=32) */
 #define INSN_PSEUDO_VS_STORE32		0x00002020
 
+#define INSN_OPCODE_MASK		0x7f
+#define INSN_OPCODE_LOAD		0x03
+#define INSN_OPCODE_STORE		0x23
+
 #define INSN_IS_16BIT(insn)	(((insn) & 3) != 3)
 #define INSN_IS_32BIT(insn)	(!INSN_IS_16BIT(insn) && ((insn) & 0x1c) != 0x1c)
 
@@ -895,6 +907,8 @@
 					 (RV_X(x, 7, 2) << 6))
 #define RVC_SDSP_IMM(x)			((RV_X(x, 10, 3) << 3) | \
 					 (RV_X(x, 7, 3) << 6))
+#define RV_RD(insn)			RV_X(insn, SH_RD, 5)
+#define RV_RS2(insn)			RV_X(insn, SH_RS2, 5)
 #define RVC_RS1S(insn)			(8 + RV_X(insn, SH_RD, 3))
 #define RVC_RS2S(insn)			(8 + RV_X(insn, SH_RS2C, 3))
 #define RVC_RS2(insn)			RV_X(insn, SH_RS2C, 5)
Signature · 1 line
2.56.1
#31 lore raw

PATCH v4 21/42 xen/riscv: add guest load emulation for trapped MMIO accesses

In reply to a message not in the archive

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

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

Sign and zero extension are done here rather than in the handlers: a shift pair drops whatever lies above the access width in the value read and, for a signed load, sign-extends it, so a handler need only report the value it read.

At the moment vINTC is the only backend registered with the MMIO dispatch, so in practice this only covers vINTC traps. An access which no handler claims currently crashes the domain; injecting an access fault into the guest instead is left for later.

---
Changes in v4:
- Drop the bits above the access width from the value read for an unsigned load too, so that a handler need not clear them itself.
- Update the commit message accordingly.
---
Changes in v3:
- Shorten the comment above "if ( di.reg )" by dropping redundant part.
- s/sizeof(unsigned long)/sizeof(info.data) in emulate_load().
- Zero-initialize di, as decode_ldst_insn() expects it to start out zeroed.
- Adjust to guest_gpr() taking the decoded instruction rather than a bare register number.
---
Changes in v2:
- Move the emulation code to the new arch/riscv/emulate.c, leaving traps.c with trap dispatch only.
- Split the patch up: struct decoded_insn and the decoding helpers are introduced by "xen/riscv: introduce the interface for trapped instruction decoding" and filled in by "xen/riscv: implement trapped instruction decoding", so only emulate_load() itself is left here.
- do_mmio() is no longer defined alongside emulate_load(); it now lives in mmio.c, next to the dispatch it drives.
- Don't write the result of a load into x0. SET_RD() wrote rd unconditionally, so a load into x0 clobbered regs->zero and broke the invariant that it reads as zero when x0 is a source operand elsewhere.
- Recognize the XLEN=64-only encodings by the guest's effective XLEN (guest_xlen()) rather than by Xen's own (CONFIG_RISCV_32). Besides those encodings simply being reserved on RV32, the compressed ones are ambiguous
there: C.LD and C.FLW share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW, C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
- Take the faulting address from struct guest_fault, filled in by resolve_faulting_gpa(), rather than from get_faulting_gpa().
- Drop the description of a fault taken while re-reading the trapped
instruction: that code is now in the patch implementing fetch_trapped_insn(), where a G-stage fault is reported to the guest as CAUSE_FETCH_ACCESS instead of hitting a BUG_ON().
- Update the commit message accordingly.
---

---
 xen/arch/riscv/emulate.c | 40 +++++++++++++++++++++++++++++++++-------
 1 file changed, 33 insertions(+), 7 deletions(-)
xen/arch/riscv/emulate.c +33 -7
index a30b2a7fadae..e95642b7617f 100644
@@ -14,6 +14,7 @@
 #include <asm/current.h>
 #include <asm/emulate.h>
 #include <asm/guest_access.h>
+#include <asm/mmio.h>
 #include <asm/processor.h>
 #include <asm/regs.h>
 #include <asm/riscv_encoding.h>
@@ -416,14 +417,39 @@ static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)
 
 static int emulate_load(const struct guest_fault *gf)
 {
-    /* Transient, until the helpers gain their users. */
-    (void)advance_pc;
-    (void)guest_xlen;
-    (void)guest_gpr;
-    (void)insn_fetch_faulted;
-    (void)decode_ldst_insn;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = false };
+    struct decoded_insn di = {};
+    unsigned int shift;
+    int rc;
 
-    return -EOPNOTSUPP;
+    /* A fault taken re-reading the instruction is redirected to the guest. */
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || di.is_write )
+        return -EOPNOTSUPP;
+
+    shift = BITS_PER_BYTE * (sizeof(info.data) - di.len);
+
+#ifdef EMULATE_LOAD_DEBUG
+    gdprintk(XENLOG_DEBUG, "pc=%#lx, addr=%#"PRIpaddr", len=%u, shift=%u\n",
+             regs->sepc, gf->gpa, di.len, shift);
+#endif
+
+    rc = do_mmio(&info, gf->gpa, di.len);
+    if ( rc )
+        return rc;
+
+    /* A load into x0 discards its result. */
+    if ( di.reg )
+        *guest_gpr(regs, &di) = di.is_unsigned
+                                ? (info.data << shift) >> shift
+                                : (long)(info.data << shift) >> shift;
+
+    advance_pc(regs, di.insn_len);
+
+    return 0;
 }
 
 static int emulate_store(const struct guest_fault *gf)
Signature · 1 line
2.56.1
#32 lore raw

PATCH v4 22/42 xen/riscv: add guest store emulation for trapped MMIO accesses

In reply to a message not in the archive

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

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

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

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

---
Changes in v4:
- Update the commit message.
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
---
Changes in v3:
- Update the commit message.
- Zero-initialize di, as decode_ldst_insn() expects it to start out zeroed.
- Adjust to guest_gpr() taking the decoded instruction rather than a bare register number.
- Don't change the prototype of emulate_store(): the stub takes a pointer to const already.
---
Changes in v2:
- Move the emulation code to the new arch/riscv/emulate.c, leaving traps.c with trap dispatch only.
- Split the patch up: the instruction fetch and the mask/match chain now live in "xen/riscv: add helpers for decoding a trapped load or store" (struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_gpr(), advance_pc()), so only emulate_store() itself is left here.
- Since the decoder is now shared with the load path, reject an encoding which is not a store (!di.is_write) explicitly; in v2 the mask/match chain was store-only and could not match a load.
- Recognize the XLEN=64-only encodings by the guest's effective XLEN (guest_xlen()) rather than by Xen's own (CONFIG_RISCV_32). Besides those encodings simply being reserved on RV32, the compressed ones are ambiguous
there: C.SD and C.FSW share an encoding, and likewise C.SDSP and C.FSWSP.
- Read the source register through guest_gpr() instead of the GET_RS2()/GET_RS2S()/GET_RS2C() macros; which of the three register fields an encoding names is now decided by decode_ldst_insn().
- Take the faulting address from struct guest_fault, filled in by resolve_faulting_gpa(), rather than from the fault_addr parameter.
- Drop the description of a fault taken while re-reading the trapped
instruction: that code is now in the patch adding the decoding helpers, where a G-stage fault is reported to the guest as CAUSE_FETCH_ACCESS.
- Update the commit message accordingly.
---

---
 xen/arch/riscv/emulate.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
xen/arch/riscv/emulate.c +20 -1
index e95642b7617f..170485ef4c01 100644
@@ -454,7 +454,26 @@ static int emulate_load(const struct guest_fault *gf)
 
 static int emulate_store(const struct guest_fault *gf)
 {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = true };
+    struct decoded_insn di = {};
+    int rc;
+
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || !di.is_write )
+        return -EOPNOTSUPP;
+
+    info.data = *guest_gpr(regs, &di);
+
+    rc = do_mmio(&info, gf->gpa, di.len);
+    if ( rc )
+        return rc;
+
+    advance_pc(regs, di.insn_len);
+
+    return 0;
 }
 
 static void inject_access_fault(const struct guest_fault *gf)
Signature · 1 line
2.56.1
#33 lore raw

PATCH v4 23/42 xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

In reply to a message not in the archive

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

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

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

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

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

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

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

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

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

---
 xen/arch/riscv/domain-build.c               |   8 ++
 xen/arch/riscv/domain.c                     | 123 ++++++++++++++++++++
 xen/arch/riscv/include/asm/domain.h         |   3 +
 xen/arch/riscv/include/asm/riscv_encoding.h |   2 +-
 xen/arch/riscv/include/asm/setup.h          |   2 +
 xen/arch/riscv/setup.c                      |   2 +
 6 files changed, 139 insertions(+), 1 deletion(-)
xen/arch/riscv/domain-build.c +8 -0
index 1e3abe259ccd..1acaf0946130 100644
@@ -15,9 +15,17 @@ int __init construct_domain(struct domain *d, struct kernel_info *kinfo)
 {
     struct vcpu *v = d->vcpu[0];
     struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(v);
+    unsigned int vsxl = domain_vsxl(d);
 
     BUG_ON(v->is_initialised);
 
+    /* Refuse the domain before any of its images are loaded. */
+    if ( !hstatus_vsxl_settable(vsxl) )
+    {
+        printk(XENLOG_ERR "%pd: hstatus.VSXL cannot be set to %u\n", d, vsxl);
+        return -EOPNOTSUPP;
+    }
+
     /*
      * At the moment *_load() don't return value and will just panic()
      * inside.
xen/arch/riscv/domain.c +123 -0

141 lines not on this page · raw message

xen/arch/riscv/include/asm/domain.h +3 -0
index c424e2428f60..005553648a3b 100644
@@ -144,6 +144,9 @@ int vcpu_unset_interrupt(struct vcpu *v, unsigned int irq);
 void vcpu_sync_interrupts(struct vcpu *curr);
 void vcpu_flush_interrupts(struct vcpu *curr);
 
+bool hstatus_vsxl_settable(unsigned int vsxl);
+unsigned int domain_vsxl(const struct domain *d);
+
 #endif /* RISCV_DOMAIN_H */
 
 /*
xen/arch/riscv/include/asm/riscv_encoding.h +1 -1
index 4529bef856b1..e909e1742f51 100644
@@ -69,13 +69,13 @@
  * Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one
  * encoding. 0 is reserved.
  */
+#define XLEN_FIELD_RESERVED		_UL(0)
 #define XLEN_FIELD_32			_UL(1)
 #define XLEN_FIELD_64			_UL(2)
 #define XLEN_FIELD_128			_UL(3)
 
 #if __riscv_xlen == 64
 #define HSTATUS_VSXL			_UL(0x300000000)
-#define HSTATUS_VSXL_SHIFT		32
 #endif
 #define HSTATUS_VTSR			_UL(0x00400000)
 #define HSTATUS_VTW			_UL(0x00200000)
xen/arch/riscv/include/asm/setup.h +2 -0
index 8eee8a746335..7e6e81751ddb 100644
@@ -11,6 +11,8 @@ void copy_from_paddr(void *dst, paddr_t paddr, unsigned long len);
 
 void init_csr_masks(void);
 
+void init_hstatus_vsxl_settable_mask(void);
+
 #endif /* RISCV_SETUP_H */
 
 /*
xen/arch/riscv/setup.c +2 -0
index 05f93a74c9d3..fd699defcfc3 100644
@@ -149,6 +149,8 @@ void __init noreturn start_xen(unsigned long bootcpu_id,
 
     init_csr_masks();
 
+    init_hstatus_vsxl_settable_mask();
+
     preinit_xen_time();
 
     intc_preinit();
Signature · 1 line
2.56.1
#34 lore raw

PATCH v4 24/42 xen/riscv: implement continue_new_vcpu()

In reply to a message not in the archive

continue_new_vcpu() is the arch hook invoked the first time a freshly created vCPU is scheduled. Implement both cases it has to cover:
- for the idle vCPU, switch to its own stack and jump to idle_loop();
- for a guest vCPU, enter the guest through the new return_to_new_vcpu() path in entry.S. It restores hstatus and sepc and passes the hart id in a0. a1 holds the DTB address for the boot vCPU (as expected by the RISC-V boot protocol), or the opaque value passed to SBI HSM hart_start() for secondary vCPUs. It then clears the remaining GPRs, sets sstatus.SPP and sstatus.SPIE, and executes sret.

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

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

Introduce get_cpu_info() and reset_stack_and_jump() in asm/current.h, needed by the above. get_cpu_info() is a macro rather than a static inline because asm/current.h is pulled in by <xen/percpu.h> before this_cpu() is defined and before <xen/sched.h> completes struct vcpu.

idle_loop() is only introduced as a stub.

---
Changes in v4:
- Split the description of the guest vCPU case in the commit message into several sentences.
- Call vcpu_set_vsxl() before entering the guest, as "xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL" now comes first.
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
---
Changes in v3:
- Drop unneeded inclusion of asm/aia.h, asm/aplic.h and asm/imsic.h.
- Mark return_to_new_vcpu() declaration with asmlinkage.
- Drop the "else" after reset_stack_and_jump(idle_loop), which cannot return.
- Move the restore of hstatus and the setting of sstatus.SPIE from continue_new_vcpu() to return_to_new_vcpu(), so that everything sret depends on is set up in one place, and shorten the comment in continue_new_vcpu() accordingly.
- Move the tp/SSCRATCH swap out to a separate patch, as nothing reads SSCRATCH yet.
- Reword the comments in return_to_new_vcpu(), which suggested that the values of .a0 and .a1 are established there.
- Clear the GPRs which are not meaningful to the vCPU being started before sret, so that Xen register values are not exposed to a guest.
- Update the commit message: a1 carries the opaque value passed to hart_start() for secondary vCPUs, describe the clearing of the GPRs, drop the comparison with a real CPU and the reference to a later implementation of idle_loop().
---
Changes in v2:
- New patch.
---

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

PATCH v4 25/42 xen/riscv: add basic VGEIN management for AIA guests

In reply to a message not in the archive

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

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

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

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

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

---
vgein_assign() gets its first user in "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu", and vgein_release() one taking the VGEIN of another pCPU in "xen/riscv: save and clear the old IMSIC VS-file on vCPU migration".
---
Changes in v4:
- Include <xen/sched.h> here, as this is where v gets dereferenced.
- Move ahead of the patches using vgein_assign() and vgein_release(), introducing them here instead of replacing stubs, and explain in the commit message why vgein_release() takes the pCPU and the bitmap is protected by a lock.
---
Changes in v3:
- Add Acked-by: Jan Beulich <[email protected]>.
- Add Reviewed-by: Baptiste Le Duc <[email protected]>.
---
Changes in v2:
- make vgein_init() pCPU agnostic as it is working with CSR which could be read only on local pCPU itself.
- Move introduction of vgein_ctrl->owners[] to separate patch.
- Add ASSERT() and re-init vgein->bmp with 0.
- Update the commit message (drop the last sentence as ->hstatus isn't filled anymore in in vgein_*() functions).
- Introduce vgein_deinit().
---

---
 xen/arch/riscv/aia.c             | 147 +++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aia.h |   5 ++
 2 files changed, 152 insertions(+)
xen/arch/riscv/aia.c +147 -0
index e31c9c2d24b6..b330da918154 100644
@@ -1,11 +1,31 @@
 /* SPDX-License-Identifier: GPL-2.0-only */
 
+#include <xen/bitops.h>
+#include <xen/cpu.h>
 #include <xen/errno.h>
 #include <xen/init.h>
+#include <xen/sched.h>
 #include <xen/sections.h>
+#include <xen/spinlock.h>
 #include <xen/types.h>
 
+#include <asm/aia.h>
 #include <asm/cpufeature.h>
+#include <asm/csr.h>
+#include <asm/current.h>
+
+struct vgein_ctrl {
+    /* The least-significant bits are implemented first, apart from bit 0 */
+    unsigned long bmp;
+    spinlock_t lock;
+    unsigned int geilen;
+};
+
+/*
+ * VGEIN control structure for each physical CPU to track which VS (guest)
+ * interrupt file IDs are in use.
+ */
+static DEFINE_PER_CPU(struct vgein_ctrl, vgein);
 
 static bool __ro_after_init _aia_usable;
 
@@ -14,10 +34,137 @@ bool aia_usable(void)
     return _aia_usable;
 }
 
+/* HGEIE is a per-hart CSR, so this has to run on the CPU being initialized. */
+static int vgein_init(void)
+{
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    spin_lock_init(&vgein->lock);
+
+    csr_write(CSR_HGEIE, ~0UL);
+    vgein->geilen = flsl(csr_read(CSR_HGEIE) >> 1);
+    csr_write(CSR_HGEIE, 0);
+
+    vgein->bmp = 0;
+
+    if ( !vgein->geilen )
+        return -EOPNOTSUPP;
+
+    return 0;
+}
+
+static void vgein_deinit(void)
+{
+    csr_write(CSR_HGEIE, 0);
+}
+
+static int cf_check cpu_callback(struct notifier_block *nfb,
+                                 unsigned long action, void *hcpu)
+{
+    unsigned int cpu = (unsigned long)hcpu;
+    int rc = 0;
+
+    switch ( action )
+    {
+    case CPU_STARTING:
+        rc = vgein_init();
+        if ( rc )
+            printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
+                   cpu, rc);
+        break;
+
+    case CPU_DYING:
+        vgein_deinit();
+        break;
+    }
+
+    return notifier_from_errno(rc);
+}
+
+static struct notifier_block cpu_nfb = {
+    .notifier_call = cpu_callback,
+};
+
 void __init aia_init(void)
 {
+    int rc;
+
     if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_ssaia) )
+    {
+        dprintk(XENLOG_WARNING, "SSAIA isn't present in riscv,isa\n");
+        return;
+    }
+
+    if ( (rc = vgein_init()) )
+    {
+        dprintk(XENLOG_ERR, "vgein_init() failed: %d\n", rc);
         return;
+    }
 
     _aia_usable = true;
+
+    register_cpu_notifier(&cpu_nfb);
+}
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    unsigned int vgein_id;
+    struct vgein_ctrl *vgein = &per_cpu(vgein, v->processor);
+    unsigned long *bmp = &vgein->bmp;
+    unsigned long flags;
+
+    if ( !vgein->geilen )
+        return 0;
+
+    spin_lock_irqsave(&vgein->lock, flags);
+    /*
+     * The vgein_id shouldn't be zero, as it will indicate that no guest
+     * external interrupt source is selected for VS-level external interrupts
+     * according to RISC-V privileged spec:
+     *   Hypervisor Status Register (hstatus) in RISC-V privileged spec:
+     *
+     *   The VGEIN (Virtual Guest External Interrupt Number) field selects
+     *   a guest external interrupt source for VS-level external interrupts.
+     *   VGEIN is a WLRL field that must be able to hold values between zero
+     *   and the maximum guest external interrupt number (known as GEILEN),
+     *   inclusive.
+     *   When VGEIN=0, no guest external interrupt source is selected for
+     *   VS-level external interrupts.
+     *
+     * So start to search from bit number 1.
+     */
+    vgein_id = find_next_zero_bit(bmp, vgein->geilen + 1, 1);
+
+    if ( vgein_id > vgein->geilen )
+        vgein_id = 0;
+    else
+        __set_bit(vgein_id, bmp);
+
+    spin_unlock_irqrestore(&vgein->lock, flags);
+
+#ifdef VGEIN_DEBUG
+    gprintk(XENLOG_DEBUG, "%s: %pv: vgein_id(%u), xen_cpu%u_bmp=%#lx\n",
+            __func__, v, vgein_id, v->processor, *bmp);
+#endif
+
+    return vgein_id;
+}
+
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
+{
+    unsigned long flags;
+    struct vgein_ctrl *vgein = &per_cpu(vgein, cpu);
+
+    if ( !vgein_id )
+        return;
+
+    spin_lock_irqsave(&vgein->lock, flags);
+    if ( !__test_and_clear_bit(vgein_id, &vgein->bmp) )
+        ASSERT_UNREACHABLE();
+    spin_unlock_irqrestore(&vgein->lock, flags);
+
+#ifdef VGEIN_DEBUG
+    gprintk(XENLOG_DEBUG, "%s: %pv: vgein_id(%u), xen_cpu%u_bmp=%#lx\n",
+            __func__, v, vgein_id, cpu, vgein->bmp);
+#endif
 }
xen/arch/riscv/include/asm/aia.h +5 -0
index aaa4bf91fc75..8e4eb2f6b14e 100644
@@ -3,8 +3,13 @@
 #ifndef RISCV_AIA_H
 #define RISCV_AIA_H
 
+struct vcpu;
+
 bool aia_usable(void);
 
 void aia_init(void);
 
+unsigned int vgein_assign(struct vcpu *v);
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu);
+
 #endif /* RISCV_AIA_H */
Signature · 1 line
2.56.1
#36 lore raw

PATCH v4 26/42 xen/riscv: map IMSIC interrupt file for vCPUs

In reply to a message not in the archive

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.

---
imsic_map_guest_file() gets its user in "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu".
---
Changes in v4:
- Move ahead of the patch using imsic_map_guest_file(), introducing it here instead of replacing a stub.
---
Changes in v3:
- Add Acked-by: Jan Beulich <[email protected]>
- Use dprintk() instead of printk() for the IMSIC_DEBUG message in imsic_map_guest_file().
- Add Reviewed-by: Baptiste Le Duc <[email protected]>
---
Changes in v2:
- Use GUEST_IMSIC_S_BASE instead of imsic_cfg.base_addr as the base of the guest address to map to, and change the type of gaddr to paddr_t as it holds a guest physical address.
- Rename guest_stride to guest_offset: it is an offset of the VS-file inside the pCPU's IMSIC block, not a stride.
- Use PRIpaddr for physical addresses and %u for unsigned values in the debug/error messages.
- Switch the mapping failure message from printk() to dprintk(XENLOG_ERR, ...).
- Update the comment above imsic_map_guest_file(): vCPUs aren't pinned, they run on the pCPU chosen by the scheduler, and mention that on migration a VS-file is acquired on the new pCPU and mapped at the same GFN, so the stale mapping is replaced rather than explicitly torn down.
---

---
 xen/arch/riscv/imsic.c             | 69 ++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/imsic.h |  2 +
 2 files changed, 71 insertions(+)
xen/arch/riscv/imsic.c +69 -0
index 8f29c5d2eec1..a17aae7b6ffa 100644
@@ -26,6 +26,7 @@
 #include <xen/xvmalloc.h>
 
 #include <asm/imsic.h>
+#include <asm/p2m.h>
 
 #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
 
@@ -342,6 +343,74 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
     return 0;
 }
 
+/*
+ * Map the physical IMSIC guest interrupt file (G-file) assigned to vCPU
+ * into the domain's stage-2 guest-physical address space.
+ *
+ * In the machine's physical address space (SPA), each hart's IMSIC
+ * supervisor-level file (S-file) is located at offset 0 of its address block,
+ * followed contiguously by GEILEN guest files at offsets of 1, 2, ..., N pages.
+ *
+ * Because a guest OS running in VS-mode expects its own supervisor-level
+ * interrupt file to be at offset 0 of its guest-physical IMSIC block, the
+ * hypervisor must use stage-2 address translation to map the vCPU's
+ * guest-physical "supervisor" page (GPA offset 0) to the specific
+ * physical guest file page (SPA offset guest_file_id) on the physical hart.
+ *
+ * A vCPU runs on the pCPU the scheduler picked for it (v->processor), and
+ * the guest file it is given (guest_file_id, from the vGEIN allocator)
+ * belongs to that very pCPU's IMSIC. A guest_file_id of 0 indicates that no
+ * hardware guest file is selected (matching the architectural behavior where
+ * vGEIN = 0 in the hstatus CSR selects no guest external interrupt source),
+ * requiring the VS-file to be emulated in software.
+ *
+ * Consequently the mapping installed here is only valid as long as the vCPU
+ * stays on that pCPU. When it migrates, a VS-file is acquired on the new
+ * pCPU and mapped at the very same GFN, so the stale mapping needs no
+ * explicit tear-down: it is simply replaced.
+ *
+ * The base guest-physical address advertised to the guest in the device
+ * tree matches offset 0 of the vCPU's virtual IMSIC block. Stage-2
+ * translation ensures that guest supervisor accesses to this page are
+ * transparently routed to the real hardware VS-file granted to it on
+ * the pCPU it currently runs on.
+ */
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    struct domain *d = v->domain;
+    unsigned int cpu = v->processor;
+    paddr_t gaddr = GUEST_IMSIC_S_BASE + (IMSIC_MMIO_PAGE_SZ * v->vcpu_id);
+    paddr_t paddr, guest_offset;
+    int res;
+
+    /* Nothing to map in the case of sw interrupt file. */
+    if ( !vsfile_id )
+        return 0;
+
+    guest_offset = vsfile_id * IMSIC_MMIO_PAGE_SZ;
+
+    paddr = imsic_cfg.msi[cpu].base_addr + imsic_cfg.msi[cpu].offset +
+            guest_offset;
+
+#ifdef IMSIC_DEBUG
+    dprintk(XENLOG_DEBUG,
+            "%s: %pv: ga(%#"PRIpaddr") -> pa(%#"PRIpaddr"), cpu(%u), "
+            "guest_file_id(%u) base_addr(%#"PRIpaddr") offset(%#lx)\n",
+            __func__, v, gaddr, paddr, cpu, vsfile_id,
+            imsic_cfg.msi[cpu].base_addr, imsic_cfg.msi[cpu].offset);
+#endif
+
+    res = map_regions_p2mt(d, gaddr_to_gfn(gaddr),
+                           PFN_DOWN(IMSIC_MMIO_PAGE_SZ), maddr_to_mfn(paddr),
+                           arch_dt_passthrough_p2m_type());
+    if ( res )
+        dprintk(XENLOG_ERR,
+                "%s: Failed to map %#"PRIpaddr" to the guest at %#"PRIpaddr"\n",
+                __func__, paddr, gaddr);
+
+    return res;
+}
+
 int cf_check vcpu_imsic_init(struct vcpu *v)
 {
     struct vimsic_state *imsic_state;
xen/arch/riscv/include/asm/imsic.h +2 -0
index 11e1e3950f42..0f68e8e89496 100644
@@ -96,4 +96,6 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
 int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
+
 #endif /* RISCV_IMSIC_H */
Signature · 1 line
2.56.1
#37 lore raw

PATCH v4 27/42 xen/riscv: introduce vaplic_reconfigure_target()

In reply to a message not in the archive

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

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

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

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

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

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

---
 xen/arch/riscv/aplic.c              | 13 ++++++-
 xen/arch/riscv/include/asm/vaplic.h |  3 ++
 xen/arch/riscv/vaplic.c             | 60 +++++++++++++++++++++++++++++
 3 files changed, 75 insertions(+), 1 deletion(-)
xen/arch/riscv/aplic.c +12 -1
index 51d7eae4617a..825eb60bf444 100644
@@ -129,7 +129,11 @@ static unsigned long aplic_hart_index(unsigned int cpu)
 /*
  * v->processor can't be used here: during a migration it names the new pCPU
  * before the interrupt file is moved there. The caller has to hold
- * vsfile_lock until the result is written to the h/w.
+ * vsfile_lock, so that the guest file id and the pCPU owning it are read as
+ * a consistent pair. A value may still be built from the old file just
+ * before a migration publishes the new one, so whoever publishes a new file
+ * has to call vaplic_reconfigure_target() afterwards, to rewrite every
+ * source targeting the vCPU.
  */
 uint32_t aplic_msi_target_gen(const struct vcpu *v, uint32_t base_val)
 {
@@ -140,6 +144,13 @@ uint32_t aplic_msi_target_gen(const struct vcpu *v, uint32_t base_val)
     ASSERT(rw_is_locked(&vimsic_state->vsfile_lock));
     ASSERT(vimsic_state->vsfile_cpu < NR_CPUS);
 
+    /*
+     * The callers rely on the physical APLIC being in MSI delivery mode.
+     * Checking that here rather than in each of them means none can be
+     * missed should direct delivery mode ever be supported.
+     */
+    ASSERT(aplic_msi_mode());
+
     hart_index = aplic_hart_index(vimsic_state->vsfile_cpu);
 
     base_val &= APLIC_TARGET_EIID;
xen/arch/riscv/include/asm/vaplic.h +3 -0
index 9a121904a346..843b78e80ad8 100644
@@ -17,6 +17,7 @@
 #include <asm/intc.h>
 
 struct domain;
+struct vcpu;
 
 #define to_vaplic(d) container_of((d)->arch.vintc, struct vaplic, vintc)
 
@@ -50,4 +51,6 @@ struct vaplic {
 int domain_vaplic_init(struct domain *d);
 void domain_vaplic_deinit(struct domain *d);
 
+void vaplic_reconfigure_target(const struct vcpu *v);
+
 #endif /* RISCV_VAPLIC_H */
xen/arch/riscv/vaplic.c +60 -0

66 lines not on this page · raw message

Signature · 1 line
2.56.1
#38 lore raw

PATCH v4 28/42 xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu

In reply to a message not in the archive

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

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

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

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

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

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

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

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

---
Changes in v4:
- s/HSTATUS.VGEIN/hstatus.VGEIN/ in a comment.
- Reword the commit message paragraph on reconfiguring the vAPLIC target registers on the first attach.
- Move ahead of the vCPU migration patches, so that the attach no longer has to be fitted into the finished migration code: imsic_vsfile_move() and its first_attach argument are gone, and imsic_vsfile_attach() is a plain sequence of its own.
- Take over imsic_vsfile_acquire() and imsic_update_state() from "xen/riscv: remap interrupts to new IMSIC VS-file", and the clearing of the file, together with the helpers it needs, from "xen/riscv: prepare new IMSIC VS-file", which is gone. They come with the changes made to them in v4: imsic_eix_check() and imsic_vs_csr_write() used directly instead of the switchcase expansion pyramid, and the switch of hstatus.VGEIN factored out into imsic_vsfile_select() and imsic_vsfile_deselect().
- Move the IOMMU TODO into imsic_vsfile_acquire(), next to the G-stage mapping it is the counterpart of.
- Introduce imsic_vsfile_set_vgein(), to be shared with imsic_migrate_vcpu().
- Clear the file with a direct call: the file is taken on the pCPU the vCPU runs on, so imsic_call_on_cpu() is left to "xen/riscv: remap interrupts to new IMSIC VS-file", which first needs another pCPU. Give imsic_vsfile_local_clear() a typed pointer, drop its cf_check.
---
Changes in v3:
- imsic_update_state() is now implemented by "xen/riscv: remap interrupts to new IMSIC VS-file".
- Share the code of imsic_vsfile_attach() and imsic_migrate_vcpu() in imsic_vsfile_move(), whose first_attach argument skips the part moving state out of the old file.
- Call vaplic_reconfigure_target() on the first attach as well, so that vAPLIC targets the guest wrote for the vCPU before it got its file reach the h/w.
- Replace panic() for a vCPU left without a h/w file by domain_crash():
it can only happen to a vCPU whose first imsic_vsfile_acquire() failed and crashed its domain, and such a vCPU can still be migrated.
- imsic_vsfile_acquire(), together with the vgein_release() on a mapping failure, is now introduced by "xen/riscv: remap interrupts to new IMSIC VS-file", without the cpu argument (the file is always taken on v->processor).
- Include asm/imsic.h for imsic_vsfile_attach().
- Drop imsic_nr_eix() in favour of imsic_cfg.nr_eix.
- Drop vcpu_set_vgein(): with the code shared in imsic_vsfile_move(), hstatus.VGEIN is updated in one place only.
- Rework the commit message: drop the stale vcpu_aia_init() name and the claim that the IMSIC state has no concurrent readers yet.
---
Changes in v2:
- Update vcpu_aia_init() to catch sw interrupt file and update some debug messages in it.
- Add vgein_release() if IMSIC h/w mapping failed.
- imsic_update_state(): store v->processor rather than cpuid_to_hartid(), as ->vsfile_cpu is consumed as a Xen CPU id (aplic_hart_field(), cpumask_of()) and its NR_CPUS sentinel lives in that numbering space.
- Drop parentheses around guest_file_id ? ... in imsic_update_state().
- Rename vcpu_aia_init to imsic_vsfile_attach() and move the code to imsic.c.
---

---
 xen/arch/riscv/domain.c            |   3 +
 xen/arch/riscv/imsic.c             | 221 +++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/imsic.h |   9 ++
 xen/arch/riscv/vaplic.c            |   3 +-
 4 files changed, 235 insertions(+), 1 deletion(-)
xen/arch/riscv/domain.c +3 -0
index 65d582aa8fe0..1b2ab7ab468c 100644
@@ -13,6 +13,7 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/gpr-num.h>
+#include <asm/imsic.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
@@ -265,6 +266,8 @@ static void continue_new_vcpu(struct vcpu *prev)
 
     vcpu_set_vsxl(current);
 
+    imsic_vsfile_attach(current);
+
     /*
      * return_to_new_vcpu() sets up hstatus.SPV, sstatus.SPP and sepc so
      * that sret enters the guest in VS-mode. A trap taken in HS-mode
xen/arch/riscv/imsic.c +221 -0

255 lines not on this page · raw message

xen/arch/riscv/include/asm/imsic.h +9 -0
index 0f68e8e89496..be45a11cce22 100644
@@ -55,6 +55,13 @@ struct imsic_config {
     /* Number off interrupt identities */
     unsigned int nr_ids;
 
+    /*
+     * Number of 64-bit EIx groups needed to cover all the interrupt
+     * identities, which are 0 (never valid, but it still occupies a bit) up
+     * to and including nr_ids.
+     */
+    unsigned int nr_eix;
+
     /* MSI */
     const struct imsic_msi *msi;
 
@@ -98,4 +105,6 @@ int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
 int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
 
+void imsic_vsfile_attach(struct vcpu *v);
+
 #endif /* RISCV_IMSIC_H */
xen/arch/riscv/vaplic.c +2 -1
index 42489bf299b9..464a8a142798 100644
@@ -153,7 +153,8 @@ static void vaplic_target_write(const struct domain *d, unsigned int irqn,
      * The h/w register names the hart and the guest interrupt file MSIs are
      * sent to, and there is none of either until the target vCPU is given a
      * h/w guest interrupt file, so until then only the stored copy is
-     * updated.
+     * updated. imsic_vsfile_attach() writes it to the h/w, through
+     * vaplic_reconfigure_target(), once there is such a file.
      *
      * TODO: once s/w guest interrupt files are supported, a vCPU using one
      * still needs its MSIs, so the h/w register will have to be written for
Signature · 1 line
2.56.1
#39 lore raw

PATCH v4 29/42 xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to a message not in the archive

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

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

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

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

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

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

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

---
 xen/arch/riscv/aia.c                | 33 +++++++++++++++
 xen/arch/riscv/domain.c             | 19 +++++++--
 xen/arch/riscv/imsic.c              | 66 +++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aia.h    |  2 +
 xen/arch/riscv/include/asm/domain.h |  1 +
 xen/arch/riscv/include/asm/imsic.h  |  3 ++
 xen/arch/riscv/traps.c              |  7 ++-
 xen/arch/riscv/vaplic.c             |  6 +++
 8 files changed, 133 insertions(+), 4 deletions(-)
xen/arch/riscv/aia.c +33 -0
index b330da918154..0e9104d7ef4c 100644
@@ -18,6 +18,13 @@ struct vgein_ctrl {
     /* The least-significant bits are implemented first, apart from bit 0 */
     unsigned long bmp;
     spinlock_t lock;
+    /*
+     * Guest interrupt file IDs run from 1 to geilen inclusive (0 means that
+     * no guest external interrupt source is selected), and geilen can never
+     * exceed BITS_PER_LONG - 1, so indexing this array by the ID directly
+     * always fits.
+     */
+    struct vcpu *owners[BITS_PER_LONG];
     unsigned int geilen;
 };
 
@@ -138,7 +145,10 @@ unsigned int vgein_assign(struct vcpu *v)
     if ( vgein_id > vgein->geilen )
         vgein_id = 0;
     else
+    {
         __set_bit(vgein_id, bmp);
+        vgein->owners[vgein_id] = v;
+    }
 
     spin_unlock_irqrestore(&vgein->lock, flags);
 
@@ -161,6 +171,8 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
     spin_lock_irqsave(&vgein->lock, flags);
     if ( !__test_and_clear_bit(vgein_id, &vgein->bmp) )
         ASSERT_UNREACHABLE();
+    ASSERT(vgein->owners[vgein_id] == v);
+    vgein->owners[vgein_id] = NULL;
     spin_unlock_irqrestore(&vgein->lock, flags);
 
 #ifdef VGEIN_DEBUG
@@ -168,3 +180,24 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
             __func__, v, vgein_id, cpu, vgein->bmp);
 #endif
 }
+
+void hgei_interrupt(void)
+{
+    unsigned long hgei_mask, flags;
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    hgei_mask = csr_read(CSR_HGEIP);
+    hgei_mask &= csr_read(CSR_HGEIE);
+
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    for_each_set_bit ( guest_file_id, hgei_mask )
+    {
+        if ( vgein->owners[guest_file_id] )
+            vcpu_kick(vgein->owners[guest_file_id]);
+    }
+
+    spin_unlock_irqrestore(&vgein->lock, flags);
+}
xen/arch/riscv/domain.c +16 -3
index 1b2ab7ab468c..2e130608b34f 100644
@@ -251,6 +251,12 @@ static void vcpu_csr_init(struct vcpu *v)
         v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                             csr_masks.ro_one.hstateen0;
     }
+
+    /*
+     * Enable SGEIs, so that a guest interrupt file marked in HGEIE while
+     * the vCPU is descheduled can raise an interrupt to Xen.
+     */
+    v->arch.hie = BIT(IRQ_S_GEXT, UL);
 }
 
 static void schedule_tail(struct vcpu *prev);
@@ -498,10 +504,12 @@ static bool vcpu_can_access_vsiselect(const struct vcpu *v)
 static void csrs_ctxt_switch_from(struct vcpu *p)
 {
     /*
-     * hedeleg, hideleg, henvcfg, hcounteren, htimedelta and hstateen0 aren't
-     * saved: neither the guest nor Xen changes them other than by
+     * hedeleg, hideleg, hie, henvcfg, hcounteren, htimedelta and hstateen0
+     * aren't saved: neither the guest nor Xen changes them other than by
      * csrs_ctxt_switch_to() writing them from v->arch.*, which is left
-     * unchanged after vcpu_csr_init().
+     * unchanged after vcpu_csr_init(). The exception are the VS-level bits
+     * of hie, which alias bits of vsie: the guest changes them through vsie,
+     * and they are saved and restored as part of it.
      */
 
     p->arch.hvip = csr_read(CSR_HVIP);
@@ -523,6 +531,7 @@ static void csrs_ctxt_switch_to(struct vcpu *n)
     csr_write(CSR_HEDELEG, n->arch.hedeleg);
     csr_write(CSR_HIDELEG, n->arch.hideleg);
     csr_write(CSR_HVIP, n->arch.hvip);
+    csr_write(CSR_HIE, n->arch.hie);
     csr_write64(HENVCFG, n->arch.henvcfg);
     csr_write(CSR_HCOUNTEREN, n->arch.hcounteren);
     csr_write64(HTIMEDELTA, n->arch.htimedelta);
@@ -531,6 +540,10 @@ static void csrs_ctxt_switch_to(struct vcpu *n)
         csr_write(CSR_HSTATEEN0, n->arch.hstateen0);
 
     csr_write(CSR_VSSTATUS, n->arch.vsstatus);
+    /*
+     * Has to come after hideleg and hie: the bits of vsie delegated by
+     * hideleg alias the VS-level bits of hie, which n->arch.hie has clear.
+     */
     csr_write64(VSIE, n->arch.vsie);
     csr_write(CSR_VSTVEC, n->arch.vstvec);
     csr_write(CSR_VSSCRATCH, n->arch.vsscratch);
xen/arch/riscv/imsic.c +66 -0

78 lines not on this page · raw message

xen/arch/riscv/include/asm/aia.h +2 -0
index 8e4eb2f6b14e..6a05bdd8c236 100644
@@ -12,4 +12,6 @@ void aia_init(void);
 unsigned int vgein_assign(struct vcpu *v);
 void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu);
 
+void hgei_interrupt(void);
+
 #endif /* RISCV_AIA_H */
xen/arch/riscv/include/asm/domain.h +1 -0
index 005553648a3b..2274ac2ab1e9 100644
@@ -68,6 +68,7 @@ struct arch_vcpu {
     register_t hstateen0;
     uint64_t   htimedelta;
     register_t hvip;
+    register_t hie;
 
     register_t vsatp;
     register_t vscause;
xen/arch/riscv/include/asm/imsic.h +3 -0
index be45a11cce22..090e902e4579 100644
@@ -103,6 +103,9 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
 int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
+void cf_check imsic_ctxt_switch_from(struct vcpu *p);
+void cf_check imsic_ctxt_switch_to(struct vcpu *n);
+
 int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
 
 void imsic_vsfile_attach(struct vcpu *v);
xen/arch/riscv/traps.c +6 -1
index 97e604091458..93996580cccf 100644
@@ -12,9 +12,10 @@
 #include <xen/sched.h>
 #include <xen/softirq.h>
 
-#include <asm/extable.h>
+#include <asm/aia.h>
 #include <asm/cpufeature.h>
 #include <asm/emulate.h>
+#include <asm/extable.h>
 #include <asm/intc.h>
 #include <asm/processor.h>
 #include <asm/riscv_encoding.h>
@@ -273,6 +274,10 @@ void do_trap(struct cpu_user_regs *cpu_regs)
                 timer_interrupt();
                 break;
 
+            case IRQ_S_GEXT:
+                hgei_interrupt();
+                break;
+
             default:
                 intr_handled = false;
                 break;
xen/arch/riscv/vaplic.c +6 -0
index 464a8a142798..eb2a263ceecb 100644
@@ -617,6 +617,12 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
 static const struct vintc_ops vintc_ops = {
     .vcpu_init = vcpu_imsic_init,
     .vcpu_deinit = vcpu_imsic_deinit,
+    /*
+     * MSI delivery is the only supported mode, so the vAPLIC state to save
+     * and restore is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
+    .ctxt_switch_to = imsic_ctxt_switch_to,
 };
 
 int domain_vaplic_init(struct domain *d)
Signature · 1 line
2.56.1
#40 lore raw

PATCH v4 30/42 xen/riscv: implement APLIC-IMSIC-hart sync barrier for vCPU migration

In reply to a message not in the archive

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

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

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

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

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

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

---
 xen/arch/riscv/aplic.c             | 51 ++++++++++++++++++++++++++++++
 xen/arch/riscv/imsic.c             | 47 +++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aplic.h |  3 ++
 xen/arch/riscv/include/asm/imsic.h | 23 ++++++++++++++
 4 files changed, 124 insertions(+)
xen/arch/riscv/aplic.c +51 -0
index 825eb60bf444..0be62c9d90f1 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,
@@ -185,6 +187,37 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
     spin_unlock_irqrestore(&aplic.lock, flags);
 }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    /*
+     * imsic_sync_id() is nr_ids, which imsic_parse_node() limits to
+     * IMSIC_MAX_ID, so it always fits into the EIID field.
+     */
+    BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
+    ASSERT(imsic_sync_id(imsic) <= IMSIC_MAX_ID);
+
+    val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
+          imsic_sync_id(imsic);
+
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
@@ -215,6 +248,7 @@ static int __init cf_check aplic_init(void)
     uint64_t size, paddr;
     const struct dt_device_node *imsic_node;
     const struct dt_device_node *node = aplic_info.node;
+    const struct imsic_config *imsic;
     int rc;
 
     /* Check for associated imsic node */
@@ -239,6 +273,23 @@ static int __init cf_check aplic_init(void)
         panic("%s: failed to get number of interrupt sources\n",
               node->full_name);
 
+    /*
+     * Xen drives the APLIC in MSI delivery mode only, mapping each source 1:1
+     * to an interrupt identity of its own IMSIC interrupt file: source i is
+     * given EIID i (see aplic_set_irq_affinity()). Hence only the sources
+     * numbered up to imsic_nr_free_ids() can be used: the identities above
+     * are either reserved or not implemented.
+     */
+    imsic = imsic_get_config();
+    if ( aplic_info.num_irqs > imsic_nr_free_ids(imsic) )
+    {
+        printk(XENLOG_WARNING
+               "%s: only %u of %u interrupt sources usable with %u IMSIC identities\n",
+               node->full_name, imsic_nr_free_ids(imsic), aplic_info.num_irqs,
+               imsic->nr_ids);
+        aplic_info.num_irqs = imsic_nr_free_ids(imsic);
+    }
+
     guest_aplic_num_sources = min(GUEST_APLIC_MAX_SOURCES, aplic_info.num_irqs);
 
     if ( aplic_info.num_irqs > ARRAY_SIZE(aplic.regs->sourcecfg) )
xen/arch/riscv/imsic.c +47 -0

77 lines not on this page · raw message

xen/arch/riscv/include/asm/aplic.h +3 -0
index b2f1d140f6f8..37584039107b 100644
@@ -89,6 +89,7 @@
 #define APLIC_SETIPNUM_BE               0x2004
 
 #define APLIC_GENMSI                    0x3000
+#define APLIC_GENMSI_BUSY               BIT(12, U)
 
 #define APLIC_TARGET_BASE               0x3004
 #define APLIC_TARGET_LAST               0x3ffc
@@ -173,4 +174,6 @@ struct aplic_regs {
 uint32_t aplic_hw_read_reg(unsigned int offset);
 void aplic_hw_write_reg(unsigned int offset, uint32_t value);
 
+void aplic_genmsi_barrier(void);
+
 #endif /* RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +23 -0
index 090e902e4579..1f3ccfbccd1e 100644
@@ -69,6 +69,29 @@ struct imsic_config {
     spinlock_t lock;
 };
 
+/*
+ * The identities of Xen's own interrupt file are allocated statically:
+ *  - the reserved ones are taken from the top down; so far that's only the
+ *    last one, nr_ids, for APLIC-to-hart synchronization;
+ *  - 1 .. imsic_nr_free_ids(), i.e. all those below the reserved ones, are
+ *    left for the APLIC sources, as Xen gives source N the EIID N
+ *    (aplic_init() drops the sources which don't fit).
+ * A new reserved identity has to be taken below the lowest one reserved so
+ * far, with imsic_nr_free_ids() lowered accordingly.
+ */
+
+/* Interrupt identity reserved for APLIC-to-hart synchronization. */
+static inline unsigned int imsic_sync_id(const struct imsic_config *cfg)
+{
+    return cfg->nr_ids;
+}
+
+/* Interrupt identities 1 .. imsic_nr_free_ids() aren't reserved. */
+static inline unsigned int imsic_nr_free_ids(const struct imsic_config *cfg)
+{
+    return imsic_sync_id(cfg) - 1;
+}
+
 struct vimsic_state {
     /* IMSIC VS-file */
     rwlock_t vsfile_lock;
Signature · 1 line
2.56.1
#41 lore raw

PATCH v4 31/42 xen/riscv: introduce imsic_migrate_vcpu()

In reply to a message not in the archive

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

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

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

Nothing calls imsic_migrate_vcpu() yet.

---
Changes in v4:
- New patch, replacing "xen/riscv: handle the case when no vCPU migration is needed": the vCPU's interrupt file is now moved by the vCPU itself on its way back to the guest rather than from arch_move_irqs(), so what has to be told first is whether the file belongs to another pCPU, rather than whether the vCPU has run yet. Why the file isn't moved from arch_move_irqs() is explained in more detail in "xen/riscv: introduce arch_move_irqs()".
---

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

PATCH v4 32/42 xen/riscv: remap interrupts to new IMSIC VS-file

In reply to a message not in the archive

Implement the first steps of migrating a vCPU to a different guest interrupt file: take a new one on the vCPU's new pCPU with imsic_vsfile_acquire(), which brings it to a clean state, maps it into the guest's G-stage in place of the old one and records it in the vCPU's IMSIC state. Then, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

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

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

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

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

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

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

PATCH v4 33/42 xen/riscv: save and clear the old IMSIC VS-file on vCPU migration

In reply to a message not in the archive

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

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

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

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

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

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

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

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

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

PATCH v4 34/42 xen/riscv: restore register state in the new IMSIC VS-file

In reply to a message not in the archive

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

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

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

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

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

---
 xen/arch/riscv/imsic.c | 56 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 55 insertions(+), 1 deletion(-)
xen/arch/riscv/imsic.c +55 -1
index c705b287c7ff..adacac5c7268 100644
@@ -115,6 +115,12 @@ do {                            \
     csr_swap(CSR_VSIREG, v);        \
 })
 
+#define imsic_vs_csr_set(c, v)      \
+do {                                \
+    csr_write(CSR_VSISELECT, c);    \
+    csr_set(CSR_VSIREG, v);         \
+} while (0)
+
 #define imsic_vs_csr_write(c, v)    \
 do {                                \
     csr_write(CSR_VSISELECT, c);    \
@@ -156,6 +162,15 @@ static uint64_t imsic_eix_swap64(unsigned int ireg, uint64_t val)
     return old;
 }
 
+/* Set bits of a whole 64-bit EIx group (see imsic_eix_check()). */
+static void imsic_eix_set64(unsigned int ireg, uint64_t val)
+{
+    imsic_eix_check(ireg);
+    imsic_vs_csr_set(ireg, val);
+    if ( IS_ENABLED(CONFIG_RISCV_32) )
+        imsic_vs_csr_set(ireg + 1, val >> 32);
+}
+
 unsigned int vcpu_guest_file_id(const struct vcpu *v)
 {
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -1087,6 +1102,42 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
     return fdt_end_node(fdt);
 }
 
+static void imsic_vsfile_local_update(const struct imsic_vsfile_data *idata)
+{
+    unsigned int i;
+    const struct imsic_mrif *mrif = idata->mrif;
+    struct imsic_vsfile_ctx ctx;
+    unsigned long flags;
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*
+     * No atomic accessors are needed to read the values out of the MRIF here,
+     * as this is always called with a pointer to a temporary MRIF on the
+     * stack.
+     */
+
+    /* Nothing on this pCPU is to run with the file selected meanwhile. */
+    local_irq_save(flags);
+
+    imsic_vsfile_select(idata->hgei, &ctx);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_set64(IMSIC_EIP0 + i * 2, mrif->eix[i].eip);
+        imsic_eix_set64(IMSIC_EIE0 + i * 2, mrif->eix[i].eie);
+    }
+
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, mrif->eithreshold);
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, mrif->eidelivery);
+
+    imsic_vsfile_deselect(&ctx);
+
+    local_irq_restore(flags);
+}
+
 /*
  * Take a h/w guest interrupt file on the pCPU @v runs on and make it the
  * vCPU's one.
@@ -1270,7 +1321,10 @@ static void imsic_vsfile_move(struct vcpu *v)
     /* Free-up old IMSIC VS-file */
     vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    imsic_vsfile_local_update(&vsfile_data);
+
+    imsic_vsfile_set_vgein(v, vsfile_data.hgei);
 }
 
 /*
Signature · 1 line
2.56.1
#45 lore raw

PATCH v4 35/42 xen/riscv: move a vCPU's guest interrupt file on its way to the guest

In reply to a message not in the archive

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

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

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

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

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

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

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

---
Changes in v4:
- Don't implement vintc_ops.move_irqs for vAPLIC: arch_move_irqs() can be called with the vCPU free to run on its new pCPU, so moving the vCPU's guest interrupt file from there would race with the vCPU running. Add vintc_ops.enter_guest instead, run by vintc_enter_guest() from check_for_pcpu_work(), and implement it for vAPLIC with imsic_migrate_vcpu().
- Let a vINTC leave vintc_ops.move_irqs unset.
- Make imsic_migrate_vcpu() cf_check, as it is an indirect call target.
- Move right after "xen/riscv: restore register state in the new IMSIC VS-file", so that the hooks are wired up to a complete move of the vCPU's guest interrupt file.
- Drop the Acked-by and the Reviewed-by, as the patch changed.
- Rename from "xen/riscv: introduce arch_move_irqs()", as the vCPU's guest interrupt file is moved on its way to the guest rather than by arch_move_irqs().
- Update the commit message accordingly.
---
Changes in v3:
- Update the commit message: drop the two last paragraphs as they are stale.
---
Changes in v2:
- New patch.
---

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

PATCH v4 36/42 xen/riscv: send MSIs to a vCPU's guest interrupt file

In reply to a message not in the archive

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

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

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

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

---
vcpu_imsic_inject() gets its users in "xen/riscv: emulate the vAPLIC genmsi register", for the MSIs a guest asks for through genmsi, and in "xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC sources", for the MSIs of virtual vAPLIC sources.

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

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

---
Changes in v4:
- New patch.
---

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

PATCH v4 37/42 xen/riscv: sync with IMSIC VS-file injections on vCPU migration

In reply to a message not in the archive

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

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

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

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

---
Before making a final decision on this patch, please review:
https://github.com/riscv/riscv-aia/issues/172

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

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

If this synchronization is actually needed, then let's go back to making V100 tolerate MSI reservation failures for the VS-file instead of panicking.
---
Changes in v4:
- New patch.
---

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

PATCH v4 38/42 xen/riscv: emulate the vAPLIC genmsi register

In reply to a message not in the archive

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

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

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

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

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

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

---
Changes in v4:
- New patch.
---

---
 xen/arch/riscv/imsic.c              | 40 ++++++++++++++
 xen/arch/riscv/include/asm/aplic.h  |  4 +-
 xen/arch/riscv/include/asm/imsic.h  |  2 +
 xen/arch/riscv/include/asm/vaplic.h |  6 +++
 xen/arch/riscv/vaplic.c             | 82 +++++++++++++++++++++++++----
 5 files changed, 124 insertions(+), 10 deletions(-)
xen/arch/riscv/imsic.c +40 -0
index e72a710b2d28..e7627dd48041 100644
@@ -811,6 +811,46 @@ static void cf_check imsic_aplic_sync(void *data)
     imsic_vsfile_local_sync(idata->hgei);
 }
 
+/*
+ * Make sure that all the MSIs the h/w APLIC or vAPLIC has already sent to @v's
+ * IMSIC interrupt file have arrived there.
+ *
+ * The barrier has to be executed by the pCPU owning the file, so for a file
+ * owned by another pCPU an IPI is sent, which has to be done with IRQs
+ * enabled.
+ *
+ * vsfile_lock can't be held across the barrier: the IPI takes IRQs enabled,
+ * while the write side is taken with IRQs disabled, by imsic_update_state()
+ * when @v acquires a file on the very pCPU the IPI goes to, so the two would
+ * wait for each other. Nor is it needed, should @v be migrated meanwhile:
+ *  - the migration does the barrier for the old file itself before moving its
+ *    state into the new one, and it is done by @v itself before it enters the
+ *    guest again;
+ *  - MSIs are redirected to the new file only after it has been published,
+ *    so whatever reaches the new file was sent after the lookup done here;
+ *  - should the file have been handed to another vCPU meanwhile, the wait
+ *    touches only the identity Xen reserves in it.
+ */
+void vcpu_imsic_aplic_barrier(const struct vcpu *v)
+{
+    struct vimsic_state *imsic = v->arch.vimsic_state;
+    struct imsic_vsfile_data idata = { };
+    unsigned long flags;
+    unsigned int cpu;
+
+    /* The file and the pCPU owning it have to be read together. */
+    read_lock_irqsave(&imsic->vsfile_lock, flags);
+    cpu = imsic->vsfile_cpu;
+    idata.hgei = imsic->guest_file_id;
+    read_unlock_irqrestore(&imsic->vsfile_lock, flags);
+
+    /* With no interrupt file, there is nothing an MSI can be on its way to. */
+    if ( cpu == CPU_NONE )
+        return;
+
+    imsic_call_on_cpu(cpu, imsic_aplic_sync, &idata);
+}
+
 /*
  * Make interrupt identity @iid pending in @v's IMSIC interrupt file, as an MSI
  * addressed to that file would.
xen/arch/riscv/include/asm/aplic.h +3 -1
index 37584039107b..5b4ae0d91f50 100644
@@ -89,7 +89,9 @@
 #define APLIC_SETIPNUM_BE               0x2004
 
 #define APLIC_GENMSI                    0x3000
-#define APLIC_GENMSI_BUSY               BIT(12, U)
+#define  APLIC_GENMSI_HART_IDX          GENMASK(31, 18)
+#define  APLIC_GENMSI_BUSY              BIT(12, U)
+#define  APLIC_GENMSI_EIID              GENMASK(10, 0)
 
 #define APLIC_TARGET_BASE               0x3004
 #define APLIC_TARGET_LAST               0x3ffc
xen/arch/riscv/include/asm/imsic.h +2 -0
index f372761b8853..5fc8f8067fcf 100644
@@ -150,4 +150,6 @@ void cf_check imsic_migrate_vcpu(struct vcpu *v);
 
 int vcpu_imsic_inject(const struct vcpu *v, unsigned int iid);
 
+void vcpu_imsic_aplic_barrier(const struct vcpu *v);
+
 #endif /* RISCV_IMSIC_H */
xen/arch/riscv/include/asm/vaplic.h +6 -0
index 843b78e80ad8..360ad3021751 100644
@@ -33,6 +33,9 @@ struct vaplic_source {
 struct vaplic_regs {
     uint32_t domaincfg;
 
+    /* Register to generate an extempore MSI. */
+    uint32_t genmsi;
+
     /*
      * Indexed by source number. The array holds d->arch.vintc->nr_virqs
      * elements; sources[0] is unused as APLIC interrupt sources start from 1.
@@ -44,6 +47,9 @@ struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
 
+    /* Protects access to the vAPLIC registers. */
+    spinlock_t lock;
+
     paddr_t regs_start;
     unsigned int regs_size;
 };
xen/arch/riscv/vaplic.c +73 -9

108 lines not on this page · raw message

Signature · 1 line
2.56.1
#49 lore raw

PATCH v4 39/42 xen/riscv: emulate vAPLIC sourcecfg[], setie[] and domaincfg.IE

In reply to a message not in the archive

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

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

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

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

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

---
Changes in v4:
- New patch.
---

---
 xen/arch/riscv/include/asm/vaplic.h |  28 +-
 xen/arch/riscv/vaplic.c             | 491 ++++++++++++++++++++++------
 2 files changed, 422 insertions(+), 97 deletions(-)
xen/arch/riscv/include/asm/vaplic.h +26 -2
index 360ad3021751..e2e4611f69c2 100644
@@ -23,11 +23,22 @@ struct vcpu;
 
 /* State of one vAPLIC interrupt source. */
 struct vaplic_source {
-    /* Protects target together with the h/w target register of the source. */
+    /*
+     * Protects target and sourcecfg, together with the corresponding h/w
+     * registers of a h/w source.
+     */
     spinlock_t lock;
 
     /* Guest's view of the APLIC target register. */
     uint32_t target;
+
+    /*
+     * sourcecfg register as the guest sees it:
+     *  - for a virtual source, this is the only place it is kept;
+     *  - for a h/w source, it is a copy of the h/w register, which only the
+     *    guest changes.
+     */
+    uint32_t sourcecfg;
 };
 
 struct vaplic_regs {
@@ -36,6 +47,15 @@ struct vaplic_regs {
     /* Register to generate an extempore MSI. */
     uint32_t genmsi;
 
+    /*
+     * Interrupt-enable bits as the guest sees them, a word per 32 sources:
+     *  - for a virtual source, this is the only place its bit is kept;
+     *  - for a h/w source, it is a copy of the h/w bit, which only the guest
+     *    changes. While domaincfg.IE is 0, the h/w bit is kept clear and the
+     *    guest's view is kept here only.
+     */
+    uint32_t *ie;
+
     /*
      * Indexed by source number. The array holds d->arch.vintc->nr_virqs
      * elements; sources[0] is unused as APLIC interrupt sources start from 1.
@@ -47,7 +67,11 @@ struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
 
-    /* Protects access to the vAPLIC registers. */
+    /*
+     * Protects access to the vAPLIC registers. A vaplic_source.lock, where
+     * needed too, is taken first, to avoid an ABBA deadlock (see
+     * vaplic_sourcecfg_write()).
+     */
     spinlock_t lock;
 
     paddr_t regs_start;
xen/arch/riscv/vaplic.c +396 -95

623 lines not on this page · raw message

Signature · 1 line
2.56.1
#50 lore raw

PATCH v4 40/42 xen/riscv: emulate target[] of virtual vAPLIC sources

In reply to a message not in the archive

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

---
Changes in v4:
- New patch.
---

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

PATCH v4 41/42 xen/riscv: emulate the pending bits and MSIs of virtual vAPLIC sources

In reply to a message not in the archive

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

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

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

---
Changes in v4:
- New patch.
---

---
 xen/arch/riscv/include/asm/vaplic.h |  16 ++
 xen/arch/riscv/vaplic.c             | 314 +++++++++++++++++++++++-----
 2 files changed, 275 insertions(+), 55 deletions(-)
xen/arch/riscv/include/asm/vaplic.h +16 -0
index e2e4611f69c2..f2c768e84b11 100644
@@ -39,6 +39,15 @@ struct vaplic_source {
      *    guest changes.
      */
     uint32_t sourcecfg;
+
+    /*
+     * Level of the line of a virtual source, protected by vaplic->lock.
+     *
+     * TODO: nothing drives it yet. The emulator of a device with an interrupt
+     * line will have to, and to call vaplic_forward_msis() for a source a
+     * change of the level makes pending.
+     */
+    bool level;
 };
 
 struct vaplic_regs {
@@ -56,6 +65,13 @@ struct vaplic_regs {
      */
     uint32_t *ie;
 
+    /*
+     * Interrupt-pending bits of the virtual sources, a word per 32 sources.
+     * Those of the h/w sources change in the h/w by themselves, so they are
+     * read from the h/w instead.
+     */
+    uint32_t *ip;
+
     /*
      * Indexed by source number. The array holds d->arch.vintc->nr_virqs
      * elements; sources[0] is unused as APLIC interrupt sources start from 1.
xen/arch/riscv/vaplic.c +259 -55

427 lines not on this page · raw message

Signature · 1 line
2.56.1
#52 lore raw

PATCH v4 42/42 xen/riscv: drive the line of a virtual vAPLIC source

In reply to a message not in the archive

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

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

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

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

[1] https://gitlab.com/xen-project/people/olkur/xen/-/tree/riscv-vuart-support-wip?ref_type=heads
---
Changes in v4:
- New patch.
---

---
 xen/arch/riscv/include/asm/intc.h   |  9 +++++
 xen/arch/riscv/include/asm/vaplic.h |  8 ++---
 xen/arch/riscv/intc.c               | 14 ++++++++
 xen/arch/riscv/vaplic.c             | 51 +++++++++++++++++++++++++++++
 4 files changed, 77 insertions(+), 5 deletions(-)
xen/arch/riscv/include/asm/intc.h +9 -0
index d188a45b3fe1..a332838bea17 100644
@@ -8,6 +8,8 @@
 #ifndef RISCV_INTC_H
 #define RISCV_INTC_H
 
+#include <xen/types.h>
+
 struct dt_device_node;
 
 enum intc_variant {
@@ -79,6 +81,10 @@ struct vintc_ops {
      * guest.
      */
     void (*enter_guest)(struct vcpu *v);
+
+    /* Set the level of the line of a virtual source */
+    void (*set_irq_level)(const struct domain *d, unsigned int virq,
+                          bool level);
 };
 
 struct vintc {
@@ -114,4 +120,7 @@ void vintc_ctxt_switch_to(struct vcpu *n);
 
 void vintc_enter_guest(struct vcpu *v);
 
+void vintc_set_irq_level(const struct domain *d, unsigned int virq,
+                         bool level);
+
 #endif /* RISCV_INTC_H */
xen/arch/riscv/include/asm/vaplic.h +3 -5
index f2c768e84b11..1d5b9840be6c 100644
@@ -41,11 +41,9 @@ struct vaplic_source {
     uint32_t sourcecfg;
 
     /*
-     * Level of the line of a virtual source, protected by vaplic->lock.
-     *
-     * TODO: nothing drives it yet. The emulator of a device with an interrupt
-     * line will have to, and to call vaplic_forward_msis() for a source a
-     * change of the level makes pending.
+     * Level of the line of a virtual source, as the emulator of the device
+     * in Xen drives it through vintc_set_irq_level(). Protected by
+     * vaplic->lock.
      */
     bool level;
 };
xen/arch/riscv/intc.c +14 -0
index 449f6b252414..630c6d2ae730 100644
@@ -224,3 +224,17 @@ void vintc_enter_guest(struct vcpu *v)
     if ( ops->enter_guest )
         ops->enter_guest(v);
 }
+
+/*
+ * Set the level of the line of virtual source @virq of @d. To be used by the
+ * emulator of a device in Xen, the line of which is connected to @virq: such
+ * a source has to be reserved with vintc_reserve_virq(), and no h/w IRQ may be
+ * routed to it.
+ */
+void vintc_set_irq_level(const struct domain *d, unsigned int virq,
+                         bool level)
+{
+    const struct vintc_ops *ops = d->arch.vintc->ops;
+
+    ops->set_irq_level(d, virq, level);
+}
xen/arch/riscv/vaplic.c +51 -0

63 lines not on this page · raw message

Signature · 1 line
2.56.1