How Is Kernel Memory Organized in Linux? – Free Linux Device Driver Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →
Linux Kernel Memory Management Internals
Part 2 — Kernel Segment, KASLR & Physical Memory Organization
🆓 Free Course
⏱ ~30 min read
🎯 Intermediate → Advanced
🐧 Kernel 6.x

Linux Kernel Memory Management: Kernel Segment, KASLR, and Physical Memory Organization

Welcome to Part 2 of our Linux kernel memory management tutorial series — part of EmbeddedPathashala’s free Linux kernel development course. In Part 1 we covered the VM split and process Virtual Address Space. Now we go deeper into the kernel side: what lives in kernel virtual address space, how KASLR protects it, and how the kernel organizes and tracks physical RAM using nodes, zones, and page frames.

This knowledge is essential for anyone working on Linux device drivers, kernel modules, or low-level embedded Linux development. Understanding physical memory layout is what separates a good driver developer from a great one.

📚 What You Will Learn
  • What the kernel segment of virtual memory contains
  • The layout of kernel virtual address space on 64-bit Linux 6.x
  • What KASLR is and how it protects the kernel
  • How to check KASLR status and kernel load address
  • How Linux organizes physical RAM into nodes, zones, and page frames
  • What NUMA is and why it matters for performance-critical kernel code
  • How to inspect physical memory info from userspace
  • How all of this connects to writing correct Linux device drivers

What Is the Kernel Segment in Linux Memory Management?

In Part 1, we said that the VM split divides the Virtual Address Space into a user half and a kernel half. Now let us look at what exactly lives inside the kernel segment — the upper portion of the VAS that every process’s page tables include, but which only the kernel (running in privileged mode) can access.

The kernel segment is not one flat block. It is carefully organized into several distinct regions, each serving a specific purpose. On modern 64-bit Linux 6.x systems (x86_64), the kernel virtual address space layout is documented in the kernel source and looks roughly like the diagram below.

Figure 1 — Kernel Virtual Address Space Layout (x86_64, Linux 6.x, simplified)
0xFFFFFFFFFFFFFFFF
Fixmap region
(fixed virtual addresses for ioremap etc.)
vmalloc / ioremap region
(virtually contiguous, non-contiguous physical)
Kernel modules region
(LKM .text/.data loaded here)
Kernel image
_text, _data, _bss, _end
(randomized by KASLR)
Direct physical memory mapping
(all physical RAM mapped here)
starts at PAGE_OFFSET
0xFFFF888000000000
(PAGE_OFFSET on x86_64)
Fixmap

Fixed virtual addresses reserved for specific kernel subsystems (e.g., APIC, kmap for highmem on 32-bit, early boot mappings). These are compile-time fixed virtual addresses, not dynamically allocated.

vmalloc / ioremap

Used by vmalloc() for large virtually-contiguous allocations (physical pages may not be contiguous). Also used by ioremap() to map device register memory into kernel virtual space — critical for writing hardware device drivers.

Kernel Modules Region

When you load a kernel module (insmod mydriver.ko), its code and data are placed in this region. It is kept close to the kernel image so that relative jump instructions in module code can reach kernel functions directly.

Kernel Image

The compiled kernel itself: all kernel functions, data structures, interrupt handlers, scheduler code, and built-in driver code. KASLR randomizes where exactly this is loaded on each boot.

Direct Physical Mapping

The kernel directly maps all (or most) physical RAM here. Physical address P maps to virtual address PAGE_OFFSET + P. This is how kmalloc() works — it allocates from this directly-mapped region, giving you both a virtual and physical address for the same memory.

Checking Kernel Virtual Addresses

You can inspect kernel virtual addresses from within a module using kernel symbols, or from userspace using /proc/iomem and /proc/kallsyms (when accessible):

/* Inside a kernel module — print key kernel addresses */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>

static int __init meminfo_init(void)
{
    pr_info("PAGE_OFFSET    = 0x%lx\n", PAGE_OFFSET);
    pr_info("VMALLOC_START  = 0x%lx\n", VMALLOC_START);
    pr_info("VMALLOC_END    = 0x%lx\n", VMALLOC_END);
    pr_info("MODULES_VADDR  = 0x%lx\n", MODULES_VADDR);
    pr_info("MODULES_END    = 0x%lx\n", MODULES_END);
    return 0;
}

static void __exit meminfo_exit(void)
{
    pr_info("meminfo module removed\n");
}

