Search code examples
cpucpu-architectureresetbootloaderboot

How is the instruction memory initialized?


In my book, in the chapter where they create the CPU (chapter 7), they already assume that the instruction memory contains the instructions in machine code.

In an earlier chapter (chapter 6) this is written about start-up:

On start-up, the processor jumps to the reset vector and begins execution boot loader code in supervisor mode. The boot loader typically configures the memory system, initializes the stack pointer, and reads the OS from disk; then it begins a much longer boot process in the OS. The OS eventually will load a program, change to unprivileged user mode, and jump to the start of the program.

But from what I understand the reset vector and the boot loader code must be in memory? Is this correct? Has my book skipped a part before the CPU jumps to the reset vector, and forgot about how the reset vector and bootloader are loaded into memory? How does the CPU get them into memory?


Solution

    • All CPUs have a fixed start address. This is set in hardware (maybe you can configure it through jumpers but that's it, because the CPU has to start somewhere).

    • The first instructions are again set in hardware, at such fixed address, usually through a hard coded memory (like a flash). There likely is a piece of hardware that translates accesses to an address-based location to flash (NAND memory), so that means that the flash, even if it's not part of the CPU, is memory mapped.

    • Some processors do a memory remap, meaning that you will have those addresses accessible for other things, as you likely don't need the first stage bootloader anymore.

    We can explore further by taking as an example the STM32 boot process:

    Configurable boot mode though physical pins and jumpers:

    enter image description here

    This means that the CPU can start fetching instructions at startup from different locations, defined by those pins.

    Factory bootloader:

    The bootloader is stored in the internal boot ROM (system memory part of the flash) of any STM32 device, and is programmed by ST during production. Its main task is to download the application program to the internal flash memory through one of the available serial peripherals, such as USART, CAN, USB, I2C, or SPI.

    So this means that if the factory bootloader is selected, the CPU will start execute a program that then, by means of the selected communication protocol (USART, CAN etc..) can fetch a program from another device. This is useful if you have another processor needed to program your device once already mounted on the PCB.

    Another option - Write directly to the internal flash

    Another option is to select the internal flash. Since this is a persistent memory it can be programmed externally and when the CPU will start it will find, at 0x8000000, the first instruction to execute. The last section of the page that I linked explain the boot process.