5  Entering the OS

Winter Semester 2026/2027

Author
Affiliation

Stavros Kousidis

ICCT

Lecture 4 ended with a process that never yields. Our CP1 operating system regains control only when the process calls process_yield() or process_exit(); a process stuck in for (;;) never makes that call. This chapter answers the first half of the problem: how can the CPU transfer control to the OS? The answer is the trap. Lecture 6 then uses the same mechanism for an event the process did not ask for.

We keep the Exercise 2 application. Its worker() and permute() do not change. What changes is everything underneath: how control reaches the OS, what is saved, and what role main() plays.

5.1 The mental model of our current OS

5.1.1 The lifetime from Lecture 3, revisited

Lecture 3 drew the lifetime of our first process as two lines: the OS on the left, the process on the right, and context switches between them. There we drew only what we wanted the OS to be: absent while the process runs. Our construction did more. main() was itself a suspended execution: it was paused inside process_run() and context_switch(), its call chain stayed on the OS stack, and its registers were saved in os_context. Each yield resumed main() exactly where it had stopped. In the completed diagram, ! marks this suspended OS execution (red on the slides):

        OS                           Process
        |
 create |
    run +------- context switch ------->| (start)
        !                               |
        |<------ context switch --------+ yield
        |
    run +------- context switch ------->| (resume)
        !                               |
        |<------ context switch --------+ exit
        |

In CP1 the OS was managed exactly like a process: two executions taking turns. This is what “main() simulated the OS” means. The red line is the part of the picture this chapter removes.

5.1.2 What if the process never yields?

for (;;) { /* keep computing */ }

The CP1 OS gets control back only through the call to context_switch() inside process_yield() or process_exit(). Both are ordinary function calls made by the process. If the process never calls, our OS never runs again.

5.2 From calls to traps

5.2.1 Two halves of the answer

The full answer to a never-yielding process has two halves:

Lecture 5: the process asks       ecall   -> CPU -> OS
Lecture 6: an event interrupts    timer   -> CPU -> OS

Both use the same entry path into the OS. This lecture builds it for the deliberate case: the process still decides when it enters the OS, now through an instruction instead of a function call, so the trace is predictable. process_yield() and process_exit() keep their interface; only the mechanism behind them changes. Lecture 6 reuses the identical path for an asynchronous event; the only new part there is the source of the event.

The goal of the refactoring is that the OS really discontinues while the process runs: no more red lines.

5.2.2 The lifetime through the CPU

With traps, the same lifetime looks different:

         OS                 CPU                   Process
                        +--------+
start-up | prepare      |        |
         +------------->| return |------------->| (start)
                        |        |              | ecall "yield"
         |<-------------|  trap  |<-------------+
 handler | decide       |        |
         +------------->| return |------------->| (resume)
                        |        |              | ecall "exit"
         |<-------------|  trap  |<-------------+
 handler | decide       |        |

The CPU is drawn as a box, not as a lifeline: it is not a third execution taking turns with the OS and the process, but the mechanism built into instruction execution that both rely on. It contains two mechanisms. Trap is the way into the OS: instead of continuing with the next instruction, the CPU records why and where, and continues at an address the OS chose earlier. Return is the way out: the OS executes a return instruction, and the CPU continues the selected process. The box is open at the bottom because every later trap and return goes through the same mechanism.

The red lines are gone. While the process runs, nothing of the OS is waiting; the OS runs only when the CPU traps into it, and after the return it is finished, not paused. Each OS bar is a short episode: start-up once, then one handler run per trap. The process is now the only long-lived execution. This does not mean that the OS forgets everything: its data, such as the process table, stays in memory. What disappears is a suspended execution with its own registers and call chain, and that is exactly what the red line was.

Even the first start is a return: the OS prepares saved state for the new process as if it had trapped into the OS just before its first instruction, and returns into it. Starting and resuming a process are the same operation for the CPU. The rest of the chapter replaces each plain word in this picture with code: “start-up”, “prepare”, “handler” and “decide”.

5.2.3 What the CPU provides for traps and returns

The mechanism is the CPU’s side of a contract, the ISA from Lecture 1. It consists of three kinds of parts:

Kind Provided by the CPU Used how
state mtvec, mepc, mcause, mstatus, mscratch read/written by the OS
instructions csrr, csrw, csrs, csrrw, mret executed by the OS
ecall executed by the process
rules on a trap: record, interrupts off, jump automatic, on an event
on a return: restore interrupt state, continue when the OS runs mret

The state lives in control and status registers (CSRs): CPU registers outside the 32 general-purpose registers x0–x31. Ordinary loads and stores cannot reach them; only the CSR instructions of the Zicsr extension can, which is why our build uses -march=rv64imac_zicsr. In our code we use four assembler forms: csrr (CSR read) copies a CSR into a register, csrw (CSR write) copies a register into a CSR, csrs (CSR set) sets bits in a CSR, and csrrw (CSR read and write) does both at once. Only csrrw is itself one of the Zicsr instructions; the other three are convenient pseudoinstructions that the assembler translates into them.

