Raspberry Pi Bare Bones: Difference between revisions

m
Use {{main}}
[unchecked revision][unchecked revision]
(→‎Makefile: There is no CXXFLAGS. Changed to CFLAGS.)
m (Use {{main}})
 
(60 intermediate revisions by 22 users not shown)
Line 1:
{{BeginnersWarning}}
==Intro==
{{Rating|3}}
This is a tutorial on bare-metal [OS] development on the Raspberry Pi. This tutorial is written specifically for the Raspberry Pi Model B Rev 2 because the author has no other hardware to test on. But so far the models are basically identical for the purpose of this tutorial (Rev 1 has 256MB ram, Model A has no ethernet).
{{Template:Kernel designs}}
 
This is a tutorial on operating systems development on the [[Raspberry Pi]]. This will serve as an example of how to create a minimal system, but not as an example of how to properly structure your project.
This is the authors very first ARM system and we learn as we write without any prior knowledge about arm. Experience with the GNU toolchain (gcc, make, ... '''very''' important) and C language ('''incredibly''' important, including how to use inline asm) is assumed and required. This is not a tutorial about how to build a kernel but a simple intro in how to get started on the RPi.
 
There's a similar tutorial [[Raspberry Pi Bare Bones Rust]] which uses Rust instead of C.
==Bare minimum kernel==
 
== Prepare ==
Lets start with a minimum of 4 files. The kernel is going to use C. The main function will be in main.c. Before the main function can be called though some things have to be set up using assembly. This will be placed in boot.S. On top of that we also need a linker script and a Makefile to build the kernel and need to create an include directory for later use.
 
You are about to begin development of a new operating system. Perhaps one day, your new operating system can be developed under itself. This is a process known as bootstrapping or going self-hosted. However, that is way into the future. Today, we simply need to set up a system that can compile your operating system from an existing operating system. This is a process known as cross-compiling and this makes the first step in operating systems development.
===main.c===
 
This article assumes you are using a Unix-like operating system such as Linux which supports operating systems development well. Windows users should be able to complete it from a MinGW or Cygwin environment.
<source lang="cpp">
/* main.c - the entry point for the kernel */
 
== Building a Cross-Compiler ==
#include <stdint.h>
{{main|GCC Cross-Compiler|Why do I need a Cross Compiler?}}
 
The first thing you should do is set up a [[GCC Cross-Compiler]] for '''arm-none-eabi'''. You have not yet modified your compiler to know about the existence of your operating system, so we use a generic target called arm-none-eabi, which provides you with a toolchain targeting the [[System V ABI]].
#define UNUSED(x) (void)(x)
You will ''not'' be able to correctly compile your operating system without a cross-compiler.
 
If you want a 64 bit kernel, you should set up '''aarch64-elf''' target instead. This provides the same System V ABI interface, but for 64 bit. Using elf is not mandatory, but simplifies things.
// kernel main function, it all begins here
void kernel_main(uint32_t r0, uint32_t r1, uint32_t atags) {
UNUSED(r0);
UNUSED(r1);
UNUSED(atags);
}
</source>
 
== Overview ==
This simply declares an empty kernel_main function that simply returns. The GPU bootloader passes arguments to the kernel via r0-r2 and the boot.S makes sure to preserve those 3 registers. They are the first 3 arguments in a C function call. I'm not sure what R0 and R1 are for but r2 contains the address of the ATAGs (more about them later). For now the UNUSED() makro makes sure the compiler doesn't complain about unused variables.
 
By now, you should have set up your [[GCC Cross-Compiler|cross-compiler]] for the proper ABI (as described above). This tutorial provides a minimal solution for creating an operating system. It doesn't serve as a recommend skeleton for project structure, but rather as an example of a minimal kernel. In this simple case, we just need three input files:
===boot.S===
 
<source lang="asm">
* boot.S - kernel entry point that sets up the processor environment
/* boot.S - assembly startup code */
* kernel.c - your actual kernel routines
* linker.ld - for linking the above files
 
== Booting the Operating System ==
 
We will now create a file called boot.S and discuss its contents. In this example, we are using the GNU assembler, which is part of the cross-compiler toolchain you built earlier. This assembler integrates very well with the rest of the GNU toolchain.
 
Each Pi Model requires different set up. In general, you must distinguish AArch32 and AArch64 mode, as they are booted differently. The latter only accessible from Pi 3 and upwards. Within a mode, you can [[Detecting_Raspberry_Pi_Board|detect the board]] in run-time, and set up mmio base address accordingly.
 
===Pi Model A, B, A+, B+, and Zero===
 
