Skip to contentSkip to conversation

RISCV basic exception handling implementation

PATCH Applied Oleksii Kurochko 3 participants 11 messages Aug 11, 2023 – Aug 14, 2023 RISC-V

v8 of 13 Applied Latest is v13 →

lore
Share & tools
lore
#1 lore raw

PATCH v8 1/6 xen/riscv: introduce temporary printk stuff

In reply to Oleksii Kurochko

The patch introdcuces printk related stuff which should be deleted after Xen common code will be available.

---
Changes in V8:
- only rebase was done.
---
Changes in V7:
- only rebase was done.
---
Changes in V6:
- the patch was introduced in the current patch series (V6)

---
 xen/arch/riscv/early_printk.c | 168 ++++++++++++++++++++++++++++++++++
 1 file changed, 168 insertions(+)
xen/arch/riscv/early_printk.c +168 -0
index 610c814f54..60742a042d 100644
@@ -40,3 +40,171 @@ void early_printk(const char *str)
         str++;
     }
 }
+
+/*
+ * The following #if 1 ... #endif should be removed after printk
+ * and related stuff are ready.
+ */
+#if 1
+
+#include <xen/stdarg.h>
+#include <xen/string.h>
+
+/**
+ * strlen - Find the length of a string
+ * @s: The string to be sized
+ */
+size_t (strlen)(const char * s)
+{
+    const char *sc;
+
+    for (sc = s; *sc != '\0'; ++sc)
+        /* nothing */;
+    return sc - s;
+}
+
+/**
+ * memcpy - Copy one area of memory to another
+ * @dest: Where to copy to
+ * @src: Where to copy from
+ * @count: The size of the area.
+ *
+ * You should not use this function to access IO space, use memcpy_toio()
+ * or memcpy_fromio() instead.
+ */
+void *(memcpy)(void *dest, const void *src, size_t count)
+{
+    char *tmp = (char *) dest, *s = (char *) src;
+
+    while (count--)
+        *tmp++ = *s++;
+
+    return dest;
+}
+
+int vsnprintf(char* str, size_t size, const char* format, va_list args)
+{
+    size_t i = 0; /* Current position in the output string */
+    size_t written = 0; /* Total number of characters written */
+    char* dest = str;
+
+    while ( format[i] != '\0' && written < size - 1 )
+    {
+        if ( format[i] == '%' )
+        {
+            i++;
+
+            if ( format[i] == '\0' )
+                break;
+
+            if ( format[i] == '%' )
+            {
+                if ( written < size - 1 )
+                {
+                    dest[written] = '%';
+                    written++;
+                }
+                i++;
+                continue;
+            }
+
+            /*
+             * Handle format specifiers.
+             * For simplicity, only %s and %d are implemented here.
+             */
+
+            if ( format[i] == 's' )
+            {
+                char* arg = va_arg(args, char*);
+                size_t arglen = strlen(arg);
+
+                size_t remaining = size - written - 1;
+
+                if ( arglen > remaining )
+                    arglen = remaining;
+
+                memcpy(dest + written, arg, arglen);
+
+                written += arglen;
+                i++;
+            }
+            else if ( format[i] == 'd' )
+            {
+                int arg = va_arg(args, int);
+
+                /* Convert the integer to string representation */
+                char numstr[32]; /* Assumes a maximum of 32 digits */
+                int numlen = 0;
+                int num = arg;
+                size_t remaining;
+
+                if ( arg < 0 )
+                {
+                    if ( written < size - 1 )
+                    {
+                        dest[written] = '-';
+                        written++;
+                    }
+
+                    num = -arg;
+                }
+
+                do
+                {
+                    numstr[numlen] = '0' + num % 10;
+                    num = num / 10;
+                    numlen++;
+                } while ( num > 0 );
+
+                /* Reverse the string */
+                for (int j = 0; j < numlen / 2; j++)
+                {
+                    char tmp = numstr[j];
+                    numstr[j] = numstr[numlen - 1 - j];
+                    numstr[numlen - 1 - j] = tmp;
+                }
+
+                remaining = size - written - 1;
+
+                if ( numlen > remaining )
+                    numlen = remaining;
+
+                memcpy(dest + written, numstr, numlen);
+
+                written += numlen;
+                i++;
+            }
+        }
+        else
+        {
+            if ( written < size - 1 )
+            {
+                dest[written] = format[i];
+                written++;
+            }
+            i++;
+        }
+    }
+
+    if ( size > 0 )
+        dest[written] = '\0';
+
+    return written;
+}
+
+void printk(const char *format, ...)
+{
+    static char buf[1024];
+
+    va_list args;
+    va_start(args, format);
+
+    (void)vsnprintf(buf, sizeof(buf), format, args);
+
+    early_printk(buf);
+
+    va_end(args);
+}
+
+#endif
+
Signature · 1 line
2.41.0
#0 lore raw

v8 cover RISCV basic exception handling implementation

The patch series is based on:
xen/riscv: introduce identity mapping [1]
which haven't been merged yet.

The patch series provides a basic implementation of exception handling. It can do only basic things such as decode a cause of an exception, save/restore registers and execute "wfi" instruction if an exception can not be handled.

To verify that exception handling works well it was implemented macros from <asm/bug.h> such as BUG/WARN/run_in_exception/assert_failed. The implementation of macros is used "ebreak" instruction and set up bug frame tables for each type of macros.
Also it was implemented register save/restore to return and continue work after WARN/run_in_exception.
Not all functionality of the macros was implemented as some of them require hard-panic the system which is not available now. Instead of hard-panic 'wfi' instruction is used but it should be definitely changed in the neareset future.
It wasn't implemented show_execution_state() and stack trace discovering as it's not necessary now.

