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