mret (machine return) and ecall (environment call, a call into the execution environment, here the OS) are not CSR instructions: they read or write CSRs only implicitly, through the CPU’s rules. mret applies the return rule; ecall causes a trap on purpose.

The OS configures the state, uses the instructions, and relies on the rules. The third row is why “services” would be a misleading word for what the hardware provides: a service is requested, whereas the trap rule is applied whether anyone asks or not. The CPU is also distinct from the platform, the machine around it: memory map, UART, and in Lecture 6 the timer. There a platform device raises the event, and the CPU’s trap rule reacts to it.

5.3 Trap and return: what the CPU does

5.3.1 Why a function call is not enough

In CP1 the OS got control back only through a call the process made. A call happens only if the running code decides to make it, and it brings three things with it:

  • the caller chooses the moment;
  • the call instruction sets ra: where to continue;
  • the calling convention says which registers may be lost.

This is why context_switch() could save only ra, sp and s0–s11. A process in for (;;) never calls, and an event between two instructions offers none of these properties. Each missing property becomes a job of the trap mechanism:

  • no ra, so nobody says where to continue: the CPU records it;
  • no chosen moment, so the event can arrive at any time: the CPU disables interrupts while the OS saves;
  • no calling convention, so every register may be live: the OS saves all of them.

The first two jobs are the CPU’s and follow in this section; the third is the OS’s and follows in the next.

5.3.2 Traps

A trap is a transfer of control to an OS-defined handler that the CPU performs itself. “OS-defined” means that the OS chooses beforehand where the CPU continues; the CPU runs no OS code and makes no decisions, it only redirects the pc. RISC-V distinguishes two kinds:

synchronous asynchronous
caused by the current instruction an independent event
where at that instruction, every run between two instructions, varies
RISC-V name exception interrupt
“trap pc” the causing instruction the next instruction, not yet executed
in BVS1 ecall, illegal instruction (Lecture 5) timer (Lecture 6)

A synchronous trap is caused by the instruction being executed. It is reproducible: it happens at the same instruction every time the program runs with the same input, and one can point to that line in the disassembly. An asynchronous trap is caused by an event outside the instruction stream; the CPU takes it between two instructions, wherever the program happens to be, so the place varies from run to run. Both kinds enter the same OS code, so “trap” is the umbrella term. Calling an ecall an interrupt blurs a distinction we need in Lecture 6.

This axis is separate from the question whether a trap is cooperative. An illegal instruction is synchronous but not cooperative: the process causes it but does not intend it as an entry into the OS. Today’s normal case, ecall, is synchronous and cooperative; Lecture 6 changes both at once.

In this section, “handler” means all OS code that runs after a trap. The next section splits it into the provided assembly trap_entry, to which the CPU jumps, and the C function trap_handler(), which trap_entry calls.

5.3.3 Who can save the pc?

Lecture 4 showed that no saved context contains the live pc. It contains a continuation address: a saved value saying where an execution continues when it is restored. In CP1 the process supplied that address itself, because its call placed it in ra.

Suppose the CPU simply jumped into the OS, to the address the OS chose earlier:

process   ecall               <- must continue after this
OS        first instruction   <- live pc is here now

The reason this is a problem lies in what the pc is. The x registers and the CSRs are addressable: instructions name them as operands and read or write them. The pc (program counter) is not. It is architectural state that changes only implicitly, through control transfers (jumps, branches, ret, mret) and through the trap rule. No instruction stores “the pc” into memory the way sd stores a register.

Software is not blind to the program counter: PC-relative instructions such as auipc compute addresses relative to the current instruction. But at the first instruction of the OS code, the live pc describes the OS code. The OS can no longer recover where the process was, unless the CPU captured that address at the moment of the jump.

5.3.4 On a trap: record where and why

On a trap, the CPU first records where and why, in two CSRs:

CSR Stands for Holds
mepc Machine Exception Program Counter the trap pc
mcause Machine Cause bit 63: interrupt; bits 62..0: code

We use trap pc for the program-counter value that the CPU records in mepc on trap entry. This is our teaching term, not a named RISC-V architectural object. Despite “Exception” in its name, mepc is written on every trap, interrupts included. The meaning of the trap pc depends on the kind of trap:

  • for an exception, it is the address of the instruction that caused it; for an ecall, the ecall itself;
  • for an interrupt, it is the address of the instruction that was about to execute and has not executed yet.

The difference matters as soon as the OS returns: after an exception it may have to skip the causing instruction, after an interrupt it must not. Three terms now stay apart:

live pc               current execution position of the CPU
trap pc               value the CPU captured in mepc on trap entry
continuation address  saved value: where this execution resumes

interrupt:  continuation address = trap pc
ecall:      continuation address = trap pc + 4

