Commit graph zephyr/arch/riscv/Kconfig
Author SHA1 Message Date
Arjun Salunkhe
4cc75aee39 arch: riscv: Add initial Zicfilp support
Adds M-mode, S-mode (internal SBI) and U-mode enablement for the RISC-V
Zicfilp (Landing Pad) extension for forward-edge Control Flow Integrity:
- Kconfig: Added RISCV_ISA_EXT_ZICFILP and RISCV_LANDING_PADS options.
- Toolchain: Passed -fcf-protection=branch when Zicfilp is active.
- CSR: Added definitions for MSECCFG_MLPE, MENVCFG_LPE, and SENVCFG_LPE.
- M-Mode: Configured mseccfg.MLPE in arch_kernel_init().
- S-Mode: Configured menvcfg.LPE in reset.S for internal SBI.
- U-Mode: Configured senvcfg.LPE in arch_kernel_init().

Tested against qemu_riscv32 with Zicfilp enabled. Verified that indirect
jumps to assembly routines lacking lpad correctly trigger a CPU trap.

Signed-off-by: Arjun Salunkhe <arjun.salunkhe@proton.me>
2026-10-28 22:27:10 -04:00
Jimmy Zheng
94bf4f365e arch: riscv: make vectored mode optional with IRQ vector table
Default RISCV_VECTORED_MODE to enabled when GEN_IRQ_VECTOR_TABLE is
enabled, rather than selecting it.

This allows platforms with a custom vectored interrupt implementation to
disable the standard RISC-V mtvec optional vectored mode while keeping
the existing behavior by default.
For example, AE350 supports the RISC-V privileged architecture but not
the optional mtvec vectored mode, and may use the Andes Vectored PLIC
extension instead.

Signed-off-by: Jimmy Zheng <jimmyzhe@andestech.com>
2026-10-19 10:27:11 +02:00
Benjamin Cabé
38b0970ef3 arch: riscv: pmp: round the null pointer guard up to the PMP granularity
NULL_POINTER_EXCEPTION_REGION_SIZE defaults to 16 bytes, less than the
128-byte PMP granularity of the ESP32-C5, so the null pointer guard
always fails the alignment assertion in set_pmp_entry(), which GCC
turns into an -Warray-bounds error in z_riscv_pmp_kernelmode_disable().
Round the size up to the PMP granularity.

Assisted-by: Claude:opus-5.5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
2026-10-06 07:24:12 +02:00
Joel Holdsworth
e3802d3e1f arch: riscv: support building without generated SW ISR table
Make GEN_SW_ISR_TABLE depend on GEN_ISR_TABLES, and guard the import of
_sw_isr_table in isr.S so that applications can build without generated
ISR tables when interrupts are unused.

Assisted-by: Gemini:gemini-3.8-flash
Signed-off-by: Joel Holdsworth <jholdsworth@nvidia.com>
2026-09-26 08:40:33 +02:00
Ayush Singh
c847bfbc8f arch: riscv: Add initial smp support with external sbi
This patch only allows enabling SMP in 1 core setups.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
2026-09-24 03:49:59 +02:00
Ayush Singh
27619328e7 arch: riscv: core: Add ipi_sbi support
RISC-V Supervisor Binary Interface Specification supports
inter-processor interrupts using the IPI extension.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
2026-09-24 03:49:59 +02:00
Adrian Śliwa
78087d0662 arch: riscv: enable U-mode access to the Zicntr counters
Reads of cycle, time and instret below M-mode are gated by mcounteren
and scounteren, both zero out of reset. Zephyr sets neither in a build
with user threads, so user mode cannot read these counters.

Set them during per-CPU init, since the registers are per-hart. An
M-mode kernel writes mcounteren, and scounteren when misa reports
S-mode, as it does not exist otherwise. An S-mode kernel writes
scounteren alone, because mcounteren is out of reach and is expected
to be set by the SBI, as reset.S does for the built-in one.

Signed-off-by: Adrian Śliwa <asliwa@internships.antmicro.com>
2026-09-16 05:58:39 +02:00
Sylvio Alves
886d9899db arch: riscv: add soc hook to close the syscall ecall
Some RISC-V SoCs cannot deliver a fault raised by the syscall
body itself while the ECALL exception of a user-mode syscall is
still being handled. The stack guard below the privileged stack
catches a syscall whose call chain runs too deep, but on such a
SoC that access fault is reported asynchronously inside the open
ECALL and locks the core up, resetting the chip with nothing
delivered to software. A user-mode application can therefore
reset the board through the depth of a granted service call.

