0
0
Cnc-programmingHow-ToBeginner · 4 min read

How to Enable and Disable Cache in ARM Processors

To enable or disable cache in ARM processors, modify the System Control Register (SCTLR) by setting or clearing the cache enable bits (bit 2 for data cache and bit 12 for instruction cache). This is typically done using assembly instructions to read, modify, and write back the SCTLR value.
📐

Syntax

The cache control in ARM is managed through the System Control Register (SCTLR). Key bits are:

  • Bit 2 (C bit): Enables or disables the data cache.
  • Bit 12 (I bit): Enables or disables the instruction cache.

To change cache settings, you read the SCTLR, modify these bits, and write it back.

armasm
MRC p15, 0, r0, c1, c0, 0  ; Read SCTLR into r0
ORR r0, r0, #(1 << 2)       ; Set bit 2 to enable data cache
ORR r0, r0, #(1 << 12)      ; Set bit 12 to enable instruction cache
MCR p15, 0, r0, c1, c0, 0  ; Write back to SCTLR
💻

Example

This example shows how to enable both data and instruction caches by setting the appropriate bits in the SCTLR register.

armasm
    .text
    .global enable_cache

enable_cache:
    MRC p15, 0, r0, c1, c0, 0      @ Read SCTLR
    ORR r0, r0, #(1 << 2)          @ Enable data cache (bit 2)
    ORR r0, r0, #(1 << 12)         @ Enable instruction cache (bit 12)
    MCR p15, 0, r0, c1, c0, 0      @ Write back SCTLR
    BX lr                          @ Return
⚠️

Common Pitfalls

Common mistakes when enabling or disabling cache in ARM include:

  • Not disabling interrupts or caches before changing cache settings, which can cause unpredictable behavior.
  • Forgetting to invalidate caches after disabling them, leading to stale data.
  • Modifying SCTLR bits incorrectly, such as clearing the wrong bits or not preserving other bits.

Always ensure proper sequence: disable caches, invalidate caches, change settings, then enable caches.

armasm
    @ Wrong: Directly clearing cache bits without invalidation
    MRC p15, 0, r0, c1, c0, 0      @ Read SCTLR
    BIC r0, r0, #(1 << 2)          @ Disable data cache (bit 2) without invalidation
    MCR p15, 0, r0, c1, c0, 0      @ Write back SCTLR

    @ Right: Invalidate caches before disabling
    BL invalidate_caches           @ Call cache invalidation routine
    MRC p15, 0, r0, c1, c0, 0      @ Read SCTLR
    BIC r0, r0, #(1 << 2)          @ Disable data cache
    MCR p15, 0, r0, c1, c0, 0      @ Write back SCTLR
📊

Quick Reference

BitNameFunction
2CData Cache Enable (1 = enable, 0 = disable)
12IInstruction Cache Enable (1 = enable, 0 = disable)

Key Takeaways

Modify the System Control Register (SCTLR) bits 2 and 12 to enable or disable data and instruction caches.
Always invalidate caches before disabling them to avoid stale data issues.
Use assembly instructions MRC and MCR to read and write the SCTLR register safely.
Preserve other SCTLR bits when changing cache settings to avoid unintended side effects.