6  Timer and Preemption

Winter Semester 2026/2027

Author
Affiliation

Stavros Kousidis

ICCT

Lecture 5 gave the OS a way in: the trap. Every trap in Lecture 5 was caused by the process, either on purpose with an ecall or by mistake with a faulty instruction. A process that never yields still keeps the CPU. This chapter answers the second half of the problem: how does the OS get control back without the process’s cooperation? The answer is an event that no process can prevent, the passing of time, delivered as a timer interrupt through the same trap path.

We keep the Exercise 4 port. The only process is now a spinner() that counts, prints and exits, and never yields. There is still one process; the handler still returns the same frame. Everything of Lecture 5 stays, and only the source of the event changes.

6.1 Where we stand

6.1.1 The lifetime through the CPU, recalled

Lecture 5 drew the lifetime of a process with the CPU as a box between the OS and the process:

         OS                 CPU                   Process
                        +--------+
start-up | os_run()     |        |
         +------------->| return |------------->| (start)
                        |        |              | ecall
         |<-------------|  trap  |<-------------+
 handler | pc += 4      |        |
         +------------->| return |------------->| (resume)

The OS prepares a frame and returns into it; the process runs; the CPU traps at the ecall; the handler adds 4 to the saved pc and returns the same frame. Nothing of the OS is suspended while the process runs. Both kinds of trap we have seen are synchronous: they happen at the same instruction in every run, and the process is their cause.

6.1.2 Why a never-yielding loop is still stuck

for (;;) { /* keep computing, never call */ }

Lecture 4 ended with this loop and Lecture 5 began with it. The trap path now exists, but nobody enters it: the loop executes no ecall and no faulty instruction, so the CPU never traps. Lecture 5 gave us the way in, not a reason to take it.

What the OS needs is an event that happens whatever the process does. A key press, a network packet or another device could interrupt the process, but none of them is guaranteed to happen. Time passes in any case. That is the event this course uses.

6.1.3 Two halves of the answer

Lecture 5 split the answer to the never-yielding process into two halves:

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

Lecture 5 promised that the second half reuses the identical entry path. This chapter keeps that promise. Three things are new: a device that keeps time and raises an interrupt request at a set time, the conditions under which the CPU accepts that request, and the two places where the trap path behaves differently for an interrupt. Today’s trap is asynchronous and non-cooperative at once: the process neither causes it nor intends it.

Keep the distinction from Lecture 4 in view. Interrupt handling is how the OS gets control; the scheduling decision is what it does with it. With one process the decision is trivial. Whether it must stay trivial is the question this chapter leaves for Lecture 7.

6.2 Time as an event: the platform timer

6.2.1 A device you have used since Exercise 1: the UART

Every program of this course has printed through the UART, the serial device of our machine. Lecture 2 left its code aside; the timer works the same way, so we look at it now. The starter main.c of Exercise 1 contained:

#define UART0_BASE 0x10000000UL
#define UART_THR    0
#define UART_LSR    5
#define UART_LSR_THRE 0x20

static volatile uint8_t *const uart0 = (volatile uint8_t *)UART0_BASE;

static void uart_putc(char c)
{
    while ((uart0[UART_LSR] & UART_LSR_THRE) == 0) {
    }

    uart0[UART_THR] = (uint8_t)c;
}

uart0 is a pointer to the first of the UART’s byte-wide registers, at address 0x10000000. The store uart0[UART_THR] = (uint8_t)c writes one byte to 0x10000000. No memory cell receives it: the UART takes the byte and sends it to the terminal. The load uart0[UART_LSR] reads one byte from 0x10000005, the UART’s line status register; its bit 0x20 says that the UART is ready to accept the next character. The loop asks the device again and again until it is ready. This is called polling.

So an address does not have to lead to RAM. A device register that has an address, and is read and written with ordinary loads and stores, is called memory-mapped. Since Exercise 4, uart_putc() lives in the shared uart.c, with the same code.

6.2.2 The timer is a platform device

Lecture 5 separated the CPU from the platform, the machine around it. The CPU provides CSRs, instructions and the trap rule; the platform provides memory and devices, and decides which address leads where. For our command line (-machine virt -m 128M), QEMU’s virt machine routes loads and stores as follows:

