---
title: "A computer of your own: memory-mapped I/O"
heading: Giving the processor a way to reach the outside world, devices as addresses, decoding which loads and stores belong to memory and which to a device, LEDs, switches, a timer and an output port, why device registers are volatile in C, and a program that times itself
eyebrow: D13 · Lesson 12 · A computer of your own
xp: 40
---

::: hook
A processor that only computes in memory is invisible: nothing goes in and nothing comes out. Real computers reach their devices with the same loads and stores they use for memory. Certain addresses are wired to an LED latch, a bank of switches, a timer or a serial port instead of RAM, and the address decoder decides which. In C those addresses are pointers to `volatile` registers, which is exactly how C12's board works. This lesson gives your core the C8 board's devices and runs a program that reads the switches, lights LEDs, prints and times itself.
:::

::: play
- A CRC program that reads the TIMER before and after computing, prints the CRC and how many cycles it took, and copies the switches to the LEDs.
- Set the switches and run: the LEDs follow them. The second printed value is the elapsed time in cycles, 1028 here, measured by the program itself.
- In the listing, find the `lui t0, 0x20` that builds the device addresses: each device register is a store or load at an offset from 0x2_0000.

```sim cpu
c:
#include "board.h"

const char message[] = "123456789";

uint32_t crc16(const char *s) {
    uint32_t reg = 0xFFFF;
    while (*s) {
        reg ^= (uint32_t)(unsigned char)*s++ << 8;
        for (int k = 0; k < 8; k++) {
            if (reg & 0x8000) reg = (reg << 1) ^ 0x1021;
            else reg = reg << 1;
            reg &= 0xFFFF;
        }
    }
    return reg;
}

int main(void) {
    uint32_t start = TIMER;
    uint32_t c = crc16(message);
    uint32_t took = TIMER - start;
    print(c);
    print(took);
    LEDS = SWITCHES;
    return 0;
}
asm:
    .text
_start:
    call main
    ebreak

crc16:
    li a1, 0xffff           #@6
.L1:
    lbu t0, 0(a0)           #@7
    beqz t0, .L2            #@7
    mv t0, a0               #@8
    addi a0, a0, 1          #@8
    lbu t0, 0(t0)           #@8
    slli t0, t0, 8          #@8
    xor a1, a1, t0          #@8
    li a2, 0                #@9
.L3:
    li t0, 8                #@9
    bge a2, t0, .L5         #@9
    li t0, 0x8000           #@10
    and t0, a1, t0          #@10
    beqz t0, .L6            #@10
    slli t0, a1, 1          #@10
    li t1, 0x1021           #@10
    xor a1, t0, t1          #@10
    j .L7                   #@10
.L6:
    slli a1, a1, 1          #@11
.L7:
    li t0, 0xffff           #@12
    and a1, a1, t0          #@12
.L4:
    addi a2, a2, 1          #@9
    j .L3                   #@9
.L5:
    j .L1                   #@7
.L2:
    mv a0, a1               #@15
.Lret_crc16:
    ret                     #@16

main:
    addi sp, sp, -16        #@18
    sw ra, 12(sp)           #@18
    sw s1, 8(sp)            #@18
    sw s2, 4(sp)            #@18
    sw s3, 0(sp)            #@18
    lui t0, 0x20            #@19
    lw s1, 8(t0)            #@19
    la a0, message          #@20
    call crc16              #@20
    mv s2, a0               #@20
    lui t0, 0x20            #@21
    lw t0, 8(t0)            #@21
    sub s3, t0, s1          #@21
    lui t0, 0x20            #@22
    sw s2, 16(t0)           #@22
    lui t0, 0x20            #@23
    sw s3, 16(t0)           #@23
    lui t0, 0x20            #@24
    lw t0, 4(t0)            #@24
    lui t1, 0x20            #@24
    sw t0, 0(t1)            #@24
    li a0, 0                #@25
.Lret_main:
    lw ra, 12(sp)           #@26
    lw s1, 8(sp)            #@26
    lw s2, 4(sp)            #@26
    lw s3, 0(sp)            #@26
    addi sp, sp, 16         #@26
    ret                     #@26

    .data
message:
    .byte 49, 50, 51, 52, 53, 54, 55, 56, 57, 0
leds: on
switches: on
out: on
speed: 500
```