[1] https://lore.kernel.org/xen-devel/177ad805a6508cf4adc9f54c20333ebcf12c333b.1691507564.git.oleksii.kurochko@gmail.com/

---
Changes in V8:
- Update the commit message of the cover letter.
- Remove the patch with an introduction of dummy asm/bug.h and introduce normal asm/bug.h
- Fix typo in return string from decode_reserved_interrupt_cause
- Add "Acked-by: Alistair Francis <[email protected]>" for the patch "xen/riscv: introduce decode_cause() stuff"
- Remove Pointless initializer of id in do_bug_frame().
- Make bug_frames[] array constant in do_bug_frame().
- Remove cast_to_bug_frame(addr).
- Rename is_valig_bugaddr to is_valid_bug_insn().
- Add check that read_instr is used only on Xen code
- Update the commit message.
---
Changes in V7:
- Update the depenency ( mentioned in the cover letter message ) of the current patch series.
- clean up comments.
- code style fixes.
- move definition of cast_to_bug_frame() from patch 4 to 5.
---
Changes in V6:
- Update the cover letter message: the patch set is based on MMU patch series.
- Introduce new patch with temporary printk functionality. ( it will be removed when Xen common code will be ready )
- Change early_printk() to printk().
- Remove usage of LINK_TO_LOAD() due to the MMU being enabled first.
- Add additional explanatory comments.
- Remove patch "xen/riscv: initialize boot_info structure" from the patch series.
---
Changes in V5:
- Rebase on top of [1] and [2]
- Add new patch which introduces stub for <asm/bug.h> to keep Xen compilable as in the patch [xen/riscv: introduce decode_cause() stuff] is used
header <xen/lib.h> which requires <asm/bug.h>.
- Remove <xen/error.h> from riscv/traps/c as nothing would require
inclusion.
- decode_reserved_interrupt_cause(), decode_interrupt_cause(),
decode_cause, do_unexpected_trap() were made as static they are expected
to be used only in traps.c
- Remove "#include <xen/types.h>" from <asm/bug.h> as there is no any need in it anymore
- Update macros GET_INSN_LENGTH: remove UL and 'unsigned int len;' from it
- Remove " include <xen/bug.h>" from risc/setup.c. it is not needed in the current version of the patch
- change an argument type from vaddr_t to uint32_t for is_valid_bugaddr and introduce read_instr() to read instruction properly as the length of qinstruction can be either 32 or 16 bits.
- Code style fixes
- update the comments before do_bug_frame() in riscv/trap.c
- [[PATCH v4 5/5] automation: modify RISC-V smoke test ] was dropped as it was provided more simple solution by Andrew. CI: Simplify RISCV smoke testing
- Refactor is_valid_bugaddr() function.
- 2 new patches ([PATCH v5 {1-2}/7]) were introduced, the goal of which is to recalculate addresses used in traps.c, which can be linker time relative. It is needed as we don't have enabled MMU yet.
---
Changes in V4:
- Rebase the patch series on top of new version of [introduce generic implementation of macros from bug.h] patch series.
- Update the cover letter message as 'Early printk' was merged and
the current one patch series is based only on [introduce generic implementation of macros from bug.h] which hasn't been commited yet.
- The following patches of the patch series were merged to staging:
[PATCH v3 01/14] xen/riscv: change ISA to r64G
[PATCH v3 02/14] xen/riscv: add <asm/asm.h> header
[PATCH v3 03/14] xen/riscv: add <asm/riscv_encoding.h header
[PATCH v3 04/14] xen/riscv: add <asm/csr.h> header
[PATCH v3 05/14] xen/riscv: introduce empty <asm/string.h>
[PATCH v3 06/14] xen/riscv: introduce empty <asm/cache.h>
[PATCH v3 07/14] xen/riscv: introduce exception context
[PATCH v3 08/14] xen/riscv: introduce exception handlers implementation [PATCH v3 10/14] xen/riscv: mask all interrupts
- Fix addressed comments in xen-devel mailing list.

---
Changes in V3:
- Change the name of config RISCV_ISA_RV64IMA to RISCV_ISA_RV64G as instructions from Zicsr and Zifencei extensions aren't part of I extension any more.
- Rebase the patch "xen/riscv: introduce an implementation of macros from <asm/bug.h>" on top of patch series [introduce generic implementation of macros from bug.h]
- Update commit messages
---
Changes in V2:
- take the latest riscv_encoding.h from OpenSBI, update it with Xen related changes, and update the commit message with "Origin:" tag and the commit message itself.
- add "Origin:" tag to the commit messag of the patch [xen/riscv: add <asm/csr.h> header].
- Remove the patch [xen/riscv: add early_printk_hnum() function] as the functionality provided by the patch isn't used now.
- Refactor prcoess.h: move structure offset defines to asm-offsets.c, change register_t to unsigned long.
- Refactor entry.S to use offsets defined in asm-offsets.C
- Rename {__,}handle_exception to handle_trap() and do_trap() to be more consistent with RISC-V spec.
- Merge the pathc which introduces do_unexpected_trap() with the patch [xen/riscv: introduce exception handlers implementation].
- Rename setup_trap_handler() to trap_init() and update correspondingly the patches in the patch series.
- Refactor bug.h, remove bug_instr_t type from it.
- Refactor decode_trap_cause() function to be more optimization-friendly.
- Add two new empty headers: <cache.h> and <string.h> as they are needed to include <xen/lib.h> which provides ARRAY_SIZE and other macros.
- Code style fixes.
---

