Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

6.3 Initializing the Address Translation Page Tables

Following the runtime modifications of the address translation infrastructure, the next primary task inside the head.S execution path is the initialization of the translation page tables, preparing the hardware platform to engage the core virtual memory management sub-blocks. This early paging matrix is constructed by invoking the __create_page_tables subroutine. It must be explicitly noted that these initial translation page tables are transient, meaning they are utilized strictly during the early bootstrap phase.

Prior to stepping into this subroutine, register r8 preserves the physical-to-virtual address translation offset delta, r9 holds the hardware CPU ID signature, and r10 targets the resolved processor metadata record. To systematically analyze the software workflow of this page table creation utility, it is necessary to detail the structural alignment of the ARM page table architecture.

The physical base boundary hosting these temporary translation page tables aligns with the memory coordinates assigned to the static symbol swapper_pg_dir. This tracking symbol evaluates precisely to:

swapper_pg_dir = KERNEL_RAM_VADDR - PG_DIR_SIZE

Where the macro definitions track as:

KERNEL_RAM_VADDR = PAGE_OFFSET + TEXT_OFFSET

Here, TEXT_OFFSET defines the physical compile-time starting alignment offset of the active .text instruction section relative to the baseline bank origin. Consequently, KERNEL_RAM_VADDR represents the absolute starting virtual address allocating the executable Linux kernel code segment. This implies that a dedicated physical memory window equal to exactly TEXT_OFFSET bytes isolates the absolute starting boundary of kernel space (PAGE_OFFSET) from the actual entry code of the kernel image.

Beyond being carved out to house the early level-1 translation page tables, this linear memory cushion stores the runtime boot argument vectors or DTB payloads handed down from the U-BOOT bootloader stage. Under standard ARM configuration templates, TEXT_OFFSET defaults to 0x8000 (32 KB) and PG_DIR_SIZE is fixed to 0x4000 (16 KB). Depending on the platform architecture and memory constraints, these dimensions can be adjusted by developers, provided they remain sufficiently large to prevent address collisions or data corruption with the trailing kernel binary blocks.

Through direct calculation, the starting virtual coordinates mapping the early translation page table array evaluate to:

swapper_pg_dir = PAGE_OFFSET + TEXT_OFFSET - PG_DIR_SIZE

The true, live physical base address allocating this table on the hardware is resolved by using the translation delta:

PHYS_OFFSET + TEXT_OFFSET - PG_DIR_SIZE

This physical mapping layout is visualized across both address domains in the schematics below:

Figure 6-4 Positional Allocation Examples of the Page Table in Virtual and Physical Address Spaces

Figure 6-5 Physical Base Address Allocation of the Early Page Table

The structures packed into this early table block are processed exclusively during the initial stages of the kernel lifecycle. Once the memory management module becomes fully operational, the system completely overwrites and reallocates the active page tables to drive the runtime memory tracking engines of the mainline Linux system.

6.3.1 ARM Page Tables

The Memory Management Unit (MMU) leverages page tables to execute runtime address translations. A page table is a structured lookup array composed of either 32-bit or 64-bit entries; tables using 32-bit entries are defined as Short-descriptor format tables, whereas tables implementing 64-bit entries are defined as Long-descriptor format tables. Each discrete descriptor entry maps an explicit virtual address window to its corresponding physical address boundaries, dictates the size envelope of that mapped region, and configures its low-level memory attributes and access control permissions. Whether the MMU parses translation lookups using the Short-descriptor or Long-descriptor format is governed strictly by the EAE (Extended Address Enable) bit inside the TTBCR (Translation Table Base Control Register). When the EAE bit is cleared to 0, the MMU parses Short-descriptors; when set to 1, it enforces Long-descriptors.

The 32-bit ARM memory management subsystem natively supports both two-tier and three-tier translation page table cascades. Short-descriptor tables can be scaled to handle both single-tier and two-tier translation flows, whereas Long-descriptor layouts are processed exclusively within three-tier translation architectures; both descriptor formats can be scaled to address a 40-bit physical address space. Through these translation tables, the MMU can perform address translations over block units configured as sections (1 MB), supersections (16 MB), small pages (4 KB), or large pages (64 KB). Within the Linux kernel, the early bootstrap phase manages address translations strictly at a section-level (1 MB) granularity; once the baseline subsystem initializations conclude, the primitive operational unit shifts down to a standard page-level (4 KB) allocation model.