mepc is a CSR, so software can read it; it holds a copy of a pc value captured by the CPU. Software never reads the pc itself.

The mcause values we need are:

mcause Meaning mepc holds
2 illegal instruction that instruction
11 ecall from M-mode the ecall
7, interrupt bit set machine timer (Lecture 6) the next instruction, not yet executed

On RV64, mcause is 64 bits wide: bit 63 is the interrupt bit, bits 62..0 hold the code. In hexadecimal the three values are 0x2, 0xb and 0x8000000000000007. The same code can mean different things depending on the interrupt bit: exception 7 is a store/AMO access fault, interrupt 7 the machine timer.

Our model focuses on the minimal trap state we need: mepc, mcause, and the relevant mstatus fields. The RISC-V privileged architecture defines additional trap-related state, for example mtval, which we deliberately leave out.

5.3.5 On a trap: interrupts off

The CPU also changes two bits of the CSR mstatus (machine status), bits 3 and 7:

Bit Stands for Means
MIE Machine Interrupt Enable interrupts allowed (1) or not (0)
MPIE Machine Previous Interrupt Enable the value MIE had before the trap
MPIE <- MIE     remember whether interrupts were allowed
MIE  <- 0       no interrupt now

Nobody interrupts the OS while it saves the process’s state. A second interrupt at that moment would overwrite mepc and mcause before they are saved. The precise rule is that the CPU saves MIE into MPIE and clears MIE; it is not a general statement that “traps disable interrupts”. MIE does not affect exceptions: an ecall or an illegal instruction traps regardless. The CPU also records the privilege mode the trap came from in a third field, MPP; in our system that is always machine mode.

In Lecture 5 no interrupt is enabled yet, so the effect is not observable. Lecture 6 adds a second, similarly named CSR: mie (lower case) holds one enable bit per interrupt source. A timer interrupt is taken only if it is pending and both mstatus.MIE and the timer’s bit in mie are set; Lecture 6 shows where “pending” is recorded.

5.3.6 On a trap: jump

pc <- mtvec        the address held in the CSR mtvec

mtvec (Machine Trap-Vector) holds a base address and a mode field. We use direct mode (mode 0), in which every trap goes to the one base address. trap_entry is 4-byte aligned, so its address leaves the two mode bits zero. The OS puts that address there once, at start-up:

csr_write(mtvec, (uintptr_t)trap_entry);    /* csrw */

csr_write() is a provided C helper around the csrw instruction. trap_entry is a label in the provided trap.S: the name of the first instruction of the trap path. Like every symbol listed with nm -n in Lecture 4, it gets its address from the linker when the linker places .text. trap.h declares it as void trap_entry(void); only so that C code can take its address; (uintptr_t)trap_entry is that address as a number for csrw. Nobody calls trap_entry, as the next section shows. The glossary distinguishes label and symbol.

The prefix m in all these names means machine mode, the most privileged RISC-V mode, in which our whole system runs. The OS decides once where all traps enter: at trap_entry.

5.3.7 On a return: mret

On a trap On a return (mret, machine return)
record where: mepc <- trap pc continue there: pc <- mepc
record why: mcause <- reason nothing: mcause was only for the OS
interrupts off: MPIE <- MIE, MIE <- 0 previous state back: MIE <- MPIE

A return is not an undo of the trap. The record of where becomes the place to continue, the record of why simply stays, and the interrupt-enable bit gets back the value saved in MPIE. Architecturally, mret restores the previous interrupt-enable state; it does not by itself mean “interrupts on”. It also sets MPIE to 1 and restores the privilege mode from MPP, in our system always machine mode. Whether interrupts are on after mret is therefore the OS’s choice: our return path deliberately sets MPIE to 1 before every mret, so in our system every process runs with machine interrupts enabled. Lecture 6 depends on this.

If the OS changes mepc before mret, execution continues elsewhere. Compare it with ret in Lecture 3: ret jumps to ra; mret jumps to mepc. Both are ordinary instructions that use saved state. The OS can therefore return to the instruction after an ecall, or later to a different execution altogether. The pc is still never written like a register: mret sets it from mepc.

The CPU neither saves nor restores the process’s registers: the OS saves them after the trap and restores them before mret. Only the process’s registers need this. The OS has none to restore: each handler run starts fresh, and no OS execution is resumed later. In CP1 the saved OS context in os_context was exactly the red line; with traps it is gone.

5.4 Between trap and return: the OS’s mechanisms

5.4.1 Why ra, sp, s0–s11 no longer suffice

CP1 saved 14 values, and at a call boundary that was enough. Compiled code follows the RISC-V calling convention, a software agreement defined in the RISC-V ABI. The caller, the function that makes a call, must expect t0–t6 and a0–a7 to be destroyed and keeps whatever it still needs in s registers or in its stack frame. The callee, the function being called, must hand back sp and s0–s11 unchanged. Across a call, only sp, s0–s11 and the continuation in ra matter; everything else the caller needs is in memory. Saving all 31 registers would also have been correct, just unnecessary.

