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