::: predict
## In C, OUT is defined as `*(volatile int32_t *)0x20010`. If the `volatile` were left out and a program printed the same variable twice in a row, what might the compiler do?

- [ ] Nothing different
- [x] Keep only the second store, since the first is overwritten
- [ ] Refuse to compile it
- [ ] Turn both stores into loads

::: reveal
To the compiler, a plain memory location that's written twice with nothing reading it in between only needs the last write, so it may delete the first. For a device, each write is an event: two prints must be two stores. `volatile` tells the compiler every access matters and must happen in order (C12).
:::
:::

::: nameit
## Devices as addresses

| Address | Device | Load | Store |
|---|---|---|---|
| 0x2_0000 | LEDS | what's shown | lights the 8 LEDs |
| 0x2_0004 | SWITCHES | the 8 switches | (ignored) |
| 0x2_0008 | TIMER | cycles since reset | |
| 0x2_0010 | OUT | | prints a number |

In hardware an **address decoder** compares the upper address bits with each device's range and enables that device instead of the RAM (D10): a 16-byte block needs the top 28 bits compared. In a simulator the decoder is an `if` on the address before falling through to memory.

## Reaching the addresses

0x2_0010 doesn't fit in a 12-bit immediate, so the compiler builds it as `lui t0, 0x20` (t0 = 0x2_0000) and then `sw a0, 16(t0)`. Any address A is `lui` with $\lfloor A/4096\rfloor$ (rounded up if the low part is 0x800 or more) plus a 12-bit offset.

## Timing with a timer

Reading a free-running timer before and after a piece of code measures it in cycles, which is how firmware is profiled on real boards. Here the timer counts instructions, so the result is the number of instructions between the two reads.
:::

::: example
## How does the compiled program reach the LEDs, and which bytes does a store there change?

::: solution
1. **Form the address.** `lui t0, 0x20` makes 0x2_0000, which is LEDS itself.
2. **Store.** `sw` writes a word there, and the decoder sends it to the LED latch, which keeps the low 8 bits.
3. **RAM.** Nothing in RAM changes.
4. **Read back.** A load from the same address reads the latch back.

**Answer:** through a `sw` to 0x2_0000, LEDS itself; the LED latch keeps the low 8 bits, and no byte of RAM changes.
:::
:::

::: example
## The program reports 1028 cycles for the CRC. How long is that at 50 MHz on a single-cycle core, and per byte of the message?

::: solution
1. **Total time.**
   $$\begin{aligned} t &= \frac{1028}{50\ \text{MHz}} \\ &= 20.6\ \mu\text{s} \end{aligned}$$
   for 9 bytes.
2. **Per byte.** That's 2.3 µs, or 114 instructions, per byte, most of them in the 8-step bit loop.
3. **A faster CRC.** A table-driven CRC (one lookup per byte) would cut that several times over.

**Answer:** 20.6 µs, about 2.3 µs or 114 instructions per byte.
:::
:::

::: check
kind: python

## Give your core memory-mapped LEDs, switches, a timer and an output port.