address range            what answers   role
0x02000000 - 0x0200ffff  CLINT          keeps time (this chapter)
0x10000000 - 0x100000ff  UART           serial output
0x80000000 - 0x87ffffff  RAM            program and data

RAM starts at 0x80000000, the ORIGIN of the linker script from Lecture 2, and -m 128M makes it 128 MiB long (0x8000000 bytes). The UART’s 0x10000000 is therefore not inside RAM: it lies far below RAM’s start, and a load or store there reaches the UART. The other ranges of the address space hold further virt devices that our system does not use, or nothing at all. The CSRs of Lecture 5 do not appear in the map: they have no address.

None of these devices is created by our code. -machine virt selects a board that QEMU emulates as a whole, with its devices at addresses fixed by QEMU’s model of that board; QEMU also describes them in the device tree it generates. A real chip has its devices built in the same way, at addresses its manual documents. Our code only uses the addresses: 0x10000000 in uart.c, and the CLINT’s addresses in riscv.h.

Lecture 4 named three parts of our target: CPU, RAM and UART. The timer is the fourth part we use. The CLINT (core-local interruptor) is the device of QEMU’s virt machine that keeps time and requests timer interrupts from the CPU. The CPU has no timer of its own that our OS programs; it reacts to the CLINT’s request as it would to any interrupt source. Newer RISC-V documents describe the same registers under the name ACLINT; QEMU and our code use CLINT. The addresses are those of QEMU’s virt machine. Real boards place their devices elsewhere, which is why the platform, not the ISA, defines them.

The roles are split. The device decides when to request an interrupt; the CPU decides when to take it.

6.2.3 mtime and mtimecmp

The CLINT has two registers that matter for us:

Register Address Holds
mtime 0x0200bff8 the current time: counts up at 10 MHz
mtimecmp 0x02004000 the time of the next timer interrupt

mtime counts up from 0 at machine start, on QEMU virt at 10 MHz: 10,000,000 counts per second, one count every 100 ns, 10,000 counts per millisecond, whatever the CPU executes. The device counts, not the OS: no instruction of our system increments mtime. It never stops; machine mode could write it, but our OS never does. mtimecmp holds a point in time, not a duration. The CLINT compares the two continuously: when mtime >= mtimecmp, the CLINT requests a timer interrupt. Both registers are 64 bits wide. As an unsigned 64-bit counter at 10 MHz, mtime would reach its largest value 264 − 1 only after about 58,000 years and then wrap to 0, so overflow plays no role.

Each hart has its own mtimecmp; all harts share one mtime. A hart (hardware thread) is the RISC-V word for one CPU that executes instructions. Our machine has one hart, so we use the mtimecmp of hart 0.

Both registers are memory-mapped, like the UART’s: an ordinary load or store to their address reads or writes the device instead of memory. The CSRs of Lecture 5 are different: they have no address and are reached only through the csr… instructions. Both are hardware state, reached in two different ways.

6.2.4 Reading and writing a device register in C

The provided riscv.h turns the two addresses into pointers:

#define CLINT_MTIMECMP0 ((volatile uint64_t *)0x02004000UL)
#define CLINT_MTIME     ((volatile uint64_t *)0x0200bff8UL)
#define TIMER_HZ        10000000UL

static inline void timer_arm(uint64_t delta)
{
    *CLINT_MTIMECMP0 = *CLINT_MTIME + delta;
}

Read the declarations from the inside out:

  • 0x02004000UL is only a number, an unsigned long constant (suffix UL).
  • The cast (volatile uint64_t *) turns that number into a pointer: the address of a 64-bit unsigned value. Nothing is read yet.
  • #define gives the pointer expression a name. The preprocessor pastes it into the code wherever the name appears; it is not a variable and occupies no memory.
  • *CLINT_MTIME dereferences the pointer: a 64-bit load from 0x0200bff8, which the CLINT answers with the current time.
  • *CLINT_MTIMECMP0 = … on the left of an assignment is a 64-bit store to 0x02004000.
  • static inline in a header gives every .c file that includes riscv.h its own copy of timer_arm(), which the compiler may place directly at the call. There is no link conflict, and no call needs to happen.

The one line in timer_arm() is therefore a load from mtime, an addition, and a store to mtimecmp: it requests the next timer interrupt delta counts from now. It is the same pattern as uart0[UART_THR] = c in the UART code, with a 64-bit value instead of a byte. Our build (GCC 13.2, -O2) translates timer_arm(100000) into exactly these three steps; lui builds the addresses like any other constant:

lui  a4,0x200c       # a4 = 0x0200c000
ld   a5,-8(a4)       # load mtime from 0x0200bff8
lui  a3,0x18
addi a3,a3,1696      # a3 = 0x186a0 = 100000
add  a5,a5,a3        # mtime + delta
lui  a4,0x2004       # a4 = 0x02004000
sd   a5,0(a4)        # store to mtimecmp

Two details of the declaration matter. uint64_t, from stdint.h, says the width exactly: the register is 64 bits by definition, so the code says so, although unsigned long is also 64 bits under our lp64 ABI. volatile tells the compiler that every access has an effect outside the program. Without it, the compiler may assume that memory changes only when the program writes it; it could load mtime once and reuse the value, or drop a store to mtimecmp that is never read back. Both are correct optimisations for RAM, of the kind Lecture 4 met with -O2, which keeps values in registers, and wrong for a device. With volatile, every access really happens, in the order written. It does not make an access atomic and has nothing to do with disabling interrupts.

The parameter of timer_arm() counts mtime units. It is called delta, and the word “tick” is kept for something else later in this chapter.

6.2.5 The time slice

A time slice is how long the OS lets a process run until the next timer interrupt. Other books call it a quantum. Our OS uses 10 ms. mtime counts at TIMER_HZ = 10,000,000 counts per second, so 10 ms are 10,000,000 / 100 = 100,000 counts. The reference names this value in its kernel.c:

/* Time slice: 10 ms at the 10 MHz CLINT timebase, in mtime counts. */
#define TIME_SLICE (TIMER_HZ / 100)

timer_arm(TIME_SLICE) therefore writes mtime + 100000 into mtimecmp. Because mtimecmp is a point in time, the OS adds the time slice to the current value of mtime. 10 ms is a common order of magnitude for real systems as well; nothing in our mechanism depends on the exact value.

6.2.6 Pending: a request, not yet a trap

Take mtimecmp = 100000 as an example:

mtime       99998   99999   100000   100001   100002 ...
pending       no      no      yes      yes      yes  ...

A timer interrupt is pending while mtime >= mtimecmp: the device has requested it, and the request has not been withdrawn. Pending is a level, not a single pulse. mtime keeps counting, so the condition stays true until software writes a larger mtimecmp. Nothing clears it by itself, and taking the interrupt does not clear it either. This has a consequence for the handler, which the section on the timer branch draws.

Three words stay apart from here on. An interrupt is pending when the device requests it, enabled when the CPU’s enable bits allow it, and taken when the CPU applies the trap rule. Whether a pending interrupt is taken is decided by the CPU, as the next section shows.

6.3 Letting the interrupt in

6.3.1 Three conditions for taking a timer interrupt

Lecture 5 said that a timer interrupt is taken only if it is pending and two enable bits are set, and that Lecture 6 shows where “pending” is recorded. All three conditions live in CSRs:

Condition Recorded in Set by
pending mip.MTIP (bit 7) the CLINT, while mtime >= mtimecmp
timer switch on mie.MTIE (bit 7) the OS: csr_set(mie, MIE_MTIE)
global switch on mstatus.MIE (bit 3) the CPU’s rules: trap and mret

mip (machine interrupt pending) and mie (machine interrupt enable) are CSRs with one bit per interrupt source. The bit for the machine timer is bit 7 in both: MTIP (machine timer interrupt pending) in mip, MTIE (machine timer interrupt enable) in mie.

  • Pending is recorded in mip.MTIP. The OS does not write it. The CLINT’s request sets it, and it clears when mtimecmp is moved beyond mtime. We need mip only as the place where pending is recorded.
  • Timer switch: mie.MTIE, “enabled for the timer”. The OS sets it once, during start-up; MIE_MTIE is the mask 1 << 7 from riscv.h, and csr_set() is the csrs instruction of Lecture 5.
  • Global switch: mstatus.MIE from Lecture 5, “enabled globally”. Our OS does not write it directly. The CPU’s trap rule clears it, and mret restores it from MPIE, which the return path sets before every mret.

When all three hold, the CPU takes the interrupt before the next instruction: it applies the trap rule of Lecture 5 instead of executing that instruction. As a reminder, the rule has three steps:

