6. Time and the hart

The tick, from comparator to handler Five stages in order. The CLINT compares mtime with the hart's mtimecmp and sets mip.MTIP, which software cannot write. The hart, running in S with mie.MTIE set and mideleg bit 7 clear, takes the machine timer interrupt in M. The M shim reloads mtimecmp, which clears MTIP, sets mip.SSIP and executes mret. Back in S, sip.SSIP, sie.SSIE and sstatus.SIE are all set and mideleg bit 1 is set, so the hart takes the supervisor software interrupt with scause 1. The handler clears sip.SSIP, counts and prints the tick, and returns to the wfi loop. One tick, from the CLINT to the S-mode handler CLINT: mtime >= mtimecmp[0] mip.MTIP goes high; no CSR write lowers it, only the comparison at reset mtimecmp is 0, so MTIP is already high hart in S: trap into M, mcause 7 mie.MTIE set; mideleg bit 7 is 0; the mode is below M so mstatus.MIE is not consulted M shim: timer_claim_m mtimecmp = mtime + INTERVAL; MTIP falls mip.SSIP = 1, then mret to S hart in S: sip.SSIP, trap into S, scause 1 mideleg bit 1 shows SSIP in sip; sie.SSIE and sstatus.SIE are set the three gates of chapter 5 trapper: the tick clears sip.SSIP itself, counts, prints, and returns with sret to the wfi loop; the kernel never wrote a deadline

Why this layer exists

A guest never reads a clock the hypervisor does not own. The time register is a shadow of a counter that machine-mode software decides how to present, a guest’s deadline is a number the hypervisor stores and compares on its behalf, and the interrupt that fires when the deadline passes is one the guest did not ask the hardware for. Chapter 18 shows the instruction-level form for a guest, where time reads back as the real counter plus an offset the hypervisor sets. This chapter builds the same shape for a kernel, with the M-mode shim of chapter 3 playing the part the hypervisor will play: the deadline stays in M, in the timer device’s mtimecmp, the machine timer interrupt is not delegated, and S sees only a software interrupt that M injected. The privileged specification states the design in two sentences: “Lower privilege levels do not have their own timecmp registers. Instead, machine-mode software can implement any number of virtual timers on a hart by multiplexing the next timer interrupt into the mtimecmp register.”

Chapters 3 and 5 gave the rules for when an interrupt is taken, in M and in S. They did not say where the timer’s bits come from, what reading the clock is, what wfi promises, or what the other harts of a machine are doing while this one runs. The Mechanism derives each from the specifications, ties the board’s own behaviour to a captured run under labs/ch06/ex/, and ends with the harts ember does not use, because a hypervisor has to put them somewhere.

Mechanism

The CLINT: a counter, a comparator and a doorbell per hart

A timer interrupt needs a counter that advances at a known rate, a register that says when to interrupt, and a comparator wired to an interrupt line. The privileged specification asks the platform for the first two: “Platforms provide a real-time counter, exposed as a memory-mapped machine-mode read-write register, mtime. mtime must increment at constant frequency, and the platform must provide a mechanism for determining the period of an mtime tick”, and “a 64-bit memory-mapped machine-mode timer compare register (mtimecmp)”. The comparator is a sentence: “A machine timer interrupt becomes pending whenever mtime contains a value greater than or equal to mtimecmp, treating the values as unsigned integers. The interrupt remains posted until mtimecmp becomes greater than mtime (typically as a result of writing mtimecmp).” Both registers sit in a device rather than in the hart because one real-time clock is shared by every hart in the machine, and the specification gives that as its reason.

On QEMU virt the device is the CLINT, the core-local interruptor: the block that holds mtime and each hart’s mtimecmp and raises the timer and software interrupts. The board’s device tree describes it as clint@2000000, with compatible = "sifive,clint0", "riscv,clint0" and a 64 KiB register window at 0x02000000 (labs/ch06/ex/dtb.txt; chapter 2’s dtb.txt lists the same node). The register layout is the SiFive CLINT’s. The RISC-V ACLINT specification splits that layout into two devices and says so: “A SiFive CLINT device on a RISC-V platform can be logically seen as one MSWI device and one MTIMER devices placed next to each other in the memory address space”, the MSWI (machine-level software interrupts) in the first 0x4000 bytes and the MTIMER (the counter and the compare registers) in the next 0x8000. The revision cited here is 1.0-rc4, which marks itself a draft; QEMU’s model (hw/intc/riscv_aclint.c) names the ACLINT repository as its source.

The addresses follow from the two devices. The MSWI holds one 32-bit msip register per hart. The MTIMER holds one 64-bit mtimecmp per hart and one mtime for the device. The ACLINT gives mtime its own base address, and where a CLINT puts it is the board’s, so that offset comes from QEMU’s source (RISCV_ACLINT_DEFAULT_MTIME is 0x7ff8 and RISCV_ACLINT_SWI_SIZE is 0x4000 in include/hw/intc/riscv_aclint.h at v11.1.1, and hw/riscv/virt.c builds the CLINT from them): 0x4000 + 0x7ff8 is 0xbff8.