Oleksii Kurochko (6):
xen/riscv: introduce temporary printk stuff
xen/riscv: introduce <asm/bug.h>
xen/riscv: introduce decode_cause() stuff
xen/riscv: introduce trap_init()
xen/riscv: implement do_bug_frame()
xen/riscv: test basic handling stuff

 xen/arch/riscv/early_printk.c      | 168 +++++++++++++++++++++
 xen/arch/riscv/include/asm/bug.h   |  37 +++++
 xen/arch/riscv/include/asm/traps.h |   1 +
 xen/arch/riscv/setup.c             |  20 +++
 xen/arch/riscv/traps.c             | 234 ++++++++++++++++++++++++++++-
 xen/arch/riscv/xen.lds.S           |  10 ++
 6 files changed, 469 insertions(+), 1 deletion(-)
 create mode 100644 xen/arch/riscv/include/asm/bug.h
Signature · 1 line
2.41.0
#3 lore raw

PATCH v8 2/6 xen/riscv: introduce <asm/bug.h>

---
Changes in V8:
- new patch. It was introduced instead of dummy asm/bug.h introduction.

---
 xen/arch/riscv/include/asm/bug.h | 37 ++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
 create mode 100644 xen/arch/riscv/include/asm/bug.h
xen/arch/riscv/include/asm/bug.h new file +37 -0
new file mode 100644
index 0000000000..f5ff96140f
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2012 Regents of the University of California
+ * Copyright (C) 2021-2023 Vates
+ *
+ */
+#ifndef _ASM_RISCV_BUG_H
+#define _ASM_RISCV_BUG_H
+
+#ifndef __ASSEMBLY__
+
+#define BUG_INSTR "ebreak"
+
+/*
+ * The base instruction set has a fixed length of 32-bit naturally aligned
+ * instructions.
+ *
+ * There are extensions of variable length ( where each instruction can be
+ * any number of 16-bit parcels in length ).
+ *
+ * Compressed ISA is used now where the instruction length is 16 bit  and
+ * 'ebreak' instruction, in this case, can be either 16 or 32 bit (
+ * depending on if compressed ISA is used or not )
+ */
+#define INSN_LENGTH_MASK        _UL(0x3)
+#define INSN_LENGTH_32          _UL(0x3)
+
+#define BUG_INSN_32             _UL(0x00100073) /* ebreak */
+#define BUG_INSN_16             _UL(0x9002)     /* c.ebreak */
+#define COMPRESSED_INSN_MASK    _UL(0xffff)
+
+#define GET_INSN_LENGTH(insn)                               \
+    (((insn) & INSN_LENGTH_MASK) == INSN_LENGTH_32 ? 4 : 2) \
+
+#endif /* !__ASSEMBLY__ */
+
+#endif /* _ASM_RISCV_BUG_H */
Signature · 1 line
2.41.0
#5 lore raw

PATCH v8 3/6 xen/riscv: introduce decode_cause() stuff

In reply to Oleksii Kurochko

The patch introduces stuff needed to decode a reason of an exception.

---
Changes in V8:
- fix typo in return string from decode_reserved_interrupt_cause
- add Acked-by: Alistair Francis <[email protected]>
---
Changes in V7:
- Nothing changed. Only rebase.
---
Changes in V6:
- Remove usage of LINK_TO_LOAD() due to the MMU being enabled first.
- Change early_printk() to printk()
---
Changes in V5:
- Remove <xen/error.h> from riscv/traps/c as nothing would require
inclusion.
- decode_reserved_interrupt_cause(), decode_interrupt_cause(), decode_cause, do_unexpected_trap() were made as static they are expected to be used only in traps.c
- use LINK_TO_LOAD() for addresses which can be linker time relative.
---
Changes in V4:
- fix string in decode_reserved_interrupt_cause()
---
Changes in V3:
- Nothing changed
---
Changes in V2:
- Make decode_trap_cause() more optimization friendly.
- Merge the pathc which introduces do_unexpected_trap() to the current one.

---
 xen/arch/riscv/traps.c | 84 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 83 insertions(+), 1 deletion(-)
xen/arch/riscv/traps.c +83 -1
index ccd3593f5a..a2b63d579b 100644
@@ -4,10 +4,92 @@
  *
  * RISC-V Trap handlers
  */
+
+#include <xen/lib.h>
+
+#include <asm/csr.h>
+#include <asm/early_printk.h>
 #include <asm/processor.h>
 #include <asm/traps.h>
 