The environment is set up and execution to _start transferred from [https://github.com/raspberrypi/tools/blob/master/armstubs/armstub.S#L35 armstub.s].
<syntaxhighlight lang="text">
// AArch32 mode
 
// To keep this in the first portion of the binary.
.section ".text.boot"
 
// Make Start_start global.
.globl Start_start
 
.org 0x8000
// Entry point for the kernel.
// r15 -> should begin execution at 0x8000.
// r0 -> 0x00000000
// r1 -> 0x00000C42 - machine id
// r2 -> 0x00000100 - start of ATAGS
// preserve these registers as argument for kernel_main
_start:
Start:
// Setup the stack.
mov sp, #0x8000
 
// Clear out bss.
ldr r4, =_bss_start__bss_start
ldr r9, =_bss_end__bss_end
mov r5, #0
mov r6, #0
mov r7, #0
mov r8, #0
b 2f
 
1:
// store multiple at r4.
stmia r4!, {r5-r8}
 
// If we're are still below bss_end, loop.
2:
cmp r4, r9
cmp r4, r9
blo 1b
blo 1b
 
// Call kernel_main
ldr r3, =kernel_main
blx r3
 
// halt
halt:
wfe
b halt
</syntaxhighlight>
</source>
 
The section ".text.boot" will be used in the linker script to place the boot.S as the verryvery first thing in outour kernel image. The code initializes a minimum C environment, which means having a stack and zeroing the BSS segment, before calling the kernel_main function. Note that the code avoids using r0-r2 so the remain valid for the kernel_main call.
 
You can then assemble boot.S using:
===link-arm-eabi.ld===
<source lang=text>
/* link-arm-eabi.ld - linker script for arm eabi */
ENTRY(Start)
 
<syntaxhighlight lang="bash">
SECTIONS
arm-none-eabi-gcc -mcpu=arm1176jzf-s -fpic -ffreestanding -c boot.S -o boot.o
{
</syntaxhighlight>
/* Starts at LOADER_ADDR. */
. = 0x8000;
_start = .;
_text_start = .;
.text :
{
KEEP(*(.text.boot))
*(.text)
}
. = ALIGN(4096); /* align to page size */
_text_end = .;
 
===Pi 2===
_rodata_start = .;
.rodata :
{
*(.rodata)
}
. = ALIGN(4096); /* align to page size */
_rodata_end = .;
 
With newer versions of the Pi, there's a bit more to be done. Raspberry Pis 2 and 3 (the first model that supports 64 bit) have 4 cores. On boot, all cores are running and executing the same boot code. Therefore you have to distinguish cores, and only allow one of them to run, putting the others in an infinite loop.
_data_start = .;
.data :
{
*(.data)
}
. = ALIGN(4096); /* align to page size */
_data_end = .;
 
The environment is set up and execution to _start transferred from [https://github.com/raspberrypi/tools/blob/master/armstubs/armstub7.S#L167 armstub7.s].
_bss_start = .;
<syntaxhighlight lang="text">
.bss :
// AArch32 mode
{
bss = .;
*(.bss)
}
. = ALIGN(4096); /* align to page size */
_bss_end = .;
_end = .;
}
</source>
 
// To keep this in the first portion of the binary.
There is a lot of text here but don't despair. The script is rather simple if you look at it bit by bit.
.section ".text.boot"
 
// Make _start global.
ENTRY(Start) declares the entry point for the kernel image. That symbol was declared in the boot.S file. Since we are actually booting a binary image I think the entry is completly irelevant. But it has to be there in the elf file we build as intermediate file. Declaring it makes the linker happy.
.globl _start
 
.org 0x8000
SECTIONS declares, well, sections. It decides where the bits and pieces of our code and data go and also sets a few symbols that help us track the size of each section.
// Entry point for the kernel.
// r15 -> should begin execution at 0x8000.
// r0 -> 0x00000000
// r1 -> 0x00000C42 - machine id
// r2 -> 0x00000100 - start of ATAGS
// preserve these registers as argument for kernel_main
_start:
// Shut off extra cores
mrc p15, 0, r5, c0, c0, 5
and r5, r5, #3
cmp r5, #0
bne halt
 
// Setup the stack.
<source lang=text>
ldr r5, =_start
. = 0x8000;
mov sp, r5
_start = .;
</source>
 
// Clear out bss.
The "." denotes the current address so the first line tells the linker to set the current address to 0x8000, where the kernel starts. The current address is automatically incremented when the linker adds data. The second line then creates a symbol "_start" and sets it to the current address.
ldr r4, =__bss_start
ldr r9, =__bss_end
mov r5, #0
mov r6, #0
mov r7, #0
mov r8, #0
b 2f
 
1:
After that sections are defined for text (code), read-only data, read-write data and BSS (0 initialized memory). Other than the name the sections are identical so lets just look at one of them:
// store multiple at r4.
stmia r4!, {r5-r8}
 
// If we are still below bss_end, loop.
<source lang=text>
2:
_text_start = .;
cmp r4, r9
.text : {
blo 1b
KEEP(*(.text.boot))
*(.text)
}
. = ALIGN(4096); /* align to page size */
_text_end = .;
</source>
 
// Call kernel_main
The first line creates a _text_start symbol for the section. The second line opens a .text section for the output file which gets closed in the fifth line. Lines 3 and 4 declare what sections from the input files will be placed inside the output .text section. In our case ".text.boot" is to be placed first followed by the more general ".text". ".text.boot" is only used in boot.S and ensures that it ends up at the beginning of the kernel image. ".text" then contains all the remaining code.
ldr r3, =kernel_main
Any data added by the linker automatically increments the current addrress ("."). In line 6 we explicitly increment it so that it is aligned to a 4096 byte boundary (which is the page size for the RPi). And last line 7 creates a _text_end symbol so we know where the section ends.
blx r3
 
// halt
What are the _text_start and _text_end for and why use page alignment? The 2 symbols can be used in the kernel source and the linker will then place the correct addresses into the binary. As an example the _bss_start and _bss_end are used in boot.S. But you can also use the symbols from C by declaring them extern first. While not required I made all sections aligned to page size. This later allows mapping them in the page tables with executable, read-only and read-write permissions without having to handle overlaps (2 sections in one page).
halt:
wfe
b halt
</syntaxhighlight>
 
You can assemble boot.S using:
<source lang=text>
_end = .;
</source>
 
<syntaxhighlight lang="bash">
After all sections are declared the _end symbol is created. If you ever want to know how large your kernel is at runtime you can use _start and _end to find out.
arm-none-eabi-gcc -mcpu=cortex-a7 -fpic -ffreestanding -c boot.S -o boot.o
</syntaxhighlight>
 
===MakefilePi 3, 4===
<source lang=make>
# Makefile - build script */
 
It worth mentioning that Pi 3 and 4 normally boots kernel8.img into 64 bit mode, but you can still use AArch32 with kernel7.img for backward compatibility. Note that in 64 bit mode, the boot code is loaded at 0x80000 and not 0x8000. The boot code in AArch64 is exactly the same for Pi 3 and 4, however Pi 4 has a different peripheral base address (see below the C example code).
# build environment
PREFIX ?= /usr/local/cross
ARMGNU ?= $(PREFIX)/bin/arm-none-eabi
 
With the latest firmware, only the primary core runs (core 0), and the secondary cores are awaiting in a spin loop. To wake them up, write a function's address at 0xE0 (core 1), 0xE8 (core 2) or 0xF0 (core 3) and they will start to execute that function.
# source files
SOURCES_ASM := $(wildcard *.S)
SOURCES_C := $(wildcard *.c)
 
The environment is set up and execution to _start transferred from [https://github.com/raspberrypi/tools/blob/master/armstubs/armstub8.S#L154 armstub8.s].
# object files
<syntaxhighlight lang="text">
OBJS := $(patsubst %.S,%.o,$(SOURCES_ASM))
// AArch64 mode
OBJS += $(patsubst %.c,%.o,$(SOURCES_C))
 
// To keep this in the first portion of the binary.
# Build flags
.section ".text.boot"
DEPENDFLAGS := -MD -MP
INCLUDES := -I include
BASEFLAGS := -O2 -fpic -pedantic -pedantic-errors -nostdlib
BASEFLAGS += -nostartfiles -ffreestanding -nodefaultlibs
BASEFLAGS += -fno-builtin -fomit-frame-pointer -mcpu=arm1176jzf-s
WARNFLAGS := -Wall -Wextra -Wshadow -Wcast-align -Wwrite-strings
WARNFLAGS += -Wredundant-decls -Winline
WARNFLAGS += -Wno-attributes -Wno-deprecated-declarations
WARNFLAGS += -Wno-div-by-zero -Wno-endif-labels -Wfloat-equal
WARNFLAGS += -Wformat=2 -Wno-format-extra-args -Winit-self
WARNFLAGS += -Winvalid-pch -Wmissing-format-attribute
WARNFLAGS += -Wmissing-include-dirs -Wno-multichar
WARNFLAGS += -Wredundant-decls -Wshadow
WARNFLAGS += -Wno-sign-compare -Wswitch -Wsystem-headers -Wundef
WARNFLAGS += -Wno-pragmas -Wno-unused-but-set-parameter
WARNFLAGS += -Wno-unused-but-set-variable -Wno-unused-result
WARNFLAGS += -Wwrite-strings -Wdisabled-optimization -Wpointer-arith
WARNFLAGS += -Werror
ASFLAGS := $(INCLUDES) $(DEPENDFLAGS) -D__ASSEMBLY__
CFLAGS := $(INCLUDES) $(DEPENDFLAGS) $(BASEFLAGS) $(WARNFLAGS)
CFLAGS += -std=c99
 
// Make _start global.
# build rules
.globl _start
all: kernel.img
 
.org 0x80000
include $(wildcard *.d)
// Entry point for the kernel. Registers:
// x0 -> 32 bit pointer to DTB in memory (primary core only) / 0 (secondary cores)
// x1 -> 0
// x2 -> 0
// x3 -> 0
// x4 -> 32 bit kernel entry point, _start location
_start:
// set stack before our code
ldr x5, =_start
mov sp, x5
 
// clear bss
kernel.elf: $(OBJS) link-arm-eabi.ld
ldr x5, =__bss_start
$(ARMGNU)-ld $(OBJS) -Tlink-arm-eabi.ld -o $@
ldr w6, =__bss_size
1: cbz w6, 2f
str xzr, [x5], #8
sub w6, w6, #1
cbnz w6, 1b
 
// jump to C code, should not return
kernel.img: kernel.elf
2: bl kernel_main
$(ARMGNU)-objcopy kernel.elf -O binary kernel.img
// for failsafe, halt this core
halt:
wfe
b halt
 
</syntaxhighlight>
clean:
$(RM) -f $(OBJS) kernel.elf kernel.img
 
Compile your code with:
dist-clean: clean
$(RM) -f *.d
 
<syntaxhighlight lang="bash">
# C.
aarch64-elf-as -c boot.S -o boot.o
%.o: %.c Makefile
</syntaxhighlight>
$(ARMGNU)-gcc $(CFLAGS) -c $< -o $@
 
== Implementing the Kernel ==
# AS.
%.o: %.S Makefile
$(ARMGNU)-gcc $(ASFLAGS) -c $< -o $@
</source>
 
So far we have written the bootstrap assembly stub that sets up the processor such that high level languages such as C can be used. It is also possible to use other languages such as C++.
And there you go. Try building it. A minimum kernel that does absolutely nothing.
 
=== Freestanding and Hosted Environments ===
==Hello World kernel==
 
If you have done C or C++ programming in user-space, you have used a so-called Hosted Environment. Hosted means that there is a C standard library and other useful runtime features. Alternatively, there is the Freestanding version, which is what we are using here. Freestanding means that there is no C standard library, only what we provide ourselves. However, some header files are actually not part of the C standard library, but rather the compiler. These remain available even in freestanding C source code. In this case we use <stddef.h> to get size_t & NULL and <stdint.h> to get the intx_t and uintx_t datatypes which are invaluable for operating systems development, where you need to make sure that the variable is of an exact size (if we used a short instead of uint16_t and the size of short changed, our code would break!). Additionally you can access the <float.h>, <iso646.h>, <limits.h>, and <stdarg.h> headers, as they are also freestanding. GCC actually ships a few more headers, but these are special purpose.
Lets make the kernel do something. Lets say hello to the world using the serial port.
 
===main.c Writing a kernel in C ===
 
The following shows how to create a simple kernel in C. Please take a few moments to understand the code. To set the value for "int raspi" in run-time, see [[Detecting_Raspberry_Pi_Board|detecting the board type]].
<source lang=c>
/* main.c - the entry point for the kernel */
 
<syntaxhighlight lang="cpp">
#include <stddef.h>
#include <stdint.h>
 
static uint32_t MMIO_BASE;
#include <uart.h>
 
// The MMIO area base address, depends on board type
#define UNUSED(x) (void)(x)
static inline void mmio_init(int raspi)
 
{
const char hello[] = "\r\nHello World\r\n";
switch (raspi) {
const char halting[] = "\r\n*** system halting ***";
case 2:
 
case 3: MMIO_BASE = 0x3F000000; break; // for raspi2 & 3
// kernel main function, it all begins here
case 4: MMIO_BASE = 0xFE000000; break; // for raspi4
void kernel_main(uint32_t r0, uint32_t r1, uint32_t atags) {
default: MMIO_BASE = 0x20000000; break; // for raspi1, raspi zero etc.
UNUSED(r0);
UNUSED(r1);}
}
UNUSED(atags);
 
// Memory-Mapped I/O output
uart_init();
static inline void mmio_write(uint32_t reg, uint32_t data)
{
uart_puts(hello);
*(volatile uint32_t*)(MMIO_BASE + reg) = data;
 
// Wait a bit
for(volatile int i = 0; i < 10000000; ++i) { }
 
uart_puts(halting);
}
</source>
 
// Memory-Mapped I/O input
===include/mmio.h===
static inline uint32_t mmio_read(uint32_t reg)
 
{
<source lang=c>
return *(volatile uint32_t*)(MMIO_BASE + reg);
/* mmio.h - access to MMIO registers */
 
#ifndef MMIO_H
#define MMIO_H
 
#include <stdint.h>
 
// write to MMIO register
static inline void mmio_write(uint32_t reg, uint32_t data) {
uint32_t *ptr = (uint32_t*)reg;
asm volatile("str %[data], [%[reg]]"
: : [reg]"r"(ptr), [data]"r"(data));
}
 
// Loop <delay> times in a way that the compiler won't optimize away
// read from MMIO register
static inline uint32_tvoid mmio_readdelay(uint32_tint32_t regcount) {
{
uint32_t *ptr = (uint32_t*)reg;
asm volatile("__delay_%=: subs %[count], %[count], #1; bne __delay_%=\n"
uint32_t data;
: "=r"(count): [count]"0"(count) : "cc");
asm volatile("ldr %[data], [%[reg]]"
: [data]"=r"(data) : [reg]"r"(ptr));
return data;
}
 
enum
#endif // #ifndef MMIO_H
{
</source>
 
 
===include/uart.h===
 
<source lang=c>
/* uart.h - UART initialization & communication */
 
#ifndef UART_H
#define UART_H
 
#include <stdint.h>
 
/*
* Initialize UART0.
*/
void uart_init();
 
/*
* Transmit a byte via UART0.
* uint8_t Byte: byte to send.
*/
void uart_putc(uint8_t byte);
 
/*
* print a string to the UART one character at a time
* const char *str: 0-terminated string
*/
void uart_puts(const char *str);
 
#endif // #ifndef UART_H
</source>
 
===uart.c===
 
<source lang=c>
/* uart.c - UART initialization & communication */
/* Reference material:
* http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf
* Chapter 13: UART
*/
 
#include <stdint.h>
#include <mmio.h>
#include <uart.h>
 
enum {
// The GPIO registers base address.
GPIO_BASE = 0x20200000,
 
// The offsets for reach register.
GPIO_BASE = 0x200000,
 
// Controls actuation of pull up/down to ALL GPIO pins.
Line 345 ⟶ 271:
 
// The base address for UART.
UART0_BASE = (GPIO_BASE + 0x1000), // for raspi4 0xFE201000, raspi2 & 3 0x3F201000, and 0x20201000 for raspi1
UART0_BASE = 0x20201000,
 
// The offsets for reach register for the UART.
Line 366 ⟶ 292:
UART0_ITOP = (UART0_BASE + 0x88),
UART0_TDR = (UART0_BASE + 0x8C),
 
// The offsets for Mailbox registers
MBOX_BASE = 0xB880,
MBOX_READ = (MBOX_BASE + 0x00),
MBOX_STATUS = (MBOX_BASE + 0x18),
MBOX_WRITE = (MBOX_BASE + 0x20)
};
 
// A Mailbox message with set clock rate of PL011 to 3MHz tag
/*
volatile unsigned int __attribute__((aligned(16))) mbox[9] = {
* delay function
9*4, 0, 0x38002, 12, 8, 2, 3000000, 0 ,0
* int32_t delay: number of cycles to delay
};
*
* This just loops <delay> times in a way that the compiler
* wont optimize away.
*/
static void delay(int32_t count) {
asm volatile("1: subs %[count], %[count], #1; bne 1b"
: : [count]"r"(count));
}
/*
* Initialize UART0.
*/
void uart_init() {
// Disable UART0.
mmio_write(UART0_CR, 0x00000000);
// Setup the GPIO pin 14 && 15.
// Disable pull up/down for all GPIO pins & delay for 150 cycles.
mmio_write(GPPUD, 0x00000000);
delay(150);
 
void uart_init(int raspi)
// Disable pull up/down for pin 14,15 & delay for 150 cycles.
{
mmio_write(GPPUDCLK0, (1 << 14) | (1 << 15));
mmio_init(raspi);
delay(150);
 
// Disable UART0.
// Write 0 to GPPUDCLK0 to make it take effect.
mmio_write(GPPUDCLK0UART0_CR, 0x00000000);
// Setup the GPIO pin 14 && 15.
// Clear pending interrupts.
mmio_write(UART0_ICR, 0x7FF);
 
// Disable pull up/down for all GPIO pins & delay for 150 cycles.
// Set integer & fractional part of baud rate.
mmio_write(GPPUD, 0x00000000);
// Divider = UART_CLOCK/(16 * Baud)
delay(150);
// Fraction part register = (Fractional part * 64) + 0.5
// UART_CLOCK = 3000000; Baud = 115200.
 
// Disable pull up/down for pin 14,15 & delay for 150 cycles.
// Divider = 3000000/(16 * 115200) = 1.627 = ~1.
mmio_write(GPPUDCLK0, (1 << 14) | (1 << 15));
// Fractional part register = (.627 * 64) + 0.5 = 40.6 = ~40.
delay(150);
mmio_write(UART0_IBRD, 1);
mmio_write(UART0_FBRD, 40);
 
// Write 0 to GPPUDCLK0 to make it take effect.
// Enable FIFO & 8 bit data transmissio (1 stop bit, no parity).
mmio_write(UART0_LCRHGPPUDCLK0, (1 << 4) | (1 << 5) | (1 << 6)0x00000000);
 
// MaskClear allpending interrupts.
mmio_write(UART0_IMSCUART0_ICR, (1 << 10x7FF) | (1 << 4) | (1 << 5) |;
(1 << 6) | (1 << 7) | (1 << 8) |
(1 << 9) | (1 << 10));
 
// EnableSet UART0, receiveinteger & transferfractional part of UARTbaud rate.
// Divider = UART_CLOCK/(16 * Baud)
mmio_write(UART0_CR, (1 << 0) | (1 << 8) | (1 << 9));
// Fraction part register = (Fractional part * 64) + 0.5
}
// Baud = 115200.
 
// For Raspi3 and 4 the UART_CLOCK is system-clock dependent by default.
/*
// Set it to 3Mhz so that we can consistently set the baud rate
* Transmit a byte via UART0.
if (raspi >= 3) {
* uint8_t Byte: byte to send.
// UART_CLOCK = 30000000;
*/
unsigned int r = (((unsigned int)(&mbox) & ~0xF) | 8);
void uart_putc(uint8_t byte) {
// wait foruntil UARTwe tocan becometalk readyto tothe transmitVC
while ( mmio_read(MBOX_STATUS) & 0x80000000 ) { }
while (1) {
// send our message to property channel and wait for the response
if (!(mmio_read(UART0_FR) & (1 << 5))) {
mmio_write(MBOX_WRITE, r);
break;
while ( (mmio_read(MBOX_STATUS) & 0x40000000) || mmio_read(MBOX_READ) != r ) { }
}
 
}
// Divider = 3000000 / (16 * 115200) = 1.627 = ~1.
mmio_write(UART0_DR, byte);
mmio_write(UART0_IBRD, 1);
// Fractional part register = (.627 * 64) + 0.5 = 40.6 = ~40.
mmio_write(UART0_FBRD, 40);
 
// Enable FIFO & 8 bit data transmission (1 stop bit, no parity).
mmio_write(UART0_LCRH, (1 << 4) | (1 << 5) | (1 << 6));
 
// Mask all interrupts.
mmio_write(UART0_IMSC, (1 << 1) | (1 << 4) | (1 << 5) | (1 << 6) |
(1 << 7) | (1 << 8) | (1 << 9) | (1 << 10));
 
// Enable UART0, receive & transfer part of UART.
mmio_write(UART0_CR, (1 << 0) | (1 << 8) | (1 << 9));
}
 
void uart_putc(unsigned char c)
/*
{
* print a string to the UART one character at a time
// Wait for UART to become ready to transmit.
* const char *str: 0-terminated string
while ( mmio_read(UART0_FR) & (1 << 5) ) { }
*/
mmio_write(UART0_DR, c);
void uart_puts(const char *str) {
while (*str) {
uart_putc(*str++);
}
}
</source>
 
unsigned char uart_getc()
===Booting the kernel===
{
// Wait for UART to have received something.
while ( mmio_read(UART0_FR) & (1 << 4) ) { }
return mmio_read(UART0_DR);
}
 
void uart_puts(const char* str)
Do you still have the SD card with the original raspian image on it from when you where testing the hardware above? Great. So you already have a SD card with a boot partition and the required files. If not then download one of the original raspberry boot images and copy them to the SD card.
{
for (size_t i = 0; str[i] != '\0'; i ++)
uart_putc((unsigned char)str[i]);
}
 
#if defined(__cplusplus)
Now mount the first partition from the SD card and look at it:
extern "C" /* Use C linkage for kernel_main. */
#endif
 
#ifdef AARCH64
<source lang=text>
// arguments for AArch64
bootcode.bin fixup.dat kernel.img start.elf
void kernel_main(uint64_t dtb_ptr32, uint64_t x1, uint64_t x2, uint64_t x3)
cmdline.txt fixup_cd.dat kernel_cutdown.img start_cd.elf
#else
config.txt issue.txt kernel_emergency.img
// arguments for AArch32
</source>
void kernel_main(uint32_t r0, uint32_t r1, uint32_t atags)
#endif
{
// initialize UART for Raspi2
uart_init(2);
uart_puts("Hello, kernel World!\r\n");
 
while (1)
Simplified when the RPi powers up the ARM cpu is halted and the GPU runs. The GPU loads the bootloader from rom and executes it. That then finds the SD card and loads the bootcode.bin. The bootcode handles the config.txt and cmdline.txt (or does start.elf read that?) and then runs start.elf. start.elf loads the kernel.img and at last the ARM cpu is started running that kernel image.
uart_putc(uart_getc());
}
</syntaxhighlight>
 
The GPU bootloader passes arguments to the AArch32 kernel via r0-r2 and the boot.S makes sure to preserve those 3 registers. They are the first 3 arguments in a C function call. The argument r0 contains a code for the device the RPi was booted from. This is generally 0 but its actual value depends on the firmware of the board. r1 contains the 'ARM Linux Machine Type' which for the RPi is 3138 (0xc42) identifying the BCM2708 CPU. A full list of ARM Machine Types is available from [http://www.arm.linux.org.uk/developer/machines/ here]. r2 contains the address of the ATAGs.
So now we replace the original kernel.img with out own, umount, sync, stick the SD card into RPi and turn the power on.
Your minicom should then show the following:
 
For AArch64, the registers are a little bit different, but also passed as arguments to the C function. The first, x0 is the 32 bit address of the DTB (that is, [https://elinux.org/Device_Tree_Reference Device Tree Blob] in memory). Watch out, it is a 32 bit address, the upper bits may not be cleared. The other arguments, x1-x3 are cleared to zero for now, but reserved for future use. Your boot.S should preserve them.
<source lang=text>
 
Notice how we wish to use the common C function strlen, but this function is part of the C standard library that we don't have available. Instead, we rely on the freestanding header <stddef.h> to provide size_t and we simply declare our own implementation of strlen. You will have to do this for every function you wish to use (as the freestanding headers only provide macros and data types).
Hello World
*** system halting ***
</source>
 
The addresses for the GPIO and UART are offsets from the peripheral base address, which is 0x20000000 for Raspberry Pi 1 and 0x3F000000 for Raspberry Pi 2 and Raspberry Pi 3. For [[Raspberry Pi 4]] the base address is 0xFE000000. You can find the addresses of registers and how to use them in the BCM2835 manual. It is possible to detect the base address in run time by [[Detecting_Raspberry_Pi_Board|reading the board id]].
===Running the kernel under QEMU===
 
Compile using:
Although vanilla QEMU does not yet support the RaspberryPi hardware, there is [https://github.com/Torlus/qemu/tree/rpi a fork by Torlus] that emulates the RPi hardware sufficiently enough to get started with ARM kernel development. To build QEMU on linux, do as follows:
 
<sourcesyntaxhighlight lang=text"bash">
arm-none-eabi-gcc -mcpu=arm1176jzf-s -fpic -ffreestanding -std=gnu99 -c kernel.c -o kernel.o -O2 -Wall -Wextra
mkdir qemu-build
</syntaxhighlight>
cd qemu-build
git clone https://github.com/Torlus/qemu/tree/rpi src
mkdir build
cd build
../src/configure --prefix=$YOURINSTALLLOCATION --target-list=arm-softmmu,arm-linux-user,armeb-linux-user --enable-sdl
make && sudo make install
</source>
 
or for 64 bit:
With qemu you do not need to objcopy the kernel into a plain binary; QEMU also supports ELF kernels:
 
<sourcesyntaxhighlight lang=text"bash">
aarch64-elf-gcc -ffreestanding -c kernel.c -o kernel.o -O2 -Wall -Wextra
$YOURINSTALLLOCATION/bin/qemu-system-arm -kernel kernel.elf -cpu arm1176 -m 256 -M raspi -serial stdio
</syntaxhighlight>
</source>
 
Note that the above code uses a few extensions and hence we build as the GNU version of C99.
Note that currently the QEMU "raspi" emulation may incorrectly load the kernel binaries at 0x10000 instead of 0x8000, so if you do not see any output, try adjusting the base address constant in the linker script.
 
== Linking the Kernel ==
==Echo kernel==
 
To create the full and final kernel we will have to link these object files into the final kernel program. When developing user-space programs, your toolchain ships with default scripts for linking such programs. However, these are unsuitable for kernel development and we need to provide our own customized linker script.
The hello world kernel shows how to do output to the UART. Next lets do some input. And to see that the input works we simply echo the input as output. A simple echo kernel.
 
The linker script for 64 bit mode looks exactly the same, except for the starting address.
In include/uart.h add the following:
 
<sourcesyntaxhighlight lang=c"text">
ENTRY(_start)
/*
* Receive a byte via UART0.
*
* Returns:
* uint8_t: byte received.
*/
uint8_t uart_getc();
</source>
 
SECTIONS
In uart.c add the following:
{
/* Starts at LOADER_ADDR. */
. = 0x8000;
/* For AArch64, use . = 0x80000; */
__start = .;
__text_start = .;
.text :
{
KEEP(*(.text.boot))
*(.text)
}
. = ALIGN(4096); /* align to page size */
__text_end = .;
 
__rodata_start = .;
<source lang=c>
.rodata :
/*
{
* Receive a byte via UART0.
*(.rodata)
*
* Returns:
* uint8_t: byte received.
*/
uint8_t uart_getc() {
// wait for UART to have recieved something
while(true) {
if (!(mmio_read(UART0_FR) & (1 << 4))) {
break;
}
}
. = ALIGN(4096); /* align to page size */
return mmio_read(UART0_DR);
__rodata_end = .;
 
__data_start = .;
.data :
{
*(.data)
}
. = ALIGN(4096); /* align to page size */
__data_end = .;
 
__bss_start = .;
.bss :
{
bss = .;
*(.bss)
}
. = ALIGN(4096); /* align to page size */
__bss_end = .;
__bss_size = __bss_end - __bss_start;
__end = .;
}
</syntaxhighlight>
</source>
 
There is a lot of text here but don't despair. The script is rather simple if you look at it bit by bit.
And last in main.c put the following:
 
ENTRY(_start) declares the entry point for the kernel image. That symbol was declared in the boot.S file. Since we are actually booting a binary image, the entry is completely irrelevant, but it has to be there in the elf file we build as intermediate file.
<source lang=c>
const char hello[] = "\r\nHello World, feel the echo\r\n";
b
// kernel main function, it all begins here
void kernel_main(uint32_t r0, uint32_t r1, uint32_t atags) {
UNUSED(r0);
UNUSED(r1);
UNUSED(atags);
 
SECTIONS declares sections. It decides where the bits and pieces of our code and data go and also sets a few symbols that help us track the size of each section.
uart_init();
 
<syntaxhighlight lang="text">
uart_puts(hello);
. = 0x8000;
__start = .;
</syntaxhighlight>
 
The "." denotes the current address so the first line tells the linker to set the current address to 0x8000 (or 0x80000), where the kernel starts. The current address is automatically incremented when the linker adds data. The second line then creates a symbol "__start" and sets it to the current address.
while (1) {
 
uart_putc(uart_getc());
After that sections are defined for text (code), read-only data, read-write data and BSS (0 initialized memory). Other than the name the sections are identical so lets just look at one of them:
 
<syntaxhighlight lang="text">
__text_start = .;
.text : {
KEEP(*(.text.boot))
*(.text)
}
. = ALIGN(4096); /* align to page size */
}
__text_end = .;
</source>
</syntaxhighlight>
 
The first line creates a __text_start symbol for the section. The second line opens a .text section for the output file which gets closed in the fifth line. Lines 3 and 4 declare what sections from the input files will be placed inside the output .text section. In our case ".text.boot" is to be placed first followed by the more general ".text". ".text.boot" is only used in boot.S and ensures that it ends up at the beginning of the kernel image. ".text" then contains all the remaining code. Any data added by the linker automatically increments the current address ("."). In line 6 we explicitly increment it so that it is aligned to a 4096 byte boundary (which is the page size for the RPi). And last line 7 creates a __text_end symbol so we know where the section ends.
 
What are the __text_start and __text_end for and why use page alignment? The 2 symbols can be used in the kernel source and the linker will then place the correct addresses into the binary. As an example the __bss_start and __bss_end are used in boot.S. But you can also use the symbols from C by declaring them extern first. While not required I made all sections aligned to page size. This later allows mapping them in the page tables with executable, read-only and read-write permissions without having to handle overlaps (2 sections in one page).
 
<syntaxhighlight lang="text">
__end = .;
</syntaxhighlight>
 
After all sections are declared the __end symbol is created. If you ever want to know how large your kernel is at runtime you can use __start and __end to find out.
 
With these components you can now actually build the final kernel. We use the compiler as the linker as it allows it greater control over the link process. Note that if your kernel is written in C++, you should use the C++ compiler instead.
 
You can then link your kernel using:
 
<syntaxhighlight lang="bash">
arm-none-eabi-gcc -T linker.ld -o myos.elf -ffreestanding -O2 -nostdlib boot.o kernel.o -lgcc
arm-none-eabi-objcopy myos.elf -O binary kernel7.img
</syntaxhighlight>
 
or for 64 bit:
 
<syntaxhighlight lang="bash">
aarch64-elf-gcc -T linker.ld -o myos.elf -ffreestanding -O2 -nostdlib boot.o kernel.o -lgcc
aarch64-elf-objcopy myos.elf -O binary kernel8.img
</syntaxhighlight>
 
== Booting the Kernel ==
 
In a few moments, you will see your kernel in action.
 
=== Testing your operating system (Real Hardware) ===
 
Do you still have the SD card with the original Raspbian image on it from when you where testing the hardware above? Great. So you already have a SD card with a boot partition and the required files. If not then download one of the original Raspberry boot images and copy them to the SD card.
 
Now mount the first partition from the SD card and look at it:
 
<syntaxhighlight lang="text">
bootcode.bin fixup.dat kernel.img start.elf
cmdline.txt fixup_cd.dat kernel_cutdown.img start_cd.elf
config.txt issue.txt kernel_emergency.img
</syntaxhighlight>
 
If you don't have a raspbian image, you can create a FAT32 partition, and [https://github.com/raspberrypi/firmware/tree/master/boot download the firmware files] from the official repository. You'll need only three files:
 
* bootcode.bin: this is the one that's loaded first, executed on the GPU (not needed on RPi4 as that model has bootcode.bin in a ROM)
* fixup.dat: this data file contains important hardware-related information, a must have
* start.elf: this is the RPi firmware (same as BIOS on IBM PC). This also runs on the GPU.
 
Simplified when the RPi powers up the ARM CPU is halted and the GPU runs. The GPU loads the bootloader from ROM and executes it. That then finds the SD card and loads the bootcode.bin (except RPi4 which has a big enough ROM to include bootcode.bin as well). The bootcode loads the firmware, start.elf which handles the config.txt and cmdline.txt. The start.elf loads the kernel*.img and at last the ARM CPU is started running that kernel image.
 
To switch among ARM modes, you have to rename your kernel.img file. If you rename it to '''kernel7.img''', that will be executed in AArch32 mode (ARMv7). For AArch64 mode (ARMv8) you'll have to rename it to '''kernel8.img'''.
 
So now we replace the original kernel.img with our own, umount, sync, stick the SD card into RPi and turn the power on.
Your Minicom should then show the following:
 
<syntaxhighlight lang="text">
Hello, kernel World!
</syntaxhighlight>
 
=== Testing your operating system (QEMU) ===
 
QEMU supports emulating Raspberry Pi 2 with the machine type "raspi2". At the time of writing this feature is not available in most package managers but can be found in the latest QEMU source found here: https://github.com/qemu/qemu
 
Check that your QEMU install has qemu-system-arm and that it supports the option "-M raspi2". When testing in QEMU, be sure to use the raspi2 base addresses noted in the source code.
 
With QEMU you do not need to objcopy the kernel into a plain binary; QEMU also supports ELF kernels:
 
<syntaxhighlight lang="text">
$YOURINSTALLLOCATION/bin/qemu-system-arm -m 256 -M raspi2 -serial stdio -kernel kernel.elf
</syntaxhighlight>
 
==== Updated Support for AArch64 (raspi2, raspi3) ====
As of QEMU 2.12 (April 2018), emulation for 64-bit ARM, ''qemu-system-aarch64'', now supports direct emulation of both Raspberry Pi 2 and 3 using the machine types '''raspi2''' and '''raspi3''', respectively. This should allow for testing of 64-bit system code.
 
<syntaxhighlight lang="bash">
qemu-system-aarch64 -M raspi3 -serial stdio -kernel kernel8.img
</syntaxhighlight>
 
Note that in most cases, there will be few if any differences between 32-bit ARM code and 64-bit ARM, but there can be difference in the way the code behaves, in particular regarding kernel memory management. Also, some AArch64 implementations may support features not found on any of their 32-bit counterparts (e.g., cryptographic extensions, enhanced NEON SIMD support).
 
Another very important note: starting from Raspberry Pi 3, the SoC is changed to [https://github.com/raspberrypi/documentation/files/1888662/ BCM2837] and PL011 clock (UART0) is not fixed any more, but derived from the system clock. Therefore to properly set up baud rate, first you have to set clock frequency. This can be done with a [https://github.com/raspberrypi/firmware/wiki/Mailboxes Mailbox call]. Or you can use AUX miniUART (UART1) chip, which is easier to program. The links below includes tutorials on how to do both.
 
== See Also ==
 
=== Articles ===
* [[Raspberry Pi Bare Bones Rust]]
* [[ARMv7-A Bare Bones]]
 
=== External Links ===
* [http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf BCM2835 ARM Peripherals] (original Raspberry Pi)
* [https://github.com/raspberrypi/documentation/files/1888662/ BCM2837 ARM Peripherals] (latest Raspberry Pi 3)
* [http://infocenter.arm.com/help/topic/com.arm.doc.ddi0183g/DDI0183G_uart_pl011_r1p5_trm.pdf PrimeCell UART (PL011) Technical Reference Manual]
* [https://github.com/s-matyukevich/raspberry-pi-os Raspberry-Pi-OS a hobby OS tutorial for the Raspberry Pi] (details Linux drivers too, great source)
* [https://github.com/bztsrc/raspi3-tutorial Bare metal tutorial for AArch64]
 
[[Category:ARM]][[Category:ARM_RaspberryPi]]
[[Category:Raspberry Pi]]
[[Category:Bare bones tutorials]]
[[Category:C]]
[[Category:C++]]