register width address hart 0 hart 1
msip 4 bytes 0x02000000 + 4 × hart 0x02000000 0x02000004
mtimecmp 8 bytes 0x02004000 + 8 × hart 0x02004000 0x02004008
mtime 8 bytes 0x0200bff8 0x0200bff8 0x0200bff8

The comparison feeds one bit of one CSR, and the bit has an owner. “Bits mip.MTIP and mie.MTIE are the interrupt-pending and interrupt-enable bits for machine timer interrupts. MTIP is read-only in the mip register, and is cleared by writing to the memory-mapped machine-mode timer compare register.” Neither S nor M can write it by CSR. It falls when the comparison changes, “typically as a result of writing mtimecmp”, and a write to mtime changes the comparison too. Chapter 3 defined mip and mie; the run mtimecmp-mip shows the bit from M, before the drop, with mie.MTIE still clear so that nothing is taken:

M: mtimecmp at reset 0x0
M: at reset: mip.MTIP=1
M: mtimecmp = all ones: mip.MTIP=0
M: after csrc mip,MTIP with mtimecmp = all ones: mip.MTIP=0
M: after csrs mip,MTIP with mtimecmp = all ones: mip.MTIP=0
M: mtimecmp = 0: mip.MTIP=1
M: after csrc mip,MTIP with mtimecmp = 0: mip.MTIP=1
M: mtimecmp = mtime as just read: mip.MTIP=1
M: mtimecmp = mtime + 10 million: mip.MTIP=0
M: mtimecmp = mtime - 1: mip.MTIP=1
M: mtime written to 0, mtimecmp untouched: mip.MTIP=0

The first two lines are the board’s reset state: mtimecmp is 0, so mtime is already at or past it and MTIP is pending before any software runs, which is the mip value 0x80 chapter 3 read. The ACLINT leaves that open (“On MTIMER device reset, the MTIMECMP registers are in unknown state”), so the 0 is the board’s. It is why timer_enable_m loads mtimecmp before the drop: with no load, the interrupt is pending when the mret reaches S (exercise (a)). The two mip writes confirm the sentence above: with mtimecmp at all ones, setting the bit does nothing, and with mtimecmp at 0, clearing it does nothing. The line “mtimecmp = mtime as just read” does not test the equality case of “greater than or equal to”: mtime has advanced by the time the compare happens, so the run shows only “at or after”. The specification’s sentence decides that case. The last line writes mtime to 0 and leaves mtimecmp alone, and MTIP falls: mtime is a writable machine register, and it is the comparison that MTIP follows.

Two further sentences bear on the code. The first is about timing: “If the result of the comparison between mtime and mtimecmp changes, it is guaranteed to be reflected in MTIP eventually, but not necessarily immediately”, with the consequence that “a spurious timer interrupt might occur if an interrupt handler increments mtimecmp then immediately returns, because MTIP might not yet have fallen in the interim.” The second is about width: “For RV64, naturally aligned 64-bit memory accesses to the mtime and mtimecmp registers are ... supported and are atomic.” ember stores mtimecmp with one aligned sd, so no intermediate value is ever visible. A 32-bit hart cannot; exercise (e) is the sequence the specification gives it.

The MSWI is the other half. “Each MSIP register is a 32-bit wide WARL register where the upper 31 bits are wired to zero. The least significant bit is reflected in MSIP of the mip CSR. A machine-level software interrupt for a HART is pending or cleared by writing 1 or 0 respectively to the corresponding MSIP register.” A hart writes another hart’s msip to ring its doorbell, which is how the specification says interprocessor interrupts are sent at M level (“MSIP is read-only in mip, and is written by accesses to memory-mapped control registers, which are used to provide machine-level interprocessor interrupts”). ember’s tick does not use it, because M injects the tick into its own hart by a CSR write. The last section does.

The timebase: ticks, not cycles

mtime counts ticks of a reference clock, and the specification requires only that “the platform must provide a mechanism for determining the period of an mtime tick”. On this board the mechanism is the device tree: the /cpus node carries timebase-frequency, and dtb.txt prints it both ways, as 0x989680 in dtc’s cells and as 10000000 from fdtget. Ten million ticks per second makes a tick 100 ns, and INTERVAL in time.c is 10000000, which is

107 ticks÷107 ticks/s=1 s.10^7 \text{ ticks} \div 10^7 \text{ ticks/s} = 1 \text{ s}.

ember does not parse the tree it was handed in a1; it assumes the number and says so in a comment. A kernel for another board would read the property.

A tick is not a CPU cycle. The cycle register counts “the number of clock cycles executed by the processor core on which the hart is running”, while time “counts wall-clock real time that has passed from an arbitrary start time in the past” (the Zicntr section of the unprivileged specification). The two are separate registers, though the specification notes that on simple platforms the cycle count may be a valid implementation of time; here time is mtime, and everything below is in mtime ticks. Every duration in this chapter is a tick count divided by the timebase, and none is measured against a wall clock.

Reading the clock: time and rdtime

mtime is in the device’s address space, so a load reads it. The register an instruction names is a CSR: “The time CSR is a read-only shadow of the memory-mapped mtime register.” rdtime is the pseudoinstruction for reading it, “mapped to the read-only csrrs rd, counter, x0 canonical form”, so rdtime t0 is csrrs t0, time, x0, which the patches write as csrr t0, time (objdump prints it as rdtime t0). The specification also leaves the implementation open in the direction a hypervisor wants: “Implementations can convert reads of the time and timeh CSRs into loads to the memory-mapped mtime register, or emulate this functionality on behalf of less-privileged modes in M-mode software.”