```python starter
MEM_SIZE = 0x30000
TEXT, DATA, STACK = 0x0, 0x1000, 0x10000

def sext(v, bits):
    # Sign-extend the low `bits` bits of v.
    v &= (1 << bits) - 1
    return v - (1 << bits) if v >> (bits - 1) else v

R_OPS = {(0, 0): 'add', (0, 0x20): 'sub', (1, 0): 'sll', (2, 0): 'slt', (3, 0): 'sltu',
         (4, 0): 'xor', (5, 0): 'srl', (5, 0x20): 'sra', (6, 0): 'or', (7, 0): 'and'}
I_OPS = {0: 'addi', 2: 'slti', 3: 'sltiu', 4: 'xori', 6: 'ori', 7: 'andi'}
LOADS = {0: 'lb', 1: 'lh', 2: 'lw', 4: 'lbu', 5: 'lhu'}
STORES = {0: 'sb', 1: 'sh', 2: 'sw'}
BRANCHES = {0: 'beq', 1: 'bne', 4: 'blt', 5: 'bge', 6: 'bltu', 7: 'bgeu'}

def decode(w):
    # One 32-bit instruction word to (name, rd, rs1, rs2, imm), with imm already sign-extended.
    op, rd, f3 = w & 0x7F, (w >> 7) & 31, (w >> 12) & 7
    rs1, rs2, f7 = (w >> 15) & 31, (w >> 20) & 31, w >> 25
    if op == 0x33:
        return R_OPS[(f3, f7)], rd, rs1, rs2, 0
    if op == 0x13:
        if f3 == 1:
            return 'slli', rd, rs1, 0, rs2
        if f3 == 5:
            return ('srai' if f7 else 'srli'), rd, rs1, 0, rs2
        return I_OPS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x03:
        return LOADS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x23:
        return STORES[f3], 0, rs1, rs2, sext((f7 << 5) | rd, 12)
    if op == 0x63:
        imm = ((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 63) << 5) | (((w >> 8) & 15) << 1)
        return BRANCHES[f3], 0, rs1, rs2, sext(imm, 13)
    if op == 0x37:
        return 'lui', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x17:
        return 'auipc', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x6F:
        imm = ((w >> 31) << 20) | (((w >> 12) & 255) << 12) | (((w >> 20) & 1) << 11) | (((w >> 21) & 1023) << 1)
        return 'jal', rd, 0, 0, sext(imm, 21)
    if op == 0x67:
        return 'jalr', rd, rs1, 0, sext(w >> 20, 12)
    if w == 0x00100073:
        return 'ebreak', 0, 0, 0, 0
    raise ValueError(f'unknown instruction {w:#010x}')

class CPU:
    def __init__(self, words, data=b''):
        self.mem = bytearray(MEM_SIZE)
        for k, w in enumerate(words):
            self.mem[TEXT + 4*k:TEXT + 4*k + 4] = (w & 0xFFFFFFFF).to_bytes(4, 'little')
        self.mem[DATA:DATA + len(data)] = bytes(data)
        self.x = [0]*32
        self.x[2] = STACK
        self.pc = TEXT
        self.count = 0

    def load(self, addr, n):
        return int.from_bytes(self.mem[addr:addr + n], 'little')

    def store(self, addr, n, value):
        self.mem[addr:addr + n] = (value & ((1 << 8*n) - 1)).to_bytes(n, 'little')

    def step(self):
        name, rd, rs1, rs2, imm = decode(self.load(self.pc, 4))
        a, b = self.x[rs1], self.x[rs2]
        u = lambda v: v & 0xFFFFFFFF
        nxt, val = self.pc + 4, None
        if name == 'ebreak':
            self.count += 1
            return False
        elif name == 'add': val = a + b
        elif name == 'sub': val = a - b
        elif name == 'and': val = a & b
        elif name == 'or': val = a | b
        elif name == 'xor': val = a ^ b
        elif name == 'sll': val = a << (b & 31)
        elif name == 'srl': val = u(a) >> (b & 31)
        elif name == 'sra': val = a >> (b & 31)
        elif name == 'slt': val = int(a < b)
        elif name == 'sltu': val = int(u(a) < u(b))
        elif name == 'addi': val = a + imm
        elif name == 'andi': val = a & imm
        elif name == 'ori': val = a | imm
        elif name == 'xori': val = a ^ imm
        elif name == 'slti': val = int(a < imm)
        elif name == 'sltiu': val = int(u(a) < u(imm))
        elif name == 'slli': val = a << imm
        elif name == 'srli': val = u(a) >> imm
        elif name == 'srai': val = a >> imm
        elif name == 'lui': val = imm
        elif name == 'auipc': val = self.pc + imm
        elif name in ('lb', 'lh', 'lw', 'lbu', 'lhu'):
            n = {'lb': 1, 'lh': 2, 'lw': 4, 'lbu': 1, 'lhu': 2}[name]
            val = self.load(u(a + imm), n)
            if name in ('lb', 'lh', 'lw'):
                val = sext(val, 8*n)
        elif name in ('sb', 'sh', 'sw'):
            self.store(u(a + imm), {'sb': 1, 'sh': 2, 'sw': 4}[name], b)
        elif name in ('beq', 'bne', 'blt', 'bge', 'bltu', 'bgeu'):
            taken = {'beq': a == b, 'bne': a != b, 'blt': a < b, 'bge': a >= b,
                     'bltu': u(a) < u(b), 'bgeu': u(a) >= u(b)}[name]
            if taken:
                nxt = self.pc + imm
        elif name == 'jal':
            val, nxt = self.pc + 4, self.pc + imm
        elif name == 'jalr':
            val, nxt = self.pc + 4, (a + imm) & ~1
        if val is not None and rd:
            self.x[rd] = sext(val, 32)
        self.pc = u(nxt)
        self.count += 1
        return True

    def run(self, limit=1000000):
        while self.count < limit and self.step():
            pass
        return self.count

# Two more compiled programs: a CRC that times itself with TIMER and copies the switches to the
# LEDs, and a Fibonacci program that reads n from the switches.
TIMED = [
    0x00000097, 0x080080e7, 0x00100073, 0x000105b7, 0xfff58593, 0x00054283,
    0x06028063, 0x00050293, 0x00150513, 0x0002c283, 0x00829293, 0x0055c5b3,
    0x00000613, 0x00800293, 0x02565e63, 0x000082b7, 0x0055f2b3, 0x00028c63,
    0x00159293, 0x00001337, 0x02130313, 0x0062c5b3, 0x0080006f, 0x00159593,
    0x000102b7, 0xfff28293, 0x0055f5b3, 0x00160613, 0xfc5ff06f, 0xfa1ff06f,
    0x00058513, 0x00008067, 0xff010113, 0x00112623, 0x00912423, 0x01212223,
    0x01312023, 0x000202b7, 0x0082a483, 0x00001517, 0xf6450513, 0x00000097,
    0xf68080e7, 0x00050913, 0x000202b7, 0x0082a283, 0x409289b3, 0x000202b7,
    0x0122a823, 0x000202b7, 0x0132a823, 0x000202b7, 0x0042a283, 0x00020337,
    0x00532023, 0x00000513, 0x00c12083, 0x00812483, 0x00412903, 0x00012983,
    0x01010113, 0x00008067,
]
TIMED_DATA = b'123456789\x00'
FIB = [
    0x00000097, 0x00c080e7, 0x00100073, 0x000202b7, 0x0042a283, 0x01f2f513,
    0x00000593, 0x00100613, 0x00000693, 0x00a6fc63, 0x00c58733, 0x00060593,
    0x00070613, 0x00168693, 0xfedff06f, 0x000202b7, 0x00b2a823, 0x000202b7,
    0x00a2a023, 0x00000513, 0x00008067,
]
FIB_DATA = b""

OUT, LEDS, SWITCHES, TIMER = 0x20010, 0x20000, 0x20004, 0x20008

class Board(CPU):
    def __init__(self, words, data=b'', switches=0):
        super().__init__(words, data)
        self.switches = switches
        self.out = []      # every value written to OUT, as signed 32-bit numbers
        self.leds = 0

    def load(self, addr, n):
        # SWITCHES reads the switches (8 bits), TIMER reads the instruction count so far, LEDS
        # reads back the LEDs; any other address is memory, as in CPU.
        return super().load(addr, n)

    def store(self, addr, n, value):
        # A store to OUT appends sext(value, 32) to self.out; a store to LEDS sets self.leds to
        # its low 8 bits; anything else is memory.
        super().store(addr, n, value)
```