The compiler guarantees this convention for the code it generates; it does not enforce it. Hand-written assembly such as CP1’s context_switch has to keep it itself, and nobody checks. The hardware knows nothing of it, which is why the CPU’s trap rule gives no such guarantee.

A trap is not a call, and the convention gives no guarantee there. The same entry path serves very different situations:

ecall in process_yield()   at a call boundary
illegal instruction        anywhere in the code
timer (Lecture 6)          between any two instructions

For example:

    add  t0, a0, a1     # t0 holds an intermediate value
    # <- timer interrupt here (Lecture 6)
    slli t0, t0, 3      # t0 is still needed

t0 is caller-saved, but that only means a callee may destroy it. Here there is no callee, so nobody saved t0.

The same happens in compiled code, not only in hand-written assembly. Here is a loop that only counts, the kind of process Lecture 6 interrupts with the timer:

volatile unsigned long counter = 0;
while (counter < 1000000) {
    ++counter;
}

Our build (GCC 13.2, -O2) turns the loop into five instructions; the comments are ours:

800002b4:  ld    a5,8(sp)       load counter
800002b6:  addi  a5,a5,1        +1
800002b8:  sd    a5,8(sp)       store counter
800002ba:  ld    a5,8(sp)
800002bc:  bgeu  a4,a5,800002b4 loop while counter <= limit

The compiler loaded the limit 999999 into a4 once, before the loop, and keeps it there for the whole loop. Between the first ld and the addi, the counter exists only in a5. Both are argument registers, so caller-saved, and no call is in sight: nothing in the calling convention protects them. A trap between any two of these instructions must leave a4 and a5 exactly as they were, although the handler’s C code is free to use both. The same holds for every other caller-saved register a compiler may use in this way: ra, t0–t6 and a0–a7.

Even at our ecall the CP1 subset is not enough. Because process_yield() is an ordinary function, the call boundary does protect the caller’s own live values: they are in s registers or in memory. But the system-call registers themselves are not among the 14 values: a7 tells the handler which system call this is, and a0 and a1 carry the arguments and the result. The handler reads them from the frame, so the trap path must capture them. In addition, the assembly statement in syscall.c promises the compiler that only a0 changes across the ecall; an inlined stub could keep further live values in caller-saved registers. This system-call contract is the OS’s choice: the RISC-V ABI leaves system calls outside its scope.

One entry path serves all traps: it must save all 31 writable integer registers. It must also save them before any C code runs, because the handler is a fresh run of C code that immediately uses registers for its own work.

5.4.2 The trap frame replaces struct context

The complete saved integer context of an execution that trapped, as our teaching model requires it, is its trap frame:

struct trap_frame {
    uintptr_t regs[32];   /* regs[i] = xi; x0 unused */
    uintptr_t pc;         /* continuation address */
};

regs[i] holds register xi. regs[0] is unused because x0 is hardwired to zero: it always reads as 0 and discards every write, so it carries no state of the process. The 32 slots keep the slot index equal to the register number, so xi lies at byte offset 8·i. We build for rv64imac, without the floating-point extensions F and D, so “all registers” means the 31 writable integer registers.

The field pc is the saved continuation address for this execution, an ordinary value in memory; it is not a copy of the live pc. At trap entry it receives the trap pc from mepc. For an interrupt that already is the continuation address; for an ecall the handler converts it, as shown below. The layout is fixed: the provided assembly stores xi at byte offset 8·i and pc at offset 256.

The name is historical. In many systems every process has its own OS stack, and the trap entry pushes the saved registers onto it, where the block sits like the stack frame of a call (Lecture 4). Ours is not on any stack: frame is a field of struct process, next to stack but not inside it. In the rest of this chapter, “frame” alone means the trap frame; the call data of Lecture 4 is called “stack frame”.

The trap frame replaces the CP1 context in the process object; the field order is otherwise unchanged:

struct process {
    process_entry_t entry;
    uint8_t stack[STACK_SIZE];
    struct trap_frame frame;      /* was: struct context context */
    enum process_state state;
    int exit_status;
};
CP1 struct context struct trap_frame
registers ra, sp, s0–s11 31 integer registers
continuation ra, restored by ret pc, via mepc and mret
field struct context context; struct trap_frame frame;

The field is called frame, so that code reads p.frame and frame->pc; the type name says what kind of frame it is. The cooperative CP1 context was the special case of this frame that a function-call boundary allows.

5.4.3 The trap path replaces context_switch(): save

context_switch() saved and restored a context in one function. With traps, its two halves become two pieces of the provided trap.S: the trap path, which saves, and the return path, which restores. context_switch() saved 14 registers when the process called it; the trap path saves 31 registers plus the trap pc when the CPU jumps to it.