Masking interrupts does not help here. The existing
RISCV_SOC_HAS_SYSCALL_INTMASK holds off the interrupt
controller, while this fault comes from the body itself.

Add the hidden RISCV_SOC_SYSCALL_CLOSE_ECALL option. When a SoC
selects it, the IRQ wrapper leaves the exception before running
the syscall body: it returns to the following instruction with
the previous privilege set to machine mode, so the body runs on
the same privileged stack with the same privileges but outside
the exception. A fault taken there is an ordinary top-level trap
the SoC delivers normally, and a syscall that overflows the
privileged stack is reported as a stack overflow that kills only
the offending thread.

The exception exit path reloads the exception program counter
and status register from the saved frame, so borrowing both here
does not disturb the return to user mode.

Assisted-by: Claude:opus-5
Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
2026-09-14 15:41:06 -04:00
Sylvio Alves
32381dcbfb arch: riscv: add soc hook to mask syscall interrupts
Some RISC-V SoCs cannot take an interrupt in the syscall body: an
interrupt, or another asynchronously reported event such as an
imprecise access fault, taken while the ECALL exception is still
being handled locks the CPU up, with no fault delivered to
software. Precise synchronous traps, such as the ECALL used to
switch out of the body, nest normally. The syscall path sets
mstatus.MIE before running the body, so such a SoC must hold
interrupts off another way.

This is not the Smdbltrp double trap. On the affected cores
reading mstatush traps, so there is no mstatus.MDT to clear, and
the vendor status CSR exposes the in-exception state as a
read-only bit that stays set until mret. Software cannot end the
exception window early, so the only option is to keep interrupts
from being taken while it is open.

Add the hidden RISCV_SOC_HAS_SYSCALL_INTMASK option following
the existing RISCV_SOC_HAS_* hook pattern. When a SoC selects it,
the IRQ wrapper invokes a SoC-provided SOC_SYSCALL_INTMASK macro
on syscall entry, typically raising a hardware interrupt level
threshold, while the generic code carries no SoC register
knowledge. This is a SoC hook rather than part of the generic
CLIC interrupt level support because the SoCs that need it drive
their interrupt controller from SoC code and do not select
RISCV_HAS_CLIC.

The mask is per exception frame. The SoC context hooks save the
state on entry and restore it on the exception exit path, and
with RISCV_ALWAYS_SWITCH_THROUGH_ECALL every context switch goes
through that path: a thread that blocks in the body hands the
CPU to a thread that restores its own saved state, and a new
thread starts from SOC_ESF_INIT. The option therefore depends on
both. While the mask is raised the body is not preemptible and
pending interrupts, the tick included, wait for the syscall to
return or block; the help text says so.

Assisted-by: Claude:opus-5
Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
2026-09-14 15:41:06 -04:00
Sylvio Alves
37d3022714 arch: riscv: pre-validate user strings on imprecise-fault socs
arch_user_string_nlen() dereferences a user pointer and recovers
from a bad address through a fault fixup that matches the
faulting mepc against the load instruction's range. On some
RISC-V SoCs the load access fault is imprecise: the reported mepc
lands past the faulting load, so the fixup misses it and the
fault escalates to a fatal reset.

Rename the asm routine to z_riscv_user_string_nlen() and alias
arch_user_string_nlen() to it by default. Under the new
RISCV_USER_STRING_NLEN_VALIDATE option a C implementation takes
over instead: it checks the whole range with
arch_buffer_validate() first and, when that fails, walks the
string in PMP-granularity chunks, validating each chunk before
reading it, so no load that could fault is ever issued. The
faulting load may sit at any offset (a string that starts in an
accessible region and runs unterminated into an inaccessible
one), which is why one check of the first byte is not enough.
The generic syscall handler is untouched.

Add a syscalls test scenario that enables the option on RISC-V.

Assisted-by: Claude:opus-5
Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
2026-09-14 15:41:06 -04:00
Liu Qian
18b49e8379 arch: riscv: pmp: add NAPOT multi-slot mode for non-aligned regions
When TOR is unsupported (PMP_NO_TOR), the Kconfig forced
PMP_POWER_OF_TWO_ALIGNMENT=y, wasting memory: 33 KB of code+rodata
aligns to 64 KB, 257 KB aligns to 512 KB.