record     mepc <- pc, mcause <- reason
off        mstatus: MPIE <- MIE, MIE <- 0
jump       pc <- mtvec

For an interrupt, the pc recorded in mepc is that of the instruction that has not executed yet. These rules are those for machine mode, the only mode in our system. The specification adds rules for other privilege modes and for several pending interrupts at once; neither occurs here.

6.3.2 Two switches in series: mie.MTIE and mstatus.MIE

The two enable bits are not equals. One belongs to the timer; the other stands above every interrupt source:

CLINT: mtime >= mtimecmp
   |   mip.MTIP = 1           pending
   v
[ mie.MTIE ]      timer switch    the OS sets it once
   |              (each source has its own bit in mie)
   v
[ mstatus.MIE ]   global switch   trap: 0, mret: 1
   |              (one bit for all sources)
   v
CPU applies the trap rule

The device requests, the request is recorded as pending, and it reaches the CPU only through both switches. Both must be on (1); neither is the pending bit. The timer switch mie.MTIE belongs to one source and stays as the OS set it. The global switch mstatus.MIE applies to all sources; the CPU itself turns it off on a trap and on again at mret. Logically the three conditions are simply combined with “and”; the hierarchy lies in the scope of the bits, one per source below one for all.

The names invite confusion. Lecture 5 introduced mstatus.MIE, bit 3 of mstatus, as “interrupts allowed (1) or not (0)”, and announced a second, similarly named CSR. The lower-case mie is that whole CSR, with one enable bit per interrupt source; the timer’s bit is MTIE, bit 7. The names come from the specification and cannot be changed, so we always write mie.MTIE or mstatus.MIE, never MIE alone.

mip and mie use the same bit position for the same source on purpose, so MTIP and MTIE are both bit 7. That MPIE in mstatus is also bit 7 is a coincidence.

6.3.3 Who sets which bit in our system

The OS does its part once, at start-up. Condensed from the reference os_run(), in the version of the Exercise 5 library:

void os_run(void)              /* start-up, once */
{
    csr_write(mtvec, (uintptr_t)trap_entry);
    timer_arm(TIME_SLICE);     /* first request in 10 ms */
    csr_set(mie, MIE_MTIE);    /* csrs: timer switch on */
    ...
    os_start(...);             /* mret: MIE <- MPIE = 1 */
}

csr_write(), csr_read() and csr_set() come from the provided riscv.h, as since Exercise 4: macros around the csrw, csrr and csrs instructions. csr_set() sets the given bits in a CSR and leaves the others unchanged. The dots stand for preparing the idle process’s frame, printing os: starting 1 process, and selecting the first process, as in Lecture 5. In the Exercise 4 library the two middle lines are missing.

While os_run() runs, the global switch mstatus.MIE is still 0 from reset. Nothing can be taken there, so the order of arming and enabling does not matter; what matters is that both happen before the first mret. That mret copies MPIE, which os_start set to 1, into mstatus.MIE. The first timer interrupt therefore arrives in the process, one time slice after os_run() armed the timer. The OS arms the timer and turns on the timer switch; mret turns on the global switch.

6.3.4 The global switch over time: the payoff of “interrupts off”

Lecture 5 taught the transition of the global switch mstatus.MIE on a trap and on mret exactly, and nothing in its output depended on it. The trap rule turns it off, mret turns it on again. Here is the payoff:

process runs   mstatus.MIE = 1         timer may interrupt
trap           MPIE <- MIE, MIE <- 0
OS runs        mstatus.MIE = 0         a request waits
mret           MIE <- MPIE, so 1       timer may interrupt

A timer interrupt can arrive between any two instructions. If it could arrive in trap_entry, a second trap would overwrite mepc and mcause before the first ones are saved. Because the trap rule clears mstatus.MIE, nothing interrupts the OS while it saves the process’s state. A timer interrupt that becomes pending while the OS runs stays pending in mip.MTIP and is taken right after mret, before the process executes its next instruction. It is delayed, not lost.

In our system the OS never runs with interrupts enabled. This is a property of our model, in which nested traps are outside the scope, not a rule for every OS.

6.3.5 What held in Exercise 4

The Exercise 4 library never wrote mtimecmp or mie. While the process ran, the three conditions stood as follows:

Condition In Exercise 4, while the process ran
mstatus.MIE 1: os_start sets MPIE before every mret
mie.MTIE 0: 0 at reset on QEMU, and never set
pending: mip.MTIP 1: set from reset on QEMU

The first row was already at work in Lecture 5. The second row alone kept the timer out: the timer switch was off. The third row is the surprise. The RISC-V specification fixes only mstatus.MIE = 0 at reset and leaves mie and the reset value of mtimecmp open; QEMU starts all three at 0. Then mtime >= mtimecmp holds from reset, and mip.MTIP stays set for the whole run. A small probe program in the reference, built for our platform, prints mtimecmp = 0x0 and mip = 0x80 at reset, mip = 0x0 after arming, and mip = 0x80 again after expiry.

So in Exercise 4, exactly one bit was missing. The natural answer “not pending, because nobody armed the timer” is wrong on QEMU, and it would be unsafe as a design rule: an OS must not rely on an unspecified reset value. Had the Exercise 4 library set mie.MTIE without arming the timer, the interrupt would have been taken right after the first mret, and again after every return, because nothing would ever have moved mtimecmp into the future. Arming first and turning on the timer switch second, both before the first mret, makes the first interrupt arrive exactly one time slice after start-up.

6.3.6 Interactive model: pending, enabled, taken

The model below steps through the three conditions count by count. Choose a scenario, among them the Exercise 4 library, a missing re-arm and a time slice that ends while the OS runs, change the values, and step back and forth. It is a model in small abstract counts, not output of our OS. It loads its Python runtime from the internet when it starts, which takes a few seconds.

Open the model in a full window

6.4 The same trap path, now asynchronous

6.4.1 The CPU takes the interrupt

When the three conditions hold, the CPU applies the trap rule of Lecture 5. Side by side with an ecall:

Step of the trap rule After ecall After a timer interrupt
record where: mepc the ecall itself the next instruction, not executed
record why: mcause 11 interrupt bit set, code 7
interrupts off MPIE <- MIE, MIE <- 0 the same
jump: pc <- mtvec trap_entry the same trap_entry

Only the first two rows differ, and only in the values recorded. The interrupt is taken between two instructions: the CPU has finished one instruction and, instead of executing the next one, applies the trap rule. That next instruction becomes the trap pc. trap_entry then saves all registers and the trap pc into the frame, exactly as after an ecall; it does not know which kind of trap it is saving, and it does not need to. Nothing is new in the CPU: the same rule, a different cause.

6.4.2 mcause: interrupt bit first

Lecture 5 introduced the layout of mcause: bit 63 is the interrupt bit, bits 62..0 hold the code. For the machine timer:

mcause = 0x8000000000000007
         bit 63 = 1: interrupt
         code   = 7: machine timer
mcause Interrupt bit Code Meaning
0xb 0 11 ecall from M-mode
0x7 0 7 store/AMO access fault
0x8000000000000007 1 7 machine timer interrupt

The code 7 alone is ambiguous. Exception 7 is a store or AMO (atomic memory operation) access fault, for example a store to an address where nothing is mapped. A handler that compared only the code would treat such a fault as a timer interrupt and resume the faulting instruction forever. The handler therefore tests the interrupt bit first. riscv.h provides the names: MCAUSE_INTERRUPT is 1UL << 63, MCAUSE_CODE(c) clears that bit, and IRQ_MACHINE_TIMER is 7.

6.4.3 The trap pc is the continuation address

Today’s test process is the spinner, the process of Exercise 5. It is the never-yielding loop of Lecture 4, made concrete: it counts to a million and never calls process_yield().

static void spinner(void)
{
    volatile unsigned long counter = 0;

    uart_puts("spinner: start\n");
    while (counter < 1000000) {
        ++counter;
    }
    /* prints "spinner: done, counter = ...", then exits */
}

The spinner has nothing to do with the timer mechanism itself. It is only a process that keeps the CPU busy, and its final counter lets us check afterwards that no increment was lost. Its loop, as compiled in our build (GCC 13.2), with our comments:

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

counter is a volatile unsigned long on the spinner’s stack at 8(sp), so every iteration loads it, increments it and stores it back. a4 holds the limit 999999, loaded once before the loop. The addresses are build-specific; a GCC 14.2 build, or your own main.c, places the loop elsewhere.