The emulation hook is a switch. “When the CY, TM, IR, or HPMn bit in the mcounteren register is clear, attempts to read the cycle, time, instret, or hpmcountern register while executing in S-mode or U-mode will cause an illegal-instruction exception.” TM is bit 1 and covers time; chapter 3’s s-cycle.txt shows the S-mode trap for cycle. U-mode has a second switch, scounteren (exercise (d)). Chapter 3’s reset-state.txt found mcounteren 0 at reset on this board, so S-mode rdtime traps until M sets TM. Two runs show it. In rdtime-denied the S-mode code reads time, then reads the stimecmp CSR of a later section, and the kernel’s trap handler is patched to print the cause and stval of each trap and skip the instruction:

S: csrr time
S: trap scause=0x2 stval=0xc01022f3
S: time not read
S: csrr stimecmp
S: trap scause=0x2 stval=0x14d022f3
S: stimecmp not read

stval for an illegal instruction is the instruction word (chapter 3), and the top twelve bits of a CSR instruction are the CSR number: 0xc01 is time. ember delegates illegal-instruction exceptions to S (chapter 5), so the trap lands in the kernel; a firmware that emulated time for its kernel would leave medeleg bit 2 clear and receive it. In rdtime-allowed the M code sets TM before the drop (csrw mcounteren, 2), and S reads time, then the memory-mapped mtime, then time again:

S: csrr time
S: time read
S: time <= mtime <= time: yes
S: csrr stimecmp
S: trap scause=0x2 stval=0x14d022f3
S: stimecmp not read

The first read succeeds, and the three reads are in order, as two views of one counter must be. The run shows consistency, not identity; the specification’s sentence allows a lag (“guaranteed to be reflected in time and timeh eventually, but not necessarily immediately”), which this board does not show. The stimecmp line still traps with TM set, for a reason the Sstc section gives.

A guest’s rdtime is the same instruction one level down. In the hypervisor specification, htimedelta “contains the delta between the value of the time CSR and the value returned in VS-mode or VU-mode”, so reading time in a guest “returns the sum of the contents of htimedelta and the actual value of time”. Chapter 18’s table of sensitive instructions has the row.

Which interrupt bits belong to time

Four bits of mip matter in this chapter, and they differ in who may write them. The mip and sip columns are the specification’s; the last is this board’s, from the delegation probe of chapter 3 (delegation-probe.txt: writing all ones to mideleg reads back 0x3666, bits 1, 2, 5, 6, 9, 10, 12 and 13).

bit name in mip in sip mideleg here
1 SSIP, supervisor software writable writable settable (chapter 5 sets it)
3 MSIP, machine software read-only; follows the msip register not shown stays 0
5 STIP, supervisor timer writable by M, unless stimecmp drives it read-only settable
7 MTIP, machine timer read-only; follows the mtime/mtimecmp comparison not shown stays 0

The specification’s words for each: “SSIP is writable in mip and may also be set to 1 by a platform-specific interrupt controller”, “If the stimecmp ... register is implemented, STIP is read-only in mip and reflects the supervisor-level timer interrupt signal resulting from stimecmp”, and, for S’s view, “If implemented, STIP is read-only in sip” and “SSIP is writable in sip”. The two machine-level bits are not delegable on this board. The specification leaves that to the platform and expects the answer: “Since most platforms will choose not to make these interrupts delegatable from M-mode to S-mode, they are shown as 0” in its figures of sip and sie. The 0 in the mideleg column is therefore a board fact, found by the probe and not by a rule. What the rules do give is the consequence. An M-level interrupt is taken when the three conditions of chapter 3’s rule hold: (a) the mode is M with MIE set, or is below M; (b) the bit is set in both mip and mie; (c) it is not delegated. With MTIE set and bit 7 not delegable, (b) and (c) hold, and (a) holds for free whenever the hart is in S or U. mstatus.MIE never matters for the tick because ember never sets it, and inside the shim, where the hart is in M with MIE cleared by the trap, a second timer interrupt waits. The S-level interrupt that M injects goes through chapter 5’s three gates: SSIP visible in sip because mideleg bit 1 is set, sie.SSIE, and sstatus.SIE while the hart is in S.

The table shows an asymmetry that decides the design. SSIP is writable in sip, so the S-mode handler can acknowledge its own interrupt with one CSR write. STIP is not, so an S-mode handler for a timer interrupt cannot make the bit fall. The run stip-inject makes M inject STIP instead of SSIP. On this board mip.STIP is writable from M, because menvcfg.STCE is 0 at reset (the Sstc section prints it) and the specification says that with STCE clear “STIP in mip and sip reverts to its defined behavior as if this extension is not implemented”. The patch delegates bit 5, has the S handler clear sip.STIP the way the tick handler clears SSIP, and prints the bit afterwards:

M: mip.STIP after csrs mip,STIP: 1
S: running
S: second map
S: trap sepc=probe scause=0x2 stval=0xf14022f3
S: STI 0x1: sip.STIP after csrc sip,STIP: 1
S: STI 0x2: sip.STIP after csrc sip,STIP: 1
S: STI 0x3: sip.STIP after csrc sip,STIP: 1

The interrupt is delivered with cause 5, the handler’s write is ignored, and the same interrupt is taken again. Only M can lower the bit. That is why the SBI has a timer call (see the miniature-SBI section), and why ember injects the software interrupt: S can finish the interrupt by itself.

wfi

wfi is the idle instruction. Its specification is a stall, a wake-up rule and a licence to cheat. The stall: it “informs the implementation that the current hart can be stalled until an interrupt might need servicing”. The wake-up: “If an enabled interrupt is present or later becomes present while the hart is stalled, the interrupt trap will be taken on the following instruction, i.e., execution resumes in the trap handler and mepc = pc + 4”, so that a simple return from the handler continues after the wfi. The licence: “Implementations are permitted to resume execution for any reason, even if an enabled interrupt has not become pending. Hence, a legal implementation is to simply implement the WFI instruction as a NOP.” A kernel therefore treats wfi as a hint and loops on a condition it checks itself, as the specification says: “software must explicitly check for any relevant pending but disabled interrupts in the code following an WFI, and should loop back to the WFI if no suitable interrupt was detected.” ember’s two loops, start.S’s and main’s, are the degenerate form: they loop unconditionally and leave the checking to the trap handler, the case the specification’s note covers (“the interrupt will be taken on some instruction in the idle loop containing the WFI, and on a simple return from the handler, the idle loop will resume execution”). park below is the form that checks. Chapter 2 glossed the instruction and this is its contract.

Which interrupts count is the part that matters here, and the specification separates two cases. “The operation of WFI must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation register mideleg (i.e., the hart must resume if a locally enabled interrupt becomes pending, even if it has been delegated to a less-privileged mode), but should honor the individual interrupt enables (e.g, MTIE) (i.e., implementations should avoid resuming the hart if the interrupt is pending but not individually enabled).” A pending interrupt that is individually enabled wakes the hart even with the global enable clear (a must); one that is not enabled should not (a should, which an implementation may break). Two runs show the board on each side. Both leave out timer_enable_m, so that no M-level timer interrupt can end the wait.

In wfi-enabled, S sets sie.SSIE and raises its own SSIP, and sstatus.SIE stays clear:

S: wfi with sip=0x2 sie=0x2 sstatus.SIE=0
S: wfi returned, no interrupt taken
S: tick 0x1
S: after setting sstatus.SIE

The wfi returns and no trap is taken, because the global gate is closed. The specification covers it: “If the event that causes the hart to resume execution does not cause an interrupt to be taken, execution will resume at pc + 4, and software must determine what action to take.” The pending interrupt is not lost. The csrs sstatus that opens the gate takes it before the next line prints, which is the evaluation rule chapter 5 quoted for writes to sstatus. In wfi-masked, the same code leaves sie clear:

S: wfi with sip=0x2 sie=0x0
qemu-system-riscv64: terminating on signal 15 from pid N (timeout)

The hart does not resume, and nothing else would wake it, so timeout ends the run after 30 s. This is the “should” honoured on this board. It is not a guarantee a kernel can rely on, and the loop above is why it does not have to.

A wfi can also be made to trap on purpose. “The TW (Timeout Wait) bit ... supports intercepting the WFI instruction. When TW=0, the WFI instruction may execute in modes less privileged than M when not prevented for some other reason. When TW=1, then if WFI is executed in any less-privileged mode, and it does not complete within an implementation-specific, bounded time limit, the WFI instruction causes an illegal-instruction exception.” The specification gives the use: “Trapping the WFI instruction can trigger a world switch to another guest OS, rather than wastefully idling in the current guest.” In wfi-tw, M sets mstatus.TW before the drop and S executes wfi with nothing pending and enabled:

S: wfi with mstatus.TW set
S: trap scause=0x2 stval=0x10500073
S: wfi done

The board traps, and the transcript cannot show how soon; the specification allows the limit to be zero (“An implementation may have WFI always raise an illegal-instruction exception in modes less privileged than M when TW=1, even if there are pending globally-disabled interrupts when the instruction is executed”). stval is the wfi instruction word, and the trap is taken in S because ember delegated cause 2. Chapter 18’s table has the version for a guest, where VTW in the hypervisor’s status register and TW combine.

The M shim as a miniature SBI

An S-mode kernel on a board with firmware does not touch mtimecmp. It asks. The SBI (chapter 2) is the specification of what S may ask of the firmware under it; chapter 2 named it and removed it, because -bios none deletes OpenSBI, the firmware that would answer. Its timer call is the part this chapter replaces. The calling convention: “An ECALL is used as the control transfer instruction between the supervisor and the SEE. a7 encodes the SBI extension ID (EID). a6 encodes the SBI function ID (FID) ... a0 through a5 contain the arguments”, and the answer comes back in a0 (an error code) and a1. The Timer extension has one function, EID 0x54494D45, FID 0:

struct sbiret sbi_set_timer(uint64_t stime_value)