The trap path has to solve one problem first. At trap entry every register belongs to the process, yet every store such as sd x5, 40(base) needs an address in a register. Loading the frame address into any register would destroy a process value that is not yet saved, and sp belongs to the process as well. The solution is a CSR that already holds the address: mscratch, which has no meaning of its own and is written only by the OS. Before every mret, the first start included, the return path sets it to the frame it returns into.

trap_entry:                  # mscratch = &p.frame, set by OS
    csrrw t6, mscratch, t6   # swap: t6 = &p.frame
    sd    x1, 8(t6)          # x1 .. x30 into the frame
    sd    x2, 16(t6)
    sd    x3, 24(t6)
    sd    x4, 32(t6)
    sd    x5, 40(t6)
    sd    x6, 48(t6)
    sd    x7, 56(t6)
    sd    x8, 64(t6)
    sd    x9, 72(t6)
    sd    x10, 80(t6)
    sd    x11, 88(t6)
    sd    x12, 96(t6)
    sd    x13, 104(t6)
    sd    x14, 112(t6)
    sd    x15, 120(t6)
    sd    x16, 128(t6)
    sd    x17, 136(t6)
    sd    x18, 144(t6)
    sd    x19, 152(t6)
    sd    x20, 160(t6)
    sd    x21, 168(t6)
    sd    x22, 176(t6)
    sd    x23, 184(t6)
    sd    x24, 192(t6)
    sd    x25, 200(t6)
    sd    x26, 208(t6)
    sd    x27, 216(t6)
    sd    x28, 224(t6)
    sd    x29, 232(t6)
    sd    x30, 240(t6)
    csrr  t5, mscratch       # t6 of the process
    sd    t5, 248(t6)        #   as x31
    csrr  t5, mepc           # the trap pc
    sd    t5, 256(t6)        #   as frame->pc
    la    sp, _stack_top     # only now: the OS stack
    mv    a0, t6             # for trap_handler: &p.frame
    call  trap_handler       # runs on the OS stack

The first instruction exchanges t6 and mscratch: csrrw rd, csr, rs1 sets rd to the old CSR value and the CSR to the old value of rs1. Afterwards t6 (x31) holds the frame address, and the process’s t6 waits in mscratch. Every store now has an address: xi goes to byte offset 8·i. The parked t6 is fetched through t5 (x30), which is free by then because it has already been stored, and saved as x31. Then the trap pc from mepc goes to offset 256.

The CPU leaves sp unchanged: a trap changes pc, mepc, mcause and mstatus, but no general-purpose register. Until la sp, sp still points into the process stack. Saving needs no stack, because the stores go through t6 into p.frame. Only the C handler needs a stack for its stack frames, so only after everything is saved does la sp, _stack_top select the OS stack. The OS stack is not new: the linker reserves it, and main() has used it since Lecture 2. What is new is that a trap does not select it; the provided code does. The process’s sp cannot be trusted in general, and OS data should not be mixed into process storage. Some architectures switch stacks in hardware, for example x86 when coming from user mode; RISC-V does not.

trap_entry and trap_handler() are different kinds of code. trap_entry is never called: the CPU jumps there via mtvec, between two arbitrary instructions of the process, so it can follow no calling convention, and it ends with mret. In its last two lines it calls trap_handler(), an ordinary C function that runs on the OS stack, receives the frame in a0, and returns the frame to restore in a0.

5.4.4 The return path replaces context_switch(): restore

The second half of trap.S follows directly after the call. Both listings are the complete provided code; only the file’s header comment and assembler directives are left out, and the offset 256, which trap.S names FRAME_PC, is written as a number:

    call  trap_handler       # returns a0 = frame to restore
os_start:                    # os_run() enters here, too
    csrw  mscratch, a0       # a0: result of trap_handler
    ld    t5, 256(a0)
    csrw  mepc, t5           # where to continue
    li    t5, (3 << 11) | (1 << 7)   # MPP = M, MPIE = 1
    csrs  mstatus, t5
    ld    x1, 8(a0)          # x1 .. x31 from the frame, not a0
    ld    x2, 16(a0)
    ld    x3, 24(a0)
    ld    x4, 32(a0)
    ld    x5, 40(a0)
    ld    x6, 48(a0)
    ld    x7, 56(a0)
    ld    x8, 64(a0)
    ld    x9, 72(a0)
    ld    x11, 88(a0)
    ld    x12, 96(a0)
    ld    x13, 104(a0)
    ld    x14, 112(a0)
    ld    x15, 120(a0)
    ld    x16, 128(a0)
    ld    x17, 136(a0)
    ld    x18, 144(a0)
    ld    x19, 152(a0)
    ld    x20, 160(a0)
    ld    x21, 168(a0)
    ld    x22, 176(a0)
    ld    x23, 184(a0)
    ld    x24, 192(a0)
    ld    x25, 200(a0)
    ld    x26, 208(a0)
    ld    x27, 216(a0)
    ld    x28, 224(a0)
    ld    x29, 232(a0)
    ld    x30, 240(a0)
    ld    x31, 248(a0)
    ld    x10, 80(a0)        # a0 last: it held the frame
    mret                     # pc <- mepc, MIE <- MPIE