Varying the target translation unit changes the binary layout of the page table descriptors, and the bit definitions of a level-1 descriptor differstrictly from those of a level-2 descriptor. Short-descriptor page tables routing level-1 translations can be formatted into four distinct descriptors mapping pages, sections, or supersections. On ARM processors enabling 40-bit Large Physical Address Extensions (LPAE), the level-1 Short-descriptor layout implements the four binary configurations shown in Figure 6-6, where the initial bit configuration designates an invalid descriptor slot:

Figure 6-6 Short-Descriptor Formats for ARM supporting 40-Bit Address Spaces

Conversely, on legacy ARM platforms that do not implement the 40-bit extended physical addressing space, the level-1 Short-descriptor formats follow the four binary alignments detailed in Figure 6-7, where the initial bit configuration designates an invalid descriptor slot:

Figure 6-7 Short-Descriptor Formats for ARM supporting only 32-Bit Address Spaces

When bit 1 of the descriptor contains a logic value of 1, the entry is parsed as a section or supersection descriptor; under this state, bit 18 is interrogated to differentiate between a 1 MB section and a 16 MB supersection. The Non-Secure (NS) bit configures the cryptographic security profile of the targeted memory segment, where NS = 0 restricts the mapped region to secure memory space, and NS = 1 exposes the block to non-secure space. The marker SBZ indicates that the corresponding bit fields are Should Be Zero. The Privileged Execute-Never (PXN) bit determines whether privileged software threads can execute code within the target memory region, and the Execute-Never (XN) flag completely fences off the block to prevent machine instruction execution under any execution state.

The composite binary configurations of the TEX, C, and B bits define memory behavior attributes, specifying parameters such as inner/outer cacheability and hardware bus shareability. The Access Permission (AP) bitmask dictates the read/write privileges governing the memory region, controlling whether a page is read-only or read-write across different execution privilege rings. While these permission and attribute flags regulate instruction access and memory barriers, they do not directly alter address calculation loops. The actual arithmetic conversion vectors are managed entirely by the high-order physical base address bits and the upper address extensions (PA[39:32]).

When a level-1 descriptor targets a 1 MB section or 16 MB supersection, the translation maps the coordinate directly via a single-tier lookup phase. Conversely, when a descriptor maps to a standard 4 KB page or 64 KB large page, the translation loop requires a secondary level-2 page table lookup. Figure 6-8 maps out the Short-descriptor formatting rules deployed across level-2 translation tables, where the initial entry configuration represents an invalid descriptor slot:

Figure 6-8 Page Table Formats Deployed Across Level-2 Translations

A large page descriptor defines the upper 16 bits of the physical address, mapping out a minimum translation step resolution equal to 2³²⁻¹⁶ = 64 KB. A standard small page descriptor registers the upper 20 bits of the target physical coordinate, yielding a primitive translation resolution equal to exactly 2³²⁻²⁰ = 4 KB.

6.3.2 Address Translation Paradigms

Having established the layout rules of the individual descriptor types, this section evaluates the technical mechanics through which a Virtual Address (VA) is parsed and translated into a final Physical Address (PA). Because the Linux kernel environment optimizes its execution pipelines by predominantly using section descriptors and small page descriptors, these two specific paging models are analyzed here to illustrate how the ARM memory management hardware maps out target address spaces.

Figure 6-9 Virtual-to-Physical Address Translation Pipeline via 1 MB Section Descriptors

When the MMU is configured to route address lookups over a single-tier section profile, the upper 12 bits of the incoming virtual address (VA[31:20]) are combined with the upper 18 bits of the Translation Table Base Register (TTBRx[31:14]) to construct the upper 30 bits of the physical address targeting the level-1 descriptor entry (L1A). Within this calculated pointer address, VA[31:20] aligns with bits L1A[13:2], the upper 18 bits derived from the tracking register fill bits L1A[31:14], and the trailing bits are cleared to L1A[1:0] = 00. This geometric alignment ensures that every possible virtual address path cleanly addresses a specific 32-bit (4-byte) descriptor slot within the page table array.

The hardware interfaces directly with memory using this composite index address L1A[31:0] to poll the level-1 page table, fetching the 32-bit descriptor word L1O[31:0]. The upper 12 bits extracted from this descriptor (L1O[31:20]) are then concatenated with the lower 20 bits of the original virtual address (VA[19:0]) to form the definitive physical address (PA[31:0]) of the memory cell. Concurrently, the lower bits (L1O[19:0]) are parsed by the memory controller to enforce the localized attributes and access barriers assigned to that segment.

If the translation resolution is scaled down to map small pages or large pages, necessitating a finer subdivision of the virtual address space, the platform engages a two-tier translation cascade. This multi-stage translation pipeline is organized as illustrated in the schematic below:

Figure 6-10 Virtual-to-Physical Address Translation Pipeline via 4 KB Page Descriptors

Initially, the high-order bits VA[31:20] of the incoming virtual address are combined with the register configurations inside TTBRx[31:14] to isolate the target bit array L1A[31:2], clearing the lower bits to 00 to format a valid level-1 look-up pointer L1A. The MMU issues a physical memory access transaction using L1A to retrieve the level-1 page table descriptor payload L1O[31:0].

Instead of addressing raw physical memory, the upper bits of this descriptor (L1O[31:10]) are combined with the middle bits of the original virtual address (VA[19:12]) to construct the address segment L2A[31:2]. The lower bounds are zeroed out to L2A[1:0] = 00 to form the definitive address pointing to a specific level-2 page table descriptor slot. The MMU polls this level-2 table to extract the final descriptor word L2O[31:0].

At the terminal execution step, the definitive physical address is assembled by mapping the upper 20 bits directly from the level-2 descriptor (PA[31:12] = L2O[31:12]) and copying the remaining low-order bits straight from the original virtual address offset (PA[11:0] = VA[11:0]), concluding the two-tier virtual-to-physical address translation loop.

In practice, the system hardware does not perform a slow physical table walk across memory for every single memory instruction. The ARM microarchitecture incorporates a specialized hardware cache known as the Translation Lookaside Buffer (TLB). Before initiating an automated page table walk over physical RAM, the MMU's internal lookup engines interrogate the TLB to check if an active virtual-to-physical address translation pair (VA -> PA) is already cached. If a valid entry matches the query, the MMU immediately uses the cached physical address to speed up execution. If a cache miss occurs, the hardware falls back to run the complete multi-stage page table walk detailed above.

6.3.3 Linux Initial Page Tables

During the address translation process, the Linux kernel employs a multi-tiered translation cascade consisting of five discrete page table layers: PGD, P4D, PUD, PMD, and PTE. The PGD (Page Global Directory) serves as the top-level page table responsible for managing the entire virtual address space allocation.

The subsequent intermediate layers—encompassing the P4D (Page 4th Level Directory), PUD (Page Upper Directory), and PMD (Page Middle Directory)—are leveraged to implement multi-stage mid-level address translation loops. Among these, the PMD functions as the immediate parent page table routing down to the PTE layer, providing the tracking vectors required to resolve the base addresses of individual PTE pools. Finally, the PTE (Page Table Entry) layer acts as the definitive, lowest-tier level within the translation hierarchy; the Linux memory management engine interrogates the individual entries within the PTE to retrieve the final physical address matching the requested virtual address block.

The structural relationship and structural hierarchy linking these multiple page table layers are mapped out in the schematic diagram below:

Figure 6-11 Linux Multi-tier Page Table Hierarchy

6.3.4 Implementing Nominal Three-tier Linux Address Translation via ARM Hardware

The ARM implementation of the Linux kernel utilizes a nominal three-tier address translation model consisting of the PGD, PMD, and PTE. The top-level PGD maps directly to the ARM hardware Translation Table Base Registers, TTBR0 and TTBR1, which provide the reference tracking vectors to locate the mid-level PMD tables.

When executing on 32-bit ARM hardware that natively supports only two levels of hardware translation, a structural mismatch arises with Linux's three-tier software model. To resolve this, the kernel implements a 1:1 structural shorthand overlay linking the PGD entries directly to the PMD entries. By assigning identical bit vectors to both descriptor layers, the Linux kernel leverages the 2-tier MMU hardware pipeline to execute its nominal 3-tier software mapping. In the low-level architecture code, this folded translation loop is managed by completely merging the P4D, PUD, and PMD layers so they reference an identical physical base context. The schematic diagram below illustrates this architectural adaptation:

Figure 6-12 Schematic Mapping of Linux Folding to a 2-Tier ARM MMU Pipeline

Within the Linux memory management framework, the PMD specifies the formatting constraints for all page table tiers above the PTE, making it structurally equivalent to an ARM level-1 section or supersection descriptor. Concurrently, the PTE maps out the absolute primitive boundaries of individual page descriptors, functioning as an ARM level-2 page descriptor.

Executing address translations over 1 MB block sections requires only a single-tier lookup phase. Because the early bootstrap lifecycle does not enforce maximum, fine-grained memory utilization, the early kernel simplifies its memory model by processing section descriptors exclusively during the initial booting sequence. Consequently, the temporary page tables are populated using standard 1 MB section structures. The low-level assembly sequence tasked with initializing these early section-level structures within the head.S source code module is declared under the global label __create_page_tables:

