page_tables.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. .. SPDX-License-Identifier: GPL-2.0
  2. ===========
  3. Page Tables
  4. ===========
  5. Paged virtual memory was invented along with virtual memory as a concept in
  6. 1962 on the Ferranti Atlas Computer which was the first computer with paged
  7. virtual memory. The feature migrated to newer computers and became a de facto
  8. feature of all Unix-like systems as time went by. In 1985 the feature was
  9. included in the Intel 80386, which was the CPU Linux 1.0 was developed on.
  10. Page tables map virtual addresses as seen by the CPU into physical addresses
  11. as seen on the external memory bus.
  12. Linux defines page tables as a hierarchy which is currently five levels in
  13. height. The architecture code for each supported architecture will then
  14. map this to the restrictions of the hardware.
  15. The physical address corresponding to the virtual address is often referenced
  16. by the underlying physical page frame. The **page frame number** or **pfn**
  17. is the physical address of the page (as seen on the external memory bus)
  18. divided by `PAGE_SIZE`.
  19. Physical memory address 0 will be *pfn 0* and the highest pfn will be
  20. the last page of physical memory the external address bus of the CPU can
  21. address.
  22. With a page granularity of 4KB and a address range of 32 bits, pfn 0 is at
  23. address 0x00000000, pfn 1 is at address 0x00001000, pfn 2 is at 0x00002000
  24. and so on until we reach pfn 0xfffff at 0xfffff000. With 16KB pages pfs are
  25. at 0x00004000, 0x00008000 ... 0xffffc000 and pfn goes from 0 to 0x3fffff.
  26. As you can see, with 4KB pages the page base address uses bits 12-31 of the
  27. address, and this is why `PAGE_SHIFT` in this case is defined as 12 and
  28. `PAGE_SIZE` is usually defined in terms of the page shift as `(1 << PAGE_SHIFT)`
  29. Over time a deeper hierarchy has been developed in response to increasing memory
  30. sizes. When Linux was created, 4KB pages and a single page table called
  31. `swapper_pg_dir` with 1024 entries was used, covering 4MB which coincided with
  32. the fact that Torvald's first computer had 4MB of physical memory. Entries in
  33. this single table were referred to as *PTE*:s - page table entries.
  34. The software page table hierarchy reflects the fact that page table hardware has
  35. become hierarchical and that in turn is done to save page table memory and
  36. speed up mapping.
  37. One could of course imagine a single, linear page table with enormous amounts
  38. of entries, breaking down the whole memory into single pages. Such a page table
  39. would be very sparse, because large portions of the virtual memory usually
  40. remains unused. By using hierarchical page tables large holes in the virtual
  41. address space does not waste valuable page table memory, because it will suffice
  42. to mark large areas as unmapped at a higher level in the page table hierarchy.
  43. Additionally, on modern CPUs, a higher level page table entry can point directly
  44. to a physical memory range, which allows mapping a contiguous range of several
  45. megabytes or even gigabytes in a single high-level page table entry, taking
  46. shortcuts in mapping virtual memory to physical memory: there is no need to
  47. traverse deeper in the hierarchy when you find a large mapped range like this.
  48. The page table hierarchy has now developed into this::
  49. +-----+
  50. | PGD |
  51. +-----+
  52. |
  53. | +-----+
  54. +-->| P4D |
  55. +-----+
  56. |
  57. | +-----+
  58. +-->| PUD |
  59. +-----+
  60. |
  61. | +-----+
  62. +-->| PMD |
  63. +-----+
  64. |
  65. | +-----+
  66. +-->| PTE |
  67. +-----+
  68. Symbols on the different levels of the page table hierarchy have the following
  69. meaning beginning from the bottom:
  70. - **pte**, `pte_t`, `pteval_t` = **Page Table Entry** - mentioned earlier.
  71. The *pte* is an array of `PTRS_PER_PTE` elements of the `pteval_t` type, each
  72. mapping a single page of virtual memory to a single page of physical memory.
  73. The architecture defines the size and contents of `pteval_t`.
  74. A typical example is that the `pteval_t` is a 32- or 64-bit value with the
  75. upper bits being a **pfn** (page frame number), and the lower bits being some
  76. architecture-specific bits such as memory protection.
  77. The **entry** part of the name is a bit confusing because while in Linux 1.0
  78. this did refer to a single page table entry in the single top level page
  79. table, it was retrofitted to be an array of mapping elements when two-level
  80. page tables were first introduced, so the *pte* is the lowermost page
  81. *table*, not a page table *entry*.
  82. - **pmd**, `pmd_t`, `pmdval_t` = **Page Middle Directory**, the hierarchy right
  83. above the *pte*, with `PTRS_PER_PMD` references to the *pte*:s.
  84. - **pud**, `pud_t`, `pudval_t` = **Page Upper Directory** was introduced after
  85. the other levels to handle 4-level page tables. It is potentially unused,
  86. or *folded* as we will discuss later.
  87. - **p4d**, `p4d_t`, `p4dval_t` = **Page Level 4 Directory** was introduced to
  88. handle 5-level page tables after the *pud* was introduced. Now it was clear
  89. that we needed to replace *pgd*, *pmd*, *pud* etc with a figure indicating the
  90. directory level and that we cannot go on with ad hoc names any more. This
  91. is only used on systems which actually have 5 levels of page tables, otherwise
  92. it is folded.
  93. - **pgd**, `pgd_t`, `pgdval_t` = **Page Global Directory** - the Linux kernel
  94. main page table handling the PGD for the kernel memory is still found in
  95. `swapper_pg_dir`, but each userspace process in the system also has its own
  96. memory context and thus its own *pgd*, found in `struct mm_struct` which
  97. in turn is referenced to in each `struct task_struct`. So tasks have memory
  98. context in the form of a `struct mm_struct` and this in turn has a
  99. `struct pgt_t *pgd` pointer to the corresponding page global directory.
  100. To repeat: each level in the page table hierarchy is a *array of pointers*, so
  101. the **pgd** contains `PTRS_PER_PGD` pointers to the next level below, **p4d**
  102. contains `PTRS_PER_P4D` pointers to **pud** items and so on. The number of
  103. pointers on each level is architecture-defined.::
  104. PMD
  105. --> +-----+ PTE
  106. | ptr |-------> +-----+
  107. | ptr |- | ptr |-------> PAGE
  108. | ptr | \ | ptr |
  109. | ptr | \ ...
  110. | ... | \
  111. | ptr | \ PTE
  112. +-----+ +----> +-----+
  113. | ptr |-------> PAGE
  114. | ptr |
  115. ...
  116. Page Table Folding
  117. ==================
  118. If the architecture does not use all the page table levels, they can be *folded*
  119. which means skipped, and all operations performed on page tables will be
  120. compile-time augmented to just skip a level when accessing the next lower
  121. level.
  122. Page table handling code that wishes to be architecture-neutral, such as the
  123. virtual memory manager, will need to be written so that it traverses all of the
  124. currently five levels. This style should also be preferred for
  125. architecture-specific code, so as to be robust to future changes.
  126. MMU, TLB, and Page Faults
  127. =========================
  128. The `Memory Management Unit (MMU)` is a hardware component that handles virtual
  129. to physical address translations. It may use relatively small caches in hardware
  130. called `Translation Lookaside Buffers (TLBs)` and `Page Walk Caches` to speed up
  131. these translations.
  132. When CPU accesses a memory location, it provides a virtual address to the MMU,
  133. which checks if there is the existing translation in the TLB or in the Page
  134. Walk Caches (on architectures that support them). If no translation is found,
  135. MMU uses the page walks to determine the physical address and create the map.
  136. The dirty bit for a page is set (i.e., turned on) when the page is written to.
  137. Each page of memory has associated permission and dirty bits. The latter
  138. indicate that the page has been modified since it was loaded into memory.
  139. If nothing prevents it, eventually the physical memory can be accessed and the
  140. requested operation on the physical frame is performed.
  141. There are several reasons why the MMU can't find certain translations. It could
  142. happen because the CPU is trying to access memory that the current task is not
  143. permitted to, or because the data is not present into physical memory.
  144. When these conditions happen, the MMU triggers page faults, which are types of
  145. exceptions that signal the CPU to pause the current execution and run a special
  146. function to handle the mentioned exceptions.
  147. There are common and expected causes of page faults. These are triggered by
  148. process management optimization techniques called "Lazy Allocation" and
  149. "Copy-on-Write". Page faults may also happen when frames have been swapped out
  150. to persistent storage (swap partition or file) and evicted from their physical
  151. locations.
  152. These techniques improve memory efficiency, reduce latency, and minimize space
  153. occupation. This document won't go deeper into the details of "Lazy Allocation"
  154. and "Copy-on-Write" because these subjects are out of scope as they belong to
  155. Process Address Management.
  156. Swapping differentiates itself from the other mentioned techniques because it's
  157. undesirable since it's performed as a means to reduce memory under heavy
  158. pressure.
  159. Swapping can't work for memory mapped by kernel logical addresses. These are a
  160. subset of the kernel virtual space that directly maps a contiguous range of
  161. physical memory. Given any logical address, its physical address is determined
  162. with simple arithmetic on an offset. Accesses to logical addresses are fast
  163. because they avoid the need for complex page table lookups at the expenses of
  164. frames not being evictable and pageable out.
  165. If the kernel fails to make room for the data that must be present in the
  166. physical frames, the kernel invokes the out-of-memory (OOM) killer to make room
  167. by terminating lower priority processes until pressure reduces under a safe
  168. threshold.
  169. Additionally, page faults may be also caused by code bugs or by maliciously
  170. crafted addresses that the CPU is instructed to access. A thread of a process
  171. could use instructions to address (non-shared) memory which does not belong to
  172. its own address space, or could try to execute an instruction that want to write
  173. to a read-only location.
  174. If the above-mentioned conditions happen in user-space, the kernel sends a
  175. `Segmentation Fault` (SIGSEGV) signal to the current thread. That signal usually
  176. causes the termination of the thread and of the process it belongs to.
  177. This document is going to simplify and show an high altitude view of how the
  178. Linux kernel handles these page faults, creates tables and tables' entries,
  179. check if memory is present and, if not, requests to load data from persistent
  180. storage or from other devices, and updates the MMU and its caches.
  181. The first steps are architecture dependent. Most architectures jump to
  182. `do_page_fault()`, whereas the x86 interrupt handler is defined by the
  183. `DEFINE_IDTENTRY_RAW_ERRORCODE()` macro which calls `handle_page_fault()`.
  184. Whatever the routes, all architectures end up to the invocation of
  185. `handle_mm_fault()` which, in turn, (likely) ends up calling
  186. `__handle_mm_fault()` to carry out the actual work of allocating the page
  187. tables.
  188. The unfortunate case of not being able to call `__handle_mm_fault()` means
  189. that the virtual address is pointing to areas of physical memory which are not
  190. permitted to be accessed (at least from the current context). This
  191. condition resolves to the kernel sending the above-mentioned SIGSEGV signal
  192. to the process and leads to the consequences already explained.
  193. `__handle_mm_fault()` carries out its work by calling several functions to
  194. find the entry's offsets of the upper layers of the page tables and allocate
  195. the tables that it may need.
  196. The functions that look for the offset have names like `*_offset()`, where the
  197. "*" is for pgd, p4d, pud, pmd, pte; instead the functions to allocate the
  198. corresponding tables, layer by layer, are called `*_alloc`, using the
  199. above-mentioned convention to name them after the corresponding types of tables
  200. in the hierarchy.
  201. The page table walk may end at one of the middle or upper layers (PMD, PUD).
  202. Linux supports larger page sizes than the usual 4KB (i.e., the so called
  203. `huge pages`). When using these kinds of larger pages, higher level pages can
  204. directly map them, with no need to use lower level page entries (PTE). Huge
  205. pages contain large contiguous physical regions that usually span from 2MB to
  206. 1GB. They are respectively mapped by the PMD and PUD page entries.
  207. The huge pages bring with them several benefits like reduced TLB pressure,
  208. reduced page table overhead, memory allocation efficiency, and performance
  209. improvement for certain workloads. However, these benefits come with
  210. trade-offs, like wasted memory and allocation challenges.
  211. At the very end of the walk with allocations, if it didn't return errors,
  212. `__handle_mm_fault()` finally calls `handle_pte_fault()`, which via `do_fault()`
  213. performs one of `do_read_fault()`, `do_cow_fault()`, `do_shared_fault()`.
  214. "read", "cow", "shared" give hints about the reasons and the kind of fault it's
  215. handling.
  216. The actual implementation of the workflow is very complex. Its design allows
  217. Linux to handle page faults in a way that is tailored to the specific
  218. characteristics of each architecture, while still sharing a common overall
  219. structure.
  220. To conclude this high altitude view of how Linux handles page faults, let's
  221. add that the page faults handler can be disabled and enabled respectively with
  222. `pagefault_disable()` and `pagefault_enable()`.
  223. Several code path make use of the latter two functions because they need to
  224. disable traps into the page faults handler, mostly to prevent deadlocks.