After call trap_handler, a0 holds the returned frame, and the code simply continues at the label os_start, with no instruction in between. The label exists because os_run() calls the same code as os_start() for the first start of a process. The return path is one piece of code with two ways in: after every trap, and once from os_run() for the first start.

The first line makes mscratch point to the frame that is about to run, which prepares that process’s next trap. The li/csrs pair sets MPP to machine mode (3, in bits 11–12) and MPIE to 1 (bit 7) in mstatus, so that mret stays in machine mode and, through MIE <- MPIE, enables machine interrupts for the process: our policy, not an effect of mret alone. A trap sets MPP itself, but the first mret from os_start needs it set explicitly. The loads skip x10: a0 is restored last because it holds the frame address during all other loads.

5.4.5 trap_handler(): return the frame to restore

Between the two paths sits one C function:

struct trap_frame *trap_handler(struct trap_frame *trapped);

The trap path calls it with a0 = &p.frame. It receives the saved state of the process that trapped and returns the state that runs next:

Returned frame Meaning
the same one resume
another one schedule (Lecture 7)

This one signature carries the whole CP2 path. The provided assembly calls it; the OS’s C code implements it. In Exercise 4 it comes from libkernel.a; for CP2 students write their own, extended by timer interrupts (Lecture 6) and a scheduler (Lecture 7). The parameter is called trapped, not interrupted: today every trap is synchronous. As in Lecture 3, a switch saves one context and restores another; the trap path only splits that into a hardware part, a provided assembly part, and a C decision in the middle.

5.5 Refactoring main() and process_yield() to use traps

5.5.1 ecall: a trap on purpose

ecall is an ordinary instruction whose only effect is a trap, with mcause 11. The provided process_yield(), compiled with GCC 14.2:

process_yield:
    li   a0, 0
    li   a1, 0
    li   a7, 1          # SYS_YIELD
    ecall               # -> mtvec, mcause = 11
    ret

Other compilers may order the three li differently. This is not hand-written assembly: syscall.c is C with one inline ecall.

A system call is a request to the OS made with ecall. We use the convention that a7 selects the service and a0, a1 carry arguments; the OS may return a result in a0. Keep the request apart from the function that makes it: process_yield() is the C function that makes the system call yield, just as the C library’s write() in Linux is a function that makes the system call write. process_yield() and process_exit() now make our first two system calls, yield and exit. The application still calls them by name; only the code behind them changed.

5.5.2 Continue after the ecall

For an ecall, the trap pc is the address of the ecall itself. Restoring the frame unchanged would execute the ecall again, which traps again: the process would yield forever and never reach its next line, and the OS would print “yielded” endlessly. The handler therefore converts the saved trap pc into the continuation address:

trap_entry:   p.frame.pc = mepc   trap pc: the ecall itself
trap_handler: p.frame.pc += 4     now the continuation address
os_start:     mepc = p.frame.pc; mret

The left column names the code that does each step. The right side describes in C-like notation what that code does: only the middle line is real C, written in the handler as trapped->pc += 4, because trapped points to p.frame. The other two lines stand for the csrr/sd and ld/csrw/mret instructions in trap.S.

This is why the handler modifies the trap frame at all. An ecall is always 4 bytes long; it has no compressed 2-byte form, even with the C extension enabled in our build. Interrupts receive no such adjustment: there mepc already names the instruction that still needs to execute.

5.5.3 yield and exit as system calls

System call a7 OS action
yield 1 report, RUNNING -> READY, resume
exit 0 record a0 as status, -> FINISHED

With one process, yield marks the process READY and immediately selects it again. This looks pointless today; it becomes meaningful when there are several READY processes in Lecture 7. The exit status travels in a0 and is read from the saved frame, not from the live register: by the time C code runs, the live a0 holds the handler’s own argument. The os: output lines now come from the trap handler:

os: process 1 yielded
os: process 1 exited 0

5.5.4 Inside trap_handler()

The whole handler as of today, condensed from the reference implementation:

uintptr_t cause = csr_read(mcause);   /* the reason */
if (cause == EXC_ECALL_FROM_M) {      /* 11: ecall */
    trapped->pc += 4;
    long a0 = trapped->regs[REG_A0];
    switch (trapped->regs[REG_A7]) {
    case SYS_YIELD: return reschedule();
    case SYS_EXIT:  return finish_current(a0);
    }
}
report_unexpected(cause, trapped->pc);
return finish_current(EXIT_STATUS_TRAP);

The OS does not know why it was entered until it reads mcause. This is the difference to a function call, where the callee knows why it was called because the caller chose it. All traps arrive at the same code, so the first line reads the reason. EXC_ECALL_FROM_M is 11: only an ecall produces this cause, and our processes execute ecall only to make a system call, so the branch is the system-call path. RISC-V distinguishes where an ecall came from: 8 from user mode, 9 from supervisor mode, 11 from machine mode. Our processes run in machine mode.

