C826 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

C8 · Lesson 26 · Privilege modes and system calls

Why a program can't touch the hardware directly, and the instruction it uses to ask the kernel instead

In lesson 25 an interrupt pulled the processor into a handler. The same mechanism, run deliberately, is how every program on a phone or a laptop talks to the operating system. Ordinary code runs in a restricted user mode: it can't disable interrupts, reprogram the timer or touch another program's memory. To print, open a file or send a packet, it puts a request number in a register and executes ecall, which traps into the kernel at a higher privilege, where the request is checked and carried out. That boundary is what keeps one buggy or malicious program from taking down the machine, and crossing it costs hundreds of cycles, which shapes how I/O libraries are written.

  • A program makes two "print" system calls and one "count" call. Each ecall jumps to the handler at mtvec, which reads mcause (11: an ecall from machine mode), looks at the request number in a7, does the work, moves mepc past the ecall, and returns with mret.
  • Watch mepc: it holds the address of the ecall itself, so without the addi the program would trap again forever.

Predict

A program writes a 1 MB file one byte at a time with a system call per byte. Each call costs about 500 cycles beyond the copying itself, on a 2 GHz processor. How long does the system-call overhead alone take?

Name it

Privilege levels

RISC-V defines three levels: machine (M, the firmware, with access to everything), supervisor (S, the operating-system kernel) and user (U, applications). Small microcontrollers may have only M, or M and U. Each level can reach only the control registers and memory its level allows; an attempt to do more is an illegal-instruction or access-fault exception, which traps to a higher level. Physical memory protection (PMP) registers let machine mode fence off memory regions from lower levels.

Traps

An interrupt or exception, or an ecall, transfers control to the handler at mtvec (or stvec in supervisor mode) and records:

  • mepc: the address of the instruction that trapped (for ecall, the ecall itself);
  • mcause: why. The top bit is 1 for an interrupt; the rest is a code. Exceptions include 2 (illegal instruction), 5 (load access fault), 8 (ecall from U), 9 (ecall from S) and 11 (ecall from M). Interrupts include 3 (software), 7 (timer) and 11 (external);
  • the previous privilege level, in mstatus.

mret returns to mepc at the previous level. For an ecall, the handler first adds 4 to mepc so the program resumes after it.

System calls

By convention, the request number goes in a7, arguments in a0 to a5, and the result comes back in a0. On Linux for RISC-V, write is 64 and exit is 93. The kernel checks every argument, since a user pointer might point at kernel memory, before acting.

The cost

A system call saves the user's registers (31 integer registers, 124 bytes on RV32, more with floating point), switches stacks, dispatches, does the work, restores and returns. Modern processors also flush or tag internal state for security. A few hundred cycles for the simplest call is typical; I/O libraries amortize it by buffering.

Worked example

Decode these mcause values: 0x80000007, 0x0000000B, 0x00000002, 0x00000008.

Show the solution
  1. 0x80000007. The top bit is set, so it's an interrupt; code 7 is the machine timer.
  2. 0x0000000B. An exception, code 11, an ecall from machine mode.
  3. 0x00000002. An illegal instruction.
  4. 0x00000008. An ecall from user mode, the ordinary system call of an application.
  5. In the handler. The handler's first job is this decoding, usually with a jump table indexed by the code.

Answer a machine timer interrupt, an ecall from machine mode, an illegal instruction, and an ecall from user mode.

Worked example

A kernel's trap entry saves all 31 integer registers and later restores them, at one cycle per store or load, plus 40 cycles of other entry and exit work. A logging task makes 20 000 system calls per second on a 100 MHz microcontroller. What fraction of the processor goes to trap overhead?

Show the solution
  1. Cycles per call. 31+31+40=102
  2. Cycles per second. 20000×102=2.04×106 which is 2.0% of 100 MHz.
  3. Batching. Batching the log into 512-byte blocks of about 50 messages would cut the calls to 400 per second and the overhead to 0.04%.

Answer 2.0% of the processor goes to trap overhead.

Worked example

A user program tries csrw mie, zero to turn off interrupts. What happens, and why is that the right design?

Show the solution
  1. What happens. mie is a machine-level register, so from user mode the instruction is illegal: it traps with mcause = 2, and the kernel typically kills the program.
  2. Why user code mustn't do it. If user code could disable interrupts, a single loop with interrupts off would freeze the scheduler, the network stack and the watchdog's servicing.
  3. What the check guarantees. The privilege check makes "the kernel always gets control back" a hardware guarantee instead of a convention.

Answer the instruction traps as illegal (mcause = 2) and the kernel typically kills the program, which guarantees in hardware that the kernel always gets control back.

Check

mcause reads 80000007, an interrupt. What is its cause code, with the interrupt bit removed?

Check

A program writes 1 MB in chunks of 64 KB, one system call per chunk. Each call costs 300 cycles of overhead on a 3 GHz processor. How much time is overhead?

Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.

Check

A trap handler saves and restores 31 registers of 4 bytes, one memory instruction each, plus 80 cycles of other work. How many cycles does a trap cost at one cycle per memory instruction?

Check

A task makes 20000 system calls a second, each costing 102 cycles of overhead, on a 400 MHz processor. What percentage of the processor does that use?

Check

The starter installs a trap handler and makes a system call. Complete the handler so that it doubles a0 and returns to the instruction after the ecall.

RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.

Check

Why does an ecall trap leave mepc pointing at the ecall itself rather than the next instruction?

Check

Model buffered output. A program emits n = 1000 messages whose lengths are rng.randrange(10, 200) bytes (rng = random.Random(seed)). Write calls_unbuffered(lengths) (one system call per message) and calls_buffered(lengths, B): copy messages into a buffer of B bytes and make one call each time the next message wouldn't fit (and one at the end if anything is left); a message longer than B gets its own call. Set u, b4k (with B = 4096) and ratio = u / b4k.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Explain why

Explain how privilege modes and the ecall instruction together let an operating system share a printer between programs safely, when a program could simply write to the printer's registers itself on a microcontroller without them.

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.