Back to home page

OSCL-LXR

 
 

    


0001 .. SPDX-License-Identifier: GPL-2.0
0002 
0003 ======================
0004 The x86 kvm shadow mmu
0005 ======================
0006 
0007 The mmu (in arch/x86/kvm, files mmu.[ch] and paging_tmpl.h) is responsible
0008 for presenting a standard x86 mmu to the guest, while translating guest
0009 physical addresses to host physical addresses.
0010 
0011 The mmu code attempts to satisfy the following requirements:
0012 
0013 - correctness:
0014                the guest should not be able to determine that it is running
0015                on an emulated mmu except for timing (we attempt to comply
0016                with the specification, not emulate the characteristics of
0017                a particular implementation such as tlb size)
0018 - security:
0019                the guest must not be able to touch host memory not assigned
0020                to it
0021 - performance:
0022                minimize the performance penalty imposed by the mmu
0023 - scaling:
0024                need to scale to large memory and large vcpu guests
0025 - hardware:
0026                support the full range of x86 virtualization hardware
0027 - integration:
0028                Linux memory management code must be in control of guest memory
0029                so that swapping, page migration, page merging, transparent
0030                hugepages, and similar features work without change
0031 - dirty tracking:
0032                report writes to guest memory to enable live migration
0033                and framebuffer-based displays
0034 - footprint:
0035                keep the amount of pinned kernel memory low (most memory
0036                should be shrinkable)
0037 - reliability:
0038                avoid multipage or GFP_ATOMIC allocations
0039 
0040 Acronyms
0041 ========
0042 
0043 ====  ====================================================================
0044 pfn   host page frame number
0045 hpa   host physical address
0046 hva   host virtual address
0047 gfn   guest frame number
0048 gpa   guest physical address
0049 gva   guest virtual address
0050 ngpa  nested guest physical address
0051 ngva  nested guest virtual address
0052 pte   page table entry (used also to refer generically to paging structure
0053       entries)
0054 gpte  guest pte (referring to gfns)
0055 spte  shadow pte (referring to pfns)
0056 tdp   two dimensional paging (vendor neutral term for NPT and EPT)
0057 ====  ====================================================================
0058 
0059 Virtual and real hardware supported
0060 ===================================
0061 
0062 The mmu supports first-generation mmu hardware, which allows an atomic switch
0063 of the current paging mode and cr3 during guest entry, as well as
0064 two-dimensional paging (AMD's NPT and Intel's EPT).  The emulated hardware
0065 it exposes is the traditional 2/3/4 level x86 mmu, with support for global
0066 pages, pae, pse, pse36, cr0.wp, and 1GB pages. Emulated hardware also
0067 able to expose NPT capable hardware on NPT capable hosts.
0068 
0069 Translation
0070 ===========
0071 
0072 The primary job of the mmu is to program the processor's mmu to translate
0073 addresses for the guest.  Different translations are required at different
0074 times:
0075 
0076 - when guest paging is disabled, we translate guest physical addresses to
0077   host physical addresses (gpa->hpa)
0078 - when guest paging is enabled, we translate guest virtual addresses, to
0079   guest physical addresses, to host physical addresses (gva->gpa->hpa)
0080 - when the guest launches a guest of its own, we translate nested guest
0081   virtual addresses, to nested guest physical addresses, to guest physical
0082   addresses, to host physical addresses (ngva->ngpa->gpa->hpa)
0083 
0084 The primary challenge is to encode between 1 and 3 translations into hardware
0085 that support only 1 (traditional) and 2 (tdp) translations.  When the
0086 number of required translations matches the hardware, the mmu operates in
0087 direct mode; otherwise it operates in shadow mode (see below).
0088 
0089 Memory
0090 ======
0091 
0092 Guest memory (gpa) is part of the user address space of the process that is
0093 using kvm.  Userspace defines the translation between guest addresses and user
0094 addresses (gpa->hva); note that two gpas may alias to the same hva, but not
0095 vice versa.
0096 
0097 These hvas may be backed using any method available to the host: anonymous
0098 memory, file backed memory, and device memory.  Memory might be paged by the
0099 host at any time.
0100 
0101 Events
0102 ======
0103 
0104 The mmu is driven by events, some from the guest, some from the host.
0105 
0106 Guest generated events:
0107 
0108 - writes to control registers (especially cr3)
0109 - invlpg/invlpga instruction execution
0110 - access to missing or protected translations
0111 
0112 Host generated events:
0113 
0114 - changes in the gpa->hpa translation (either through gpa->hva changes or
0115   through hva->hpa changes)
0116 - memory pressure (the shrinker)
0117 
0118 Shadow pages
0119 ============
0120 
0121 The principal data structure is the shadow page, 'struct kvm_mmu_page'.  A
0122 shadow page contains 512 sptes, which can be either leaf or nonleaf sptes.  A
0123 shadow page may contain a mix of leaf and nonleaf sptes.
0124 
0125 A nonleaf spte allows the hardware mmu to reach the leaf pages and
0126 is not related to a translation directly.  It points to other shadow pages.
0127 
0128 A leaf spte corresponds to either one or two translations encoded into
0129 one paging structure entry.  These are always the lowest level of the
0130 translation stack, with optional higher level translations left to NPT/EPT.
0131 Leaf ptes point at guest pages.
0132 
0133 The following table shows translations encoded by leaf ptes, with higher-level
0134 translations in parentheses:
0135 
0136  Non-nested guests::
0137 
0138   nonpaging:     gpa->hpa
0139   paging:        gva->gpa->hpa
0140   paging, tdp:   (gva->)gpa->hpa
0141 
0142  Nested guests::
0143 
0144   non-tdp:       ngva->gpa->hpa  (*)
0145   tdp:           (ngva->)ngpa->gpa->hpa
0146 
0147   (*) the guest hypervisor will encode the ngva->gpa translation into its page
0148       tables if npt is not present
0149 
0150 Shadow pages contain the following information:
0151   role.level:
0152     The level in the shadow paging hierarchy that this shadow page belongs to.
0153     1=4k sptes, 2=2M sptes, 3=1G sptes, etc.
0154   role.direct:
0155     If set, leaf sptes reachable from this page are for a linear range.
0156     Examples include real mode translation, large guest pages backed by small
0157     host pages, and gpa->hpa translations when NPT or EPT is active.
0158     The linear range starts at (gfn << PAGE_SHIFT) and its size is determined
0159     by role.level (2MB for first level, 1GB for second level, 0.5TB for third
0160     level, 256TB for fourth level)
0161     If clear, this page corresponds to a guest page table denoted by the gfn
0162     field.
0163   role.quadrant:
0164     When role.has_4_byte_gpte=1, the guest uses 32-bit gptes while the host uses 64-bit
0165     sptes.  That means a guest page table contains more ptes than the host,
0166     so multiple shadow pages are needed to shadow one guest page.
0167     For first-level shadow pages, role.quadrant can be 0 or 1 and denotes the
0168     first or second 512-gpte block in the guest page table.  For second-level
0169     page tables, each 32-bit gpte is converted to two 64-bit sptes
0170     (since each first-level guest page is shadowed by two first-level
0171     shadow pages) so role.quadrant takes values in the range 0..3.  Each
0172     quadrant maps 1GB virtual address space.
0173   role.access:
0174     Inherited guest access permissions from the parent ptes in the form uwx.
0175     Note execute permission is positive, not negative.
0176   role.invalid:
0177     The page is invalid and should not be used.  It is a root page that is
0178     currently pinned (by a cpu hardware register pointing to it); once it is
0179     unpinned it will be destroyed.
0180   role.has_4_byte_gpte:
0181     Reflects the size of the guest PTE for which the page is valid, i.e. '0'
0182     if direct map or 64-bit gptes are in use, '1' if 32-bit gptes are in use.
0183   role.efer_nx:
0184     Contains the value of efer.nx for which the page is valid.
0185   role.cr0_wp:
0186     Contains the value of cr0.wp for which the page is valid.
0187   role.smep_andnot_wp:
0188     Contains the value of cr4.smep && !cr0.wp for which the page is valid
0189     (pages for which this is true are different from other pages; see the
0190     treatment of cr0.wp=0 below).
0191   role.smap_andnot_wp:
0192     Contains the value of cr4.smap && !cr0.wp for which the page is valid
0193     (pages for which this is true are different from other pages; see the
0194     treatment of cr0.wp=0 below).
0195   role.smm:
0196     Is 1 if the page is valid in system management mode.  This field
0197     determines which of the kvm_memslots array was used to build this
0198     shadow page; it is also used to go back from a struct kvm_mmu_page
0199     to a memslot, through the kvm_memslots_for_spte_role macro and
0200     __gfn_to_memslot.
0201   role.ad_disabled:
0202     Is 1 if the MMU instance cannot use A/D bits.  EPT did not have A/D
0203     bits before Haswell; shadow EPT page tables also cannot use A/D bits
0204     if the L1 hypervisor does not enable them.
0205   role.passthrough:
0206     The page is not backed by a guest page table, but its first entry
0207     points to one.  This is set if NPT uses 5-level page tables (host
0208     CR4.LA57=1) and is shadowing L1's 4-level NPT (L1 CR4.LA57=1).
0209   gfn:
0210     Either the guest page table containing the translations shadowed by this
0211     page, or the base page frame for linear translations.  See role.direct.
0212   spt:
0213     A pageful of 64-bit sptes containing the translations for this page.
0214     Accessed by both kvm and hardware.
0215     The page pointed to by spt will have its page->private pointing back
0216     at the shadow page structure.
0217     sptes in spt point either at guest pages, or at lower-level shadow pages.
0218     Specifically, if sp1 and sp2 are shadow pages, then sp1->spt[n] may point
0219     at __pa(sp2->spt).  sp2 will point back at sp1 through parent_pte.
0220     The spt array forms a DAG structure with the shadow page as a node, and
0221     guest pages as leaves.
0222   gfns:
0223     An array of 512 guest frame numbers, one for each present pte.  Used to
0224     perform a reverse map from a pte to a gfn. When role.direct is set, any
0225     element of this array can be calculated from the gfn field when used, in
0226     this case, the array of gfns is not allocated. See role.direct and gfn.
0227   root_count:
0228     A counter keeping track of how many hardware registers (guest cr3 or
0229     pdptrs) are now pointing at the page.  While this counter is nonzero, the
0230     page cannot be destroyed.  See role.invalid.
0231   parent_ptes:
0232     The reverse mapping for the pte/ptes pointing at this page's spt. If
0233     parent_ptes bit 0 is zero, only one spte points at this page and
0234     parent_ptes points at this single spte, otherwise, there exists multiple
0235     sptes pointing at this page and (parent_ptes & ~0x1) points at a data
0236     structure with a list of parent sptes.
0237   unsync:
0238     If true, then the translations in this page may not match the guest's
0239     translation.  This is equivalent to the state of the tlb when a pte is
0240     changed but before the tlb entry is flushed.  Accordingly, unsync ptes
0241     are synchronized when the guest executes invlpg or flushes its tlb by
0242     other means.  Valid for leaf pages.
0243   unsync_children:
0244     How many sptes in the page point at pages that are unsync (or have
0245     unsynchronized children).
0246   unsync_child_bitmap:
0247     A bitmap indicating which sptes in spt point (directly or indirectly) at
0248     pages that may be unsynchronized.  Used to quickly locate all unsychronized
0249     pages reachable from a given page.
0250   clear_spte_count:
0251     Only present on 32-bit hosts, where a 64-bit spte cannot be written
0252     atomically.  The reader uses this while running out of the MMU lock
0253     to detect in-progress updates and retry them until the writer has
0254     finished the write.
0255   write_flooding_count:
0256     A guest may write to a page table many times, causing a lot of
0257     emulations if the page needs to be write-protected (see "Synchronized
0258     and unsynchronized pages" below).  Leaf pages can be unsynchronized
0259     so that they do not trigger frequent emulation, but this is not
0260     possible for non-leafs.  This field counts the number of emulations
0261     since the last time the page table was actually used; if emulation
0262     is triggered too frequently on this page, KVM will unmap the page
0263     to avoid emulation in the future.
0264 
0265 Reverse map
0266 ===========
0267 
0268 The mmu maintains a reverse mapping whereby all ptes mapping a page can be
0269 reached given its gfn.  This is used, for example, when swapping out a page.
0270 
0271 Synchronized and unsynchronized pages
0272 =====================================
0273 
0274 The guest uses two events to synchronize its tlb and page tables: tlb flushes
0275 and page invalidations (invlpg).
0276 
0277 A tlb flush means that we need to synchronize all sptes reachable from the
0278 guest's cr3.  This is expensive, so we keep all guest page tables write
0279 protected, and synchronize sptes to gptes when a gpte is written.
0280 
0281 A special case is when a guest page table is reachable from the current
0282 guest cr3.  In this case, the guest is obliged to issue an invlpg instruction
0283 before using the translation.  We take advantage of that by removing write
0284 protection from the guest page, and allowing the guest to modify it freely.
0285 We synchronize modified gptes when the guest invokes invlpg.  This reduces
0286 the amount of emulation we have to do when the guest modifies multiple gptes,
0287 or when the a guest page is no longer used as a page table and is used for
0288 random guest data.
0289 
0290 As a side effect we have to resynchronize all reachable unsynchronized shadow
0291 pages on a tlb flush.
0292 
0293 
0294 Reaction to events
0295 ==================
0296 
0297 - guest page fault (or npt page fault, or ept violation)
0298 
0299 This is the most complicated event.  The cause of a page fault can be:
0300 
0301   - a true guest fault (the guest translation won't allow the access) (*)
0302   - access to a missing translation
0303   - access to a protected translation
0304     - when logging dirty pages, memory is write protected
0305     - synchronized shadow pages are write protected (*)
0306   - access to untranslatable memory (mmio)
0307 
0308   (*) not applicable in direct mode
0309 
0310 Handling a page fault is performed as follows:
0311 
0312  - if the RSV bit of the error code is set, the page fault is caused by guest
0313    accessing MMIO and cached MMIO information is available.
0314 
0315    - walk shadow page table
0316    - check for valid generation number in the spte (see "Fast invalidation of
0317      MMIO sptes" below)
0318    - cache the information to vcpu->arch.mmio_gva, vcpu->arch.mmio_access and
0319      vcpu->arch.mmio_gfn, and call the emulator
0320 
0321  - If both P bit and R/W bit of error code are set, this could possibly
0322    be handled as a "fast page fault" (fixed without taking the MMU lock).  See
0323    the description in Documentation/virt/kvm/locking.rst.
0324 
0325  - if needed, walk the guest page tables to determine the guest translation
0326    (gva->gpa or ngpa->gpa)
0327 
0328    - if permissions are insufficient, reflect the fault back to the guest
0329 
0330  - determine the host page
0331 
0332    - if this is an mmio request, there is no host page; cache the info to
0333      vcpu->arch.mmio_gva, vcpu->arch.mmio_access and vcpu->arch.mmio_gfn
0334 
0335  - walk the shadow page table to find the spte for the translation,
0336    instantiating missing intermediate page tables as necessary
0337 
0338    - If this is an mmio request, cache the mmio info to the spte and set some
0339      reserved bit on the spte (see callers of kvm_mmu_set_mmio_spte_mask)
0340 
0341  - try to unsynchronize the page
0342 
0343    - if successful, we can let the guest continue and modify the gpte
0344 
0345  - emulate the instruction
0346 
0347    - if failed, unshadow the page and let the guest continue
0348 
0349  - update any translations that were modified by the instruction
0350 
0351 invlpg handling:
0352 
0353   - walk the shadow page hierarchy and drop affected translations
0354   - try to reinstantiate the indicated translation in the hope that the
0355     guest will use it in the near future
0356 
0357 Guest control register updates:
0358 
0359 - mov to cr3
0360 
0361   - look up new shadow roots
0362   - synchronize newly reachable shadow pages
0363 
0364 - mov to cr0/cr4/efer
0365 
0366   - set up mmu context for new paging mode
0367   - look up new shadow roots
0368   - synchronize newly reachable shadow pages
0369 
0370 Host translation updates:
0371 
0372   - mmu notifier called with updated hva
0373   - look up affected sptes through reverse map
0374   - drop (or update) translations
0375 
0376 Emulating cr0.wp
0377 ================
0378 
0379 If tdp is not enabled, the host must keep cr0.wp=1 so page write protection
0380 works for the guest kernel, not guest guest userspace.  When the guest
0381 cr0.wp=1, this does not present a problem.  However when the guest cr0.wp=0,
0382 we cannot map the permissions for gpte.u=1, gpte.w=0 to any spte (the
0383 semantics require allowing any guest kernel access plus user read access).
0384 
0385 We handle this by mapping the permissions to two possible sptes, depending
0386 on fault type:
0387 
0388 - kernel write fault: spte.u=0, spte.w=1 (allows full kernel access,
0389   disallows user access)
0390 - read fault: spte.u=1, spte.w=0 (allows full read access, disallows kernel
0391   write access)
0392 
0393 (user write faults generate a #PF)
0394 
0395 In the first case there are two additional complications:
0396 
0397 - if CR4.SMEP is enabled: since we've turned the page into a kernel page,
0398   the kernel may now execute it.  We handle this by also setting spte.nx.
0399   If we get a user fetch or read fault, we'll change spte.u=1 and
0400   spte.nx=gpte.nx back.  For this to work, KVM forces EFER.NX to 1 when
0401   shadow paging is in use.
0402 - if CR4.SMAP is disabled: since the page has been changed to a kernel
0403   page, it can not be reused when CR4.SMAP is enabled. We set
0404   CR4.SMAP && !CR0.WP into shadow page's role to avoid this case. Note,
0405   here we do not care the case that CR4.SMAP is enabled since KVM will
0406   directly inject #PF to guest due to failed permission check.
0407 
0408 To prevent an spte that was converted into a kernel page with cr0.wp=0
0409 from being written by the kernel after cr0.wp has changed to 1, we make
0410 the value of cr0.wp part of the page role.  This means that an spte created
0411 with one value of cr0.wp cannot be used when cr0.wp has a different value -
0412 it will simply be missed by the shadow page lookup code.  A similar issue
0413 exists when an spte created with cr0.wp=0 and cr4.smep=0 is used after
0414 changing cr4.smep to 1.  To avoid this, the value of !cr0.wp && cr4.smep
0415 is also made a part of the page role.
0416 
0417 Large pages
0418 ===========
0419 
0420 The mmu supports all combinations of large and small guest and host pages.
0421 Supported page sizes include 4k, 2M, 4M, and 1G.  4M pages are treated as
0422 two separate 2M pages, on both guest and host, since the mmu always uses PAE
0423 paging.
0424 
0425 To instantiate a large spte, four constraints must be satisfied:
0426 
0427 - the spte must point to a large host page
0428 - the guest pte must be a large pte of at least equivalent size (if tdp is
0429   enabled, there is no guest pte and this condition is satisfied)
0430 - if the spte will be writeable, the large page frame may not overlap any
0431   write-protected pages
0432 - the guest page must be wholly contained by a single memory slot
0433 
0434 To check the last two conditions, the mmu maintains a ->disallow_lpage set of
0435 arrays for each memory slot and large page size.  Every write protected page
0436 causes its disallow_lpage to be incremented, thus preventing instantiation of
0437 a large spte.  The frames at the end of an unaligned memory slot have
0438 artificially inflated ->disallow_lpages so they can never be instantiated.
0439 
0440 Fast invalidation of MMIO sptes
0441 ===============================
0442 
0443 As mentioned in "Reaction to events" above, kvm will cache MMIO
0444 information in leaf sptes.  When a new memslot is added or an existing
0445 memslot is changed, this information may become stale and needs to be
0446 invalidated.  This also needs to hold the MMU lock while walking all
0447 shadow pages, and is made more scalable with a similar technique.
0448 
0449 MMIO sptes have a few spare bits, which are used to store a
0450 generation number.  The global generation number is stored in
0451 kvm_memslots(kvm)->generation, and increased whenever guest memory info
0452 changes.
0453 
0454 When KVM finds an MMIO spte, it checks the generation number of the spte.
0455 If the generation number of the spte does not equal the global generation
0456 number, it will ignore the cached MMIO information and handle the page
0457 fault through the slow path.
0458 
0459 Since only 18 bits are used to store generation-number on mmio spte, all
0460 pages are zapped when there is an overflow.
0461 
0462 Unfortunately, a single memory access might access kvm_memslots(kvm) multiple
0463 times, the last one happening when the generation number is retrieved and
0464 stored into the MMIO spte.  Thus, the MMIO spte might be created based on
0465 out-of-date information, but with an up-to-date generation number.
0466 
0467 To avoid this, the generation number is incremented again after synchronize_srcu
0468 returns; thus, bit 63 of kvm_memslots(kvm)->generation set to 1 only during a
0469 memslot update, while some SRCU readers might be using the old copy.  We do not
0470 want to use an MMIO sptes created with an odd generation number, and we can do
0471 this without losing a bit in the MMIO spte.  The "update in-progress" bit of the
0472 generation is not stored in MMIO spte, and is so is implicitly zero when the
0473 generation is extracted out of the spte.  If KVM is unlucky and creates an MMIO
0474 spte while an update is in-progress, the next access to the spte will always be
0475 a cache miss.  For example, a subsequent access during the update window will
0476 miss due to the in-progress flag diverging, while an access after the update
0477 window closes will have a higher generation number (as compared to the spte).
0478 
0479 
0480 Further reading
0481 ===============
0482 
0483 - NPT presentation from KVM Forum 2008
0484   https://www.linux-kvm.org/images/c/c8/KvmForum2008%24kdf2008_21.pdf