6.2 Modifying the Address Translation Routines
The Linux kernel frequently executes translation loops to map between virtual address channels and physical address paths. Prior to initializing and enabling the Memory Management Unit (MMU), virtual-to-physical translations behave as static, linear mappings. The architectural relationship bridging physical addresses and virtual addresses is generally defined by the following programmatic formulas:
phy = virt + (PHYS_OFFSET - PAGE_OFFSET)
virt = phy - (PHYS_OFFSET - PAGE_OFFSET)
The system configuration includes a specialized preprocessor compilation switch named CONFIG_ARM_PATCH_PHYS_VIRT. If this build switch is disabled, the inline functions handling translations between physical and virtual address spaces are strictly hardcoded as follows:
static inline unsigned long __phys_to_virt(phys_addr_t x)
{
return x - PHYS_OFFSET + PAGE_OFFSET;
}
static inline phys_addr_t __virt_to_phys(unsigned long x)
{
return (phys_addr_t)x - PAGE_OFFSET + PHYS_OFFSET;
}
This translation paradigm is limited strictly to handling continuous 1:1 linear tracking. However, across complex Linux system configurations, virtual memory pages do not necessarily map to a simple, static one-to-one relationship with physical memory frames; multiple unique virtual memory zones can map down to share an identical physical memory base address. Furthermore, the core kernel must scale seamlessly to accommodate a diverse taxonomy of silicon architectures where the starting physical page frame numbers (PFN) vary significantly. Because these page numbers are heavily utilized across downstream memory management sub-blocks, they require constant runtime updates.
Consequently, the kernel cannot rely on a static, compile-time constant declaration of PHYS_OFFSET to govern memory translations. It must leverage advanced engineering techniques to dynamically patch and compute virtual-to-physical translation parameters at runtime to suit the active memory topology. Within contemporary kernels, these highly optimized, dynamic address translation macros are structured as follows:
static inline unsigned long __phys_to_virt(phys_addr_t x)
{
unsigned long t;
__pv_stub((unsigned long)x, t, "sub", __PV_BITS_31_24);
return t;
}
static inline phys_addr_t __virt_to_phys(unsigned long x)
{
phys_addr_t t;
if (sizeof(phys_addr_t) == 4) { /* Executed when physical address space is 32-bit */
__pv_stub(x, t, "add", __PV_BITS_31_24);
} else { /* Executed when physical address space is 40-bit (LPAE) */
__pv_stub_mov_hi(t);
__pv_add_carry_stub(x, t);
}
return t;
}
During the compilation process, the __pv_stub macro is expanded into the following inline assembly sequence, where the placeholder argument instr resolves explicitly to either the add or sub assembly operation code tokens:
#define __pv_stub(from,to,instr,type) \
__asm__("@ __pv_stub\n" \ @ Assembly comment line
"1: " instr " %0, %1, %2\n" \ @ Core arithmetic translation instruction
\@ %0=from, %1=to, %2=type
" .pushsection .pv_table,\"a\"\n" \ @ Divert context to custom .pv_table section
" .long 1b\n" \ @ Commit the absolute pointer of label 1 to the table
" .popsection\n" \ @ Revert back to the original text segment context
: "=r" (to) \
: "r" (from), "I" (type))
Concurrently, the architectural macro extensions __pv_stub_mov_hi and __pv_add_carry_stub expand to the following inline assembly definitions:
#define __pv_stub_mov_hi(t) \
__asm__ volatile("@ __pv_stub_mov\n" \
"1: mov %R0, %1\n" \
" .pushsection .pv_table,\"a\"\n" \
" .long 1b\n" \
" .popsection\n" \
: "=r" (t) \
: "I" (__PV_BITS_7_0))
#define __pv_add_carry_stub(x, y) \
__asm__ volatile("@ __pv_add_carry_stub\n" \
"1: adds %Q0, %1, %2\n" \
" adc %R0, %R0, #0\n" \
" .pushsection .pv_table,\"a\"\n" \
" .long 1b\n" \
" .popsection\n" \
: "+r" (y) \
: "r" (x), "I" (__PV_BITS_31_24) \
: "cc")
Once modified by the early runtime patching routines, the __pv_stub_mov_hi sequence copies the upper 32-bit bitmask tracking the delta between physical and virtual address spaces directly into the most significant register (high-order register) of a allocated 64-bit architecture register pair. Subsequently, the patched __pv_add_carry_stub routine adds the lower 32-bit translation offset to the target virtual address and propagates any resulting carry bit into the high-order register via the Add with Carry (adc) instruction.
Prior to the execution of the early runtime patcher, the initialization sequence injects temporary placeholder immediate operands defined by the constants __PV_BITS_31_24 and __PV_BITS_7_0. Pre-allocating these explicit constant arguments guarantees that the compiler generates valid, immediate-form mov and adds assembly tokens, complete with correctly populated immediate operand rotation fields (rotation). Ensuring these internal encoding parameters are generated properly guarantees that the 12-bit immediate field of the adds opcode can cleanly map out the lower 32 bits of the address translation offset.
Furthermore, the early patcher inspects the internal rotation bits embedded within the instruction encodings to easily differentiate whether a target instruction was instantiated via the __pv_stub_mov_hi macro or the __pv_add_carry_stub macro, executing the corresponding patch routine required for that instruction type. The key architectural characteristic of this framework is that the absolute address referencing the label 1: (the instruction address) is recorded inside a dedicated tracking section named .pv_table, fully decoupled from the active instruction text stream.
Ultimately, beyond performing baseline addition or subtraction for coordinate shifts, these macros register the absolute physical instruction address of every single translation location within a compiled lookup database named __pv_table. Before these instructions execute at runtime, the early patcher loops across this table to dynamically override the immediate fields of each registered instruction, tuning them to execute the exact offset shift matching the current board topology.
To manage this register mapping precisely, the inline assembly utilizes ARM-specific constraints modifiers, where %R0 restricts allocation strictly to the high-order register within a 64-bit pair, and %Q0 targets the low-order register.
The assembly code block residing at label __fixup_pv_table acts as this early dynamic runtime patcher. This routine analyzes the system parameters to dynamically adapt to varying physical memory structures, systematically sweeping across every reference descriptor registered inside __pv_table to patch the immediate operand bytes of the linked instructions. Prior to entering the code path at __fixup_pv_table, register r8 must contain the baseline physical memory coordinate matching PHYS_OFFSET. The detailed assembly-level code listing defining this runtime patcher is outlined below, followed by a comprehensive structural analysis of its execution workflow.
The assembly implementations for the dynamic runtime patcher subsystem are structured and executed as detailed below:
__fixup_pv_table:
adr r0, 1f @ Calculate physical address of label 1
ldmia r0, {r3-r7} @ Load virtual addresses of pf_table_begin, __pv_table_end,
@ __pv_phys_pfn_offset, and __pv_offset into r3-r7
mvn ip, #0
subs r3, r0, r3 @ r3 = Delta between physical and virtual addresses
add r4, r4, r3 @ Calculate physical address of pf_table_begin
add r5, r5, r3 @ Calculate physical address of __pv_table_end
add r6, r6, r3 @ Calculate physical address of __pv_phys_pfn_offset
add r7, r7, r3 @ Calculate physical address of __pv_offset
mov r0, r8, lsr #PAGE_SHIFT @ Convert to Page Frame Number (PFN); PHYS_OFFSET is in r8
str r0, [r6] @ Store to __pv_phys_pfn_offset for MMU usage
strcc ip, [r7, #HIGH_OFFSET] @ Store high 32 bits of __pv_offset (typically 0 or -1)
mov r6, r3, lsr #24 @ Constant used for add/sub instructions
teq r3, r6, lsl #24 @ Test whether the delta is an integer multiple of 16 MiB
bne __error
str r3, [r7,
#LOW_OFFSET] @ Store to the lower word of __pv_offset
b __fixup_a_pv_table
ENDPROC(__fixup_pv_table)
.align
1: .long .
.long pf_table_begin
.long __pv_table_end
2: .long __pv_phys_pfn_offset
.long __pv_offset
The first line of assembly code calculates the physical address corresponding to label 1:, storing the result inside register r0. The instruction ldmia r0, {r3-r7} loads the compiled virtual addresses of label 1:, pf_table_begin, __pv_table_end, __pv_phys_pfn_offset, and __pv_offset into registers r3, r4, r5, r6, and r7 respectively. Since the MMU is not yet active, virtual-to-physical links map out via a 1:1 direct identity mechanism. The command subs r3, r0, r3 yields the absolute translation delta between the current physical running position and the virtual link address. After executing the following code segment:
add r4, r4, r3 @ Calculate starting physical coordinates of __pv_table
add r5, r5, r3 @ Calculate ending physical coordinates of __pv_table
add r6, r6, r3 @ Calculate physical address of __pv_phys_pfn_offset
add r7, r7, r3 @ Calculate physical address of __pv_offset
registers r4, r5, r6, and r7 contain the physical addresses of pf_table_begin, __pv_table_end, __pv_phys_pfn_offset, and __pv_offset respectively, resolving the true operational boundaries of these tables in memory.
The subsequent logic scales the physical memory base PHYS_OFFSET into a Page Frame Number (PFN) and stores it within the __pv_phys_pfn_offset table. Concurrently, the absolute difference PHYS_OFFSET - PAGE_OFFSET is committed to the lower word of the __pv_offset data structure. If PHYS_OFFSET evaluates to less than PAGE_OFFSET, the execution sequence stores the word 0xFFFFFFFF to the upper word (HIGH_OFFSET) of __pv_offset. The matching operations mov r6, r3, lsr #24 and teq r3, r6, lsl #24 execute an arithmetic verification loop to guarantee that the hardware address translation delta is aligned to a strict 16 MiB boundary; a validation failure branches directly into error trapping routines.
Once these descriptor updates conclude, the code branches into __fixup_a_pv_table to execute the active runtime patching loops and update the instruction immediate fields.
.text
__fixup_a_pv_table:
adr r0, 3f @ Calculate physical address of label 3
ldr r6, [r0] @ Load virtual address of __pv_offset
add r6, r6, r3 @ Calculate physical address of __pv_offset
ldr r0, [r6, #HIGH_OFFSET] @ pv_offset high word
ldr r6, [r6, #LOW_OFFSET] @ pv_offset low word
mov r6, r6, lsr #24
cmn r0, #1 @ Check whether address offset is negative
moveq r0, #0x400000 @ If r0 is negative, set bit 22 to 1
b 2f
1: ldr ip, [r7, r3]
bic ip, ip, #0x000000ff
tst ip, #0xf00 @ Interrogate rotation field in the immediate operand
orrne ip, ip, r6 @ If rotation field is non-zero, patch the immediate field
biceq ip, ip, #0x400000 @ If rotation field is zero, clear bit 22 of the opcode
orreq ip, ip, r0 @ Based on r0 value, preserve the mov instruction or convert it to mvn
str ip, [r7, r3] @ Write the patched instruction back to its original location
2: cmp r4, r5 @ Verify if structural end of __pv_table is reached
ldrcc r7, [r4], #4
bcc 1b
ret lr
ENDPROC(__fixup_a_pv_table)
.align
3: .long __pv_offset
ENTRY(fixup_pv_table)
stmfd sp!, {r4 - r7, lr}
mov r3, #0 @ No offset translation vector
mov r4, r0 @ r0 = Table start pointer boundary
add r5, r0, r1 @ r1 = Table size boundary
bl __fixup_a_pv_table
ldmfd sp!, {r4 - r7, pc}
ENDPROC(fixup_pv_table)
.data
.align 2
.globl __pv_phys_pfn_offset
.type __pv_phys_pfn_offset, %object @ Variable type is explicitly data
__pv_phys_pfn_offset:
.word 0
.size __pv_phys_pfn_offset, . - __pv_phys_pfn_offset
.globl __pv_offset
.type __pv_offset, %object
__pv_offset:
.quad 0
.size __pv_offset, . - __pv_offset @ Size = current position minus label origin
The underlying segment tasked with parsing high and low word boundaries and scaling parameters relies on the following execution path:
adr r0, 3f @ Calculate physical address of label 3
ldr r6, [r0] @ Load virtual address of __pv_offset
add r6, r6, r3 @ Calculate physical address of __pv_offset
ldr r0, [r6, #HIGH_OFFSET] @ pv_offset high word
ldr r6, [r6, #LOW_OFFSET] @ pv_offset low word
mov r6, r6, lsr #24
This block extracts the upper and lower 32-bit values tracking the address translation offset and logically shifts the lower word right by 24 bits, retaining exclusively the highest 8 bits of the lower word configuration.
The directives cmn r0, #1 and moveq r0, #0x400000 evaluate whether the address translation offset is a negative value. If it is negative, register r0 is overwritten with the bitmask 0x400000, which transforms a standard mov opcode into a Bitwise NOT Move (mvn) operation.
The operation ldr ip, [r7, r3] indexes into the data pointer arrays cached within the .pv_table database to load the active machine instruction word directly into the Inter-Processor scratch register ip (r12). Upon initial entry into this execution loop, register r7 targets the virtual baseline pointer of pf_table_begin and register r3 contains the address translation delta.
The combined decoding instructions bic ip, ip, #0x000000ff and tst ip, #0xf00 clear the lower 8 bits of the instruction's immediate field to verify if the underlying immediate operand rotation field (rotation) scales to zero. If the rotation field is non-zero, indicating that the target instruction maps to an arithmetic adds statement, the command orrne ip, ip, r6 executes to patch the lower 8 bits of the immediate field with the active offset parameter.
Conversely, if the rotation bits evaluate to zero, confirming that the current instruction is a standard mov configuration, the patcher invokes biceq ip, ip, #0x400000 and orreq ip, ip, r0 to modify the instruction flags. If register r0 was populated with the mask value 0x400000, the underlying mov instruction transforms cleanly into an mvn instruction; otherwise, the primitive mov formatting is preserved, zeroing out the lower 8 bits of its immediate field. Finally, str ip, [r7, r3] writes the fully modified opcode instruction back to its original location in memory.
The trailing looping construct:
cmp r4, r5
ldrcc r7, [r4], #4
bcc 1b
ret lr
systematically traverses the complete linear boundary pool of the __pv_table array, re-programming every single memory translation opcode registered within the database, and returns control to the calling execution phase.
This concludes Section 6.2 and the runtime architecture modifications of the kernel address translation layers.