Accessing flash memory from the bootloader

In Chapter 3, All About Bootloaders, I mentioned the need for the bootloader to load kernel binaries and other images from various flash devices and to be able to perform system maintenance tasks such as erasing and reprogramming flash memory. It follows that the bootloader must have the drivers and infrastructure to support read, erase, and write operations on the type of memory you have, whether it be NOR, NAND, or managed. I will use U-Boot in the following example; other bootloaders follow a similar pattern.

U-Boot has drivers for NOR CFI chips in drivers/mtd and has the commands erase to erase memory and cp.b to copy data byte by byte, programming the flash. Suppose that you have NOR flash memory mapped from 0x40000000 to 0x48000000, of which 4MiB starting at 0x40040000 is a kernel image, then you would load a new kernel into flash using these U-Boot commands:

The variable filesize in the preceding example is set by the tftpboot command to the size of the file just downloaded.

For NAND flash, you need a driver for the NAND flash controller on your SoC, which you can find in drivers/mtd/nand. You use the nand command to manage the memory using the sub-commands erase, write, and read. This example shows a kernel image being loaded into RAM at 0x82000000 and then placed into flash starting at offset 0x280000:

U-Boot can also read files stored in the JFFS2, YAFFS2, and UBIFS filesystems.

U-Boot has drivers for several MMC controllers in drivers/mmc. You can access the raw data using mmc read and mmc write at the user interface level, which allows you to handle raw kernel and filesystem images.

U-boot can also read files from the FAT32 and ext4 filesystems on MMC storage.