mmu.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. .. SPDX-License-Identifier: GPL-2.0
  2. ======================
  3. The x86 kvm shadow mmu
  4. ======================
  5. The mmu (in arch/x86/kvm, files mmu.[ch] and paging_tmpl.h) is responsible
  6. for presenting a standard x86 mmu to the guest, while translating guest
  7. physical addresses to host physical addresses.
  8. The mmu code attempts to satisfy the following requirements:
  9. - correctness:
  10. the guest should not be able to determine that it is running
  11. on an emulated mmu except for timing (we attempt to comply
  12. with the specification, not emulate the characteristics of
  13. a particular implementation such as tlb size)
  14. - security:
  15. the guest must not be able to touch host memory not assigned
  16. to it
  17. - performance:
  18. minimize the performance penalty imposed by the mmu
  19. - scaling:
  20. need to scale to large memory and large vcpu guests
  21. - hardware:
  22. support the full range of x86 virtualization hardware
  23. - integration:
  24. Linux memory management code must be in control of guest memory
  25. so that swapping, page migration, page merging, transparent
  26. hugepages, and similar features work without change
  27. - dirty tracking:
  28. report writes to guest memory to enable live migration
  29. and framebuffer-based displays
  30. - footprint:
  31. keep the amount of pinned kernel memory low (most memory
  32. should be shrinkable)
  33. - reliability:
  34. avoid multipage or GFP_ATOMIC allocations
  35. Acronyms
  36. ========
  37. ==== ====================================================================
  38. pfn host page frame number
  39. hpa host physical address
  40. hva host virtual address
  41. gfn guest frame number
  42. gpa guest physical address
  43. gva guest virtual address
  44. ngpa nested guest physical address
  45. ngva nested guest virtual address
  46. pte page table entry (used also to refer generically to paging structure
  47. entries)
  48. gpte guest pte (referring to gfns)
  49. spte shadow pte (referring to pfns)
  50. tdp two dimensional paging (vendor neutral term for NPT and EPT)
  51. ==== ====================================================================
  52. Virtual and real hardware supported
  53. ===================================
  54. The mmu supports first-generation mmu hardware, which allows an atomic switch
  55. of the current paging mode and cr3 during guest entry, as well as
  56. two-dimensional paging (AMD's NPT and Intel's EPT). The emulated hardware
  57. it exposes is the traditional 2/3/4 level x86 mmu, with support for global
  58. pages, pae, pse, pse36, cr0.wp, and 1GB pages. Emulated hardware also
  59. able to expose NPT capable hardware on NPT capable hosts.
  60. Translation
  61. ===========
  62. The primary job of the mmu is to program the processor's mmu to translate
  63. addresses for the guest. Different translations are required at different
  64. times:
  65. - when guest paging is disabled, we translate guest physical addresses to
  66. host physical addresses (gpa->hpa)
  67. - when guest paging is enabled, we translate guest virtual addresses, to
  68. guest physical addresses, to host physical addresses (gva->gpa->hpa)
  69. - when the guest launches a guest of its own, we translate nested guest
  70. virtual addresses, to nested guest physical addresses, to guest physical
  71. addresses, to host physical addresses (ngva->ngpa->gpa->hpa)
  72. The primary challenge is to encode between 1 and 3 translations into hardware
  73. that support only 1 (traditional) and 2 (tdp) translations. When the
  74. number of required translations matches the hardware, the mmu operates in
  75. direct mode; otherwise it operates in shadow mode (see below).
  76. Memory
  77. ======
  78. Guest memory (gpa) is part of the user address space of the process that is
  79. using kvm. Userspace defines the translation between guest addresses and user
  80. addresses (gpa->hva); note that two gpas may alias to the same hva, but not
  81. vice versa.
  82. These hvas may be backed using any method available to the host: anonymous
  83. memory, file backed memory, and device memory. Memory might be paged by the
  84. host at any time.
  85. Events
  86. ======
  87. The mmu is driven by events, some from the guest, some from the host.
  88. Guest generated events:
  89. - writes to control registers (especially cr3)
  90. - invlpg/invlpga instruction execution
  91. - access to missing or protected translations
  92. Host generated events:
  93. - changes in the gpa->hpa translation (either through gpa->hva changes or
  94. through hva->hpa changes)
  95. - memory pressure (the shrinker)
  96. Shadow pages
  97. ============
  98. The principal data structure is the shadow page, 'struct kvm_mmu_page'. A
  99. shadow page contains 512 sptes, which can be either leaf or nonleaf sptes. A
  100. shadow page may contain a mix of leaf and nonleaf sptes.
  101. A nonleaf spte allows the hardware mmu to reach the leaf pages and
  102. is not related to a translation directly. It points to other shadow pages.
  103. A leaf spte corresponds to either one or two translations encoded into
  104. one paging structure entry. These are always the lowest level of the
  105. translation stack, with optional higher level translations left to NPT/EPT.
  106. Leaf ptes point at guest pages.
  107. The following table shows translations encoded by leaf ptes, with higher-level
  108. translations in parentheses:
  109. Non-nested guests::
  110. nonpaging: gpa->hpa
  111. paging: gva->gpa->hpa
  112. paging, tdp: (gva->)gpa->hpa
  113. Nested guests::
  114. non-tdp: ngva->gpa->hpa (*)
  115. tdp: (ngva->)ngpa->gpa->hpa
  116. (*) the guest hypervisor will encode the ngva->gpa translation into its page
  117. tables if npt is not present
  118. Shadow pages contain the following information:
  119. role.level:
  120. The level in the shadow paging hierarchy that this shadow page belongs to.
  121. 1=4k sptes, 2=2M sptes, 3=1G sptes, etc.
  122. role.direct:
  123. If set, leaf sptes reachable from this page are for a linear range.
  124. Examples include real mode translation, large guest pages backed by small
  125. host pages, and gpa->hpa translations when NPT or EPT is active.
  126. The linear range starts at (gfn << PAGE_SHIFT) and its size is determined
  127. by role.level (2MB for first level, 1GB for second level, 0.5TB for third
  128. level, 256TB for fourth level)
  129. If clear, this page corresponds to a guest page table denoted by the gfn
  130. field.
  131. role.quadrant:
  132. When role.has_4_byte_gpte=1, the guest uses 32-bit gptes while the host uses 64-bit
  133. sptes. That means a guest page table contains more ptes than the host,
  134. so multiple shadow pages are needed to shadow one guest page.
  135. For first-level shadow pages, role.quadrant can be 0 or 1 and denotes the
  136. first or second 512-gpte block in the guest page table. For second-level
  137. page tables, each 32-bit gpte is converted to two 64-bit sptes
  138. (since each first-level guest page is shadowed by two first-level
  139. shadow pages) so role.quadrant takes values in the range 0..3. Each
  140. quadrant maps 1GB virtual address space.
  141. role.access:
  142. Inherited guest access permissions from the parent ptes in the form uwx.
  143. Note execute permission is positive, not negative.
  144. role.invalid:
  145. The page is invalid and should not be used. It is a root page that is
  146. currently pinned (by a cpu hardware register pointing to it); once it is
  147. unpinned it will be destroyed.
  148. role.has_4_byte_gpte:
  149. Reflects the size of the guest PTE for which the page is valid, i.e. '0'
  150. if direct map or 64-bit gptes are in use, '1' if 32-bit gptes are in use.
  151. role.efer_nx:
  152. Contains the value of efer.nx for which the page is valid.
  153. role.cr0_wp:
  154. Contains the value of cr0.wp for which the page is valid.
  155. role.smep_andnot_wp:
  156. Contains the value of cr4.smep && !cr0.wp for which the page is valid
  157. (pages for which this is true are different from other pages; see the
  158. treatment of cr0.wp=0 below).
  159. role.smap_andnot_wp:
  160. Contains the value of cr4.smap && !cr0.wp for which the page is valid
  161. (pages for which this is true are different from other pages; see the
  162. treatment of cr0.wp=0 below).
  163. role.smm:
  164. Is 1 if the page is valid in system management mode. This field
  165. determines which of the kvm_memslots array was used to build this
  166. shadow page; it is also used to go back from a struct kvm_mmu_page
  167. to a memslot, through the kvm_memslots_for_spte_role macro and
  168. __gfn_to_memslot.
  169. role.ad_disabled:
  170. Is 1 if the MMU instance cannot use A/D bits. EPT did not have A/D
  171. bits before Haswell; shadow EPT page tables also cannot use A/D bits
  172. if the L1 hypervisor does not enable them.
  173. role.passthrough:
  174. The page is not backed by a guest page table, but its first entry
  175. points to one. This is set if NPT uses 5-level page tables (host
  176. CR4.LA57=1) and is shadowing L1's 4-level NPT (L1 CR4.LA57=1).
  177. gfn:
  178. Either the guest page table containing the translations shadowed by this
  179. page, or the base page frame for linear translations. See role.direct.
  180. spt:
  181. A pageful of 64-bit sptes containing the translations for this page.
  182. Accessed by both kvm and hardware.
  183. The page pointed to by spt will have its page->private pointing back
  184. at the shadow page structure.
  185. sptes in spt point either at guest pages, or at lower-level shadow pages.
  186. Specifically, if sp1 and sp2 are shadow pages, then sp1->spt[n] may point
  187. at __pa(sp2->spt). sp2 will point back at sp1 through parent_pte.
  188. The spt array forms a DAG structure with the shadow page as a node, and
  189. guest pages as leaves.
  190. gfns:
  191. An array of 512 guest frame numbers, one for each present pte. Used to
  192. perform a reverse map from a pte to a gfn. When role.direct is set, any
  193. element of this array can be calculated from the gfn field when used, in
  194. this case, the array of gfns is not allocated. See role.direct and gfn.
  195. root_count:
  196. A counter keeping track of how many hardware registers (guest cr3 or
  197. pdptrs) are now pointing at the page. While this counter is nonzero, the
  198. page cannot be destroyed. See role.invalid.
  199. parent_ptes:
  200. The reverse mapping for the pte/ptes pointing at this page's spt. If
  201. parent_ptes bit 0 is zero, only one spte points at this page and
  202. parent_ptes points at this single spte, otherwise, there exists multiple
  203. sptes pointing at this page and (parent_ptes & ~0x1) points at a data
  204. structure with a list of parent sptes.
  205. unsync:
  206. If true, then the translations in this page may not match the guest's
  207. translation. This is equivalent to the state of the tlb when a pte is
  208. changed but before the tlb entry is flushed. Accordingly, unsync ptes
  209. are synchronized when the guest executes invlpg or flushes its tlb by
  210. other means. Valid for leaf pages.
  211. unsync_children:
  212. How many sptes in the page point at pages that are unsync (or have
  213. unsynchronized children).
  214. unsync_child_bitmap:
  215. A bitmap indicating which sptes in spt point (directly or indirectly) at
  216. pages that may be unsynchronized. Used to quickly locate all unsychronized
  217. pages reachable from a given page.
  218. clear_spte_count:
  219. Only present on 32-bit hosts, where a 64-bit spte cannot be written
  220. atomically. The reader uses this while running out of the MMU lock
  221. to detect in-progress updates and retry them until the writer has
  222. finished the write.
  223. write_flooding_count:
  224. A guest may write to a page table many times, causing a lot of
  225. emulations if the page needs to be write-protected (see "Synchronized
  226. and unsynchronized pages" below). Leaf pages can be unsynchronized
  227. so that they do not trigger frequent emulation, but this is not
  228. possible for non-leafs. This field counts the number of emulations
  229. since the last time the page table was actually used; if emulation
  230. is triggered too frequently on this page, KVM will unmap the page
  231. to avoid emulation in the future.
  232. Reverse map
  233. ===========
  234. The mmu maintains a reverse mapping whereby all ptes mapping a page can be
  235. reached given its gfn. This is used, for example, when swapping out a page.
  236. Synchronized and unsynchronized pages
  237. =====================================
  238. The guest uses two events to synchronize its tlb and page tables: tlb flushes
  239. and page invalidations (invlpg).
  240. A tlb flush means that we need to synchronize all sptes reachable from the
  241. guest's cr3. This is expensive, so we keep all guest page tables write
  242. protected, and synchronize sptes to gptes when a gpte is written.
  243. A special case is when a guest page table is reachable from the current
  244. guest cr3. In this case, the guest is obliged to issue an invlpg instruction
  245. before using the translation. We take advantage of that by removing write
  246. protection from the guest page, and allowing the guest to modify it freely.
  247. We synchronize modified gptes when the guest invokes invlpg. This reduces
  248. the amount of emulation we have to do when the guest modifies multiple gptes,
  249. or when the a guest page is no longer used as a page table and is used for
  250. random guest data.
  251. As a side effect we have to resynchronize all reachable unsynchronized shadow
  252. pages on a tlb flush.
  253. Reaction to events
  254. ==================
  255. - guest page fault (or npt page fault, or ept violation)
  256. This is the most complicated event. The cause of a page fault can be:
  257. - a true guest fault (the guest translation won't allow the access) (*)
  258. - access to a missing translation
  259. - access to a protected translation
  260. - when logging dirty pages, memory is write protected
  261. - synchronized shadow pages are write protected (*)
  262. - access to untranslatable memory (mmio)
  263. (*) not applicable in direct mode
  264. Handling a page fault is performed as follows:
  265. - if the RSV bit of the error code is set, the page fault is caused by guest
  266. accessing MMIO and cached MMIO information is available.
  267. - walk shadow page table
  268. - check for valid generation number in the spte (see "Fast invalidation of
  269. MMIO sptes" below)
  270. - cache the information to vcpu->arch.mmio_gva, vcpu->arch.mmio_access and
  271. vcpu->arch.mmio_gfn, and call the emulator
  272. - If both P bit and R/W bit of error code are set, this could possibly
  273. be handled as a "fast page fault" (fixed without taking the MMU lock). See
  274. the description in Documentation/virt/kvm/locking.rst.
  275. - if needed, walk the guest page tables to determine the guest translation
  276. (gva->gpa or ngpa->gpa)
  277. - if permissions are insufficient, reflect the fault back to the guest
  278. - determine the host page
  279. - if this is an mmio request, there is no host page; cache the info to
  280. vcpu->arch.mmio_gva, vcpu->arch.mmio_access and vcpu->arch.mmio_gfn
  281. - walk the shadow page table to find the spte for the translation,
  282. instantiating missing intermediate page tables as necessary
  283. - If this is an mmio request, cache the mmio info to the spte and set some
  284. reserved bit on the spte (see callers of kvm_mmu_set_mmio_spte_mask)
  285. - try to unsynchronize the page
  286. - if successful, we can let the guest continue and modify the gpte
  287. - emulate the instruction
  288. - if failed, unshadow the page and let the guest continue
  289. - update any translations that were modified by the instruction
  290. invlpg handling:
  291. - walk the shadow page hierarchy and drop affected translations
  292. - try to reinstantiate the indicated translation in the hope that the
  293. guest will use it in the near future
  294. Guest control register updates:
  295. - mov to cr3
  296. - look up new shadow roots
  297. - synchronize newly reachable shadow pages
  298. - mov to cr0/cr4/efer
  299. - set up mmu context for new paging mode
  300. - look up new shadow roots
  301. - synchronize newly reachable shadow pages
  302. Host translation updates:
  303. - mmu notifier called with updated hva
  304. - look up affected sptes through reverse map
  305. - drop (or update) translations
  306. Emulating cr0.wp
  307. ================
  308. If tdp is not enabled, the host must keep cr0.wp=1 so page write protection
  309. works for the guest kernel, not guest userspace. When the guest
  310. cr0.wp=1, this does not present a problem. However when the guest cr0.wp=0,
  311. we cannot map the permissions for gpte.u=1, gpte.w=0 to any spte (the
  312. semantics require allowing any guest kernel access plus user read access).
  313. We handle this by mapping the permissions to two possible sptes, depending
  314. on fault type:
  315. - kernel write fault: spte.u=0, spte.w=1 (allows full kernel access,
  316. disallows user access)
  317. - read fault: spte.u=1, spte.w=0 (allows full read access, disallows kernel
  318. write access)
  319. (user write faults generate a #PF)
  320. In the first case there are two additional complications:
  321. - if CR4.SMEP is enabled: since we've turned the page into a kernel page,
  322. the kernel may now execute it. We handle this by also setting spte.nx.
  323. If we get a user fetch or read fault, we'll change spte.u=1 and
  324. spte.nx=gpte.nx back. For this to work, KVM forces EFER.NX to 1 when
  325. shadow paging is in use.
  326. - if CR4.SMAP is disabled: since the page has been changed to a kernel
  327. page, it can not be reused when CR4.SMAP is enabled. We set
  328. CR4.SMAP && !CR0.WP into shadow page's role to avoid this case. Note,
  329. here we do not care the case that CR4.SMAP is enabled since KVM will
  330. directly inject #PF to guest due to failed permission check.
  331. To prevent an spte that was converted into a kernel page with cr0.wp=0
  332. from being written by the kernel after cr0.wp has changed to 1, we make
  333. the value of cr0.wp part of the page role. This means that an spte created
  334. with one value of cr0.wp cannot be used when cr0.wp has a different value -
  335. it will simply be missed by the shadow page lookup code. A similar issue
  336. exists when an spte created with cr0.wp=0 and cr4.smep=0 is used after
  337. changing cr4.smep to 1. To avoid this, the value of !cr0.wp && cr4.smep
  338. is also made a part of the page role.
  339. Large pages
  340. ===========
  341. The mmu supports all combinations of large and small guest and host pages.
  342. Supported page sizes include 4k, 2M, 4M, and 1G. 4M pages are treated as
  343. two separate 2M pages, on both guest and host, since the mmu always uses PAE
  344. paging.
  345. To instantiate a large spte, four constraints must be satisfied:
  346. - the spte must point to a large host page
  347. - the guest pte must be a large pte of at least equivalent size (if tdp is
  348. enabled, there is no guest pte and this condition is satisfied)
  349. - if the spte will be writeable, the large page frame may not overlap any
  350. write-protected pages
  351. - the guest page must be wholly contained by a single memory slot
  352. To check the last two conditions, the mmu maintains a ->disallow_lpage set of
  353. arrays for each memory slot and large page size. Every write protected page
  354. causes its disallow_lpage to be incremented, thus preventing instantiation of
  355. a large spte. The frames at the end of an unaligned memory slot have
  356. artificially inflated ->disallow_lpages so they can never be instantiated.
  357. Fast invalidation of MMIO sptes
  358. ===============================
  359. As mentioned in "Reaction to events" above, kvm will cache MMIO
  360. information in leaf sptes. When a new memslot is added or an existing
  361. memslot is changed, this information may become stale and needs to be
  362. invalidated. This also needs to hold the MMU lock while walking all
  363. shadow pages, and is made more scalable with a similar technique.
  364. MMIO sptes have a few spare bits, which are used to store a
  365. generation number. The global generation number is stored in
  366. kvm_memslots(kvm)->generation, and increased whenever guest memory info
  367. changes.
  368. When KVM finds an MMIO spte, it checks the generation number of the spte.
  369. If the generation number of the spte does not equal the global generation
  370. number, it will ignore the cached MMIO information and handle the page
  371. fault through the slow path.
  372. Since only 18 bits are used to store generation-number on mmio spte, all
  373. pages are zapped when there is an overflow.
  374. Unfortunately, a single memory access might access kvm_memslots(kvm) multiple
  375. times, the last one happening when the generation number is retrieved and
  376. stored into the MMIO spte. Thus, the MMIO spte might be created based on
  377. out-of-date information, but with an up-to-date generation number.
  378. To avoid this, the generation number is incremented again after synchronize_srcu
  379. returns; thus, bit 63 of kvm_memslots(kvm)->generation set to 1 only during a
  380. memslot update, while some SRCU readers might be using the old copy. We do not
  381. want to use an MMIO sptes created with an odd generation number, and we can do
  382. this without losing a bit in the MMIO spte. The "update in-progress" bit of the
  383. generation is not stored in MMIO spte, and is so is implicitly zero when the
  384. generation is extracted out of the spte. If KVM is unlucky and creates an MMIO
  385. spte while an update is in-progress, the next access to the spte will always be
  386. a cache miss. For example, a subsequent access during the update window will
  387. miss due to the in-progress flag diverging, while an access after the update
  388. window closes will have a higher generation number (as compared to the spte).
  389. Further reading
  390. ===============
  391. - NPT presentation from KVM Forum 2008
  392. https://www.linux-kvm.org/images/c/c8/KvmForum2008%24kdf2008_21.pdf