“Programs the clock for next event after stime_value time. stime_value is in absolute time.” And the sentence that ties it to stip-inject: “This function must clear the pending timer interrupt bit when stime_value is set to some time in the future, regardless of whether timer interrupts are masked or not.” The kernel supplies a deadline in time units, the firmware programs the comparator, and the firmware clears STIP, which on a hart without Sstc the kernel cannot do (stip-inject). The kernel receives supervisor timer interrupts, cause 5.

ember turns each part around. The deadline is M’s: INTERVAL ticks after the last one, with no request from S. The comparator is mtimecmp, programmed by timer_reload. The kernel receives cause 1, the software interrupt, which it acknowledges itself. M-mode code with S-mode’s request removed is a timer driver with one client and no protocol, and it has the shape of the thing a hypervisor sits in: M owns the clock and decides what S sees of it. A hypervisor that answers sbi_set_timer for a guest is the same loop with the guest’s deadline kept in memory and multiplexed into mtimecmp, as the quotation at the top of the chapter says.

sstc, named and unused

The Sstc extension removes the firmware from this path. It adds a CSR, stimecmp, to S: “A supervisor timer interrupt becomes pending, as reflected in the STIP bit in the mip and sip registers whenever time contains a value greater than or equal to stimecmp”. S programs its own deadline in the same time units, STIP is a function of the comparison and not a bit anyone writes, and “the interrupt remains posted until stimecmp becomes greater than time, typically as a result of writing stimecmp”, which the S handler can do. Firmware that offers sbi_set_timer on such a hart “will simply make use of stimecmp, changing its value as appropriate.”

The board has it. dtb.txt lists sstc in the hart’s ISA extensions. It is off until M turns it on: “The STCE bit enables stimecmp for S-mode when set to one. When this extension is implemented and STCE in menvcfg is zero, an attempt to access stimecmp in a mode other than M-mode raises an illegal-instruction exception”. That is the stimecmp line in both runs above. TM in mcounteren is a second condition: “when the TM bit in the mcounteren register is clear, attempts to access the stimecmp or vstimecmp register while executing in a mode less privileged than M will cause an illegal-instruction exception.” The run stimecmp-enabled sets TM and STCE from M and prints what changed:

M: menvcfg at reset 0x2000000000000000
M: mip now 0xa0
M: menvcfg now 0xa000000000000000
S: running
S: second map
S: csrr time
S: time read
S: csrr stimecmp
S: stimecmp read: 0x0

menvcfg is 0x2000000000000000 at reset, bit 61 (the hardware-update bit for page-table flags that chapter 4 named) and not bit 63. Setting STCE makes mip read 0xa0 (it was 0x80, chapter 3’s reset-state.txt): MTIP, still pending from the unloaded mtimecmp, and STIP, now driven by the comparison of time with a stimecmp that resets to 0. S can read it, and reads 0. The book stops here. The tick of this chapter goes through M because the lesson is a path with M in it. A hypervisor that wants to steal time from a guest, or to show it a clock that does not match the board’s, needs that path; with Sstc a guest gets its own vstimecmp (hypervisor specification, 14.1.2.19), compared against time plus htimedelta, and the hypervisor no longer injects each tick.

One hart, and the others

Every hart in the machine leaves reset the same way (chapter 2): it starts at the reset ROM, which sets a0 to its hart ID and a1 to the device tree, and jumps to the start of DRAM. The specification numbers them: “one hart must have a hart ID of zero”. With -smp 2 the board has two. dtb.txt shows the second cpu@1, its own interrupt controller (identified by a phandle, the number other nodes use to refer to it: 2, where the first hart’s is 4), and the CLINT’s interrupts-extended grown from two (controller, cause) entries to four, two per hart, with causes 3 and 7, the machine software and machine timer interrupts. The same CLINT serves both: hart 1’s msip and mtimecmp are the second row of the register table.

ember is written for one. _start has no check on a0: every hart that enters it loads sp with the same stack_top, clears .bss and calls main. And main’s first act, in ch2_report, is to halt when a0 is not 0, which writes the finisher (chapter 2) and ends the machine, not the hart. The run smp2-unparked makes that visible. Its patch holds hart 0 in an endless loop at the top of ch2_report so that only hart 1 can speak, and has hart 1 print before it halts. The extra flag is in smp2-unparked.qemu, which labs/ex-run.sh adds to the QEMU command line:

ember: hart 0x1 reached main; halt(1)

That is the whole transcript. There is no terminating on signal line, as there is in wfi-masked, so QEMU ended itself: the second hart’s halt(1) took the machine down with hart 0 still spinning. (The unpatched image under -smp 2 has two effects, and the first is certain. Hart 1’s halt(1) ends the machine. Before it does, both harts’ frames sit on the one stack_top: halt saves its ra in the slot where hart 0’s own callees (uart_puts, puthex) keep theirs, so hart 0 can return through hart 1’s saved address and run its report again. The second effect depends on host timing, and this book keeps no count of it. The patch holds hart 0 to remove both effects.) A second hart that runs the first hart’s boot code is not a spare, it is a fault.