The ecall branch combines the two previous subsections: += 4 turns the trap pc into the continuation address, and a7 selects the system call. Every branch ends by returning a frame, as the contract requires. reschedule() and finish_current() are the reference’s helpers: they update the state of the current process (READY, or FINISHED with a status), choose the next process and return its frame. With one process, yield returns the same frame; after exit, only the idle process is left, a wfi loop that the OS starts when nothing else is READY. An unknown system-call number leaves the switch and also ends the process with an error status.

report_unexpected() is a name used only here for brevity; in the reference implementation the report is inline code. The reference also has an interrupt branch before the ecall test, omitted here because no interrupt is enabled in the Exercise 4 stage. Lecture 6 adds the timer branch. Today’s handler is the core that students extend for CP2, not the CP2 handler.

5.5.5 Unexpected traps

A faulty instruction in the process enters through the same mtvec. Inserted into worker(), the following line places the 32-bit word 0, an encoding defined as illegal on RISC-V, into the code:

__asm__ volatile (".word 0");   /* illegal instruction */

The CPU traps with mcause = 2 and mepc = the address of the inserted word. trap_handler() does not find EXC_ECALL_FROM_M, so it reaches its last two lines: it reports the cause and the saved pc, marks the process FINISHED with an error status, and returns the next frame. With one process, that is the idle loop. The output, from a GCC 14.2 build, is:

trap: cause 2 at 0x80000136 in process 1

The first code line runs in the process; the output line is printed by the OS. The address is build-specific and can be located with objdump -d. One faulty process does not take down the OS. Without this case, the handler would have to guess, and a fault would look like a system call or vanish.

5.5.6 First entry: prepare a frame

A process that has never run has no saved state yet. As in CP1, the OS prepares one:

CP1 initial context Trap-frame equivalent
p.context.ra = process_start p.frame.pc = process_start
p.context.sp = stack top p.frame.regs[2] = stack top
p.context.s[i] = 0 all other p.frame.regs[i] = 0

The new process looks as if it had trapped into the OS just before its first instruction. Every assignment writes a field in memory, not a register: p.frame.pc is the saved continuation address, and the live pc receives this value only later, when the return path copies it into mepc and executes mret. regs[2] is sp (x2); the stack top must be 16-byte aligned, as in CP1. process_start() is still the internal bootstrap: it calls the entry function and, if that returns, process_exit(0). The first restore of this frame enters process_start(); this is the first-start return of the CPU-box lifetime.

5.5.7 Three entries

In CP1, main() simulated the OS. It called process_run(), got control back when the process yielded, and printed os: process yielded itself. With traps, a yield lands in trap_handler(), not in main(). The model “the OS is a program that calls processes” no longer fits. Instead, the OS is code that runs when an event occurs. main() therefore only starts the system:

void main(void)                 /* the OS's start-up */
{
    static struct process p;

    process_create(&p, worker);
    os_run();                   /* never returns */
}

os_run() installs mtvec, selects the first process and calls the provided os_start(), which restores that process’s frame and executes mret: the first return. main() never gets control back, neither by a return nor by a resume. The system now has three entries:

_start      CPU's entry      once, at reset; calls main()
main()      OS start-up      once; never returns
trap_entry  OS entry         every trap, via mtvec

_start (in start.S) sets up the OS stack and calls main(). _start is the CPU’s entry, main() is the OS’s start-up, and the trap vector is the OS’s entry for everything that happens afterwards. The trap vector is the address in mtvec, and that address is trap_entry. main() is where the OS begins, not where it lives.

Real operating systems follow the same pattern at this level: a one-time start-up, followed by event-driven entry into the kernel. In Linux, the start-up function start_kernel() initialises the system, including the trap vector. Through rest_init() it then creates two kernel threads, kernel_init and kthreadd, and the boot task itself becomes the idle task. kernel_init finally loads the first user program, init, which becomes PID 1; it enters user mode through a return instruction (sret, the supervisor-mode counterpart of mret). From user space the kernel is entered only through traps, and further processes are created by init and its descendants through the system calls fork and exec. The mechanisms differ in detail; the shape is the same. Our main() still creates the processes itself, because we have no system call for that yet.

5.5.8 Why p must become static

Exercise 2 declared struct process p; inside main(), an object with automatic storage duration. Its storage, including p.stack and the saved state, was part of main()’s stack frame at the top of the OS stack:

OS stack
+--------------------------------------+  _stack_top <- sp
| main()'s stack frame: p, p.stack ... |
+--------------------------------------+

In CP1 this was safe: main() stayed active, and the OS ran below its stack frame. Now every trap executes la sp, _stack_top, and trap_handler() builds its stack frames downward from _stack_top, into the region where p lies. main() is never resumed, so nothing treats its stack frame as live any more. The handler’s own call data overwrites the top of p, including parts of p.frame and p.state, at the first trap.

