Nios® II Software Developer Handbook

ID 683525
Date 8/28/2023
Public
Document Table of Contents

10.5. Cache Considerations for Writing Program Loaders

Software that writes instructions to memory, such as program loaders, needs to ensure that old instructions are flushed from the instruction cache and processor pipeline. This flushing is accomplished with the flushi and flushp instructions, respectively. Additionally, if new instruction(s) are written to memory using store instructions that do not bypass the data cache, you must use the flushd instruction to flush the new instruction(s) from the data cache to memory.

Example 9–4. Assembly Code That Writes a New Instruction to Memory

/*
* Assume new instruction in r4 and
* instruction address already in r5.
*/
stw r4, 0(r5)
flushd 0(r5)
flushi r5
flushp
Note: Notice that this example uses the stw/flushd pair instead of the stwio instruction. The stwio instruction does not flush the data cache, and therefore might leave stale data in the data cache.

The stw instruction writes the new instruction in r4 to the instruction address specified by r5. If a data cache is present, the instruction is written just to the data cache and the associated line is marked dirty. The flushd instruction writes the data cache line associated with the address in r5 to memory and invalidates the corresponding data cache line. The flushi instruction invalidates the instruction cache line associated with the address in r5. Finally, the flushp instruction ensures that the processor pipeline has not prefetched the old instruction at the address specified by r5.

This code sequence is correct for all Nios® II implementations. If a Nios® II core does not have a particular kind of cache, the corresponding flush instruction (flushd or flushi) is executed as a nop.