The fix has to happen before the first shared instruction: keep the hart out of the boot code. The SBI’s Hart State Management extension has a name for a hart that is not running the kernel, STOPPED, defined as “The hart is not executing in supervisor-mode or any lower privilege mode.” In smp2-parked the patch adds one instruction at the top of _start, bnez a0, park, and a loop at park that uses only registers (excerpt from labs/ch06/ex/smp2-parked.patch):

park:
    li      t0, 8                 /* mie.MSIE */
    csrw    mie, t0
1:  wfi
    csrr    t1, mip
    andi    t1, t1, 8             /* mip.MSIP */
    beqz    t1, 1b                /* wfi may return for any reason: look */
    ...                           /* print one line to the UART, then: */
    li      t2, 0x02000004        /* msip of hart 1: clear it */
    sw      zero, 0(t2)
    j       1b

The parked hart enables only the machine software interrupt, leaves mstatus.MIE alone, and waits. Hart 0, after its probe, has S-mode write 1 to 0x02000004 and spin until it reads 0. Hart 1’s wfi returns, the loop finds MSIP set, and hart 1 prints which state it saw and clears its own doorbell:

S: trap sepc=probe scause=0x2 stval=0xf14022f3
hart 1: wfi returned, mip.MSIP is set, mstatus.MIE is clear
S: tick 0x1

The run is the lab with the park added, followed to PASS (the full transcript is smp2-parked.txt), and it shows the three things the section claims. The wfi of a hart in M with MIE clear returned and took no trap, and the next instruction ran. That the hart really stalled is what wfi-masked shows; this transcript alone would also fit a wfi that does nothing, which is why park checks mip after it. The doorbell is a store to a register in the CLINT, from a hart in S, to another hart. And the second hart’s presence changed nothing hart 0 printed, in the order hart 0 prints it, because hart 0 waited for the clear. It is a variant of the lab, not the lab: the committed image has no park.

hearth will have the same problem. Under -bios none every hart enters at once, so whatever hearth later does with the extra harts, keeping them out of the boot code as smp2-parked does is the first step. What it then does with them is chapter 37’s design, and nothing in ember builds it.

Walkthrough

The CLINT’s addresses and the one constant are in the first lines of time.c:

#define CLINT      0x02000000UL
#define MTIMECMP   ((volatile unsigned long *)(CLINT + 0x4000))
#define MTIME      ((volatile unsigned long *)(CLINT + 0xbff8))
#define INTERVAL   10000000UL /* 1 Hz at QEMU virt 10 MHz */
#define MCAUSE_MTI 7UL

MTIMECMP and MTIME are pointers to volatile unsigned long, so each access is one 64-bit load or store of exactly the width the table gives, and the compiler may neither merge nor drop them. 0x4000 and 0xbff8 are the table’s offsets, hart 0’s mtimecmp and the shared mtime; a second hart would index MTIMECMP by its ID. INTERVAL is the timebase divided by 1 Hz. The comment in the source says 1 Hz; the arithmetic is the section above.

M arms the deadline before the drop and reloads it on every timer interrupt:

void timer_reload(void)
{
    *MTIMECMP = *MTIME + INTERVAL;
}

void timer_enable_m(void)
{
    timer_reload();
    csr_set(mie, 1UL << 7); /* MTIE. From S, mie is the gate; MIE is not. */
}

timer_reload stores mtime + INTERVAL. The deadline is relative to now, read after the trap has been taken, not to the previous deadline, so the spacing between ticks is INTERVAL plus the latency of the path (exercise (c) bounds it). Adding to the old mtimecmp would keep the cadence exact and, after a long stall, would leave mtimecmp in the past and fire the timer again at once for every missed interval. timer_enable_m reloads first and sets the enable second. Inside M the order is a habit: mstatus.MIE is 0, so nothing is taken until the mret (chapter 3’s mtie-set.txt shows cause 7 arriving at the mret when only mie.MTIE is set). What matters is that the deadline is loaded before the mret. Without the reload, the pending MTIP that mtimecmp = 0 leaves is taken as soon as the hart is in S; exercise (a) runs the case. The comment says what chapter 3 proved: from S, mie is the gate and MIE is not.

drop_to_s calls it in a fixed order:

void drop_to_s(void (*entry)(void))
{
    unsigned long s;

    pmp_open();
    csr_write(mtvec, (unsigned long)mshim_entry);
    /* Unconditional: mshim_entry swaps through mscratch on every M
     * trap. From ch 8 the timer can fire while U runs; for traps from
     * S (ch 3–7) the shim now runs on its own stack instead of the
     * kernel's, which nothing in those chapters observes. */
    csr_write(mscratch, (unsigned long)mshim_sp);
    timer_enable_m();
    s = csr_read(mstatus);
    s = (s & ~MSTATUS_MPP) | MSTATUS_MPP_S;
    csr_write(mstatus, s);
    csr_write(mepc, (unsigned long)entry);
    __asm__ volatile("mret");
}

mtvec, mscratch (the shim’s stack top) and the deadline all have to be in place before the mret, because an M timer interrupt can arrive from the first instruction in S; inside M, with mstatus.MIE clear, the order among them is not a constraint. Dropping with mtvec still at its reset value 0 would send the first interrupt to address 0, where nothing is mapped, and the hart would take instruction access faults there for ever, the trace chapter 2’s exercise (b) shows for a different reason. timer_enable_m precedes the mstatus and mepc writes and the mret, so by the time S runs its first instruction the deadline is already one second away. pmp_open has come first (chapter 3), because without it S could not fetch.