```python solution
MEM_SIZE = 0x30000
TEXT, DATA, STACK = 0x0, 0x1000, 0x10000

def sext(v, bits):
    # Sign-extend the low `bits` bits of v.
    v &= (1 << bits) - 1
    return v - (1 << bits) if v >> (bits - 1) else v

R_OPS = {(0, 0): 'add', (0, 0x20): 'sub', (1, 0): 'sll', (2, 0): 'slt', (3, 0): 'sltu',
         (4, 0): 'xor', (5, 0): 'srl', (5, 0x20): 'sra', (6, 0): 'or', (7, 0): 'and'}
I_OPS = {0: 'addi', 2: 'slti', 3: 'sltiu', 4: 'xori', 6: 'ori', 7: 'andi'}
LOADS = {0: 'lb', 1: 'lh', 2: 'lw', 4: 'lbu', 5: 'lhu'}
STORES = {0: 'sb', 1: 'sh', 2: 'sw'}
BRANCHES = {0: 'beq', 1: 'bne', 4: 'blt', 5: 'bge', 6: 'bltu', 7: 'bgeu'}

def decode(w):
    # One 32-bit instruction word to (name, rd, rs1, rs2, imm), with imm already sign-extended.
    op, rd, f3 = w & 0x7F, (w >> 7) & 31, (w >> 12) & 7
    rs1, rs2, f7 = (w >> 15) & 31, (w >> 20) & 31, w >> 25
    if op == 0x33:
        return R_OPS[(f3, f7)], rd, rs1, rs2, 0
    if op == 0x13:
        if f3 == 1:
            return 'slli', rd, rs1, 0, rs2
        if f3 == 5:
            return ('srai' if f7 else 'srli'), rd, rs1, 0, rs2
        return I_OPS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x03:
        return LOADS[f3], rd, rs1, 0, sext(w >> 20, 12)
    if op == 0x23:
        return STORES[f3], 0, rs1, rs2, sext((f7 << 5) | rd, 12)
    if op == 0x63:
        imm = ((w >> 31) << 12) | (((w >> 7) & 1) << 11) | (((w >> 25) & 63) << 5) | (((w >> 8) & 15) << 1)
        return BRANCHES[f3], 0, rs1, rs2, sext(imm, 13)
    if op == 0x37:
        return 'lui', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x17:
        return 'auipc', rd, 0, 0, sext(w & 0xFFFFF000, 32)
    if op == 0x6F:
        imm = ((w >> 31) << 20) | (((w >> 12) & 255) << 12) | (((w >> 20) & 1) << 11) | (((w >> 21) & 1023) << 1)
        return 'jal', rd, 0, 0, sext(imm, 21)
    if op == 0x67:
        return 'jalr', rd, rs1, 0, sext(w >> 20, 12)
    if w == 0x00100073:
        return 'ebreak', 0, 0, 0, 0
    raise ValueError(f'unknown instruction {w:#010x}')

class CPU:
    def __init__(self, words, data=b''):
        self.mem = bytearray(MEM_SIZE)
        for k, w in enumerate(words):
            self.mem[TEXT + 4*k:TEXT + 4*k + 4] = (w & 0xFFFFFFFF).to_bytes(4, 'little')
        self.mem[DATA:DATA + len(data)] = bytes(data)
        self.x = [0]*32
        self.x[2] = STACK
        self.pc = TEXT
        self.count = 0

    def load(self, addr, n):
        return int.from_bytes(self.mem[addr:addr + n], 'little')

    def store(self, addr, n, value):
        self.mem[addr:addr + n] = (value & ((1 << 8*n) - 1)).to_bytes(n, 'little')

    def step(self):
        name, rd, rs1, rs2, imm = decode(self.load(self.pc, 4))
        a, b = self.x[rs1], self.x[rs2]
        u = lambda v: v & 0xFFFFFFFF
        nxt, val = self.pc + 4, None
        if name == 'ebreak':
            self.count += 1
            return False
        elif name == 'add': val = a + b
        elif name == 'sub': val = a - b
        elif name == 'and': val = a & b
        elif name == 'or': val = a | b
        elif name == 'xor': val = a ^ b
        elif name == 'sll': val = a << (b & 31)
        elif name == 'srl': val = u(a) >> (b & 31)
        elif name == 'sra': val = a >> (b & 31)
        elif name == 'slt': val = int(a < b)
        elif name == 'sltu': val = int(u(a) < u(b))
        elif name == 'addi': val = a + imm
        elif name == 'andi': val = a & imm
        elif name == 'ori': val = a | imm
        elif name == 'xori': val = a ^ imm
        elif name == 'slti': val = int(a < imm)
        elif name == 'sltiu': val = int(u(a) < u(imm))
        elif name == 'slli': val = a << imm
        elif name == 'srli': val = u(a) >> imm
        elif name == 'srai': val = a >> imm
        elif name == 'lui': val = imm
        elif name == 'auipc': val = self.pc + imm
        elif name in ('lb', 'lh', 'lw', 'lbu', 'lhu'):
            n = {'lb': 1, 'lh': 2, 'lw': 4, 'lbu': 1, 'lhu': 2}[name]
            val = self.load(u(a + imm), n)
            if name in ('lb', 'lh', 'lw'):
                val = sext(val, 8*n)
        elif name in ('sb', 'sh', 'sw'):
            self.store(u(a + imm), {'sb': 1, 'sh': 2, 'sw': 4}[name], b)
        elif name in ('beq', 'bne', 'blt', 'bge', 'bltu', 'bgeu'):
            taken = {'beq': a == b, 'bne': a != b, 'blt': a < b, 'bge': a >= b,
                     'bltu': u(a) < u(b), 'bgeu': u(a) >= u(b)}[name]
            if taken:
                nxt = self.pc + imm
        elif name == 'jal':
            val, nxt = self.pc + 4, self.pc + imm
        elif name == 'jalr':
            val, nxt = self.pc + 4, (a + imm) & ~1
        if val is not None and rd:
            self.x[rd] = sext(val, 32)
        self.pc = u(nxt)
        self.count += 1
        return True

    def run(self, limit=1000000):
        while self.count < limit and self.step():
            pass
        return self.count

# Two more compiled programs: a CRC that times itself with TIMER and copies the switches to the
# LEDs, and a Fibonacci program that reads n from the switches.
TIMED = [
    0x00000097, 0x080080e7, 0x00100073, 0x000105b7, 0xfff58593, 0x00054283,
    0x06028063, 0x00050293, 0x00150513, 0x0002c283, 0x00829293, 0x0055c5b3,
    0x00000613, 0x00800293, 0x02565e63, 0x000082b7, 0x0055f2b3, 0x00028c63,
    0x00159293, 0x00001337, 0x02130313, 0x0062c5b3, 0x0080006f, 0x00159593,
    0x000102b7, 0xfff28293, 0x0055f5b3, 0x00160613, 0xfc5ff06f, 0xfa1ff06f,
    0x00058513, 0x00008067, 0xff010113, 0x00112623, 0x00912423, 0x01212223,
    0x01312023, 0x000202b7, 0x0082a483, 0x00001517, 0xf6450513, 0x00000097,
    0xf68080e7, 0x00050913, 0x000202b7, 0x0082a283, 0x409289b3, 0x000202b7,
    0x0122a823, 0x000202b7, 0x0132a823, 0x000202b7, 0x0042a283, 0x00020337,
    0x00532023, 0x00000513, 0x00c12083, 0x00812483, 0x00412903, 0x00012983,
    0x01010113, 0x00008067,
]
TIMED_DATA = b'123456789\x00'
FIB = [
    0x00000097, 0x00c080e7, 0x00100073, 0x000202b7, 0x0042a283, 0x01f2f513,
    0x00000593, 0x00100613, 0x00000693, 0x00a6fc63, 0x00c58733, 0x00060593,
    0x00070613, 0x00168693, 0xfedff06f, 0x000202b7, 0x00b2a823, 0x000202b7,
    0x00a2a023, 0x00000513, 0x00008067,
]
FIB_DATA = b""

OUT, LEDS, SWITCHES, TIMER = 0x20010, 0x20000, 0x20004, 0x20008

class Board(CPU):
    def __init__(self, words, data=b'', switches=0):
        super().__init__(words, data)
        self.switches = switches
        self.out = []
        self.leds = 0

    def load(self, addr, n):
        if addr == SWITCHES:
            return self.switches & 0xFF
        if addr == TIMER:
            return self.count & 0xFFFFFFFF
        if addr == LEDS:
            return self.leds
        return super().load(addr, n)

    def store(self, addr, n, value):
        if addr == OUT:
            self.out.append(sext(value, 32))
        elif addr == LEDS:
            self.leds = value & 0xFF
        else:
            super().store(addr, n, value)
```

```python tests
_t = Board(TIMED, TIMED_DATA, switches=0x5A)
_t.run()
assert _t.out == [0x29B1, 1028], f"The program prints the CRC, 10673, then the instructions it took, 1028; got {_t.out}."
assert _t.leds == 0x5A, "It copies the switches to the LEDs."
assert _t.load(0x20010, 4) == 0 and _t.mem[0x20010] == 0, "A store to OUT goes to the device and leaves memory untouched."
_fib = [0, 1]
for _k in range(40):
    _fib.append(_fib[-1] + _fib[-2])
for _n in (0, 10, 20, 31):
    _b = Board(FIB, FIB_DATA, switches=_n)
    _b.run()
    assert _b.out == [_fib[_n]] and _b.leds == _n, f"With the switches at {_n} the program prints F({_n}) = {_fib[_n]} and shows {_n} on the LEDs; got {_b.out}, {_b.leds}."
```

::: right
Right. Your computer prints, lights its LEDs from its switches and times itself exactly as the simulator does.
:::
:::

::: check
given: A = 0x20010 | 0x40000008 | 0x12345 | 0x2000C
answer: floor(A/4096)
base: 16
tolerance: 0

## A store goes to the address {A:hex8}, whose low 12 bits are under 0x800. What upper value does the `lui` that builds it load?

::: right
Right. `lui` with {answer:hex5}, then an offset of the low 12 bits.
:::

::: misses
- [A] `lui` takes only the upper 20 bits; the rest goes in the offset.
- [any] Not yet. Drop the low 12 bits.
:::
:::

::: check
given: k = 4 | 8 | 12 | 20
answer: 32 - k
tolerance: 0.4

## A device occupies a block of $2^{\given{k}}$ bytes, aligned to its size. How many of the 32 address bits must the decoder compare to select it?

::: right
Right. The low {k} bits pick a byte within the block; the other {answer} pick the block.
:::

::: misses
- [k] Those bits address within the block; the decoder compares the rest.
- [any] Not yet. All the bits above the block's size.
:::
:::

::: check
given: N = 1028 | 1670 | 5000; f = 10 | 50 | 100
answer: N/f
unit: µs
tolerance: 0.5%

## A program's timer reads show {N} cycles of a {f} MHz clock. How long did the code take?

::: right
Right. {answer} µs.
:::

::: misses
- [any] Not yet. Cycles over the clock rate.
:::
:::

::: check
given: B = 1073741824 | 268435456; k = 1 | 3 | 7
answer: B + 4*k
base: 16
width: 8

## A peripheral's registers start at {B:hex8}, one 32-bit register every 4 bytes. What is the address of register {k}?