__create_page_tables:
        pgtbl    r4, r8                	@ page table address
        mov    r0, r4
        mov    r3, #0
        add    r6, r0, #PG_DIR_SIZE
1:    str    r3, [r0], #4
        str    r3, [r0], #4
        str    r3, [r0], #4
        str    r3, [r0], #4
        teq    r0, r6
        bne    1b
        /* ... Note: For clarity, the core loop is shown fully in the text above ... */
        ret    lr
ENDPROC(__create_page_tables)
    .ltorg
    .align
__turn_mmu_on_loc:
    .long    .
    .long    __turn_mmu_on
    .long    __turn_mmu_on_end

Prior to branching into this assembly block, register r8 must contain the baseline physical memory offset vector (PHYS_OFFSET), r9 preserves the hardware CPU ID signature, and r10 references the memory workspace hosting the resolved processor metadata record.

The initial macro command pgtbl r4, r8 calculates the hardware absolute physical memory boundary tracking to PHYS_OFFSET + TEXT_OFFSET - PG_DIR_SIZE, caching the resulting base reference inside register r4. As analyzed in Figure 6-5, this coordinate defines the absolute starting address of the transient page table structure.

Immediately following this base registration loop, the system steps into the zero-fill segment:

mov    r0, r4
        mov    r3, #0
        add    r6, r0, #PG_DIR_SIZE
1:    str    r3, [r0], #4
        str    r3, [r0], #4
        str    r3, [r0], #4
        str    r3, [r0], #4
        teq    r0, r6
        bne    1b

This assembly loop iterates across the entire memory layout allocated to PG_DIR_SIZE, writing null bytes (0x00000000) throughout the table to clear out stale artifacts.

A fundamental challenge arises during MMU bring-up: an identical virtual coordinate might address entirely different physical cells before and after the MMU is engaged. Crucially, the explicit physical instructions tasked with executing the MMU activation sequence must remain strictly identity-mapped, meaning their virtual address must align perfectly with their true physical address during the instruction pipelining phase. If an address drift occurs during this structural step, the processor's fetch engine will jump to an unmapped sector, leading to an immediate system crash. To prevent this, the initialization code constructs explicit identity-mapped descriptor entries covering the code block that toggles the MMU. This is achieved by storing the upper 12 bits of the code section's physical base address directly into the corresponding section descriptor base domain.

        adr    r0, __turn_mmu_on_loc
        ldmia    r0, {r3, r5, r6}
        sub    r0, r0, r3                    @ virt->phys offset
        add    r5, r5, r0                    @ phys __turn_mmu_on
        add    r6, r6, r0                    @ phys __turn_mmu_on_end
        mov    r5, r5, lsr #SECTION_SHIFT
        mov    r6, r6, lsr #SECTION_SHIFT
