---
title: Privilege modes and system calls
heading: Why a program can't touch the hardware directly, and the instruction it uses to ask the kernel instead
eyebrow: C8 · Lesson 26 · Privilege modes and system calls
xp: 40
---

::: hook
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.
:::

::: play
- 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.
:::

```sim cpu
    la   t0, trap
    csrw mtvec, t0        # the kernel's entry point
    li   a7, 1            # request 1: print a character
    li   a0, 72           # 'H'
    ecall
    li   a0, 105          # 'i'
    ecall
    li   a7, 2            # request 2: how many characters so far?
    ecall
    ebreak
trap:
    csrr t0, mcause
    li   t1, 11
    bne  t0, t1, fail     # only ecalls are handled here
    li   t1, 1
    bne  a7, t1, count
    li   t0, 0x20000
    sw   a0, 16(t0)       # write the character to OUT
    addi s0, s0, 1
    j    back
count:
    mv   a0, s0           # return value in a0
back:
    csrr t0, mepc
    addi t0, t0, 4        # resume after the ecall
    csrw mepc, t0
    mret
fail:
    ebreak
show: a0, a7, s0
csrs: mepc, mcause, mtvec
out: on
speed: 4
```

::: 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?

- [ ] 0.25 ms
- [x] About 0.26 s
- [ ] About 2.6 s
- [ ] 26 µs

::: reveal
About 0.26 s: $1\,048\,576 \times 500$ = 524 million cycles, 0.26 s at 2 GHz. With a 4 KB buffer, the program makes only 256 calls, 64 µs of overhead. That's why C's `fwrite` and `printf` buffer their output and call the kernel only when the buffer fills.
:::
:::

::: nameit
## 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.
:::

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

::: 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.
:::
:::

::: 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?

::: solution
1. **Cycles per call.**
   $$31 + 31 + 40 = 102$$
2. **Cycles per second.**
   $$20\,000 \times 102 = 2.04 \times 10^6$$
   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.
:::
:::

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

::: 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
given: v = 2147483651 | 2147483655 | 2147483659
answer: v - 2147483648*floor(v/2147483648)
tolerance: 0.5%

## `mcause` reads {v:hex8}, an interrupt. What is its cause code, with the interrupt bit removed?

::: right
Right: {answer}. The top bit says whether it's an interrupt; the low bits say which.
:::

::: misses
- [v] Remove the interrupt bit (bit 31) first.
- [any] Not yet. Keep the low 31 bits.
:::
:::

::: check
given: B = 0.1 | 1 | 10; c = 300 | 500 | 1000; f = 1 | 2 | 3; k = 1 | 4 | 64
answer: B*2^20/(k*1024)*c/(f*1e9)*1e3
unit: ms
tolerance: 0.5%

## A program writes {B} MB in chunks of {k} KB, one system call per chunk. Each call costs {c} cycles of overhead on a {f} GHz processor. How much time is overhead?

::: right
Right. $(B \cdot 2^{20}/(k \cdot 1024)) \times c/f$ = {answer}.
:::

::: misses
- [B*2^20*c/(f*1e9)*1e3] That's one call per byte. There's one call per {k} KB chunk.
- [any] Not yet. Count the calls, then multiply by the cycles per call.
:::
:::

::: check
given: r = 31 | 15; w = 4 | 8; e = 20 | 40 | 80
answer: 2*r + e
tolerance: 0.5%

## A trap handler saves and restores {r} registers of {w} bytes, one memory instruction each, plus {e} cycles of other work. How many cycles does a trap cost at one cycle per memory instruction?

::: right
Right. $2r + e$ = {answer}; the register width changes the bytes moved, not the instruction count.
:::

::: misses
- [r + e] Each register is both saved and restored.
- [2*r*w + e] One instruction moves a whole register, whatever its width.
- [any] Not yet. $r$ stores, $r$ loads, plus the rest.
:::
:::

::: check
given: n = 1000 | 20000 | 100000; c = 102 | 250; f = 50 | 100 | 400
answer: n*c/(f*1e6)*100
tolerance: 0.5%

## A task makes {n} system calls a second, each costing {c} cycles of overhead, on a {f} MHz processor. What percentage of the processor does that use?

::: right
Right. $nc/f$ = {answer}%.
:::

::: misses
- [n*c/(f*1e6)] Give a percentage.
- [any] Not yet. Overhead cycles per second over clock cycles per second.
:::
:::

::: check
kind: asm
given: v = 1..1000 int
setup: a0 = v
expect: a0 = 2*v

## 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`.

```asm starter
    la t0, trap
    csrw mtvec, t0
    ecall
    ebreak
trap:
    # your code: double a0, then resume after the ecall
    mret
```

```asm solution
    la t0, trap
    csrw mtvec, t0
    ecall
    ebreak
trap:
    add a0, a0, a0
    csrr t0, mepc
    addi t0, t0, 4
    csrw mepc, t0
    mret
```

::: right
Right. Without advancing `mepc`, `mret` would return to the `ecall` and trap again forever.
:::
:::

::: check
kind: choice

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

- [x] So that one mechanism serves all exceptions: for a fault like a page miss, the handler fixes the cause and re-executes the same instruction
- [ ] Because the processor hasn't fetched the next instruction yet
- [ ] So user programs can't skip instructions
- [ ] It's an error in the RISC-V specification

::: right
Right. A page fault or misaligned access should be retried after the kernel fixes it, so the trap records the faulting instruction. For `ecall`, where retrying would loop, the handler adds 4.
:::

::: misses
- [2] The next address is known; the choice is deliberate.
- [3] It has nothing to do with skipping; the handler decides where to resume.
- [4] It's deliberate, and the same as on most architectures.
:::
:::

::: check
kind: python
given: n = 1000 | 50000; seed = 1 | 2

## Model buffered output. A program emits `n` = {n} 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 starter
import random
rng = random.Random(seed)
lengths = [rng.randrange(10, 200) for _ in range(n)]
u = b4k = len(lengths)
ratio = 1.0
```

```python solution
import random
rng = random.Random(seed)
lengths = [rng.randrange(10, 200) for _ in range(n)]
def calls_unbuffered(ls):
    return len(ls)
def calls_buffered(ls, B):
    calls, used = 0, 0
    for L in ls:
        if L > B:
            if used: calls += 1; used = 0
            calls += 1
            continue
        if used + L > B:
            calls += 1; used = 0
        used += L
    return calls + (1 if used else 0)
u = calls_unbuffered(lengths)
b4k = calls_buffered(lengths, 4096)
ratio = u / b4k
```

```python tests
import random
rng = random.Random(seed)
ls = [rng.randrange(10, 200) for _ in range(n)]
def ref(ls, B):
    c, used = 0, 0
    for L in ls:
        if L > B:
            if used: c += 1; used = 0
            c += 1; continue
        if used + L > B: c += 1; used = 0
        used += L
    return c + (1 if used else 0)
assert u == n, "Unbuffered, each message is one call."
assert b4k == ref(ls, 4096), f"With a 4096-byte buffer there should be {ref(ls, 4096)} calls."
assert calls_buffered([5000, 10, 10], 4096) == 2, "A message larger than the buffer gets its own call."
assert abs(ratio - u / b4k) < 1e-12 and ratio > 20, "Buffering should cut the calls by a large factor."
```

::: right
Right. Messages averaging about 105 bytes pack about 39 to a 4 KB buffer, so buffering cuts the system calls by that factor, and the overhead with them.
:::
:::

::: explain
## 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.

::: model
With privilege modes, the printer's registers are mapped into memory that only supervisor or machine mode may access, enforced by the memory-protection hardware. A user program that tries to write them directly takes an access fault and traps to the kernel, which can stop it. The only way to print is to execute `ecall` with a request number and a pointer to the data. That trap enters the kernel at a fixed address chosen by the kernel, at higher privilege; the kernel checks that the pointer refers to the caller's own memory, queues the job, and drives the printer itself, one job at a time. Without privilege modes, any program could write the registers in the middle of another's job, and nothing could stop a buggy program from hanging the device; with them, the kernel's checks are unavoidable.
:::
:::

::: practice

::: check
given: v = 2147483649 | 2147483651 | 2147483653 | 2147483655 | 2147483657 | 2147483659
answer: v - 2147483648*floor(v/2147483648)
tolerance: 0.5%

## What cause code is in `mcause` = {v:hex8}?

::: misses
- [v] Clear the interrupt bit first.
- [any] The low 31 bits.
:::
:::

::: check
given: n = 1000 | 8000; c = 200 | 600; f = 1 | 3
answer: n*c/(f*1e9)*1e6
unit: µs
tolerance: 0.5%

## How long do {n} system calls of {c} cycles take on a {f} GHz processor, in µs?

::: misses
- [n/(f*1e9)*1e6] Each call costs {c} cycles.
- [any] $nc/f$.
:::
:::
:::