Suppose a timer interrupt is reported at 0x800002b6. The addi at that address has not executed yet: the CPU took the interrupt instead of executing it. Resuming at the trap pc executes it for the first time. After an interrupt, mepc already says where to continue: the trap pc is the continuation address, and the handler changes nothing.

Lecture 5 had the opposite case. After an ecall, mepc holds the ecall, which has executed, and the handler adds 4. Adding 4 after an interrupt would skip work that was never done. Our target has the C extension, so instructions are 2 or 4 bytes long. From 0x800002b6, + 4 lands on 0x800002ba: addi and sd are skipped, and one increment is lost silently. From 0x800002bc, + 4 skips the loop’s branch, and the loop ends early. From a 2-byte instruction followed by a 4-byte one, + 4 lands in the middle of an instruction, and the CPU decodes from there.

The registers of the interrupted loop survive the handler for the reason Lecture 5 gave: between the ld and the addi, the counter exists only in a5 and the limit only in a4, two caller-saved registers with no call in sight, and trap_entry saves all 31 registers before any C code runs. The Lecture 5 chapter uses this loop as its compiled example. The final line spinner: done, counter = 1000000, identical with and without timer interrupts, is the evidence in our run.

6.4.4 The timer branch of trap_handler()

The handler of Lecture 5 (“Inside trap_handler()”) gets one new branch at the top; everything below it is unchanged:

uintptr_t cause = csr_read(mcause);   /* the reason */
if (cause & MCAUSE_INTERRUPT) {                    /* new */
    if (MCAUSE_CODE(cause) == IRQ_MACHINE_TIMER) {
        report_tick(trapped->pc);   /* Exercise 5 only */
        timer_arm(TIME_SLICE);      /* re-arm */
        return reschedule();        /* same frame, no +4 */
    }
} else 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);

report_tick() and report_unexpected() are names used only here for brevity; in the reference both reports are inline code. report_tick() prints the line os: tick N at <pc> in process 1 and is compiled only into the Exercise 5 library; the reference also counts the interrupt there. In the reference, the ecall branch is the function handle_syscall(): it adds 4 and decides by a7 as above, with additional report lines. An interrupt with another code falls through to the unexpected-trap report, as every unknown cause did in Lecture 5.

The timer branch has three jobs:

  • Report, in the Exercise 5 library only: one line with the trap pc.
  • Re-arm: timer_arm(TIME_SLICE) moves mtimecmp one time slice into the future. This also withdraws the pending request, because mtime >= mtimecmp no longer holds.
  • Decide: reschedule() marks the current process READY and selects the next READY one. With one process, that is the same process, so the same frame is returned.

There is no pc += 4. The re-arm is not optional. Without it, mip.MTIP would still be set when the handler returns; mret sets mstatus.MIE to 1, mie.MTIE is 1, so all three conditions hold again, and the CPU traps before the spinner executes a single instruction. The OS would run and the process would not.

The parameter of trap_handler() is still called trapped. For the timer case, read it as “the process that was interrupted”.

6.4.5 The lifetime with a timer interrupt

The picture of Lecture 5, “The lifetime in detail”, changes in two places only:

              OS             CPU               Process
                          +--------+
os_run()     | arm, MTIE  |        |
os_start     +----------->| return |----------->| (start)
                          |        |            | loop ...
trap_entry   |<-----------|  trap  |<-----------+ timer
             | save frame |        |
trap_handler | re-arm     |        |
os_start     +----------->| return |----------->| (resume)

os_run() arms the timer and sets mie.MTIE, and the trap arrow starts at “timer” instead of an ecall. The process line has no ecall at all: the spinner just keeps computing, and the trap arrow leaves it between two instructions of its loop. From trap_entry until os_start restores it, the spinner’s state is in p.frame. The handler bar says “re-arm”, not “pc += 4”. The process never asked; the OS ran anyway and returned the same frame.

After the spinner exits, the idle process receives the timer interrupts, as Lecture 5 showed for the time after the last exit.

6.4.6 Interactive model: one trap, step by step

The model below follows one timer interrupt through the loop of our build, from the trap rule to mret: the registers a4 and a5, the counter in memory, mepc, mcause, mstatus.MIE and MPIE, and the frame. Choose the instruction before which the interrupt lands and the trap path: the correct one, a handler that adds 4, or a trap_entry that saves only the CP1 subset. The listing is that of our build; the execution is a model, not output of our OS. It loads its Python runtime from the internet when it starts, which takes a few seconds.