::: right
Right: {answer}.
:::

::: misses
- [B + k] Registers are 4 bytes apart.
- [any] Not yet. Base + 4 × index.
:::
:::

::: check
given: k = 0 | 5 | 12 | 31
answer: 2^k
base: 16
width: 8

## To set bit {k} of a control register with a read-modify-write, what mask do you OR in?

::: right
Right: {answer}, a single 1 in position {k}.
:::

::: misses
- [k] The mask is $1 \ll k$, not k itself.
- [any] Not yet. $2^k$.
:::
:::

::: explain
## Why are devices reached through ordinary loads and stores instead of special instructions?

::: model
Using the address space for devices means the processor needs no extra instructions or wiring for each new device: the address decoder routes some addresses to device registers instead of memory, and every existing load, store and addressing mode works on them. Compiled C can reach a device through a pointer just as it reaches a variable, which is how drivers are written. The cost is that the compiler and processor must not treat those addresses like memory, by caching, reordering or removing accesses, which is what `volatile` in C and uncached address regions in hardware are for.
:::
:::

::: practice

::: check
given: A = 0x30004 | 0x4000000C | 0x10200 | 0x7F010
answer: floor(A/4096)
base: 16
tolerance: 0

## `lui` value for {A:hex8}?

::: misses
- [any] Drop the low 12 bits.
:::
:::

::: check
given: k = 2 | 6 | 10 | 20
answer: 32 - k
tolerance: 0.4

## Decoder bits for a $2^{\given{k}}$-byte block (k = {k})?

::: misses
- [any] $32 - k$.
:::
:::
:::