-void do_trap(struct cpu_user_regs *cpu_regs)
+static const char *decode_trap_cause(unsigned long cause)
+{
+    static const char *const trap_causes[] = {
+        [CAUSE_MISALIGNED_FETCH] = "Instruction Address Misaligned",
+        [CAUSE_FETCH_ACCESS] = "Instruction Access Fault",
+        [CAUSE_ILLEGAL_INSTRUCTION] = "Illegal Instruction",
+        [CAUSE_BREAKPOINT] = "Breakpoint",
+        [CAUSE_MISALIGNED_LOAD] = "Load Address Misaligned",
+        [CAUSE_LOAD_ACCESS] = "Load Access Fault",
+        [CAUSE_MISALIGNED_STORE] = "Store/AMO Address Misaligned",
+        [CAUSE_STORE_ACCESS] = "Store/AMO Access Fault",
+        [CAUSE_USER_ECALL] = "Environment Call from U-Mode",
+        [CAUSE_SUPERVISOR_ECALL] = "Environment Call from S-Mode",
+        [CAUSE_MACHINE_ECALL] = "Environment Call from M-Mode",
+        [CAUSE_FETCH_PAGE_FAULT] = "Instruction Page Fault",
+        [CAUSE_LOAD_PAGE_FAULT] = "Load Page Fault",
+        [CAUSE_STORE_PAGE_FAULT] = "Store/AMO Page Fault",
+        [CAUSE_FETCH_GUEST_PAGE_FAULT] = "Instruction Guest Page Fault",
+        [CAUSE_LOAD_GUEST_PAGE_FAULT] = "Load Guest Page Fault",
+        [CAUSE_VIRTUAL_INST_FAULT] = "Virtualized Instruction Fault",
+        [CAUSE_STORE_GUEST_PAGE_FAULT] = "Guest Store/AMO Page Fault",
+    };
+
+    if ( cause < ARRAY_SIZE(trap_causes) && trap_causes[cause] )
+        return trap_causes[cause];
+    return "UNKNOWN";
+}
+
+static const char *decode_reserved_interrupt_cause(unsigned long irq_cause)
+{
+    switch ( irq_cause )
+    {
+    case IRQ_M_SOFT:
+        return "M-mode Software Interrupt";
+    case IRQ_M_TIMER:
+        return "M-mode Timer Interrupt";
+    case IRQ_M_EXT:
+        return "M-mode External Interrupt";
+    default:
+        return "UNKNOWN IRQ type";
+    }
+}
+
+static const char *decode_interrupt_cause(unsigned long cause)
+{
+    unsigned long irq_cause = cause & ~CAUSE_IRQ_FLAG;
+
+    switch ( irq_cause )
+    {
+    case IRQ_S_SOFT:
+        return "Supervisor Software Interrupt";
+    case IRQ_S_TIMER:
+        return "Supervisor Timer Interrupt";
+    case IRQ_S_EXT:
+        return "Supervisor External Interrupt";
+    default:
+        return decode_reserved_interrupt_cause(irq_cause);
+    }
+}
+
+static const char *decode_cause(unsigned long cause)
+{
+    if ( cause & CAUSE_IRQ_FLAG )
+        return decode_interrupt_cause(cause);
+
+    return decode_trap_cause(cause);
+}
+
+static void do_unexpected_trap(const struct cpu_user_regs *regs)
 {
+    unsigned long cause = csr_read(CSR_SCAUSE);
+
+    printk("Unhandled exception: %s\n", decode_cause(cause));
+
     die();
 }
+
+void do_trap(struct cpu_user_regs *cpu_regs)
+{
+    do_unexpected_trap(cpu_regs);
+}
Signature · 1 line
2.41.0
#9 lore raw

PATCH v8 6/6 xen/riscv: test basic handling stuff

In reply to Oleksii Kurochko

---
Changes in V8:
- Nothing changed. Only rebase.
---
Changes in V6:
- Nothing changed. Only rebase.
---
Changes in V6:
- Nothing changed
---
Changes in V5:
- Nothing changed
---
Changes in V4:
- Add Acked-by: Alistair Francis <[email protected]>
---
Changes in V3:
- Nothing changed
---
Changes in V2:
- Nothing changed

---
 xen/arch/riscv/setup.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
xen/arch/riscv/setup.c +17 -0
index abdd1669c6..ab83f84e67 100644
@@ -1,5 +1,6 @@
 /* SPDX-License-Identifier: GPL-2.0-only */
 
+#include <xen/bug.h>
 #include <xen/compile.h>
 #include <xen/init.h>
 
@@ -11,6 +12,20 @@
 unsigned char __initdata cpu0_boot_stack[STACK_SIZE]
     __aligned(STACK_SIZE);
 