Add PMP_NAPOT_USE_MULTI_SLOTS: splits a non-naturally-aligned region
into multiple NAPOT entries, each covering the largest naturally-
aligned block at the current address. [0x1800, 0x3800) becomes
0x800 + 0x1000 + 0x800 (3 slots instead of padding to 8192).

Depends on !USERSPACE: arch_mem_domain_max_partitions_get() assumes
1-2 slots per partition and resync_pmp_domain() can only log on
failure, so a partition needing more slots would run unmapped (silent
loss of protection). Help text documents that disabling
PMP_POWER_OF_TWO_ALIGNMENT also splits stack guards and u-mode stacks,
and that PMP_GRANULARITY=64 cuts both ways for that case.

try_multi_entries_set() uses clz/ctz builtins, clears already-written
config bytes on failure before restoring *index_p (otherwise the
trailing write_pmp_entries(0, PMP_SLOTS) in z_riscv_pmp_init() would
program locked partial entries), and folds start/size into the inner
failure logs.

Signed-off-by: Liu Qian <liuqian.andy@picoheart.com>
2026-09-11 17:34:41 +02:00
Kaveesha Yalegama
b06c28cf3d riscv: fpu: improve FPU instruction filtering in trap handler
Updates the fast-path assembly in isr.S to explicitly filter out
vector instructions that share opcodes with FP loads/stores,
preventing them from corrupting the FPU context state.

Additionally, introduces CONFIG_RISCV_FPU_INSN_VALIDATE (default
'y' with CONFIG_ASSERT) to provide a C-level runtime validator in
z_riscv_fpu_trap(). This intercepts misrouted non-FPU instructions,
prints the faulting opcode, and throws a kernel oops.

Fixes #96551

Signed-off-by: Kaveesha Yalegama <kaveesha.yalegama@gmail.com>
2026-08-27 12:04:26 +01:00
Benjamin Cabé
5389672ba0 arch: riscv: remove deprecated EXTRA_EXCEPTION_INFO Kconfig option
The RISC-V specific shadow definition of EXTRA_EXCEPTION_INFO was
deprecated in Zephyr 4.3 and is now removed as part of the 4.5
deprecation removal cycle.

The RISC-V exception handling code (isr.S, fatal.c, coredump.c and the
offsets definitions) has been keyed off CONFIG_EXCEPTION_DEBUG since the
deprecation, so removing the symbol requires no code conversion. RISC-V
applications that still set CONFIG_EXTRA_EXCEPTION_INFO must use
CONFIG_EXCEPTION_DEBUG instead.

Note this only drops the deprecated RISC-V local definition. The generic
EXTRA_EXCEPTION_INFO option in arch/Kconfig, guarded by
ARCH_HAS_EXTRA_EXCEPTION_INFO and used by Arm and SPARC, is unaffected.

Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Assisted-by: Claude:opus-5
2026-08-25 07:59:26 -07:00
Ayush Singh
5a95bb9cff arch: riscv: Add S-mode only support
- When launching Zephyr from a bootloader (eg: u-boot), the image binary
  launches in S-mode. Thus we cannot call M-mode only functions, or
  perform M to S mode transition.
- SMP is currently broken in this setup. MPU, FPU not tested yet either
  since PolarFire soc does not enable it by default.
- Tested on beaglev_fire with PolarFire soc.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
2026-08-25 11:24:09 +02:00
Adrian Śliwa
5bf87816ff arch: riscv: bump idle stack size
Test

```
west twister -p mpfs_icicle/polarfire/u54/smp -s
kernel.threads.thread_stack
```

fails with `idle thread stack size 512 too low`.

Signed-off-by: Adrian Śliwa <asliwa@internships.antmicro.com>
2026-07-17 11:56:19 -04:00
Adrian Śliwa
cda79d7ac6 arch: riscv: Bump privileged stack size
Since 5528dee556 (`device: Add asserts to DEVICE_API_GET`), the
following tests fail with a privileged-stack overflow during the
`log_panic()` syscall:

```
west twister -p hifive_unmatched/fu740/u74 -s logging.log_user
west twister -p hifive_unleashed/fu540/u54 -s logging.log_user
```

`qemu_riscv64` passes only because its defconfig sets
`CONFIG_PRIVILEGED_STACK_SIZE=2048`, lowering it to `1024` reproduces
the failure in a similar way.