Open the model in a full window

6.5 Preemption

6.5.1 Losing the CPU without yielding

Preemption means that the OS takes the CPU away from a process that did not yield. In our system the only way this happens is the timer interrupt: the process neither causes nor intends the entry into the OS.

Cooperative (Lecture 5) Preemptive (Lecture 6)
who causes the entry the process: ecall the timer
when where the process chooses between any two instructions
a for (;;) loop keeps the CPU loses it every 10 ms

This answers the question of Lecture 4. The answer depends on nothing the process does: the OS arms the timer and turns on the timer switch before the first return, and the next time slice is armed in every timer branch. From now on, no process can keep the OS out for longer than one time slice. That last sentence holds for well-behaved processes only. Everything runs in machine mode, so a process could write mie or mtimecmp itself; privilege modes, which would prevent this, are outside our model.

Keep this axis apart from the one of Lecture 5. Cooperative versus non-cooperative asks whether the process intends the entry; synchronous versus asynchronous asks whether the current instruction causes it. A timer interrupt is non-cooperative and asynchronous; an illegal instruction is non-cooperative but synchronous.

6.5.2 Interrupt handling versus the scheduling decision

The timer gives the OS control. What the OS does with it is a separate step:

interrupt handling     CPU: trap rule         the OS gets control
                       trap_entry: save       the state becomes data
scheduling decision    trap_handler(): which frame to return?
return                 os_start, mret         that frame continues

The decision is one line of trap_handler(): return reschedule();. With one process it has one option, and the same frame continues. Preemption makes a decision possible; it does not make one. Lecture 7 asks whether the handler must return the same frame, and that question only makes sense now that the OS has control without the process’s help.

6.5.3 One line per tick

A tick is one timer interrupt of the OS. It is not one count of mtime, which is why the code uses delta and TIME_SLICE for mtime counts. The Exercise 5 library prints one line per tick taken in a process. Our spinner counts to 1,000,000 and exits with status 7; linked against the Exercise 5 library, it produced, in our build (GCC 13.2, QEMU 8.2):

os: starting 1 process
spinner: start
os: tick 1 at 0x800002b8 in process 1
os: tick 2 at 0x800002b8 in process 1
os: tick 3 at 0x800002b8 in process 1
os: tick 4 at 0x800002b6 in process 1
os: tick 5 at 0x800002b6 in process 1
os: tick 6 at 0x800002b6 in process 1
os: tick 7 at 0x800002b4 in process 1
os: tick 8 at 0x800002b4 in process 1
spinner: done, counter = 1000000
os: process 1 exited 7
os: all processes finished
os: 8 timer interrupts

The spinner: lines come from the process, the os: lines from the OS. All eight reported addresses lie in the loop shown above. The last line is the count of timer interrupts, printed when the last process has finished. Addresses and counts are those of our build; yours differ, the structure does not.

6.5.4 Can the process tell it was interrupted?

The same spinner, linked once against the Exercise 4 library and once against the Exercise 5 library:

Exercise 4 library               Exercise 5 library
spinner: start                   spinner: start
                                 os: tick 1 ... os: tick 8
spinner: done,                   spinner: done,
  counter = 1000000                counter = 1000000

The spinner’s own lines and its final counter are identical. The tick lines were printed by the OS between two instructions of the spinner; the spinner executed none of its own instructions meanwhile. After each tick, its registers, its memory and its next instruction are as they were before the interrupt.

The process cannot tell that it was interrupted, except that time has passed. It could find out only by measuring time, for example by reading mtime before and after its loop and noticing that more time passed than its own instructions need. This is the only trace preemption leaves, and it is why the trap path must be exact: any register it failed to restore would be a visible trace, and a wrong one.

6.5.5 Reproducible interrupts with -icount

Lecture 5 said that an interrupt happens between two instructions, at a place that varies from run to run. Real hardware behaves like that, and so does QEMU by default: its timer follows the time of the host, so the places where the spinner is interrupted change from run to run. That makes asynchronous behaviour hard to observe and impossible to predict exactly.

For the course we start QEMU with an additional flag:

qemu-system-riscv64 ... -icount shift=4,sleep=off

