A Hello World RISC-V operating system in 14 lines ================================================= [Published 2020-05-04] Here is the full code: 1 csrrs t0, mhartid, zero 2 blt zero, t0, halt 3 4 lui t1, 0x10010 5 addi t2, zero, 'h' 6 sw t2, 0(t1) 7 addi t2, zero, 'i' 8 sw t2, 0(t1) 9 addi t2, zero, 0x0a 10 sw t2, 0(t1) 11 12 halt: 13 wfi 14 jal zero, halt All it does is to print "hi" and then stop. Compile it with an assembler that can output raw binary (and not just ELF files) and then run it with this command, assuming the binary file is called "os": qemu-system-riscv64 -machine sifive_u -bios os -nographic I have not tested it on real hardware or other emulators so this is only for qemu. What the code means ------------------- When a RISC-V CPU starts, all cores start running at an implementation defined address. This means that all cores execute the code at the same time. That means that we will get 4 "hi" printed on a CPU with 4 cores (more precisely harts, hardware threads). We only want one "hi" to be printed and therefore we need to park all cores except for one. On line 1 we read the "mhartid" control/status register and put the value of that in register t0. This value is the id number of the currently executing hardware thread (hart), so all harts will get different values in t0 here. On line 2 we branch if zero is less than t0, i.e. if the hart id is greater than 0. That means all harts except for the first one, that is required to have id 0, will jump to label "halt" at line 12 where they will be stuck in an infinite loop while waiting for interrupts (wfi). Now we are on line 4. Only one hart will execute this code. We load the value 0x10010 into the upper 20 bits of t1, so now t1 has value 0x10010000. This is the base address of the UART0 on the sifive_u machine. On line 5 and 6 we store byte 'h' on that address. This will write a 'h' to the UART, which you will see in the terminal. Next we do the same with 'i' and a newline. After all of that this hart will get down to the infinite loop with the other harts and nothing more will happen.