The bad commit makes stack frames bigger along the `log_panic()` flush
chain. Peak privileged-stack usage goes from just-under to just-over
1024 bytes.

Signed-off-by: Adrian Śliwa <asliwa@internships.antmicro.com>
2026-07-07 17:25:03 +01:00
Christoph Busold
9828037e91 arch: riscv: Detach DEP config from EXECUTE_XOR_WRITE
Move EXECUTE_XOR_WRITE back into userspace and update the comment
to reflect that it only applies to memory partitions.

PMP_DATA_EXECUTION_PREVENTION is now independent from it and no
longer a requirement.

For full protection both options should be enabled. Otherwise,
some data areas my be left executable and writable at the same
time.

Signed-off-by: Christoph Busold <cbusold@qti.qualcomm.com>
2026-06-19 22:37:17 +02:00
Christoph Busold
fe26d3747e arch: riscv: Add new config PMP_DATA_EXECUTION_PREVENTION
CONFIG_EXECUTE_XOR_WRITE now depends on
PMP_DATA_EXECUTION_PREVENTION, which in turn selects
PMP_KERNEL_MODE_DYNAMIC if user space is enabled. Another new
config PMP_KERNEL_MODE_DYNAMIC_CATCHALL indicates whether dynamic
catch-all programming is required.

This simplifies the code structure.

Signed-off-by: Christoph Busold <cbusold@qti.qualcomm.com>
2026-06-19 22:37:17 +02:00
Christoph Busold
70df4ac429 arch: riscv: Add CONFIG_EXECUTE_XOR_WRITE support using PMP
CONFIG_EXECUTE_XOR_WRITE is a basic countermeasure to prevent code
injection attacks by making data non-executable. This can be done
on RISC-V with PMP by removing the executable permission.

Since PMP slots are statically prioritized, we can add a region
covering the whole address space into the last register giving
only read-write access. This will be overridden by any other
configured register with lower index so that the code region
remains executable.

In order to make this register apply to kernel threads in M mode,
it needs to be locked, but this means we cannot remove it anymore.
For CONFIG_USERSPACE we therefore need to reserve another register
so that we can add another address space-wide region with higher
priority without any permission to override the last one and limit
user threads to their assigned regions. This needs to be removed
when switching from user to kernel threads, which is done in the
new function z_riscv_pmp_usermode_disable.

This feature simplifies CONFIG_PMP_KERNEL_MODE_DYNAMIC because we
already have a catch-all register for kernel threads.

Does not work with CONFIG_CODE_DATA_RELOCATION for now and requires
PMP region locking.

Signed-off-by: Christoph Busold <cbusold@qti.qualcomm.com>
2026-06-19 22:37:17 +02:00
Fin Maaß
83600be95e riscv: increase SYSTEM_WORKQUEUE_STACK_SIZE if 64BIT
increase SYSTEM_WORKQUEUE_STACK_SIZE if
we use 64BIT, just like at ARM64 and ARC.

Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
2026-06-02 13:29:49 +02:00
Camille BAUD
9ea48bd453 arch: riscv: Allow decoding unaligned FP instruction in FP no-MTVAL trap
Load the instruction byte per byte to avoid an unaligned access exception

Signed-off-by: Camille BAUD <mail@massdriver.space>
2026-05-22 18:26:16 +02:00
Afonso Oliveira
8cd5e1ee14 arch: riscv: add RISCV_HAS_AIA capability
Add a capability symbol for platforms providing RISC-V AIA interrupt
controllers.

Signed-off-by: Afonso Oliveira <afonso.oliveira707@gmail.com>
2026-05-12 22:15:36 +02:00
Jamie McCrae
96d1142210 arch: Add support for dts RAM configuration
Allows using the chosen SRAM node for RAM configuration without
using Kconfig values

Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
2026-05-11 08:45:38 +02:00
Alexios Lyrakis
1cf1de81a1 arch: riscv: add Supervisor-mode (S-mode) support
Introduce CONFIG_RISCV_S_MODE to select Supervisor-mode execution.
Add depends on !RISCV_S_MODE to RISCV_PMP since PMP CSRs are
inaccessible from S-mode.

Add an M-mode SBI shim (reset.S + sbi.S) that configures exception
delegation, PMP, and counter access before dropping to S-mode via mret.
The shim handles SBI_SET_TIMER ecalls from S-mode and forwards MTIP to
STIP so the supervisor timer driver works without a full SBI firmware.