+static void test_run_in_exception(struct cpu_user_regs *regs)
+{
+    early_printk("If you see this message, ");
+    early_printk("run_in_exception_handler is most likely working\n");
+}
+
+static void test_macros_from_bug_h(void)
+{
+    run_in_exception_handler(test_run_in_exception);
+    WARN();
+    early_printk("If you see this message, ");
+    early_printk("WARN is most likely working\n");
+}
+
 void __init noreturn start_xen(unsigned long bootcpu_id,
                                paddr_t dtb_addr)
 {
@@ -18,6 +33,8 @@ void __init noreturn start_xen(unsigned long bootcpu_id,
 
     trap_init();
 
+    test_macros_from_bug_h();
+
     early_printk("Hello from C env\n");
 
     early_printk("All set up\n");
Signature · 1 line
2.41.0
#6 lore raw

PATCH v8 4/6 xen/riscv: introduce trap_init()

In reply to Oleksii Kurochko

---
Changes in V8:
- nothing changed. only rebase was done.
---
Changes in V7:
- #define cast_to_bug_frame(addr) ((const struct bug_frame *)(addr)).
- remove unnecessary comments in trap_init() function.
---
Changes in V6:
- trap_init() is now called after enabling the MMU.
- Add additional explanatory comments.
---
Changes in V5:
- Nothing changed
---
Changes in V4:
- Nothing changed
---
Changes in V3:
- Nothing changed
---
Changes in V2:
- Rename setup_trap_handler() to trap_init().
- Add Reviewed-by to the commit message.

---
 xen/arch/riscv/include/asm/traps.h |  1 +
 xen/arch/riscv/setup.c             |  3 +++
 xen/arch/riscv/traps.c             | 12 ++++++++++++
 3 files changed, 16 insertions(+)
xen/arch/riscv/include/asm/traps.h +1 -0
index 3fef318478..c30118e095 100644
@@ -9,6 +9,7 @@
 
 void do_trap(struct cpu_user_regs *cpu_regs);
 void handle_trap(void);
+void trap_init(void);
 
 #endif /* __ASSEMBLY__ */
 
xen/arch/riscv/setup.c +3 -0
index 6593f601c1..abdd1669c6 100644
@@ -5,6 +5,7 @@
 
 #include <asm/early_printk.h>
 #include <asm/mm.h>
+#include <asm/traps.h>
 
 /* Xen stack for bringing up the first CPU. */
 unsigned char __initdata cpu0_boot_stack[STACK_SIZE]
@@ -15,6 +16,8 @@ void __init noreturn start_xen(unsigned long bootcpu_id,
 {
     remove_identity_mapping();
 
+    trap_init();
+
     early_printk("Hello from C env\n");
 
     early_printk("All set up\n");
xen/arch/riscv/traps.c +12 -0
index a2b63d579b..c1175668b6 100644
@@ -12,6 +12,18 @@
 #include <asm/processor.h>
 #include <asm/traps.h>
 
+/*
+ * Initialize the trap handling.
+ *
+ * The function is called after MMU is enabled.
+ */
+void trap_init(void)
+{
+    unsigned long addr = (unsigned long)&handle_trap;
+
+    csr_write(CSR_STVEC, addr);
+}
+
 static const char *decode_trap_cause(unsigned long cause)
 {
     static const char *const trap_causes[] = {
Signature · 1 line
2.41.0
#7 lore raw

PATCH v8 5/6 xen/riscv: implement do_bug_frame()

In reply to Oleksii Kurochko

The patch introduces the temporary implementation of do_bug_frame(). When common code is merged, CONFIG_GENERIC_BUG_FRAME should be used instead.

---
Changes in V8:
- remove Pointless initializer of id.
- make bug_frames[] array constant.
- remove cast_to_bug_frame(addr).
- rename is_valig_bugaddr to is_valid_bug_insn().
- add check that read_instr is used only on xen code
- update the commit message.
---
Changes in V7:
- move to this patch the definition of cast_to_bug_frame() from the previous patch.
- update the comment in bug.h.
- update the comment above do_bug_frame().
- fix code style.
- add comment to read_instr func.
- add space for bug_frames in lds.S.
---
Changes in V6:
- Avoid LINK_TO_LOAD() as bug.h functionality expected to be used
after MMU is enabled.
- Change early_printk() to printk()
---
Changes in V5:
- Remove "#include <xen/types.h>" from <asm/bug.h> as there is no any need in it anymore
- Update macros GET_INSN_LENGTH: remove UL and 'unsigned int len;' from it
- Remove " include <xen/bug.h>" from risc/setup.c. it is not needed in the current version of the patch
- change an argument type from vaddr_t to uint32_t for is_valid_bugaddr and introduce read_instr() to read instruction properly as the length of qinstruction can be either 32 or 16 bits.
- Code style fixes
- update the comments before do_bug_frame() in riscv/trap.c
- Refactor is_valid_bugaddr() function.
- introduce macros cast_to_bug_frame(addr) to hide casts.
- use LINK_TO_LOAD() for addresses which are linker time relative.
---
Changes in V4:
- Updates in RISC-V's <asm/bug.h>:
* Add explanatory comment about why there is only defined for 32-bits length instructions and 16/32-bits BUG_INSN_{16,32}.
* Change 'unsigned long' to 'unsigned int' inside GET_INSN_LENGTH().
* Update declaration of is_valid_bugaddr(): switch return type from int to bool and the argument from 'unsigned int' to 'vaddr'.
- Updates in RISC-V's traps.c:
* replace /xen and /asm includes
* update definition of is_valid_bugaddr():switch return type from int to bool
and the argument from 'unsigned int' to 'vaddr'. Code style inside function
was updated too.
* do_bug_frame() refactoring:
* local variables start and bug became 'const struct bug_frame'
* bug_frames[] array became 'static const struct bug_frame[] = ...'
* remove all casts
* remove unneeded comments and add an explanatory comment that the do_bug_frame() will be switched to a generic one.
* do_trap() refactoring:
* read 16-bits value instead of 32-bits as compressed instruction can
be used and it might happen than only 16-bits may be accessible.
* code style updates
* re-use instr variable instead of re-reading instruction.
- Updates in setup.c:
* add blank line between xen/ and asm/ includes.
---
Changes in V3:
- Rebase the patch "xen/riscv: introduce an implementation of macros
from <asm/bug.h>" on top of patch series [introduce generic implementation
of macros from bug.h]
---
Changes in V2:
- Remove __ in define namings
- Update run_in_exception_handler() with

    register void *fn_ asm(__stringify(BUG_FN_REG)) = (fn);
  - Remove bug_instr_t type and change it's usage to uint32_t
---
 xen/arch/riscv/traps.c   | 138 +++++++++++++++++++++++++++++++++++++++
 xen/arch/riscv/xen.lds.S |  10 +++
 2 files changed, 148 insertions(+)
xen/arch/riscv/traps.c +138 -0
index c1175668b6..b096dce6c7 100644
@@ -5,6 +5,8 @@
  * RISC-V Trap handlers
  */
 
+#include <xen/bug.h>
+#include <xen/errno.h>
 #include <xen/lib.h>
 
 #include <asm/csr.h>
@@ -101,7 +103,143 @@ static void do_unexpected_trap(const struct cpu_user_regs *regs)
     die();
 }
 
+void show_execution_state(const struct cpu_user_regs *regs)
+{
+    printk("implement show_execution_state(regs)\n");
+}
+
+/*
+ * TODO: generic do_bug_frame() should be used instead of current
+ * implementation panic(), printk() and find_text_region()
+ * (virtual memory?) will be ready/merged
+ */
+int do_bug_frame(const struct cpu_user_regs *regs, vaddr_t pc)
+{
+    const struct bug_frame *start, *end;
+    const struct bug_frame *bug = NULL;
+    unsigned int id;
+    const char *filename, *predicate;
+    int lineno;
+
+    static const struct bug_frame * const bug_frames[] = {
+        &__start_bug_frames[0],
+        &__stop_bug_frames_0[0],
+        &__stop_bug_frames_1[0],
+        &__stop_bug_frames_2[0],
+        &__stop_bug_frames_3[0],
+    };
+
+    for ( id = 0; id < BUGFRAME_NR; id++ )
+    {
+        start = bug_frames[id];
+        end   = bug_frames[id + 1];
+
+        while ( start != end )
+        {
+            if ( (vaddr_t)bug_loc(start) == pc )
+            {
+                bug = start;
+                goto found;
+            }
+
+            start++;
+        }
+    }
+
+ found:
+    if ( bug == NULL )
+        return -ENOENT;
+
+    if ( id == BUGFRAME_run_fn )
+    {
+        void (*fn)(const struct cpu_user_regs *) = bug_ptr(bug);
+
+        fn(regs);
+
+        goto end;
+    }
+
+    /* WARN, BUG or ASSERT: decode the filename pointer and line number. */
+    filename = bug_ptr(bug);
+    lineno = bug_line(bug);
+
+    switch ( id )
+    {
+    case BUGFRAME_warn:
+        printk("Xen WARN at %s:%d\n", filename, lineno);
+
+        show_execution_state(regs);
+
+        goto end;
+
+    case BUGFRAME_bug:
+        printk("Xen BUG at %s:%d\n", filename, lineno);
+
+        show_execution_state(regs);
+
+        printk("change wait_for_interrupt to panic() when common is available\n");
+        die();
+
+    case BUGFRAME_assert:
+        /* ASSERT: decode the predicate string pointer. */
+        predicate = bug_msg(bug);
+
+        printk("Assertion %s failed at %s:%d\n", predicate, filename, lineno);
+
+        show_execution_state(regs);
+
+        printk("change wait_for_interrupt to panic() when common is available\n");
+        die();
+    }
+
+    return -EINVAL;
+
+ end:
+    return 0;
+}
+
+static bool is_valid_bug_insn(uint32_t insn)
+{
+    return insn == BUG_INSN_32 ||
+           (insn & COMPRESSED_INSN_MASK) == BUG_INSN_16;
+}
+
+/* There are no guests for now so  the func has to return alwasys false */
+static inline bool guest_mode(void)
+{
+    return false;
+}
+
+/* Should be used only on Xen code */
+static uint32_t read_instr(unsigned long pc)
+{
+    uint16_t instr16 = *(uint16_t *)pc;
+
+    if ( guest_mode() )
+    {
+        printk("%s should be called only on Xen code\n", __func__);
+        die();
+    }
+
+    if ( GET_INSN_LENGTH(instr16) == 2 )
+        return instr16;
+    else
+        return *(uint32_t *)pc;
+}
+
 void do_trap(struct cpu_user_regs *cpu_regs)
 {
+    register_t pc = cpu_regs->sepc;
+    uint32_t instr = read_instr(pc);
+
+    if ( is_valid_bug_insn(instr) )
+    {
+        if ( !do_bug_frame(cpu_regs, pc) )
+        {
+            cpu_regs->sepc += GET_INSN_LENGTH(instr);
+            return;
+        }
+    }
+
     do_unexpected_trap(cpu_regs);
 }
xen/arch/riscv/xen.lds.S +10 -0
index 3fa7db3bf9..a10e0ad87c 100644
@@ -45,6 +45,16 @@ SECTIONS
     . = ALIGN(PAGE_SIZE);
     .rodata : {
         _srodata = .;          /* Read-only data */
+        /* Bug frames table */
+        __start_bug_frames = .;
+        *(.bug_frames.0)
+        __stop_bug_frames_0 = .;
+        *(.bug_frames.1)
+        __stop_bug_frames_1 = .;
+        *(.bug_frames.2)
+        __stop_bug_frames_2 = .;
+        *(.bug_frames.3)
+        __stop_bug_frames_3 = .;
         *(.rodata)
         *(.rodata.*)
         *(.data.rel.ro)
Signature · 1 line
2.41.0
Acked-by on v8 1/6
#2 lore raw

Re: [PATCH v8 1/6] xen/riscv: introduce temporary printk stuff

In reply to Oleksii Kurochko
Quoted 5 lines · Oleksii Kurochko

The patch introdcuces printk related stuff which should be deleted after Xen common code will be available.

Alistair

Quoted 193 lines

---
Changes in V8:
- only rebase was done.
---
Changes in V7:
- only rebase was done.
---
Changes in V6:
- the patch was introduced in the current patch series (V6)

---
 xen/arch/riscv/early_printk.c | 168 ++++++++++++++++++++++++++++++++++
 1 file changed, 168 insertions(+)
xen/arch/riscv/early_printk.c +168 -1
index 610c814f54..60742a042d 100644
@@ -40,3 +40,171 @@ void early_printk(const char *str)
         str++;
     }
 }
+
+/*
+ * The following #if 1 ... #endif should be removed after printk
+ * and related stuff are ready.
+ */
+#if 1
+
+#include <xen/stdarg.h>
+#include <xen/string.h>
+
+/**
+ * strlen - Find the length of a string
+ * @s: The string to be sized
+ */
+size_t (strlen)(const char * s)
+{
+    const char *sc;
+
+    for (sc = s; *sc != '\0'; ++sc)
+        /* nothing */;
+    return sc - s;
+}
+
+/**
+ * memcpy - Copy one area of memory to another
+ * @dest: Where to copy to
+ * @src: Where to copy from
+ * @count: The size of the area.
+ *
+ * You should not use this function to access IO space, use memcpy_toio()
+ * or memcpy_fromio() instead.
+ */
+void *(memcpy)(void *dest, const void *src, size_t count)
+{
+    char *tmp = (char *) dest, *s = (char *) src;
+
+    while (count--)
+        *tmp++ = *s++;
+
+    return dest;
+}
+
+int vsnprintf(char* str, size_t size, const char* format, va_list args)
+{
+    size_t i = 0; /* Current position in the output string */
+    size_t written = 0; /* Total number of characters written */
+    char* dest = str;
+
+    while ( format[i] != '\0' && written < size - 1 )
+    {
+        if ( format[i] == '%' )
+        {
+            i++;
+
+            if ( format[i] == '\0' )
+                break;
+
+            if ( format[i] == '%' )
+            {
+                if ( written < size - 1 )
+                {
+                    dest[written] = '%';
+                    written++;
+                }
+                i++;
+                continue;
+            }
+
+            /*
+             * Handle format specifiers.
+             * For simplicity, only %s and %d are implemented here.
+             */
+
+            if ( format[i] == 's' )
+            {
+                char* arg = va_arg(args, char*);
+                size_t arglen = strlen(arg);
+
+                size_t remaining = size - written - 1;
+
+                if ( arglen > remaining )
+                    arglen = remaining;
+
+                memcpy(dest + written, arg, arglen);
+
+                written += arglen;
+                i++;
+            }
+            else if ( format[i] == 'd' )
+            {
+                int arg = va_arg(args, int);
+
+                /* Convert the integer to string representation */
+                char numstr[32]; /* Assumes a maximum of 32 digits */
+                int numlen = 0;
+                int num = arg;
+                size_t remaining;
+
+                if ( arg < 0 )
+                {
+                    if ( written < size - 1 )
+                    {
+                        dest[written] = '-';
+                        written++;
+                    }
+
+                    num = -arg;
+                }
+
+                do
+                {
+                    numstr[numlen] = '0' + num % 10;
+                    num = num / 10;
+                    numlen++;
+                } while ( num > 0 );
+
+                /* Reverse the string */
+                for (int j = 0; j < numlen / 2; j++)
+                {
+                    char tmp = numstr[j];
+                    numstr[j] = numstr[numlen - 1 - j];
+                    numstr[numlen - 1 - j] = tmp;
+                }
+
+                remaining = size - written - 1;
+
+                if ( numlen > remaining )
+                    numlen = remaining;
+
+                memcpy(dest + written, numstr, numlen);
+
+                written += numlen;
+                i++;
+            }
+        }
+        else
+        {
+            if ( written < size - 1 )
+            {
+                dest[written] = format[i];
+                written++;
+            }
+            i++;
+        }
+    }
+
+    if ( size > 0 )
+        dest[written] = '\0';
+
+    return written;
+}
+
+void printk(const char *format, ...)
+{
+    static char buf[1024];
+
+    va_list args;
+    va_start(args, format);
+
+    (void)vsnprintf(buf, sizeof(buf), format, args);
+
+    early_printk(buf);
+
+    va_end(args);
+}
+
+#endif
+
--

2.41.0

Reviewed-by on v8 2/6
#4 lore raw

Re: [PATCH v8 2/6] xen/riscv: introduce <asm/bug.h>

In reply to Oleksii Kurochko
Quoted 2 lines · Oleksii Kurochko

Alistair

Quoted 55 lines

---
Changes in V8:
- new patch. It was introduced instead of dummy asm/bug.h introduction.

---
 xen/arch/riscv/include/asm/bug.h | 37 ++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
 create mode 100644 xen/arch/riscv/include/asm/bug.h
xen/arch/riscv/include/asm/bug.h new file +37 -1
new file mode 100644
index 0000000000..f5ff96140f
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2012 Regents of the University of California
+ * Copyright (C) 2021-2023 Vates
+ *
+ */
+#ifndef _ASM_RISCV_BUG_H
+#define _ASM_RISCV_BUG_H
+
+#ifndef __ASSEMBLY__
+
+#define BUG_INSTR "ebreak"
+
+/*
+ * The base instruction set has a fixed length of 32-bit naturally aligned
+ * instructions.
+ *
+ * There are extensions of variable length ( where each instruction can be
+ * any number of 16-bit parcels in length ).
+ *
+ * Compressed ISA is used now where the instruction length is 16 bit  and
+ * 'ebreak' instruction, in this case, can be either 16 or 32 bit (
+ * depending on if compressed ISA is used or not )
+ */
+#define INSN_LENGTH_MASK        _UL(0x3)
+#define INSN_LENGTH_32          _UL(0x3)
+
+#define BUG_INSN_32             _UL(0x00100073) /* ebreak */
+#define BUG_INSN_16             _UL(0x9002)     /* c.ebreak */
+#define COMPRESSED_INSN_MASK    _UL(0xffff)
+
+#define GET_INSN_LENGTH(insn)                               \
+    (((insn) & INSN_LENGTH_MASK) == INSN_LENGTH_32 ? 4 : 2) \
+
+#endif /* !__ASSEMBLY__ */
+
+#endif /* _ASM_RISCV_BUG_H */
--

2.41.0

Applied
#10 lore raw
In reply to Oleksii Kurochko
Quoted 3 lines · Oleksii Kurochko

The patch series is based on:
xen/riscv: introduce identity mapping [1]
which haven't been merged yet.

I've applied the series here up to patch 3, which looks to be the independent part. Patch 4 "conflicts" with the missing bits.

Jan

#8 lore raw

Re: [PATCH v8 5/6] xen/riscv: implement do_bug_frame()

In reply to Oleksii Kurochko
Quoted 5 lines · Oleksii Kurochko

The patch introduces the temporary implementation of do_bug_frame(). When common code is merged, CONFIG_GENERIC_BUG_FRAME should be used instead.

Quoted 8 lines

---
Changes in V8:
- remove Pointless initializer of id.
- make bug_frames[] array constant.
- remove cast_to_bug_frame(addr).
- rename is_valig_bugaddr to is_valid_bug_insn().
- add check that read_instr is used only on xen code
- update the commit message.

Looks largely okay to me now, yet still a couple of remarks / suggestions:

Quoted 34 lines
xen/arch/riscv/traps.c +34 -0
+int do_bug_frame(const struct cpu_user_regs *regs, vaddr_t pc)
+{
+    const struct bug_frame *start, *end;
+    const struct bug_frame *bug = NULL;
+    unsigned int id;
+    const char *filename, *predicate;
+    int lineno;
+
+    static const struct bug_frame * const bug_frames[] = {
+        &__start_bug_frames[0],
+        &__stop_bug_frames_0[0],
+        &__stop_bug_frames_1[0],
+        &__stop_bug_frames_2[0],
+        &__stop_bug_frames_3[0],
+    };
+
+    for ( id = 0; id < BUGFRAME_NR; id++ )
+    {
+        start = bug_frames[id];
+        end   = bug_frames[id + 1];
+
+        while ( start != end )
+        {
+            if ( (vaddr_t)bug_loc(start) == pc )
+            {
+                bug = start;
+                goto found;
+            }
+
+            start++;
+        }
+    }
+
+ found:

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 159

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    if ( bug == NULL )
+        return -ENOENT;
+
+    if ( id == BUGFRAME_run_fn )
+    {
+        void (*fn)(const struct cpu_user_regs *) = bug_ptr(bug);
+
+        fn(regs);
+
+        goto end;

I'd like to suggest that you avoid "goto" when at the label there's just a single, simple statement (like return in the case here).

Quoted 12 lines
xen/arch/riscv/traps.c +12 -0
+    }
+
+    /* WARN, BUG or ASSERT: decode the filename pointer and line number. */
+    filename = bug_ptr(bug);
+    lineno = bug_line(bug);
+
+    switch ( id )
+    {
+    case BUGFRAME_warn:
+        printk("Xen WARN at %s:%d\n", filename, lineno);
+
+        show_execution_state(regs);

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 181

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+
+        goto end;
+
+    case BUGFRAME_bug:
+        printk("Xen BUG at %s:%d\n", filename, lineno);
+
+        show_execution_state(regs);
+
+        printk("change wait_for_interrupt to panic() when common is available\n");
+        die();

The log message here ...

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 192

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    case BUGFRAME_assert:
+        /* ASSERT: decode the predicate string pointer. */
+        predicate = bug_msg(bug);
+
+        printk("Assertion %s failed at %s:%d\n", predicate, filename, lineno);
+
+        show_execution_state(regs);
+
+        printk("change wait_for_interrupt to panic() when common is available\n");
+        die();

... and here doesn't really fit with the following code. There's no wait_for_interrupt() in sight.

Quoted 9 lines
xen/arch/riscv/traps.c +9 -0
+    }
+
+    return -EINVAL;
+
+ end:
+    return 0;
+}
+
+static bool is_valid_bug_insn(uint32_t insn)

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 211

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+{
+    return insn == BUG_INSN_32 ||
+           (insn & COMPRESSED_INSN_MASK) == BUG_INSN_16;
+}
+
+/* There are no guests for now so  the func has to return alwasys false */
+static inline bool guest_mode(void)
+{
+    return false;
+}

I think this makes little sense to have, and ...

Quoted 1 line

+/* Should be used only on Xen code */

... just the comment is good enough. First and foremost I don't think a function with name and purpose of the above can get away without any parameters. Furthermore, as said before, ...

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 216

Quoted 3 lines
xen/arch/riscv/traps.c +3 -0
+static uint32_t read_instr(unsigned long pc)
+{
+    uint16_t instr16 = *(uint16_t *)pc;

... such casting can't be legitimate for guest addresses anyway; you would need to map guest memory instead. What you might do ...

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 222

Quoted 5 lines
xen/arch/riscv/traps.c +5 -0
+    if ( guest_mode() )
+    {
+        printk("%s should be called only on Xen code\n", __func__);
+        die();
+    }

... instead of this, as some minimalistic checking, is

    ASSERT(is_kernel_text(pc + 1) || is_kernel_inittext(pc + 1));

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 227

Quoted 4 lines
xen/arch/riscv/traps.c +4 -0
+    if ( GET_INSN_LENGTH(instr16) == 2 )
+        return instr16;
+    else
+        return *(uint32_t *)pc;

and then

    if ( GET_INSN_LENGTH(instr16) == 2 )
        return instr16;

    ASSERT(is_kernel_text(pc + 3) || is_kernel_inittext(pc + 3));

    return *(uint32_t *)pc;

Yet then again asserting in exception handlers is of limited use only, as then you risk recursive exceptions.

xen/arch/riscv/traps.c static void do_unexpected_trap(const struct cpu_user_regs *regs) · line 237

Quoted 8 lines

void do_trap(struct cpu_user_regs *cpu_regs)
{

xen/arch/riscv/traps.c +6 -0
+    register_t pc = cpu_regs->sepc;
+    uint32_t instr = read_instr(pc);
+
+    if ( is_valid_bug_insn(instr) )
+    {
+        if ( !do_bug_frame(cpu_regs, pc) )

Two if()-s like these typically want folding into one.

Jan