# Linux: Kernel/User Address Space ## xv6 In xv6, we have per-process pagetables, and the kernel owns a pagetable `kernel_pagetable`. Whenever switching to kernel mode, we will replace pagetable register w/ `kernel_pagetable`. ### Lab In 2020, MIT 6.S081 release a [lab](https://pdos.csail.mit.edu/6.S081/2020/labs/pgtbl.html) that modifies the per-process pagetable such that each process contains two pagetable. - `pagetable`: original pagetable - `kpagetable`: kernel pagetable with user mappings The kernel no longer uses the global `kernel_pagetable` but rather per-process `kpagetable`. Note that in the design, kernel use address starting from `0x0C000000` and the user use address starting from `0x00000000` to `0x0BFFFFFF`. (no overlap !!) This is extremely useful, as sometimes the user process calls a syscall and passes in a user pointer, the kernel wouldn't be able to dereference it directly since they were using different address spaces. ## Linux In Linux, the memory layout depends on the architecture, but in general, the user process and kernel share the same address space, which are split in **ratio 3/1**. For example, we have 4GB, then we have - user address range: `0x0000_0000` to `0xC000_0000 - 1` - kernel address range: `0xC000_0000` to `0xFFFF_FFFF` Moreover, the kernel address space is **globally shared across all processes**. That is, no matter which page table we are using, the kernel address maps to the same underlying physical page. In this way, we can **stop TLB from flushing entries of kernel address** as they were shared across all processes. ### Kernel page-table isolation In 2018, [Meltdown](https://en.wikipedia.org/wiki/Meltdown_(security_vulnerability)) vulnerability was found, and linux developers decided to **seperate user-space and kernel-space page table**. ![](https://i.imgur.com/KjOTeKG.png) The user-space page table contains all user mappings and minimal kernel mappings. (for syscall, interrupt, exception etc.) The kernel-space page table contains user mappings and all kernel mappings. Now everything seems familiar, and it turns out to be almost the same as we did in the above xv6 lab !! ## Ref - [What is "the kernel address space"?](https://stackoverflow.com/questions/52340014/what-is-the-kernel-address-space) - [Why do you have to use copy_to_user()/copy_from_user() to access user space from the kernel?](https://stackoverflow.com/questions/12666493/why-do-you-have-to-use-copy-to-user-copy-from-user-to-access-user-space-from) ###### tags: `Linux` `xv6`