With -icount, QEMU’s virtual clock counts executed instructions instead of host time: each instruction advances virtual time by 24 ns = 16 ns. mtime then depends only on how many instructions ran, and two runs of the same binary are interrupted at the same instructions. A 10 ms time slice is 625,000 instructions; one mtime count of 100 ns is about 6 instructions. sleep=off is part of the flag on purpose: with plain shift=4, the QEMU version of our build environment still interrupted the same binary at different instructions from run to run. Without -icount, on a fast host, the spinner may even finish before the first timer interrupt.

-icount is our observation tool, not a property of real hardware. Nothing in the OS may depend on where an interrupt lands. The flag makes our observations reproducible; it does not make the system more correct.

6.5.6 Interactive model: preemption over time

The model below shows who runs over time when the spinner runs against the Exercise 4 and the Exercise 5 library. Change the time slice, the length of the loop and the OS time per tick, switch -icount off and run again, and step from tick to tick. It counts only the spinner’s loop and is not output of our OS. It loads its Python runtime from the internet when it starts, which takes a few seconds.

Open the model in a full window

6.6 What can go wrong

6.6.1 Ticks without progress

The following output comes from the reference OS with exactly one line of its timer path removed, run with the same spinner. It never reaches spinner: done:

os: starting 1 process
spinner: start
os: tick 1 at 0x800002b8 in process 1
os: tick 2 at 0x800002b8 in process 1
os: tick 3 at 0x800002b8 in process 1
...                      (tens of thousands of lines)

The re-arm is missing from the timer branch. mtimecmp stays in the past, so mip.MTIP stays set. After every mret all three conditions hold at once, and the CPU traps before the spinner executes its next instruction: the same trap pc every time, and no progress. The OS is busy, and the process starves.

The conditions table is the tool to find such a defect. Exercise 5 has you diagnose further broken timer paths with your own build.

6.6.2 Our trap model: who does what, with the timer

Lecture 5 summarised the trap model in a table. With the timer it gains one row at the top and changes in two cells:

Step Who What
request CLINT pending while mtime >= mtimecmp
trap CPU if enabled: mepc, mcause; interrupts off; pc <- mtvec
save trap_entry registers and trap pc into the frame; OS stack
decide trap_handler() timer: re-arm, return a frame
restore os_start registers and mepc from the frame
return CPU, mret pc <- mepc; MIE <- MPIE, interrupts on

The platform device requests, the CPU takes the interrupt if it is enabled, and the handler re-arms and returns a frame. Everything else is unchanged. For CP2, students write their own os_run() and trap_handler(): os_run() arms the timer and turns on the timer switch, and trap_handler() has the timer branch and, after Lecture 7, a scheduler.

The model stays as restricted as in Lecture 5: machine mode only, one trap entry through mtvec, no nested traps, since the OS always runs with mstatus.MIE = 0, and no privilege separation. Lecture 6 adds exactly one interrupt source, the machine timer of the CLINT. Outside the model: other interrupt sources and the interrupt controllers that collect them, vectored mtvec, timers for supervisor mode, and the protection that would keep a process from changing mie or mtimecmp.

6.7 Key ideas

  • The CLINT is a platform device: mtime counts at 10 MHz, mtimecmp holds the time of the next request, and both are memory-mapped registers reached through volatile pointers.
  • A timer interrupt is pending in mip.MTIP while mtime >= mtimecmp, until the OS writes a larger mtimecmp. It is taken only if the timer switch mie.MTIE and the global switch mstatus.MIE are also on; the OS sets mie.MTIE once, and the trap rule and mret switch mstatus.MIE.
  • Because a trap clears mstatus.MIE, a timer interrupt never interrupts the OS; one that becomes pending meanwhile is taken right after mret.
  • A timer interrupt enters through the same trap path as an ecall. mcause has the interrupt bit set and code 7, and the trap pc is the instruction not yet executed: it already is the continuation address, so the handler adds nothing.
  • The full trap frame of Lecture 5 is what makes this safe: at an interrupt, caller-saved registers hold live values and no calling convention protects them.
  • The timer branch of trap_handler() re-arms the timer and returns a frame. Without the re-arm, the interrupt stays pending and the process makes no progress.
  • Preemption: the OS gets the CPU back every time slice without a yield. It makes a scheduling decision possible; with one process, the decision is the same frame.
  • -icount makes the places of interrupts reproducible for observation; it is not a property of real hardware.

The OS now has control at every tick. Must it give the CPU back to the same process?

References