cachingembeddedbootloaderu-bootflash-memory

Why must we flush the data cache after copying code from flash to RAM?


In an embedded system, a bootloader is used to initialise the board and load the image. Usually, a bootloader runs in norflash during the first stage and needs to copy itself (.text+.date code) from flash to RAM, then jump to RAM to execute code.

My question is: when copying code from flash to RAM with cache enabled, why must we flush the data cache and invalidate the instruction cache? I found uboot and other bootloaders execute this operation, but if I don't do that, could the system still boot successfully?


Solution

  • Simple embedded MCUs usually do not have any means to "snoop" the bus checking if anybody (even itself) invalidates cache contents with writes to cached memory addresses.

    If your MCU has separate data and instruction caches (which most modern MCUs have) and you copy code as data from flash to RAM, you need to flush the data cache (to ensure everything you copied is physically written to RAM) and invalidate the instruction cache (which might contain "old" information from before the copy) to really execute the code you just copied instead of executing what was there before and still resides in instruction cache.

    You might get away not doing the latter if you can be sure your MCU has never "seen" the memory area before you just copied (since it will not have cached anything and needs to physically read RAM anyway), but it's good practice to do data cache flushes and instruction cache invalidation nevertheless to stay on the safe side.

    Copying code from flash to RAM is a special case of self modifying code and you as a programmer need to make sure it's doing no damage.