1:    orr    r3, r7, r5, lsl #SECTION_SHIFT    	@ flags + kernel base
        str    r3, [r4, r5, lsl #PMD_ORDER]        @ identity mapping
        cmp    r5, r6
        addlo    r5, r5, #1                    		@ next section
        blo    1b
.align
__turn_mmu_on_loc:
        .long    .
        .long    __turn_mmu_on
        .long    __turn_mmu_on_end

The code sequence shown above establishes a 1:1 identity mapping in the page tables for the memory region spanning from __turn_mmu_on to __turn_mmu_on_end. When using these specific descriptor entries for address translation, the input virtual address resolves to an identical output physical address. The technical mechanics of this assembly sequence are detailed below.

The instruction adr r0, __turn_mmu_on_loc calculates the physical address of the __turn_mmu_on_loc label. The command ldmia r0, {r3, r5, r6} loads the virtual linking addresses (address offsets) corresponding to . (the __turn_mmu_on_loc label itself), __turn_mmu_on, and __turn_mmu_on_end into registers r3, r5, and r6 respectively. The arithmetic instruction sub r0, r0, r3 calculates the physical-to-virtual translation delta (PHYS_OFFSET - PAGE_OFFSET). The subsequent addition instructions:

add r5, r5, r0
add r6, r6, r0

compute the absolute physical addresses of __turn_mmu_on and __turn_mmu_on_end. The logical shift commands:

mov r5, r5, lsr #SECTION_SHIFT
mov r6, r6, lsr #SECTION_SHIFT

isolate the section base fields from these addresses by stripping away the lower order bits.

To maximize code portability, the ARM kernel tree shares a unified codebase between processors supporting a 40-bit large physical address space and those limited to a legacy 32-bit space. When executing a 2-tier hardware translation, SECTION_SHIFT is configured to 20. Conversely, under a 3-tier translation scheme, SECTION_SHIFT scales to

  1. Because the kernel operates under a short-descriptor 2-tier profile during this early bootstrap phase, SECTION_SHIFT evaluates strictly to

The core programming instructions:

orr r3, r7, r5, lsl #SECTION_SHIFT
str r3, [r4, r5, lsl #PMD_ORDER]

combine the section base address with the memory attribute flag bits passed in r7 to form a valid level-1 section descriptor entry. It then commits this descriptor word to the active page table structure pointed to by r4. Because each short-descriptor entry consumes exactly 32 bits (4 bytes) of storage, the scaling shift constant PMD_ORDER is fixed to 2 (since (1 \ll 2 = 4)). The execution workflow tracking this routine is illustrated below:

Figure 6-13 Page Table Initialization Pipeline

Having completed the identity mapping vectors, the subsequent code block constructs the page table descriptors for the main kernel image space extending from PAGE_OFFSET up to the end of the BSS segment (_end). The underlying allocation methodology mirrors the identity-mapping routine, with the exception that it maps virtual addresses down to distinct physical targets instead of enforcing a 1:1 match. The code segment managing this mapping is structured as follows:

        add    r0, r4, #PAGE_OFFSET >> (SECTION_SHIFT - PMD_ORDER)
        ldr    r6, =(_end - 1)
        orr    r3, r8, r7
        add    r6, r4, r6, lsr #(SECTION_SHIFT - PMD_ORDER) 
1:    str    r3, [r0], #1 << PMD_ORDER
        add    r3, r3, #1 << SECTION_SHIFT
        cmp    r0, r6
        bls    1b

Prior to executing this block, register r4 references the baseline address of the early page table array, r7 encapsulates the low-level memory attribute flags, and r8 holds PHYS_OFFSET. The initial line of assembly computes the exact descriptor entry index within the page table that maps to the base virtual address PAGE_OFFSET. Because each descriptor slot consumes a 4-byte width, PAGE_OFFSET must be shifted right by 18 bits instead of 20 bits (20 - 2 = 18).

The logic operation orr r3, r8, r7 builds the raw section descriptor content. This operation requires that the lower 20 bits of PHYS_OFFSET are strictly zero-initialized—a hardware boundary constraint that is universally satisfied across ARM platforms. As shown in the code logic, register r6 resolves to the absolute page table entry index corresponding to the virtual address limit _end.

The instruction str r3, [r0], #1 << PMD_ORDER writes the generated descriptor word into the page table slot indexed by r0 and automatically increments r0 by 4 bytes to point to the next contiguous descriptor entry. Concurrently, add r3, r3, #1 << SECTION_SHIFT increments the section base domain within the descriptor word by 1 MB, aligning it with the next contiguous physical memory block. The structural software loop tracking this mapping is charted in the flowchart below:

Figure 6-14 Page Table Configuration for the Kernel and BSS Segments

During the U-BOOT platform boot phase, beyond importing the primary executable Linux kernel binary into physical RAM, the bootloader also copies the Device Tree Blob (DTB) or legacy boot parameter arrays (atags) into memory. Because the kernel must access these configuration structures continuously throughout its operational lifecycle, it must map this specific memory footprint inside the early page tables. After unpacking the DTB or parameters into memory, U-BOOT caches the absolute starting physical address of this storage region inside register r2.

Although the actual linear width of this parameter block typically consumes less than a single 1 MB section boundary, its physical placement on the media may sit dangerously close to a section edge. If the memory block overlaps a section boundary and spans into an adjacent section, mapping it safely requires two consecutive section descriptors. The assembly block responsible for generating the page table entries for this parameter region is structured as follows:

mov    r0, r2, lsr #SECTION_SHIFT
        movs    r0, r0, lsl #SECTION_SHIFT
        subne    r3, r0, r8
        addne    r3, r3, #PAGE_OFFSET
        addne    r3, r4, r3, lsr #(SECTION_SHIFT - PMD_ORDER)
        orrne    r6, r7, r0
        strne    r6, [r3], #1 << PMD_ORDER
        addne    r6, r6, #1 << SECTION_SHIFT
        strne    r6, [r3]
        ret    lr

The initial bitmask operations:

mov r0, r2, lsr #SECTION_SHIFT
movs r0, r0, lsl #SECTION_SHIFT

isolate the 1 MB section base address fields (bits[31:20]) hosting the Device Tree or parameter block. The conditional execution block:

subne r3, r0, r8
addne r3, r3, #PAGE_OFFSET

computes the corresponding virtual address of this region by applying the transformation matrix (phys_addr - PHYS_OFFSET + PAGE_OFFSET). The subsequent line:

addne r3, r4, r3, lsr #(SECTION_SHIFT - PMD_ORDER)

calculates the target index offset within the page table matching that virtual address.

The bitwise instruction orrne r6, r7, r0 constructs the section descriptor word mapping the parameter block. Finally, the trailing two store operations commit these two sequential descriptor words into the calculated page table offsets to ensure complete boundary coverage, then branch back to the calling function.

The comprehensive spatial relationship mapping the physical address blocks to their respective virtual spaces after processing this early page table generation phase is illustrated in the diagram below:

Figure 6-15 Virtual-to-Physical Address Layout Mappings Established via the Early Page Tables

This concludes Section 6.3 and the detailed technical analysis of the early page table initialization phase.

6.3.5 Enabling the Memory Management Unit (MMU)

Following the initialization of the early translation page tables, the next step in the boot sequence is provisioning the CPU to engage the MMU safely. The assembly logic first loads the post-MMU execution target address __mmap_switched into register r13 (which functions as the primary Stack Pointer, sp), and writes the absolute physical return vector address (label 1:) into the Link Register (lr).

The following assembly sequence implements the MMU preparation pipeline for platforms supporting a standard 32-bit physical address space. Prior to entering this code segment, register r4 preserves the early page table base reference, and r10 targets the absolute physical address of the resolved proc_info_list matching the active ARM processor core model:

        ldr    r13, =__mmap_switched
        badr    lr, 1f
        mov    r8, r4
        ldr    r12, [r10, #PROCINFO_INITFUNC]
        add    r12, r12, r10
        ret    r12
1:    b    __enable_mmu

The operation ldr r13, =__mmap_switched writes the virtual linking address of the __mmap_switched routine into register r13. The command badr lr, 1f calculates and stores the physical address of the fallback label 1: into lr as the baseline return address vector. The command mov r8, r4 copies the page table base address into register r8.

The instruction ldr r12, [r10, #PROCINFO_INITFUNC] resolves the explicit relative byte offset of the core processor initialization block (__cpu_flush) relative to the proc_info_list base address. The command add r12, r12, r10 computes the absolute physical execution address of this __cpu_flush routine, writing the vector into register r12. Finally, ret r12 fires an unconditional branch to jump straight into the processor-specific setup subroutine.

For ARMv7 Cortex-A9 MPCore application processors, this setup routine is defined as the core symbol __v7_ca9mp_setup within the low-level memory management architecture source module git/arch/arm/mm/proc-v7.S. The assembly code block is structured as follows:

__v7_ca9mp_setup:
        mov    r10, #(1 << 0)                	@ Cache/TLB ops broadcasting
        adr    r0, __v7_setup_stack_ptr
        ldr    r12, [r0]
        add    r12, r12, r0                    	@ Calculate local stack pointer
        stmia    r12, {r1-r6, lr}                	@ Save r1-r6 and lr to __v7_setup_stack
        bl      v7_invalidate_l1
        ldmia    r12, {r1-r6, lr}
        b    __v7_setup_cont

The technical objective of this routine is to back up the contents of registers r1 through r6 and the lr vector by pushing them into a temporary local stack allocation frame named __v7_setup_stack. It then calls v7_invalidate_l1 to completely purge and invalidate all stale entries within the level-1 data cache hierarchy. Upon restoring the original values of registers r1–r6 and lr from the temporary stack, the state machine branches to __v7_setup_cont to provision the hardware Translation Table Base Control Register (TTBCR) and the Translation Table Base Registers (TTBR0/TTBR1).

The following assembly-level subroutine implements the absolute level-1 data cache invalidation loop. This routine interrogates the CP15 coprocessor configuration registers to read the explicit number of sets and cache ways implemented by the silicon, and subsequently loops across every cache line to execute hardware-enforced invalidate steps by writing to the CP15 c7 register:

ENTRY(v7_invalidate_l1)
          mov     r0, #0
          mcr     p15, 2, r0, c0, c0, 0            	@ Write CSSELR (Cache Size Selection Register) to target L1 Data Cache
          mrc     p15, 1, r0, c0, c0, 0            	@ Read CCSIDR (Cache Size ID Register) metrics
          movw    r1, #0x7fff
          and     r2, r1, r0, lsr #13                	@ Extract total sets parameter (Assigned value = actual sets - 1)
          movw    r1, #0x3ff
          and     r3, r1, r0, lsr #3                  	@ Extract total ways parameter (Assigned value = actual ways - 1)
          add     r2, r2, #1                              	@ Calculate absolute number of sets
          and     r0, r0, #0x7                    	@ Extract cache line word width (Actual = log2(words) - 2)
          add     r0, r0, #4                      	@ Define set shift value for DCISW formatting
          clz     r1, r3                              	@ Calculate way shift value based on leading zeros of ways bitmask
          add     r4, r3, #1                      	@ NumWays total constant
1:        sub     r2, r2, #1                      	@ Decrement NumSets loop counter
          mov     r3, r4                            	@ Reset Temp counter back to NumWays
2:        subs    r3, r3, #1                      	@ Decrement Temp way index counter
          mov     r5, r3, lsl r1
          mov     r6, r2, lsl r0
          orr     r5, r5, r6                          	@ Synthesize final formatted DCISW command register value
          mcr     p15, 0, r5, c7, c6, 2           	@ Write DCISW (Data Cache Invalidate by Set/Way) to invalidate cache line
          bgt     2b                        		@ Loop until all associative ways within the active set are invalidated
          cmp     r2, #0
          bgt     1b                        		@ Loop until all sets across the L1 cache controller are invalidated
          dsb     st
          isb
          ret     lr
ENDPROC(v7_invalidate_l1)

The logical execution workflow and register decrement tracking loop implemented across the v7_invalidate_l1 assembly subroutine is visualized in the schematic flowchart below:

Figure 6-16 Hardware Level-1 Data Cache Invalidation Loop

Upon returning from the invalidation path, the processor branches into __v7_setup_cont to proceed with secondary low-level register updates. The __v7_setup_cont code path is architected to optionally apply silicon errata workarounds and hardware bug patches. Since NXP applications processors do not utilize these specific errata workarounds, this software segment has been omitted for clarity.

Following these conditional checks, the routine clears out stale instruction pipelines and pre-fetch buffers by writing zero values into the CP15 coprocessor c7 and c8 registers, which completely flushes the Instruction Cache (I-Cache) and invalidates the Translation Lookaside Buffers (TLBs).

The routine then invokes the system macro v7_ttb_setup r10, r4, r5, r8, r3 to program the Translation Table Base Control Register (TTBCR) layout, and writes the early page table physical base address preserved in r8 straight into the primary hardware page table register TTBR1. Finally, it programs the primary memory region attribute and normal memory re-mapping registers (PRRR and NMRR) within the CP15 configuration block. For granular details tracking the bit definitions and access controls of these re-mapping registers, developers can reference the official ARM Architecture Reference Manual.

__v7_setup_cont:
    mov    r10, #0
    mcr    p15, 0, r10, c7, c5, 0        	@ Invalidate all instruction caches
    mcr    p15, 0, r10, c8, c7, 0        	@ Invalidate TLBs
    v7_ttb_setup r10, r4, r5, r8, r3        	@ Configure TTBCR and TTBRx
    ldr    r3, =PRRR    
    ldr    r6, =NMRR    
    mcr    p15, 0, r3, c10, c2, 0        	@ Configure Primary Region Remap Register
    mcr    p15, 0, r6, c10, c2, 1        	@ Configure Normal Memory Region Remap Register
    dsb
    adr    r3, v7_crval
    ldmia    r3, {r3, r6}
    mrc    p15, 0, r0, c1, c0, 0        	@ Read System Control Register (SCTLR)
    bic    r0, r0, r3
    orr    r0, r0, r6 
    ret    lr

The instruction ldmia r3, {r3, r6} loads the explicit bitmask configurations 0x0122C302 and 0x30C03C7D into registers r3 and r6 respectively. Prior to returning to the caller, the target bit values destined for the System Control Register (SCTLR) are temporarily preserved within register r0.

Because the Link Register (lr) preserved the physical base address of label 1: during the cache invalidation call, returning from the setup block automatically executes b __enable_mmu, which shifts the execution pipeline into the __enable_mmu subroutine to kick off MMU activation. Prior to entering the __enable_mmu code block, the hardware register matrix is aligned precisely as follows:

  • r0: Holds the prepared configuration bitmask to be written to the System Control Register (SCTLR).

  • r1: Preserves the machine type identifier code.

  • r2: Stores the absolute physical base pointer address referencing the atags or the Device Tree Blob (DTB).

  • r4: Holds the lower 32 bits of the level-1 Translation Table Base Register 0 (TTBR0).

  • r5: Holds the upper 32 bits of TTBR0 (processed exclusively within 40-bit large physical addressing pipelines where TTBR0 and TTBR1 scale to 64-bit widths).

  • r8: Holds the structural base value for TTBR1.

  • r9: Preserves the hardware processor ID signature.

  • r13: Stores the absolute virtual destination address targeted for execution once the MMU has been successfully engaged.

The low-level assembly sequence tasked with transitioning the CPU into virtual memory mode is structured as follows:

__enable_mmu:
        bic    r0, r0, #CR_A            	@ Clear alignment fault checking bits in SCTLR configuration
        mov    r5, #DACR_INIT 
        mcr    p15, 0, r5, c3, c0, 0        	@ Write Domain Access Control Register (DACR)
        mcr    p15, 0, r4, c2, c0, 0        	@ Write Translation Table Base Register 0 (TTBR0)
        b    __turn_mmu_on
ENDPROC(__enable_mmu)   

.align    5
.pushsection    .idmap.text, "ax"
ENTRY(__turn_mmu_on)
        mov    r0, r0
        instr_sync
        mcr    p15, 0, r0, c1, c0, 0        @ Write SCTLR: Enable the Memory Management Unit (MMU)
        mrc    p15, 0, r3, c0, c0, 0        @ Read Cache Size ID Register (CCSIDR)
        instr_sync
        mov    r3, r3
        mov    r3, r13
        ret    r3                    	@ Return/Jump to virtual address space inside __mmap_switched
__turn_mmu_on_end:
ENDPROC(__turn_mmu_on)
    .popsection

The compiled binary code for the __turn_mmu_on block is mapped directly into the .idmap.text section. This section resides strictly within the identity-mapped (1:1) translation boundary, meaning the virtual and physical address planes are completely identical for this execution window. Consequently, instructions fetched within this loop proceed smoothly without being disrupted or unmapped when the MMU configuration changes.

The enabling routine itself is direct: it enforces the global memory access permission domains inside the DACR, registers the base table tracking pointer within TTBR0, and updates the System Control Register bits to activate the MMU hardware. The implementation uses the Instruction Synchronization Barrier isb macro constant (instr_sync) to flush the execution pipeline, guaranteeing that all internal processor states align before branching to the virtual domain.

Once the MMU is fully engaged, the execution pipeline executes the jump into virtual space, landing at the __mmap_switched entry vector to run the following routine:

__mmap_switched:
    mov    r7, r1
    mov    r8, r2
    mov    r10, r0
    adr    r4, __mmap_switched_data
    mov    fp, #0
    ldmia    r4!, {r0, r1, sp}
    sub    r2, r1, r0
    mov    r1, #0
    bl    memset            		@ Zero out the uninitialized global data (.bss) segment
    ldmia    r4, {r0, r1, r2, r3}
    str    r9, [r0]            		@ Store processor ID parameters
    str    r7, [r1]            		@ Store hardware machine type index
    str    r8, [r2]            		@ Store boot parameters pointer or Device Tree base address
    cmp    r3, #0
    strne    r10, [r3]            	@ Store System Control Register (SCTLR) value
    mov    lr, #0
    b    start_kernel   
.align    2
.type    __mmap_switched_data, %object
__mmap_switched_data:
    .long    __bss_start                		@ Read into r0
    .long    __bss_stop                		@ Read into r1
    .long    . + THREAD_START_SP     	@ Read into Stack Pointer (sp)

    .long    processor_id                		@ Read into r0
    .long    __machine_arch_type        		@ Read into r1
    .long    __atags_pointer            		@ Read into r2
    .long    cr_alignment               		@ Read into r3
    .size    __mmap_switched_data, . - __mmap_switched_data

The fundamental purpose of the __mmap_switched routine is to clear the uninitialized global variable region bounded between the __bss_start and __bss_stop markers by filling the blocks with null bytes via memset. Following this runtime cleanup, it commits the runtime hardware processor ID, the machine architecture index, the absolute memory pointer referencing the Device Tree blob, and the active System Control Register state into their respective global kernel variables (processor_id, __machine_arch_type, __atags_pointer, and cr_alignment).

Having successfully finalized the execution stacks and established a valid C environment within the virtual memory domain, it clears the link register and invokes an unconditional branch to jump directly into the architecture-independent C language initialization routine: start_kernel().

This concludes Section 6.3.5 and the complete technical translation of the low-level assembly bootstrap phase.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com