{"id":9,"date":"2019-11-01T21:27:00","date_gmt":"2019-11-02T01:27:00","guid":{"rendered":"https:\/\/www.vociferousvoid.org\/?p=9"},"modified":"2023-07-01T17:26:41","modified_gmt":"2023-07-01T21:26:41","slug":"risc-v-bare-metal-programming-chapter-1-the-setup","status":"publish","type":"post","link":"https:\/\/www.vociferousvoid.org\/index.php\/2019\/11\/01\/risc-v-bare-metal-programming-chapter-1-the-setup\/","title":{"rendered":"RISC-V Bare Metal Programming Chapter 1: The Setup"},"content":{"rendered":"\n<div class=\"wp-block-group is-vertical is-layout-flex wp-container-core-group-is-layout-8cf370e7 wp-block-group-is-layout-flex\">\n<p>This tutorial, will walk through the process of building and running a RISC-V program on bare metal hardware. The reader is assumed to be familiar with the GNU toolchain and basic C programming. Assembly experience is useful but should not be required to follow along.<\/p>\n\n\n\n<p>There are many tutorials available to get started with bare metal programming<sup><a href=\"#fn.1\">1<\/a>, <a href=\"#fn.2\">2<\/a><\/sup>. However, most of them are for more common architectures such as x86 and ARM-32. Moreover, many of the existing tutorials are targetted at aspiring OS developers and often assume that the reader is already familiar with embedded programming. The objective of this tutorial is to learn how to walk before being asked to run.<\/p>\n\n\n\n<p>This tutorial is loosely modelled after a similar one for the ARM-32 architecture: <a href=\"http:\/\/www.bravegnu.org\/gnu-eprog\/index.html\">Embedded Programming with the GNU Toolchain<\/a>. However, the RISC-V ISA will be used rather than ARM-V5TE. QEMU will be used to emulate the hardware platform, thus allowing the learner to proceed without having to obtain an actual board.<\/p>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Why RISC-V?<\/h2>\n\n\n\n<p>RISC-V is a modern and open instruction set architecture (ISA). As opposed to X86 and ARM, which have existed for decades and have been updated incrementally, RISC-V was developed from scratch as a clean-slate, minimalist and open ISA informed by the mistakes of the past. As an open ISA, RISC-V is ideal for educational purposes as it is not subject to the whims or fates of a single corporation. More importantly, I have not found may resources for bare metal programming using this architecture<sup><a href=\"#fn.3\">3<\/a><\/sup>, therefore this tutorial aims to that knowledge void.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Setting Up the Host<\/h2>\n\n\n\n<p>Most programmers start off in a self-hosted envrionment. This means that they write programs for an environment using the same environment (e.g. writing GNU\/Linux programs using a GNU\/Linux machine). However, in embedded development, the machine on which a program is run (the target) will generally have a different architecture from the one on which it was created (the host). This section will outline the steps for setting up a GNU\/Linux workstation as a host development environment (in my case Debian Buster) to build programs for a RISC-V 64-bit architecture. The steps oulined herein will be specific to Debian based GNU\/Linux distributions (i.e. Ubuntu, PureOS, Mint)<sup><a href=\"#fn.4\">4<\/a><\/sup>.<\/p>\n\n\n\n<p>The first step of any kind of programming is setting up the toolchain. Since we&#8217;re building for the RISC-V architecture, we will need a suitable toolchain, and the <a href=\"https:\/\/github.com\/riscv\/riscv-gnu-toolchain\">RISC-V GNU Compiler Toolchain<\/a> fits the bill.<\/p>\n\n\n\n<p>Some dependencies are required in order to build the toolchain. These can be installed using the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ sudo apt-get install autoconf automake autotools-dev curl \\\nlibmpc-dev libmpfr-dev libgmp-dev gawk build-essential bison \\\nflex texinfo gperf libtool patchutils bc zlib1g-dev libexpat-dev<\/code><\/pre>\n\n\n\n<p>Next retrieve the source for the RISC-V GNU toolchain and all the required sub-modules:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ git clone --recursive https:\/\/github.com\/riscv\/riscv-gnu-toolchain<\/code><\/pre>\n\n\n\n<p>Since we are dealing with a bare metal system, the toolchain must be built for the <a href=\"https:\/\/www.sourceware.org\/newlib\/\">Newlib library<\/a>. The Newlib library is an implementation of the standard C library for embedded systems.<\/p>\n\n\n\n<p>Choose a destination folder on your host system where the toolchain will be installed (this tutorial will assume <code>\/opt\/riscv\/<\/code>), ensuring that its location is in the PATH. Then build the toolchain with the following commands:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ .\/configure --prefix=\/opt\/riscv\n$ make<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Do As RISC Does<\/h2>\n\n\n\n<p>Once the compiler toolchain is setup, the next requirement is an environment in which to run the programs thereby generated. <code>QEMU<\/code> will be used for this purpose. Use apt-get on Debian systems to install <code>QEMU<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ apt-get install qemu-system-misc<\/code><\/pre>\n\n\n\n<p>This will install several QEMU binaries supporting various architectures including:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>qemu-system-riscv64<\/li>\n\n\n\n<li>qemu-system-riscv32<\/li>\n<\/ul>\n\n\n\n<p>We&#8217;re interested in the 64-bit RISC-V version.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">RISC-V is Alive<\/h1>\n\n\n\n<p>This section describes the process of writing a simple RISC-V program in assembly, and running it on a bare metal virtual board emulated by QEMU. The programming examples are modelled after those in the <a href=\"http:\/\/www.bravegnu.org\/gnu-eprog\/index.html\">Embedded Programming with the GNU Toolchain<\/a> tutorial, but adapted from ARM-32 to the RISC-V 64-bit architecture.<\/p>\n\n\n\n<p>Each line of the assembly program is composed of three optional elements: a label, an instruction, and a comment: label A label is a convenience to allow the program to refer to a particular memory location using a symbolic name. A label is composed of a sequence of alphanumeric characters, in addition to underscores (_) or dollar signs ($). A label will always be terminated by a colon (:). instruction Instructions consist of either RISC-V assembly instructions or assembler directives. Assembler directives are prefixed with a period (.) comment Comments are preceded by an &#8220;#&#8221; charachter. Anything that follows that character will be ignored until the first newline character.<\/p>\n\n\n\n<p>The first example will simply calculate the sum of two literal numerical values:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>        .text\n        .global _start\n_start:\n        li      a2, 5           # a2 = 5\n        li      a3, 4           # a3 = 4\n        add     a0, a2, a3      # a0 = a2 + a3\nstop:   j       stop<\/code><\/pre>\n\n\n\n<p>The first line is an assembler directive which indicates that the program is meant to go in the &#8220;text&#8221; section of the binary file. The next line uses the <code>.global<\/code> directive to define the <code>_start<\/code> symbol. This will ensure that this symbol is visible to the loader. Next the <code>_start<\/code> label is defined to indicate the start offset of the program.<\/p>\n\n\n\n<p>The first two instructions will load integer values 5 and 4 in to registers <code>a2<\/code> and <code>a3<\/code> respectively. The instruction mnemonic stands for &#8220;Load Immediate&#8221;. This is a pseudo instruction since it does not actually correspond with a RISC-V opcode; internally this maps to a RISC-V <code>addi<\/code> instruction:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>addi a2,zero,5\naddi a3,zero,4<\/code><\/pre>\n\n\n\n<p>The last line defines the label &#8220;stop&#8221; and a jump instruction that will return the program counter to the memory address at that label; thus will loop indefinitely.<\/p>\n\n\n\n<p>Save the program to a file called <code>add.s<\/code> then compile it using the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ riscv64-unknown-elf-as -o add.o add.s<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">This will create the <code>add.o<\/code> object file representing the assembled program. Before it can be used, the program must be linked into suitable executable file. We use the loader for this purpose. Moreover since we are targeting a bare metal machine, we have to ensure that our program is loaded to an address where it can be found by the processor.<\/pre>\n\n\n\n<p>We will be working with the <code>virt<\/code> machine emulated by <code>QEMU<\/code>. The reset vector for this machine is located at address <code>0x8000000<\/code>. This means that the first instruction that will be executed when the processor is reset will be the one at memory location <code>0x80000000<\/code>. Therefore we must ensure that the memory offset labelled &#8220;<sub>start<\/sub>&#8221; in our program is loaded at the reset vector location:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ riscv64-unknown-elf-ld -Ttext=0x80000000 -o add.elf add.o<\/code><\/pre>\n\n\n\n<p>The <code>-Ttext=<\/code> options forces the text section (defined using the <code>.text<\/code> assembler directive) to be loaded at the given memory address. We can verify that the instruction with the label _start is at the correct location using the <code>nm<\/code> command. The output should be similar to the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ riscv64-unknown-elf-nm add.elf \n0000000080001010 T __BSS_END__\n0000000080001010 T __bss_start\n0000000080001010 T __DATA_BEGIN__\n0000000080001010 T _edata\n0000000080001010 T _end\n0000000080001810 A __global_pointer$\n0000000080001010 T __SDATA_BEGIN__\n0000000080000000 T _start\n000000008000000c t stop\n$ <\/code><\/pre>\n\n\n\n<p>Notice that the <code>_start<\/code> label in the previous example is located at address <code>0000000080000000<\/code>, which corresponds with the reset vector of the <code>virt<\/code> machine. We can now run the program in <code>QEMU<\/code> using the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ qemu-system-riscv64 -M virt -serial \/dev\/null -nographic -kernel add.elf\nQEMU 3.1.0 monitor - type 'help' for more information\n(qemu) <\/code><\/pre>\n\n\n\n<p>This executes the RISC-V 64-bit <code>QEMU<\/code> emulator with the following options: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>M virt:<\/code> This sets the machine type to &#8216;virt&#8217; which models a RISC-V VirtIO board using the privilege RISC-V ISA version (1.10).<\/li>\n\n\n\n<li><code>serial \/dev\/null:<\/code> Since there is no I\/O in our the serial output is redirected to <code>\/dev\/null<\/code>.<\/li>\n\n\n\n<li><code>nographic<\/code>: Again, since there is no I\/O, we don&#8217;t need a graphical UI. <\/li>\n\n\n\n<li><code>kernel add.elf<\/code>: Load the kernel in add.elf.<\/li>\n<\/ul>\n\n\n\n<p>Although it doesn&#8217;t seem that the program has done very much, remember that it is very basic and does not involve any kind if I\/O. To ensure that it did what was expected, we have to inspect the state of the machine. The QEMU console allows us to do this. We can inspect the state of the registers using the <code>info registers<\/code> command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(qemu) info registers\n pc       000000008000000c\n mhartid  0000000000000000\n mstatus  0000000000000000\n mip      0000000000000000\n mie      0000000000000000\n mideleg  0000000000000000\n medeleg  0000000000000000\n mtvec    0000000000000000\n mepc     0000000000000000\n mcause   0000000000000000\n zero 0000000000000000 ra   0000000000000000 sp   0000000000000000 gp   0000000000000000\n tp   0000000000000000 t0   0000000080000000 t1   0000000000000000 t2   0000000000000000\n s0   0000000000000000 s1   0000000000000000 a0   0000000000000009 a1   0000000000001020\n a2   0000000000000005 a3   0000000000000004 a4   0000000000000000 a5   0000000000000000\n a6   0000000000000000 a7   0000000000000000 s2   0000000000000000 s3   0000000000000000\n s4   0000000000000000 s5   0000000000000000 s6   0000000000000000 s7   0000000000000000\n s8   0000000000000000 s9   0000000000000000 s10  0000000000000000 s11  0000000000000000\n t3   0000000000000000 t4   0000000000000000 t5   0000000000000000 t6   0000000000000000\n ft0  0000000000000000 ft1  0000000000000000 ft2  0000000000000000 ft3  0000000000000000\n ft4  0000000000000000 ft5  0000000000000000 ft6  0000000000000000 ft7  0000000000000000\n fs0  0000000000000000 fs1  0000000000000000 fa0  0000000000000000 fa1  0000000000000000\n fa2  0000000000000000 fa3  0000000000000000 fa4  0000000000000000 fa5  0000000000000000\n fa6  0000000000000000 fa7  0000000000000000 fs2  0000000000000000 fs3  0000000000000000\n fs4  0000000000000000 fs5  0000000000000000 fs6  0000000000000000 fs7  0000000000000000\n fs8  0000000000000000 fs9  0000000000000000 fs10 0000000000000000 fs11 0000000000000000\n ft8  0000000000000000 ft9  0000000000000000 ft10 0000000000000000 ft11 0000000000000000\n<\/code><\/pre>\n\n\n\n<p>Remember that we had loaded the immediate value 5 in register <code>a2<\/code>, and the immediate value 4 in register <code>a3<\/code>. The values in the register dump reflect this. Moreover the program will sum the values in <code>a2<\/code> and <code>a3<\/code> and store the result in register <code>a0<\/code>. The regiseter dump shows that the value in register <code>a0<\/code> is in fact 9, which is the sum of 4 and 5. Moreover we see that the program counter in register <code>pc<\/code> is at memory address <code>0x8000000c<\/code> which corresponds with the label &#8220;stop&#8221; which is an infinite loop.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Conclusion<\/h1>\n\n\n\n<p>This tutorial went through the process of setting up a host environment for developing bare metal RISC-V programs, creating a simple program to add two numbers in RISC-V assembly, then running this program using QEMU. In future tutorials, the coding examples will get progressively more complex. However, the host environment will remain the same.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Footnotes<\/h1>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a name=\"fn.1\"><\/a><a href=\"http:\/\/www.bravegnu.org\/gnu-eprog\/index.html\">http:\/\/www.bravegnu.org\/gnu-eprog\/index.html<\/a><\/li>\n\n\n\n<li><a name=\"fn.2\"><\/a><a href=\"https:\/\/wiki.osdev.org\/Bare_Bones\">https:\/\/wiki.osdev.org\/Bare_Bones<\/a><\/li>\n\n\n\n<li><a name=\"fn.3\"><\/a>One good reference is Stepen Marz tutorial for building an OS in Rust: <a href=\"http:\/\/osblog.stephenmarz.com\/index.html\">http:\/\/osblog.stephenmarz.com\/index.html<\/a><\/li>\n\n\n\n<li><a name=\"fn.4\"><\/a>Future tutorials may focus on setting up other host platforms.<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial, will walk through the process of building and running a RISC-V program on bare metal hardware. The reader is assumed to be familiar with the GNU toolchain and basic C programming. Assembly experience is useful but should not be required to follow along. There are many tutorials available to get started with bare [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-9","post","type-post","status-publish","format-standard","hentry","category-risc-v"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts\/9","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/comments?post=9"}],"version-history":[{"count":2,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts\/9\/revisions"}],"predecessor-version":[{"id":12,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/posts\/9\/revisions\/12"}],"wp:attachment":[{"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/media?parent=9"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/categories?post=9"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vociferousvoid.org\/index.php\/wp-json\/wp\/v2\/tags?post=9"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}