1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
7 *
8 * MMU support
9 *
10 * Copyright (C) 2006 Qumranet, Inc.
11 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12 *
13 * Authors:
14 * Yaniv Kamay <yaniv@qumranet.com>
15 * Avi Kivity <avi@qumranet.com>
16 */
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18
19 #include "irq.h"
20 #include "ioapic.h"
21 #include "mmu.h"
22 #include "mmu_internal.h"
23 #include "tdp_mmu.h"
24 #include "x86.h"
25 #include "kvm_cache_regs.h"
26 #include "smm.h"
27 #include "kvm_emulate.h"
28 #include "page_track.h"
29 #include "cpuid.h"
30 #include "spte.h"
31
32 #include <linux/kvm_host.h>
33 #include <linux/types.h>
34 #include <linux/string.h>
35 #include <linux/mm.h>
36 #include <linux/highmem.h>
37 #include <linux/moduleparam.h>
38 #include <linux/export.h>
39 #include <linux/swap.h>
40 #include <linux/hugetlb.h>
41 #include <linux/compiler.h>
42 #include <linux/srcu.h>
43 #include <linux/slab.h>
44 #include <linux/sched/signal.h>
45 #include <linux/uaccess.h>
46 #include <linux/hash.h>
47 #include <linux/kern_levels.h>
48 #include <linux/kstrtox.h>
49 #include <linux/kthread.h>
50 #include <linux/wordpart.h>
51
52 #include <asm/page.h>
53 #include <asm/memtype.h>
54 #include <asm/cmpxchg.h>
55 #include <asm/io.h>
56 #include <asm/set_memory.h>
57 #include <asm/spec-ctrl.h>
58 #include <asm/vmx.h>
59
60 #include "trace.h"
61
62 static bool nx_hugepage_mitigation_hard_disabled;
63
64 int __read_mostly nx_huge_pages = -1;
65 static uint __read_mostly nx_huge_pages_recovery_period_ms;
66 #ifdef CONFIG_PREEMPT_RT
67 /* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
68 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
69 #else
70 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
71 #endif
72
73 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp);
74 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
75 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
76
77 static const struct kernel_param_ops nx_huge_pages_ops = {
78 .set = set_nx_huge_pages,
79 .get = get_nx_huge_pages,
80 };
81
82 static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
83 .set = set_nx_huge_pages_recovery_param,
84 .get = param_get_uint,
85 };
86
87 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
88 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
89 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
90 &nx_huge_pages_recovery_ratio, 0644);
91 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
92 module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
93 &nx_huge_pages_recovery_period_ms, 0644);
94 __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
95
96 static bool __read_mostly force_flush_and_sync_on_reuse;
97 module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
98
99 /*
100 * When setting this variable to true it enables Two-Dimensional-Paging
101 * where the hardware walks 2 page tables:
102 * 1. the guest-virtual to guest-physical
103 * 2. while doing 1. it walks guest-physical to host-physical
104 * If the hardware supports that we don't need to do shadow paging.
105 */
106 bool tdp_enabled = false;
107
108 static bool __ro_after_init tdp_mmu_allowed;
109
110 #ifdef CONFIG_X86_64
111 bool __read_mostly tdp_mmu_enabled = true;
112 module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
113 #endif
114
115 static int max_huge_page_level __read_mostly;
116 static int tdp_root_level __read_mostly;
117 static int max_tdp_level __read_mostly;
118
119 #define PTE_PREFETCH_NUM 8
120
121 #include <trace/events/kvm.h>
122
123 /* make pte_list_desc fit well in cache lines */
124 #define PTE_LIST_EXT 14
125
126 /*
127 * struct pte_list_desc is the core data structure used to implement a custom
128 * list for tracking a set of related SPTEs, e.g. all the SPTEs that map a
129 * given GFN when used in the context of rmaps. Using a custom list allows KVM
130 * to optimize for the common case where many GFNs will have at most a handful
131 * of SPTEs pointing at them, i.e. allows packing multiple SPTEs into a small
132 * memory footprint, which in turn improves runtime performance by exploiting
133 * cache locality.
134 *
135 * A list is comprised of one or more pte_list_desc objects (descriptors).
136 * Each individual descriptor stores up to PTE_LIST_EXT SPTEs. If a descriptor
137 * is full and a new SPTEs needs to be added, a new descriptor is allocated and
138 * becomes the head of the list. This means that by definitions, all tail
139 * descriptors are full.
140 *
141 * Note, the meta data fields are deliberately placed at the start of the
142 * structure to optimize the cacheline layout; accessing the descriptor will
143 * touch only a single cacheline so long as @spte_count<=6 (or if only the
144 * descriptors metadata is accessed).
145 */
146 struct pte_list_desc {
147 struct pte_list_desc *more;
148 /* The number of PTEs stored in _this_ descriptor. */
149 u32 spte_count;
150 /* The number of PTEs stored in all tails of this descriptor. */
151 u32 tail_count;
152 u64 *sptes[PTE_LIST_EXT];
153 };
154
155 struct kvm_shadow_walk_iterator {
156 u64 addr;
157 hpa_t shadow_addr;
158 u64 *sptep;
159 int level;
160 unsigned index;
161 };
162
163 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
164 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
165 (_root), (_addr)); \
166 shadow_walk_okay(&(_walker)); \
167 shadow_walk_next(&(_walker)))
168
169 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
170 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
171 shadow_walk_okay(&(_walker)); \
172 shadow_walk_next(&(_walker)))
173
174 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
175 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
176 shadow_walk_okay(&(_walker)) && \
177 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
178 __shadow_walk_next(&(_walker), spte))
179
180 static struct kmem_cache *pte_list_desc_cache;
181 struct kmem_cache *mmu_page_header_cache;
182 static struct percpu_counter kvm_total_used_mmu_pages;
183
184 static void mmu_spte_set(u64 *sptep, u64 spte);
185
186 struct kvm_mmu_role_regs {
187 const unsigned long cr0;
188 const unsigned long cr4;
189 const u64 efer;
190 };
191
192 #define CREATE_TRACE_POINTS
193 #include "mmutrace.h"
194
195 /*
196 * Yes, lot's of underscores. They're a hint that you probably shouldn't be
197 * reading from the role_regs. Once the root_role is constructed, it becomes
198 * the single source of truth for the MMU's state.
199 */
200 #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag) \
201 static inline bool __maybe_unused \
202 ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs) \
203 { \
204 return !!(regs->reg & flag); \
205 }
206 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
207 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
208 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
209 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
210 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
211 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
212 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
213 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
214 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
215 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
216
217 /*
218 * The MMU itself (with a valid role) is the single source of truth for the
219 * MMU. Do not use the regs used to build the MMU/role, nor the vCPU. The
220 * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
221 * and the vCPU may be incorrect/irrelevant.
222 */
223 #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name) \
224 static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu) \
225 { \
226 return !!(mmu->cpu_role. base_or_ext . reg##_##name); \
227 }
228 BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
229 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pse);
230 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smep);
231 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smap);
232 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pke);
233 BUILD_MMU_ROLE_ACCESSOR(ext, cr4, la57);
234 BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
235 BUILD_MMU_ROLE_ACCESSOR(ext, efer, lma);
236
is_cr0_pg(struct kvm_mmu * mmu)237 static inline bool is_cr0_pg(struct kvm_mmu *mmu)
238 {
239 return mmu->cpu_role.base.level > 0;
240 }
241
is_cr4_pae(struct kvm_mmu * mmu)242 static inline bool is_cr4_pae(struct kvm_mmu *mmu)
243 {
244 return !mmu->cpu_role.base.has_4_byte_gpte;
245 }
246
vcpu_to_role_regs(struct kvm_vcpu * vcpu)247 static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
248 {
249 struct kvm_mmu_role_regs regs = {
250 .cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
251 .cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
252 .efer = vcpu->arch.efer,
253 };
254
255 return regs;
256 }
257
get_guest_cr3(struct kvm_vcpu * vcpu)258 static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
259 {
260 return kvm_read_cr3(vcpu);
261 }
262
kvm_mmu_get_guest_pgd(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)263 static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
264 struct kvm_mmu *mmu)
265 {
266 if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
267 return kvm_read_cr3(vcpu);
268
269 return mmu->get_guest_pgd(vcpu);
270 }
271
kvm_available_flush_remote_tlbs_range(void)272 static inline bool kvm_available_flush_remote_tlbs_range(void)
273 {
274 #if IS_ENABLED(CONFIG_HYPERV)
275 return kvm_x86_ops.flush_remote_tlbs_range;
276 #else
277 return false;
278 #endif
279 }
280
281 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
282
283 /* Flush the range of guest memory mapped by the given SPTE. */
kvm_flush_remote_tlbs_sptep(struct kvm * kvm,u64 * sptep)284 static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
285 {
286 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
287 gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
288
289 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
290 }
291
mark_mmio_spte(struct kvm_vcpu * vcpu,u64 * sptep,u64 gfn,unsigned int access)292 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
293 unsigned int access)
294 {
295 u64 spte = make_mmio_spte(vcpu, gfn, access);
296
297 trace_mark_mmio_spte(sptep, gfn, spte);
298 mmu_spte_set(sptep, spte);
299 }
300
get_mmio_spte_gfn(u64 spte)301 static gfn_t get_mmio_spte_gfn(u64 spte)
302 {
303 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
304
305 gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
306 & shadow_nonpresent_or_rsvd_mask;
307
308 return gpa >> PAGE_SHIFT;
309 }
310
get_mmio_spte_access(u64 spte)311 static unsigned get_mmio_spte_access(u64 spte)
312 {
313 return spte & shadow_mmio_access_mask;
314 }
315
check_mmio_spte(struct kvm_vcpu * vcpu,u64 spte)316 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
317 {
318 u64 kvm_gen, spte_gen, gen;
319
320 gen = kvm_vcpu_memslots(vcpu)->generation;
321 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
322 return false;
323
324 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
325 spte_gen = get_mmio_spte_generation(spte);
326
327 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
328 return likely(kvm_gen == spte_gen);
329 }
330
is_cpuid_PSE36(void)331 static int is_cpuid_PSE36(void)
332 {
333 return 1;
334 }
335
336 #ifdef CONFIG_X86_64
__set_spte(u64 * sptep,u64 spte)337 static void __set_spte(u64 *sptep, u64 spte)
338 {
339 KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
340 WRITE_ONCE(*sptep, spte);
341 }
342
__update_clear_spte_fast(u64 * sptep,u64 spte)343 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
344 {
345 KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
346 WRITE_ONCE(*sptep, spte);
347 }
348
__update_clear_spte_slow(u64 * sptep,u64 spte)349 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
350 {
351 KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
352 return xchg(sptep, spte);
353 }
354
__get_spte_lockless(u64 * sptep)355 static u64 __get_spte_lockless(u64 *sptep)
356 {
357 return READ_ONCE(*sptep);
358 }
359 #else
360 union split_spte {
361 struct {
362 u32 spte_low;
363 u32 spte_high;
364 };
365 u64 spte;
366 };
367
count_spte_clear(u64 * sptep,u64 spte)368 static void count_spte_clear(u64 *sptep, u64 spte)
369 {
370 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
371
372 if (is_shadow_present_pte(spte))
373 return;
374
375 /* Ensure the spte is completely set before we increase the count */
376 smp_wmb();
377 sp->clear_spte_count++;
378 }
379
__set_spte(u64 * sptep,u64 spte)380 static void __set_spte(u64 *sptep, u64 spte)
381 {
382 union split_spte *ssptep, sspte;
383
384 ssptep = (union split_spte *)sptep;
385 sspte = (union split_spte)spte;
386
387 ssptep->spte_high = sspte.spte_high;
388
389 /*
390 * If we map the spte from nonpresent to present, We should store
391 * the high bits firstly, then set present bit, so cpu can not
392 * fetch this spte while we are setting the spte.
393 */
394 smp_wmb();
395
396 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
397 }
398
__update_clear_spte_fast(u64 * sptep,u64 spte)399 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
400 {
401 union split_spte *ssptep, sspte;
402
403 ssptep = (union split_spte *)sptep;
404 sspte = (union split_spte)spte;
405
406 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
407
408 /*
409 * If we map the spte from present to nonpresent, we should clear
410 * present bit firstly to avoid vcpu fetch the old high bits.
411 */
412 smp_wmb();
413
414 ssptep->spte_high = sspte.spte_high;
415 count_spte_clear(sptep, spte);
416 }
417
__update_clear_spte_slow(u64 * sptep,u64 spte)418 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
419 {
420 union split_spte *ssptep, sspte, orig;
421
422 ssptep = (union split_spte *)sptep;
423 sspte = (union split_spte)spte;
424
425 /* xchg acts as a barrier before the setting of the high bits */
426 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
427 orig.spte_high = ssptep->spte_high;
428 ssptep->spte_high = sspte.spte_high;
429 count_spte_clear(sptep, spte);
430
431 return orig.spte;
432 }
433
434 /*
435 * The idea using the light way get the spte on x86_32 guest is from
436 * gup_get_pte (mm/gup.c).
437 *
438 * An spte tlb flush may be pending, because they are coalesced and
439 * we are running out of the MMU lock. Therefore
440 * we need to protect against in-progress updates of the spte.
441 *
442 * Reading the spte while an update is in progress may get the old value
443 * for the high part of the spte. The race is fine for a present->non-present
444 * change (because the high part of the spte is ignored for non-present spte),
445 * but for a present->present change we must reread the spte.
446 *
447 * All such changes are done in two steps (present->non-present and
448 * non-present->present), hence it is enough to count the number of
449 * present->non-present updates: if it changed while reading the spte,
450 * we might have hit the race. This is done using clear_spte_count.
451 */
__get_spte_lockless(u64 * sptep)452 static u64 __get_spte_lockless(u64 *sptep)
453 {
454 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
455 union split_spte spte, *orig = (union split_spte *)sptep;
456 int count;
457
458 retry:
459 count = sp->clear_spte_count;
460 smp_rmb();
461
462 spte.spte_low = orig->spte_low;
463 smp_rmb();
464
465 spte.spte_high = orig->spte_high;
466 smp_rmb();
467
468 if (unlikely(spte.spte_low != orig->spte_low ||
469 count != sp->clear_spte_count))
470 goto retry;
471
472 return spte.spte;
473 }
474 #endif
475
476 /* Rules for using mmu_spte_set:
477 * Set the sptep from nonpresent to present.
478 * Note: the sptep being assigned *must* be either not present
479 * or in a state where the hardware will not attempt to update
480 * the spte.
481 */
mmu_spte_set(u64 * sptep,u64 new_spte)482 static void mmu_spte_set(u64 *sptep, u64 new_spte)
483 {
484 WARN_ON_ONCE(is_shadow_present_pte(*sptep));
485 __set_spte(sptep, new_spte);
486 }
487
488 /*
489 * Update the SPTE (excluding the PFN), but do not track changes in its
490 * accessed/dirty status.
491 */
mmu_spte_update_no_track(u64 * sptep,u64 new_spte)492 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
493 {
494 u64 old_spte = *sptep;
495
496 WARN_ON_ONCE(!is_shadow_present_pte(new_spte));
497 check_spte_writable_invariants(new_spte);
498
499 if (!is_shadow_present_pte(old_spte)) {
500 mmu_spte_set(sptep, new_spte);
501 return old_spte;
502 }
503
504 if (!spte_has_volatile_bits(old_spte))
505 __update_clear_spte_fast(sptep, new_spte);
506 else
507 old_spte = __update_clear_spte_slow(sptep, new_spte);
508
509 WARN_ON_ONCE(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
510
511 return old_spte;
512 }
513
514 /* Rules for using mmu_spte_update:
515 * Update the state bits, it means the mapped pfn is not changed.
516 *
517 * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
518 * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
519 * spte, even though the writable spte might be cached on a CPU's TLB.
520 *
521 * Returns true if the TLB needs to be flushed
522 */
mmu_spte_update(u64 * sptep,u64 new_spte)523 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
524 {
525 bool flush = false;
526 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
527
528 if (!is_shadow_present_pte(old_spte))
529 return false;
530
531 /*
532 * For the spte updated out of mmu-lock is safe, since
533 * we always atomically update it, see the comments in
534 * spte_has_volatile_bits().
535 */
536 if (is_mmu_writable_spte(old_spte) &&
537 !is_writable_pte(new_spte))
538 flush = true;
539
540 /*
541 * Flush TLB when accessed/dirty states are changed in the page tables,
542 * to guarantee consistency between TLB and page tables.
543 */
544
545 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
546 flush = true;
547 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
548 }
549
550 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
551 flush = true;
552 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
553 }
554
555 return flush;
556 }
557
558 /*
559 * Rules for using mmu_spte_clear_track_bits:
560 * It sets the sptep from present to nonpresent, and track the
561 * state bits, it is used to clear the last level sptep.
562 * Returns the old PTE.
563 */
mmu_spte_clear_track_bits(struct kvm * kvm,u64 * sptep)564 static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
565 {
566 kvm_pfn_t pfn;
567 u64 old_spte = *sptep;
568 int level = sptep_to_sp(sptep)->role.level;
569 struct page *page;
570
571 if (!is_shadow_present_pte(old_spte) ||
572 !spte_has_volatile_bits(old_spte))
573 __update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
574 else
575 old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
576
577 if (!is_shadow_present_pte(old_spte))
578 return old_spte;
579
580 kvm_update_page_stats(kvm, level, -1);
581
582 pfn = spte_to_pfn(old_spte);
583
584 /*
585 * KVM doesn't hold a reference to any pages mapped into the guest, and
586 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
587 * before they are reclaimed. Sanity check that, if the pfn is backed
588 * by a refcounted page, the refcount is elevated.
589 */
590 page = kvm_pfn_to_refcounted_page(pfn);
591 WARN_ON_ONCE(page && !page_count(page));
592
593 if (is_accessed_spte(old_spte))
594 kvm_set_pfn_accessed(pfn);
595
596 if (is_dirty_spte(old_spte))
597 kvm_set_pfn_dirty(pfn);
598
599 return old_spte;
600 }
601
602 /*
603 * Rules for using mmu_spte_clear_no_track:
604 * Directly clear spte without caring the state bits of sptep,
605 * it is used to set the upper level spte.
606 */
mmu_spte_clear_no_track(u64 * sptep)607 static void mmu_spte_clear_no_track(u64 *sptep)
608 {
609 __update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
610 }
611
mmu_spte_get_lockless(u64 * sptep)612 static u64 mmu_spte_get_lockless(u64 *sptep)
613 {
614 return __get_spte_lockless(sptep);
615 }
616
is_tdp_mmu_active(struct kvm_vcpu * vcpu)617 static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
618 {
619 return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
620 }
621
walk_shadow_page_lockless_begin(struct kvm_vcpu * vcpu)622 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
623 {
624 if (is_tdp_mmu_active(vcpu)) {
625 kvm_tdp_mmu_walk_lockless_begin();
626 } else {
627 /*
628 * Prevent page table teardown by making any free-er wait during
629 * kvm_flush_remote_tlbs() IPI to all active vcpus.
630 */
631 local_irq_disable();
632
633 /*
634 * Make sure a following spte read is not reordered ahead of the write
635 * to vcpu->mode.
636 */
637 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
638 }
639 }
640
walk_shadow_page_lockless_end(struct kvm_vcpu * vcpu)641 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
642 {
643 if (is_tdp_mmu_active(vcpu)) {
644 kvm_tdp_mmu_walk_lockless_end();
645 } else {
646 /*
647 * Make sure the write to vcpu->mode is not reordered in front of
648 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
649 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
650 */
651 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
652 local_irq_enable();
653 }
654 }
655
mmu_topup_memory_caches(struct kvm_vcpu * vcpu,bool maybe_indirect)656 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
657 {
658 int r;
659
660 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
661 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
662 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
663 if (r)
664 return r;
665 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
666 PT64_ROOT_MAX_LEVEL);
667 if (r)
668 return r;
669 if (maybe_indirect) {
670 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
671 PT64_ROOT_MAX_LEVEL);
672 if (r)
673 return r;
674 }
675 return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
676 PT64_ROOT_MAX_LEVEL);
677 }
678
mmu_free_memory_caches(struct kvm_vcpu * vcpu)679 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
680 {
681 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
682 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
683 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
684 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
685 }
686
mmu_free_pte_list_desc(struct pte_list_desc * pte_list_desc)687 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
688 {
689 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
690 }
691
692 static bool sp_has_gptes(struct kvm_mmu_page *sp);
693
kvm_mmu_page_get_gfn(struct kvm_mmu_page * sp,int index)694 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
695 {
696 if (sp->role.passthrough)
697 return sp->gfn;
698
699 if (sp->shadowed_translation)
700 return sp->shadowed_translation[index] >> PAGE_SHIFT;
701
702 return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
703 }
704
705 /*
706 * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
707 * that the SPTE itself may have a more constrained access permissions that
708 * what the guest enforces. For example, a guest may create an executable
709 * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
710 */
kvm_mmu_page_get_access(struct kvm_mmu_page * sp,int index)711 static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
712 {
713 if (sp->shadowed_translation)
714 return sp->shadowed_translation[index] & ACC_ALL;
715
716 /*
717 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
718 * KVM is not shadowing any guest page tables, so the "guest access
719 * permissions" are just ACC_ALL.
720 *
721 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
722 * is shadowing a guest huge page with small pages, the guest access
723 * permissions being shadowed are the access permissions of the huge
724 * page.
725 *
726 * In both cases, sp->role.access contains the correct access bits.
727 */
728 return sp->role.access;
729 }
730
kvm_mmu_page_set_translation(struct kvm_mmu_page * sp,int index,gfn_t gfn,unsigned int access)731 static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
732 gfn_t gfn, unsigned int access)
733 {
734 if (sp->shadowed_translation) {
735 sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
736 return;
737 }
738
739 WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
740 "access mismatch under %s page %llx (expected %u, got %u)\n",
741 sp->role.passthrough ? "passthrough" : "direct",
742 sp->gfn, kvm_mmu_page_get_access(sp, index), access);
743
744 WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
745 "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
746 sp->role.passthrough ? "passthrough" : "direct",
747 sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
748 }
749
kvm_mmu_page_set_access(struct kvm_mmu_page * sp,int index,unsigned int access)750 static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
751 unsigned int access)
752 {
753 gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
754
755 kvm_mmu_page_set_translation(sp, index, gfn, access);
756 }
757
758 /*
759 * Return the pointer to the large page information for a given gfn,
760 * handling slots that are not large page aligned.
761 */
lpage_info_slot(gfn_t gfn,const struct kvm_memory_slot * slot,int level)762 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
763 const struct kvm_memory_slot *slot, int level)
764 {
765 unsigned long idx;
766
767 idx = gfn_to_index(gfn, slot->base_gfn, level);
768 return &slot->arch.lpage_info[level - 2][idx];
769 }
770
771 /*
772 * The most significant bit in disallow_lpage tracks whether or not memory
773 * attributes are mixed, i.e. not identical for all gfns at the current level.
774 * The lower order bits are used to refcount other cases where a hugepage is
775 * disallowed, e.g. if KVM has shadow a page table at the gfn.
776 */
777 #define KVM_LPAGE_MIXED_FLAG BIT(31)
778
update_gfn_disallow_lpage_count(const struct kvm_memory_slot * slot,gfn_t gfn,int count)779 static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
780 gfn_t gfn, int count)
781 {
782 struct kvm_lpage_info *linfo;
783 int old, i;
784
785 for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
786 linfo = lpage_info_slot(gfn, slot, i);
787
788 old = linfo->disallow_lpage;
789 linfo->disallow_lpage += count;
790 WARN_ON_ONCE((old ^ linfo->disallow_lpage) & KVM_LPAGE_MIXED_FLAG);
791 }
792 }
793
kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot * slot,gfn_t gfn)794 void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
795 {
796 update_gfn_disallow_lpage_count(slot, gfn, 1);
797 }
798
kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot * slot,gfn_t gfn)799 void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
800 {
801 update_gfn_disallow_lpage_count(slot, gfn, -1);
802 }
803
account_shadowed(struct kvm * kvm,struct kvm_mmu_page * sp)804 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
805 {
806 struct kvm_memslots *slots;
807 struct kvm_memory_slot *slot;
808 gfn_t gfn;
809
810 kvm->arch.indirect_shadow_pages++;
811 /*
812 * Ensure indirect_shadow_pages is elevated prior to re-reading guest
813 * child PTEs in FNAME(gpte_changed), i.e. guarantee either in-flight
814 * emulated writes are visible before re-reading guest PTEs, or that
815 * an emulated write will see the elevated count and acquire mmu_lock
816 * to update SPTEs. Pairs with the smp_mb() in kvm_mmu_track_write().
817 */
818 smp_mb();
819
820 gfn = sp->gfn;
821 slots = kvm_memslots_for_spte_role(kvm, sp->role);
822 slot = __gfn_to_memslot(slots, gfn);
823
824 /* the non-leaf shadow pages are keeping readonly. */
825 if (sp->role.level > PG_LEVEL_4K)
826 return __kvm_write_track_add_gfn(kvm, slot, gfn);
827
828 kvm_mmu_gfn_disallow_lpage(slot, gfn);
829
830 if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
831 kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
832 }
833
track_possible_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp)834 void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
835 {
836 /*
837 * If it's possible to replace the shadow page with an NX huge page,
838 * i.e. if the shadow page is the only thing currently preventing KVM
839 * from using a huge page, add the shadow page to the list of "to be
840 * zapped for NX recovery" pages. Note, the shadow page can already be
841 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
842 * links a shadow page at multiple points.
843 */
844 if (!list_empty(&sp->possible_nx_huge_page_link))
845 return;
846
847 ++kvm->stat.nx_lpage_splits;
848 list_add_tail(&sp->possible_nx_huge_page_link,
849 &kvm->arch.possible_nx_huge_pages);
850 }
851
account_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp,bool nx_huge_page_possible)852 static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
853 bool nx_huge_page_possible)
854 {
855 sp->nx_huge_page_disallowed = true;
856
857 if (nx_huge_page_possible)
858 track_possible_nx_huge_page(kvm, sp);
859 }
860
unaccount_shadowed(struct kvm * kvm,struct kvm_mmu_page * sp)861 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
862 {
863 struct kvm_memslots *slots;
864 struct kvm_memory_slot *slot;
865 gfn_t gfn;
866
867 kvm->arch.indirect_shadow_pages--;
868 gfn = sp->gfn;
869 slots = kvm_memslots_for_spte_role(kvm, sp->role);
870 slot = __gfn_to_memslot(slots, gfn);
871 if (sp->role.level > PG_LEVEL_4K)
872 return __kvm_write_track_remove_gfn(kvm, slot, gfn);
873
874 kvm_mmu_gfn_allow_lpage(slot, gfn);
875 }
876
untrack_possible_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp)877 void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
878 {
879 if (list_empty(&sp->possible_nx_huge_page_link))
880 return;
881
882 --kvm->stat.nx_lpage_splits;
883 list_del_init(&sp->possible_nx_huge_page_link);
884 }
885
unaccount_nx_huge_page(struct kvm * kvm,struct kvm_mmu_page * sp)886 static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
887 {
888 sp->nx_huge_page_disallowed = false;
889
890 untrack_possible_nx_huge_page(kvm, sp);
891 }
892
gfn_to_memslot_dirty_bitmap(struct kvm_vcpu * vcpu,gfn_t gfn,bool no_dirty_log)893 static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
894 gfn_t gfn,
895 bool no_dirty_log)
896 {
897 struct kvm_memory_slot *slot;
898
899 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
900 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
901 return NULL;
902 if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
903 return NULL;
904
905 return slot;
906 }
907
908 /*
909 * About rmap_head encoding:
910 *
911 * If the bit zero of rmap_head->val is clear, then it points to the only spte
912 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
913 * pte_list_desc containing more mappings.
914 */
915 #define KVM_RMAP_MANY BIT(0)
916
917 /*
918 * Returns the number of pointers in the rmap chain, not counting the new one.
919 */
pte_list_add(struct kvm_mmu_memory_cache * cache,u64 * spte,struct kvm_rmap_head * rmap_head)920 static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
921 struct kvm_rmap_head *rmap_head)
922 {
923 struct pte_list_desc *desc;
924 int count = 0;
925
926 if (!rmap_head->val) {
927 rmap_head->val = (unsigned long)spte;
928 } else if (!(rmap_head->val & KVM_RMAP_MANY)) {
929 desc = kvm_mmu_memory_cache_alloc(cache);
930 desc->sptes[0] = (u64 *)rmap_head->val;
931 desc->sptes[1] = spte;
932 desc->spte_count = 2;
933 desc->tail_count = 0;
934 rmap_head->val = (unsigned long)desc | KVM_RMAP_MANY;
935 ++count;
936 } else {
937 desc = (struct pte_list_desc *)(rmap_head->val & ~KVM_RMAP_MANY);
938 count = desc->tail_count + desc->spte_count;
939
940 /*
941 * If the previous head is full, allocate a new head descriptor
942 * as tail descriptors are always kept full.
943 */
944 if (desc->spte_count == PTE_LIST_EXT) {
945 desc = kvm_mmu_memory_cache_alloc(cache);
946 desc->more = (struct pte_list_desc *)(rmap_head->val & ~KVM_RMAP_MANY);
947 desc->spte_count = 0;
948 desc->tail_count = count;
949 rmap_head->val = (unsigned long)desc | KVM_RMAP_MANY;
950 }
951 desc->sptes[desc->spte_count++] = spte;
952 }
953 return count;
954 }
955
pte_list_desc_remove_entry(struct kvm * kvm,struct kvm_rmap_head * rmap_head,struct pte_list_desc * desc,int i)956 static void pte_list_desc_remove_entry(struct kvm *kvm,
957 struct kvm_rmap_head *rmap_head,
958 struct pte_list_desc *desc, int i)
959 {
960 struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~KVM_RMAP_MANY);
961 int j = head_desc->spte_count - 1;
962
963 /*
964 * The head descriptor should never be empty. A new head is added only
965 * when adding an entry and the previous head is full, and heads are
966 * removed (this flow) when they become empty.
967 */
968 KVM_BUG_ON_DATA_CORRUPTION(j < 0, kvm);
969
970 /*
971 * Replace the to-be-freed SPTE with the last valid entry from the head
972 * descriptor to ensure that tail descriptors are full at all times.
973 * Note, this also means that tail_count is stable for each descriptor.
974 */
975 desc->sptes[i] = head_desc->sptes[j];
976 head_desc->sptes[j] = NULL;
977 head_desc->spte_count--;
978 if (head_desc->spte_count)
979 return;
980
981 /*
982 * The head descriptor is empty. If there are no tail descriptors,
983 * nullify the rmap head to mark the list as empty, else point the rmap
984 * head at the next descriptor, i.e. the new head.
985 */
986 if (!head_desc->more)
987 rmap_head->val = 0;
988 else
989 rmap_head->val = (unsigned long)head_desc->more | KVM_RMAP_MANY;
990 mmu_free_pte_list_desc(head_desc);
991 }
992
pte_list_remove(struct kvm * kvm,u64 * spte,struct kvm_rmap_head * rmap_head)993 static void pte_list_remove(struct kvm *kvm, u64 *spte,
994 struct kvm_rmap_head *rmap_head)
995 {
996 struct pte_list_desc *desc;
997 int i;
998
999 if (KVM_BUG_ON_DATA_CORRUPTION(!rmap_head->val, kvm))
1000 return;
1001
1002 if (!(rmap_head->val & KVM_RMAP_MANY)) {
1003 if (KVM_BUG_ON_DATA_CORRUPTION((u64 *)rmap_head->val != spte, kvm))
1004 return;
1005
1006 rmap_head->val = 0;
1007 } else {
1008 desc = (struct pte_list_desc *)(rmap_head->val & ~KVM_RMAP_MANY);
1009 while (desc) {
1010 for (i = 0; i < desc->spte_count; ++i) {
1011 if (desc->sptes[i] == spte) {
1012 pte_list_desc_remove_entry(kvm, rmap_head,
1013 desc, i);
1014 return;
1015 }
1016 }
1017 desc = desc->more;
1018 }
1019
1020 KVM_BUG_ON_DATA_CORRUPTION(true, kvm);
1021 }
1022 }
1023
kvm_zap_one_rmap_spte(struct kvm * kvm,struct kvm_rmap_head * rmap_head,u64 * sptep)1024 static void kvm_zap_one_rmap_spte(struct kvm *kvm,
1025 struct kvm_rmap_head *rmap_head, u64 *sptep)
1026 {
1027 mmu_spte_clear_track_bits(kvm, sptep);
1028 pte_list_remove(kvm, sptep, rmap_head);
1029 }
1030
1031 /* Return true if at least one SPTE was zapped, false otherwise */
kvm_zap_all_rmap_sptes(struct kvm * kvm,struct kvm_rmap_head * rmap_head)1032 static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
1033 struct kvm_rmap_head *rmap_head)
1034 {
1035 struct pte_list_desc *desc, *next;
1036 int i;
1037
1038 if (!rmap_head->val)
1039 return false;
1040
1041 if (!(rmap_head->val & KVM_RMAP_MANY)) {
1042 mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1043 goto out;
1044 }
1045
1046 desc = (struct pte_list_desc *)(rmap_head->val & ~KVM_RMAP_MANY);
1047
1048 for (; desc; desc = next) {
1049 for (i = 0; i < desc->spte_count; i++)
1050 mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1051 next = desc->more;
1052 mmu_free_pte_list_desc(desc);
1053 }
1054 out:
1055 /* rmap_head is meaningless now, remember to reset it */
1056 rmap_head->val = 0;
1057 return true;
1058 }
1059
pte_list_count(struct kvm_rmap_head * rmap_head)1060 unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
1061 {
1062 struct pte_list_desc *desc;
1063
1064 if (!rmap_head->val)
1065 return 0;
1066 else if (!(rmap_head->val & KVM_RMAP_MANY))
1067 return 1;
1068
1069 desc = (struct pte_list_desc *)(rmap_head->val & ~KVM_RMAP_MANY);
1070 return desc->tail_count + desc->spte_count;
1071 }
1072
gfn_to_rmap(gfn_t gfn,int level,const struct kvm_memory_slot * slot)1073 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1074 const struct kvm_memory_slot *slot)
1075 {
1076 unsigned long idx;
1077
1078 idx = gfn_to_index(gfn, slot->base_gfn, level);
1079 return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1080 }
1081
rmap_remove(struct kvm * kvm,u64 * spte)1082 static void rmap_remove(struct kvm *kvm, u64 *spte)
1083 {
1084 struct kvm_memslots *slots;
1085 struct kvm_memory_slot *slot;
1086 struct kvm_mmu_page *sp;
1087 gfn_t gfn;
1088 struct kvm_rmap_head *rmap_head;
1089
1090 sp = sptep_to_sp(spte);
1091 gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1092
1093 /*
1094 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
1095 * so we have to determine which memslots to use based on context
1096 * information in sp->role.
1097 */
1098 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1099
1100 slot = __gfn_to_memslot(slots, gfn);
1101 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1102
1103 pte_list_remove(kvm, spte, rmap_head);
1104 }
1105
1106 /*
1107 * Used by the following functions to iterate through the sptes linked by a
1108 * rmap. All fields are private and not assumed to be used outside.
1109 */
1110 struct rmap_iterator {
1111 /* private fields */
1112 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1113 int pos; /* index of the sptep */
1114 };
1115
1116 /*
1117 * Iteration must be started by this function. This should also be used after
1118 * removing/dropping sptes from the rmap link because in such cases the
1119 * information in the iterator may not be valid.
1120 *
1121 * Returns sptep if found, NULL otherwise.
1122 */
rmap_get_first(struct kvm_rmap_head * rmap_head,struct rmap_iterator * iter)1123 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1124 struct rmap_iterator *iter)
1125 {
1126 u64 *sptep;
1127
1128 if (!rmap_head->val)
1129 return NULL;
1130
1131 if (!(rmap_head->val & KVM_RMAP_MANY)) {
1132 iter->desc = NULL;
1133 sptep = (u64 *)rmap_head->val;
1134 goto out;
1135 }
1136
1137 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~KVM_RMAP_MANY);
1138 iter->pos = 0;
1139 sptep = iter->desc->sptes[iter->pos];
1140 out:
1141 BUG_ON(!is_shadow_present_pte(*sptep));
1142 return sptep;
1143 }
1144
1145 /*
1146 * Must be used with a valid iterator: e.g. after rmap_get_first().
1147 *
1148 * Returns sptep if found, NULL otherwise.
1149 */
rmap_get_next(struct rmap_iterator * iter)1150 static u64 *rmap_get_next(struct rmap_iterator *iter)
1151 {
1152 u64 *sptep;
1153
1154 if (iter->desc) {
1155 if (iter->pos < PTE_LIST_EXT - 1) {
1156 ++iter->pos;
1157 sptep = iter->desc->sptes[iter->pos];
1158 if (sptep)
1159 goto out;
1160 }
1161
1162 iter->desc = iter->desc->more;
1163
1164 if (iter->desc) {
1165 iter->pos = 0;
1166 /* desc->sptes[0] cannot be NULL */
1167 sptep = iter->desc->sptes[iter->pos];
1168 goto out;
1169 }
1170 }
1171
1172 return NULL;
1173 out:
1174 BUG_ON(!is_shadow_present_pte(*sptep));
1175 return sptep;
1176 }
1177
1178 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1179 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
1180 _spte_; _spte_ = rmap_get_next(_iter_))
1181
drop_spte(struct kvm * kvm,u64 * sptep)1182 static void drop_spte(struct kvm *kvm, u64 *sptep)
1183 {
1184 u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
1185
1186 if (is_shadow_present_pte(old_spte))
1187 rmap_remove(kvm, sptep);
1188 }
1189
drop_large_spte(struct kvm * kvm,u64 * sptep,bool flush)1190 static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1191 {
1192 struct kvm_mmu_page *sp;
1193
1194 sp = sptep_to_sp(sptep);
1195 WARN_ON_ONCE(sp->role.level == PG_LEVEL_4K);
1196
1197 drop_spte(kvm, sptep);
1198
1199 if (flush)
1200 kvm_flush_remote_tlbs_sptep(kvm, sptep);
1201 }
1202
1203 /*
1204 * Write-protect on the specified @sptep, @pt_protect indicates whether
1205 * spte write-protection is caused by protecting shadow page table.
1206 *
1207 * Note: write protection is difference between dirty logging and spte
1208 * protection:
1209 * - for dirty logging, the spte can be set to writable at anytime if
1210 * its dirty bitmap is properly set.
1211 * - for spte protection, the spte can be writable only after unsync-ing
1212 * shadow page.
1213 *
1214 * Return true if tlb need be flushed.
1215 */
spte_write_protect(u64 * sptep,bool pt_protect)1216 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1217 {
1218 u64 spte = *sptep;
1219
1220 if (!is_writable_pte(spte) &&
1221 !(pt_protect && is_mmu_writable_spte(spte)))
1222 return false;
1223
1224 if (pt_protect)
1225 spte &= ~shadow_mmu_writable_mask;
1226 spte = spte & ~PT_WRITABLE_MASK;
1227
1228 return mmu_spte_update(sptep, spte);
1229 }
1230
rmap_write_protect(struct kvm_rmap_head * rmap_head,bool pt_protect)1231 static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1232 bool pt_protect)
1233 {
1234 u64 *sptep;
1235 struct rmap_iterator iter;
1236 bool flush = false;
1237
1238 for_each_rmap_spte(rmap_head, &iter, sptep)
1239 flush |= spte_write_protect(sptep, pt_protect);
1240
1241 return flush;
1242 }
1243
spte_clear_dirty(u64 * sptep)1244 static bool spte_clear_dirty(u64 *sptep)
1245 {
1246 u64 spte = *sptep;
1247
1248 KVM_MMU_WARN_ON(!spte_ad_enabled(spte));
1249 spte &= ~shadow_dirty_mask;
1250 return mmu_spte_update(sptep, spte);
1251 }
1252
spte_wrprot_for_clear_dirty(u64 * sptep)1253 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1254 {
1255 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1256 (unsigned long *)sptep);
1257 if (was_writable && !spte_ad_enabled(*sptep))
1258 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1259
1260 return was_writable;
1261 }
1262
1263 /*
1264 * Gets the GFN ready for another round of dirty logging by clearing the
1265 * - D bit on ad-enabled SPTEs, and
1266 * - W bit on ad-disabled SPTEs.
1267 * Returns true iff any D or W bits were cleared.
1268 */
__rmap_clear_dirty(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)1269 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1270 const struct kvm_memory_slot *slot)
1271 {
1272 u64 *sptep;
1273 struct rmap_iterator iter;
1274 bool flush = false;
1275
1276 for_each_rmap_spte(rmap_head, &iter, sptep)
1277 if (spte_ad_need_write_protect(*sptep))
1278 flush |= spte_wrprot_for_clear_dirty(sptep);
1279 else
1280 flush |= spte_clear_dirty(sptep);
1281
1282 return flush;
1283 }
1284
kvm_mmu_write_protect_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1285 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1286 struct kvm_memory_slot *slot,
1287 gfn_t gfn_offset, unsigned long mask)
1288 {
1289 struct kvm_rmap_head *rmap_head;
1290
1291 if (tdp_mmu_enabled)
1292 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1293 slot->base_gfn + gfn_offset, mask, true);
1294
1295 if (!kvm_memslots_have_rmaps(kvm))
1296 return;
1297
1298 while (mask) {
1299 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1300 PG_LEVEL_4K, slot);
1301 rmap_write_protect(rmap_head, false);
1302
1303 /* clear the first set bit */
1304 mask &= mask - 1;
1305 }
1306 }
1307
kvm_mmu_clear_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1308 static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1309 struct kvm_memory_slot *slot,
1310 gfn_t gfn_offset, unsigned long mask)
1311 {
1312 struct kvm_rmap_head *rmap_head;
1313
1314 if (tdp_mmu_enabled)
1315 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1316 slot->base_gfn + gfn_offset, mask, false);
1317
1318 if (!kvm_memslots_have_rmaps(kvm))
1319 return;
1320
1321 while (mask) {
1322 rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1323 PG_LEVEL_4K, slot);
1324 __rmap_clear_dirty(kvm, rmap_head, slot);
1325
1326 /* clear the first set bit */
1327 mask &= mask - 1;
1328 }
1329 }
1330
kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)1331 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1332 struct kvm_memory_slot *slot,
1333 gfn_t gfn_offset, unsigned long mask)
1334 {
1335 /*
1336 * If the slot was assumed to be "initially all dirty", write-protect
1337 * huge pages to ensure they are split to 4KiB on the first write (KVM
1338 * dirty logs at 4KiB granularity). If eager page splitting is enabled,
1339 * immediately try to split huge pages, e.g. so that vCPUs don't get
1340 * saddled with the cost of splitting.
1341 *
1342 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
1343 * of memslot has no such restriction, so the range can cross two large
1344 * pages.
1345 */
1346 if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1347 gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
1348 gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
1349
1350 if (READ_ONCE(eager_page_split))
1351 kvm_mmu_try_split_huge_pages(kvm, slot, start, end + 1, PG_LEVEL_4K);
1352
1353 kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
1354
1355 /* Cross two large pages? */
1356 if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
1357 ALIGN(end << PAGE_SHIFT, PMD_SIZE))
1358 kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
1359 PG_LEVEL_2M);
1360 }
1361
1362 /*
1363 * (Re)Enable dirty logging for all 4KiB SPTEs that map the GFNs in
1364 * mask. If PML is enabled and the GFN doesn't need to be write-
1365 * protected for other reasons, e.g. shadow paging, clear the Dirty bit.
1366 * Otherwise clear the Writable bit.
1367 *
1368 * Note that kvm_mmu_clear_dirty_pt_masked() is called whenever PML is
1369 * enabled but it chooses between clearing the Dirty bit and Writeable
1370 * bit based on the context.
1371 */
1372 if (kvm_x86_ops.cpu_dirty_log_size)
1373 kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1374 else
1375 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1376 }
1377
kvm_cpu_dirty_log_size(void)1378 int kvm_cpu_dirty_log_size(void)
1379 {
1380 return kvm_x86_ops.cpu_dirty_log_size;
1381 }
1382
kvm_mmu_slot_gfn_write_protect(struct kvm * kvm,struct kvm_memory_slot * slot,u64 gfn,int min_level)1383 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1384 struct kvm_memory_slot *slot, u64 gfn,
1385 int min_level)
1386 {
1387 struct kvm_rmap_head *rmap_head;
1388 int i;
1389 bool write_protected = false;
1390
1391 if (kvm_memslots_have_rmaps(kvm)) {
1392 for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1393 rmap_head = gfn_to_rmap(gfn, i, slot);
1394 write_protected |= rmap_write_protect(rmap_head, true);
1395 }
1396 }
1397
1398 if (tdp_mmu_enabled)
1399 write_protected |=
1400 kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
1401
1402 return write_protected;
1403 }
1404
kvm_vcpu_write_protect_gfn(struct kvm_vcpu * vcpu,u64 gfn)1405 static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1406 {
1407 struct kvm_memory_slot *slot;
1408
1409 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1410 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1411 }
1412
kvm_zap_rmap(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)1413 static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1414 const struct kvm_memory_slot *slot)
1415 {
1416 return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1417 }
1418
1419 struct slot_rmap_walk_iterator {
1420 /* input fields. */
1421 const struct kvm_memory_slot *slot;
1422 gfn_t start_gfn;
1423 gfn_t end_gfn;
1424 int start_level;
1425 int end_level;
1426
1427 /* output fields. */
1428 gfn_t gfn;
1429 struct kvm_rmap_head *rmap;
1430 int level;
1431
1432 /* private field. */
1433 struct kvm_rmap_head *end_rmap;
1434 };
1435
rmap_walk_init_level(struct slot_rmap_walk_iterator * iterator,int level)1436 static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1437 int level)
1438 {
1439 iterator->level = level;
1440 iterator->gfn = iterator->start_gfn;
1441 iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
1442 iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1443 }
1444
slot_rmap_walk_init(struct slot_rmap_walk_iterator * iterator,const struct kvm_memory_slot * slot,int start_level,int end_level,gfn_t start_gfn,gfn_t end_gfn)1445 static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1446 const struct kvm_memory_slot *slot,
1447 int start_level, int end_level,
1448 gfn_t start_gfn, gfn_t end_gfn)
1449 {
1450 iterator->slot = slot;
1451 iterator->start_level = start_level;
1452 iterator->end_level = end_level;
1453 iterator->start_gfn = start_gfn;
1454 iterator->end_gfn = end_gfn;
1455
1456 rmap_walk_init_level(iterator, iterator->start_level);
1457 }
1458
slot_rmap_walk_okay(struct slot_rmap_walk_iterator * iterator)1459 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1460 {
1461 return !!iterator->rmap;
1462 }
1463
slot_rmap_walk_next(struct slot_rmap_walk_iterator * iterator)1464 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1465 {
1466 while (++iterator->rmap <= iterator->end_rmap) {
1467 iterator->gfn += KVM_PAGES_PER_HPAGE(iterator->level);
1468
1469 if (iterator->rmap->val)
1470 return;
1471 }
1472
1473 if (++iterator->level > iterator->end_level) {
1474 iterator->rmap = NULL;
1475 return;
1476 }
1477
1478 rmap_walk_init_level(iterator, iterator->level);
1479 }
1480
1481 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1482 _start_gfn, _end_gfn, _iter_) \
1483 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1484 _end_level_, _start_gfn, _end_gfn); \
1485 slot_rmap_walk_okay(_iter_); \
1486 slot_rmap_walk_next(_iter_))
1487
1488 /* The return value indicates if tlb flush on all vcpus is needed. */
1489 typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
1490 struct kvm_rmap_head *rmap_head,
1491 const struct kvm_memory_slot *slot);
1492
__walk_slot_rmaps(struct kvm * kvm,const struct kvm_memory_slot * slot,slot_rmaps_handler fn,int start_level,int end_level,gfn_t start_gfn,gfn_t end_gfn,bool can_yield,bool flush_on_yield,bool flush)1493 static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
1494 const struct kvm_memory_slot *slot,
1495 slot_rmaps_handler fn,
1496 int start_level, int end_level,
1497 gfn_t start_gfn, gfn_t end_gfn,
1498 bool can_yield, bool flush_on_yield,
1499 bool flush)
1500 {
1501 struct slot_rmap_walk_iterator iterator;
1502
1503 lockdep_assert_held_write(&kvm->mmu_lock);
1504
1505 for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
1506 end_gfn, &iterator) {
1507 if (iterator.rmap)
1508 flush |= fn(kvm, iterator.rmap, slot);
1509
1510 if (!can_yield)
1511 continue;
1512
1513 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
1514 if (flush && flush_on_yield) {
1515 kvm_flush_remote_tlbs_range(kvm, start_gfn,
1516 iterator.gfn - start_gfn + 1);
1517 flush = false;
1518 }
1519 cond_resched_rwlock_write(&kvm->mmu_lock);
1520 }
1521 }
1522
1523 return flush;
1524 }
1525
walk_slot_rmaps(struct kvm * kvm,const struct kvm_memory_slot * slot,slot_rmaps_handler fn,int start_level,int end_level,bool flush_on_yield)1526 static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
1527 const struct kvm_memory_slot *slot,
1528 slot_rmaps_handler fn,
1529 int start_level, int end_level,
1530 bool flush_on_yield)
1531 {
1532 return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
1533 slot->base_gfn, slot->base_gfn + slot->npages - 1,
1534 true, flush_on_yield, false);
1535 }
1536
walk_slot_rmaps_4k(struct kvm * kvm,const struct kvm_memory_slot * slot,slot_rmaps_handler fn,bool flush_on_yield)1537 static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
1538 const struct kvm_memory_slot *slot,
1539 slot_rmaps_handler fn,
1540 bool flush_on_yield)
1541 {
1542 return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
1543 }
1544
__kvm_rmap_zap_gfn_range(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t start,gfn_t end,bool can_yield,bool flush)1545 static bool __kvm_rmap_zap_gfn_range(struct kvm *kvm,
1546 const struct kvm_memory_slot *slot,
1547 gfn_t start, gfn_t end, bool can_yield,
1548 bool flush)
1549 {
1550 return __walk_slot_rmaps(kvm, slot, kvm_zap_rmap,
1551 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1552 start, end - 1, can_yield, true, flush);
1553 }
1554
kvm_unmap_gfn_range(struct kvm * kvm,struct kvm_gfn_range * range)1555 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1556 {
1557 bool flush = false;
1558
1559 /*
1560 * To prevent races with vCPUs faulting in a gfn using stale data,
1561 * zapping a gfn range must be protected by mmu_invalidate_in_progress
1562 * (and mmu_invalidate_seq). The only exception is memslot deletion;
1563 * in that case, SRCU synchronization ensures that SPTEs are zapped
1564 * after all vCPUs have unlocked SRCU, guaranteeing that vCPUs see the
1565 * invalid slot.
1566 */
1567 lockdep_assert_once(kvm->mmu_invalidate_in_progress ||
1568 lockdep_is_held(&kvm->slots_lock));
1569
1570 if (kvm_memslots_have_rmaps(kvm))
1571 flush = __kvm_rmap_zap_gfn_range(kvm, range->slot,
1572 range->start, range->end,
1573 range->may_block, flush);
1574
1575 if (tdp_mmu_enabled)
1576 flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1577
1578 if (kvm_x86_ops.set_apic_access_page_addr &&
1579 range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
1580 kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
1581
1582 return flush;
1583 }
1584
1585 #define RMAP_RECYCLE_THRESHOLD 1000
1586
__rmap_add(struct kvm * kvm,struct kvm_mmu_memory_cache * cache,const struct kvm_memory_slot * slot,u64 * spte,gfn_t gfn,unsigned int access)1587 static void __rmap_add(struct kvm *kvm,
1588 struct kvm_mmu_memory_cache *cache,
1589 const struct kvm_memory_slot *slot,
1590 u64 *spte, gfn_t gfn, unsigned int access)
1591 {
1592 struct kvm_mmu_page *sp;
1593 struct kvm_rmap_head *rmap_head;
1594 int rmap_count;
1595
1596 sp = sptep_to_sp(spte);
1597 kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
1598 kvm_update_page_stats(kvm, sp->role.level, 1);
1599
1600 rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1601 rmap_count = pte_list_add(cache, spte, rmap_head);
1602
1603 if (rmap_count > kvm->stat.max_mmu_rmap_size)
1604 kvm->stat.max_mmu_rmap_size = rmap_count;
1605 if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
1606 kvm_zap_all_rmap_sptes(kvm, rmap_head);
1607 kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
1608 }
1609 }
1610
rmap_add(struct kvm_vcpu * vcpu,const struct kvm_memory_slot * slot,u64 * spte,gfn_t gfn,unsigned int access)1611 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
1612 u64 *spte, gfn_t gfn, unsigned int access)
1613 {
1614 struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
1615
1616 __rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
1617 }
1618
kvm_rmap_age_gfn_range(struct kvm * kvm,struct kvm_gfn_range * range,bool test_only)1619 static bool kvm_rmap_age_gfn_range(struct kvm *kvm,
1620 struct kvm_gfn_range *range, bool test_only)
1621 {
1622 struct slot_rmap_walk_iterator iterator;
1623 struct rmap_iterator iter;
1624 bool young = false;
1625 u64 *sptep;
1626
1627 for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1628 range->start, range->end - 1, &iterator) {
1629 for_each_rmap_spte(iterator.rmap, &iter, sptep) {
1630 u64 spte = *sptep;
1631
1632 if (!is_accessed_spte(spte))
1633 continue;
1634
1635 if (test_only)
1636 return true;
1637
1638 if (spte_ad_enabled(spte)) {
1639 clear_bit((ffs(shadow_accessed_mask) - 1),
1640 (unsigned long *)sptep);
1641 } else {
1642 /*
1643 * Capture the dirty status of the page, so that
1644 * it doesn't get lost when the SPTE is marked
1645 * for access tracking.
1646 */
1647 if (is_writable_pte(spte))
1648 kvm_set_pfn_dirty(spte_to_pfn(spte));
1649
1650 spte = mark_spte_for_access_track(spte);
1651 mmu_spte_update_no_track(sptep, spte);
1652 }
1653 young = true;
1654 }
1655 }
1656 return young;
1657 }
1658
kvm_age_gfn(struct kvm * kvm,struct kvm_gfn_range * range)1659 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1660 {
1661 bool young = false;
1662
1663 if (kvm_memslots_have_rmaps(kvm))
1664 young = kvm_rmap_age_gfn_range(kvm, range, false);
1665
1666 if (tdp_mmu_enabled)
1667 young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1668
1669 return young;
1670 }
1671
kvm_test_age_gfn(struct kvm * kvm,struct kvm_gfn_range * range)1672 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1673 {
1674 bool young = false;
1675
1676 if (kvm_memslots_have_rmaps(kvm))
1677 young = kvm_rmap_age_gfn_range(kvm, range, true);
1678
1679 if (tdp_mmu_enabled)
1680 young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1681
1682 return young;
1683 }
1684
kvm_mmu_check_sptes_at_free(struct kvm_mmu_page * sp)1685 static void kvm_mmu_check_sptes_at_free(struct kvm_mmu_page *sp)
1686 {
1687 #ifdef CONFIG_KVM_PROVE_MMU
1688 int i;
1689
1690 for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1691 if (KVM_MMU_WARN_ON(is_shadow_present_pte(sp->spt[i])))
1692 pr_err_ratelimited("SPTE %llx (@ %p) for gfn %llx shadow-present at free",
1693 sp->spt[i], &sp->spt[i],
1694 kvm_mmu_page_get_gfn(sp, i));
1695 }
1696 #endif
1697 }
1698
1699 /*
1700 * This value is the sum of all of the kvm instances's
1701 * kvm->arch.n_used_mmu_pages values. We need a global,
1702 * aggregate version in order to make the slab shrinker
1703 * faster
1704 */
kvm_mod_used_mmu_pages(struct kvm * kvm,long nr)1705 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1706 {
1707 kvm->arch.n_used_mmu_pages += nr;
1708 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1709 }
1710
kvm_account_mmu_page(struct kvm * kvm,struct kvm_mmu_page * sp)1711 static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1712 {
1713 kvm_mod_used_mmu_pages(kvm, +1);
1714 kvm_account_pgtable_pages((void *)sp->spt, +1);
1715 }
1716
kvm_unaccount_mmu_page(struct kvm * kvm,struct kvm_mmu_page * sp)1717 static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1718 {
1719 kvm_mod_used_mmu_pages(kvm, -1);
1720 kvm_account_pgtable_pages((void *)sp->spt, -1);
1721 }
1722
kvm_mmu_free_shadow_page(struct kvm_mmu_page * sp)1723 static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1724 {
1725 kvm_mmu_check_sptes_at_free(sp);
1726
1727 hlist_del(&sp->hash_link);
1728 list_del(&sp->link);
1729 free_page((unsigned long)sp->spt);
1730 free_page((unsigned long)sp->shadowed_translation);
1731 kmem_cache_free(mmu_page_header_cache, sp);
1732 }
1733
kvm_page_table_hashfn(gfn_t gfn)1734 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1735 {
1736 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1737 }
1738
mmu_page_add_parent_pte(struct kvm_mmu_memory_cache * cache,struct kvm_mmu_page * sp,u64 * parent_pte)1739 static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1740 struct kvm_mmu_page *sp, u64 *parent_pte)
1741 {
1742 if (!parent_pte)
1743 return;
1744
1745 pte_list_add(cache, parent_pte, &sp->parent_ptes);
1746 }
1747
mmu_page_remove_parent_pte(struct kvm * kvm,struct kvm_mmu_page * sp,u64 * parent_pte)1748 static void mmu_page_remove_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1749 u64 *parent_pte)
1750 {
1751 pte_list_remove(kvm, parent_pte, &sp->parent_ptes);
1752 }
1753
drop_parent_pte(struct kvm * kvm,struct kvm_mmu_page * sp,u64 * parent_pte)1754 static void drop_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1755 u64 *parent_pte)
1756 {
1757 mmu_page_remove_parent_pte(kvm, sp, parent_pte);
1758 mmu_spte_clear_no_track(parent_pte);
1759 }
1760
1761 static void mark_unsync(u64 *spte);
kvm_mmu_mark_parents_unsync(struct kvm_mmu_page * sp)1762 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1763 {
1764 u64 *sptep;
1765 struct rmap_iterator iter;
1766
1767 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1768 mark_unsync(sptep);
1769 }
1770 }
1771
mark_unsync(u64 * spte)1772 static void mark_unsync(u64 *spte)
1773 {
1774 struct kvm_mmu_page *sp;
1775
1776 sp = sptep_to_sp(spte);
1777 if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1778 return;
1779 if (sp->unsync_children++)
1780 return;
1781 kvm_mmu_mark_parents_unsync(sp);
1782 }
1783
1784 #define KVM_PAGE_ARRAY_NR 16
1785
1786 struct kvm_mmu_pages {
1787 struct mmu_page_and_offset {
1788 struct kvm_mmu_page *sp;
1789 unsigned int idx;
1790 } page[KVM_PAGE_ARRAY_NR];
1791 unsigned int nr;
1792 };
1793
mmu_pages_add(struct kvm_mmu_pages * pvec,struct kvm_mmu_page * sp,int idx)1794 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1795 int idx)
1796 {
1797 int i;
1798
1799 if (sp->unsync)
1800 for (i=0; i < pvec->nr; i++)
1801 if (pvec->page[i].sp == sp)
1802 return 0;
1803
1804 pvec->page[pvec->nr].sp = sp;
1805 pvec->page[pvec->nr].idx = idx;
1806 pvec->nr++;
1807 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1808 }
1809
clear_unsync_child_bit(struct kvm_mmu_page * sp,int idx)1810 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1811 {
1812 --sp->unsync_children;
1813 WARN_ON_ONCE((int)sp->unsync_children < 0);
1814 __clear_bit(idx, sp->unsync_child_bitmap);
1815 }
1816
__mmu_unsync_walk(struct kvm_mmu_page * sp,struct kvm_mmu_pages * pvec)1817 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1818 struct kvm_mmu_pages *pvec)
1819 {
1820 int i, ret, nr_unsync_leaf = 0;
1821
1822 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1823 struct kvm_mmu_page *child;
1824 u64 ent = sp->spt[i];
1825
1826 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1827 clear_unsync_child_bit(sp, i);
1828 continue;
1829 }
1830
1831 child = spte_to_child_sp(ent);
1832
1833 if (child->unsync_children) {
1834 if (mmu_pages_add(pvec, child, i))
1835 return -ENOSPC;
1836
1837 ret = __mmu_unsync_walk(child, pvec);
1838 if (!ret) {
1839 clear_unsync_child_bit(sp, i);
1840 continue;
1841 } else if (ret > 0) {
1842 nr_unsync_leaf += ret;
1843 } else
1844 return ret;
1845 } else if (child->unsync) {
1846 nr_unsync_leaf++;
1847 if (mmu_pages_add(pvec, child, i))
1848 return -ENOSPC;
1849 } else
1850 clear_unsync_child_bit(sp, i);
1851 }
1852
1853 return nr_unsync_leaf;
1854 }
1855
1856 #define INVALID_INDEX (-1)
1857
mmu_unsync_walk(struct kvm_mmu_page * sp,struct kvm_mmu_pages * pvec)1858 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1859 struct kvm_mmu_pages *pvec)
1860 {
1861 pvec->nr = 0;
1862 if (!sp->unsync_children)
1863 return 0;
1864
1865 mmu_pages_add(pvec, sp, INVALID_INDEX);
1866 return __mmu_unsync_walk(sp, pvec);
1867 }
1868
kvm_unlink_unsync_page(struct kvm * kvm,struct kvm_mmu_page * sp)1869 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1870 {
1871 WARN_ON_ONCE(!sp->unsync);
1872 trace_kvm_mmu_sync_page(sp);
1873 sp->unsync = 0;
1874 --kvm->stat.mmu_unsync;
1875 }
1876
1877 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1878 struct list_head *invalid_list);
1879 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1880 struct list_head *invalid_list);
1881
sp_has_gptes(struct kvm_mmu_page * sp)1882 static bool sp_has_gptes(struct kvm_mmu_page *sp)
1883 {
1884 if (sp->role.direct)
1885 return false;
1886
1887 if (sp->role.passthrough)
1888 return false;
1889
1890 return true;
1891 }
1892
1893 #define for_each_valid_sp(_kvm, _sp, _list) \
1894 hlist_for_each_entry(_sp, _list, hash_link) \
1895 if (is_obsolete_sp((_kvm), (_sp))) { \
1896 } else
1897
1898 #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn) \
1899 for_each_valid_sp(_kvm, _sp, \
1900 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
1901 if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1902
kvm_sync_page_check(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp)1903 static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1904 {
1905 union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
1906
1907 /*
1908 * Ignore various flags when verifying that it's safe to sync a shadow
1909 * page using the current MMU context.
1910 *
1911 * - level: not part of the overall MMU role and will never match as the MMU's
1912 * level tracks the root level
1913 * - access: updated based on the new guest PTE
1914 * - quadrant: not part of the overall MMU role (similar to level)
1915 */
1916 const union kvm_mmu_page_role sync_role_ign = {
1917 .level = 0xf,
1918 .access = 0x7,
1919 .quadrant = 0x3,
1920 .passthrough = 0x1,
1921 };
1922
1923 /*
1924 * Direct pages can never be unsync, and KVM should never attempt to
1925 * sync a shadow page for a different MMU context, e.g. if the role
1926 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
1927 * reserved bits checks will be wrong, etc...
1928 */
1929 if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
1930 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
1931 return false;
1932
1933 return true;
1934 }
1935
kvm_sync_spte(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,int i)1936 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
1937 {
1938 /* sp->spt[i] has initial value of shadow page table allocation */
1939 if (sp->spt[i] == SHADOW_NONPRESENT_VALUE)
1940 return 0;
1941
1942 return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
1943 }
1944
__kvm_sync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp)1945 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1946 {
1947 int flush = 0;
1948 int i;
1949
1950 if (!kvm_sync_page_check(vcpu, sp))
1951 return -1;
1952
1953 for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1954 int ret = kvm_sync_spte(vcpu, sp, i);
1955
1956 if (ret < -1)
1957 return -1;
1958 flush |= ret;
1959 }
1960
1961 /*
1962 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1963 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1964 * unmap or dirty logging event doesn't fail to flush. The guest is
1965 * responsible for flushing the TLB to ensure any changes in protection
1966 * bits are recognized, i.e. until the guest flushes or page faults on
1967 * a relevant address, KVM is architecturally allowed to let vCPUs use
1968 * cached translations with the old protection bits.
1969 */
1970 return flush;
1971 }
1972
kvm_sync_page(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,struct list_head * invalid_list)1973 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1974 struct list_head *invalid_list)
1975 {
1976 int ret = __kvm_sync_page(vcpu, sp);
1977
1978 if (ret < 0)
1979 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1980 return ret;
1981 }
1982
kvm_mmu_remote_flush_or_zap(struct kvm * kvm,struct list_head * invalid_list,bool remote_flush)1983 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1984 struct list_head *invalid_list,
1985 bool remote_flush)
1986 {
1987 if (!remote_flush && list_empty(invalid_list))
1988 return false;
1989
1990 if (!list_empty(invalid_list))
1991 kvm_mmu_commit_zap_page(kvm, invalid_list);
1992 else
1993 kvm_flush_remote_tlbs(kvm);
1994 return true;
1995 }
1996
is_obsolete_sp(struct kvm * kvm,struct kvm_mmu_page * sp)1997 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1998 {
1999 if (sp->role.invalid)
2000 return true;
2001
2002 /* TDP MMU pages do not use the MMU generation. */
2003 return !is_tdp_mmu_page(sp) &&
2004 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2005 }
2006
2007 struct mmu_page_path {
2008 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2009 unsigned int idx[PT64_ROOT_MAX_LEVEL];
2010 };
2011
2012 #define for_each_sp(pvec, sp, parents, i) \
2013 for (i = mmu_pages_first(&pvec, &parents); \
2014 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2015 i = mmu_pages_next(&pvec, &parents, i))
2016
mmu_pages_next(struct kvm_mmu_pages * pvec,struct mmu_page_path * parents,int i)2017 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2018 struct mmu_page_path *parents,
2019 int i)
2020 {
2021 int n;
2022
2023 for (n = i+1; n < pvec->nr; n++) {
2024 struct kvm_mmu_page *sp = pvec->page[n].sp;
2025 unsigned idx = pvec->page[n].idx;
2026 int level = sp->role.level;
2027
2028 parents->idx[level-1] = idx;
2029 if (level == PG_LEVEL_4K)
2030 break;
2031
2032 parents->parent[level-2] = sp;
2033 }
2034
2035 return n;
2036 }
2037
mmu_pages_first(struct kvm_mmu_pages * pvec,struct mmu_page_path * parents)2038 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2039 struct mmu_page_path *parents)
2040 {
2041 struct kvm_mmu_page *sp;
2042 int level;
2043
2044 if (pvec->nr == 0)
2045 return 0;
2046
2047 WARN_ON_ONCE(pvec->page[0].idx != INVALID_INDEX);
2048
2049 sp = pvec->page[0].sp;
2050 level = sp->role.level;
2051 WARN_ON_ONCE(level == PG_LEVEL_4K);
2052
2053 parents->parent[level-2] = sp;
2054
2055 /* Also set up a sentinel. Further entries in pvec are all
2056 * children of sp, so this element is never overwritten.
2057 */
2058 parents->parent[level-1] = NULL;
2059 return mmu_pages_next(pvec, parents, 0);
2060 }
2061
mmu_pages_clear_parents(struct mmu_page_path * parents)2062 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2063 {
2064 struct kvm_mmu_page *sp;
2065 unsigned int level = 0;
2066
2067 do {
2068 unsigned int idx = parents->idx[level];
2069 sp = parents->parent[level];
2070 if (!sp)
2071 return;
2072
2073 WARN_ON_ONCE(idx == INVALID_INDEX);
2074 clear_unsync_child_bit(sp, idx);
2075 level++;
2076 } while (!sp->unsync_children);
2077 }
2078
mmu_sync_children(struct kvm_vcpu * vcpu,struct kvm_mmu_page * parent,bool can_yield)2079 static int mmu_sync_children(struct kvm_vcpu *vcpu,
2080 struct kvm_mmu_page *parent, bool can_yield)
2081 {
2082 int i;
2083 struct kvm_mmu_page *sp;
2084 struct mmu_page_path parents;
2085 struct kvm_mmu_pages pages;
2086 LIST_HEAD(invalid_list);
2087 bool flush = false;
2088
2089 while (mmu_unsync_walk(parent, &pages)) {
2090 bool protected = false;
2091
2092 for_each_sp(pages, sp, parents, i)
2093 protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2094
2095 if (protected) {
2096 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2097 flush = false;
2098 }
2099
2100 for_each_sp(pages, sp, parents, i) {
2101 kvm_unlink_unsync_page(vcpu->kvm, sp);
2102 flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2103 mmu_pages_clear_parents(&parents);
2104 }
2105 if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2106 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2107 if (!can_yield) {
2108 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2109 return -EINTR;
2110 }
2111
2112 cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2113 flush = false;
2114 }
2115 }
2116
2117 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2118 return 0;
2119 }
2120
__clear_sp_write_flooding_count(struct kvm_mmu_page * sp)2121 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2122 {
2123 atomic_set(&sp->write_flooding_count, 0);
2124 }
2125
clear_sp_write_flooding_count(u64 * spte)2126 static void clear_sp_write_flooding_count(u64 *spte)
2127 {
2128 __clear_sp_write_flooding_count(sptep_to_sp(spte));
2129 }
2130
2131 /*
2132 * The vCPU is required when finding indirect shadow pages; the shadow
2133 * page may already exist and syncing it needs the vCPU pointer in
2134 * order to read guest page tables. Direct shadow pages are never
2135 * unsync, thus @vcpu can be NULL if @role.direct is true.
2136 */
kvm_mmu_find_shadow_page(struct kvm * kvm,struct kvm_vcpu * vcpu,gfn_t gfn,struct hlist_head * sp_list,union kvm_mmu_page_role role)2137 static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
2138 struct kvm_vcpu *vcpu,
2139 gfn_t gfn,
2140 struct hlist_head *sp_list,
2141 union kvm_mmu_page_role role)
2142 {
2143 struct kvm_mmu_page *sp;
2144 int ret;
2145 int collisions = 0;
2146 LIST_HEAD(invalid_list);
2147
2148 for_each_valid_sp(kvm, sp, sp_list) {
2149 if (sp->gfn != gfn) {
2150 collisions++;
2151 continue;
2152 }
2153
2154 if (sp->role.word != role.word) {
2155 /*
2156 * If the guest is creating an upper-level page, zap
2157 * unsync pages for the same gfn. While it's possible
2158 * the guest is using recursive page tables, in all
2159 * likelihood the guest has stopped using the unsync
2160 * page and is installing a completely unrelated page.
2161 * Unsync pages must not be left as is, because the new
2162 * upper-level page will be write-protected.
2163 */
2164 if (role.level > PG_LEVEL_4K && sp->unsync)
2165 kvm_mmu_prepare_zap_page(kvm, sp,
2166 &invalid_list);
2167 continue;
2168 }
2169
2170 /* unsync and write-flooding only apply to indirect SPs. */
2171 if (sp->role.direct)
2172 goto out;
2173
2174 if (sp->unsync) {
2175 if (KVM_BUG_ON(!vcpu, kvm))
2176 break;
2177
2178 /*
2179 * The page is good, but is stale. kvm_sync_page does
2180 * get the latest guest state, but (unlike mmu_unsync_children)
2181 * it doesn't write-protect the page or mark it synchronized!
2182 * This way the validity of the mapping is ensured, but the
2183 * overhead of write protection is not incurred until the
2184 * guest invalidates the TLB mapping. This allows multiple
2185 * SPs for a single gfn to be unsync.
2186 *
2187 * If the sync fails, the page is zapped. If so, break
2188 * in order to rebuild it.
2189 */
2190 ret = kvm_sync_page(vcpu, sp, &invalid_list);
2191 if (ret < 0)
2192 break;
2193
2194 WARN_ON_ONCE(!list_empty(&invalid_list));
2195 if (ret > 0)
2196 kvm_flush_remote_tlbs(kvm);
2197 }
2198
2199 __clear_sp_write_flooding_count(sp);
2200
2201 goto out;
2202 }
2203
2204 sp = NULL;
2205 ++kvm->stat.mmu_cache_miss;
2206
2207 out:
2208 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2209
2210 if (collisions > kvm->stat.max_mmu_page_hash_collisions)
2211 kvm->stat.max_mmu_page_hash_collisions = collisions;
2212 return sp;
2213 }
2214
2215 /* Caches used when allocating a new shadow page. */
2216 struct shadow_page_caches {
2217 struct kvm_mmu_memory_cache *page_header_cache;
2218 struct kvm_mmu_memory_cache *shadow_page_cache;
2219 struct kvm_mmu_memory_cache *shadowed_info_cache;
2220 };
2221
kvm_mmu_alloc_shadow_page(struct kvm * kvm,struct shadow_page_caches * caches,gfn_t gfn,struct hlist_head * sp_list,union kvm_mmu_page_role role)2222 static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
2223 struct shadow_page_caches *caches,
2224 gfn_t gfn,
2225 struct hlist_head *sp_list,
2226 union kvm_mmu_page_role role)
2227 {
2228 struct kvm_mmu_page *sp;
2229
2230 sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
2231 sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2232 if (!role.direct && role.level <= KVM_MAX_HUGEPAGE_LEVEL)
2233 sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2234
2235 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2236
2237 INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2238
2239 /*
2240 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2241 * depends on valid pages being added to the head of the list. See
2242 * comments in kvm_zap_obsolete_pages().
2243 */
2244 sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2245 list_add(&sp->link, &kvm->arch.active_mmu_pages);
2246 kvm_account_mmu_page(kvm, sp);
2247
2248 sp->gfn = gfn;
2249 sp->role = role;
2250 hlist_add_head(&sp->hash_link, sp_list);
2251 if (sp_has_gptes(sp))
2252 account_shadowed(kvm, sp);
2253
2254 return sp;
2255 }
2256
2257 /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
__kvm_mmu_get_shadow_page(struct kvm * kvm,struct kvm_vcpu * vcpu,struct shadow_page_caches * caches,gfn_t gfn,union kvm_mmu_page_role role)2258 static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
2259 struct kvm_vcpu *vcpu,
2260 struct shadow_page_caches *caches,
2261 gfn_t gfn,
2262 union kvm_mmu_page_role role)
2263 {
2264 struct hlist_head *sp_list;
2265 struct kvm_mmu_page *sp;
2266 bool created = false;
2267
2268 sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2269
2270 sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
2271 if (!sp) {
2272 created = true;
2273 sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
2274 }
2275
2276 trace_kvm_mmu_get_page(sp, created);
2277 return sp;
2278 }
2279
kvm_mmu_get_shadow_page(struct kvm_vcpu * vcpu,gfn_t gfn,union kvm_mmu_page_role role)2280 static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
2281 gfn_t gfn,
2282 union kvm_mmu_page_role role)
2283 {
2284 struct shadow_page_caches caches = {
2285 .page_header_cache = &vcpu->arch.mmu_page_header_cache,
2286 .shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
2287 .shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
2288 };
2289
2290 return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
2291 }
2292
kvm_mmu_child_role(u64 * sptep,bool direct,unsigned int access)2293 static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
2294 unsigned int access)
2295 {
2296 struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
2297 union kvm_mmu_page_role role;
2298
2299 role = parent_sp->role;
2300 role.level--;
2301 role.access = access;
2302 role.direct = direct;
2303 role.passthrough = 0;
2304
2305 /*
2306 * If the guest has 4-byte PTEs then that means it's using 32-bit,
2307 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
2308 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
2309 * shadow each guest page table with multiple shadow page tables, which
2310 * requires extra bookkeeping in the role.
2311 *
2312 * Specifically, to shadow the guest's page directory (which covers a
2313 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
2314 * 1GiB of the address space. @role.quadrant encodes which quarter of
2315 * the address space each maps.
2316 *
2317 * To shadow the guest's page tables (which each map a 4MiB region), KVM
2318 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
2319 * @role.quadrant encodes which half of the region they map.
2320 *
2321 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
2322 * consumes bits 29:21. To consume bits 31:30, KVM's uses 4 shadow
2323 * PDPTEs; those 4 PAE page directories are pre-allocated and their
2324 * quadrant is assigned in mmu_alloc_root(). A 4-byte PTE consumes
2325 * bits 21:12, while an 8-byte PTE consumes bits 20:12. To consume
2326 * bit 21 in the PTE (the child here), KVM propagates that bit to the
2327 * quadrant, i.e. sets quadrant to '0' or '1'. The parent 8-byte PDE
2328 * covers bit 21 (see above), thus the quadrant is calculated from the
2329 * _least_ significant bit of the PDE index.
2330 */
2331 if (role.has_4_byte_gpte) {
2332 WARN_ON_ONCE(role.level != PG_LEVEL_4K);
2333 role.quadrant = spte_index(sptep) & 1;
2334 }
2335
2336 return role;
2337 }
2338
kvm_mmu_get_child_sp(struct kvm_vcpu * vcpu,u64 * sptep,gfn_t gfn,bool direct,unsigned int access)2339 static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
2340 u64 *sptep, gfn_t gfn,
2341 bool direct, unsigned int access)
2342 {
2343 union kvm_mmu_page_role role;
2344
2345 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
2346 return ERR_PTR(-EEXIST);
2347
2348 role = kvm_mmu_child_role(sptep, direct, access);
2349 return kvm_mmu_get_shadow_page(vcpu, gfn, role);
2350 }
2351
shadow_walk_init_using_root(struct kvm_shadow_walk_iterator * iterator,struct kvm_vcpu * vcpu,hpa_t root,u64 addr)2352 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2353 struct kvm_vcpu *vcpu, hpa_t root,
2354 u64 addr)
2355 {
2356 iterator->addr = addr;
2357 iterator->shadow_addr = root;
2358 iterator->level = vcpu->arch.mmu->root_role.level;
2359
2360 if (iterator->level >= PT64_ROOT_4LEVEL &&
2361 vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2362 !vcpu->arch.mmu->root_role.direct)
2363 iterator->level = PT32E_ROOT_LEVEL;
2364
2365 if (iterator->level == PT32E_ROOT_LEVEL) {
2366 /*
2367 * prev_root is currently only used for 64-bit hosts. So only
2368 * the active root_hpa is valid here.
2369 */
2370 BUG_ON(root != vcpu->arch.mmu->root.hpa);
2371
2372 iterator->shadow_addr
2373 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2374 iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2375 --iterator->level;
2376 if (!iterator->shadow_addr)
2377 iterator->level = 0;
2378 }
2379 }
2380
shadow_walk_init(struct kvm_shadow_walk_iterator * iterator,struct kvm_vcpu * vcpu,u64 addr)2381 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2382 struct kvm_vcpu *vcpu, u64 addr)
2383 {
2384 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2385 addr);
2386 }
2387
shadow_walk_okay(struct kvm_shadow_walk_iterator * iterator)2388 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2389 {
2390 if (iterator->level < PG_LEVEL_4K)
2391 return false;
2392
2393 iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2394 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2395 return true;
2396 }
2397
__shadow_walk_next(struct kvm_shadow_walk_iterator * iterator,u64 spte)2398 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2399 u64 spte)
2400 {
2401 if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2402 iterator->level = 0;
2403 return;
2404 }
2405
2406 iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2407 --iterator->level;
2408 }
2409
shadow_walk_next(struct kvm_shadow_walk_iterator * iterator)2410 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2411 {
2412 __shadow_walk_next(iterator, *iterator->sptep);
2413 }
2414
__link_shadow_page(struct kvm * kvm,struct kvm_mmu_memory_cache * cache,u64 * sptep,struct kvm_mmu_page * sp,bool flush)2415 static void __link_shadow_page(struct kvm *kvm,
2416 struct kvm_mmu_memory_cache *cache, u64 *sptep,
2417 struct kvm_mmu_page *sp, bool flush)
2418 {
2419 u64 spte;
2420
2421 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2422
2423 /*
2424 * If an SPTE is present already, it must be a leaf and therefore
2425 * a large one. Drop it, and flush the TLB if needed, before
2426 * installing sp.
2427 */
2428 if (is_shadow_present_pte(*sptep))
2429 drop_large_spte(kvm, sptep, flush);
2430
2431 spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2432
2433 mmu_spte_set(sptep, spte);
2434
2435 mmu_page_add_parent_pte(cache, sp, sptep);
2436
2437 /*
2438 * The non-direct sub-pagetable must be updated before linking. For
2439 * L1 sp, the pagetable is updated via kvm_sync_page() in
2440 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2441 * so sp->unsync can be true or false. For higher level non-direct
2442 * sp, the pagetable is updated/synced via mmu_sync_children() in
2443 * FNAME(fetch)(), so sp->unsync_children can only be false.
2444 * WARN_ON_ONCE() if anything happens unexpectedly.
2445 */
2446 if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2447 mark_unsync(sptep);
2448 }
2449
link_shadow_page(struct kvm_vcpu * vcpu,u64 * sptep,struct kvm_mmu_page * sp)2450 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2451 struct kvm_mmu_page *sp)
2452 {
2453 __link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
2454 }
2455
validate_direct_spte(struct kvm_vcpu * vcpu,u64 * sptep,unsigned direct_access)2456 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2457 unsigned direct_access)
2458 {
2459 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2460 struct kvm_mmu_page *child;
2461
2462 /*
2463 * For the direct sp, if the guest pte's dirty bit
2464 * changed form clean to dirty, it will corrupt the
2465 * sp's access: allow writable in the read-only sp,
2466 * so we should update the spte at this point to get
2467 * a new sp with the correct access.
2468 */
2469 child = spte_to_child_sp(*sptep);
2470 if (child->role.access == direct_access)
2471 return;
2472
2473 drop_parent_pte(vcpu->kvm, child, sptep);
2474 kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2475 }
2476 }
2477
2478 /* Returns the number of zapped non-leaf child shadow pages. */
mmu_page_zap_pte(struct kvm * kvm,struct kvm_mmu_page * sp,u64 * spte,struct list_head * invalid_list)2479 static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2480 u64 *spte, struct list_head *invalid_list)
2481 {
2482 u64 pte;
2483 struct kvm_mmu_page *child;
2484
2485 pte = *spte;
2486 if (is_shadow_present_pte(pte)) {
2487 if (is_last_spte(pte, sp->role.level)) {
2488 drop_spte(kvm, spte);
2489 } else {
2490 child = spte_to_child_sp(pte);
2491 drop_parent_pte(kvm, child, spte);
2492
2493 /*
2494 * Recursively zap nested TDP SPs, parentless SPs are
2495 * unlikely to be used again in the near future. This
2496 * avoids retaining a large number of stale nested SPs.
2497 */
2498 if (tdp_enabled && invalid_list &&
2499 child->role.guest_mode && !child->parent_ptes.val)
2500 return kvm_mmu_prepare_zap_page(kvm, child,
2501 invalid_list);
2502 }
2503 } else if (is_mmio_spte(kvm, pte)) {
2504 mmu_spte_clear_no_track(spte);
2505 }
2506 return 0;
2507 }
2508
kvm_mmu_page_unlink_children(struct kvm * kvm,struct kvm_mmu_page * sp,struct list_head * invalid_list)2509 static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2510 struct kvm_mmu_page *sp,
2511 struct list_head *invalid_list)
2512 {
2513 int zapped = 0;
2514 unsigned i;
2515
2516 for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
2517 zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2518
2519 return zapped;
2520 }
2521
kvm_mmu_unlink_parents(struct kvm * kvm,struct kvm_mmu_page * sp)2522 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2523 {
2524 u64 *sptep;
2525 struct rmap_iterator iter;
2526
2527 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2528 drop_parent_pte(kvm, sp, sptep);
2529 }
2530
mmu_zap_unsync_children(struct kvm * kvm,struct kvm_mmu_page * parent,struct list_head * invalid_list)2531 static int mmu_zap_unsync_children(struct kvm *kvm,
2532 struct kvm_mmu_page *parent,
2533 struct list_head *invalid_list)
2534 {
2535 int i, zapped = 0;
2536 struct mmu_page_path parents;
2537 struct kvm_mmu_pages pages;
2538
2539 if (parent->role.level == PG_LEVEL_4K)
2540 return 0;
2541
2542 while (mmu_unsync_walk(parent, &pages)) {
2543 struct kvm_mmu_page *sp;
2544
2545 for_each_sp(pages, sp, parents, i) {
2546 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2547 mmu_pages_clear_parents(&parents);
2548 zapped++;
2549 }
2550 }
2551
2552 return zapped;
2553 }
2554
__kvm_mmu_prepare_zap_page(struct kvm * kvm,struct kvm_mmu_page * sp,struct list_head * invalid_list,int * nr_zapped)2555 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2556 struct kvm_mmu_page *sp,
2557 struct list_head *invalid_list,
2558 int *nr_zapped)
2559 {
2560 bool list_unstable, zapped_root = false;
2561
2562 lockdep_assert_held_write(&kvm->mmu_lock);
2563 trace_kvm_mmu_prepare_zap_page(sp);
2564 ++kvm->stat.mmu_shadow_zapped;
2565 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2566 *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2567 kvm_mmu_unlink_parents(kvm, sp);
2568
2569 /* Zapping children means active_mmu_pages has become unstable. */
2570 list_unstable = *nr_zapped;
2571
2572 if (!sp->role.invalid && sp_has_gptes(sp))
2573 unaccount_shadowed(kvm, sp);
2574
2575 if (sp->unsync)
2576 kvm_unlink_unsync_page(kvm, sp);
2577 if (!sp->root_count) {
2578 /* Count self */
2579 (*nr_zapped)++;
2580
2581 /*
2582 * Already invalid pages (previously active roots) are not on
2583 * the active page list. See list_del() in the "else" case of
2584 * !sp->root_count.
2585 */
2586 if (sp->role.invalid)
2587 list_add(&sp->link, invalid_list);
2588 else
2589 list_move(&sp->link, invalid_list);
2590 kvm_unaccount_mmu_page(kvm, sp);
2591 } else {
2592 /*
2593 * Remove the active root from the active page list, the root
2594 * will be explicitly freed when the root_count hits zero.
2595 */
2596 list_del(&sp->link);
2597
2598 /*
2599 * Obsolete pages cannot be used on any vCPUs, see the comment
2600 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2601 * treats invalid shadow pages as being obsolete.
2602 */
2603 zapped_root = !is_obsolete_sp(kvm, sp);
2604 }
2605
2606 if (sp->nx_huge_page_disallowed)
2607 unaccount_nx_huge_page(kvm, sp);
2608
2609 sp->role.invalid = 1;
2610
2611 /*
2612 * Make the request to free obsolete roots after marking the root
2613 * invalid, otherwise other vCPUs may not see it as invalid.
2614 */
2615 if (zapped_root)
2616 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2617 return list_unstable;
2618 }
2619
kvm_mmu_prepare_zap_page(struct kvm * kvm,struct kvm_mmu_page * sp,struct list_head * invalid_list)2620 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2621 struct list_head *invalid_list)
2622 {
2623 int nr_zapped;
2624
2625 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2626 return nr_zapped;
2627 }
2628
kvm_mmu_commit_zap_page(struct kvm * kvm,struct list_head * invalid_list)2629 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2630 struct list_head *invalid_list)
2631 {
2632 struct kvm_mmu_page *sp, *nsp;
2633
2634 if (list_empty(invalid_list))
2635 return;
2636
2637 /*
2638 * We need to make sure everyone sees our modifications to
2639 * the page tables and see changes to vcpu->mode here. The barrier
2640 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2641 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2642 *
2643 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2644 * guest mode and/or lockless shadow page table walks.
2645 */
2646 kvm_flush_remote_tlbs(kvm);
2647
2648 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2649 WARN_ON_ONCE(!sp->role.invalid || sp->root_count);
2650 kvm_mmu_free_shadow_page(sp);
2651 }
2652 }
2653
kvm_mmu_zap_oldest_mmu_pages(struct kvm * kvm,unsigned long nr_to_zap)2654 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2655 unsigned long nr_to_zap)
2656 {
2657 unsigned long total_zapped = 0;
2658 struct kvm_mmu_page *sp, *tmp;
2659 LIST_HEAD(invalid_list);
2660 bool unstable;
2661 int nr_zapped;
2662
2663 if (list_empty(&kvm->arch.active_mmu_pages))
2664 return 0;
2665
2666 restart:
2667 list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2668 /*
2669 * Don't zap active root pages, the page itself can't be freed
2670 * and zapping it will just force vCPUs to realloc and reload.
2671 */
2672 if (sp->root_count)
2673 continue;
2674
2675 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2676 &nr_zapped);
2677 total_zapped += nr_zapped;
2678 if (total_zapped >= nr_to_zap)
2679 break;
2680
2681 if (unstable)
2682 goto restart;
2683 }
2684
2685 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2686
2687 kvm->stat.mmu_recycled += total_zapped;
2688 return total_zapped;
2689 }
2690
kvm_mmu_available_pages(struct kvm * kvm)2691 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2692 {
2693 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2694 return kvm->arch.n_max_mmu_pages -
2695 kvm->arch.n_used_mmu_pages;
2696
2697 return 0;
2698 }
2699
make_mmu_pages_available(struct kvm_vcpu * vcpu)2700 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2701 {
2702 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2703
2704 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2705 return 0;
2706
2707 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2708
2709 /*
2710 * Note, this check is intentionally soft, it only guarantees that one
2711 * page is available, while the caller may end up allocating as many as
2712 * four pages, e.g. for PAE roots or for 5-level paging. Temporarily
2713 * exceeding the (arbitrary by default) limit will not harm the host,
2714 * being too aggressive may unnecessarily kill the guest, and getting an
2715 * exact count is far more trouble than it's worth, especially in the
2716 * page fault paths.
2717 */
2718 if (!kvm_mmu_available_pages(vcpu->kvm))
2719 return -ENOSPC;
2720 return 0;
2721 }
2722
2723 /*
2724 * Changing the number of mmu pages allocated to the vm
2725 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2726 */
kvm_mmu_change_mmu_pages(struct kvm * kvm,unsigned long goal_nr_mmu_pages)2727 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2728 {
2729 write_lock(&kvm->mmu_lock);
2730
2731 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2732 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2733 goal_nr_mmu_pages);
2734
2735 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2736 }
2737
2738 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2739
2740 write_unlock(&kvm->mmu_lock);
2741 }
2742
__kvm_mmu_unprotect_gfn_and_retry(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,bool always_retry)2743 bool __kvm_mmu_unprotect_gfn_and_retry(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
2744 bool always_retry)
2745 {
2746 struct kvm *kvm = vcpu->kvm;
2747 LIST_HEAD(invalid_list);
2748 struct kvm_mmu_page *sp;
2749 gpa_t gpa = cr2_or_gpa;
2750 bool r = false;
2751
2752 /*
2753 * Bail early if there aren't any write-protected shadow pages to avoid
2754 * unnecessarily taking mmu_lock lock, e.g. if the gfn is write-tracked
2755 * by a third party. Reading indirect_shadow_pages without holding
2756 * mmu_lock is safe, as this is purely an optimization, i.e. a false
2757 * positive is benign, and a false negative will simply result in KVM
2758 * skipping the unprotect+retry path, which is also an optimization.
2759 */
2760 if (!READ_ONCE(kvm->arch.indirect_shadow_pages))
2761 goto out;
2762
2763 if (!vcpu->arch.mmu->root_role.direct) {
2764 gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
2765 if (gpa == INVALID_GPA)
2766 goto out;
2767 }
2768
2769 write_lock(&kvm->mmu_lock);
2770 for_each_gfn_valid_sp_with_gptes(kvm, sp, gpa_to_gfn(gpa))
2771 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2772
2773 /*
2774 * Snapshot the result before zapping, as zapping will remove all list
2775 * entries, i.e. checking the list later would yield a false negative.
2776 */
2777 r = !list_empty(&invalid_list);
2778 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2779 write_unlock(&kvm->mmu_lock);
2780
2781 out:
2782 if (r || always_retry) {
2783 vcpu->arch.last_retry_eip = kvm_rip_read(vcpu);
2784 vcpu->arch.last_retry_addr = cr2_or_gpa;
2785 }
2786 return r;
2787 }
2788
kvm_unsync_page(struct kvm * kvm,struct kvm_mmu_page * sp)2789 static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2790 {
2791 trace_kvm_mmu_unsync_page(sp);
2792 ++kvm->stat.mmu_unsync;
2793 sp->unsync = 1;
2794
2795 kvm_mmu_mark_parents_unsync(sp);
2796 }
2797
2798 /*
2799 * Attempt to unsync any shadow pages that can be reached by the specified gfn,
2800 * KVM is creating a writable mapping for said gfn. Returns 0 if all pages
2801 * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
2802 * be write-protected.
2803 */
mmu_try_to_unsync_pages(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t gfn,bool can_unsync,bool prefetch)2804 int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
2805 gfn_t gfn, bool can_unsync, bool prefetch)
2806 {
2807 struct kvm_mmu_page *sp;
2808 bool locked = false;
2809
2810 /*
2811 * Force write-protection if the page is being tracked. Note, the page
2812 * track machinery is used to write-protect upper-level shadow pages,
2813 * i.e. this guards the role.level == 4K assertion below!
2814 */
2815 if (kvm_gfn_is_write_tracked(kvm, slot, gfn))
2816 return -EPERM;
2817
2818 /*
2819 * The page is not write-tracked, mark existing shadow pages unsync
2820 * unless KVM is synchronizing an unsync SP (can_unsync = false). In
2821 * that case, KVM must complete emulation of the guest TLB flush before
2822 * allowing shadow pages to become unsync (writable by the guest).
2823 */
2824 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2825 if (!can_unsync)
2826 return -EPERM;
2827
2828 if (sp->unsync)
2829 continue;
2830
2831 if (prefetch)
2832 return -EEXIST;
2833
2834 /*
2835 * TDP MMU page faults require an additional spinlock as they
2836 * run with mmu_lock held for read, not write, and the unsync
2837 * logic is not thread safe. Take the spinklock regardless of
2838 * the MMU type to avoid extra conditionals/parameters, there's
2839 * no meaningful penalty if mmu_lock is held for write.
2840 */
2841 if (!locked) {
2842 locked = true;
2843 spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2844
2845 /*
2846 * Recheck after taking the spinlock, a different vCPU
2847 * may have since marked the page unsync. A false
2848 * negative on the unprotected check above is not
2849 * possible as clearing sp->unsync _must_ hold mmu_lock
2850 * for write, i.e. unsync cannot transition from 1->0
2851 * while this CPU holds mmu_lock for read (or write).
2852 */
2853 if (READ_ONCE(sp->unsync))
2854 continue;
2855 }
2856
2857 WARN_ON_ONCE(sp->role.level != PG_LEVEL_4K);
2858 kvm_unsync_page(kvm, sp);
2859 }
2860 if (locked)
2861 spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2862
2863 /*
2864 * We need to ensure that the marking of unsync pages is visible
2865 * before the SPTE is updated to allow writes because
2866 * kvm_mmu_sync_roots() checks the unsync flags without holding
2867 * the MMU lock and so can race with this. If the SPTE was updated
2868 * before the page had been marked as unsync-ed, something like the
2869 * following could happen:
2870 *
2871 * CPU 1 CPU 2
2872 * ---------------------------------------------------------------------
2873 * 1.2 Host updates SPTE
2874 * to be writable
2875 * 2.1 Guest writes a GPTE for GVA X.
2876 * (GPTE being in the guest page table shadowed
2877 * by the SP from CPU 1.)
2878 * This reads SPTE during the page table walk.
2879 * Since SPTE.W is read as 1, there is no
2880 * fault.
2881 *
2882 * 2.2 Guest issues TLB flush.
2883 * That causes a VM Exit.
2884 *
2885 * 2.3 Walking of unsync pages sees sp->unsync is
2886 * false and skips the page.
2887 *
2888 * 2.4 Guest accesses GVA X.
2889 * Since the mapping in the SP was not updated,
2890 * so the old mapping for GVA X incorrectly
2891 * gets used.
2892 * 1.1 Host marks SP
2893 * as unsync
2894 * (sp->unsync = true)
2895 *
2896 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2897 * the situation in 2.4 does not arise. It pairs with the read barrier
2898 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2899 */
2900 smp_wmb();
2901
2902 return 0;
2903 }
2904
mmu_set_spte(struct kvm_vcpu * vcpu,struct kvm_memory_slot * slot,u64 * sptep,unsigned int pte_access,gfn_t gfn,kvm_pfn_t pfn,struct kvm_page_fault * fault)2905 static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
2906 u64 *sptep, unsigned int pte_access, gfn_t gfn,
2907 kvm_pfn_t pfn, struct kvm_page_fault *fault)
2908 {
2909 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2910 int level = sp->role.level;
2911 int was_rmapped = 0;
2912 int ret = RET_PF_FIXED;
2913 bool flush = false;
2914 bool wrprot;
2915 u64 spte;
2916
2917 /* Prefetching always gets a writable pfn. */
2918 bool host_writable = !fault || fault->map_writable;
2919 bool prefetch = !fault || fault->prefetch;
2920 bool write_fault = fault && fault->write;
2921
2922 if (unlikely(is_noslot_pfn(pfn))) {
2923 vcpu->stat.pf_mmio_spte_created++;
2924 mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2925 return RET_PF_EMULATE;
2926 }
2927
2928 if (is_shadow_present_pte(*sptep)) {
2929 /*
2930 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2931 * the parent of the now unreachable PTE.
2932 */
2933 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2934 struct kvm_mmu_page *child;
2935 u64 pte = *sptep;
2936
2937 child = spte_to_child_sp(pte);
2938 drop_parent_pte(vcpu->kvm, child, sptep);
2939 flush = true;
2940 } else if (pfn != spte_to_pfn(*sptep)) {
2941 drop_spte(vcpu->kvm, sptep);
2942 flush = true;
2943 } else
2944 was_rmapped = 1;
2945 }
2946
2947 wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
2948 true, host_writable, &spte);
2949
2950 if (*sptep == spte) {
2951 ret = RET_PF_SPURIOUS;
2952 } else {
2953 flush |= mmu_spte_update(sptep, spte);
2954 trace_kvm_mmu_set_spte(level, gfn, sptep);
2955 }
2956
2957 if (wrprot && write_fault)
2958 ret = RET_PF_WRITE_PROTECTED;
2959
2960 if (flush)
2961 kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2962
2963 if (!was_rmapped) {
2964 WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
2965 rmap_add(vcpu, slot, sptep, gfn, pte_access);
2966 } else {
2967 /* Already rmapped but the pte_access bits may have changed. */
2968 kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2969 }
2970
2971 return ret;
2972 }
2973
direct_pte_prefetch_many(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * start,u64 * end)2974 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2975 struct kvm_mmu_page *sp,
2976 u64 *start, u64 *end)
2977 {
2978 struct page *pages[PTE_PREFETCH_NUM];
2979 struct kvm_memory_slot *slot;
2980 unsigned int access = sp->role.access;
2981 int i, ret;
2982 gfn_t gfn;
2983
2984 gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2985 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2986 if (!slot)
2987 return -1;
2988
2989 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2990 if (ret <= 0)
2991 return -1;
2992
2993 for (i = 0; i < ret; i++, gfn++, start++) {
2994 mmu_set_spte(vcpu, slot, start, access, gfn,
2995 page_to_pfn(pages[i]), NULL);
2996 put_page(pages[i]);
2997 }
2998
2999 return 0;
3000 }
3001
__direct_pte_prefetch(struct kvm_vcpu * vcpu,struct kvm_mmu_page * sp,u64 * sptep)3002 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3003 struct kvm_mmu_page *sp, u64 *sptep)
3004 {
3005 u64 *spte, *start = NULL;
3006 int i;
3007
3008 WARN_ON_ONCE(!sp->role.direct);
3009
3010 i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3011 spte = sp->spt + i;
3012
3013 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3014 if (is_shadow_present_pte(*spte) || spte == sptep) {
3015 if (!start)
3016 continue;
3017 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3018 return;
3019 start = NULL;
3020 } else if (!start)
3021 start = spte;
3022 }
3023 if (start)
3024 direct_pte_prefetch_many(vcpu, sp, start, spte);
3025 }
3026
direct_pte_prefetch(struct kvm_vcpu * vcpu,u64 * sptep)3027 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3028 {
3029 struct kvm_mmu_page *sp;
3030
3031 sp = sptep_to_sp(sptep);
3032
3033 /*
3034 * Without accessed bits, there's no way to distinguish between
3035 * actually accessed translations and prefetched, so disable pte
3036 * prefetch if accessed bits aren't available.
3037 */
3038 if (sp_ad_disabled(sp))
3039 return;
3040
3041 if (sp->role.level > PG_LEVEL_4K)
3042 return;
3043
3044 /*
3045 * If addresses are being invalidated, skip prefetching to avoid
3046 * accidentally prefetching those addresses.
3047 */
3048 if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
3049 return;
3050
3051 __direct_pte_prefetch(vcpu, sp, sptep);
3052 }
3053
3054 /*
3055 * Lookup the mapping level for @gfn in the current mm.
3056 *
3057 * WARNING! Use of host_pfn_mapping_level() requires the caller and the end
3058 * consumer to be tied into KVM's handlers for MMU notifier events!
3059 *
3060 * There are several ways to safely use this helper:
3061 *
3062 * - Check mmu_invalidate_retry_gfn() after grabbing the mapping level, before
3063 * consuming it. In this case, mmu_lock doesn't need to be held during the
3064 * lookup, but it does need to be held while checking the MMU notifier.
3065 *
3066 * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
3067 * event for the hva. This can be done by explicit checking the MMU notifier
3068 * or by ensuring that KVM already has a valid mapping that covers the hva.
3069 *
3070 * - Do not use the result to install new mappings, e.g. use the host mapping
3071 * level only to decide whether or not to zap an entry. In this case, it's
3072 * not required to hold mmu_lock (though it's highly likely the caller will
3073 * want to hold mmu_lock anyways, e.g. to modify SPTEs).
3074 *
3075 * Note! The lookup can still race with modifications to host page tables, but
3076 * the above "rules" ensure KVM will not _consume_ the result of the walk if a
3077 * race with the primary MMU occurs.
3078 */
host_pfn_mapping_level(struct kvm * kvm,gfn_t gfn,const struct kvm_memory_slot * slot)3079 static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
3080 const struct kvm_memory_slot *slot)
3081 {
3082 int level = PG_LEVEL_4K;
3083 unsigned long hva;
3084 unsigned long flags;
3085 pgd_t pgd;
3086 p4d_t p4d;
3087 pud_t pud;
3088 pmd_t pmd;
3089
3090 /*
3091 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3092 * is not solely for performance, it's also necessary to avoid the
3093 * "writable" check in __gfn_to_hva_many(), which will always fail on
3094 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
3095 * page fault steps have already verified the guest isn't writing a
3096 * read-only memslot.
3097 */
3098 hva = __gfn_to_hva_memslot(slot, gfn);
3099
3100 /*
3101 * Disable IRQs to prevent concurrent tear down of host page tables,
3102 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
3103 * the original page table.
3104 */
3105 local_irq_save(flags);
3106
3107 /*
3108 * Read each entry once. As above, a non-leaf entry can be promoted to
3109 * a huge page _during_ this walk. Re-reading the entry could send the
3110 * walk into the weeks, e.g. p*d_leaf() returns false (sees the old
3111 * value) and then p*d_offset() walks into the target huge page instead
3112 * of the old page table (sees the new value).
3113 */
3114 pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
3115 if (pgd_none(pgd))
3116 goto out;
3117
3118 p4d = READ_ONCE(*p4d_offset(&pgd, hva));
3119 if (p4d_none(p4d) || !p4d_present(p4d))
3120 goto out;
3121
3122 pud = READ_ONCE(*pud_offset(&p4d, hva));
3123 if (pud_none(pud) || !pud_present(pud))
3124 goto out;
3125
3126 if (pud_leaf(pud)) {
3127 level = PG_LEVEL_1G;
3128 goto out;
3129 }
3130
3131 pmd = READ_ONCE(*pmd_offset(&pud, hva));
3132 if (pmd_none(pmd) || !pmd_present(pmd))
3133 goto out;
3134
3135 if (pmd_leaf(pmd))
3136 level = PG_LEVEL_2M;
3137
3138 out:
3139 local_irq_restore(flags);
3140 return level;
3141 }
3142
__kvm_mmu_max_mapping_level(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t gfn,int max_level,bool is_private)3143 static int __kvm_mmu_max_mapping_level(struct kvm *kvm,
3144 const struct kvm_memory_slot *slot,
3145 gfn_t gfn, int max_level, bool is_private)
3146 {
3147 struct kvm_lpage_info *linfo;
3148 int host_level;
3149
3150 max_level = min(max_level, max_huge_page_level);
3151 for ( ; max_level > PG_LEVEL_4K; max_level--) {
3152 linfo = lpage_info_slot(gfn, slot, max_level);
3153 if (!linfo->disallow_lpage)
3154 break;
3155 }
3156
3157 if (is_private)
3158 return max_level;
3159
3160 if (max_level == PG_LEVEL_4K)
3161 return PG_LEVEL_4K;
3162
3163 host_level = host_pfn_mapping_level(kvm, gfn, slot);
3164 return min(host_level, max_level);
3165 }
3166
kvm_mmu_max_mapping_level(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t gfn,int max_level)3167 int kvm_mmu_max_mapping_level(struct kvm *kvm,
3168 const struct kvm_memory_slot *slot, gfn_t gfn,
3169 int max_level)
3170 {
3171 bool is_private = kvm_slot_can_be_private(slot) &&
3172 kvm_mem_is_private(kvm, gfn);
3173
3174 return __kvm_mmu_max_mapping_level(kvm, slot, gfn, max_level, is_private);
3175 }
3176
kvm_mmu_hugepage_adjust(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3177 void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3178 {
3179 struct kvm_memory_slot *slot = fault->slot;
3180 kvm_pfn_t mask;
3181
3182 fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
3183
3184 if (unlikely(fault->max_level == PG_LEVEL_4K))
3185 return;
3186
3187 if (is_error_noslot_pfn(fault->pfn))
3188 return;
3189
3190 if (kvm_slot_dirty_track_enabled(slot))
3191 return;
3192
3193 /*
3194 * Enforce the iTLB multihit workaround after capturing the requested
3195 * level, which will be used to do precise, accurate accounting.
3196 */
3197 fault->req_level = __kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3198 fault->gfn, fault->max_level,
3199 fault->is_private);
3200 if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
3201 return;
3202
3203 /*
3204 * mmu_invalidate_retry() was successful and mmu_lock is held, so
3205 * the pmd can't be split from under us.
3206 */
3207 fault->goal_level = fault->req_level;
3208 mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
3209 VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
3210 fault->pfn &= ~mask;
3211 }
3212
disallowed_hugepage_adjust(struct kvm_page_fault * fault,u64 spte,int cur_level)3213 void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3214 {
3215 if (cur_level > PG_LEVEL_4K &&
3216 cur_level == fault->goal_level &&
3217 is_shadow_present_pte(spte) &&
3218 !is_large_pte(spte) &&
3219 spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3220 /*
3221 * A small SPTE exists for this pfn, but FNAME(fetch),
3222 * direct_map(), or kvm_tdp_mmu_map() would like to create a
3223 * large PTE instead: just force them to go down another level,
3224 * patching back for them into pfn the next 9 bits of the
3225 * address.
3226 */
3227 u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3228 KVM_PAGES_PER_HPAGE(cur_level - 1);
3229 fault->pfn |= fault->gfn & page_mask;
3230 fault->goal_level--;
3231 }
3232 }
3233
direct_map(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3234 static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3235 {
3236 struct kvm_shadow_walk_iterator it;
3237 struct kvm_mmu_page *sp;
3238 int ret;
3239 gfn_t base_gfn = fault->gfn;
3240
3241 kvm_mmu_hugepage_adjust(vcpu, fault);
3242
3243 trace_kvm_mmu_spte_requested(fault);
3244 for_each_shadow_entry(vcpu, fault->addr, it) {
3245 /*
3246 * We cannot overwrite existing page tables with an NX
3247 * large page, as the leaf could be executable.
3248 */
3249 if (fault->nx_huge_page_workaround_enabled)
3250 disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3251
3252 base_gfn = gfn_round_for_level(fault->gfn, it.level);
3253 if (it.level == fault->goal_level)
3254 break;
3255
3256 sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
3257 if (sp == ERR_PTR(-EEXIST))
3258 continue;
3259
3260 link_shadow_page(vcpu, it.sptep, sp);
3261 if (fault->huge_page_disallowed)
3262 account_nx_huge_page(vcpu->kvm, sp,
3263 fault->req_level >= it.level);
3264 }
3265
3266 if (WARN_ON_ONCE(it.level != fault->goal_level))
3267 return -EFAULT;
3268
3269 ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3270 base_gfn, fault->pfn, fault);
3271 if (ret == RET_PF_SPURIOUS)
3272 return ret;
3273
3274 direct_pte_prefetch(vcpu, it.sptep);
3275 return ret;
3276 }
3277
kvm_send_hwpoison_signal(struct kvm_memory_slot * slot,gfn_t gfn)3278 static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3279 {
3280 unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3281
3282 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3283 }
3284
kvm_handle_error_pfn(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3285 static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3286 {
3287 if (is_sigpending_pfn(fault->pfn)) {
3288 kvm_handle_signal_exit(vcpu);
3289 return -EINTR;
3290 }
3291
3292 /*
3293 * Do not cache the mmio info caused by writing the readonly gfn
3294 * into the spte otherwise read access on readonly gfn also can
3295 * caused mmio page fault and treat it as mmio access.
3296 */
3297 if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3298 return RET_PF_EMULATE;
3299
3300 if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3301 kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3302 return RET_PF_RETRY;
3303 }
3304
3305 return -EFAULT;
3306 }
3307
kvm_handle_noslot_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault,unsigned int access)3308 static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3309 struct kvm_page_fault *fault,
3310 unsigned int access)
3311 {
3312 gva_t gva = fault->is_tdp ? 0 : fault->addr;
3313
3314 if (fault->is_private) {
3315 kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
3316 return -EFAULT;
3317 }
3318
3319 vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3320 access & shadow_mmio_access_mask);
3321
3322 fault->slot = NULL;
3323 fault->pfn = KVM_PFN_NOSLOT;
3324 fault->map_writable = false;
3325 fault->hva = KVM_HVA_ERR_BAD;
3326
3327 /*
3328 * If MMIO caching is disabled, emulate immediately without
3329 * touching the shadow page tables as attempting to install an
3330 * MMIO SPTE will just be an expensive nop.
3331 */
3332 if (unlikely(!enable_mmio_caching))
3333 return RET_PF_EMULATE;
3334
3335 /*
3336 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3337 * any guest that generates such gfns is running nested and is being
3338 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3339 * only if L1's MAXPHYADDR is inaccurate with respect to the
3340 * hardware's).
3341 */
3342 if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3343 return RET_PF_EMULATE;
3344
3345 return RET_PF_CONTINUE;
3346 }
3347
page_fault_can_be_fast(struct kvm * kvm,struct kvm_page_fault * fault)3348 static bool page_fault_can_be_fast(struct kvm *kvm, struct kvm_page_fault *fault)
3349 {
3350 /*
3351 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
3352 * reach the common page fault handler if the SPTE has an invalid MMIO
3353 * generation number. Refreshing the MMIO generation needs to go down
3354 * the slow path. Note, EPT Misconfigs do NOT set the PRESENT flag!
3355 */
3356 if (fault->rsvd)
3357 return false;
3358
3359 /*
3360 * For hardware-protected VMs, certain conditions like attempting to
3361 * perform a write to a page which is not in the state that the guest
3362 * expects it to be in can result in a nested/extended #PF. In this
3363 * case, the below code might misconstrue this situation as being the
3364 * result of a write-protected access, and treat it as a spurious case
3365 * rather than taking any action to satisfy the real source of the #PF
3366 * such as generating a KVM_EXIT_MEMORY_FAULT. This can lead to the
3367 * guest spinning on a #PF indefinitely, so don't attempt the fast path
3368 * in this case.
3369 *
3370 * Note that the kvm_mem_is_private() check might race with an
3371 * attribute update, but this will either result in the guest spinning
3372 * on RET_PF_SPURIOUS until the update completes, or an actual spurious
3373 * case might go down the slow path. Either case will resolve itself.
3374 */
3375 if (kvm->arch.has_private_mem &&
3376 fault->is_private != kvm_mem_is_private(kvm, fault->gfn))
3377 return false;
3378
3379 /*
3380 * #PF can be fast if:
3381 *
3382 * 1. The shadow page table entry is not present and A/D bits are
3383 * disabled _by KVM_, which could mean that the fault is potentially
3384 * caused by access tracking (if enabled). If A/D bits are enabled
3385 * by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
3386 * bits for L2 and employ access tracking, but the fast page fault
3387 * mechanism only supports direct MMUs.
3388 * 2. The shadow page table entry is present, the access is a write,
3389 * and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
3390 * the fault was caused by a write-protection violation. If the
3391 * SPTE is MMU-writable (determined later), the fault can be fixed
3392 * by setting the Writable bit, which can be done out of mmu_lock.
3393 */
3394 if (!fault->present)
3395 return !kvm_ad_enabled();
3396
3397 /*
3398 * Note, instruction fetches and writes are mutually exclusive, ignore
3399 * the "exec" flag.
3400 */
3401 return fault->write;
3402 }
3403
3404 /*
3405 * Returns true if the SPTE was fixed successfully. Otherwise,
3406 * someone else modified the SPTE from its original value.
3407 */
fast_pf_fix_direct_spte(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault,u64 * sptep,u64 old_spte,u64 new_spte)3408 static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3409 struct kvm_page_fault *fault,
3410 u64 *sptep, u64 old_spte, u64 new_spte)
3411 {
3412 /*
3413 * Theoretically we could also set dirty bit (and flush TLB) here in
3414 * order to eliminate unnecessary PML logging. See comments in
3415 * set_spte. But fast_page_fault is very unlikely to happen with PML
3416 * enabled, so we do not do this. This might result in the same GPA
3417 * to be logged in PML buffer again when the write really happens, and
3418 * eventually to be called by mark_page_dirty twice. But it's also no
3419 * harm. This also avoids the TLB flush needed after setting dirty bit
3420 * so non-PML cases won't be impacted.
3421 *
3422 * Compare with set_spte where instead shadow_dirty_mask is set.
3423 */
3424 if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3425 return false;
3426
3427 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3428 mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3429
3430 return true;
3431 }
3432
is_access_allowed(struct kvm_page_fault * fault,u64 spte)3433 static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3434 {
3435 if (fault->exec)
3436 return is_executable_pte(spte);
3437
3438 if (fault->write)
3439 return is_writable_pte(spte);
3440
3441 /* Fault was on Read access */
3442 return spte & PT_PRESENT_MASK;
3443 }
3444
3445 /*
3446 * Returns the last level spte pointer of the shadow page walk for the given
3447 * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
3448 * walk could be performed, returns NULL and *spte does not contain valid data.
3449 *
3450 * Contract:
3451 * - Must be called between walk_shadow_page_lockless_{begin,end}.
3452 * - The returned sptep must not be used after walk_shadow_page_lockless_end.
3453 */
fast_pf_get_last_sptep(struct kvm_vcpu * vcpu,gpa_t gpa,u64 * spte)3454 static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
3455 {
3456 struct kvm_shadow_walk_iterator iterator;
3457 u64 old_spte;
3458 u64 *sptep = NULL;
3459
3460 for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
3461 sptep = iterator.sptep;
3462 *spte = old_spte;
3463 }
3464
3465 return sptep;
3466 }
3467
3468 /*
3469 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3470 */
fast_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)3471 static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3472 {
3473 struct kvm_mmu_page *sp;
3474 int ret = RET_PF_INVALID;
3475 u64 spte;
3476 u64 *sptep;
3477 uint retry_count = 0;
3478
3479 if (!page_fault_can_be_fast(vcpu->kvm, fault))
3480 return ret;
3481
3482 walk_shadow_page_lockless_begin(vcpu);
3483
3484 do {
3485 u64 new_spte;
3486
3487 if (tdp_mmu_enabled)
3488 sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->gfn, &spte);
3489 else
3490 sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3491
3492 /*
3493 * It's entirely possible for the mapping to have been zapped
3494 * by a different task, but the root page should always be
3495 * available as the vCPU holds a reference to its root(s).
3496 */
3497 if (WARN_ON_ONCE(!sptep))
3498 spte = FROZEN_SPTE;
3499
3500 if (!is_shadow_present_pte(spte))
3501 break;
3502
3503 sp = sptep_to_sp(sptep);
3504 if (!is_last_spte(spte, sp->role.level))
3505 break;
3506
3507 /*
3508 * Check whether the memory access that caused the fault would
3509 * still cause it if it were to be performed right now. If not,
3510 * then this is a spurious fault caused by TLB lazily flushed,
3511 * or some other CPU has already fixed the PTE after the
3512 * current CPU took the fault.
3513 *
3514 * Need not check the access of upper level table entries since
3515 * they are always ACC_ALL.
3516 */
3517 if (is_access_allowed(fault, spte)) {
3518 ret = RET_PF_SPURIOUS;
3519 break;
3520 }
3521
3522 new_spte = spte;
3523
3524 /*
3525 * KVM only supports fixing page faults outside of MMU lock for
3526 * direct MMUs, nested MMUs are always indirect, and KVM always
3527 * uses A/D bits for non-nested MMUs. Thus, if A/D bits are
3528 * enabled, the SPTE can't be an access-tracked SPTE.
3529 */
3530 if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3531 new_spte = restore_acc_track_spte(new_spte);
3532
3533 /*
3534 * To keep things simple, only SPTEs that are MMU-writable can
3535 * be made fully writable outside of mmu_lock, e.g. only SPTEs
3536 * that were write-protected for dirty-logging or access
3537 * tracking are handled here. Don't bother checking if the
3538 * SPTE is writable to prioritize running with A/D bits enabled.
3539 * The is_access_allowed() check above handles the common case
3540 * of the fault being spurious, and the SPTE is known to be
3541 * shadow-present, i.e. except for access tracking restoration
3542 * making the new SPTE writable, the check is wasteful.
3543 */
3544 if (fault->write && is_mmu_writable_spte(spte)) {
3545 new_spte |= PT_WRITABLE_MASK;
3546
3547 /*
3548 * Do not fix write-permission on the large spte when
3549 * dirty logging is enabled. Since we only dirty the
3550 * first page into the dirty-bitmap in
3551 * fast_pf_fix_direct_spte(), other pages are missed
3552 * if its slot has dirty logging enabled.
3553 *
3554 * Instead, we let the slow page fault path create a
3555 * normal spte to fix the access.
3556 */
3557 if (sp->role.level > PG_LEVEL_4K &&
3558 kvm_slot_dirty_track_enabled(fault->slot))
3559 break;
3560 }
3561
3562 /* Verify that the fault can be handled in the fast path */
3563 if (new_spte == spte ||
3564 !is_access_allowed(fault, new_spte))
3565 break;
3566
3567 /*
3568 * Currently, fast page fault only works for direct mapping
3569 * since the gfn is not stable for indirect shadow page. See
3570 * Documentation/virt/kvm/locking.rst to get more detail.
3571 */
3572 if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3573 ret = RET_PF_FIXED;
3574 break;
3575 }
3576
3577 if (++retry_count > 4) {
3578 pr_warn_once("Fast #PF retrying more than 4 times.\n");
3579 break;
3580 }
3581
3582 } while (true);
3583
3584 trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3585 walk_shadow_page_lockless_end(vcpu);
3586
3587 if (ret != RET_PF_INVALID)
3588 vcpu->stat.pf_fast++;
3589
3590 return ret;
3591 }
3592
mmu_free_root_page(struct kvm * kvm,hpa_t * root_hpa,struct list_head * invalid_list)3593 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3594 struct list_head *invalid_list)
3595 {
3596 struct kvm_mmu_page *sp;
3597
3598 if (!VALID_PAGE(*root_hpa))
3599 return;
3600
3601 sp = root_to_sp(*root_hpa);
3602 if (WARN_ON_ONCE(!sp))
3603 return;
3604
3605 if (is_tdp_mmu_page(sp)) {
3606 lockdep_assert_held_read(&kvm->mmu_lock);
3607 kvm_tdp_mmu_put_root(kvm, sp);
3608 } else {
3609 lockdep_assert_held_write(&kvm->mmu_lock);
3610 if (!--sp->root_count && sp->role.invalid)
3611 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3612 }
3613
3614 *root_hpa = INVALID_PAGE;
3615 }
3616
3617 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
kvm_mmu_free_roots(struct kvm * kvm,struct kvm_mmu * mmu,ulong roots_to_free)3618 void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3619 ulong roots_to_free)
3620 {
3621 bool is_tdp_mmu = tdp_mmu_enabled && mmu->root_role.direct;
3622 int i;
3623 LIST_HEAD(invalid_list);
3624 bool free_active_root;
3625
3626 WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3627
3628 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3629
3630 /* Before acquiring the MMU lock, see if we need to do any real work. */
3631 free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3632 && VALID_PAGE(mmu->root.hpa);
3633
3634 if (!free_active_root) {
3635 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3636 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3637 VALID_PAGE(mmu->prev_roots[i].hpa))
3638 break;
3639
3640 if (i == KVM_MMU_NUM_PREV_ROOTS)
3641 return;
3642 }
3643
3644 if (is_tdp_mmu)
3645 read_lock(&kvm->mmu_lock);
3646 else
3647 write_lock(&kvm->mmu_lock);
3648
3649 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3650 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3651 mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3652 &invalid_list);
3653
3654 if (free_active_root) {
3655 if (kvm_mmu_is_dummy_root(mmu->root.hpa)) {
3656 /* Nothing to cleanup for dummy roots. */
3657 } else if (root_to_sp(mmu->root.hpa)) {
3658 mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
3659 } else if (mmu->pae_root) {
3660 for (i = 0; i < 4; ++i) {
3661 if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3662 continue;
3663
3664 mmu_free_root_page(kvm, &mmu->pae_root[i],
3665 &invalid_list);
3666 mmu->pae_root[i] = INVALID_PAE_ROOT;
3667 }
3668 }
3669 mmu->root.hpa = INVALID_PAGE;
3670 mmu->root.pgd = 0;
3671 }
3672
3673 if (is_tdp_mmu) {
3674 read_unlock(&kvm->mmu_lock);
3675 WARN_ON_ONCE(!list_empty(&invalid_list));
3676 } else {
3677 kvm_mmu_commit_zap_page(kvm, &invalid_list);
3678 write_unlock(&kvm->mmu_lock);
3679 }
3680 }
3681 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3682
kvm_mmu_free_guest_mode_roots(struct kvm * kvm,struct kvm_mmu * mmu)3683 void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
3684 {
3685 unsigned long roots_to_free = 0;
3686 struct kvm_mmu_page *sp;
3687 hpa_t root_hpa;
3688 int i;
3689
3690 /*
3691 * This should not be called while L2 is active, L2 can't invalidate
3692 * _only_ its own roots, e.g. INVVPID unconditionally exits.
3693 */
3694 WARN_ON_ONCE(mmu->root_role.guest_mode);
3695
3696 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3697 root_hpa = mmu->prev_roots[i].hpa;
3698 if (!VALID_PAGE(root_hpa))
3699 continue;
3700
3701 sp = root_to_sp(root_hpa);
3702 if (!sp || sp->role.guest_mode)
3703 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
3704 }
3705
3706 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
3707 }
3708 EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
3709
mmu_alloc_root(struct kvm_vcpu * vcpu,gfn_t gfn,int quadrant,u8 level)3710 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
3711 u8 level)
3712 {
3713 union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3714 struct kvm_mmu_page *sp;
3715
3716 role.level = level;
3717 role.quadrant = quadrant;
3718
3719 WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
3720 WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
3721
3722 sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
3723 ++sp->root_count;
3724
3725 return __pa(sp->spt);
3726 }
3727
mmu_alloc_direct_roots(struct kvm_vcpu * vcpu)3728 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3729 {
3730 struct kvm_mmu *mmu = vcpu->arch.mmu;
3731 u8 shadow_root_level = mmu->root_role.level;
3732 hpa_t root;
3733 unsigned i;
3734 int r;
3735
3736 if (tdp_mmu_enabled)
3737 return kvm_tdp_mmu_alloc_root(vcpu);
3738
3739 write_lock(&vcpu->kvm->mmu_lock);
3740 r = make_mmu_pages_available(vcpu);
3741 if (r < 0)
3742 goto out_unlock;
3743
3744 if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3745 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3746 mmu->root.hpa = root;
3747 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3748 if (WARN_ON_ONCE(!mmu->pae_root)) {
3749 r = -EIO;
3750 goto out_unlock;
3751 }
3752
3753 for (i = 0; i < 4; ++i) {
3754 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3755
3756 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
3757 PT32_ROOT_LEVEL);
3758 mmu->pae_root[i] = root | PT_PRESENT_MASK |
3759 shadow_me_value;
3760 }
3761 mmu->root.hpa = __pa(mmu->pae_root);
3762 } else {
3763 WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
3764 r = -EIO;
3765 goto out_unlock;
3766 }
3767
3768 /* root.pgd is ignored for direct MMUs. */
3769 mmu->root.pgd = 0;
3770 out_unlock:
3771 write_unlock(&vcpu->kvm->mmu_lock);
3772 return r;
3773 }
3774
mmu_first_shadow_root_alloc(struct kvm * kvm)3775 static int mmu_first_shadow_root_alloc(struct kvm *kvm)
3776 {
3777 struct kvm_memslots *slots;
3778 struct kvm_memory_slot *slot;
3779 int r = 0, i, bkt;
3780
3781 /*
3782 * Check if this is the first shadow root being allocated before
3783 * taking the lock.
3784 */
3785 if (kvm_shadow_root_allocated(kvm))
3786 return 0;
3787
3788 mutex_lock(&kvm->slots_arch_lock);
3789
3790 /* Recheck, under the lock, whether this is the first shadow root. */
3791 if (kvm_shadow_root_allocated(kvm))
3792 goto out_unlock;
3793
3794 /*
3795 * Check if anything actually needs to be allocated, e.g. all metadata
3796 * will be allocated upfront if TDP is disabled.
3797 */
3798 if (kvm_memslots_have_rmaps(kvm) &&
3799 kvm_page_track_write_tracking_enabled(kvm))
3800 goto out_success;
3801
3802 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
3803 slots = __kvm_memslots(kvm, i);
3804 kvm_for_each_memslot(slot, bkt, slots) {
3805 /*
3806 * Both of these functions are no-ops if the target is
3807 * already allocated, so unconditionally calling both
3808 * is safe. Intentionally do NOT free allocations on
3809 * failure to avoid having to track which allocations
3810 * were made now versus when the memslot was created.
3811 * The metadata is guaranteed to be freed when the slot
3812 * is freed, and will be kept/used if userspace retries
3813 * KVM_RUN instead of killing the VM.
3814 */
3815 r = memslot_rmap_alloc(slot, slot->npages);
3816 if (r)
3817 goto out_unlock;
3818 r = kvm_page_track_write_tracking_alloc(slot);
3819 if (r)
3820 goto out_unlock;
3821 }
3822 }
3823
3824 /*
3825 * Ensure that shadow_root_allocated becomes true strictly after
3826 * all the related pointers are set.
3827 */
3828 out_success:
3829 smp_store_release(&kvm->arch.shadow_root_allocated, true);
3830
3831 out_unlock:
3832 mutex_unlock(&kvm->slots_arch_lock);
3833 return r;
3834 }
3835
mmu_alloc_shadow_roots(struct kvm_vcpu * vcpu)3836 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3837 {
3838 struct kvm_mmu *mmu = vcpu->arch.mmu;
3839 u64 pdptrs[4], pm_mask;
3840 gfn_t root_gfn, root_pgd;
3841 int quadrant, i, r;
3842 hpa_t root;
3843
3844 root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3845 root_gfn = (root_pgd & __PT_BASE_ADDR_MASK) >> PAGE_SHIFT;
3846
3847 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3848 mmu->root.hpa = kvm_mmu_get_dummy_root();
3849 return 0;
3850 }
3851
3852 /*
3853 * On SVM, reading PDPTRs might access guest memory, which might fault
3854 * and thus might sleep. Grab the PDPTRs before acquiring mmu_lock.
3855 */
3856 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3857 for (i = 0; i < 4; ++i) {
3858 pdptrs[i] = mmu->get_pdptr(vcpu, i);
3859 if (!(pdptrs[i] & PT_PRESENT_MASK))
3860 continue;
3861
3862 if (!kvm_vcpu_is_visible_gfn(vcpu, pdptrs[i] >> PAGE_SHIFT))
3863 pdptrs[i] = 0;
3864 }
3865 }
3866
3867 r = mmu_first_shadow_root_alloc(vcpu->kvm);
3868 if (r)
3869 return r;
3870
3871 write_lock(&vcpu->kvm->mmu_lock);
3872 r = make_mmu_pages_available(vcpu);
3873 if (r < 0)
3874 goto out_unlock;
3875
3876 /*
3877 * Do we shadow a long mode page table? If so we need to
3878 * write-protect the guests page table root.
3879 */
3880 if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3881 root = mmu_alloc_root(vcpu, root_gfn, 0,
3882 mmu->root_role.level);
3883 mmu->root.hpa = root;
3884 goto set_root_pgd;
3885 }
3886
3887 if (WARN_ON_ONCE(!mmu->pae_root)) {
3888 r = -EIO;
3889 goto out_unlock;
3890 }
3891
3892 /*
3893 * We shadow a 32 bit page table. This may be a legacy 2-level
3894 * or a PAE 3-level page table. In either case we need to be aware that
3895 * the shadow page table may be a PAE or a long mode page table.
3896 */
3897 pm_mask = PT_PRESENT_MASK | shadow_me_value;
3898 if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3899 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3900
3901 if (WARN_ON_ONCE(!mmu->pml4_root)) {
3902 r = -EIO;
3903 goto out_unlock;
3904 }
3905 mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3906
3907 if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3908 if (WARN_ON_ONCE(!mmu->pml5_root)) {
3909 r = -EIO;
3910 goto out_unlock;
3911 }
3912 mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3913 }
3914 }
3915
3916 for (i = 0; i < 4; ++i) {
3917 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3918
3919 if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3920 if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3921 mmu->pae_root[i] = INVALID_PAE_ROOT;
3922 continue;
3923 }
3924 root_gfn = pdptrs[i] >> PAGE_SHIFT;
3925 }
3926
3927 /*
3928 * If shadowing 32-bit non-PAE page tables, each PAE page
3929 * directory maps one quarter of the guest's non-PAE page
3930 * directory. Othwerise each PAE page direct shadows one guest
3931 * PAE page directory so that quadrant should be 0.
3932 */
3933 quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
3934
3935 root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3936 mmu->pae_root[i] = root | pm_mask;
3937 }
3938
3939 if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3940 mmu->root.hpa = __pa(mmu->pml5_root);
3941 else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3942 mmu->root.hpa = __pa(mmu->pml4_root);
3943 else
3944 mmu->root.hpa = __pa(mmu->pae_root);
3945
3946 set_root_pgd:
3947 mmu->root.pgd = root_pgd;
3948 out_unlock:
3949 write_unlock(&vcpu->kvm->mmu_lock);
3950
3951 return r;
3952 }
3953
mmu_alloc_special_roots(struct kvm_vcpu * vcpu)3954 static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3955 {
3956 struct kvm_mmu *mmu = vcpu->arch.mmu;
3957 bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3958 u64 *pml5_root = NULL;
3959 u64 *pml4_root = NULL;
3960 u64 *pae_root;
3961
3962 /*
3963 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3964 * tables are allocated and initialized at root creation as there is no
3965 * equivalent level in the guest's NPT to shadow. Allocate the tables
3966 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3967 */
3968 if (mmu->root_role.direct ||
3969 mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3970 mmu->root_role.level < PT64_ROOT_4LEVEL)
3971 return 0;
3972
3973 /*
3974 * NPT, the only paging mode that uses this horror, uses a fixed number
3975 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3976 * all MMus are 5-level. Thus, this can safely require that pml5_root
3977 * is allocated if the other roots are valid and pml5 is needed, as any
3978 * prior MMU would also have required pml5.
3979 */
3980 if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3981 return 0;
3982
3983 /*
3984 * The special roots should always be allocated in concert. Yell and
3985 * bail if KVM ends up in a state where only one of the roots is valid.
3986 */
3987 if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3988 (need_pml5 && mmu->pml5_root)))
3989 return -EIO;
3990
3991 /*
3992 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
3993 * doesn't need to be decrypted.
3994 */
3995 pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3996 if (!pae_root)
3997 return -ENOMEM;
3998
3999 #ifdef CONFIG_X86_64
4000 pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
4001 if (!pml4_root)
4002 goto err_pml4;
4003
4004 if (need_pml5) {
4005 pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
4006 if (!pml5_root)
4007 goto err_pml5;
4008 }
4009 #endif
4010
4011 mmu->pae_root = pae_root;
4012 mmu->pml4_root = pml4_root;
4013 mmu->pml5_root = pml5_root;
4014
4015 return 0;
4016
4017 #ifdef CONFIG_X86_64
4018 err_pml5:
4019 free_page((unsigned long)pml4_root);
4020 err_pml4:
4021 free_page((unsigned long)pae_root);
4022 return -ENOMEM;
4023 #endif
4024 }
4025
is_unsync_root(hpa_t root)4026 static bool is_unsync_root(hpa_t root)
4027 {
4028 struct kvm_mmu_page *sp;
4029
4030 if (!VALID_PAGE(root) || kvm_mmu_is_dummy_root(root))
4031 return false;
4032
4033 /*
4034 * The read barrier orders the CPU's read of SPTE.W during the page table
4035 * walk before the reads of sp->unsync/sp->unsync_children here.
4036 *
4037 * Even if another CPU was marking the SP as unsync-ed simultaneously,
4038 * any guest page table changes are not guaranteed to be visible anyway
4039 * until this VCPU issues a TLB flush strictly after those changes are
4040 * made. We only need to ensure that the other CPU sets these flags
4041 * before any actual changes to the page tables are made. The comments
4042 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4043 * requirement isn't satisfied.
4044 */
4045 smp_rmb();
4046 sp = root_to_sp(root);
4047
4048 /*
4049 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
4050 * PDPTEs for a given PAE root need to be synchronized individually.
4051 */
4052 if (WARN_ON_ONCE(!sp))
4053 return false;
4054
4055 if (sp->unsync || sp->unsync_children)
4056 return true;
4057
4058 return false;
4059 }
4060
kvm_mmu_sync_roots(struct kvm_vcpu * vcpu)4061 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4062 {
4063 int i;
4064 struct kvm_mmu_page *sp;
4065
4066 if (vcpu->arch.mmu->root_role.direct)
4067 return;
4068
4069 if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4070 return;
4071
4072 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4073
4074 if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4075 hpa_t root = vcpu->arch.mmu->root.hpa;
4076
4077 if (!is_unsync_root(root))
4078 return;
4079
4080 sp = root_to_sp(root);
4081
4082 write_lock(&vcpu->kvm->mmu_lock);
4083 mmu_sync_children(vcpu, sp, true);
4084 write_unlock(&vcpu->kvm->mmu_lock);
4085 return;
4086 }
4087
4088 write_lock(&vcpu->kvm->mmu_lock);
4089
4090 for (i = 0; i < 4; ++i) {
4091 hpa_t root = vcpu->arch.mmu->pae_root[i];
4092
4093 if (IS_VALID_PAE_ROOT(root)) {
4094 sp = spte_to_child_sp(root);
4095 mmu_sync_children(vcpu, sp, true);
4096 }
4097 }
4098
4099 write_unlock(&vcpu->kvm->mmu_lock);
4100 }
4101
kvm_mmu_sync_prev_roots(struct kvm_vcpu * vcpu)4102 void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
4103 {
4104 unsigned long roots_to_free = 0;
4105 int i;
4106
4107 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4108 if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
4109 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
4110
4111 /* sync prev_roots by simply freeing them */
4112 kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
4113 }
4114
nonpaging_gva_to_gpa(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,gpa_t vaddr,u64 access,struct x86_exception * exception)4115 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4116 gpa_t vaddr, u64 access,
4117 struct x86_exception *exception)
4118 {
4119 if (exception)
4120 exception->error_code = 0;
4121 return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4122 }
4123
mmio_info_in_cache(struct kvm_vcpu * vcpu,u64 addr,bool direct)4124 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4125 {
4126 /*
4127 * A nested guest cannot use the MMIO cache if it is using nested
4128 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4129 */
4130 if (mmu_is_nested(vcpu))
4131 return false;
4132
4133 if (direct)
4134 return vcpu_match_mmio_gpa(vcpu, addr);
4135
4136 return vcpu_match_mmio_gva(vcpu, addr);
4137 }
4138
4139 /*
4140 * Return the level of the lowest level SPTE added to sptes.
4141 * That SPTE may be non-present.
4142 *
4143 * Must be called between walk_shadow_page_lockless_{begin,end}.
4144 */
get_walk(struct kvm_vcpu * vcpu,u64 addr,u64 * sptes,int * root_level)4145 static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4146 {
4147 struct kvm_shadow_walk_iterator iterator;
4148 int leaf = -1;
4149 u64 spte;
4150
4151 for (shadow_walk_init(&iterator, vcpu, addr),
4152 *root_level = iterator.level;
4153 shadow_walk_okay(&iterator);
4154 __shadow_walk_next(&iterator, spte)) {
4155 leaf = iterator.level;
4156 spte = mmu_spte_get_lockless(iterator.sptep);
4157
4158 sptes[leaf] = spte;
4159 }
4160
4161 return leaf;
4162 }
4163
get_sptes_lockless(struct kvm_vcpu * vcpu,u64 addr,u64 * sptes,int * root_level)4164 static int get_sptes_lockless(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes,
4165 int *root_level)
4166 {
4167 int leaf;
4168
4169 walk_shadow_page_lockless_begin(vcpu);
4170
4171 if (is_tdp_mmu_active(vcpu))
4172 leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, root_level);
4173 else
4174 leaf = get_walk(vcpu, addr, sptes, root_level);
4175
4176 walk_shadow_page_lockless_end(vcpu);
4177 return leaf;
4178 }
4179
4180 /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
get_mmio_spte(struct kvm_vcpu * vcpu,u64 addr,u64 * sptep)4181 static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
4182 {
4183 u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
4184 struct rsvd_bits_validate *rsvd_check;
4185 int root, leaf, level;
4186 bool reserved = false;
4187
4188 leaf = get_sptes_lockless(vcpu, addr, sptes, &root);
4189 if (unlikely(leaf < 0)) {
4190 *sptep = 0ull;
4191 return reserved;
4192 }
4193
4194 *sptep = sptes[leaf];
4195
4196 /*
4197 * Skip reserved bits checks on the terminal leaf if it's not a valid
4198 * SPTE. Note, this also (intentionally) skips MMIO SPTEs, which, by
4199 * design, always have reserved bits set. The purpose of the checks is
4200 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
4201 */
4202 if (!is_shadow_present_pte(sptes[leaf]))
4203 leaf++;
4204
4205 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
4206
4207 for (level = root; level >= leaf; level--)
4208 reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4209
4210 if (reserved) {
4211 pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4212 __func__, addr);
4213 for (level = root; level >= leaf; level--)
4214 pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4215 sptes[level], level,
4216 get_rsvd_bits(rsvd_check, sptes[level], level));
4217 }
4218
4219 return reserved;
4220 }
4221
handle_mmio_page_fault(struct kvm_vcpu * vcpu,u64 addr,bool direct)4222 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4223 {
4224 u64 spte;
4225 bool reserved;
4226
4227 if (mmio_info_in_cache(vcpu, addr, direct))
4228 return RET_PF_EMULATE;
4229
4230 reserved = get_mmio_spte(vcpu, addr, &spte);
4231 if (WARN_ON_ONCE(reserved))
4232 return -EINVAL;
4233
4234 if (is_mmio_spte(vcpu->kvm, spte)) {
4235 gfn_t gfn = get_mmio_spte_gfn(spte);
4236 unsigned int access = get_mmio_spte_access(spte);
4237
4238 if (!check_mmio_spte(vcpu, spte))
4239 return RET_PF_INVALID;
4240
4241 if (direct)
4242 addr = 0;
4243
4244 trace_handle_mmio_page_fault(addr, gfn, access);
4245 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4246 return RET_PF_EMULATE;
4247 }
4248
4249 /*
4250 * If the page table is zapped by other cpus, let CPU fault again on
4251 * the address.
4252 */
4253 return RET_PF_RETRY;
4254 }
4255
page_fault_handle_page_track(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4256 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4257 struct kvm_page_fault *fault)
4258 {
4259 if (unlikely(fault->rsvd))
4260 return false;
4261
4262 if (!fault->present || !fault->write)
4263 return false;
4264
4265 /*
4266 * guest is writing the page which is write tracked which can
4267 * not be fixed by page fault handler.
4268 */
4269 if (kvm_gfn_is_write_tracked(vcpu->kvm, fault->slot, fault->gfn))
4270 return true;
4271
4272 return false;
4273 }
4274
shadow_page_table_clear_flood(struct kvm_vcpu * vcpu,gva_t addr)4275 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4276 {
4277 struct kvm_shadow_walk_iterator iterator;
4278 u64 spte;
4279
4280 walk_shadow_page_lockless_begin(vcpu);
4281 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4282 clear_sp_write_flooding_count(iterator.sptep);
4283 walk_shadow_page_lockless_end(vcpu);
4284 }
4285
alloc_apf_token(struct kvm_vcpu * vcpu)4286 static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
4287 {
4288 /* make sure the token value is not 0 */
4289 u32 id = vcpu->arch.apf.id;
4290
4291 if (id << 12 == 0)
4292 vcpu->arch.apf.id = 1;
4293
4294 return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4295 }
4296
kvm_arch_setup_async_pf(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4297 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu,
4298 struct kvm_page_fault *fault)
4299 {
4300 struct kvm_arch_async_pf arch;
4301
4302 arch.token = alloc_apf_token(vcpu);
4303 arch.gfn = fault->gfn;
4304 arch.error_code = fault->error_code;
4305 arch.direct_map = vcpu->arch.mmu->root_role.direct;
4306 arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4307
4308 return kvm_setup_async_pf(vcpu, fault->addr,
4309 kvm_vcpu_gfn_to_hva(vcpu, fault->gfn), &arch);
4310 }
4311
kvm_arch_async_page_ready(struct kvm_vcpu * vcpu,struct kvm_async_pf * work)4312 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
4313 {
4314 int r;
4315
4316 if (WARN_ON_ONCE(work->arch.error_code & PFERR_PRIVATE_ACCESS))
4317 return;
4318
4319 if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
4320 work->wakeup_all)
4321 return;
4322
4323 r = kvm_mmu_reload(vcpu);
4324 if (unlikely(r))
4325 return;
4326
4327 if (!vcpu->arch.mmu->root_role.direct &&
4328 work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
4329 return;
4330
4331 r = kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, work->arch.error_code,
4332 true, NULL, NULL);
4333
4334 /*
4335 * Account fixed page faults, otherwise they'll never be counted, but
4336 * ignore stats for all other return times. Page-ready "faults" aren't
4337 * truly spurious and never trigger emulation
4338 */
4339 if (r == RET_PF_FIXED)
4340 vcpu->stat.pf_fixed++;
4341 }
4342
kvm_max_level_for_order(int order)4343 static inline u8 kvm_max_level_for_order(int order)
4344 {
4345 BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
4346
4347 KVM_MMU_WARN_ON(order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G) &&
4348 order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M) &&
4349 order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_4K));
4350
4351 if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
4352 return PG_LEVEL_1G;
4353
4354 if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
4355 return PG_LEVEL_2M;
4356
4357 return PG_LEVEL_4K;
4358 }
4359
kvm_max_private_mapping_level(struct kvm * kvm,kvm_pfn_t pfn,u8 max_level,int gmem_order)4360 static u8 kvm_max_private_mapping_level(struct kvm *kvm, kvm_pfn_t pfn,
4361 u8 max_level, int gmem_order)
4362 {
4363 u8 req_max_level;
4364
4365 if (max_level == PG_LEVEL_4K)
4366 return PG_LEVEL_4K;
4367
4368 max_level = min(kvm_max_level_for_order(gmem_order), max_level);
4369 if (max_level == PG_LEVEL_4K)
4370 return PG_LEVEL_4K;
4371
4372 req_max_level = kvm_x86_call(private_max_mapping_level)(kvm, pfn);
4373 if (req_max_level)
4374 max_level = min(max_level, req_max_level);
4375
4376 return max_level;
4377 }
4378
kvm_faultin_pfn_private(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4379 static int kvm_faultin_pfn_private(struct kvm_vcpu *vcpu,
4380 struct kvm_page_fault *fault)
4381 {
4382 int max_order, r;
4383
4384 if (!kvm_slot_can_be_private(fault->slot)) {
4385 kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4386 return -EFAULT;
4387 }
4388
4389 r = kvm_gmem_get_pfn(vcpu->kvm, fault->slot, fault->gfn, &fault->pfn,
4390 &max_order);
4391 if (r) {
4392 kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4393 return r;
4394 }
4395
4396 fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
4397 fault->max_level = kvm_max_private_mapping_level(vcpu->kvm, fault->pfn,
4398 fault->max_level, max_order);
4399
4400 return RET_PF_CONTINUE;
4401 }
4402
__kvm_faultin_pfn(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4403 static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4404 {
4405 bool async;
4406
4407 if (fault->is_private)
4408 return kvm_faultin_pfn_private(vcpu, fault);
4409
4410 async = false;
4411 fault->pfn = __gfn_to_pfn_memslot(fault->slot, fault->gfn, false, false,
4412 &async, fault->write,
4413 &fault->map_writable, &fault->hva);
4414 if (!async)
4415 return RET_PF_CONTINUE; /* *pfn has correct page already */
4416
4417 if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
4418 trace_kvm_try_async_get_page(fault->addr, fault->gfn);
4419 if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
4420 trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4421 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4422 return RET_PF_RETRY;
4423 } else if (kvm_arch_setup_async_pf(vcpu, fault)) {
4424 return RET_PF_RETRY;
4425 }
4426 }
4427
4428 /*
4429 * Allow gup to bail on pending non-fatal signals when it's also allowed
4430 * to wait for IO. Note, gup always bails if it is unable to quickly
4431 * get a page and a fatal signal, i.e. SIGKILL, is pending.
4432 */
4433 fault->pfn = __gfn_to_pfn_memslot(fault->slot, fault->gfn, false, true,
4434 NULL, fault->write,
4435 &fault->map_writable, &fault->hva);
4436 return RET_PF_CONTINUE;
4437 }
4438
kvm_faultin_pfn(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault,unsigned int access)4439 static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4440 unsigned int access)
4441 {
4442 struct kvm_memory_slot *slot = fault->slot;
4443 int ret;
4444
4445 /*
4446 * Note that the mmu_invalidate_seq also serves to detect a concurrent
4447 * change in attributes. is_page_fault_stale() will detect an
4448 * invalidation relate to fault->fn and resume the guest without
4449 * installing a mapping in the page tables.
4450 */
4451 fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4452 smp_rmb();
4453
4454 /*
4455 * Now that we have a snapshot of mmu_invalidate_seq we can check for a
4456 * private vs. shared mismatch.
4457 */
4458 if (fault->is_private != kvm_mem_is_private(vcpu->kvm, fault->gfn)) {
4459 kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4460 return -EFAULT;
4461 }
4462
4463 if (unlikely(!slot))
4464 return kvm_handle_noslot_fault(vcpu, fault, access);
4465
4466 /*
4467 * Retry the page fault if the gfn hit a memslot that is being deleted
4468 * or moved. This ensures any existing SPTEs for the old memslot will
4469 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4470 */
4471 if (slot->flags & KVM_MEMSLOT_INVALID)
4472 return RET_PF_RETRY;
4473
4474 if (slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT) {
4475 /*
4476 * Don't map L1's APIC access page into L2, KVM doesn't support
4477 * using APICv/AVIC to accelerate L2 accesses to L1's APIC,
4478 * i.e. the access needs to be emulated. Emulating access to
4479 * L1's APIC is also correct if L1 is accelerating L2's own
4480 * virtual APIC, but for some reason L1 also maps _L1's_ APIC
4481 * into L2. Note, vcpu_is_mmio_gpa() always treats access to
4482 * the APIC as MMIO. Allow an MMIO SPTE to be created, as KVM
4483 * uses different roots for L1 vs. L2, i.e. there is no danger
4484 * of breaking APICv/AVIC for L1.
4485 */
4486 if (is_guest_mode(vcpu))
4487 return kvm_handle_noslot_fault(vcpu, fault, access);
4488
4489 /*
4490 * If the APIC access page exists but is disabled, go directly
4491 * to emulation without caching the MMIO access or creating a
4492 * MMIO SPTE. That way the cache doesn't need to be purged
4493 * when the AVIC is re-enabled.
4494 */
4495 if (!kvm_apicv_activated(vcpu->kvm))
4496 return RET_PF_EMULATE;
4497 }
4498
4499 /*
4500 * Check for a relevant mmu_notifier invalidation event before getting
4501 * the pfn from the primary MMU, and before acquiring mmu_lock.
4502 *
4503 * For mmu_lock, if there is an in-progress invalidation and the kernel
4504 * allows preemption, the invalidation task may drop mmu_lock and yield
4505 * in response to mmu_lock being contended, which is *very* counter-
4506 * productive as this vCPU can't actually make forward progress until
4507 * the invalidation completes.
4508 *
4509 * Retrying now can also avoid unnessary lock contention in the primary
4510 * MMU, as the primary MMU doesn't necessarily hold a single lock for
4511 * the duration of the invalidation, i.e. faulting in a conflicting pfn
4512 * can cause the invalidation to take longer by holding locks that are
4513 * needed to complete the invalidation.
4514 *
4515 * Do the pre-check even for non-preemtible kernels, i.e. even if KVM
4516 * will never yield mmu_lock in response to contention, as this vCPU is
4517 * *guaranteed* to need to retry, i.e. waiting until mmu_lock is held
4518 * to detect retry guarantees the worst case latency for the vCPU.
4519 */
4520 if (mmu_invalidate_retry_gfn_unsafe(vcpu->kvm, fault->mmu_seq, fault->gfn))
4521 return RET_PF_RETRY;
4522
4523 ret = __kvm_faultin_pfn(vcpu, fault);
4524 if (ret != RET_PF_CONTINUE)
4525 return ret;
4526
4527 if (unlikely(is_error_pfn(fault->pfn)))
4528 return kvm_handle_error_pfn(vcpu, fault);
4529
4530 if (WARN_ON_ONCE(!fault->slot || is_noslot_pfn(fault->pfn)))
4531 return kvm_handle_noslot_fault(vcpu, fault, access);
4532
4533 /*
4534 * Check again for a relevant mmu_notifier invalidation event purely to
4535 * avoid contending mmu_lock. Most invalidations will be detected by
4536 * the previous check, but checking is extremely cheap relative to the
4537 * overall cost of failing to detect the invalidation until after
4538 * mmu_lock is acquired.
4539 */
4540 if (mmu_invalidate_retry_gfn_unsafe(vcpu->kvm, fault->mmu_seq, fault->gfn)) {
4541 kvm_release_pfn_clean(fault->pfn);
4542 return RET_PF_RETRY;
4543 }
4544
4545 return RET_PF_CONTINUE;
4546 }
4547
4548 /*
4549 * Returns true if the page fault is stale and needs to be retried, i.e. if the
4550 * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4551 */
is_page_fault_stale(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4552 static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4553 struct kvm_page_fault *fault)
4554 {
4555 struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
4556
4557 /* Special roots, e.g. pae_root, are not backed by shadow pages. */
4558 if (sp && is_obsolete_sp(vcpu->kvm, sp))
4559 return true;
4560
4561 /*
4562 * Roots without an associated shadow page are considered invalid if
4563 * there is a pending request to free obsolete roots. The request is
4564 * only a hint that the current root _may_ be obsolete and needs to be
4565 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
4566 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
4567 * to reload even if no vCPU is actively using the root.
4568 */
4569 if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4570 return true;
4571
4572 /*
4573 * Check for a relevant mmu_notifier invalidation event one last time
4574 * now that mmu_lock is held, as the "unsafe" checks performed without
4575 * holding mmu_lock can get false negatives.
4576 */
4577 return fault->slot &&
4578 mmu_invalidate_retry_gfn(vcpu->kvm, fault->mmu_seq, fault->gfn);
4579 }
4580
direct_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4581 static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4582 {
4583 kvm_pfn_t orig_pfn;
4584 int r;
4585
4586 /* Dummy roots are used only for shadowing bad guest roots. */
4587 if (WARN_ON_ONCE(kvm_mmu_is_dummy_root(vcpu->arch.mmu->root.hpa)))
4588 return RET_PF_RETRY;
4589
4590 if (page_fault_handle_page_track(vcpu, fault))
4591 return RET_PF_WRITE_PROTECTED;
4592
4593 r = fast_page_fault(vcpu, fault);
4594 if (r != RET_PF_INVALID)
4595 return r;
4596
4597 r = mmu_topup_memory_caches(vcpu, false);
4598 if (r)
4599 return r;
4600
4601 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4602 if (r != RET_PF_CONTINUE)
4603 return r;
4604
4605 orig_pfn = fault->pfn;
4606
4607 r = RET_PF_RETRY;
4608 write_lock(&vcpu->kvm->mmu_lock);
4609
4610 if (is_page_fault_stale(vcpu, fault))
4611 goto out_unlock;
4612
4613 r = make_mmu_pages_available(vcpu);
4614 if (r)
4615 goto out_unlock;
4616
4617 r = direct_map(vcpu, fault);
4618
4619 out_unlock:
4620 write_unlock(&vcpu->kvm->mmu_lock);
4621 kvm_release_pfn_clean(orig_pfn);
4622 return r;
4623 }
4624
nonpaging_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4625 static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4626 struct kvm_page_fault *fault)
4627 {
4628 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4629 fault->max_level = PG_LEVEL_2M;
4630 return direct_page_fault(vcpu, fault);
4631 }
4632
kvm_handle_page_fault(struct kvm_vcpu * vcpu,u64 error_code,u64 fault_address,char * insn,int insn_len)4633 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4634 u64 fault_address, char *insn, int insn_len)
4635 {
4636 int r = 1;
4637 u32 flags = vcpu->arch.apf.host_apf_flags;
4638
4639 #ifndef CONFIG_X86_64
4640 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4641 if (WARN_ON_ONCE(fault_address >> 32))
4642 return -EFAULT;
4643 #endif
4644 /*
4645 * Legacy #PF exception only have a 32-bit error code. Simply drop the
4646 * upper bits as KVM doesn't use them for #PF (because they are never
4647 * set), and to ensure there are no collisions with KVM-defined bits.
4648 */
4649 if (WARN_ON_ONCE(error_code >> 32))
4650 error_code = lower_32_bits(error_code);
4651
4652 /*
4653 * Restrict KVM-defined flags to bits 63:32 so that it's impossible for
4654 * them to conflict with #PF error codes, which are limited to 32 bits.
4655 */
4656 BUILD_BUG_ON(lower_32_bits(PFERR_SYNTHETIC_MASK));
4657
4658 vcpu->arch.l1tf_flush_l1d = true;
4659 if (!flags) {
4660 trace_kvm_page_fault(vcpu, fault_address, error_code);
4661
4662 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4663 insn_len);
4664 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4665 vcpu->arch.apf.host_apf_flags = 0;
4666 local_irq_disable();
4667 kvm_async_pf_task_wait_schedule(fault_address);
4668 local_irq_enable();
4669 } else {
4670 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4671 }
4672
4673 return r;
4674 }
4675 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4676
4677 #ifdef CONFIG_X86_64
kvm_tdp_mmu_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4678 static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
4679 struct kvm_page_fault *fault)
4680 {
4681 kvm_pfn_t orig_pfn;
4682 int r;
4683
4684 if (page_fault_handle_page_track(vcpu, fault))
4685 return RET_PF_WRITE_PROTECTED;
4686
4687 r = fast_page_fault(vcpu, fault);
4688 if (r != RET_PF_INVALID)
4689 return r;
4690
4691 r = mmu_topup_memory_caches(vcpu, false);
4692 if (r)
4693 return r;
4694
4695 r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4696 if (r != RET_PF_CONTINUE)
4697 return r;
4698
4699 orig_pfn = fault->pfn;
4700
4701 r = RET_PF_RETRY;
4702 read_lock(&vcpu->kvm->mmu_lock);
4703
4704 if (is_page_fault_stale(vcpu, fault))
4705 goto out_unlock;
4706
4707 r = kvm_tdp_mmu_map(vcpu, fault);
4708
4709 out_unlock:
4710 read_unlock(&vcpu->kvm->mmu_lock);
4711 kvm_release_pfn_clean(orig_pfn);
4712 return r;
4713 }
4714 #endif
4715
kvm_mmu_may_ignore_guest_pat(void)4716 bool kvm_mmu_may_ignore_guest_pat(void)
4717 {
4718 /*
4719 * When EPT is enabled (shadow_memtype_mask is non-zero), and the VM
4720 * has non-coherent DMA (DMA doesn't snoop CPU caches), KVM's ABI is to
4721 * honor the memtype from the guest's PAT so that guest accesses to
4722 * memory that is DMA'd aren't cached against the guest's wishes. As a
4723 * result, KVM _may_ ignore guest PAT, whereas without non-coherent DMA,
4724 * KVM _always_ ignores guest PAT (when EPT is enabled).
4725 */
4726 return shadow_memtype_mask;
4727 }
4728
kvm_tdp_page_fault(struct kvm_vcpu * vcpu,struct kvm_page_fault * fault)4729 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4730 {
4731 #ifdef CONFIG_X86_64
4732 if (tdp_mmu_enabled)
4733 return kvm_tdp_mmu_page_fault(vcpu, fault);
4734 #endif
4735
4736 return direct_page_fault(vcpu, fault);
4737 }
4738
kvm_tdp_map_page(struct kvm_vcpu * vcpu,gpa_t gpa,u64 error_code,u8 * level)4739 static int kvm_tdp_map_page(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code,
4740 u8 *level)
4741 {
4742 int r;
4743
4744 /*
4745 * Restrict to TDP page fault, since that's the only case where the MMU
4746 * is indexed by GPA.
4747 */
4748 if (vcpu->arch.mmu->page_fault != kvm_tdp_page_fault)
4749 return -EOPNOTSUPP;
4750
4751 do {
4752 if (signal_pending(current))
4753 return -EINTR;
4754 cond_resched();
4755 r = kvm_mmu_do_page_fault(vcpu, gpa, error_code, true, NULL, level);
4756 } while (r == RET_PF_RETRY);
4757
4758 if (r < 0)
4759 return r;
4760
4761 switch (r) {
4762 case RET_PF_FIXED:
4763 case RET_PF_SPURIOUS:
4764 case RET_PF_WRITE_PROTECTED:
4765 return 0;
4766
4767 case RET_PF_EMULATE:
4768 return -ENOENT;
4769
4770 case RET_PF_RETRY:
4771 case RET_PF_CONTINUE:
4772 case RET_PF_INVALID:
4773 default:
4774 WARN_ONCE(1, "could not fix page fault during prefault");
4775 return -EIO;
4776 }
4777 }
4778
kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu * vcpu,struct kvm_pre_fault_memory * range)4779 long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
4780 struct kvm_pre_fault_memory *range)
4781 {
4782 u64 error_code = PFERR_GUEST_FINAL_MASK;
4783 u8 level = PG_LEVEL_4K;
4784 u64 end;
4785 int r;
4786
4787 if (!vcpu->kvm->arch.pre_fault_allowed)
4788 return -EOPNOTSUPP;
4789
4790 /*
4791 * reload is efficient when called repeatedly, so we can do it on
4792 * every iteration.
4793 */
4794 r = kvm_mmu_reload(vcpu);
4795 if (r)
4796 return r;
4797
4798 if (kvm_arch_has_private_mem(vcpu->kvm) &&
4799 kvm_mem_is_private(vcpu->kvm, gpa_to_gfn(range->gpa)))
4800 error_code |= PFERR_PRIVATE_ACCESS;
4801
4802 /*
4803 * Shadow paging uses GVA for kvm page fault, so restrict to
4804 * two-dimensional paging.
4805 */
4806 r = kvm_tdp_map_page(vcpu, range->gpa, error_code, &level);
4807 if (r < 0)
4808 return r;
4809
4810 /*
4811 * If the mapping that covers range->gpa can use a huge page, it
4812 * may start below it or end after range->gpa + range->size.
4813 */
4814 end = (range->gpa & KVM_HPAGE_MASK(level)) + KVM_HPAGE_SIZE(level);
4815 return min(range->size, end - range->gpa);
4816 }
4817
nonpaging_init_context(struct kvm_mmu * context)4818 static void nonpaging_init_context(struct kvm_mmu *context)
4819 {
4820 context->page_fault = nonpaging_page_fault;
4821 context->gva_to_gpa = nonpaging_gva_to_gpa;
4822 context->sync_spte = NULL;
4823 }
4824
is_root_usable(struct kvm_mmu_root_info * root,gpa_t pgd,union kvm_mmu_page_role role)4825 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4826 union kvm_mmu_page_role role)
4827 {
4828 struct kvm_mmu_page *sp;
4829
4830 if (!VALID_PAGE(root->hpa))
4831 return false;
4832
4833 if (!role.direct && pgd != root->pgd)
4834 return false;
4835
4836 sp = root_to_sp(root->hpa);
4837 if (WARN_ON_ONCE(!sp))
4838 return false;
4839
4840 return role.word == sp->role.word;
4841 }
4842
4843 /*
4844 * Find out if a previously cached root matching the new pgd/role is available,
4845 * and insert the current root as the MRU in the cache.
4846 * If a matching root is found, it is assigned to kvm_mmu->root and
4847 * true is returned.
4848 * If no match is found, kvm_mmu->root is left invalid, the LRU root is
4849 * evicted to make room for the current root, and false is returned.
4850 */
cached_root_find_and_keep_current(struct kvm * kvm,struct kvm_mmu * mmu,gpa_t new_pgd,union kvm_mmu_page_role new_role)4851 static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
4852 gpa_t new_pgd,
4853 union kvm_mmu_page_role new_role)
4854 {
4855 uint i;
4856
4857 if (is_root_usable(&mmu->root, new_pgd, new_role))
4858 return true;
4859
4860 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4861 /*
4862 * The swaps end up rotating the cache like this:
4863 * C 0 1 2 3 (on entry to the function)
4864 * 0 C 1 2 3
4865 * 1 C 0 2 3
4866 * 2 C 0 1 3
4867 * 3 C 0 1 2 (on exit from the loop)
4868 */
4869 swap(mmu->root, mmu->prev_roots[i]);
4870 if (is_root_usable(&mmu->root, new_pgd, new_role))
4871 return true;
4872 }
4873
4874 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4875 return false;
4876 }
4877
4878 /*
4879 * Find out if a previously cached root matching the new pgd/role is available.
4880 * On entry, mmu->root is invalid.
4881 * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
4882 * of the cache becomes invalid, and true is returned.
4883 * If no match is found, kvm_mmu->root is left invalid and false is returned.
4884 */
cached_root_find_without_current(struct kvm * kvm,struct kvm_mmu * mmu,gpa_t new_pgd,union kvm_mmu_page_role new_role)4885 static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
4886 gpa_t new_pgd,
4887 union kvm_mmu_page_role new_role)
4888 {
4889 uint i;
4890
4891 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4892 if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
4893 goto hit;
4894
4895 return false;
4896
4897 hit:
4898 swap(mmu->root, mmu->prev_roots[i]);
4899 /* Bubble up the remaining roots. */
4900 for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
4901 mmu->prev_roots[i] = mmu->prev_roots[i + 1];
4902 mmu->prev_roots[i].hpa = INVALID_PAGE;
4903 return true;
4904 }
4905
fast_pgd_switch(struct kvm * kvm,struct kvm_mmu * mmu,gpa_t new_pgd,union kvm_mmu_page_role new_role)4906 static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
4907 gpa_t new_pgd, union kvm_mmu_page_role new_role)
4908 {
4909 /*
4910 * Limit reuse to 64-bit hosts+VMs without "special" roots in order to
4911 * avoid having to deal with PDPTEs and other complexities.
4912 */
4913 if (VALID_PAGE(mmu->root.hpa) && !root_to_sp(mmu->root.hpa))
4914 kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4915
4916 if (VALID_PAGE(mmu->root.hpa))
4917 return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
4918 else
4919 return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4920 }
4921
kvm_mmu_new_pgd(struct kvm_vcpu * vcpu,gpa_t new_pgd)4922 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4923 {
4924 struct kvm_mmu *mmu = vcpu->arch.mmu;
4925 union kvm_mmu_page_role new_role = mmu->root_role;
4926
4927 /*
4928 * Return immediately if no usable root was found, kvm_mmu_reload()
4929 * will establish a valid root prior to the next VM-Enter.
4930 */
4931 if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4932 return;
4933
4934 /*
4935 * It's possible that the cached previous root page is obsolete because
4936 * of a change in the MMU generation number. However, changing the
4937 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4938 * which will free the root set here and allocate a new one.
4939 */
4940 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4941
4942 if (force_flush_and_sync_on_reuse) {
4943 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4944 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4945 }
4946
4947 /*
4948 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4949 * switching to a new CR3, that GVA->GPA mapping may no longer be
4950 * valid. So clear any cached MMIO info even when we don't need to sync
4951 * the shadow page tables.
4952 */
4953 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4954
4955 /*
4956 * If this is a direct root page, it doesn't have a write flooding
4957 * count. Otherwise, clear the write flooding count.
4958 */
4959 if (!new_role.direct) {
4960 struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
4961
4962 if (!WARN_ON_ONCE(!sp))
4963 __clear_sp_write_flooding_count(sp);
4964 }
4965 }
4966 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4967
sync_mmio_spte(struct kvm_vcpu * vcpu,u64 * sptep,gfn_t gfn,unsigned int access)4968 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4969 unsigned int access)
4970 {
4971 if (unlikely(is_mmio_spte(vcpu->kvm, *sptep))) {
4972 if (gfn != get_mmio_spte_gfn(*sptep)) {
4973 mmu_spte_clear_no_track(sptep);
4974 return true;
4975 }
4976
4977 mark_mmio_spte(vcpu, sptep, gfn, access);
4978 return true;
4979 }
4980
4981 return false;
4982 }
4983
4984 #define PTTYPE_EPT 18 /* arbitrary */
4985 #define PTTYPE PTTYPE_EPT
4986 #include "paging_tmpl.h"
4987 #undef PTTYPE
4988
4989 #define PTTYPE 64
4990 #include "paging_tmpl.h"
4991 #undef PTTYPE
4992
4993 #define PTTYPE 32
4994 #include "paging_tmpl.h"
4995 #undef PTTYPE
4996
__reset_rsvds_bits_mask(struct rsvd_bits_validate * rsvd_check,u64 pa_bits_rsvd,int level,bool nx,bool gbpages,bool pse,bool amd)4997 static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4998 u64 pa_bits_rsvd, int level, bool nx,
4999 bool gbpages, bool pse, bool amd)
5000 {
5001 u64 gbpages_bit_rsvd = 0;
5002 u64 nonleaf_bit8_rsvd = 0;
5003 u64 high_bits_rsvd;
5004
5005 rsvd_check->bad_mt_xwr = 0;
5006
5007 if (!gbpages)
5008 gbpages_bit_rsvd = rsvd_bits(7, 7);
5009
5010 if (level == PT32E_ROOT_LEVEL)
5011 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
5012 else
5013 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
5014
5015 /* Note, NX doesn't exist in PDPTEs, this is handled below. */
5016 if (!nx)
5017 high_bits_rsvd |= rsvd_bits(63, 63);
5018
5019 /*
5020 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
5021 * leaf entries) on AMD CPUs only.
5022 */
5023 if (amd)
5024 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
5025
5026 switch (level) {
5027 case PT32_ROOT_LEVEL:
5028 /* no rsvd bits for 2 level 4K page table entries */
5029 rsvd_check->rsvd_bits_mask[0][1] = 0;
5030 rsvd_check->rsvd_bits_mask[0][0] = 0;
5031 rsvd_check->rsvd_bits_mask[1][0] =
5032 rsvd_check->rsvd_bits_mask[0][0];
5033
5034 if (!pse) {
5035 rsvd_check->rsvd_bits_mask[1][1] = 0;
5036 break;
5037 }
5038
5039 if (is_cpuid_PSE36())
5040 /* 36bits PSE 4MB page */
5041 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
5042 else
5043 /* 32 bits PSE 4MB page */
5044 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
5045 break;
5046 case PT32E_ROOT_LEVEL:
5047 rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
5048 high_bits_rsvd |
5049 rsvd_bits(5, 8) |
5050 rsvd_bits(1, 2); /* PDPTE */
5051 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd; /* PDE */
5052 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd; /* PTE */
5053 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
5054 rsvd_bits(13, 20); /* large page */
5055 rsvd_check->rsvd_bits_mask[1][0] =
5056 rsvd_check->rsvd_bits_mask[0][0];
5057 break;
5058 case PT64_ROOT_5LEVEL:
5059 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
5060 nonleaf_bit8_rsvd |
5061 rsvd_bits(7, 7);
5062 rsvd_check->rsvd_bits_mask[1][4] =
5063 rsvd_check->rsvd_bits_mask[0][4];
5064 fallthrough;
5065 case PT64_ROOT_4LEVEL:
5066 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
5067 nonleaf_bit8_rsvd |
5068 rsvd_bits(7, 7);
5069 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
5070 gbpages_bit_rsvd;
5071 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
5072 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
5073 rsvd_check->rsvd_bits_mask[1][3] =
5074 rsvd_check->rsvd_bits_mask[0][3];
5075 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
5076 gbpages_bit_rsvd |
5077 rsvd_bits(13, 29);
5078 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
5079 rsvd_bits(13, 20); /* large page */
5080 rsvd_check->rsvd_bits_mask[1][0] =
5081 rsvd_check->rsvd_bits_mask[0][0];
5082 break;
5083 }
5084 }
5085
reset_guest_rsvds_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context)5086 static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
5087 struct kvm_mmu *context)
5088 {
5089 __reset_rsvds_bits_mask(&context->guest_rsvd_check,
5090 vcpu->arch.reserved_gpa_bits,
5091 context->cpu_role.base.level, is_efer_nx(context),
5092 guest_can_use(vcpu, X86_FEATURE_GBPAGES),
5093 is_cr4_pse(context),
5094 guest_cpuid_is_amd_compatible(vcpu));
5095 }
5096
__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate * rsvd_check,u64 pa_bits_rsvd,bool execonly,int huge_page_level)5097 static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
5098 u64 pa_bits_rsvd, bool execonly,
5099 int huge_page_level)
5100 {
5101 u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
5102 u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
5103 u64 bad_mt_xwr;
5104
5105 if (huge_page_level < PG_LEVEL_1G)
5106 large_1g_rsvd = rsvd_bits(7, 7);
5107 if (huge_page_level < PG_LEVEL_2M)
5108 large_2m_rsvd = rsvd_bits(7, 7);
5109
5110 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
5111 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
5112 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
5113 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
5114 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
5115
5116 /* large page */
5117 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
5118 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
5119 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
5120 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
5121 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
5122
5123 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
5124 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
5125 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
5126 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
5127 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
5128 if (!execonly) {
5129 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
5130 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
5131 }
5132 rsvd_check->bad_mt_xwr = bad_mt_xwr;
5133 }
5134
reset_rsvds_bits_mask_ept(struct kvm_vcpu * vcpu,struct kvm_mmu * context,bool execonly,int huge_page_level)5135 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
5136 struct kvm_mmu *context, bool execonly, int huge_page_level)
5137 {
5138 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
5139 vcpu->arch.reserved_gpa_bits, execonly,
5140 huge_page_level);
5141 }
5142
reserved_hpa_bits(void)5143 static inline u64 reserved_hpa_bits(void)
5144 {
5145 return rsvd_bits(kvm_host.maxphyaddr, 63);
5146 }
5147
5148 /*
5149 * the page table on host is the shadow page table for the page
5150 * table in guest or amd nested guest, its mmu features completely
5151 * follow the features in guest.
5152 */
reset_shadow_zero_bits_mask(struct kvm_vcpu * vcpu,struct kvm_mmu * context)5153 static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
5154 struct kvm_mmu *context)
5155 {
5156 /* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
5157 bool is_amd = true;
5158 /* KVM doesn't use 2-level page tables for the shadow MMU. */
5159 bool is_pse = false;
5160 struct rsvd_bits_validate *shadow_zero_check;
5161 int i;
5162
5163 WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
5164
5165 shadow_zero_check = &context->shadow_zero_check;
5166 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
5167 context->root_role.level,
5168 context->root_role.efer_nx,
5169 guest_can_use(vcpu, X86_FEATURE_GBPAGES),
5170 is_pse, is_amd);
5171
5172 if (!shadow_me_mask)
5173 return;
5174
5175 for (i = context->root_role.level; --i >= 0;) {
5176 /*
5177 * So far shadow_me_value is a constant during KVM's life
5178 * time. Bits in shadow_me_value are allowed to be set.
5179 * Bits in shadow_me_mask but not in shadow_me_value are
5180 * not allowed to be set.
5181 */
5182 shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
5183 shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
5184 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
5185 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
5186 }
5187
5188 }
5189
boot_cpu_is_amd(void)5190 static inline bool boot_cpu_is_amd(void)
5191 {
5192 WARN_ON_ONCE(!tdp_enabled);
5193 return shadow_x_mask == 0;
5194 }
5195
5196 /*
5197 * the direct page table on host, use as much mmu features as
5198 * possible, however, kvm currently does not do execution-protection.
5199 */
reset_tdp_shadow_zero_bits_mask(struct kvm_mmu * context)5200 static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
5201 {
5202 struct rsvd_bits_validate *shadow_zero_check;
5203 int i;
5204
5205 shadow_zero_check = &context->shadow_zero_check;
5206
5207 if (boot_cpu_is_amd())
5208 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
5209 context->root_role.level, true,
5210 boot_cpu_has(X86_FEATURE_GBPAGES),
5211 false, true);
5212 else
5213 __reset_rsvds_bits_mask_ept(shadow_zero_check,
5214 reserved_hpa_bits(), false,
5215 max_huge_page_level);
5216
5217 if (!shadow_me_mask)
5218 return;
5219
5220 for (i = context->root_role.level; --i >= 0;) {
5221 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
5222 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
5223 }
5224 }
5225
5226 /*
5227 * as the comments in reset_shadow_zero_bits_mask() except it
5228 * is the shadow page table for intel nested guest.
5229 */
5230 static void
reset_ept_shadow_zero_bits_mask(struct kvm_mmu * context,bool execonly)5231 reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
5232 {
5233 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
5234 reserved_hpa_bits(), execonly,
5235 max_huge_page_level);
5236 }
5237
5238 #define BYTE_MASK(access) \
5239 ((1 & (access) ? 2 : 0) | \
5240 (2 & (access) ? 4 : 0) | \
5241 (3 & (access) ? 8 : 0) | \
5242 (4 & (access) ? 16 : 0) | \
5243 (5 & (access) ? 32 : 0) | \
5244 (6 & (access) ? 64 : 0) | \
5245 (7 & (access) ? 128 : 0))
5246
5247
update_permission_bitmask(struct kvm_mmu * mmu,bool ept)5248 static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
5249 {
5250 unsigned byte;
5251
5252 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
5253 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
5254 const u8 u = BYTE_MASK(ACC_USER_MASK);
5255
5256 bool cr4_smep = is_cr4_smep(mmu);
5257 bool cr4_smap = is_cr4_smap(mmu);
5258 bool cr0_wp = is_cr0_wp(mmu);
5259 bool efer_nx = is_efer_nx(mmu);
5260
5261 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
5262 unsigned pfec = byte << 1;
5263
5264 /*
5265 * Each "*f" variable has a 1 bit for each UWX value
5266 * that causes a fault with the given PFEC.
5267 */
5268
5269 /* Faults from writes to non-writable pages */
5270 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5271 /* Faults from user mode accesses to supervisor pages */
5272 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5273 /* Faults from fetches of non-executable pages*/
5274 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5275 /* Faults from kernel mode fetches of user pages */
5276 u8 smepf = 0;
5277 /* Faults from kernel mode accesses of user pages */
5278 u8 smapf = 0;
5279
5280 if (!ept) {
5281 /* Faults from kernel mode accesses to user pages */
5282 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5283
5284 /* Not really needed: !nx will cause pte.nx to fault */
5285 if (!efer_nx)
5286 ff = 0;
5287
5288 /* Allow supervisor writes if !cr0.wp */
5289 if (!cr0_wp)
5290 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5291
5292 /* Disallow supervisor fetches of user code if cr4.smep */
5293 if (cr4_smep)
5294 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5295
5296 /*
5297 * SMAP:kernel-mode data accesses from user-mode
5298 * mappings should fault. A fault is considered
5299 * as a SMAP violation if all of the following
5300 * conditions are true:
5301 * - X86_CR4_SMAP is set in CR4
5302 * - A user page is accessed
5303 * - The access is not a fetch
5304 * - The access is supervisor mode
5305 * - If implicit supervisor access or X86_EFLAGS_AC is clear
5306 *
5307 * Here, we cover the first four conditions.
5308 * The fifth is computed dynamically in permission_fault();
5309 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5310 * *not* subject to SMAP restrictions.
5311 */
5312 if (cr4_smap)
5313 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5314 }
5315
5316 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5317 }
5318 }
5319
5320 /*
5321 * PKU is an additional mechanism by which the paging controls access to
5322 * user-mode addresses based on the value in the PKRU register. Protection
5323 * key violations are reported through a bit in the page fault error code.
5324 * Unlike other bits of the error code, the PK bit is not known at the
5325 * call site of e.g. gva_to_gpa; it must be computed directly in
5326 * permission_fault based on two bits of PKRU, on some machine state (CR4,
5327 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5328 *
5329 * In particular the following conditions come from the error code, the
5330 * page tables and the machine state:
5331 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5332 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5333 * - PK is always zero if U=0 in the page tables
5334 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5335 *
5336 * The PKRU bitmask caches the result of these four conditions. The error
5337 * code (minus the P bit) and the page table's U bit form an index into the
5338 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
5339 * with the two bits of the PKRU register corresponding to the protection key.
5340 * For the first three conditions above the bits will be 00, thus masking
5341 * away both AD and WD. For all reads or if the last condition holds, WD
5342 * only will be masked away.
5343 */
update_pkru_bitmask(struct kvm_mmu * mmu)5344 static void update_pkru_bitmask(struct kvm_mmu *mmu)
5345 {
5346 unsigned bit;
5347 bool wp;
5348
5349 mmu->pkru_mask = 0;
5350
5351 if (!is_cr4_pke(mmu))
5352 return;
5353
5354 wp = is_cr0_wp(mmu);
5355
5356 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5357 unsigned pfec, pkey_bits;
5358 bool check_pkey, check_write, ff, uf, wf, pte_user;
5359
5360 pfec = bit << 1;
5361 ff = pfec & PFERR_FETCH_MASK;
5362 uf = pfec & PFERR_USER_MASK;
5363 wf = pfec & PFERR_WRITE_MASK;
5364
5365 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
5366 pte_user = pfec & PFERR_RSVD_MASK;
5367
5368 /*
5369 * Only need to check the access which is not an
5370 * instruction fetch and is to a user page.
5371 */
5372 check_pkey = (!ff && pte_user);
5373 /*
5374 * write access is controlled by PKRU if it is a
5375 * user access or CR0.WP = 1.
5376 */
5377 check_write = check_pkey && wf && (uf || wp);
5378
5379 /* PKRU.AD stops both read and write access. */
5380 pkey_bits = !!check_pkey;
5381 /* PKRU.WD stops write access. */
5382 pkey_bits |= (!!check_write) << 1;
5383
5384 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5385 }
5386 }
5387
reset_guest_paging_metadata(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)5388 static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5389 struct kvm_mmu *mmu)
5390 {
5391 if (!is_cr0_pg(mmu))
5392 return;
5393
5394 reset_guest_rsvds_bits_mask(vcpu, mmu);
5395 update_permission_bitmask(mmu, false);
5396 update_pkru_bitmask(mmu);
5397 }
5398
paging64_init_context(struct kvm_mmu * context)5399 static void paging64_init_context(struct kvm_mmu *context)
5400 {
5401 context->page_fault = paging64_page_fault;
5402 context->gva_to_gpa = paging64_gva_to_gpa;
5403 context->sync_spte = paging64_sync_spte;
5404 }
5405
paging32_init_context(struct kvm_mmu * context)5406 static void paging32_init_context(struct kvm_mmu *context)
5407 {
5408 context->page_fault = paging32_page_fault;
5409 context->gva_to_gpa = paging32_gva_to_gpa;
5410 context->sync_spte = paging32_sync_spte;
5411 }
5412
kvm_calc_cpu_role(struct kvm_vcpu * vcpu,const struct kvm_mmu_role_regs * regs)5413 static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5414 const struct kvm_mmu_role_regs *regs)
5415 {
5416 union kvm_cpu_role role = {0};
5417
5418 role.base.access = ACC_ALL;
5419 role.base.smm = is_smm(vcpu);
5420 role.base.guest_mode = is_guest_mode(vcpu);
5421 role.ext.valid = 1;
5422
5423 if (!____is_cr0_pg(regs)) {
5424 role.base.direct = 1;
5425 return role;
5426 }
5427
5428 role.base.efer_nx = ____is_efer_nx(regs);
5429 role.base.cr0_wp = ____is_cr0_wp(regs);
5430 role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5431 role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5432 role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
5433
5434 if (____is_efer_lma(regs))
5435 role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
5436 : PT64_ROOT_4LEVEL;
5437 else if (____is_cr4_pae(regs))
5438 role.base.level = PT32E_ROOT_LEVEL;
5439 else
5440 role.base.level = PT32_ROOT_LEVEL;
5441
5442 role.ext.cr4_smep = ____is_cr4_smep(regs);
5443 role.ext.cr4_smap = ____is_cr4_smap(regs);
5444 role.ext.cr4_pse = ____is_cr4_pse(regs);
5445
5446 /* PKEY and LA57 are active iff long mode is active. */
5447 role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5448 role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5449 role.ext.efer_lma = ____is_efer_lma(regs);
5450 return role;
5451 }
5452
__kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)5453 void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5454 struct kvm_mmu *mmu)
5455 {
5456 const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5457
5458 BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5459 BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5460
5461 if (is_cr0_wp(mmu) == cr0_wp)
5462 return;
5463
5464 mmu->cpu_role.base.cr0_wp = cr0_wp;
5465 reset_guest_paging_metadata(vcpu, mmu);
5466 }
5467
kvm_mmu_get_tdp_level(struct kvm_vcpu * vcpu)5468 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5469 {
5470 /* tdp_root_level is architecture forced level, use it if nonzero */
5471 if (tdp_root_level)
5472 return tdp_root_level;
5473
5474 /* Use 5-level TDP if and only if it's useful/necessary. */
5475 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5476 return 4;
5477
5478 return max_tdp_level;
5479 }
5480
kvm_mmu_get_max_tdp_level(void)5481 u8 kvm_mmu_get_max_tdp_level(void)
5482 {
5483 return tdp_root_level ? tdp_root_level : max_tdp_level;
5484 }
5485
5486 static union kvm_mmu_page_role
kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5487 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
5488 union kvm_cpu_role cpu_role)
5489 {
5490 union kvm_mmu_page_role role = {0};
5491
5492 role.access = ACC_ALL;
5493 role.cr0_wp = true;
5494 role.efer_nx = true;
5495 role.smm = cpu_role.base.smm;
5496 role.guest_mode = cpu_role.base.guest_mode;
5497 role.ad_disabled = !kvm_ad_enabled();
5498 role.level = kvm_mmu_get_tdp_level(vcpu);
5499 role.direct = true;
5500 role.has_4_byte_gpte = false;
5501
5502 return role;
5503 }
5504
init_kvm_tdp_mmu(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5505 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5506 union kvm_cpu_role cpu_role)
5507 {
5508 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5509 union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5510
5511 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5512 root_role.word == context->root_role.word)
5513 return;
5514
5515 context->cpu_role.as_u64 = cpu_role.as_u64;
5516 context->root_role.word = root_role.word;
5517 context->page_fault = kvm_tdp_page_fault;
5518 context->sync_spte = NULL;
5519 context->get_guest_pgd = get_guest_cr3;
5520 context->get_pdptr = kvm_pdptr_read;
5521 context->inject_page_fault = kvm_inject_page_fault;
5522
5523 if (!is_cr0_pg(context))
5524 context->gva_to_gpa = nonpaging_gva_to_gpa;
5525 else if (is_cr4_pae(context))
5526 context->gva_to_gpa = paging64_gva_to_gpa;
5527 else
5528 context->gva_to_gpa = paging32_gva_to_gpa;
5529
5530 reset_guest_paging_metadata(vcpu, context);
5531 reset_tdp_shadow_zero_bits_mask(context);
5532 }
5533
shadow_mmu_init_context(struct kvm_vcpu * vcpu,struct kvm_mmu * context,union kvm_cpu_role cpu_role,union kvm_mmu_page_role root_role)5534 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
5535 union kvm_cpu_role cpu_role,
5536 union kvm_mmu_page_role root_role)
5537 {
5538 if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5539 root_role.word == context->root_role.word)
5540 return;
5541
5542 context->cpu_role.as_u64 = cpu_role.as_u64;
5543 context->root_role.word = root_role.word;
5544
5545 if (!is_cr0_pg(context))
5546 nonpaging_init_context(context);
5547 else if (is_cr4_pae(context))
5548 paging64_init_context(context);
5549 else
5550 paging32_init_context(context);
5551
5552 reset_guest_paging_metadata(vcpu, context);
5553 reset_shadow_zero_bits_mask(vcpu, context);
5554 }
5555
kvm_init_shadow_mmu(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5556 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5557 union kvm_cpu_role cpu_role)
5558 {
5559 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5560 union kvm_mmu_page_role root_role;
5561
5562 root_role = cpu_role.base;
5563
5564 /* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
5565 root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
5566
5567 /*
5568 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
5569 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
5570 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
5571 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
5572 * The iTLB multi-hit workaround can be toggled at any time, so assume
5573 * NX can be used by any non-nested shadow MMU to avoid having to reset
5574 * MMU contexts.
5575 */
5576 root_role.efer_nx = true;
5577
5578 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5579 }
5580
kvm_init_shadow_npt_mmu(struct kvm_vcpu * vcpu,unsigned long cr0,unsigned long cr4,u64 efer,gpa_t nested_cr3)5581 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5582 unsigned long cr4, u64 efer, gpa_t nested_cr3)
5583 {
5584 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5585 struct kvm_mmu_role_regs regs = {
5586 .cr0 = cr0,
5587 .cr4 = cr4 & ~X86_CR4_PKE,
5588 .efer = efer,
5589 };
5590 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5591 union kvm_mmu_page_role root_role;
5592
5593 /* NPT requires CR0.PG=1. */
5594 WARN_ON_ONCE(cpu_role.base.direct || !cpu_role.base.guest_mode);
5595
5596 root_role = cpu_role.base;
5597 root_role.level = kvm_mmu_get_tdp_level(vcpu);
5598 if (root_role.level == PT64_ROOT_5LEVEL &&
5599 cpu_role.base.level == PT64_ROOT_4LEVEL)
5600 root_role.passthrough = 1;
5601
5602 shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5603 kvm_mmu_new_pgd(vcpu, nested_cr3);
5604 }
5605 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5606
5607 static union kvm_cpu_role
kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu * vcpu,bool accessed_dirty,bool execonly,u8 level)5608 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5609 bool execonly, u8 level)
5610 {
5611 union kvm_cpu_role role = {0};
5612
5613 /*
5614 * KVM does not support SMM transfer monitors, and consequently does not
5615 * support the "entry to SMM" control either. role.base.smm is always 0.
5616 */
5617 WARN_ON_ONCE(is_smm(vcpu));
5618 role.base.level = level;
5619 role.base.has_4_byte_gpte = false;
5620 role.base.direct = false;
5621 role.base.ad_disabled = !accessed_dirty;
5622 role.base.guest_mode = true;
5623 role.base.access = ACC_ALL;
5624
5625 role.ext.word = 0;
5626 role.ext.execonly = execonly;
5627 role.ext.valid = 1;
5628
5629 return role;
5630 }
5631
kvm_init_shadow_ept_mmu(struct kvm_vcpu * vcpu,bool execonly,int huge_page_level,bool accessed_dirty,gpa_t new_eptp)5632 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5633 int huge_page_level, bool accessed_dirty,
5634 gpa_t new_eptp)
5635 {
5636 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5637 u8 level = vmx_eptp_page_walk_level(new_eptp);
5638 union kvm_cpu_role new_mode =
5639 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5640 execonly, level);
5641
5642 if (new_mode.as_u64 != context->cpu_role.as_u64) {
5643 /* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5644 context->cpu_role.as_u64 = new_mode.as_u64;
5645 context->root_role.word = new_mode.base.word;
5646
5647 context->page_fault = ept_page_fault;
5648 context->gva_to_gpa = ept_gva_to_gpa;
5649 context->sync_spte = ept_sync_spte;
5650
5651 update_permission_bitmask(context, true);
5652 context->pkru_mask = 0;
5653 reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5654 reset_ept_shadow_zero_bits_mask(context, execonly);
5655 }
5656
5657 kvm_mmu_new_pgd(vcpu, new_eptp);
5658 }
5659 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5660
init_kvm_softmmu(struct kvm_vcpu * vcpu,union kvm_cpu_role cpu_role)5661 static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5662 union kvm_cpu_role cpu_role)
5663 {
5664 struct kvm_mmu *context = &vcpu->arch.root_mmu;
5665
5666 kvm_init_shadow_mmu(vcpu, cpu_role);
5667
5668 context->get_guest_pgd = get_guest_cr3;
5669 context->get_pdptr = kvm_pdptr_read;
5670 context->inject_page_fault = kvm_inject_page_fault;
5671 }
5672
init_kvm_nested_mmu(struct kvm_vcpu * vcpu,union kvm_cpu_role new_mode)5673 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5674 union kvm_cpu_role new_mode)
5675 {
5676 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5677
5678 if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5679 return;
5680
5681 g_context->cpu_role.as_u64 = new_mode.as_u64;
5682 g_context->get_guest_pgd = get_guest_cr3;
5683 g_context->get_pdptr = kvm_pdptr_read;
5684 g_context->inject_page_fault = kvm_inject_page_fault;
5685
5686 /*
5687 * L2 page tables are never shadowed, so there is no need to sync
5688 * SPTEs.
5689 */
5690 g_context->sync_spte = NULL;
5691
5692 /*
5693 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5694 * L1's nested page tables (e.g. EPT12). The nested translation
5695 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5696 * L2's page tables as the first level of translation and L1's
5697 * nested page tables as the second level of translation. Basically
5698 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5699 */
5700 if (!is_paging(vcpu))
5701 g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5702 else if (is_long_mode(vcpu))
5703 g_context->gva_to_gpa = paging64_gva_to_gpa;
5704 else if (is_pae(vcpu))
5705 g_context->gva_to_gpa = paging64_gva_to_gpa;
5706 else
5707 g_context->gva_to_gpa = paging32_gva_to_gpa;
5708
5709 reset_guest_paging_metadata(vcpu, g_context);
5710 }
5711
kvm_init_mmu(struct kvm_vcpu * vcpu)5712 void kvm_init_mmu(struct kvm_vcpu *vcpu)
5713 {
5714 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5715 union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, ®s);
5716
5717 if (mmu_is_nested(vcpu))
5718 init_kvm_nested_mmu(vcpu, cpu_role);
5719 else if (tdp_enabled)
5720 init_kvm_tdp_mmu(vcpu, cpu_role);
5721 else
5722 init_kvm_softmmu(vcpu, cpu_role);
5723 }
5724 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5725
kvm_mmu_after_set_cpuid(struct kvm_vcpu * vcpu)5726 void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
5727 {
5728 /*
5729 * Invalidate all MMU roles to force them to reinitialize as CPUID
5730 * information is factored into reserved bit calculations.
5731 *
5732 * Correctly handling multiple vCPU models with respect to paging and
5733 * physical address properties) in a single VM would require tracking
5734 * all relevant CPUID information in kvm_mmu_page_role. That is very
5735 * undesirable as it would increase the memory requirements for
5736 * gfn_write_track (see struct kvm_mmu_page_role comments). For now
5737 * that problem is swept under the rug; KVM's CPUID API is horrific and
5738 * it's all but impossible to solve it without introducing a new API.
5739 */
5740 vcpu->arch.root_mmu.root_role.invalid = 1;
5741 vcpu->arch.guest_mmu.root_role.invalid = 1;
5742 vcpu->arch.nested_mmu.root_role.invalid = 1;
5743 vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5744 vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5745 vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
5746 kvm_mmu_reset_context(vcpu);
5747
5748 /*
5749 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5750 * kvm_arch_vcpu_ioctl().
5751 */
5752 KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
5753 }
5754
kvm_mmu_reset_context(struct kvm_vcpu * vcpu)5755 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5756 {
5757 kvm_mmu_unload(vcpu);
5758 kvm_init_mmu(vcpu);
5759 }
5760 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5761
kvm_mmu_load(struct kvm_vcpu * vcpu)5762 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5763 {
5764 int r;
5765
5766 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5767 if (r)
5768 goto out;
5769 r = mmu_alloc_special_roots(vcpu);
5770 if (r)
5771 goto out;
5772 if (vcpu->arch.mmu->root_role.direct)
5773 r = mmu_alloc_direct_roots(vcpu);
5774 else
5775 r = mmu_alloc_shadow_roots(vcpu);
5776 if (r)
5777 goto out;
5778
5779 kvm_mmu_sync_roots(vcpu);
5780
5781 kvm_mmu_load_pgd(vcpu);
5782
5783 /*
5784 * Flush any TLB entries for the new root, the provenance of the root
5785 * is unknown. Even if KVM ensures there are no stale TLB entries
5786 * for a freed root, in theory another hypervisor could have left
5787 * stale entries. Flushing on alloc also allows KVM to skip the TLB
5788 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5789 */
5790 kvm_x86_call(flush_tlb_current)(vcpu);
5791 out:
5792 return r;
5793 }
5794
kvm_mmu_unload(struct kvm_vcpu * vcpu)5795 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5796 {
5797 struct kvm *kvm = vcpu->kvm;
5798
5799 kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5800 WARN_ON_ONCE(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
5801 kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5802 WARN_ON_ONCE(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
5803 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5804 }
5805
is_obsolete_root(struct kvm * kvm,hpa_t root_hpa)5806 static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5807 {
5808 struct kvm_mmu_page *sp;
5809
5810 if (!VALID_PAGE(root_hpa))
5811 return false;
5812
5813 /*
5814 * When freeing obsolete roots, treat roots as obsolete if they don't
5815 * have an associated shadow page, as it's impossible to determine if
5816 * such roots are fresh or stale. This does mean KVM will get false
5817 * positives and free roots that don't strictly need to be freed, but
5818 * such false positives are relatively rare:
5819 *
5820 * (a) only PAE paging and nested NPT have roots without shadow pages
5821 * (or any shadow paging flavor with a dummy root, see note below)
5822 * (b) remote reloads due to a memslot update obsoletes _all_ roots
5823 * (c) KVM doesn't track previous roots for PAE paging, and the guest
5824 * is unlikely to zap an in-use PGD.
5825 *
5826 * Note! Dummy roots are unique in that they are obsoleted by memslot
5827 * _creation_! See also FNAME(fetch).
5828 */
5829 sp = root_to_sp(root_hpa);
5830 return !sp || is_obsolete_sp(kvm, sp);
5831 }
5832
__kvm_mmu_free_obsolete_roots(struct kvm * kvm,struct kvm_mmu * mmu)5833 static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5834 {
5835 unsigned long roots_to_free = 0;
5836 int i;
5837
5838 if (is_obsolete_root(kvm, mmu->root.hpa))
5839 roots_to_free |= KVM_MMU_ROOT_CURRENT;
5840
5841 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5842 if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5843 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5844 }
5845
5846 if (roots_to_free)
5847 kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5848 }
5849
kvm_mmu_free_obsolete_roots(struct kvm_vcpu * vcpu)5850 void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5851 {
5852 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5853 __kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5854 }
5855
mmu_pte_write_fetch_gpte(struct kvm_vcpu * vcpu,gpa_t * gpa,int * bytes)5856 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5857 int *bytes)
5858 {
5859 u64 gentry = 0;
5860 int r;
5861
5862 /*
5863 * Assume that the pte write on a page table of the same type
5864 * as the current vcpu paging mode since we update the sptes only
5865 * when they have the same mode.
5866 */
5867 if (is_pae(vcpu) && *bytes == 4) {
5868 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5869 *gpa &= ~(gpa_t)7;
5870 *bytes = 8;
5871 }
5872
5873 if (*bytes == 4 || *bytes == 8) {
5874 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5875 if (r)
5876 gentry = 0;
5877 }
5878
5879 return gentry;
5880 }
5881
5882 /*
5883 * If we're seeing too many writes to a page, it may no longer be a page table,
5884 * or we may be forking, in which case it is better to unmap the page.
5885 */
detect_write_flooding(struct kvm_mmu_page * sp)5886 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5887 {
5888 /*
5889 * Skip write-flooding detected for the sp whose level is 1, because
5890 * it can become unsync, then the guest page is not write-protected.
5891 */
5892 if (sp->role.level == PG_LEVEL_4K)
5893 return false;
5894
5895 atomic_inc(&sp->write_flooding_count);
5896 return atomic_read(&sp->write_flooding_count) >= 3;
5897 }
5898
5899 /*
5900 * Misaligned accesses are too much trouble to fix up; also, they usually
5901 * indicate a page is not used as a page table.
5902 */
detect_write_misaligned(struct kvm_mmu_page * sp,gpa_t gpa,int bytes)5903 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5904 int bytes)
5905 {
5906 unsigned offset, pte_size, misaligned;
5907
5908 offset = offset_in_page(gpa);
5909 pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5910
5911 /*
5912 * Sometimes, the OS only writes the last one bytes to update status
5913 * bits, for example, in linux, andb instruction is used in clear_bit().
5914 */
5915 if (!(offset & (pte_size - 1)) && bytes == 1)
5916 return false;
5917
5918 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5919 misaligned |= bytes < 4;
5920
5921 return misaligned;
5922 }
5923
get_written_sptes(struct kvm_mmu_page * sp,gpa_t gpa,int * nspte)5924 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5925 {
5926 unsigned page_offset, quadrant;
5927 u64 *spte;
5928 int level;
5929
5930 page_offset = offset_in_page(gpa);
5931 level = sp->role.level;
5932 *nspte = 1;
5933 if (sp->role.has_4_byte_gpte) {
5934 page_offset <<= 1; /* 32->64 */
5935 /*
5936 * A 32-bit pde maps 4MB while the shadow pdes map
5937 * only 2MB. So we need to double the offset again
5938 * and zap two pdes instead of one.
5939 */
5940 if (level == PT32_ROOT_LEVEL) {
5941 page_offset &= ~7; /* kill rounding error */
5942 page_offset <<= 1;
5943 *nspte = 2;
5944 }
5945 quadrant = page_offset >> PAGE_SHIFT;
5946 page_offset &= ~PAGE_MASK;
5947 if (quadrant != sp->role.quadrant)
5948 return NULL;
5949 }
5950
5951 spte = &sp->spt[page_offset / sizeof(*spte)];
5952 return spte;
5953 }
5954
kvm_mmu_track_write(struct kvm_vcpu * vcpu,gpa_t gpa,const u8 * new,int bytes)5955 void kvm_mmu_track_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new,
5956 int bytes)
5957 {
5958 gfn_t gfn = gpa >> PAGE_SHIFT;
5959 struct kvm_mmu_page *sp;
5960 LIST_HEAD(invalid_list);
5961 u64 entry, gentry, *spte;
5962 int npte;
5963 bool flush = false;
5964
5965 /*
5966 * When emulating guest writes, ensure the written value is visible to
5967 * any task that is handling page faults before checking whether or not
5968 * KVM is shadowing a guest PTE. This ensures either KVM will create
5969 * the correct SPTE in the page fault handler, or this task will see
5970 * a non-zero indirect_shadow_pages. Pairs with the smp_mb() in
5971 * account_shadowed().
5972 */
5973 smp_mb();
5974 if (!vcpu->kvm->arch.indirect_shadow_pages)
5975 return;
5976
5977 write_lock(&vcpu->kvm->mmu_lock);
5978
5979 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5980
5981 ++vcpu->kvm->stat.mmu_pte_write;
5982
5983 for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5984 if (detect_write_misaligned(sp, gpa, bytes) ||
5985 detect_write_flooding(sp)) {
5986 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5987 ++vcpu->kvm->stat.mmu_flooded;
5988 continue;
5989 }
5990
5991 spte = get_written_sptes(sp, gpa, &npte);
5992 if (!spte)
5993 continue;
5994
5995 while (npte--) {
5996 entry = *spte;
5997 mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5998 if (gentry && sp->role.level != PG_LEVEL_4K)
5999 ++vcpu->kvm->stat.mmu_pde_zapped;
6000 if (is_shadow_present_pte(entry))
6001 flush = true;
6002 ++spte;
6003 }
6004 }
6005 kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
6006 write_unlock(&vcpu->kvm->mmu_lock);
6007 }
6008
is_write_to_guest_page_table(u64 error_code)6009 static bool is_write_to_guest_page_table(u64 error_code)
6010 {
6011 const u64 mask = PFERR_GUEST_PAGE_MASK | PFERR_WRITE_MASK | PFERR_PRESENT_MASK;
6012
6013 return (error_code & mask) == mask;
6014 }
6015
kvm_mmu_write_protect_fault(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,u64 error_code,int * emulation_type)6016 static int kvm_mmu_write_protect_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
6017 u64 error_code, int *emulation_type)
6018 {
6019 bool direct = vcpu->arch.mmu->root_role.direct;
6020
6021 /*
6022 * Do not try to unprotect and retry if the vCPU re-faulted on the same
6023 * RIP with the same address that was previously unprotected, as doing
6024 * so will likely put the vCPU into an infinite. E.g. if the vCPU uses
6025 * a non-page-table modifying instruction on the PDE that points to the
6026 * instruction, then unprotecting the gfn will unmap the instruction's
6027 * code, i.e. make it impossible for the instruction to ever complete.
6028 */
6029 if (vcpu->arch.last_retry_eip == kvm_rip_read(vcpu) &&
6030 vcpu->arch.last_retry_addr == cr2_or_gpa)
6031 return RET_PF_EMULATE;
6032
6033 /*
6034 * Reset the unprotect+retry values that guard against infinite loops.
6035 * The values will be refreshed if KVM explicitly unprotects a gfn and
6036 * retries, in all other cases it's safe to retry in the future even if
6037 * the next page fault happens on the same RIP+address.
6038 */
6039 vcpu->arch.last_retry_eip = 0;
6040 vcpu->arch.last_retry_addr = 0;
6041
6042 /*
6043 * It should be impossible to reach this point with an MMIO cache hit,
6044 * as RET_PF_WRITE_PROTECTED is returned if and only if there's a valid,
6045 * writable memslot, and creating a memslot should invalidate the MMIO
6046 * cache by way of changing the memslot generation. WARN and disallow
6047 * retry if MMIO is detected, as retrying MMIO emulation is pointless
6048 * and could put the vCPU into an infinite loop because the processor
6049 * will keep faulting on the non-existent MMIO address.
6050 */
6051 if (WARN_ON_ONCE(mmio_info_in_cache(vcpu, cr2_or_gpa, direct)))
6052 return RET_PF_EMULATE;
6053
6054 /*
6055 * Before emulating the instruction, check to see if the access was due
6056 * to a read-only violation while the CPU was walking non-nested NPT
6057 * page tables, i.e. for a direct MMU, for _guest_ page tables in L1.
6058 * If L1 is sharing (a subset of) its page tables with L2, e.g. by
6059 * having nCR3 share lower level page tables with hCR3, then when KVM
6060 * (L0) write-protects the nested NPTs, i.e. npt12 entries, KVM is also
6061 * unknowingly write-protecting L1's guest page tables, which KVM isn't
6062 * shadowing.
6063 *
6064 * Because the CPU (by default) walks NPT page tables using a write
6065 * access (to ensure the CPU can do A/D updates), page walks in L1 can
6066 * trigger write faults for the above case even when L1 isn't modifying
6067 * PTEs. As a result, KVM will unnecessarily emulate (or at least, try
6068 * to emulate) an excessive number of L1 instructions; because L1's MMU
6069 * isn't shadowed by KVM, there is no need to write-protect L1's gPTEs
6070 * and thus no need to emulate in order to guarantee forward progress.
6071 *
6072 * Try to unprotect the gfn, i.e. zap any shadow pages, so that L1 can
6073 * proceed without triggering emulation. If one or more shadow pages
6074 * was zapped, skip emulation and resume L1 to let it natively execute
6075 * the instruction. If no shadow pages were zapped, then the write-
6076 * fault is due to something else entirely, i.e. KVM needs to emulate,
6077 * as resuming the guest will put it into an infinite loop.
6078 *
6079 * Note, this code also applies to Intel CPUs, even though it is *very*
6080 * unlikely that an L1 will share its page tables (IA32/PAE/paging64
6081 * format) with L2's page tables (EPT format).
6082 *
6083 * For indirect MMUs, i.e. if KVM is shadowing the current MMU, try to
6084 * unprotect the gfn and retry if an event is awaiting reinjection. If
6085 * KVM emulates multiple instructions before completing event injection,
6086 * the event could be delayed beyond what is architecturally allowed,
6087 * e.g. KVM could inject an IRQ after the TPR has been raised.
6088 */
6089 if (((direct && is_write_to_guest_page_table(error_code)) ||
6090 (!direct && kvm_event_needs_reinjection(vcpu))) &&
6091 kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa))
6092 return RET_PF_RETRY;
6093
6094 /*
6095 * The gfn is write-protected, but if KVM detects its emulating an
6096 * instruction that is unlikely to be used to modify page tables, or if
6097 * emulation fails, KVM can try to unprotect the gfn and let the CPU
6098 * re-execute the instruction that caused the page fault. Do not allow
6099 * retrying an instruction from a nested guest as KVM is only explicitly
6100 * shadowing L1's page tables, i.e. unprotecting something for L1 isn't
6101 * going to magically fix whatever issue caused L2 to fail.
6102 */
6103 if (!is_guest_mode(vcpu))
6104 *emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
6105
6106 return RET_PF_EMULATE;
6107 }
6108
kvm_mmu_page_fault(struct kvm_vcpu * vcpu,gpa_t cr2_or_gpa,u64 error_code,void * insn,int insn_len)6109 int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
6110 void *insn, int insn_len)
6111 {
6112 int r, emulation_type = EMULTYPE_PF;
6113 bool direct = vcpu->arch.mmu->root_role.direct;
6114
6115 if (WARN_ON_ONCE(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
6116 return RET_PF_RETRY;
6117
6118 /*
6119 * Except for reserved faults (emulated MMIO is shared-only), set the
6120 * PFERR_PRIVATE_ACCESS flag for software-protected VMs based on the gfn's
6121 * current attributes, which are the source of truth for such VMs. Note,
6122 * this wrong for nested MMUs as the GPA is an L2 GPA, but KVM doesn't
6123 * currently supported nested virtualization (among many other things)
6124 * for software-protected VMs.
6125 */
6126 if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) &&
6127 !(error_code & PFERR_RSVD_MASK) &&
6128 vcpu->kvm->arch.vm_type == KVM_X86_SW_PROTECTED_VM &&
6129 kvm_mem_is_private(vcpu->kvm, gpa_to_gfn(cr2_or_gpa)))
6130 error_code |= PFERR_PRIVATE_ACCESS;
6131
6132 r = RET_PF_INVALID;
6133 if (unlikely(error_code & PFERR_RSVD_MASK)) {
6134 if (WARN_ON_ONCE(error_code & PFERR_PRIVATE_ACCESS))
6135 return -EFAULT;
6136
6137 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
6138 if (r == RET_PF_EMULATE)
6139 goto emulate;
6140 }
6141
6142 if (r == RET_PF_INVALID) {
6143 vcpu->stat.pf_taken++;
6144
6145 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa, error_code, false,
6146 &emulation_type, NULL);
6147 if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
6148 return -EIO;
6149 }
6150
6151 if (r < 0)
6152 return r;
6153
6154 if (r == RET_PF_WRITE_PROTECTED)
6155 r = kvm_mmu_write_protect_fault(vcpu, cr2_or_gpa, error_code,
6156 &emulation_type);
6157
6158 if (r == RET_PF_FIXED)
6159 vcpu->stat.pf_fixed++;
6160 else if (r == RET_PF_EMULATE)
6161 vcpu->stat.pf_emulate++;
6162 else if (r == RET_PF_SPURIOUS)
6163 vcpu->stat.pf_spurious++;
6164
6165 if (r != RET_PF_EMULATE)
6166 return 1;
6167
6168 emulate:
6169 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
6170 insn_len);
6171 }
6172 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
6173
kvm_mmu_print_sptes(struct kvm_vcpu * vcpu,gpa_t gpa,const char * msg)6174 void kvm_mmu_print_sptes(struct kvm_vcpu *vcpu, gpa_t gpa, const char *msg)
6175 {
6176 u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
6177 int root_level, leaf, level;
6178
6179 leaf = get_sptes_lockless(vcpu, gpa, sptes, &root_level);
6180 if (unlikely(leaf < 0))
6181 return;
6182
6183 pr_err("%s %llx", msg, gpa);
6184 for (level = root_level; level >= leaf; level--)
6185 pr_cont(", spte[%d] = 0x%llx", level, sptes[level]);
6186 pr_cont("\n");
6187 }
6188 EXPORT_SYMBOL_GPL(kvm_mmu_print_sptes);
6189
__kvm_mmu_invalidate_addr(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,u64 addr,hpa_t root_hpa)6190 static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
6191 u64 addr, hpa_t root_hpa)
6192 {
6193 struct kvm_shadow_walk_iterator iterator;
6194
6195 vcpu_clear_mmio_info(vcpu, addr);
6196
6197 /*
6198 * Walking and synchronizing SPTEs both assume they are operating in
6199 * the context of the current MMU, and would need to be reworked if
6200 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
6201 */
6202 if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
6203 return;
6204
6205 if (!VALID_PAGE(root_hpa))
6206 return;
6207
6208 write_lock(&vcpu->kvm->mmu_lock);
6209 for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
6210 struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
6211
6212 if (sp->unsync) {
6213 int ret = kvm_sync_spte(vcpu, sp, iterator.index);
6214
6215 if (ret < 0)
6216 mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
6217 if (ret)
6218 kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
6219 }
6220
6221 if (!sp->unsync_children)
6222 break;
6223 }
6224 write_unlock(&vcpu->kvm->mmu_lock);
6225 }
6226
kvm_mmu_invalidate_addr(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu,u64 addr,unsigned long roots)6227 void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
6228 u64 addr, unsigned long roots)
6229 {
6230 int i;
6231
6232 WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
6233
6234 /* It's actually a GPA for vcpu->arch.guest_mmu. */
6235 if (mmu != &vcpu->arch.guest_mmu) {
6236 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
6237 if (is_noncanonical_invlpg_address(addr, vcpu))
6238 return;
6239
6240 kvm_x86_call(flush_tlb_gva)(vcpu, addr);
6241 }
6242
6243 if (!mmu->sync_spte)
6244 return;
6245
6246 if (roots & KVM_MMU_ROOT_CURRENT)
6247 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
6248
6249 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6250 if (roots & KVM_MMU_ROOT_PREVIOUS(i))
6251 __kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
6252 }
6253 }
6254 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
6255
kvm_mmu_invlpg(struct kvm_vcpu * vcpu,gva_t gva)6256 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
6257 {
6258 /*
6259 * INVLPG is required to invalidate any global mappings for the VA,
6260 * irrespective of PCID. Blindly sync all roots as it would take
6261 * roughly the same amount of work/time to determine whether any of the
6262 * previous roots have a global mapping.
6263 *
6264 * Mappings not reachable via the current or previous cached roots will
6265 * be synced when switching to that new cr3, so nothing needs to be
6266 * done here for them.
6267 */
6268 kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
6269 ++vcpu->stat.invlpg;
6270 }
6271 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
6272
6273
kvm_mmu_invpcid_gva(struct kvm_vcpu * vcpu,gva_t gva,unsigned long pcid)6274 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
6275 {
6276 struct kvm_mmu *mmu = vcpu->arch.mmu;
6277 unsigned long roots = 0;
6278 uint i;
6279
6280 if (pcid == kvm_get_active_pcid(vcpu))
6281 roots |= KVM_MMU_ROOT_CURRENT;
6282
6283 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6284 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
6285 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
6286 roots |= KVM_MMU_ROOT_PREVIOUS(i);
6287 }
6288
6289 if (roots)
6290 kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
6291 ++vcpu->stat.invlpg;
6292
6293 /*
6294 * Mappings not reachable via the current cr3 or the prev_roots will be
6295 * synced when switching to that cr3, so nothing needs to be done here
6296 * for them.
6297 */
6298 }
6299
kvm_configure_mmu(bool enable_tdp,int tdp_forced_root_level,int tdp_max_root_level,int tdp_huge_page_level)6300 void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
6301 int tdp_max_root_level, int tdp_huge_page_level)
6302 {
6303 tdp_enabled = enable_tdp;
6304 tdp_root_level = tdp_forced_root_level;
6305 max_tdp_level = tdp_max_root_level;
6306
6307 #ifdef CONFIG_X86_64
6308 tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
6309 #endif
6310 /*
6311 * max_huge_page_level reflects KVM's MMU capabilities irrespective
6312 * of kernel support, e.g. KVM may be capable of using 1GB pages when
6313 * the kernel is not. But, KVM never creates a page size greater than
6314 * what is used by the kernel for any given HVA, i.e. the kernel's
6315 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
6316 */
6317 if (tdp_enabled)
6318 max_huge_page_level = tdp_huge_page_level;
6319 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
6320 max_huge_page_level = PG_LEVEL_1G;
6321 else
6322 max_huge_page_level = PG_LEVEL_2M;
6323 }
6324 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
6325
free_mmu_pages(struct kvm_mmu * mmu)6326 static void free_mmu_pages(struct kvm_mmu *mmu)
6327 {
6328 if (!tdp_enabled && mmu->pae_root)
6329 set_memory_encrypted((unsigned long)mmu->pae_root, 1);
6330 free_page((unsigned long)mmu->pae_root);
6331 free_page((unsigned long)mmu->pml4_root);
6332 free_page((unsigned long)mmu->pml5_root);
6333 }
6334
__kvm_mmu_create(struct kvm_vcpu * vcpu,struct kvm_mmu * mmu)6335 static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6336 {
6337 struct page *page;
6338 int i;
6339
6340 mmu->root.hpa = INVALID_PAGE;
6341 mmu->root.pgd = 0;
6342 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
6343 mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
6344
6345 /* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
6346 if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
6347 return 0;
6348
6349 /*
6350 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
6351 * while the PDP table is a per-vCPU construct that's allocated at MMU
6352 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
6353 * x86_64. Therefore we need to allocate the PDP table in the first
6354 * 4GB of memory, which happens to fit the DMA32 zone. TDP paging
6355 * generally doesn't use PAE paging and can skip allocating the PDP
6356 * table. The main exception, handled here, is SVM's 32-bit NPT. The
6357 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
6358 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6359 */
6360 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6361 return 0;
6362
6363 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6364 if (!page)
6365 return -ENOMEM;
6366
6367 mmu->pae_root = page_address(page);
6368
6369 /*
6370 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
6371 * get the CPU to treat the PDPTEs as encrypted. Decrypt the page so
6372 * that KVM's writes and the CPU's reads get along. Note, this is
6373 * only necessary when using shadow paging, as 64-bit NPT can get at
6374 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
6375 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
6376 */
6377 if (!tdp_enabled)
6378 set_memory_decrypted((unsigned long)mmu->pae_root, 1);
6379 else
6380 WARN_ON_ONCE(shadow_me_value);
6381
6382 for (i = 0; i < 4; ++i)
6383 mmu->pae_root[i] = INVALID_PAE_ROOT;
6384
6385 return 0;
6386 }
6387
kvm_mmu_create(struct kvm_vcpu * vcpu)6388 int kvm_mmu_create(struct kvm_vcpu *vcpu)
6389 {
6390 int ret;
6391
6392 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
6393 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
6394
6395 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
6396 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
6397
6398 vcpu->arch.mmu_shadow_page_cache.init_value =
6399 SHADOW_NONPRESENT_VALUE;
6400 if (!vcpu->arch.mmu_shadow_page_cache.init_value)
6401 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
6402
6403 vcpu->arch.mmu = &vcpu->arch.root_mmu;
6404 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6405
6406 ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6407 if (ret)
6408 return ret;
6409
6410 ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6411 if (ret)
6412 goto fail_allocate_root;
6413
6414 return ret;
6415 fail_allocate_root:
6416 free_mmu_pages(&vcpu->arch.guest_mmu);
6417 return ret;
6418 }
6419
6420 #define BATCH_ZAP_PAGES 10
kvm_zap_obsolete_pages(struct kvm * kvm)6421 static void kvm_zap_obsolete_pages(struct kvm *kvm)
6422 {
6423 struct kvm_mmu_page *sp, *node;
6424 int nr_zapped, batch = 0;
6425 bool unstable;
6426
6427 restart:
6428 list_for_each_entry_safe_reverse(sp, node,
6429 &kvm->arch.active_mmu_pages, link) {
6430 /*
6431 * No obsolete valid page exists before a newly created page
6432 * since active_mmu_pages is a FIFO list.
6433 */
6434 if (!is_obsolete_sp(kvm, sp))
6435 break;
6436
6437 /*
6438 * Invalid pages should never land back on the list of active
6439 * pages. Skip the bogus page, otherwise we'll get stuck in an
6440 * infinite loop if the page gets put back on the list (again).
6441 */
6442 if (WARN_ON_ONCE(sp->role.invalid))
6443 continue;
6444
6445 /*
6446 * No need to flush the TLB since we're only zapping shadow
6447 * pages with an obsolete generation number and all vCPUS have
6448 * loaded a new root, i.e. the shadow pages being zapped cannot
6449 * be in active use by the guest.
6450 */
6451 if (batch >= BATCH_ZAP_PAGES &&
6452 cond_resched_rwlock_write(&kvm->mmu_lock)) {
6453 batch = 0;
6454 goto restart;
6455 }
6456
6457 unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6458 &kvm->arch.zapped_obsolete_pages, &nr_zapped);
6459 batch += nr_zapped;
6460
6461 if (unstable)
6462 goto restart;
6463 }
6464
6465 /*
6466 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
6467 * to ensure KVM is not in the middle of a lockless shadow page table
6468 * walk, which may reference the pages. The remote TLB flush itself is
6469 * not required and is simply a convenient way to kick vCPUs as needed.
6470 * KVM performs a local TLB flush when allocating a new root (see
6471 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
6472 * running with an obsolete MMU.
6473 */
6474 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6475 }
6476
6477 /*
6478 * Fast invalidate all shadow pages and use lock-break technique
6479 * to zap obsolete pages.
6480 *
6481 * It's required when memslot is being deleted or VM is being
6482 * destroyed, in these cases, we should ensure that KVM MMU does
6483 * not use any resource of the being-deleted slot or all slots
6484 * after calling the function.
6485 */
kvm_mmu_zap_all_fast(struct kvm * kvm)6486 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6487 {
6488 lockdep_assert_held(&kvm->slots_lock);
6489
6490 write_lock(&kvm->mmu_lock);
6491 trace_kvm_mmu_zap_all_fast(kvm);
6492
6493 /*
6494 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
6495 * held for the entire duration of zapping obsolete pages, it's
6496 * impossible for there to be multiple invalid generations associated
6497 * with *valid* shadow pages at any given time, i.e. there is exactly
6498 * one valid generation and (at most) one invalid generation.
6499 */
6500 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6501
6502 /*
6503 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
6504 * invalidating TDP MMU roots must be done while holding mmu_lock for
6505 * write and in the same critical section as making the reload request,
6506 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6507 */
6508 if (tdp_mmu_enabled)
6509 kvm_tdp_mmu_invalidate_all_roots(kvm);
6510
6511 /*
6512 * Notify all vcpus to reload its shadow page table and flush TLB.
6513 * Then all vcpus will switch to new shadow page table with the new
6514 * mmu_valid_gen.
6515 *
6516 * Note: we need to do this under the protection of mmu_lock,
6517 * otherwise, vcpu would purge shadow page but miss tlb flush.
6518 */
6519 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6520
6521 kvm_zap_obsolete_pages(kvm);
6522
6523 write_unlock(&kvm->mmu_lock);
6524
6525 /*
6526 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6527 * returning to the caller, e.g. if the zap is in response to a memslot
6528 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6529 * associated with the deleted memslot once the update completes, and
6530 * Deferring the zap until the final reference to the root is put would
6531 * lead to use-after-free.
6532 */
6533 if (tdp_mmu_enabled)
6534 kvm_tdp_mmu_zap_invalidated_roots(kvm);
6535 }
6536
kvm_has_zapped_obsolete_pages(struct kvm * kvm)6537 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6538 {
6539 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6540 }
6541
kvm_mmu_init_vm(struct kvm * kvm)6542 void kvm_mmu_init_vm(struct kvm *kvm)
6543 {
6544 kvm->arch.shadow_mmio_value = shadow_mmio_value;
6545 INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6546 INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
6547 INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6548 spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6549
6550 if (tdp_mmu_enabled)
6551 kvm_mmu_init_tdp_mmu(kvm);
6552
6553 kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6554 kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6555
6556 kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6557
6558 kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6559 kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6560 }
6561
mmu_free_vm_memory_caches(struct kvm * kvm)6562 static void mmu_free_vm_memory_caches(struct kvm *kvm)
6563 {
6564 kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6565 kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6566 kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6567 }
6568
kvm_mmu_uninit_vm(struct kvm * kvm)6569 void kvm_mmu_uninit_vm(struct kvm *kvm)
6570 {
6571 if (tdp_mmu_enabled)
6572 kvm_mmu_uninit_tdp_mmu(kvm);
6573
6574 mmu_free_vm_memory_caches(kvm);
6575 }
6576
kvm_rmap_zap_gfn_range(struct kvm * kvm,gfn_t gfn_start,gfn_t gfn_end)6577 static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6578 {
6579 const struct kvm_memory_slot *memslot;
6580 struct kvm_memslots *slots;
6581 struct kvm_memslot_iter iter;
6582 bool flush = false;
6583 gfn_t start, end;
6584 int i;
6585
6586 if (!kvm_memslots_have_rmaps(kvm))
6587 return flush;
6588
6589 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
6590 slots = __kvm_memslots(kvm, i);
6591
6592 kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6593 memslot = iter.slot;
6594 start = max(gfn_start, memslot->base_gfn);
6595 end = min(gfn_end, memslot->base_gfn + memslot->npages);
6596 if (WARN_ON_ONCE(start >= end))
6597 continue;
6598
6599 flush = __kvm_rmap_zap_gfn_range(kvm, memslot, start,
6600 end, true, flush);
6601 }
6602 }
6603
6604 return flush;
6605 }
6606
6607 /*
6608 * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
6609 * (not including it)
6610 */
kvm_zap_gfn_range(struct kvm * kvm,gfn_t gfn_start,gfn_t gfn_end)6611 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6612 {
6613 bool flush;
6614
6615 if (WARN_ON_ONCE(gfn_end <= gfn_start))
6616 return;
6617
6618 write_lock(&kvm->mmu_lock);
6619
6620 kvm_mmu_invalidate_begin(kvm);
6621
6622 kvm_mmu_invalidate_range_add(kvm, gfn_start, gfn_end);
6623
6624 flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
6625
6626 if (tdp_mmu_enabled)
6627 flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
6628
6629 if (flush)
6630 kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
6631
6632 kvm_mmu_invalidate_end(kvm);
6633
6634 write_unlock(&kvm->mmu_lock);
6635 }
6636
slot_rmap_write_protect(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)6637 static bool slot_rmap_write_protect(struct kvm *kvm,
6638 struct kvm_rmap_head *rmap_head,
6639 const struct kvm_memory_slot *slot)
6640 {
6641 return rmap_write_protect(rmap_head, false);
6642 }
6643
kvm_mmu_slot_remove_write_access(struct kvm * kvm,const struct kvm_memory_slot * memslot,int start_level)6644 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6645 const struct kvm_memory_slot *memslot,
6646 int start_level)
6647 {
6648 if (kvm_memslots_have_rmaps(kvm)) {
6649 write_lock(&kvm->mmu_lock);
6650 walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6651 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6652 write_unlock(&kvm->mmu_lock);
6653 }
6654
6655 if (tdp_mmu_enabled) {
6656 read_lock(&kvm->mmu_lock);
6657 kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
6658 read_unlock(&kvm->mmu_lock);
6659 }
6660 }
6661
need_topup(struct kvm_mmu_memory_cache * cache,int min)6662 static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6663 {
6664 return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6665 }
6666
need_topup_split_caches_or_resched(struct kvm * kvm)6667 static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6668 {
6669 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6670 return true;
6671
6672 /*
6673 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6674 * to split a single huge page. Calculating how many are actually needed
6675 * is possible but not worth the complexity.
6676 */
6677 return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6678 need_topup(&kvm->arch.split_page_header_cache, 1) ||
6679 need_topup(&kvm->arch.split_shadow_page_cache, 1);
6680 }
6681
topup_split_caches(struct kvm * kvm)6682 static int topup_split_caches(struct kvm *kvm)
6683 {
6684 /*
6685 * Allocating rmap list entries when splitting huge pages for nested
6686 * MMUs is uncommon as KVM needs to use a list if and only if there is
6687 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6688 * aliased by multiple L2 gfns and/or from multiple nested roots with
6689 * different roles. Aliasing gfns when using TDP is atypical for VMMs;
6690 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6691 * but aliasing rarely occurs post-boot or for many gfns. If there is
6692 * only one rmap entry, rmap->val points directly at that one entry and
6693 * doesn't need to allocate a list. Buffer the cache by the default
6694 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6695 * encounters an aliased gfn or two.
6696 */
6697 const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6698 KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6699 int r;
6700
6701 lockdep_assert_held(&kvm->slots_lock);
6702
6703 r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6704 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6705 if (r)
6706 return r;
6707
6708 r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6709 if (r)
6710 return r;
6711
6712 return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6713 }
6714
shadow_mmu_get_sp_for_split(struct kvm * kvm,u64 * huge_sptep)6715 static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6716 {
6717 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6718 struct shadow_page_caches caches = {};
6719 union kvm_mmu_page_role role;
6720 unsigned int access;
6721 gfn_t gfn;
6722
6723 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6724 access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6725
6726 /*
6727 * Note, huge page splitting always uses direct shadow pages, regardless
6728 * of whether the huge page itself is mapped by a direct or indirect
6729 * shadow page, since the huge page region itself is being directly
6730 * mapped with smaller pages.
6731 */
6732 role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6733
6734 /* Direct SPs do not require a shadowed_info_cache. */
6735 caches.page_header_cache = &kvm->arch.split_page_header_cache;
6736 caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6737
6738 /* Safe to pass NULL for vCPU since requesting a direct SP. */
6739 return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6740 }
6741
shadow_mmu_split_huge_page(struct kvm * kvm,const struct kvm_memory_slot * slot,u64 * huge_sptep)6742 static void shadow_mmu_split_huge_page(struct kvm *kvm,
6743 const struct kvm_memory_slot *slot,
6744 u64 *huge_sptep)
6745
6746 {
6747 struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6748 u64 huge_spte = READ_ONCE(*huge_sptep);
6749 struct kvm_mmu_page *sp;
6750 bool flush = false;
6751 u64 *sptep, spte;
6752 gfn_t gfn;
6753 int index;
6754
6755 sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6756
6757 for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6758 sptep = &sp->spt[index];
6759 gfn = kvm_mmu_page_get_gfn(sp, index);
6760
6761 /*
6762 * The SP may already have populated SPTEs, e.g. if this huge
6763 * page is aliased by multiple sptes with the same access
6764 * permissions. These entries are guaranteed to map the same
6765 * gfn-to-pfn translation since the SP is direct, so no need to
6766 * modify them.
6767 *
6768 * However, if a given SPTE points to a lower level page table,
6769 * that lower level page table may only be partially populated.
6770 * Installing such SPTEs would effectively unmap a potion of the
6771 * huge page. Unmapping guest memory always requires a TLB flush
6772 * since a subsequent operation on the unmapped regions would
6773 * fail to detect the need to flush.
6774 */
6775 if (is_shadow_present_pte(*sptep)) {
6776 flush |= !is_last_spte(*sptep, sp->role.level);
6777 continue;
6778 }
6779
6780 spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6781 mmu_spte_set(sptep, spte);
6782 __rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6783 }
6784
6785 __link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6786 }
6787
shadow_mmu_try_split_huge_page(struct kvm * kvm,const struct kvm_memory_slot * slot,u64 * huge_sptep)6788 static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6789 const struct kvm_memory_slot *slot,
6790 u64 *huge_sptep)
6791 {
6792 struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6793 int level, r = 0;
6794 gfn_t gfn;
6795 u64 spte;
6796
6797 /* Grab information for the tracepoint before dropping the MMU lock. */
6798 gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6799 level = huge_sp->role.level;
6800 spte = *huge_sptep;
6801
6802 if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6803 r = -ENOSPC;
6804 goto out;
6805 }
6806
6807 if (need_topup_split_caches_or_resched(kvm)) {
6808 write_unlock(&kvm->mmu_lock);
6809 cond_resched();
6810 /*
6811 * If the topup succeeds, return -EAGAIN to indicate that the
6812 * rmap iterator should be restarted because the MMU lock was
6813 * dropped.
6814 */
6815 r = topup_split_caches(kvm) ?: -EAGAIN;
6816 write_lock(&kvm->mmu_lock);
6817 goto out;
6818 }
6819
6820 shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6821
6822 out:
6823 trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6824 return r;
6825 }
6826
shadow_mmu_try_split_huge_pages(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)6827 static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6828 struct kvm_rmap_head *rmap_head,
6829 const struct kvm_memory_slot *slot)
6830 {
6831 struct rmap_iterator iter;
6832 struct kvm_mmu_page *sp;
6833 u64 *huge_sptep;
6834 int r;
6835
6836 restart:
6837 for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6838 sp = sptep_to_sp(huge_sptep);
6839
6840 /* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6841 if (WARN_ON_ONCE(!sp->role.guest_mode))
6842 continue;
6843
6844 /* The rmaps should never contain non-leaf SPTEs. */
6845 if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6846 continue;
6847
6848 /* SPs with level >PG_LEVEL_4K should never by unsync. */
6849 if (WARN_ON_ONCE(sp->unsync))
6850 continue;
6851
6852 /* Don't bother splitting huge pages on invalid SPs. */
6853 if (sp->role.invalid)
6854 continue;
6855
6856 r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6857
6858 /*
6859 * The split succeeded or needs to be retried because the MMU
6860 * lock was dropped. Either way, restart the iterator to get it
6861 * back into a consistent state.
6862 */
6863 if (!r || r == -EAGAIN)
6864 goto restart;
6865
6866 /* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6867 break;
6868 }
6869
6870 return false;
6871 }
6872
kvm_shadow_mmu_try_split_huge_pages(struct kvm * kvm,const struct kvm_memory_slot * slot,gfn_t start,gfn_t end,int target_level)6873 static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6874 const struct kvm_memory_slot *slot,
6875 gfn_t start, gfn_t end,
6876 int target_level)
6877 {
6878 int level;
6879
6880 /*
6881 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6882 * down to the target level. This ensures pages are recursively split
6883 * all the way to the target level. There's no need to split pages
6884 * already at the target level.
6885 */
6886 for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6887 __walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6888 level, level, start, end - 1, true, true, false);
6889 }
6890
6891 /* Must be called with the mmu_lock held in write-mode. */
kvm_mmu_try_split_huge_pages(struct kvm * kvm,const struct kvm_memory_slot * memslot,u64 start,u64 end,int target_level)6892 void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6893 const struct kvm_memory_slot *memslot,
6894 u64 start, u64 end,
6895 int target_level)
6896 {
6897 if (!tdp_mmu_enabled)
6898 return;
6899
6900 if (kvm_memslots_have_rmaps(kvm))
6901 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6902
6903 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6904
6905 /*
6906 * A TLB flush is unnecessary at this point for the same reasons as in
6907 * kvm_mmu_slot_try_split_huge_pages().
6908 */
6909 }
6910
kvm_mmu_slot_try_split_huge_pages(struct kvm * kvm,const struct kvm_memory_slot * memslot,int target_level)6911 void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6912 const struct kvm_memory_slot *memslot,
6913 int target_level)
6914 {
6915 u64 start = memslot->base_gfn;
6916 u64 end = start + memslot->npages;
6917
6918 if (!tdp_mmu_enabled)
6919 return;
6920
6921 if (kvm_memslots_have_rmaps(kvm)) {
6922 write_lock(&kvm->mmu_lock);
6923 kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6924 write_unlock(&kvm->mmu_lock);
6925 }
6926
6927 read_lock(&kvm->mmu_lock);
6928 kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6929 read_unlock(&kvm->mmu_lock);
6930
6931 /*
6932 * No TLB flush is necessary here. KVM will flush TLBs after
6933 * write-protecting and/or clearing dirty on the newly split SPTEs to
6934 * ensure that guest writes are reflected in the dirty log before the
6935 * ioctl to enable dirty logging on this memslot completes. Since the
6936 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6937 * safe for KVM to decide if a TLB flush is necessary based on the split
6938 * SPTEs.
6939 */
6940 }
6941
kvm_mmu_zap_collapsible_spte(struct kvm * kvm,struct kvm_rmap_head * rmap_head,const struct kvm_memory_slot * slot)6942 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
6943 struct kvm_rmap_head *rmap_head,
6944 const struct kvm_memory_slot *slot)
6945 {
6946 u64 *sptep;
6947 struct rmap_iterator iter;
6948 int need_tlb_flush = 0;
6949 struct kvm_mmu_page *sp;
6950
6951 restart:
6952 for_each_rmap_spte(rmap_head, &iter, sptep) {
6953 sp = sptep_to_sp(sptep);
6954
6955 /*
6956 * We cannot do huge page mapping for indirect shadow pages,
6957 * which are found on the last rmap (level = 1) when not using
6958 * tdp; such shadow pages are synced with the page table in
6959 * the guest, and the guest page table is using 4K page size
6960 * mapping if the indirect sp has level = 1.
6961 */
6962 if (sp->role.direct &&
6963 sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6964 PG_LEVEL_NUM)) {
6965 kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6966
6967 if (kvm_available_flush_remote_tlbs_range())
6968 kvm_flush_remote_tlbs_sptep(kvm, sptep);
6969 else
6970 need_tlb_flush = 1;
6971
6972 goto restart;
6973 }
6974 }
6975
6976 return need_tlb_flush;
6977 }
6978 EXPORT_SYMBOL_GPL(kvm_zap_gfn_range);
6979
kvm_rmap_zap_collapsible_sptes(struct kvm * kvm,const struct kvm_memory_slot * slot)6980 static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
6981 const struct kvm_memory_slot *slot)
6982 {
6983 /*
6984 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
6985 * pages that are already mapped at the maximum hugepage level.
6986 */
6987 if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
6988 PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6989 kvm_flush_remote_tlbs_memslot(kvm, slot);
6990 }
6991
kvm_mmu_zap_collapsible_sptes(struct kvm * kvm,const struct kvm_memory_slot * slot)6992 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6993 const struct kvm_memory_slot *slot)
6994 {
6995 if (kvm_memslots_have_rmaps(kvm)) {
6996 write_lock(&kvm->mmu_lock);
6997 kvm_rmap_zap_collapsible_sptes(kvm, slot);
6998 write_unlock(&kvm->mmu_lock);
6999 }
7000
7001 if (tdp_mmu_enabled) {
7002 read_lock(&kvm->mmu_lock);
7003 kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
7004 read_unlock(&kvm->mmu_lock);
7005 }
7006 }
7007
kvm_mmu_slot_leaf_clear_dirty(struct kvm * kvm,const struct kvm_memory_slot * memslot)7008 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
7009 const struct kvm_memory_slot *memslot)
7010 {
7011 if (kvm_memslots_have_rmaps(kvm)) {
7012 write_lock(&kvm->mmu_lock);
7013 /*
7014 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
7015 * support dirty logging at a 4k granularity.
7016 */
7017 walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
7018 write_unlock(&kvm->mmu_lock);
7019 }
7020
7021 if (tdp_mmu_enabled) {
7022 read_lock(&kvm->mmu_lock);
7023 kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
7024 read_unlock(&kvm->mmu_lock);
7025 }
7026
7027 /*
7028 * The caller will flush the TLBs after this function returns.
7029 *
7030 * It's also safe to flush TLBs out of mmu lock here as currently this
7031 * function is only used for dirty logging, in which case flushing TLB
7032 * out of mmu lock also guarantees no dirty pages will be lost in
7033 * dirty_bitmap.
7034 */
7035 }
7036
kvm_mmu_zap_all(struct kvm * kvm)7037 static void kvm_mmu_zap_all(struct kvm *kvm)
7038 {
7039 struct kvm_mmu_page *sp, *node;
7040 LIST_HEAD(invalid_list);
7041 int ign;
7042
7043 write_lock(&kvm->mmu_lock);
7044 restart:
7045 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
7046 if (WARN_ON_ONCE(sp->role.invalid))
7047 continue;
7048 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
7049 goto restart;
7050 if (cond_resched_rwlock_write(&kvm->mmu_lock))
7051 goto restart;
7052 }
7053
7054 kvm_mmu_commit_zap_page(kvm, &invalid_list);
7055
7056 if (tdp_mmu_enabled)
7057 kvm_tdp_mmu_zap_all(kvm);
7058
7059 write_unlock(&kvm->mmu_lock);
7060 }
7061
kvm_arch_flush_shadow_all(struct kvm * kvm)7062 void kvm_arch_flush_shadow_all(struct kvm *kvm)
7063 {
7064 kvm_mmu_zap_all(kvm);
7065 }
7066
kvm_mmu_zap_memslot_pages_and_flush(struct kvm * kvm,struct kvm_memory_slot * slot,bool flush)7067 static void kvm_mmu_zap_memslot_pages_and_flush(struct kvm *kvm,
7068 struct kvm_memory_slot *slot,
7069 bool flush)
7070 {
7071 LIST_HEAD(invalid_list);
7072 unsigned long i;
7073
7074 if (list_empty(&kvm->arch.active_mmu_pages))
7075 goto out_flush;
7076
7077 /*
7078 * Since accounting information is stored in struct kvm_arch_memory_slot,
7079 * all MMU pages that are shadowing guest PTEs must be zapped before the
7080 * memslot is deleted, as freeing such pages after the memslot is freed
7081 * will result in use-after-free, e.g. in unaccount_shadowed().
7082 */
7083 for (i = 0; i < slot->npages; i++) {
7084 struct kvm_mmu_page *sp;
7085 gfn_t gfn = slot->base_gfn + i;
7086
7087 for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn)
7088 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7089
7090 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7091 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7092 flush = false;
7093 cond_resched_rwlock_write(&kvm->mmu_lock);
7094 }
7095 }
7096
7097 out_flush:
7098 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7099 }
7100
kvm_mmu_zap_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)7101 static void kvm_mmu_zap_memslot(struct kvm *kvm,
7102 struct kvm_memory_slot *slot)
7103 {
7104 struct kvm_gfn_range range = {
7105 .slot = slot,
7106 .start = slot->base_gfn,
7107 .end = slot->base_gfn + slot->npages,
7108 .may_block = true,
7109 };
7110 bool flush;
7111
7112 write_lock(&kvm->mmu_lock);
7113 flush = kvm_unmap_gfn_range(kvm, &range);
7114 kvm_mmu_zap_memslot_pages_and_flush(kvm, slot, flush);
7115 write_unlock(&kvm->mmu_lock);
7116 }
7117
kvm_memslot_flush_zap_all(struct kvm * kvm)7118 static inline bool kvm_memslot_flush_zap_all(struct kvm *kvm)
7119 {
7120 return kvm->arch.vm_type == KVM_X86_DEFAULT_VM &&
7121 kvm_check_has_quirk(kvm, KVM_X86_QUIRK_SLOT_ZAP_ALL);
7122 }
7123
kvm_arch_flush_shadow_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)7124 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
7125 struct kvm_memory_slot *slot)
7126 {
7127 if (kvm_memslot_flush_zap_all(kvm))
7128 kvm_mmu_zap_all_fast(kvm);
7129 else
7130 kvm_mmu_zap_memslot(kvm, slot);
7131 }
7132
kvm_mmu_invalidate_mmio_sptes(struct kvm * kvm,u64 gen)7133 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
7134 {
7135 WARN_ON_ONCE(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
7136
7137 gen &= MMIO_SPTE_GEN_MASK;
7138
7139 /*
7140 * Generation numbers are incremented in multiples of the number of
7141 * address spaces in order to provide unique generations across all
7142 * address spaces. Strip what is effectively the address space
7143 * modifier prior to checking for a wrap of the MMIO generation so
7144 * that a wrap in any address space is detected.
7145 */
7146 gen &= ~((u64)kvm_arch_nr_memslot_as_ids(kvm) - 1);
7147
7148 /*
7149 * The very rare case: if the MMIO generation number has wrapped,
7150 * zap all shadow pages.
7151 */
7152 if (unlikely(gen == 0)) {
7153 kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
7154 kvm_mmu_zap_all_fast(kvm);
7155 }
7156 }
7157
mmu_shrink_scan(struct shrinker * shrink,struct shrink_control * sc)7158 static unsigned long mmu_shrink_scan(struct shrinker *shrink,
7159 struct shrink_control *sc)
7160 {
7161 struct kvm *kvm;
7162 int nr_to_scan = sc->nr_to_scan;
7163 unsigned long freed = 0;
7164
7165 mutex_lock(&kvm_lock);
7166
7167 list_for_each_entry(kvm, &vm_list, vm_list) {
7168 int idx;
7169
7170 /*
7171 * Never scan more than sc->nr_to_scan VM instances.
7172 * Will not hit this condition practically since we do not try
7173 * to shrink more than one VM and it is very unlikely to see
7174 * !n_used_mmu_pages so many times.
7175 */
7176 if (!nr_to_scan--)
7177 break;
7178 /*
7179 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
7180 * here. We may skip a VM instance errorneosly, but we do not
7181 * want to shrink a VM that only started to populate its MMU
7182 * anyway.
7183 */
7184 if (!kvm->arch.n_used_mmu_pages &&
7185 !kvm_has_zapped_obsolete_pages(kvm))
7186 continue;
7187
7188 idx = srcu_read_lock(&kvm->srcu);
7189 write_lock(&kvm->mmu_lock);
7190
7191 if (kvm_has_zapped_obsolete_pages(kvm)) {
7192 kvm_mmu_commit_zap_page(kvm,
7193 &kvm->arch.zapped_obsolete_pages);
7194 goto unlock;
7195 }
7196
7197 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
7198
7199 unlock:
7200 write_unlock(&kvm->mmu_lock);
7201 srcu_read_unlock(&kvm->srcu, idx);
7202
7203 /*
7204 * unfair on small ones
7205 * per-vm shrinkers cry out
7206 * sadness comes quickly
7207 */
7208 list_move_tail(&kvm->vm_list, &vm_list);
7209 break;
7210 }
7211
7212 mutex_unlock(&kvm_lock);
7213 return freed;
7214 }
7215
mmu_shrink_count(struct shrinker * shrink,struct shrink_control * sc)7216 static unsigned long mmu_shrink_count(struct shrinker *shrink,
7217 struct shrink_control *sc)
7218 {
7219 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
7220 }
7221
7222 static struct shrinker *mmu_shrinker;
7223
mmu_destroy_caches(void)7224 static void mmu_destroy_caches(void)
7225 {
7226 kmem_cache_destroy(pte_list_desc_cache);
7227 kmem_cache_destroy(mmu_page_header_cache);
7228 }
7229
kvm_wake_nx_recovery_thread(struct kvm * kvm)7230 static void kvm_wake_nx_recovery_thread(struct kvm *kvm)
7231 {
7232 /*
7233 * The NX recovery thread is spawned on-demand at the first KVM_RUN and
7234 * may not be valid even though the VM is globally visible. Do nothing,
7235 * as such a VM can't have any possible NX huge pages.
7236 */
7237 struct vhost_task *nx_thread = READ_ONCE(kvm->arch.nx_huge_page_recovery_thread);
7238
7239 if (nx_thread)
7240 vhost_task_wake(nx_thread);
7241 }
7242
get_nx_huge_pages(char * buffer,const struct kernel_param * kp)7243 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
7244 {
7245 if (nx_hugepage_mitigation_hard_disabled)
7246 return sysfs_emit(buffer, "never\n");
7247
7248 return param_get_bool(buffer, kp);
7249 }
7250
get_nx_auto_mode(void)7251 static bool get_nx_auto_mode(void)
7252 {
7253 /* Return true when CPU has the bug, and mitigations are ON */
7254 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
7255 }
7256
__set_nx_huge_pages(bool val)7257 static void __set_nx_huge_pages(bool val)
7258 {
7259 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
7260 }
7261
set_nx_huge_pages(const char * val,const struct kernel_param * kp)7262 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
7263 {
7264 bool old_val = nx_huge_pages;
7265 bool new_val;
7266
7267 if (nx_hugepage_mitigation_hard_disabled)
7268 return -EPERM;
7269
7270 /* In "auto" mode deploy workaround only if CPU has the bug. */
7271 if (sysfs_streq(val, "off")) {
7272 new_val = 0;
7273 } else if (sysfs_streq(val, "force")) {
7274 new_val = 1;
7275 } else if (sysfs_streq(val, "auto")) {
7276 new_val = get_nx_auto_mode();
7277 } else if (sysfs_streq(val, "never")) {
7278 new_val = 0;
7279
7280 mutex_lock(&kvm_lock);
7281 if (!list_empty(&vm_list)) {
7282 mutex_unlock(&kvm_lock);
7283 return -EBUSY;
7284 }
7285 nx_hugepage_mitigation_hard_disabled = true;
7286 mutex_unlock(&kvm_lock);
7287 } else if (kstrtobool(val, &new_val) < 0) {
7288 return -EINVAL;
7289 }
7290
7291 __set_nx_huge_pages(new_val);
7292
7293 if (new_val != old_val) {
7294 struct kvm *kvm;
7295
7296 mutex_lock(&kvm_lock);
7297
7298 list_for_each_entry(kvm, &vm_list, vm_list) {
7299 mutex_lock(&kvm->slots_lock);
7300 kvm_mmu_zap_all_fast(kvm);
7301 mutex_unlock(&kvm->slots_lock);
7302
7303 kvm_wake_nx_recovery_thread(kvm);
7304 }
7305 mutex_unlock(&kvm_lock);
7306 }
7307
7308 return 0;
7309 }
7310
7311 /*
7312 * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
7313 * its default value of -1 is technically undefined behavior for a boolean.
7314 * Forward the module init call to SPTE code so that it too can handle module
7315 * params that need to be resolved/snapshot.
7316 */
kvm_mmu_x86_module_init(void)7317 void __init kvm_mmu_x86_module_init(void)
7318 {
7319 if (nx_huge_pages == -1)
7320 __set_nx_huge_pages(get_nx_auto_mode());
7321
7322 /*
7323 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
7324 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
7325 * when the vendor module is loaded.
7326 */
7327 tdp_mmu_allowed = tdp_mmu_enabled;
7328
7329 kvm_mmu_spte_module_init();
7330 }
7331
7332 /*
7333 * The bulk of the MMU initialization is deferred until the vendor module is
7334 * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
7335 * to be reset when a potentially different vendor module is loaded.
7336 */
kvm_mmu_vendor_module_init(void)7337 int kvm_mmu_vendor_module_init(void)
7338 {
7339 int ret = -ENOMEM;
7340
7341 /*
7342 * MMU roles use union aliasing which is, generally speaking, an
7343 * undefined behavior. However, we supposedly know how compilers behave
7344 * and the current status quo is unlikely to change. Guardians below are
7345 * supposed to let us know if the assumption becomes false.
7346 */
7347 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
7348 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
7349 BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
7350
7351 kvm_mmu_reset_all_pte_masks();
7352
7353 pte_list_desc_cache = KMEM_CACHE(pte_list_desc, SLAB_ACCOUNT);
7354 if (!pte_list_desc_cache)
7355 goto out;
7356
7357 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
7358 sizeof(struct kvm_mmu_page),
7359 0, SLAB_ACCOUNT, NULL);
7360 if (!mmu_page_header_cache)
7361 goto out;
7362
7363 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
7364 goto out;
7365
7366 mmu_shrinker = shrinker_alloc(0, "x86-mmu");
7367 if (!mmu_shrinker)
7368 goto out_shrinker;
7369
7370 mmu_shrinker->count_objects = mmu_shrink_count;
7371 mmu_shrinker->scan_objects = mmu_shrink_scan;
7372 mmu_shrinker->seeks = DEFAULT_SEEKS * 10;
7373
7374 shrinker_register(mmu_shrinker);
7375
7376 return 0;
7377
7378 out_shrinker:
7379 percpu_counter_destroy(&kvm_total_used_mmu_pages);
7380 out:
7381 mmu_destroy_caches();
7382 return ret;
7383 }
7384
kvm_mmu_destroy(struct kvm_vcpu * vcpu)7385 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
7386 {
7387 kvm_mmu_unload(vcpu);
7388 free_mmu_pages(&vcpu->arch.root_mmu);
7389 free_mmu_pages(&vcpu->arch.guest_mmu);
7390 mmu_free_memory_caches(vcpu);
7391 }
7392
kvm_mmu_vendor_module_exit(void)7393 void kvm_mmu_vendor_module_exit(void)
7394 {
7395 mmu_destroy_caches();
7396 percpu_counter_destroy(&kvm_total_used_mmu_pages);
7397 shrinker_free(mmu_shrinker);
7398 }
7399
7400 /*
7401 * Calculate the effective recovery period, accounting for '0' meaning "let KVM
7402 * select a halving time of 1 hour". Returns true if recovery is enabled.
7403 */
calc_nx_huge_pages_recovery_period(uint * period)7404 static bool calc_nx_huge_pages_recovery_period(uint *period)
7405 {
7406 /*
7407 * Use READ_ONCE to get the params, this may be called outside of the
7408 * param setters, e.g. by the kthread to compute its next timeout.
7409 */
7410 bool enabled = READ_ONCE(nx_huge_pages);
7411 uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7412
7413 if (!enabled || !ratio)
7414 return false;
7415
7416 *period = READ_ONCE(nx_huge_pages_recovery_period_ms);
7417 if (!*period) {
7418 /* Make sure the period is not less than one second. */
7419 ratio = min(ratio, 3600u);
7420 *period = 60 * 60 * 1000 / ratio;
7421 }
7422 return true;
7423 }
7424
set_nx_huge_pages_recovery_param(const char * val,const struct kernel_param * kp)7425 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7426 {
7427 bool was_recovery_enabled, is_recovery_enabled;
7428 uint old_period, new_period;
7429 int err;
7430
7431 if (nx_hugepage_mitigation_hard_disabled)
7432 return -EPERM;
7433
7434 was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
7435
7436 err = param_set_uint(val, kp);
7437 if (err)
7438 return err;
7439
7440 is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
7441
7442 if (is_recovery_enabled &&
7443 (!was_recovery_enabled || old_period > new_period)) {
7444 struct kvm *kvm;
7445
7446 mutex_lock(&kvm_lock);
7447
7448 list_for_each_entry(kvm, &vm_list, vm_list)
7449 kvm_wake_nx_recovery_thread(kvm);
7450
7451 mutex_unlock(&kvm_lock);
7452 }
7453
7454 return err;
7455 }
7456
kvm_recover_nx_huge_pages(struct kvm * kvm)7457 static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7458 {
7459 unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7460 struct kvm_memory_slot *slot;
7461 int rcu_idx;
7462 struct kvm_mmu_page *sp;
7463 unsigned int ratio;
7464 LIST_HEAD(invalid_list);
7465 bool flush = false;
7466 ulong to_zap;
7467
7468 rcu_idx = srcu_read_lock(&kvm->srcu);
7469 write_lock(&kvm->mmu_lock);
7470
7471 /*
7472 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7473 * be done under RCU protection, because the pages are freed via RCU
7474 * callback.
7475 */
7476 rcu_read_lock();
7477
7478 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7479 to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
7480 for ( ; to_zap; --to_zap) {
7481 if (list_empty(&kvm->arch.possible_nx_huge_pages))
7482 break;
7483
7484 /*
7485 * We use a separate list instead of just using active_mmu_pages
7486 * because the number of shadow pages that be replaced with an
7487 * NX huge page is expected to be relatively small compared to
7488 * the total number of shadow pages. And because the TDP MMU
7489 * doesn't use active_mmu_pages.
7490 */
7491 sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7492 struct kvm_mmu_page,
7493 possible_nx_huge_page_link);
7494 WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7495 WARN_ON_ONCE(!sp->role.direct);
7496
7497 /*
7498 * Unaccount and do not attempt to recover any NX Huge Pages
7499 * that are being dirty tracked, as they would just be faulted
7500 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7501 * recovered, along with all the other huge pages in the slot,
7502 * when dirty logging is disabled.
7503 *
7504 * Since gfn_to_memslot() is relatively expensive, it helps to
7505 * skip it if it the test cannot possibly return true. On the
7506 * other hand, if any memslot has logging enabled, chances are
7507 * good that all of them do, in which case unaccount_nx_huge_page()
7508 * is much cheaper than zapping the page.
7509 *
7510 * If a memslot update is in progress, reading an incorrect value
7511 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
7512 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
7513 * it is becoming nonzero, the page will be zapped unnecessarily.
7514 * Either way, this only affects efficiency in racy situations,
7515 * and not correctness.
7516 */
7517 slot = NULL;
7518 if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7519 struct kvm_memslots *slots;
7520
7521 slots = kvm_memslots_for_spte_role(kvm, sp->role);
7522 slot = __gfn_to_memslot(slots, sp->gfn);
7523 WARN_ON_ONCE(!slot);
7524 }
7525
7526 if (slot && kvm_slot_dirty_track_enabled(slot))
7527 unaccount_nx_huge_page(kvm, sp);
7528 else if (is_tdp_mmu_page(sp))
7529 flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
7530 else
7531 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7532 WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7533
7534 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7535 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7536 rcu_read_unlock();
7537
7538 cond_resched_rwlock_write(&kvm->mmu_lock);
7539 flush = false;
7540
7541 rcu_read_lock();
7542 }
7543 }
7544 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7545
7546 rcu_read_unlock();
7547
7548 write_unlock(&kvm->mmu_lock);
7549 srcu_read_unlock(&kvm->srcu, rcu_idx);
7550 }
7551
kvm_nx_huge_page_recovery_worker_kill(void * data)7552 static void kvm_nx_huge_page_recovery_worker_kill(void *data)
7553 {
7554 }
7555
kvm_nx_huge_page_recovery_worker(void * data)7556 static bool kvm_nx_huge_page_recovery_worker(void *data)
7557 {
7558 struct kvm *kvm = data;
7559 bool enabled;
7560 uint period;
7561 long remaining_time;
7562
7563 enabled = calc_nx_huge_pages_recovery_period(&period);
7564 if (!enabled)
7565 return false;
7566
7567 remaining_time = kvm->arch.nx_huge_page_last + msecs_to_jiffies(period)
7568 - get_jiffies_64();
7569 if (remaining_time > 0) {
7570 schedule_timeout(remaining_time);
7571 /* check for signals and come back */
7572 return true;
7573 }
7574
7575 __set_current_state(TASK_RUNNING);
7576 kvm_recover_nx_huge_pages(kvm);
7577 kvm->arch.nx_huge_page_last = get_jiffies_64();
7578 return true;
7579 }
7580
kvm_mmu_start_lpage_recovery(struct once * once)7581 static int kvm_mmu_start_lpage_recovery(struct once *once)
7582 {
7583 struct kvm_arch *ka = container_of(once, struct kvm_arch, nx_once);
7584 struct kvm *kvm = container_of(ka, struct kvm, arch);
7585 struct vhost_task *nx_thread;
7586
7587 kvm->arch.nx_huge_page_last = get_jiffies_64();
7588 nx_thread = vhost_task_create(kvm_nx_huge_page_recovery_worker,
7589 kvm_nx_huge_page_recovery_worker_kill,
7590 kvm, "kvm-nx-lpage-recovery");
7591
7592 if (IS_ERR(nx_thread))
7593 return PTR_ERR(nx_thread);
7594
7595 vhost_task_start(nx_thread);
7596
7597 /* Make the task visible only once it is fully started. */
7598 WRITE_ONCE(kvm->arch.nx_huge_page_recovery_thread, nx_thread);
7599 return 0;
7600 }
7601
kvm_mmu_post_init_vm(struct kvm * kvm)7602 int kvm_mmu_post_init_vm(struct kvm *kvm)
7603 {
7604 if (nx_hugepage_mitigation_hard_disabled)
7605 return 0;
7606
7607 return call_once(&kvm->arch.nx_once, kvm_mmu_start_lpage_recovery);
7608 }
7609
kvm_mmu_pre_destroy_vm(struct kvm * kvm)7610 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7611 {
7612 if (kvm->arch.nx_huge_page_recovery_thread)
7613 vhost_task_stop(kvm->arch.nx_huge_page_recovery_thread);
7614 }
7615
7616 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
hugepage_test_mixed(struct kvm_memory_slot * slot,gfn_t gfn,int level)7617 static bool hugepage_test_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
7618 int level)
7619 {
7620 return lpage_info_slot(gfn, slot, level)->disallow_lpage & KVM_LPAGE_MIXED_FLAG;
7621 }
7622
hugepage_clear_mixed(struct kvm_memory_slot * slot,gfn_t gfn,int level)7623 static void hugepage_clear_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
7624 int level)
7625 {
7626 lpage_info_slot(gfn, slot, level)->disallow_lpage &= ~KVM_LPAGE_MIXED_FLAG;
7627 }
7628
hugepage_set_mixed(struct kvm_memory_slot * slot,gfn_t gfn,int level)7629 static void hugepage_set_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
7630 int level)
7631 {
7632 lpage_info_slot(gfn, slot, level)->disallow_lpage |= KVM_LPAGE_MIXED_FLAG;
7633 }
7634
kvm_arch_pre_set_memory_attributes(struct kvm * kvm,struct kvm_gfn_range * range)7635 bool kvm_arch_pre_set_memory_attributes(struct kvm *kvm,
7636 struct kvm_gfn_range *range)
7637 {
7638 struct kvm_memory_slot *slot = range->slot;
7639 int level;
7640
7641 /*
7642 * Zap SPTEs even if the slot can't be mapped PRIVATE. KVM x86 only
7643 * supports KVM_MEMORY_ATTRIBUTE_PRIVATE, and so it *seems* like KVM
7644 * can simply ignore such slots. But if userspace is making memory
7645 * PRIVATE, then KVM must prevent the guest from accessing the memory
7646 * as shared. And if userspace is making memory SHARED and this point
7647 * is reached, then at least one page within the range was previously
7648 * PRIVATE, i.e. the slot's possible hugepage ranges are changing.
7649 * Zapping SPTEs in this case ensures KVM will reassess whether or not
7650 * a hugepage can be used for affected ranges.
7651 */
7652 if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
7653 return false;
7654
7655 if (WARN_ON_ONCE(range->end <= range->start))
7656 return false;
7657
7658 /*
7659 * If the head and tail pages of the range currently allow a hugepage,
7660 * i.e. reside fully in the slot and don't have mixed attributes, then
7661 * add each corresponding hugepage range to the ongoing invalidation,
7662 * e.g. to prevent KVM from creating a hugepage in response to a fault
7663 * for a gfn whose attributes aren't changing. Note, only the range
7664 * of gfns whose attributes are being modified needs to be explicitly
7665 * unmapped, as that will unmap any existing hugepages.
7666 */
7667 for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
7668 gfn_t start = gfn_round_for_level(range->start, level);
7669 gfn_t end = gfn_round_for_level(range->end - 1, level);
7670 gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
7671
7672 if ((start != range->start || start + nr_pages > range->end) &&
7673 start >= slot->base_gfn &&
7674 start + nr_pages <= slot->base_gfn + slot->npages &&
7675 !hugepage_test_mixed(slot, start, level))
7676 kvm_mmu_invalidate_range_add(kvm, start, start + nr_pages);
7677
7678 if (end == start)
7679 continue;
7680
7681 if ((end + nr_pages) > range->end &&
7682 (end + nr_pages) <= (slot->base_gfn + slot->npages) &&
7683 !hugepage_test_mixed(slot, end, level))
7684 kvm_mmu_invalidate_range_add(kvm, end, end + nr_pages);
7685 }
7686
7687 /* Unmap the old attribute page. */
7688 if (range->arg.attributes & KVM_MEMORY_ATTRIBUTE_PRIVATE)
7689 range->attr_filter = KVM_FILTER_SHARED;
7690 else
7691 range->attr_filter = KVM_FILTER_PRIVATE;
7692
7693 return kvm_unmap_gfn_range(kvm, range);
7694 }
7695
7696
7697
hugepage_has_attrs(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn,int level,unsigned long attrs)7698 static bool hugepage_has_attrs(struct kvm *kvm, struct kvm_memory_slot *slot,
7699 gfn_t gfn, int level, unsigned long attrs)
7700 {
7701 const unsigned long start = gfn;
7702 const unsigned long end = start + KVM_PAGES_PER_HPAGE(level);
7703
7704 if (level == PG_LEVEL_2M)
7705 return kvm_range_has_memory_attributes(kvm, start, end, ~0, attrs);
7706
7707 for (gfn = start; gfn < end; gfn += KVM_PAGES_PER_HPAGE(level - 1)) {
7708 if (hugepage_test_mixed(slot, gfn, level - 1) ||
7709 attrs != kvm_get_memory_attributes(kvm, gfn))
7710 return false;
7711 }
7712 return true;
7713 }
7714
kvm_arch_post_set_memory_attributes(struct kvm * kvm,struct kvm_gfn_range * range)7715 bool kvm_arch_post_set_memory_attributes(struct kvm *kvm,
7716 struct kvm_gfn_range *range)
7717 {
7718 unsigned long attrs = range->arg.attributes;
7719 struct kvm_memory_slot *slot = range->slot;
7720 int level;
7721
7722 lockdep_assert_held_write(&kvm->mmu_lock);
7723 lockdep_assert_held(&kvm->slots_lock);
7724
7725 /*
7726 * Calculate which ranges can be mapped with hugepages even if the slot
7727 * can't map memory PRIVATE. KVM mustn't create a SHARED hugepage over
7728 * a range that has PRIVATE GFNs, and conversely converting a range to
7729 * SHARED may now allow hugepages.
7730 */
7731 if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
7732 return false;
7733
7734 /*
7735 * The sequence matters here: upper levels consume the result of lower
7736 * level's scanning.
7737 */
7738 for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
7739 gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
7740 gfn_t gfn = gfn_round_for_level(range->start, level);
7741
7742 /* Process the head page if it straddles the range. */
7743 if (gfn != range->start || gfn + nr_pages > range->end) {
7744 /*
7745 * Skip mixed tracking if the aligned gfn isn't covered
7746 * by the memslot, KVM can't use a hugepage due to the
7747 * misaligned address regardless of memory attributes.
7748 */
7749 if (gfn >= slot->base_gfn &&
7750 gfn + nr_pages <= slot->base_gfn + slot->npages) {
7751 if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
7752 hugepage_clear_mixed(slot, gfn, level);
7753 else
7754 hugepage_set_mixed(slot, gfn, level);
7755 }
7756 gfn += nr_pages;
7757 }
7758
7759 /*
7760 * Pages entirely covered by the range are guaranteed to have
7761 * only the attributes which were just set.
7762 */
7763 for ( ; gfn + nr_pages <= range->end; gfn += nr_pages)
7764 hugepage_clear_mixed(slot, gfn, level);
7765
7766 /*
7767 * Process the last tail page if it straddles the range and is
7768 * contained by the memslot. Like the head page, KVM can't
7769 * create a hugepage if the slot size is misaligned.
7770 */
7771 if (gfn < range->end &&
7772 (gfn + nr_pages) <= (slot->base_gfn + slot->npages)) {
7773 if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
7774 hugepage_clear_mixed(slot, gfn, level);
7775 else
7776 hugepage_set_mixed(slot, gfn, level);
7777 }
7778 }
7779 return false;
7780 }
7781
kvm_mmu_init_memslot_memory_attributes(struct kvm * kvm,struct kvm_memory_slot * slot)7782 void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
7783 struct kvm_memory_slot *slot)
7784 {
7785 int level;
7786
7787 if (!kvm_arch_has_private_mem(kvm))
7788 return;
7789
7790 for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
7791 /*
7792 * Don't bother tracking mixed attributes for pages that can't
7793 * be huge due to alignment, i.e. process only pages that are
7794 * entirely contained by the memslot.
7795 */
7796 gfn_t end = gfn_round_for_level(slot->base_gfn + slot->npages, level);
7797 gfn_t start = gfn_round_for_level(slot->base_gfn, level);
7798 gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
7799 gfn_t gfn;
7800
7801 if (start < slot->base_gfn)
7802 start += nr_pages;
7803
7804 /*
7805 * Unlike setting attributes, every potential hugepage needs to
7806 * be manually checked as the attributes may already be mixed.
7807 */
7808 for (gfn = start; gfn < end; gfn += nr_pages) {
7809 unsigned long attrs = kvm_get_memory_attributes(kvm, gfn);
7810
7811 if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
7812 hugepage_clear_mixed(slot, gfn, level);
7813 else
7814 hugepage_set_mixed(slot, gfn, level);
7815 }
7816 }
7817 }
7818 #endif
7819