Introduce privilege-level abstractions in isr.S (RV_CAUSE, RV_EPC,
RV_STATUS, RV_TVAL, etc.) and update all runtime code that previously
accessed M-mode-only CSRs (mcause, mtval, mstatus, mie, mip) to use the
S-mode equivalents when CONFIG_RISCV_S_MODE is set.

ARCH_EXCEPT in kernel context uses ebreak (cause=3, Breakpoint) instead
of a direct z_riscv_fatal_error() call.  In S-mode, ecall (cause=9) is
kept in M-mode for SBI and never reaches the S-mode exception handler;
a direct call with NULL esf caused the stack unwinder to crash into an
infinite fault loop.  ebreak is delegated to S-mode by our medeleg
configuration; isr.S treats ebreak with t0=RV_ECALL_RUNTIME_EXCEPT the
same way M-mode treats ecall-based ARCH_EXCEPT.

Signed-off-by: Alexios Lyrakis <alexios.lyrakis@gmail.com>
2026-05-04 14:54:52 +02:00
Anas Nashif
eb294b7a1e kernel: move userspace code to own folder
Isolate userspace code into userspace/.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-04-14 22:31:16 -04:00
Rick Tsao
a88b3c5453 arch: riscv: add custom stack guard
Add architecture-level support for a custom stack guard on RISC-V,
preventing stack overflow at the hardware level.

This framework allows vendors to implement the custom stack guard
using their own vendor-specific stack protection hardware, providing
flexibility for different RISC-V cores.

A new config option, CUTOM_STACK_GUARD, allows users to enable this
stack guard on supported RISC-V cores.

Signed-off-by: Rick Tsao <rick592@andestech.com>
2026-03-21 07:51:15 -05:00
Peter Marheine
1d67c392a7 arch: riscv: remove unused RISCV_SOC_EXCEPTION_FROM_IRQ
This option was formerly enabled by sy1xx, but all supported socs now
appear to use the standard behavior so this support can be removed.

Signed-off-by: Peter Marheine <pmarheine@chromium.org>
2026-03-19 14:48:34 -05:00
Andy Lin
6cb74ad968 arch: riscv: Add -msave-restore option to reduce code footprint
Add `-msave-restore` option to reduce the code footprint
of function prologue and epilogue.

Signed-off-by: Andy Lin <andylinpersonal@gmail.com>
2026-03-16 10:07:57 -04:00
Alex Lyrakis
359dead234 riscv: pmp: add option to unlock ROM region for debugging
Add CONFIG_PMP_UNLOCK_ROM_FOR_DEBUG option to conditionally disable
the lock bit (L=0) for the ROM region PMP entry. This allows debuggers
running in machine mode to access ROM for setting breakpoints and
reading instructions while preserving userspace protection.

When PMP lock bits are set, they restrict access even in machine mode,
causing "unable to halt hart" errors with hardware debuggers like
OpenOCD. This option provides a surgical fix that only affects the ROM
region - NULL pointer guards and stack guards remain locked to catch
critical bugs during development.

The option integrates with existing PMP_NO_LOCK_GLOBAL configuration
using nested COND_CODE_1 macros and defaults to disabled for production
builds.

Fixes: zephyrproject-rtos/zephyr#82729

Signed-off-by: Alex Lyrakis <alex_gfd@hotmail.com>
2026-02-13 10:06:18 +01:00
Fin Maaß
daf90f79ee arch: riscv: add dependencies to FLOAT_HARD
1. it reguires that there are floating point registers,
so the extention f is required. (zfinx uses the int regs instead)
2. RV32E doesn't supports hardware floating-point calling convention.

Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
2026-01-24 08:47:18 -06:00
Firas Sammoura
e0f2b4e354 riscv: pmp: Add support for unlocked global PMP entries
Adds the Kconfig option PMP_NO_LOCK_GLOBAL to remove the PMP Lock bit
usage. The global entry is an internal detail of the driver
implementation and should not be reflected in the user interface. This
allows the application to dynamically reconfigure the PMP entries
without requiring hard reset. This is essential for firmware that
performs an RO-to-RW jump. By keeping these system entries unlocked,
higher-privileged M-mode code can dynamically reconfigure memory
permissions during the secure handover process, which is not possible if
the entries are permanently locked during early boot.

