Kernel Part in Virtual Memory Space of Linux Processes

kernellinuxlinux-kernelmemoryprocess

I found a similar question but still it doesn't answer my questions
Do the virtual address spaces of all the processes have the same content in their "Kernel" parts?

  1. First off, considering user processes don't have access to this part and I guess if they try to access it, it would lead to an error, then why even include this part in the user process virtual space?
    Can you guys give me a real life scenario of this part being essential and useful?

  2. Also, one more question is I always thought the kernel part of memory is dynamic, meaning it might grow for example when we use dynamic libraries in our programs, so is it true? If so, then how can the OS determine how big the size of kernel is in the virtual space of our processes?

  3. And when our kernel in physical memory grows or changes, does the same effect happens in the kernel part of virtual memory for all the processes? Is the mapping of this virtual kernel to real kernel a one to one mapping?

enter image description here

Best Answer

  1. The kernel mapping exists primarily for the kernel’s purposes, not user processes’. From the CPU’s perspective, any physical memory address which isn’t mapped as a linear address might as well not exist. But the CPU does need to be able to call into the kernel: to service interrupts, to handle exceptions... It also needs to be able to call into the kernel when a user process issues a system call (there are various ways this can happen so I won’t go into details). On most if not all architectures, this happens without the opportunity to switch page tables — see for example SYSENTER. So at minimum, entry points into the kernel have to be mapped into the current address space at all times.

  2. Kernel allocations are dynamic, but the address space isn’t. On 32-bit x86, various splits are available, such as the 3/1 GiB split shown in your diagram; on 64-bit x86, the top half of the address space is reserved for the kernel (see the memory map in the kernel documentation). That split can’t move. (Note that libraries are loaded into user space. Kernel modules are loaded into kernel space, but again that only changes the allocations, not the address space split.)

  3. In user mode, there is a single mapping for the kernel, shared across all processes. When a kernel-side page mapping changes, that change is reflected everywhere.

    When KPTI is enabled, the kernel has its own private mappings, which aren’t exposed when running user-space code; so with KPTI there are two mappings, and changes to the kernel-private one won’t be visible to user-space (which is the whole point of KPTI).

    The kernel memory map always maps all the kernel (in kernel mode when running KPTI), but it’s not necessarily one-to-one — on 64-bit x86 for example it includes a full map of physical memory, so all kernel physical addresses are mapped at least twice.

Related Question