Skip to content
systemcoding.dev
Kernels

Use OpenSBI and SBI Calls From a RISC-V Kernel

Call the RISC-V SBI from supervisor mode: probe extensions, print through DBCN, set timers, start harts and shut down, with the ecall rules and errors.

9 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the RISC-V, Linux and Intel logos.

A supervisor-mode RISC-V kernel is not alone. Beneath it, in machine mode, runs firmware that owns the timer, the platform reset and the other harts, and it offers them to the kernel through a standard interface called the Supervisor Binary Interface, SBI. OpenSBI is the reference implementation, and it is what QEMU's virt machine loads by default. This post shows how to talk to it: the calling convention, the error codes, how to ask what the firmware supports before relying on it, and working calls for printing, timers, starting other harts and powering off. Together they replace the board-specific code you would otherwise write.

The interface is defined by the RISC-V SBI specification, and the calls here are from version 2.0. The code is C with inline assembly, for a kernel that is already booting in supervisor mode as in the bare-metal kernel post.

The calling convention

An SBI call is an ecall instruction executed in supervisor mode. It traps to machine mode, where the firmware's handler reads the arguments, does the work and returns with mret. The register assignments are fixed by the specification:

RegisterOn entryOn return
a7Extension ID (EID)preserved
a6Function ID (FID)preserved
a0 to a5Argumentsa0: error code, a1: return value; others preserved

Every other register is preserved across the call. That makes SBI cheap to wrap as a function: the compiler needs to know only that a0 and a1 are outputs and that memory may change.

sbi.cc
#include <stdint.h>

struct sbiret {
    long error;
    long value;
};

static inline struct sbiret sbi_ecall(long eid, long fid,
                                      long a0, long a1, long a2,
                                      long a3, long a4, long a5)
{
    register long r0 __asm__("a0") = a0;
    register long r1 __asm__("a1") = a1;
    register long r2 __asm__("a2") = a2;
    register long r3 __asm__("a3") = a3;
    register long r4 __asm__("a4") = a4;
    register long r5 __asm__("a5") = a5;
    register long r6 __asm__("a6") = fid;
    register long r7 __asm__("a7") = eid;

    __asm__ volatile("ecall"
                     : "+r"(r0), "+r"(r1)
                     : "r"(r2), "r"(r3), "r"(r4), "r"(r5), "r"(r6), "r"(r7)
                     : "memory");
    return (struct sbiret){ r0, r1 };
}

Binding variables to specific registers with register ... __asm__("a0") is how GCC is told which register each input lives in. The "+r" constraints mark a0 and a1 as both read and written. The memory clobber matters for calls that read or write memory the kernel owns, such as the console write.

The error code is a small negative number on failure. The specification defines the set:

ValueNameMeaning
0SBI_SUCCESSThe call worked
-1SBI_ERR_FAILEDFailed for an unspecified reason
-2SBI_ERR_NOT_SUPPORTEDThe extension or function is not implemented
-3SBI_ERR_INVALID_PARAMAn argument was invalid
-4SBI_ERR_DENIEDThe request is not allowed
-5SBI_ERR_INVALID_ADDRESSAn address argument is invalid
-6SBI_ERR_ALREADY_AVAILABLEThe resource is already available

Ask first: the base extension

Firmware differs, and a kernel that assumes an extension exists will fail on a platform that lacks it. The base extension, EID 0x10, is the one extension every SBI implementation must provide, and it answers questions about the rest.

sbi.cc
#define SBI_EXT_BASE 0x10

#define SBI_BASE_GET_SPEC_VERSION 0
#define SBI_BASE_GET_IMPL_ID      1
#define SBI_BASE_GET_IMPL_VERSION 2
#define SBI_BASE_PROBE_EXT        3

static inline struct sbiret sbi_call1(long eid, long fid, long a0)
{
    return sbi_ecall(eid, fid, a0, 0, 0, 0, 0, 0);
}

long sbi_probe_extension(long eid)
{
    struct sbiret r = sbi_call1(SBI_EXT_BASE, SBI_BASE_PROBE_EXT, eid);
    return r.error == 0 ? r.value : 0;               // non-zero means available
}

void sbi_print_info(void)
{
    struct sbiret v = sbi_ecall(SBI_EXT_BASE, SBI_BASE_GET_SPEC_VERSION, 0, 0, 0, 0, 0, 0);
    struct sbiret id = sbi_ecall(SBI_EXT_BASE, SBI_BASE_GET_IMPL_ID, 0, 0, 0, 0, 0, 0);
    struct sbiret iv = sbi_ecall(SBI_EXT_BASE, SBI_BASE_GET_IMPL_VERSION, 0, 0, 0, 0, 0, 0);

    kprintf("SBI spec v%ld.%ld, implementation id %ld, version %lx\n",
            (v.value >> 24) & 0x7F, v.value & 0xFFFFFF, id.value, iv.value);
}

The specification version packs the major number in bits 30:24 and the minor in bits 23:0. Implementation ID 1 is OpenSBI, and its version number is encoded as the major in the upper half and the minor in the lower. On QEMU 9.2 with the bundled OpenSBI v1.5, the output is:

Text
SBI spec v2.0, implementation id 1, version 10005

Probe before using anything that arrived after the first release. An ecall for an unknown extension is not a crash: the firmware returns SBI_ERR_NOT_SUPPORTED in a0, which is why a failed probe is cheap to test:

main.cc
kprintf("DBCN: %s\n", sbi_probe_extension(0x4442434E) ? "yes" : "no");
kprintf("TIME: %s\n", sbi_probe_extension(0x54494D45) ? "yes" : "no");
kprintf("HSM:  %s\n", sbi_probe_extension(0x48534D)   ? "yes" : "no");
kprintf("SRST: %s\n", sbi_probe_extension(0x53525354) ? "yes" : "no");
Text
DBCN: yes
TIME: yes
HSM:  yes
SRST: yes

Extension IDs are 32-bit values, and most are the ASCII spelling of the name: "TIME" is 0x54494D45, "HSM" is 0x48534D, and "DBCN" is 0x4442434E.

Printing: the debug console extension

Before you have a UART driver, the firmware prints for you. The Debug Console extension (DBCN, 0x4442434E) has three functions: write a buffer, read into a buffer and write one byte. The byte version is the easiest to use:

sbi.cc
#define SBI_EXT_DBCN 0x4442434E

void sbi_putc(char c)
{
    sbi_ecall(SBI_EXT_DBCN, 2, (unsigned char)c, 0, 0, 0, 0, 0);   // FID 2: write byte
}

// FID 0: write num_bytes bytes starting at the physical address (base_lo, base_hi).
long sbi_write(const char *buf, unsigned long n)
{
    struct sbiret r = sbi_ecall(SBI_EXT_DBCN, 0, (long)n, (long)buf, 0, 0, 0, 0);
    return r.error == 0 ? r.value : r.error;                      // bytes written, or an error
}

The buffer address is physical, split across two arguments for 32-bit compatibility, with the high half zero on RV64 when the address fits. The call works in a kernel with paging off, or with an identity map, and it breaks the moment the kernel uses virtual addresses that are not the physical ones, because the firmware interprets the argument as physical. Writing a byte at a time sidesteps that, which is why sbi_putc is the safe default.

Older firmware may not provide DBCN. The legacy console extensions, EID 0x01 for putchar and 0x02 for getchar, were removed from the specification in version 2.0 but remain in OpenSBI for compatibility. Probe DBCN first and fall back to legacy only when you must support older firmware.

Timers

A supervisor kernel cannot program the machine timer directly, because the compare register lives in the machine-mode CLINT. The TIME extension (0x54494D45) has one function, set_timer, that asks the firmware to raise a supervisor timer interrupt when the counter reaches an absolute value:

sbi.cc
#define SBI_EXT_TIME 0x54494D45

void sbi_set_timer(unsigned long stime_value)
{
    sbi_ecall(SBI_EXT_TIME, 0, (long)stime_value, 0, 0, 0, 0, 0);
}

Read the current counter with rdtime, add the interval and call sbi_set_timer. The firmware clears the pending interrupt when you set a new value, which is how a handler acknowledges a tick. To stop the timer, set it to the maximum value.

The Sstc extension, present on newer cores and enabled in recent QEMU versions, adds an stimecmp CSR that supervisor mode writes directly, and avoids the trap into firmware on every tick. Check isa strings in the device tree for sstc before relying on it, and keep the SBI path as the fallback.

Starting other harts

At power-on only one hart runs your kernel. The others wait in firmware, in a stopped state. The HSM extension, Hart State Management, controls them. hart_start (FID 0) takes the hart ID, the physical address where it should begin, and an opaque value delivered in a1:

sbi.cc
#define SBI_EXT_HSM 0x48534D

int sbi_hart_start(unsigned long hartid, unsigned long start_addr, unsigned long opaque)
{
    return (int)sbi_ecall(SBI_EXT_HSM, 0, (long)hartid, (long)start_addr, (long)opaque, 0, 0, 0).error;
}

// FID 2: hart_get_status returns 0 started, 1 stopped, 2 start pending, 3 stop pending, ...
long sbi_hart_status(unsigned long hartid)
{
    return sbi_ecall(SBI_EXT_HSM, 2, (long)hartid, 0, 0, 0, 0, 0).value;
}

The started hart begins at start_addr in supervisor mode, with satp zero and interrupts off, a0 set to its hart ID and a1 to the opaque value. It has no stack, so its entry code must set one up, usually from a per-hart table indexed by the ID. A common pattern is to pass the address of that hart's stack as the opaque value, so the entry code needs only mv sp, a1.

With -smp 4, starting hart 1 and checking its state:

main.cc
int err = sbi_hart_start(1, (unsigned long)secondary_entry, (unsigned long)hart1_stack_top);
kprintf("hart_start(1): %d\n", err);
kprintf("hart 1 status: %ld\n", sbi_hart_status(1));
Text
hart_start(1): 0
hart 1 status: 0

Status 0 means started. A returned error of -3, invalid parameter, means the hart ID does not exist, and -6, already available, means it is already running.

Inter-hart signals and remote fences

Two more extensions matter once there is more than one hart. The IPI extension (0x735049) sends an inter-processor interrupt, which arrives on the target as a supervisor software interrupt, and the RFENCE extension (0x52464E43) asks other harts to flush their translation caches or instruction caches, which a kernel needs after it changes a page table that another hart may be using.

sbi.cc
#define SBI_EXT_IPI    0x735049
#define SBI_EXT_RFENCE 0x52464E43

// Send a software interrupt to the harts whose bit is set in hart_mask, relative to hart_mask_base.
void sbi_send_ipi(unsigned long hart_mask, unsigned long hart_mask_base)
{
    sbi_ecall(SBI_EXT_IPI, 0, (long)hart_mask, (long)hart_mask_base, 0, 0, 0, 0);
}

// Ask the selected harts to execute sfence.vma over a virtual address range.
void sbi_remote_sfence_vma(unsigned long hart_mask, unsigned long hart_mask_base,
                           unsigned long start, unsigned long size)
{
    sbi_ecall(SBI_EXT_RFENCE, 1, (long)hart_mask, (long)hart_mask_base,
              (long)start, (long)size, 0, 0);
}

Both take a hart mask: a bit per hart, plus a base to shift the window, so that a machine with more than 64 harts is addressed in slices. Skipping the remote fence after unmapping a page is a classic multi-hart bug, with a stale mapping on another hart as the symptom.

Shutting down

The system reset extension (SRST, 0x53525354) powers off or reboots the machine. Function 0, system_reset, takes a type and a reason:

sbi.cc
#define SBI_EXT_SRST 0x53525354

#define SRST_SHUTDOWN    0
#define SRST_COLD_REBOOT 1
#define SRST_WARM_REBOOT 2

__attribute__((noreturn)) void sbi_shutdown(void)
{
    sbi_ecall(SBI_EXT_SRST, 0, SRST_SHUTDOWN, 0, 0, 0, 0, 0);
    for (;;)
        __asm__ volatile("wfi");                 // reached only if the firmware refused
}

Under QEMU, this exits the emulator with status 0, which makes it a convenient way to end a test run, though it does not signal failure. For pass or fail results, the test finisher device is a better fit, as the guide shows.

Boundaries

The SBI is the right abstraction when you want a portable kernel across boards. It has two costs. Every call is a trap into machine mode, so a hot path such as a timer tick on a busy system pays for a context change that a direct register write would avoid, and extensions such as Sstc exist to remove that cost. And the firmware owns what it owns: you cannot use the machine timer for anything else, and you cannot change PMP regions. A kernel that must control those, such as one that is itself the firmware, runs in machine mode and does not use SBI at all.

Version skew is the other practical problem. A kernel that uses DBCN fails on firmware older than SBI 2.0, and one that uses only the legacy calls fails on firmware that dropped them. The probe-first discipline from earlier is what lets one binary run on both.

Also inAssembly
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.