Signed-off-by: Firas Sammoura <fsammoura@google.com>
2025-11-28 09:49:50 +00:00
Firas Sammoura
c011fddf95 riscv: pmp: Support custom entries from Device Tree for memory attributes
The Physical Memory Protection (PMP) initialization is updated to support
custom entries defined in the Device Tree (DT) using the `zephyr,memattr`
property, contingent on `CONFIG_MEM_ATTR` being enabled. A new function,
`set_pmp_mem_attr()`, iterates over DT-defined regions and programs PMP
entries in `z_riscv_pmp_init()`, allowing for early, flexible, and
hardware-specific R/W/X protection for critical memory areas. DT-based
entries are also installed in `z_riscv_pmp_kernelmode_prepare()` for
thread-specific configuration. The logic for the temporary PMP "catch-all"
entry is adjusted to account for new DT entries. Furthermore, the PMP
domain resync logic now masks user partition permissions against DT-defined
region permissions, preventing privilege escalation. `CONFIG_RISCV_PMP` is
updated to select `PMP_KERNEL_MODE_DYNAMIC` if `MEM_ATTR`. Finally, the
`pmp_cfg` array in `z_riscv_pmp_init()` is initialized to zero to prevent
writing uninitialized stack data to unused PMP entries.

Signed-off-by: Firas Sammoura <fsammoura@google.com>
2025-11-17 09:25:01 -05:00
Firas Sammoura
f6cec1c30f riscv: Add CONFIG_PMP_KERNEL_MODE_DYNAMIC
Introduce `CONFIG_PMP_KERNEL_MODE_DYNAMIC` to enable dynamic
configuration and activation of Machine mode PMP entries. This allows
PMP settings to be managed efficiently during transitions between
kernel and thread contexts.

Signed-off-by: Firas Sammoura <fsammoura@google.com>
2025-11-17 09:25:01 -05:00
Afonso Oliveira
b9a15bf5c8 arch/riscv: Enable NMI delivery for SMRNMI hardware
Add option to enable NMI delivery on boot for SMRNMI hardware.

Changes:
- Add CONFIG_RISCV_SMRNMI_ENABLE_NMI_DELIVERY Kconfig option
- Define SMRNMI CSRs in arch/riscv/include/csr.h
- Set NMIE bit during boot to enable NMI delivery

SMRNMI hardware generates but doesn't deliver NMIs when NMIE=0 (default).
This causes twister test failures and prevents handling of critical
hardware events like watchdog NMIs and ECC errors.

Setting NMIE=1 enables NMI delivery, but note that this implementation
only sets the enable bit - it does not provide full SMRNMI support
(no mnret instruction handling, no RNMI handlers). Users must implement
proper RNMI handlers in SoC-specific code to avoid undefined behavior.

Signed-off-by: Afonso Oliveira <afonsoo@synopsys.com>
2025-11-17 09:23:11 -05:00
Yong Cong Sin
643e09febf arch: riscv: streamline fatal handling code
`CONFIG_EXTRA_EXCEPTION_INFO` that was added in #78065 doesn't
seem necessary, as we were already storing and printing the
callee-saved-registers before that. All `CONFIG_EXTRA_EXCEPTION_INFO`
does in RISCV is to add an additional `_callee_saved_t *csf` in the
`struct arch_esf`, which overhead is negligible to what's being enabled
by `CONFIG_EXCEPTION_DEBUG`.

Let's remove `CONFIG_EXTRA_EXCEPTION_INFO`, and have that extra
`_callee_saved_t *csf` in the `struct arch_esf` as long as
`CONFIG_EXCEPTION_DEBUG` is enabled.

TL;DR: it doesn't make sense to not enable `CONFIG_EXTRA_EXCEPTION_INFO`
when `CONFIG_EXCEPTION_DEBUG` is enabled, so let's merge them.

Then, since `*csf` is always available in the `struct arch_esf` when
`CONFIG_EXCEPTION_DEBUG=y`, we can simply rely on that pointer in
`z_riscv_fatal_error()` instead of an additional argument in
`z_riscv_fatal_error_csf()`, rendering the latter redundant and thus
can be removed.

Additionally, save the callee-saved registers before jumping to
to `z_riscv_fault()`, so that callee-saved-registers are printed on
generic CPU exception as well.

Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
Signed-off-by: Yong Cong Sin <ycsin@meta.com>
2025-10-24 08:51:15 -07:00
Jimmy Zheng
7edb310d02 arch: riscv: custom: add T-Head Xuantie CSR support
Move Xuantie supprot from arch/riscv/core/xuantie to the custom common
layer arch/riscv/custom/thead, with the following changes:

1. Rename Kconfig name
   CACHE_XTHEADCMO -> RISCV_CUSTOM_CSR_THEAD_CMO
2. Split the original arch/riscv/core/xuantie/Kconfig to
   a. arch/riscv/custom/thead/Kconfig: for T-Head extension
   b. arch/riscv/custom/thead/Kconfig.core: for T-Head CPU series
      (e.g. Xuantie E907)
3. Move cache line size defaults to SoC devicetree

Signed-off-by: Jimmy Zheng <jimmyzhe@andestech.com>
2025-10-13 11:26:28 -04:00
Jimmy Zheng
679ce42f15 arch: riscv: custom: add Andes CSR support
Rework Andes-specific CSR to use RISC-V custom CSR common code.
Move these stuff to 'arch/riscv/custom/andes':

1. Rename 'soc_v5.h' to 'andes_csr.h' for CSR definitions.
2. Replace '_start' with '__reset' hook for low-level CSR initialization.
3. Move CSR context to common macro '__custom_csr_save/restore_context'.
4. Move 'EXECIT' CSR support to common code.
5. Move PMA CSR driver to common code.
6. Use RISC-V common linker.ld instead of SoC-specific linker.ld.

Signed-off-by: Jimmy Zheng <jimmyzhe@andestech.com>
2025-10-13 11:26:28 -04:00
Camille BAUD
1afca0369c arch: riscv: Add support for Xuantie CPUs
Adds some support for xuantie CPU, namely cache control

Signed-off-by: Camille BAUD <mail@massdriver.space>
2025-10-08 15:12:49 -04:00
Łukasz Stępnicki
10941ca73e arch: riscv: added helper config to include isr wrapper
Added helper Kcoinfig option USE_ISR_WRAPPER which can be used to
include isr_wrapper even if GEN_SW_ISR_TABLE is not enabled. This
is needed to enable configurations where only IRQ vector table is
used with multithreading (only direct isr used). This change is
backward compatibible with previous config.

Signed-off-by: Łukasz Stępnicki <lukasz.stepnicki@nordicsemi.no>
2025-08-18 13:06:50 +02:00
Afonso Oliveira
b4eb116478 arch: riscv: decouple mtval usefulness for FP traps from QEMU target
Introduce CONFIG_RISCV_NO_MTVAL_ON_FP_TRAP to handle implementations
where the mtval CSR does not provide useful information during
floating-point illegal instruction exceptions.

The RISC-V specification states that mtval is "either set to zero or
written with exception-specific information" on traps. Some
implementations, including QEMU, do not populate mtval with the
faulting instruction value during FP-related illegal instruction
exceptions, making it unusable for FP exception handling.

Previously, this behavior was hardcoded for QEMU targets only, but
other CPU implementations may also lack useful mtval content for FP
traps. Decoupling this from CONFIG_QEMU_TARGET and allows other
platforms to properly declare this limitation.

The new Kconfig option defaults to enabled for QEMU targets to
maintain backward compatibility.

Signed-off-by: Afonso Oliveira <afonsoo@synopsys.com>
2025-07-29 22:52:37 -04:00
Stephanos Ioannidis
dc3c9f3560 arch: riscv: Introduce code model options
This commit introduces a new Kconfig choice for configuring the code model
used for compilation.

All three code models specified by the RISC-V ELF psABI specification are
supported: medlow, medany and large.

For RV32, the `medlow` code model is always selected.
For RV64, the `large` code model is selected if the SRAM or kernel VM base
address is greater than or equal to 4 GiB; otherwise, the `medany` code
model is selected.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2025-07-19 15:43:09 -04:00
Pisit Sawangvonganan
a163f9db61 kconfig: fix typo in (arch, boards, kernel, modules, samples, share)
Utilize a code spell-checking tool to scan for and correct spelling errors
in `Kconfig` files within the `arch`, `boards`, `kernel`, `modules`,
`samples`, and `share` directory.
Additionally, incorporates a fix recommended by the reviewer.

Signed-off-by: Pisit Sawangvonganan <pisit@ndrsolution.com>
2025-07-01 10:58:54 -10:00
Keith Packard
e4b4a8dfe8 riscv: Increase TEST_EXTRA_STACK_SIZE to 4096 if c++ exceptions
Initializing the C++ stack unwinding data structures takes quite a bit
of stack space. Increase the TEST_EXTRA_STACK_SIZE when using these.