module_init(meminfo_init);
module_exit(meminfo_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("EmbeddedPathashala");
MODULE_DESCRIPTION("Print kernel virtual address layout");

After loading with sudo insmod meminfo.ko, check output with dmesg | tail. The values you see depend on KASLR — they will differ each boot.

What Is KASLR and Why Does Linux Kernel Memory Management Need It?

KASLR stands for Kernel Address Space Layout Randomization. Just as user-space ASLR randomizes where libraries and the stack load in a process’s VAS, KASLR randomizes where the kernel image itself loads in kernel virtual address space on each boot.

Without KASLR, every Linux system would load the kernel at the same fixed virtual address. An attacker who knows the address of a kernel function or data structure can exploit kernel vulnerabilities (like a buffer overflow) to overwrite them reliably. KASLR removes this predictability.

Figure 2 — KASLR: Kernel Load Address Changes Each Boot
WITHOUT KASLR
···vmalloc area···
Kernel @ FIXED
0xFFFFFFFF80000000
(every boot)
···direct map···
Attacker knows exact addresses ❌
→
WITH KASLR (default, Linux 6.x)
Boot 1
Kernel @ A
random offset
Boot 2
Kernel @ B
different offset
Boot 3
Kernel @ C
yet another offset
Attacker cannot predict addresses ✅

Checking KASLR Status on Your System

# Check if KASLR is enabled (1 = enabled, 0 = disabled)
$ cat /proc/sys/kernel/randomize_va_space
2

# Check the kernel load offset (requires root on most systems)
$ sudo cat /proc/kallsyms | grep " _text"
ffffffff92000000 T _text   <-- changes each boot with KASLR

# See KASLR offset in kernel boot log
$ dmesg | grep -i kaslr
[    0.000000] KASLR enabled
💡 KASLR and Kernel Module Development

KASLR is transparent to kernel module developers — the kernel handles all address relocation automatically when your module is loaded. However, if you use crash dump analysis tools (like crash utility with vmcore), you need the KASLR offset to correctly resolve symbol addresses in the dump. Modern versions of the crash tool handle this automatically.

How the Linux Kernel Manages Physical Memory — Nodes, Zones, and Pages

So far we have only talked about virtual memory. Now let us understand how the Linux kernel tracks and manages actual physical RAM. This is where the kernel’s physical memory management machinery comes in — and it is a beautifully structured three-level hierarchy: Nodes → Zones → Page Frames.

Figure 3 — Linux Physical Memory Hierarchy
LEVEL 1: Memory Nodes (pg_data_t)
Each node = one NUMA memory bank (physically close to a CPU package)
Node 0
(CPU 0–7)
Node 1
(CPU 8–15)
Node N
…
↓ Each node contains multiple zones ↓
ZONE_DMA
First 16 MB
Legacy ISA DMA
ZONE_DMA32
0–4 GB range
32-bit DMA devices
ZONE_NORMAL
Directly mapped RAM
Most kernel allocations
ZONE_MOVABLE
Movable pages
Memory hotplug
↓ Each zone contains thousands of page frames ↓
LEVEL 3: Page Frames (struct page)
Page 0
4 KB
Page 1
4 KB
Page 2
4 KB
…
Page N
4 KB
Each page = 4096 bytes. Each has a struct page descriptor tracking usage, reference count, flags.

Memory Nodes — The Top Level

A memory node corresponds to a physical memory bank that is connected to (and fast to access from) a specific CPU or group of CPUs. This is the concept of NUMA — Non-Uniform Memory Access.

On a simple single-socket desktop or embedded system, there is only one NUMA node (Node 0), and all memory is equally accessible. On a dual-socket or multi-socket server, each CPU socket has local RAM that is faster to access than RAM attached to a different socket. The kernel is NUMA-aware and tries to allocate memory from the node closest to the CPU that needs it.

System Type NUMA Nodes Memory Access Pattern
Embedded system (ARM/RISC-V) 1 node UMA — uniform latency everywhere
Desktop PC (single CPU) 1 node UMA
Dual-socket server 2 nodes NUMA — local memory is ~2× faster than remote
Large HPC system 4–8+ nodes NUMA — critical to get right for performance
# Check NUMA topology on your system
$ numactl --hardware

# Or via /proc
$ cat /proc/buddyinfo
$ cat /sys/devices/system/node/online

Memory Zones — Why They Exist

Within each NUMA node, physical memory is divided into zones. Zones exist because not all physical memory is equally usable for all purposes. The reason is largely historical hardware constraints — some older DMA controllers can only access the first 16 MB of RAM (ZONE_DMA), and some 32-bit PCI devices can only address up to 4 GB (ZONE_DMA32).

Zone Physical Range (x86_64) Primary Purpose Kernel Allocator Flag
ZONE_DMA 0 — 16 MB Legacy ISA DMA hardware GFP_DMA
ZONE_DMA32 16 MB — 4 GB 32-bit DMA-capable devices GFP_DMA32
ZONE_NORMAL 4 GB — end of RAM Most kernel + user allocations GFP_KERNEL (default)
ZONE_MOVABLE Configurable subset Movable pages for memory hotplug GFP_HIGHUSER_MOVABLE
ZONE_DEVICE Device memory (PMEM, GPU HBM) Persistent memory, RDMA Special — via device driver
💡 Critical Tip for Device Driver Developers

When your device driver performs DMA (Direct Memory Access), you must allocate memory from the correct zone. If your device’s DMA controller can only address 32 bits of physical address space, use GFP_DMA32 with kmalloc(), or better yet, use the DMA API: dma_alloc_coherent(). This handles zone selection, cache coherency, and IOMMU mapping automatically and correctly.

Page Frames — The Fundamental Unit of Physical Memory

At the lowest level, physical memory is divided into fixed-size chunks called page frames. On x86_64 and most ARM/RISC-V systems, the page size is 4096 bytes (4 KB). The kernel represents each physical page frame with a struct page descriptor.

The array of all struct page descriptors is called the mem_map. Given a physical address, you can find its struct page using the pfn_to_page() macro (PFN = Page Frame Number = physical_address / PAGE_SIZE).

/* Key macros for working with page frames in kernel/driver code */

/* Convert physical address to page frame number */
unsigned long pfn = phys_addr >> PAGE_SHIFT;  /* PAGE_SHIFT = 12 for 4KB pages */

/* Get struct page* from PFN */
struct page *pg = pfn_to_page(pfn);

/* Get PFN from struct page* */
unsigned long pfn2 = page_to_pfn(pg);

/* Get physical address from struct page* */
phys_addr_t phys = page_to_phys(pg);

/* Get kernel virtual address from struct page* (direct map) */
void *vaddr = page_address(pg);  /* valid only for lowmem/ZONE_NORMAL pages */

/* Get page from kernel virtual address */
struct page *pg2 = virt_to_page(kernel_vaddr);

The Buddy Allocator — How Linux Kernel Memory Management Handles Physical Page Allocation

When the kernel needs to allocate one or more physical page frames, it uses the Buddy Allocator (also called the page frame allocator). Understanding this is important for driver developers who allocate large contiguous physical buffers for DMA.

Figure 4 — Buddy Allocator Free Lists (order 0 to order 10)
Order 0
Free list of 4 KB chunks (1 page each) — smallest allocation unit
Order 1
Free list of 8 KB chunks (2 contiguous pages)
Order 2
Free list of 16 KB chunks (4 contiguous pages)
Order 3
Free list of 32 KB chunks (8 contiguous pages)
… continues …
Order 10
Free list of 4 MB chunks (1024 contiguous pages) — largest single allocation

When you request N pages, the buddy allocator finds the smallest order ≥ log₂(N) with available blocks. Unused half gets split back and returned to a smaller free list.

/* Allocating physical pages directly — used in device drivers for DMA buffers */
#include <linux/gfp.h>

/* Allocate 2^order contiguous pages */
struct page *pages = alloc_pages(GFP_KERNEL, order);
if (!pages) {
    pr_err("Page allocation failed!\n");
    return -ENOMEM;
}

void *vaddr = page_address(pages);   /* virtual address */
phys_addr_t phys = page_to_phys(pages); /* physical address */

/* ... use the memory ... */

/* Free the pages when done */
__free_pages(pages, order);
# Inspect buddy allocator free lists from userspace
$ cat /proc/buddyinfo
Node 0, zone      DMA      1      0      0      1      2      1      1      0      1      1      3
Node 0, zone    DMA32      0      0      0      0      1      1      1      0      1      1      2
Node 0, zone   Normal    420    180     90     42     22     12      8      4      2      0      0

# Columns: order 0, order 1, ..., order 10
# Numbers = count of free blocks of that order in that zone

The SLAB/SLUB Allocator — Efficient Small Object Allocation in Linux Kernel

The buddy allocator works in units of whole pages (4 KB minimum). But kernel data structures are often much smaller — a struct task_struct is a few kilobytes, a socket buffer header (struct sk_buff) is around 200 bytes. Allocating a full page for each small object would waste enormous amounts of memory.

The SLUB allocator (the default slab allocator since Linux 2.6.23, and refined through all 6.x releases) solves this. It carves pages obtained from the buddy allocator into pools of fixed-size objects called slabs. Each object type gets its own cache.

Figure 5 — SLUB Allocator: Object Caches
kmalloc-64 cache
obj 0
64B
obj 1
64B
obj 2
64B
free
backed by 1 page
task_struct cache
task A
~8 KB
task B
~8 KB
free
free
backed by 2 pages
sk_buff cache
skb 0
~232B
skb 1
~232B
skb 2
~232B
skb 3
~232B
backed by 1 page
/* Using kmalloc in a kernel module (allocates from SLUB size caches) */
#include <linux/slab.h>

/* Allocate 128 bytes — comes from kmalloc-128 slab cache */
void *buf = kmalloc(128, GFP_KERNEL);
if (!buf)
    return -ENOMEM;

/* Use the buffer */
memset(buf, 0, 128);

/* Always free what you allocate */
kfree(buf);
/* Creating a custom slab cache for a driver's own data structures */
struct my_device_data {
    u32 reg_base;
    u32 irq;
    spinlock_t lock;
    /* ... */
};

static struct kmem_cache *my_cache;

/* In module_init */
my_cache = kmem_cache_create("my_driver_cache",
                              sizeof(struct my_device_data),
                              0,               /* alignment */
                              SLAB_HWCACHE_ALIGN,
                              NULL);           /* no constructor */

/* Allocate an object */
struct my_device_data *dev = kmem_cache_alloc(my_cache, GFP_KERNEL);

/* Free an object */
kmem_cache_free(my_cache, dev);

/* In module_exit */
kmem_cache_destroy(my_cache);

Inspecting Physical Memory Info — Linux Kernel Memory Management from Userspace

# Overall memory statistics
$ cat /proc/meminfo
MemTotal:       16207504 kB
MemFree:         4512180 kB
MemAvailable:   10231040 kB
Buffers:          421384 kB
Cached:          5811292 kB
SwapCached:            0 kB
...
Slab:            1048576 kB
SReclaimable:    756832  kB
SUnreclaim:      291744  kB

# Per-zone memory info
$ cat /proc/zoneinfo | head -40

# SLUB cache statistics
$ cat /proc/slabinfo | head -20

# Or use slabtop (real-time)
$ sudo slabtop

Security Considerations in Linux Kernel Memory Management

  • KASLR: Randomizes kernel image load address — prevents ROP (Return-Oriented Programming) attacks from using fixed gadget addresses.
  • SMEP (Supervisor Mode Execution Prevention): CPU hardware prevents kernel from executing code in user-space pages. Controlled by a CR4 bit on x86.
  • SMAP (Supervisor Mode Access Prevention): CPU hardware prevents kernel from reading/writing user-space pages except through copy_from_user/copy_to_user.
  • KPTI (Kernel Page Table Isolation): Added after Meltdown. User-mode page tables contain minimal kernel mappings (only what’s needed for syscall entry). Prevents user-space speculation attacks from reading kernel memory.
  • KASAN (Kernel Address Sanitizer): A compile-time instrumentation tool that detects out-of-bounds accesses and use-after-free bugs in kernel code and drivers.
⚠️ Driver Developer Warning

Enable KASAN (CONFIG_KASAN=y) on your development kernel. It will catch memory bugs in your driver that would silently corrupt memory on production kernels. It adds overhead but is invaluable for debugging. Never ship a driver that hasn’t been tested with KASAN enabled.

📝 Key Takeaways — Part 2
Kernel VAS: direct map + kernel image + vmalloc + modules + fixmap KASLR randomizes kernel load address each boot Physical memory hierarchy: Nodes → Zones → Page Frames ZONE_DMA / DMA32 / NORMAL — choose right zone for DMA drivers Buddy allocator manages page-level physical allocation (orders 0–10) SLUB allocator handles small object allocation (kmalloc) Use DMA API (dma_alloc_coherent) not raw alloc_pages for DMA KASAN + SMEP + SMAP + KPTI protect kernel memory

Frequently Asked Questions — Linux Kernel Physical Memory Management

Q1: What is the difference between kmalloc and vmalloc in Linux kernel development?

kmalloc() allocates physically and virtually contiguous memory from the direct-mapped kernel region (ZONE_NORMAL). It is fast and suitable for DMA. vmalloc() allocates virtually contiguous memory by mapping physically non-contiguous pages — it is slower due to TLB pressure and cannot be used for DMA without IOMMU. Use kmalloc() by default; use vmalloc() only when you need large buffers and physical contiguity is not required.

Q2: What is GFP_KERNEL vs GFP_ATOMIC?

GFP_KERNEL is the standard allocation flag — it allows the kernel to sleep (block) waiting for memory if none is immediately available. Use this in process context (regular code paths, ioctl handlers). GFP_ATOMIC says “never sleep” — the allocator must either succeed immediately or fail. Use this in interrupt handlers, spin-lock-held sections, or any other atomic context where sleeping is not allowed.

Q3: How does the kernel know which physical pages are free?

The buddy allocator maintains per-zone free lists organized by order (0 to 10). Each free list is a linked list of free page blocks of that size. When a page is freed, the allocator checks whether its “buddy” (adjacent block of the same size) is also free — if so, they are merged into a larger free block. This prevents fragmentation and makes allocation/freeing O(log N) operations. You can observe the state of these lists via /proc/buddyinfo.

Q4: What does ioremap() do and when do I need it in a device driver?

ioremap() maps a range of physical addresses (typically device register space from the hardware’s memory-mapped I/O BAR) into the kernel’s vmalloc region, giving you a kernel virtual address you can read/write with readl()/writel(). You must use ioremap() (not direct physical address access) because the CPU may need cache-bypassing attributes set for device memory, and on some architectures direct physical access is simply not possible from C code.

Q5: What is memory fragmentation and how does Linux deal with it?

Physical memory fragmentation happens over time as pages are allocated and freed in varying patterns, leaving free pages scattered rather than contiguous. The buddy allocator reduces external fragmentation by merging buddy blocks. The SLUB allocator reduces internal fragmentation by packing same-sized objects tightly. Linux 6.x also has the memory compaction mechanism which migrates movable pages to consolidate free space into larger contiguous blocks when higher-order allocations fail.

Q6: What is the OOM killer?

When the system runs critically low on memory and all reclaim mechanisms have been exhausted, the kernel invokes the OOM (Out Of Memory) killer. It selects a process to terminate based on an OOM score (roughly: processes using lots of memory and that are not critical get higher scores). The killed process frees its memory, allowing the system to continue. You can adjust a process’s OOM score using /proc/<pid>/oom_score_adj. Kernel threads and memory-critical processes are protected from OOM kills.

Q7: How is KPTI related to the Meltdown vulnerability?

The Meltdown CPU vulnerability (CVE-2017-5754) allowed user-space code to read kernel memory by exploiting speculative execution in Intel CPUs. The kernel’s mitigations included KPTI (Kernel Page Table Isolation), which maintains two separate sets of page tables: a full set used in kernel mode (containing both kernel and user mappings) and a minimal set used in user mode (containing only user mappings plus the bare minimum for syscall entry). Switching between them on every kernel entry/exit adds a small overhead (~0.1–5% depending on workload) but prevents the speculation-based information leak.

Q8: Can I disable KASLR for easier kernel debugging?

Yes. Add nokaslr to the kernel boot command line in your bootloader configuration (e.g., in /etc/default/grub, append nokaslr to GRUB_CMDLINE_LINUX). This is only recommended for development/debugging VMs, never for production systems. With KASLR disabled, kernel symbol addresses are fixed and consistent across reboots, making crash dump analysis and gdb debugging much easier.

🎉 Congratulations — You’ve Completed the Linux Kernel Memory Management Series!

You now have a solid understanding of how the Linux kernel manages both virtual and physical memory — from the VM split, process VAS and VMAs, through the kernel segment, KASLR, all the way down to nodes, zones, page frames, the buddy allocator, and the SLUB allocator. This knowledge directly applies to writing robust, correct, and efficient Linux device drivers and kernel modules.

Next up in our free Linux kernel development course: Dynamic Kernel Memory Allocation in Depth — kmalloc, vmalloc, alloc_pages, and the DMA API in practice.

💬 Need help or career guidance? Ask us!Contact Us →

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →