/* Original external boot-configuration reader. This protocol and machine are
 * teaching models, not a vendor device or a safety-rated boot controller.
 * SPI mode 3, MSB-first, READ 03 20 00 00 00 under one selected transaction.
 * RAM stores magic, requested mask, complement, error bits, completion phase.
 * Errors: bit0 magic, bit1 complement, bit2 reserved output bits. */
.option norvc
.option norelax
.section .text.start,"ax",@progbits
.globl _start
.type _start,@function
.macro send value, offset=64
    addi x6, zero, \value
    sw x6, \offset(x5)
.endm
.macro receive reg
1:  lw x7, 68(x5)
    andi x7, x7, 4
    beq x7, zero, 1b
    lw \reg, 64(x5)
.endm
_start:
    lui x5, 0x40000
    lui x22, 0x20000
    sw zero, 4(x5)
    send 127, 8
    send 4, 76
    send 119, 72
    send 1, 88
    send 3
    send 32
    send 0
    send 0
    send 0, 92
    receive x10
    receive x11
    receive x12
    receive x13
    receive x14
    sw x12, 0(x22)
    sw x13, 4(x22)
    sw x14, 8(x22)
    xori x6, x12, 195
    sltu x23, zero, x6
    xor x6, x13, x14
    xori x6, x6, 255
    sltu x6, zero, x6
    slli x6, x6, 1
    or x23, x23, x6
    andi x6, x13, 248
    sltu x6, zero, x6
    slli x6, x6, 2
    or x23, x23, x6
    bne x23, zero, done
    slli x6, x13, 4
    sw x6, 4(x5)
done:
    sw x23, 12(x22)
    addi x6, zero, 2
    sw x6, 16(x22)
idle:
    jal zero, idle
.size _start, .-_start
.section .note.GNU-stack,"",@progbits