Signed-off-by: Keith Packard <keithp@keithp.com>
2025-05-23 17:41:40 -04:00
Jimmy Zheng
3804387350 arch: riscv: handle interrupt level for CLIC
CLIC supports mintstatus.MIL (RO) and mcause.MPIL (RW) for the current
interrupt level and the previous interrut level before a trap. Each ISR
must execute MRET to set mcause.MPIL back to mintstatus.MIL.

This commit introduces CONFIG_CLIC_SUPPORT_INTERRUPT_LEVEL to handle
mcause.MPIL for interrupt preemption in nested ISR, and uses
CONFIG_RISCV_ALWAYS_SWITCH_THROUGH_ECALL to ensure ISR always switch out
with MRET.

e.g.
  With CONFIG_RISCV_ALWAYS_SWITCH_THROUGH_ECALL=n, a context-switch in
  ISR may skip MRET in this flow:
  IRQ -> _isr_wrapper -> z_riscv_switch() -> retrun to arch_switch()

Signed-off-by: Jimmy Zheng <jimmyzhe@andestech.com>
2025-02-05 17:48:45 +01:00
Łukasz Stępnicki
9c574ed922 arch: riscv: option to init custom hw stacked esf members.
When RISCV_SOC_HAS_ISR_STACKING is used, it may
be needed to initialize custom hw stacked esf members.
Some initial values may need to be aligned with
hw stacking mechanism to avoid any side effects.

Signed-off-by: Łukasz Stępnicki <lukasz.stepnicki@nordicsemi.no>
2025-01-20 16:27:33 +01:00
Nicolas Pitre
46aa6717ff Revert "arch: deprecate _current"
Mostly a revert of commit b1def7145f ("arch: deprecate `_current`").

This commit was part of PR #80716 whose initial purpose was about providing
an architecture specific optimization for _current. The actual deprecation
was sneaked in later on without proper discussion.

The Zephyr core always used _current before and that was fine. It is quite
prevalent as well and the alternative is proving rather verbose.
Furthermore, as a concept, the "current thread" is not something that is
necessarily architecture specific. Therefore the primary abstraction
should not carry the arch_ prefix.

Hence this revert.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2025-01-10 07:49:08 +01:00
Yong Cong Sin
e6dd68ec89 arch: riscv: introduce CONFIG_RISCV_GP_PURPOSE choice
Introduce `CONFIG_RISCV_GP_PURPOSE` choice to make sure that only
one of `CONFIG_RISCV_GP` or `CONFIG_RISCV_CURRENT_VIA_GP` can be
enabled, instead of relying of dependencies.

To do that, introduce a new
`CONFIG_RISCV_SOC_HAS_GP_RELATIVE_ADDRESSING` that can be selected
by SoC when it implemented global pointer (GP) initialization for
relative addressing in its linker.

`CONFIG_RISCV_GP` will be the default choice when
`CONFIG_RISCV_SOC_HAS_GP_RELATIVE_ADDRESSING=y`

Signed-off-by: Yong Cong Sin <ycsin@meta.com>
Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2024-11-28 12:51:09 +01:00
Yong Cong Sin
033804e266 arch: riscv: support CONFIG_USERSPACE in CONFIG_RISCV_CURRENT_VIA_GP
Reset the the `gp` register to `_kernel->cpus[i].current` when
`CONFIG_USERSPACE` is enabled on exception to keep it sane.

Updated the testcase to test both `CONFIG_RISCV_GP` and
`CONFIG_RISCV_CURRENT_VIA_GP`.

Signed-off-by: Yong Cong Sin <ycsin@meta.com>
Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2024-11-28 12:51:09 +01:00
Yong Cong Sin
b1def7145f arch: deprecate _current
`_current` is now functionally equals to `arch_curr_thread()`, remove
its usage in-tree and deprecate it instead of removing it outright,
as it has been with us since forever.

Signed-off-by: Yong Cong Sin <ycsin@meta.com>
Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2024-11-23 20:12:24 -05:00
Yong Cong Sin
1a752e8a35 arch: riscv: implement ARCH_HAS_CUSTOM_CURRENT_IMPL with GP
Implement `arch_curr_thread()` & `arch_set_curr_thread()`
with the global pointer (GP) register.

Signed-off-by: Yong Cong Sin <ycsin@meta.com>
Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2024-11-23 20:12:24 -05:00