Whether that becomes visible depends on the build. With GCC 14.2 the output may even stay correct, because the overwritten saved registers happen to be unused by this small program; with clang the output stops after os: process 1 yielded. A run that looks correct is not a correctness argument: the saved state is no longer reliable, and Exercise 4 lets you find the overlap in the disassembly.

Declaring p as static gives it static storage duration: the object exists once, for the whole run, in .bss, outside every stack. A global variable outside main() has the same storage duration; static inside main() only keeps the name local, while the OS reaches the object through &p anyway. The rule behind this: anything that must outlive a single handler run must not live on the OS stack. The glossary defines both storage durations.

5.6 The whole path

5.6.1 The lifetime in detail

The CPU-box lifetime from the beginning of the chapter, now with the code names:

              OS             CPU               Process
                          +--------+
main()       | os_run()   |        |
os_start     +----------->| return |----------->| (start)
                          |        |            | ecall
trap_entry   |<-----------|  trap  |<-----------+
             | save frame |        |
trap_handler | pc += 4    |        |
os_start     +----------->| return |----------->| (resume)

exit takes the same path; its handler returns the idle process’s frame. “start-up” became main() and os_run(), each “handler” bar became three pieces of code, and “prepare” and “decide” are now concrete. The CPU box is unchanged: the CPU traps and returns; the OS saves, decides, and restores.

The same steps as a list of what runs where:

permute() calls process_yield()   on the process stack
  ecall                           CPU: mepc, mcause, pc <- mtvec
trap_entry: save 31 regs + pc     into p.frame
  la sp, _stack_top               now on the OS stack
trap_handler: cause 11, a7 = 1    pc += 4; READY, then RUNNING
  return &p.frame
os_start: restore p.frame, mret   pc = after the ecall
process_yield() returns           same permute() call

After mret, sp selects the process stack again because it was restored from the frame. process_yield() returns into the same permute() invocation, which continues with the same array.

5.6.2 Our trap model: who does what

Step Who What
trap CPU mepc, mcause; interrupts off; pc <- mtvec
save trap_entry registers and trap pc into the frame; OS stack
decide trap_handler() read mcause, return a frame
restore os_start registers and mepc from the frame
return CPU, mret pc <- mepc; MIE <- MPIE

The CPU’s two rules frame the OS’s three pieces of code. trap_entry and os_start are provided assembly; for CP2, students write their own trap_handler(), with timer and scheduler (following Lectures 6 and 7).

This is a deliberately restricted teaching model of trap-based OS entry, not a complete model of the RISC-V privileged architecture. Inside the model:

  • execution remains entirely in machine mode, with one trap entry point through mtvec;
  • the traps covered are ecall, timer interrupts (Lecture 6), and unexpected traps such as illegal instructions;
  • the CSRs our trap mechanism uses are mtvec, mepc, mcause and mstatus, which the hardware trap rule reads or writes, and mscratch, which the hardware never touches on a trap and our OS uses by convention; Lecture 6 adds the timer, a device of the platform, not of the CPU;
  • the trap transition itself is hardware; saving the process’s state, switching to the OS stack, calling the C handler and restoring the selected frame are software, in the provided assembly, which ends with mret;
  • the trap frame holds the 31 integer registers and the continuation address;
  • scheduling is choosing which trap frame is restored.

Outside the model: privilege modes and protection, delegation of traps between privilege levels, nested traps, virtual memory and page faults, further interrupt sources, floating-point state, and production-grade interrupt handling. Because everything runs in machine mode, nothing prevents a process from changing mtvec, the timer or OS memory; we accept this to keep the mechanism small and visible. The essential mechanism is this: an event transfers control into the OS, the state of the trapped execution becomes explicit data, and the OS decides which saved state continues.

5.7 Key ideas

  • A trap is a transfer of control into the OS that the CPU performs itself; exceptions come from the current instruction, interrupts from independent events, and both enter at mtvec.
  • On a trap the CPU records where in mepc (the trap pc) and why in mcause, turns interrupts off and jumps to mtvec; mret continues at mepc and restores the previous interrupt state, which our return path sets to “enabled”. Only mret sets the pc from mepc.
  • The trap frame replaces struct context: 31 integer registers plus the continuation address, because a trap is not a call and the calling convention gives no guarantee.
  • The trap path and the return path in trap.S replace context_switch(); the trap path, not the CPU, switches to the OS stack, and only after everything is saved.
  • A system call is a request made with ecall; the handler adds 4 to the saved pc to obtain the continuation address.
  • trap_handler() reads mcause and returns the frame that runs next: the same one resumes, another one schedules.
  • main() is only the OS’s start-up; afterwards the OS is entered only at trap_entry, and nothing of the OS is suspended while a process runs.
  • Our system runs entirely in machine mode; the trap mechanism is a deliberately restricted teaching model.

References