S-mode’s side is two CSR writes and a loop:

mem_init();
trap_init();
/* The probe. Its address is what the delegated trap must report. */
__asm__ volatile(".globl ember_probe\n"
                 "ember_probe:\n"
                 "    csrr t0, mhartid");
timer_on();
for (;;)
    __asm__ volatile("wfi");
void timer_on(void)
{
    csr_set(sie, 1UL << 1); /* SSIE */
    csr_set(sstatus, MSTATUS_SIE);
}

timer_on sets sie.SSIE and then sstatus.SIE, and the order is deliberate: the second write opens the last gate and, by the evaluation rule of chapter 5, anything already pending is taken at that instruction. S never writes mtimecmp and never asks for a deadline. The loop in s_entry is the wfi pattern of the Mechanism: after each tick the handler srets to the instruction after the wfi, which jumps back to it. The probe above the call is chapter 5’s, and the capture’s S: trap sepc=probe scause=0x2 stval=0xf14022f3 line is its result, a delegated illegal instruction taken in S at the probe, nothing about time.

The M half of the tick is in two places, the shim’s C entry and the timer function it calls first:

void mshim(unsigned long cause, unsigned long tval)
{
    unsigned long code = cause & ~MCAUSE_INT;
    int expected = 0;

    if (timer_claim_m(cause))
        return;

    uart_puts("M: trap cause ");
    uart_puthex(code);
    if (code == MCAUSE_ILLEGAL) {
        uart_puts(" (illegal instruction) mtval=");
        uart_puthex(tval);
        uart_puts(" — S-mode proven\r\n");
    } else if (code == MCAUSE_STORE_PAGE || code == MCAUSE_LOAD_PAGE) {
        uart_puts(" (page fault) mtval=");
        uart_puthex(tval);
        uart_puts("\r\n");
    } else {
        uart_puts(" mtval=");
        uart_puthex(tval);
        uart_puts("\r\n");
    }

    if (expected) {
        uart_puts("PASS\r\n");
        halt(0);
    }
    halt(1);
}
int timer_claim_m(unsigned long cause)
{
    unsigned long code = cause & ~MCAUSE_INT;

    if ((cause & MCAUSE_INT) && code == MCAUSE_MTI) {
        timer_reload();
        csr_set(mip, 1UL << 1); /* SSIP → S */
        return 1;
    }
    return 0;
}

mshim offers the cause to timer_claim_m before anything else, so a timer interrupt never reaches the exception printing code and its halt. Past that call is chapter 3’s exception path; at HP_CH 6 expected stays 0, so any exception that does reach it halts with status 1, which is what a fault inside the shim should do. timer_claim_m strips the interrupt bit with cause & ~MCAUSE_INT and answers only when the bit was set and the code is MCAUSE_MTI, 7 (the machine timer interrupt’s code, the same as its bit in mip). The test on both matters: exception code 7 is a store access fault, and without the interrupt-bit test one would be mistaken for a timer tick. It reloads, which lowers MTIP, then sets SSIP in mip by CSR write, which the table says is allowed (MTIP could not be written this way). It returns 1, mshim returns, and mshim_entry restores the registers and executes mret, which returns to S with SSIP pending and mideleg bit 1 set. If the hart is in S with sstatus.SIE set, the software interrupt is taken before the next instruction.

The S half is the tick handler, inside trapper:

csr_clear(sip, 1UL << 1);
ticks++;
uart_puts("S: tick ");
uart_puthex(ticks);
uart_puts("\r\n");
if (ticks >= 3) {
    uart_puts("PASS\r\n");
    halt(0);
}

csr_clear(sip, 1UL << 1) acknowledges the interrupt; stip-inject showed what happens to a bit S cannot clear. The count is a static unsigned char in trap.c, three ticks end the lab, and the PASS and halt lines, compiled only at HP_CH 6, are the terminator that chapter 8 drops when the same handler starts scheduling. The three printed lines are the evidence that a timer interrupt was taken in M, turned into a software interrupt, and taken again in S, three times, with no UART input and no PLIC interrupt in the path.

The capture is chapter 5’s boot lines through the probe line, then the ticks. It has no ember or chars=0x6 echo, because chapter 6’s s_entry branch does not call uart_irq_on, so the UART path is idle (input.txt is empty, and nothing would read it):

S: trap sepc=probe scause=0x2 stval=0xf14022f3
S: tick 0x1
S: tick 0x2
S: tick 0x3
PASS

A frame in S that survives a trap, and a tick the kernel did not ask for, are what Part II puts a process under: chapter 7 fabricates that frame to enter a program, and chapter 8 uses this tick to take the hart back from it.

Exercises

(a) timer_enable_m reloads mtimecmp before it sets mie.MTIE. Remove the reload, so that mtimecmp stays at its reset value, and have S check, from time, how long after it started each tick arrives. What changes, and why is the first early tick not a loop?

Answer

mtimecmp-zero.txt removes the timer_reload() line from timer_enable_m, has M set mcounteren.TM, and has S read time when it starts and at each tick:

S: tick 0x1
S: tick 1 within 0.1 s of S starting: yes
S: tick 0x2
S: tick 0x2 one interval, within 0.1 s, after the one before: yes
S: tick 0x3
S: tick 0x3 one interval, within 0.1 s, after the one before: yes

The first tick arrives with S, not one interval later: MTIP was pending from reset, MTIE was already set when the mret dropped to S, where the interrupt is taken at once, and the shim’s first run did the reload that timer_enable_m skipped. From then on the cadence is the ordinary one, so it is a single early tick and not a loop. The loop would need the shim not to move mtimecmp. The transcript’s tick lines are otherwise the capture’s, which is why the patch prints something that tells the two apart. The 0.1 s bounds are the patch’s choice, and chapter 3’s mtie-set.txt shows the same trap at the mret with only mie.MTIE set.

(b) M normally arms the deadline. Leave it unarmed (no timer_enable_m) and have S set its own sip.SSIP in a loop, with no wfi. What does the transcript say, and what does it show about what the handler can know?

Answer

ssip-self.txt leaves out timer_enable_m, so M arms nothing, and has S write sip.SSIP in a loop:

S: tick 0x1
S: tick 0x2
S: tick 0x3
PASS

The three tick lines and PASS are the capture’s, with no armed deadline and no M-mode trap in the path. The handler cannot tell whether SSIP was raised by M, by the platform or by S itself (the specification lists all three as writers: “SSIP is writable in mip and may also be set to 1 by a platform-specific interrupt controller”, and in sip by S). The count proves that interrupts arrived, not that time passed. A kernel that wanted a clock would read time. The loop has no wfi because the interrupt is taken at the csrs itself, once SIE is set; a wfi after it would wait for ever, as wfi-masked does, since once the handler has returned nothing is pending and enabled and no deadline is armed.

(c) The lab prints three ticks. Without a wall clock, how would you show they are one interval apart, and why is the test “at least” and not “equal”?

Answer

tick-interval.txt is the run. Its patch has M set mcounteren.TM and the tick handler read time at tick 1 and tick 3, and it prints the difference in whole intervals and two checks:

S: time at tick 3 minus time at tick 1: whole intervals 0x2; at least two intervals: yes; skew under 0.1 s: yes

Two intervals is the difference of the two reads, and no wall clock is involved. The inequality is about the deadlines: timer_reload stores mtime + INTERVAL with mtime read inside the shim, after the interrupt was taken, so consecutive deadlines are at least INTERVAL apart, which is why the test is “at least” and not “equal”. What the run measures is the S-side reads, taken after each S: tick print, so the printed difference is two intervals plus the delays of two shim runs plus the difference of two S-side delays, and that last term can be negative. The run therefore checks both bounds, at least two intervals and under 0.1 s over, and the 0.1 s is the patch’s own choice, not a property of the hardware. It prints booleans because the raw difference depends on the host’s timing.

(d) A user program in chapter 7 will run rdtime. M has set mcounteren.TM. Is that enough?

Answer

No. The specification’s sentence for scounteren is: “U-mode may only access a counter if the corresponding bits in scounteren and mcounteren are both set.” The register’s own text: “When the CY, TM, IR, or HPMn bit in the scounteren register is clear, attempts to read the cycle, time, instret, or hpmcountern register while executing in U-mode will cause an illegal-instruction exception.” S-mode must set bit 1 of scounteren as well, and “scounteren must be implemented. However, any of the bits may be read-only zero”, so a kernel reads the bit back after writing it.

(e) timer_reload is one sd. Write the same operation for a 32-bit hart and say why its first store is all ones.

Answer

The specification gives the sequence, “assuming a little-endian memory system and that the registers live in a strongly ordered I/O region”, with the new comparand in a1:a0:

li t0, -1
la t1, mtimecmp
sw t0, 0(t1)     # No smaller than old value.
sw a1, 4(t1)     # No smaller than new value.
sw a0, 0(t1)     # New value.

Each store writes 32 bits, so between two stores mtimecmp is half old and half new. The first store sets the low word to all ones: “Storing -1 to the low-order bits of mtimecmp prevents mtimecmp from temporarily becoming smaller than the lesser of the old and new values”, so if neither the old deadline nor the new one is due yet, no intermediate value is. The sequence “sets a 64-bit mtimecmp value without spuriously generating a timer interrupt due to the intermediate value of the comparand.” On RV64 none of it is needed, as the width sentence above says.

Lab

make lab CH=06
make lab CH=06 IMPL=mine
make ex CH=06

The capture pins the boot lines through the probe line, then S: tick 0x1 to 0x3 and PASS; it pins no timing. IMPL=mine has timer_on as a halt(1), so the diff fails on the three tick lines and PASS until the reader writes the two CSR lines. make ex CH=06 reruns every side run in a scratch copy of ember/ and diffs each transcript against the one in labs/ch06/ex/; it is not part of make check. The committed transcripts are from QEMU 11.1.1. smp2-unparked and smp2-parked add -smp 2 through a .qemu file next to the patch. wfi-masked ends by timeout after 30 s, which is the result. dtb.sh (the board’s device tree) is a script, so make ex does not rerun it.

Further reading

results matching ""

    No results matching ""