]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - arch/x86/kvm/mmu/mmu.c
KVM: Introduce kvm_get_kvm_safe()
[mirror_ubuntu-jammy-kernel.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 */
e495606d 17
af585b92 18#include "irq.h"
88197e6a 19#include "ioapic.h"
1d737c8a 20#include "mmu.h"
6ca9a6f3 21#include "mmu_internal.h"
fe5db27d 22#include "tdp_mmu.h"
836a1b3c 23#include "x86.h"
6de4f3ad 24#include "kvm_cache_regs.h"
2f728d66 25#include "kvm_emulate.h"
5f7dde7b 26#include "cpuid.h"
5a9624af 27#include "spte.h"
e495606d 28
edf88417 29#include <linux/kvm_host.h>
6aa8b732
AK
30#include <linux/types.h>
31#include <linux/string.h>
6aa8b732
AK
32#include <linux/mm.h>
33#include <linux/highmem.h>
1767e931
PG
34#include <linux/moduleparam.h>
35#include <linux/export.h>
448353ca 36#include <linux/swap.h>
05da4558 37#include <linux/hugetlb.h>
2f333bcb 38#include <linux/compiler.h>
bc6678a3 39#include <linux/srcu.h>
5a0e3ad6 40#include <linux/slab.h>
3f07c014 41#include <linux/sched/signal.h>
bf998156 42#include <linux/uaccess.h>
114df303 43#include <linux/hash.h>
f160c7b7 44#include <linux/kern_levels.h>
1aa9b957 45#include <linux/kthread.h>
6aa8b732 46
e495606d 47#include <asm/page.h>
eb243d1d 48#include <asm/memtype.h>
e495606d 49#include <asm/cmpxchg.h>
4e542370 50#include <asm/io.h>
4a98623d 51#include <asm/set_memory.h>
13673a90 52#include <asm/vmx.h>
3d0c27ad 53#include <asm/kvm_page_track.h>
1261bfa3 54#include "trace.h"
6aa8b732 55
fc9bf2e0
SC
56#include "paging.h"
57
b8e8c830
PB
58extern bool itlb_multihit_kvm_mitigation;
59
a9d6496d 60int __read_mostly nx_huge_pages = -1;
13fb5927
PB
61#ifdef CONFIG_PREEMPT_RT
62/* Recovery can cause latency spikes, disable it for PREEMPT_RT. */
63static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
64#else
1aa9b957 65static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
13fb5927 66#endif
b8e8c830
PB
67
68static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
1aa9b957 69static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
b8e8c830 70
d5d6c18d 71static const struct kernel_param_ops nx_huge_pages_ops = {
b8e8c830
PB
72 .set = set_nx_huge_pages,
73 .get = param_get_bool,
74};
75
d5d6c18d 76static const struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
1aa9b957
JS
77 .set = set_nx_huge_pages_recovery_ratio,
78 .get = param_get_uint,
79};
80
b8e8c830
PB
81module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
82__MODULE_PARM_TYPE(nx_huge_pages, "bool");
1aa9b957
JS
83module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
84 &nx_huge_pages_recovery_ratio, 0644);
85__MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
b8e8c830 86
71fe7013
SC
87static bool __read_mostly force_flush_and_sync_on_reuse;
88module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
89
18552672
JR
90/*
91 * When setting this variable to true it enables Two-Dimensional-Paging
92 * where the hardware walks 2 page tables:
93 * 1. the guest-virtual to guest-physical
94 * 2. while doing 1. it walks guest-physical to host-physical
95 * If the hardware supports that we don't need to do shadow paging.
96 */
2f333bcb 97bool tdp_enabled = false;
18552672 98
1d92d2e8 99static int max_huge_page_level __read_mostly;
83013059 100static int max_tdp_level __read_mostly;
703c335d 101
8b1fe17c
XG
102enum {
103 AUDIT_PRE_PAGE_FAULT,
104 AUDIT_POST_PAGE_FAULT,
105 AUDIT_PRE_PTE_WRITE,
6903074c
XG
106 AUDIT_POST_PTE_WRITE,
107 AUDIT_PRE_SYNC,
108 AUDIT_POST_SYNC
8b1fe17c 109};
37a7d8b0 110
37a7d8b0 111#ifdef MMU_DEBUG
5a9624af 112bool dbg = 0;
fa4a2c08 113module_param(dbg, bool, 0644);
d6c69ee9 114#endif
6aa8b732 115
957ed9ef
XG
116#define PTE_PREFETCH_NUM 8
117
6aa8b732
AK
118#define PT32_LEVEL_BITS 10
119
120#define PT32_LEVEL_SHIFT(level) \
d77c26fc 121 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
6aa8b732 122
e04da980
JR
123#define PT32_LVL_OFFSET_MASK(level) \
124 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
125 * PT32_LEVEL_BITS))) - 1))
6aa8b732
AK
126
127#define PT32_INDEX(address, level)\
128 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
129
130
6aa8b732
AK
131#define PT32_BASE_ADDR_MASK PAGE_MASK
132#define PT32_DIR_BASE_ADDR_MASK \
133 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
e04da980
JR
134#define PT32_LVL_ADDR_MASK(level) \
135 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
136 * PT32_LEVEL_BITS))) - 1))
6aa8b732 137
90bb6fc5
AK
138#include <trace/events/kvm.h>
139
220f773a
TY
140/* make pte_list_desc fit well in cache line */
141#define PTE_LIST_EXT 3
142
53c07b18
XG
143struct pte_list_desc {
144 u64 *sptes[PTE_LIST_EXT];
145 struct pte_list_desc *more;
cd4a4e53
AK
146};
147
2d11123a
AK
148struct kvm_shadow_walk_iterator {
149 u64 addr;
150 hpa_t shadow_addr;
2d11123a 151 u64 *sptep;
dd3bfd59 152 int level;
2d11123a
AK
153 unsigned index;
154};
155
7eb77e9f
JS
156#define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker) \
157 for (shadow_walk_init_using_root(&(_walker), (_vcpu), \
158 (_root), (_addr)); \
159 shadow_walk_okay(&(_walker)); \
160 shadow_walk_next(&(_walker)))
161
162#define for_each_shadow_entry(_vcpu, _addr, _walker) \
2d11123a
AK
163 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
164 shadow_walk_okay(&(_walker)); \
165 shadow_walk_next(&(_walker)))
166
c2a2ac2b
XG
167#define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
168 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
169 shadow_walk_okay(&(_walker)) && \
170 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
171 __shadow_walk_next(&(_walker), spte))
172
53c07b18 173static struct kmem_cache *pte_list_desc_cache;
02c00b3a 174struct kmem_cache *mmu_page_header_cache;
45221ab6 175static struct percpu_counter kvm_total_used_mmu_pages;
b5a33a75 176
ce88decf 177static void mmu_spte_set(u64 *sptep, u64 spte);
9fa72119
JS
178static union kvm_mmu_page_role
179kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
ce88decf 180
594e91a1
SC
181struct kvm_mmu_role_regs {
182 const unsigned long cr0;
183 const unsigned long cr4;
184 const u64 efer;
185};
186
335e192a
PB
187#define CREATE_TRACE_POINTS
188#include "mmutrace.h"
189
594e91a1
SC
190/*
191 * Yes, lot's of underscores. They're a hint that you probably shouldn't be
192 * reading from the role_regs. Once the mmu_role is constructed, it becomes
193 * the single source of truth for the MMU's state.
194 */
195#define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag) \
196static inline bool ____is_##reg##_##name(struct kvm_mmu_role_regs *regs)\
197{ \
198 return !!(regs->reg & flag); \
199}
200BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
201BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
202BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
203BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
204BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
205BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
206BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
207BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
208BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
209BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
210
60667724
SC
211/*
212 * The MMU itself (with a valid role) is the single source of truth for the
213 * MMU. Do not use the regs used to build the MMU/role, nor the vCPU. The
214 * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
215 * and the vCPU may be incorrect/irrelevant.
216 */
217#define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name) \
218static inline bool is_##reg##_##name(struct kvm_mmu *mmu) \
219{ \
220 return !!(mmu->mmu_role. base_or_ext . reg##_##name); \
221}
222BUILD_MMU_ROLE_ACCESSOR(ext, cr0, pg);
223BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
224BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pse);
225BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pae);
226BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smep);
227BUILD_MMU_ROLE_ACCESSOR(ext, cr4, smap);
228BUILD_MMU_ROLE_ACCESSOR(ext, cr4, pke);
229BUILD_MMU_ROLE_ACCESSOR(ext, cr4, la57);
230BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
231
594e91a1
SC
232static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
233{
234 struct kvm_mmu_role_regs regs = {
235 .cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
236 .cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
237 .efer = vcpu->arch.efer,
238 };
239
240 return regs;
241}
40ef75a7 242
f4bd6f73
SC
243static int role_regs_to_root_level(struct kvm_mmu_role_regs *regs)
244{
245 if (!____is_cr0_pg(regs))
246 return 0;
247 else if (____is_efer_lma(regs))
248 return ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL :
249 PT64_ROOT_4LEVEL;
250 else if (____is_cr4_pae(regs))
251 return PT32E_ROOT_LEVEL;
252 else
253 return PT32_ROOT_LEVEL;
254}
40ef75a7
LT
255
256static inline bool kvm_available_flush_tlb_with_range(void)
257{
afaf0b2f 258 return kvm_x86_ops.tlb_remote_flush_with_range;
40ef75a7
LT
259}
260
261static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
262 struct kvm_tlb_range *range)
263{
264 int ret = -ENOTSUPP;
265
afaf0b2f 266 if (range && kvm_x86_ops.tlb_remote_flush_with_range)
b3646477 267 ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
40ef75a7
LT
268
269 if (ret)
270 kvm_flush_remote_tlbs(kvm);
271}
272
2f2fad08 273void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
40ef75a7
LT
274 u64 start_gfn, u64 pages)
275{
276 struct kvm_tlb_range range;
277
278 range.start_gfn = start_gfn;
279 range.pages = pages;
280
281 kvm_flush_remote_tlbs_with_range(kvm, &range);
282}
283
8f79b064
BG
284static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
285 unsigned int access)
286{
c236d962 287 u64 spte = make_mmio_spte(vcpu, gfn, access);
8f79b064 288
c236d962
SC
289 trace_mark_mmio_spte(sptep, gfn, spte);
290 mmu_spte_set(sptep, spte);
ce88decf
XG
291}
292
ce88decf
XG
293static gfn_t get_mmio_spte_gfn(u64 spte)
294{
daa07cbc 295 u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
28a1f3ac 296
8a967d65 297 gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
28a1f3ac
JS
298 & shadow_nonpresent_or_rsvd_mask;
299
300 return gpa >> PAGE_SHIFT;
ce88decf
XG
301}
302
303static unsigned get_mmio_spte_access(u64 spte)
304{
4af77151 305 return spte & shadow_mmio_access_mask;
ce88decf
XG
306}
307
54bf36aa 308static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
f8f55942 309{
cae7ed3c 310 u64 kvm_gen, spte_gen, gen;
089504c0 311
cae7ed3c
SC
312 gen = kvm_vcpu_memslots(vcpu)->generation;
313 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
314 return false;
089504c0 315
cae7ed3c 316 kvm_gen = gen & MMIO_SPTE_GEN_MASK;
089504c0
XG
317 spte_gen = get_mmio_spte_generation(spte);
318
319 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
320 return likely(kvm_gen == spte_gen);
f8f55942
XG
321}
322
cd313569
MG
323static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
324 struct x86_exception *exception)
325{
ec7771ab 326 /* Check if guest physical address doesn't exceed guest maximum */
dc46515c 327 if (kvm_vcpu_is_illegal_gpa(vcpu, gpa)) {
ec7771ab
MG
328 exception->error_code |= PFERR_RSVD_MASK;
329 return UNMAPPED_GVA;
330 }
331
cd313569
MG
332 return gpa;
333}
334
6aa8b732
AK
335static int is_cpuid_PSE36(void)
336{
337 return 1;
338}
339
da928521
AK
340static gfn_t pse36_gfn_delta(u32 gpte)
341{
342 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
343
344 return (gpte & PT32_DIR_PSE36_MASK) << shift;
345}
346
603e0651 347#ifdef CONFIG_X86_64
d555c333 348static void __set_spte(u64 *sptep, u64 spte)
e663ee64 349{
b19ee2ff 350 WRITE_ONCE(*sptep, spte);
e663ee64
AK
351}
352
603e0651 353static void __update_clear_spte_fast(u64 *sptep, u64 spte)
a9221dd5 354{
b19ee2ff 355 WRITE_ONCE(*sptep, spte);
603e0651
XG
356}
357
358static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
359{
360 return xchg(sptep, spte);
361}
c2a2ac2b
XG
362
363static u64 __get_spte_lockless(u64 *sptep)
364{
6aa7de05 365 return READ_ONCE(*sptep);
c2a2ac2b 366}
a9221dd5 367#else
603e0651
XG
368union split_spte {
369 struct {
370 u32 spte_low;
371 u32 spte_high;
372 };
373 u64 spte;
374};
a9221dd5 375
c2a2ac2b
XG
376static void count_spte_clear(u64 *sptep, u64 spte)
377{
57354682 378 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
c2a2ac2b
XG
379
380 if (is_shadow_present_pte(spte))
381 return;
382
383 /* Ensure the spte is completely set before we increase the count */
384 smp_wmb();
385 sp->clear_spte_count++;
386}
387
603e0651
XG
388static void __set_spte(u64 *sptep, u64 spte)
389{
390 union split_spte *ssptep, sspte;
a9221dd5 391
603e0651
XG
392 ssptep = (union split_spte *)sptep;
393 sspte = (union split_spte)spte;
394
395 ssptep->spte_high = sspte.spte_high;
396
397 /*
398 * If we map the spte from nonpresent to present, We should store
399 * the high bits firstly, then set present bit, so cpu can not
400 * fetch this spte while we are setting the spte.
401 */
402 smp_wmb();
403
b19ee2ff 404 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
a9221dd5
AK
405}
406
603e0651
XG
407static void __update_clear_spte_fast(u64 *sptep, u64 spte)
408{
409 union split_spte *ssptep, sspte;
410
411 ssptep = (union split_spte *)sptep;
412 sspte = (union split_spte)spte;
413
b19ee2ff 414 WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
603e0651
XG
415
416 /*
417 * If we map the spte from present to nonpresent, we should clear
418 * present bit firstly to avoid vcpu fetch the old high bits.
419 */
420 smp_wmb();
421
422 ssptep->spte_high = sspte.spte_high;
c2a2ac2b 423 count_spte_clear(sptep, spte);
603e0651
XG
424}
425
426static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
427{
428 union split_spte *ssptep, sspte, orig;
429
430 ssptep = (union split_spte *)sptep;
431 sspte = (union split_spte)spte;
432
433 /* xchg acts as a barrier before the setting of the high bits */
434 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
41bc3186
ZJ
435 orig.spte_high = ssptep->spte_high;
436 ssptep->spte_high = sspte.spte_high;
c2a2ac2b 437 count_spte_clear(sptep, spte);
603e0651
XG
438
439 return orig.spte;
440}
c2a2ac2b
XG
441
442/*
443 * The idea using the light way get the spte on x86_32 guest is from
39656e83 444 * gup_get_pte (mm/gup.c).
accaefe0
XG
445 *
446 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
447 * coalesces them and we are running out of the MMU lock. Therefore
448 * we need to protect against in-progress updates of the spte.
449 *
450 * Reading the spte while an update is in progress may get the old value
451 * for the high part of the spte. The race is fine for a present->non-present
452 * change (because the high part of the spte is ignored for non-present spte),
453 * but for a present->present change we must reread the spte.
454 *
455 * All such changes are done in two steps (present->non-present and
456 * non-present->present), hence it is enough to count the number of
457 * present->non-present updates: if it changed while reading the spte,
458 * we might have hit the race. This is done using clear_spte_count.
c2a2ac2b
XG
459 */
460static u64 __get_spte_lockless(u64 *sptep)
461{
57354682 462 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
c2a2ac2b
XG
463 union split_spte spte, *orig = (union split_spte *)sptep;
464 int count;
465
466retry:
467 count = sp->clear_spte_count;
468 smp_rmb();
469
470 spte.spte_low = orig->spte_low;
471 smp_rmb();
472
473 spte.spte_high = orig->spte_high;
474 smp_rmb();
475
476 if (unlikely(spte.spte_low != orig->spte_low ||
477 count != sp->clear_spte_count))
478 goto retry;
479
480 return spte.spte;
481}
603e0651
XG
482#endif
483
8672b721
XG
484static bool spte_has_volatile_bits(u64 spte)
485{
f160c7b7
JS
486 if (!is_shadow_present_pte(spte))
487 return false;
488
c7ba5b48 489 /*
6a6256f9 490 * Always atomically update spte if it can be updated
c7ba5b48
XG
491 * out of mmu-lock, it can ensure dirty bit is not lost,
492 * also, it can help us to get a stable is_writable_pte()
493 * to ensure tlb flush is not missed.
494 */
f160c7b7
JS
495 if (spte_can_locklessly_be_made_writable(spte) ||
496 is_access_track_spte(spte))
c7ba5b48
XG
497 return true;
498
ac8d57e5 499 if (spte_ad_enabled(spte)) {
f160c7b7
JS
500 if ((spte & shadow_accessed_mask) == 0 ||
501 (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
502 return true;
503 }
8672b721 504
f160c7b7 505 return false;
8672b721
XG
506}
507
1df9f2dc
XG
508/* Rules for using mmu_spte_set:
509 * Set the sptep from nonpresent to present.
510 * Note: the sptep being assigned *must* be either not present
511 * or in a state where the hardware will not attempt to update
512 * the spte.
513 */
514static void mmu_spte_set(u64 *sptep, u64 new_spte)
515{
516 WARN_ON(is_shadow_present_pte(*sptep));
517 __set_spte(sptep, new_spte);
518}
519
f39a058d
JS
520/*
521 * Update the SPTE (excluding the PFN), but do not track changes in its
522 * accessed/dirty status.
1df9f2dc 523 */
f39a058d 524static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
b79b93f9 525{
c7ba5b48 526 u64 old_spte = *sptep;
4132779b 527
afd28fe1 528 WARN_ON(!is_shadow_present_pte(new_spte));
b79b93f9 529
6e7d0354
XG
530 if (!is_shadow_present_pte(old_spte)) {
531 mmu_spte_set(sptep, new_spte);
f39a058d 532 return old_spte;
6e7d0354 533 }
4132779b 534
c7ba5b48 535 if (!spte_has_volatile_bits(old_spte))
603e0651 536 __update_clear_spte_fast(sptep, new_spte);
4132779b 537 else
603e0651 538 old_spte = __update_clear_spte_slow(sptep, new_spte);
4132779b 539
83ef6c81
JS
540 WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
541
f39a058d
JS
542 return old_spte;
543}
544
545/* Rules for using mmu_spte_update:
546 * Update the state bits, it means the mapped pfn is not changed.
547 *
548 * Whenever we overwrite a writable spte with a read-only one we
549 * should flush remote TLBs. Otherwise rmap_write_protect
550 * will find a read-only spte, even though the writable spte
551 * might be cached on a CPU's TLB, the return value indicates this
552 * case.
553 *
554 * Returns true if the TLB needs to be flushed
555 */
556static bool mmu_spte_update(u64 *sptep, u64 new_spte)
557{
558 bool flush = false;
559 u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
560
561 if (!is_shadow_present_pte(old_spte))
562 return false;
563
c7ba5b48
XG
564 /*
565 * For the spte updated out of mmu-lock is safe, since
6a6256f9 566 * we always atomically update it, see the comments in
c7ba5b48
XG
567 * spte_has_volatile_bits().
568 */
ea4114bc 569 if (spte_can_locklessly_be_made_writable(old_spte) &&
7f31c959 570 !is_writable_pte(new_spte))
83ef6c81 571 flush = true;
4132779b 572
7e71a59b 573 /*
83ef6c81 574 * Flush TLB when accessed/dirty states are changed in the page tables,
7e71a59b
KH
575 * to guarantee consistency between TLB and page tables.
576 */
7e71a59b 577
83ef6c81
JS
578 if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
579 flush = true;
4132779b 580 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
83ef6c81
JS
581 }
582
583 if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
584 flush = true;
4132779b 585 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
83ef6c81 586 }
6e7d0354 587
83ef6c81 588 return flush;
b79b93f9
AK
589}
590
1df9f2dc
XG
591/*
592 * Rules for using mmu_spte_clear_track_bits:
593 * It sets the sptep from present to nonpresent, and track the
594 * state bits, it is used to clear the last level sptep.
7fa2a347 595 * Returns the old PTE.
1df9f2dc 596 */
7fa2a347 597static u64 mmu_spte_clear_track_bits(u64 *sptep)
1df9f2dc 598{
ba049e93 599 kvm_pfn_t pfn;
1df9f2dc
XG
600 u64 old_spte = *sptep;
601
602 if (!spte_has_volatile_bits(old_spte))
603e0651 603 __update_clear_spte_fast(sptep, 0ull);
1df9f2dc 604 else
603e0651 605 old_spte = __update_clear_spte_slow(sptep, 0ull);
1df9f2dc 606
afd28fe1 607 if (!is_shadow_present_pte(old_spte))
7fa2a347 608 return old_spte;
1df9f2dc
XG
609
610 pfn = spte_to_pfn(old_spte);
86fde74c
XG
611
612 /*
613 * KVM does not hold the refcount of the page used by
614 * kvm mmu, before reclaiming the page, we should
615 * unmap it from mmu first.
616 */
bf4bea8e 617 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
86fde74c 618
83ef6c81 619 if (is_accessed_spte(old_spte))
1df9f2dc 620 kvm_set_pfn_accessed(pfn);
83ef6c81
JS
621
622 if (is_dirty_spte(old_spte))
1df9f2dc 623 kvm_set_pfn_dirty(pfn);
83ef6c81 624
7fa2a347 625 return old_spte;
1df9f2dc
XG
626}
627
628/*
629 * Rules for using mmu_spte_clear_no_track:
630 * Directly clear spte without caring the state bits of sptep,
631 * it is used to set the upper level spte.
632 */
633static void mmu_spte_clear_no_track(u64 *sptep)
634{
603e0651 635 __update_clear_spte_fast(sptep, 0ull);
1df9f2dc
XG
636}
637
c2a2ac2b
XG
638static u64 mmu_spte_get_lockless(u64 *sptep)
639{
640 return __get_spte_lockless(sptep);
641}
642
d3e328f2
JS
643/* Restore an acc-track PTE back to a regular PTE */
644static u64 restore_acc_track_spte(u64 spte)
645{
646 u64 new_spte = spte;
8a967d65
PB
647 u64 saved_bits = (spte >> SHADOW_ACC_TRACK_SAVED_BITS_SHIFT)
648 & SHADOW_ACC_TRACK_SAVED_BITS_MASK;
d3e328f2 649
ac8d57e5 650 WARN_ON_ONCE(spte_ad_enabled(spte));
d3e328f2
JS
651 WARN_ON_ONCE(!is_access_track_spte(spte));
652
653 new_spte &= ~shadow_acc_track_mask;
8a967d65
PB
654 new_spte &= ~(SHADOW_ACC_TRACK_SAVED_BITS_MASK <<
655 SHADOW_ACC_TRACK_SAVED_BITS_SHIFT);
d3e328f2
JS
656 new_spte |= saved_bits;
657
658 return new_spte;
659}
660
f160c7b7
JS
661/* Returns the Accessed status of the PTE and resets it at the same time. */
662static bool mmu_spte_age(u64 *sptep)
663{
664 u64 spte = mmu_spte_get_lockless(sptep);
665
666 if (!is_accessed_spte(spte))
667 return false;
668
ac8d57e5 669 if (spte_ad_enabled(spte)) {
f160c7b7
JS
670 clear_bit((ffs(shadow_accessed_mask) - 1),
671 (unsigned long *)sptep);
672 } else {
673 /*
674 * Capture the dirty status of the page, so that it doesn't get
675 * lost when the SPTE is marked for access tracking.
676 */
677 if (is_writable_pte(spte))
678 kvm_set_pfn_dirty(spte_to_pfn(spte));
679
680 spte = mark_spte_for_access_track(spte);
681 mmu_spte_update_no_track(sptep, spte);
682 }
683
684 return true;
685}
686
c2a2ac2b
XG
687static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
688{
c142786c
AK
689 /*
690 * Prevent page table teardown by making any free-er wait during
691 * kvm_flush_remote_tlbs() IPI to all active vcpus.
692 */
693 local_irq_disable();
36ca7e0a 694
c142786c
AK
695 /*
696 * Make sure a following spte read is not reordered ahead of the write
697 * to vcpu->mode.
698 */
36ca7e0a 699 smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
c2a2ac2b
XG
700}
701
702static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
703{
c142786c
AK
704 /*
705 * Make sure the write to vcpu->mode is not reordered in front of
9a984586 706 * reads to sptes. If it does, kvm_mmu_commit_zap_page() can see us
c142786c
AK
707 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
708 */
36ca7e0a 709 smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
c142786c 710 local_irq_enable();
c2a2ac2b
XG
711}
712
378f5cd6 713static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
714b93da 714{
e2dec939
AK
715 int r;
716
531281ad 717 /* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
94ce87ef
SC
718 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
719 1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
d3d25b04 720 if (r)
284aa868 721 return r;
94ce87ef
SC
722 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
723 PT64_ROOT_MAX_LEVEL);
d3d25b04 724 if (r)
171a90d7 725 return r;
378f5cd6 726 if (maybe_indirect) {
94ce87ef
SC
727 r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_gfn_array_cache,
728 PT64_ROOT_MAX_LEVEL);
378f5cd6
SC
729 if (r)
730 return r;
731 }
94ce87ef
SC
732 return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
733 PT64_ROOT_MAX_LEVEL);
714b93da
AK
734}
735
736static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
737{
94ce87ef
SC
738 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
739 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
740 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
741 kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
714b93da
AK
742}
743
53c07b18 744static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
714b93da 745{
94ce87ef 746 return kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
714b93da
AK
747}
748
53c07b18 749static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
714b93da 750{
53c07b18 751 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
714b93da
AK
752}
753
2032a93d
LJ
754static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
755{
756 if (!sp->role.direct)
757 return sp->gfns[index];
758
759 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
760}
761
762static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
763{
e9f2a760 764 if (!sp->role.direct) {
2032a93d 765 sp->gfns[index] = gfn;
e9f2a760
PB
766 return;
767 }
768
769 if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
770 pr_err_ratelimited("gfn mismatch under direct page %llx "
771 "(expected %llx, got %llx)\n",
772 sp->gfn,
773 kvm_mmu_page_get_gfn(sp, index), gfn);
2032a93d
LJ
774}
775
05da4558 776/*
d4dbf470
TY
777 * Return the pointer to the large page information for a given gfn,
778 * handling slots that are not large page aligned.
05da4558 779 */
d4dbf470 780static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
8ca6f063 781 const struct kvm_memory_slot *slot, int level)
05da4558
MT
782{
783 unsigned long idx;
784
fb03cb6f 785 idx = gfn_to_index(gfn, slot->base_gfn, level);
db3fe4eb 786 return &slot->arch.lpage_info[level - 2][idx];
05da4558
MT
787}
788
547ffaed
XG
789static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
790 gfn_t gfn, int count)
791{
792 struct kvm_lpage_info *linfo;
793 int i;
794
3bae0459 795 for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
547ffaed
XG
796 linfo = lpage_info_slot(gfn, slot, i);
797 linfo->disallow_lpage += count;
798 WARN_ON(linfo->disallow_lpage < 0);
799 }
800}
801
802void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
803{
804 update_gfn_disallow_lpage_count(slot, gfn, 1);
805}
806
807void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
808{
809 update_gfn_disallow_lpage_count(slot, gfn, -1);
810}
811
3ed1a478 812static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
05da4558 813{
699023e2 814 struct kvm_memslots *slots;
d25797b2 815 struct kvm_memory_slot *slot;
3ed1a478 816 gfn_t gfn;
05da4558 817
56ca57f9 818 kvm->arch.indirect_shadow_pages++;
3ed1a478 819 gfn = sp->gfn;
699023e2
PB
820 slots = kvm_memslots_for_spte_role(kvm, sp->role);
821 slot = __gfn_to_memslot(slots, gfn);
56ca57f9
XG
822
823 /* the non-leaf shadow pages are keeping readonly. */
3bae0459 824 if (sp->role.level > PG_LEVEL_4K)
56ca57f9
XG
825 return kvm_slot_page_track_add_page(kvm, slot, gfn,
826 KVM_PAGE_TRACK_WRITE);
827
547ffaed 828 kvm_mmu_gfn_disallow_lpage(slot, gfn);
05da4558
MT
829}
830
29cf0f50 831void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
b8e8c830
PB
832{
833 if (sp->lpage_disallowed)
834 return;
835
836 ++kvm->stat.nx_lpage_splits;
1aa9b957
JS
837 list_add_tail(&sp->lpage_disallowed_link,
838 &kvm->arch.lpage_disallowed_mmu_pages);
b8e8c830
PB
839 sp->lpage_disallowed = true;
840}
841
3ed1a478 842static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
05da4558 843{
699023e2 844 struct kvm_memslots *slots;
d25797b2 845 struct kvm_memory_slot *slot;
3ed1a478 846 gfn_t gfn;
05da4558 847
56ca57f9 848 kvm->arch.indirect_shadow_pages--;
3ed1a478 849 gfn = sp->gfn;
699023e2
PB
850 slots = kvm_memslots_for_spte_role(kvm, sp->role);
851 slot = __gfn_to_memslot(slots, gfn);
3bae0459 852 if (sp->role.level > PG_LEVEL_4K)
56ca57f9
XG
853 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
854 KVM_PAGE_TRACK_WRITE);
855
547ffaed 856 kvm_mmu_gfn_allow_lpage(slot, gfn);
05da4558
MT
857}
858
29cf0f50 859void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
b8e8c830
PB
860{
861 --kvm->stat.nx_lpage_splits;
862 sp->lpage_disallowed = false;
1aa9b957 863 list_del(&sp->lpage_disallowed_link);
b8e8c830
PB
864}
865
5d163b1c
XG
866static struct kvm_memory_slot *
867gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
868 bool no_dirty_log)
05da4558
MT
869{
870 struct kvm_memory_slot *slot;
5d163b1c 871
54bf36aa 872 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
91b0d268
PB
873 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
874 return NULL;
044c59c4 875 if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
91b0d268 876 return NULL;
5d163b1c
XG
877
878 return slot;
879}
880
290fc38d 881/*
018aabb5 882 * About rmap_head encoding:
cd4a4e53 883 *
018aabb5
TY
884 * If the bit zero of rmap_head->val is clear, then it points to the only spte
885 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
53c07b18 886 * pte_list_desc containing more mappings.
018aabb5
TY
887 */
888
889/*
890 * Returns the number of pointers in the rmap chain, not counting the new one.
cd4a4e53 891 */
53c07b18 892static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
018aabb5 893 struct kvm_rmap_head *rmap_head)
cd4a4e53 894{
53c07b18 895 struct pte_list_desc *desc;
53a27b39 896 int i, count = 0;
cd4a4e53 897
018aabb5 898 if (!rmap_head->val) {
805a0f83 899 rmap_printk("%p %llx 0->1\n", spte, *spte);
018aabb5
TY
900 rmap_head->val = (unsigned long)spte;
901 } else if (!(rmap_head->val & 1)) {
805a0f83 902 rmap_printk("%p %llx 1->many\n", spte, *spte);
53c07b18 903 desc = mmu_alloc_pte_list_desc(vcpu);
018aabb5 904 desc->sptes[0] = (u64 *)rmap_head->val;
d555c333 905 desc->sptes[1] = spte;
018aabb5 906 rmap_head->val = (unsigned long)desc | 1;
cb16a7b3 907 ++count;
cd4a4e53 908 } else {
805a0f83 909 rmap_printk("%p %llx many->many\n", spte, *spte);
018aabb5 910 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
c6c4f961 911 while (desc->sptes[PTE_LIST_EXT-1]) {
53c07b18 912 count += PTE_LIST_EXT;
c6c4f961
LR
913
914 if (!desc->more) {
915 desc->more = mmu_alloc_pte_list_desc(vcpu);
916 desc = desc->more;
917 break;
918 }
cd4a4e53
AK
919 desc = desc->more;
920 }
d555c333 921 for (i = 0; desc->sptes[i]; ++i)
cb16a7b3 922 ++count;
d555c333 923 desc->sptes[i] = spte;
cd4a4e53 924 }
53a27b39 925 return count;
cd4a4e53
AK
926}
927
53c07b18 928static void
018aabb5
TY
929pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
930 struct pte_list_desc *desc, int i,
931 struct pte_list_desc *prev_desc)
cd4a4e53
AK
932{
933 int j;
934
53c07b18 935 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
cd4a4e53 936 ;
d555c333
AK
937 desc->sptes[i] = desc->sptes[j];
938 desc->sptes[j] = NULL;
cd4a4e53
AK
939 if (j != 0)
940 return;
941 if (!prev_desc && !desc->more)
fe3c2b4c 942 rmap_head->val = 0;
cd4a4e53
AK
943 else
944 if (prev_desc)
945 prev_desc->more = desc->more;
946 else
018aabb5 947 rmap_head->val = (unsigned long)desc->more | 1;
53c07b18 948 mmu_free_pte_list_desc(desc);
cd4a4e53
AK
949}
950
8daf3462 951static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
cd4a4e53 952{
53c07b18
XG
953 struct pte_list_desc *desc;
954 struct pte_list_desc *prev_desc;
cd4a4e53
AK
955 int i;
956
018aabb5 957 if (!rmap_head->val) {
8daf3462 958 pr_err("%s: %p 0->BUG\n", __func__, spte);
cd4a4e53 959 BUG();
018aabb5 960 } else if (!(rmap_head->val & 1)) {
805a0f83 961 rmap_printk("%p 1->0\n", spte);
018aabb5 962 if ((u64 *)rmap_head->val != spte) {
8daf3462 963 pr_err("%s: %p 1->BUG\n", __func__, spte);
cd4a4e53
AK
964 BUG();
965 }
018aabb5 966 rmap_head->val = 0;
cd4a4e53 967 } else {
805a0f83 968 rmap_printk("%p many->many\n", spte);
018aabb5 969 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
cd4a4e53
AK
970 prev_desc = NULL;
971 while (desc) {
018aabb5 972 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
d555c333 973 if (desc->sptes[i] == spte) {
018aabb5
TY
974 pte_list_desc_remove_entry(rmap_head,
975 desc, i, prev_desc);
cd4a4e53
AK
976 return;
977 }
018aabb5 978 }
cd4a4e53
AK
979 prev_desc = desc;
980 desc = desc->more;
981 }
8daf3462 982 pr_err("%s: %p many->many\n", __func__, spte);
cd4a4e53
AK
983 BUG();
984 }
985}
986
e7912386
WY
987static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
988{
989 mmu_spte_clear_track_bits(sptep);
990 __pte_list_remove(sptep, rmap_head);
991}
992
018aabb5
TY
993static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
994 struct kvm_memory_slot *slot)
53c07b18 995{
77d11309 996 unsigned long idx;
53c07b18 997
77d11309 998 idx = gfn_to_index(gfn, slot->base_gfn, level);
3bae0459 999 return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
53c07b18
XG
1000}
1001
018aabb5
TY
1002static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1003 struct kvm_mmu_page *sp)
9b9b1492 1004{
699023e2 1005 struct kvm_memslots *slots;
9b9b1492
TY
1006 struct kvm_memory_slot *slot;
1007
699023e2
PB
1008 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1009 slot = __gfn_to_memslot(slots, gfn);
e4cd1da9 1010 return __gfn_to_rmap(gfn, sp->role.level, slot);
9b9b1492
TY
1011}
1012
f759e2b4
XG
1013static bool rmap_can_add(struct kvm_vcpu *vcpu)
1014{
356ec69a 1015 struct kvm_mmu_memory_cache *mc;
f759e2b4 1016
356ec69a 1017 mc = &vcpu->arch.mmu_pte_list_desc_cache;
94ce87ef 1018 return kvm_mmu_memory_cache_nr_free_objects(mc);
f759e2b4
XG
1019}
1020
53c07b18
XG
1021static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1022{
1023 struct kvm_mmu_page *sp;
018aabb5 1024 struct kvm_rmap_head *rmap_head;
53c07b18 1025
57354682 1026 sp = sptep_to_sp(spte);
53c07b18 1027 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
018aabb5
TY
1028 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1029 return pte_list_add(vcpu, spte, rmap_head);
53c07b18
XG
1030}
1031
53c07b18
XG
1032static void rmap_remove(struct kvm *kvm, u64 *spte)
1033{
1034 struct kvm_mmu_page *sp;
1035 gfn_t gfn;
018aabb5 1036 struct kvm_rmap_head *rmap_head;
53c07b18 1037
57354682 1038 sp = sptep_to_sp(spte);
53c07b18 1039 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
018aabb5 1040 rmap_head = gfn_to_rmap(kvm, gfn, sp);
8daf3462 1041 __pte_list_remove(spte, rmap_head);
53c07b18
XG
1042}
1043
1e3f42f0
TY
1044/*
1045 * Used by the following functions to iterate through the sptes linked by a
1046 * rmap. All fields are private and not assumed to be used outside.
1047 */
1048struct rmap_iterator {
1049 /* private fields */
1050 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1051 int pos; /* index of the sptep */
1052};
1053
1054/*
1055 * Iteration must be started by this function. This should also be used after
1056 * removing/dropping sptes from the rmap link because in such cases the
0a03cbda 1057 * information in the iterator may not be valid.
1e3f42f0
TY
1058 *
1059 * Returns sptep if found, NULL otherwise.
1060 */
018aabb5
TY
1061static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1062 struct rmap_iterator *iter)
1e3f42f0 1063{
77fbbbd2
TY
1064 u64 *sptep;
1065
018aabb5 1066 if (!rmap_head->val)
1e3f42f0
TY
1067 return NULL;
1068
018aabb5 1069 if (!(rmap_head->val & 1)) {
1e3f42f0 1070 iter->desc = NULL;
77fbbbd2
TY
1071 sptep = (u64 *)rmap_head->val;
1072 goto out;
1e3f42f0
TY
1073 }
1074
018aabb5 1075 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1e3f42f0 1076 iter->pos = 0;
77fbbbd2
TY
1077 sptep = iter->desc->sptes[iter->pos];
1078out:
1079 BUG_ON(!is_shadow_present_pte(*sptep));
1080 return sptep;
1e3f42f0
TY
1081}
1082
1083/*
1084 * Must be used with a valid iterator: e.g. after rmap_get_first().
1085 *
1086 * Returns sptep if found, NULL otherwise.
1087 */
1088static u64 *rmap_get_next(struct rmap_iterator *iter)
1089{
77fbbbd2
TY
1090 u64 *sptep;
1091
1e3f42f0
TY
1092 if (iter->desc) {
1093 if (iter->pos < PTE_LIST_EXT - 1) {
1e3f42f0
TY
1094 ++iter->pos;
1095 sptep = iter->desc->sptes[iter->pos];
1096 if (sptep)
77fbbbd2 1097 goto out;
1e3f42f0
TY
1098 }
1099
1100 iter->desc = iter->desc->more;
1101
1102 if (iter->desc) {
1103 iter->pos = 0;
1104 /* desc->sptes[0] cannot be NULL */
77fbbbd2
TY
1105 sptep = iter->desc->sptes[iter->pos];
1106 goto out;
1e3f42f0
TY
1107 }
1108 }
1109
1110 return NULL;
77fbbbd2
TY
1111out:
1112 BUG_ON(!is_shadow_present_pte(*sptep));
1113 return sptep;
1e3f42f0
TY
1114}
1115
018aabb5
TY
1116#define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1117 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
77fbbbd2 1118 _spte_; _spte_ = rmap_get_next(_iter_))
0d536790 1119
c3707958 1120static void drop_spte(struct kvm *kvm, u64 *sptep)
e4b502ea 1121{
7fa2a347
SC
1122 u64 old_spte = mmu_spte_clear_track_bits(sptep);
1123
1124 if (is_shadow_present_pte(old_spte))
eb45fda4 1125 rmap_remove(kvm, sptep);
be38d276
AK
1126}
1127
8e22f955
XG
1128
1129static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1130{
1131 if (is_large_pte(*sptep)) {
57354682 1132 WARN_ON(sptep_to_sp(sptep)->role.level == PG_LEVEL_4K);
8e22f955
XG
1133 drop_spte(kvm, sptep);
1134 --kvm->stat.lpages;
1135 return true;
1136 }
1137
1138 return false;
1139}
1140
1141static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1142{
c3134ce2 1143 if (__drop_large_spte(vcpu->kvm, sptep)) {
57354682 1144 struct kvm_mmu_page *sp = sptep_to_sp(sptep);
c3134ce2
LT
1145
1146 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1147 KVM_PAGES_PER_HPAGE(sp->role.level));
1148 }
8e22f955
XG
1149}
1150
1151/*
49fde340 1152 * Write-protect on the specified @sptep, @pt_protect indicates whether
c126d94f 1153 * spte write-protection is caused by protecting shadow page table.
49fde340 1154 *
b4619660 1155 * Note: write protection is difference between dirty logging and spte
49fde340
XG
1156 * protection:
1157 * - for dirty logging, the spte can be set to writable at anytime if
1158 * its dirty bitmap is properly set.
1159 * - for spte protection, the spte can be writable only after unsync-ing
1160 * shadow page.
8e22f955 1161 *
c126d94f 1162 * Return true if tlb need be flushed.
8e22f955 1163 */
c4f138b4 1164static bool spte_write_protect(u64 *sptep, bool pt_protect)
d13bc5b5
XG
1165{
1166 u64 spte = *sptep;
1167
49fde340 1168 if (!is_writable_pte(spte) &&
ea4114bc 1169 !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
d13bc5b5
XG
1170 return false;
1171
805a0f83 1172 rmap_printk("spte %p %llx\n", sptep, *sptep);
d13bc5b5 1173
49fde340 1174 if (pt_protect)
5fc3424f 1175 spte &= ~shadow_mmu_writable_mask;
d13bc5b5 1176 spte = spte & ~PT_WRITABLE_MASK;
49fde340 1177
c126d94f 1178 return mmu_spte_update(sptep, spte);
d13bc5b5
XG
1179}
1180
018aabb5
TY
1181static bool __rmap_write_protect(struct kvm *kvm,
1182 struct kvm_rmap_head *rmap_head,
245c3912 1183 bool pt_protect)
98348e95 1184{
1e3f42f0
TY
1185 u64 *sptep;
1186 struct rmap_iterator iter;
d13bc5b5 1187 bool flush = false;
374cbac0 1188
018aabb5 1189 for_each_rmap_spte(rmap_head, &iter, sptep)
c4f138b4 1190 flush |= spte_write_protect(sptep, pt_protect);
855149aa 1191
d13bc5b5 1192 return flush;
a0ed4607
TY
1193}
1194
c4f138b4 1195static bool spte_clear_dirty(u64 *sptep)
f4b4b180
KH
1196{
1197 u64 spte = *sptep;
1198
805a0f83 1199 rmap_printk("spte %p %llx\n", sptep, *sptep);
f4b4b180 1200
1f4e5fc8 1201 MMU_WARN_ON(!spte_ad_enabled(spte));
f4b4b180 1202 spte &= ~shadow_dirty_mask;
f4b4b180
KH
1203 return mmu_spte_update(sptep, spte);
1204}
1205
1f4e5fc8 1206static bool spte_wrprot_for_clear_dirty(u64 *sptep)
ac8d57e5
PF
1207{
1208 bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1209 (unsigned long *)sptep);
1f4e5fc8 1210 if (was_writable && !spte_ad_enabled(*sptep))
ac8d57e5
PF
1211 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1212
1213 return was_writable;
1214}
1215
1216/*
1217 * Gets the GFN ready for another round of dirty logging by clearing the
1218 * - D bit on ad-enabled SPTEs, and
1219 * - W bit on ad-disabled SPTEs.
1220 * Returns true iff any D or W bits were cleared.
1221 */
0a234f5d
SC
1222static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1223 struct kvm_memory_slot *slot)
f4b4b180
KH
1224{
1225 u64 *sptep;
1226 struct rmap_iterator iter;
1227 bool flush = false;
1228
018aabb5 1229 for_each_rmap_spte(rmap_head, &iter, sptep)
1f4e5fc8
PB
1230 if (spte_ad_need_write_protect(*sptep))
1231 flush |= spte_wrprot_for_clear_dirty(sptep);
ac8d57e5 1232 else
1f4e5fc8 1233 flush |= spte_clear_dirty(sptep);
f4b4b180
KH
1234
1235 return flush;
1236}
1237
5dc99b23 1238/**
3b0f1d01 1239 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
5dc99b23
TY
1240 * @kvm: kvm instance
1241 * @slot: slot to protect
1242 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1243 * @mask: indicates which pages we should protect
1244 *
89212919 1245 * Used when we do not need to care about huge page mappings.
5dc99b23 1246 */
3b0f1d01 1247static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
5dc99b23
TY
1248 struct kvm_memory_slot *slot,
1249 gfn_t gfn_offset, unsigned long mask)
a0ed4607 1250{
018aabb5 1251 struct kvm_rmap_head *rmap_head;
a0ed4607 1252
897218ff 1253 if (is_tdp_mmu_enabled(kvm))
a6a0b05d
BG
1254 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1255 slot->base_gfn + gfn_offset, mask, true);
e2209710
BG
1256
1257 if (!kvm_memslots_have_rmaps(kvm))
1258 return;
1259
5dc99b23 1260 while (mask) {
018aabb5 1261 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
3bae0459 1262 PG_LEVEL_4K, slot);
018aabb5 1263 __rmap_write_protect(kvm, rmap_head, false);
05da4558 1264
5dc99b23
TY
1265 /* clear the first set bit */
1266 mask &= mask - 1;
1267 }
374cbac0
AK
1268}
1269
f4b4b180 1270/**
ac8d57e5
PF
1271 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1272 * protect the page if the D-bit isn't supported.
f4b4b180
KH
1273 * @kvm: kvm instance
1274 * @slot: slot to clear D-bit
1275 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1276 * @mask: indicates which pages we should clear D-bit
1277 *
1278 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1279 */
a018eba5
SC
1280static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1281 struct kvm_memory_slot *slot,
1282 gfn_t gfn_offset, unsigned long mask)
f4b4b180 1283{
018aabb5 1284 struct kvm_rmap_head *rmap_head;
f4b4b180 1285
897218ff 1286 if (is_tdp_mmu_enabled(kvm))
a6a0b05d
BG
1287 kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1288 slot->base_gfn + gfn_offset, mask, false);
e2209710
BG
1289
1290 if (!kvm_memslots_have_rmaps(kvm))
1291 return;
1292
f4b4b180 1293 while (mask) {
018aabb5 1294 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
3bae0459 1295 PG_LEVEL_4K, slot);
0a234f5d 1296 __rmap_clear_dirty(kvm, rmap_head, slot);
f4b4b180
KH
1297
1298 /* clear the first set bit */
1299 mask &= mask - 1;
1300 }
1301}
f4b4b180 1302
3b0f1d01
KH
1303/**
1304 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1305 * PT level pages.
1306 *
1307 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1308 * enable dirty logging for them.
1309 *
89212919
KZ
1310 * We need to care about huge page mappings: e.g. during dirty logging we may
1311 * have such mappings.
3b0f1d01
KH
1312 */
1313void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1314 struct kvm_memory_slot *slot,
1315 gfn_t gfn_offset, unsigned long mask)
1316{
89212919
KZ
1317 /*
1318 * Huge pages are NOT write protected when we start dirty logging in
1319 * initially-all-set mode; must write protect them here so that they
1320 * are split to 4K on the first write.
1321 *
1322 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
1323 * of memslot has no such restriction, so the range can cross two large
1324 * pages.
1325 */
1326 if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1327 gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
1328 gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
1329
1330 kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
1331
1332 /* Cross two large pages? */
1333 if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
1334 ALIGN(end << PAGE_SHIFT, PMD_SIZE))
1335 kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
1336 PG_LEVEL_2M);
1337 }
1338
1339 /* Now handle 4K PTEs. */
a018eba5
SC
1340 if (kvm_x86_ops.cpu_dirty_log_size)
1341 kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
88178fd4
KH
1342 else
1343 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
3b0f1d01
KH
1344}
1345
fb04a1ed
PX
1346int kvm_cpu_dirty_log_size(void)
1347{
6dd03800 1348 return kvm_x86_ops.cpu_dirty_log_size;
fb04a1ed
PX
1349}
1350
aeecee2e 1351bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
3ad93562
KZ
1352 struct kvm_memory_slot *slot, u64 gfn,
1353 int min_level)
95d4c16c 1354{
018aabb5 1355 struct kvm_rmap_head *rmap_head;
5dc99b23 1356 int i;
2f84569f 1357 bool write_protected = false;
95d4c16c 1358
e2209710
BG
1359 if (kvm_memslots_have_rmaps(kvm)) {
1360 for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1361 rmap_head = __gfn_to_rmap(gfn, i, slot);
1362 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1363 }
5dc99b23
TY
1364 }
1365
897218ff 1366 if (is_tdp_mmu_enabled(kvm))
46044f72 1367 write_protected |=
3ad93562 1368 kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
46044f72 1369
5dc99b23 1370 return write_protected;
95d4c16c
TY
1371}
1372
aeecee2e
XG
1373static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1374{
1375 struct kvm_memory_slot *slot;
1376
1377 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3ad93562 1378 return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
aeecee2e
XG
1379}
1380
0a234f5d
SC
1381static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1382 struct kvm_memory_slot *slot)
e930bffe 1383{
1e3f42f0
TY
1384 u64 *sptep;
1385 struct rmap_iterator iter;
6a49f85c 1386 bool flush = false;
e930bffe 1387
018aabb5 1388 while ((sptep = rmap_get_first(rmap_head, &iter))) {
805a0f83 1389 rmap_printk("spte %p %llx.\n", sptep, *sptep);
1e3f42f0 1390
e7912386 1391 pte_list_remove(rmap_head, sptep);
6a49f85c 1392 flush = true;
e930bffe 1393 }
1e3f42f0 1394
6a49f85c
XG
1395 return flush;
1396}
1397
3039bcc7
SC
1398static bool kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1399 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1400 pte_t unused)
6a49f85c 1401{
0a234f5d 1402 return kvm_zap_rmapp(kvm, rmap_head, slot);
e930bffe
AA
1403}
1404
3039bcc7
SC
1405static bool kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1406 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1407 pte_t pte)
3da0dd43 1408{
1e3f42f0
TY
1409 u64 *sptep;
1410 struct rmap_iterator iter;
3da0dd43 1411 int need_flush = 0;
1e3f42f0 1412 u64 new_spte;
ba049e93 1413 kvm_pfn_t new_pfn;
3da0dd43 1414
3039bcc7
SC
1415 WARN_ON(pte_huge(pte));
1416 new_pfn = pte_pfn(pte);
1e3f42f0 1417
0d536790 1418restart:
018aabb5 1419 for_each_rmap_spte(rmap_head, &iter, sptep) {
805a0f83 1420 rmap_printk("spte %p %llx gfn %llx (%d)\n",
f160c7b7 1421 sptep, *sptep, gfn, level);
1e3f42f0 1422
3da0dd43 1423 need_flush = 1;
1e3f42f0 1424
3039bcc7 1425 if (pte_write(pte)) {
e7912386 1426 pte_list_remove(rmap_head, sptep);
0d536790 1427 goto restart;
3da0dd43 1428 } else {
cb3eedab
PB
1429 new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1430 *sptep, new_pfn);
1e3f42f0
TY
1431
1432 mmu_spte_clear_track_bits(sptep);
1433 mmu_spte_set(sptep, new_spte);
3da0dd43
IE
1434 }
1435 }
1e3f42f0 1436
3cc5ea94
LT
1437 if (need_flush && kvm_available_flush_tlb_with_range()) {
1438 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1439 return 0;
1440 }
1441
0cf853c5 1442 return need_flush;
3da0dd43
IE
1443}
1444
6ce1f4e2
XG
1445struct slot_rmap_walk_iterator {
1446 /* input fields. */
1447 struct kvm_memory_slot *slot;
1448 gfn_t start_gfn;
1449 gfn_t end_gfn;
1450 int start_level;
1451 int end_level;
1452
1453 /* output fields. */
1454 gfn_t gfn;
018aabb5 1455 struct kvm_rmap_head *rmap;
6ce1f4e2
XG
1456 int level;
1457
1458 /* private field. */
018aabb5 1459 struct kvm_rmap_head *end_rmap;
6ce1f4e2
XG
1460};
1461
1462static void
1463rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1464{
1465 iterator->level = level;
1466 iterator->gfn = iterator->start_gfn;
1467 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1468 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1469 iterator->slot);
1470}
1471
1472static void
1473slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1474 struct kvm_memory_slot *slot, int start_level,
1475 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1476{
1477 iterator->slot = slot;
1478 iterator->start_level = start_level;
1479 iterator->end_level = end_level;
1480 iterator->start_gfn = start_gfn;
1481 iterator->end_gfn = end_gfn;
1482
1483 rmap_walk_init_level(iterator, iterator->start_level);
1484}
1485
1486static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1487{
1488 return !!iterator->rmap;
1489}
1490
1491static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1492{
1493 if (++iterator->rmap <= iterator->end_rmap) {
1494 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1495 return;
1496 }
1497
1498 if (++iterator->level > iterator->end_level) {
1499 iterator->rmap = NULL;
1500 return;
1501 }
1502
1503 rmap_walk_init_level(iterator, iterator->level);
1504}
1505
1506#define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1507 _start_gfn, _end_gfn, _iter_) \
1508 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1509 _end_level_, _start_gfn, _end_gfn); \
1510 slot_rmap_walk_okay(_iter_); \
1511 slot_rmap_walk_next(_iter_))
1512
3039bcc7
SC
1513typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1514 struct kvm_memory_slot *slot, gfn_t gfn,
1515 int level, pte_t pte);
c1b91493 1516
3039bcc7
SC
1517static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
1518 struct kvm_gfn_range *range,
1519 rmap_handler_t handler)
e930bffe 1520{
6ce1f4e2 1521 struct slot_rmap_walk_iterator iterator;
3039bcc7 1522 bool ret = false;
e930bffe 1523
3039bcc7
SC
1524 for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1525 range->start, range->end - 1, &iterator)
1526 ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
1527 iterator.level, range->pte);
e930bffe 1528
f395302e 1529 return ret;
e930bffe
AA
1530}
1531
3039bcc7 1532bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
84504ef3 1533{
e2209710 1534 bool flush = false;
063afacd 1535
e2209710
BG
1536 if (kvm_memslots_have_rmaps(kvm))
1537 flush = kvm_handle_gfn_range(kvm, range, kvm_unmap_rmapp);
063afacd 1538
897218ff 1539 if (is_tdp_mmu_enabled(kvm))
3039bcc7 1540 flush |= kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
063afacd 1541
3039bcc7 1542 return flush;
b3ae2096
TY
1543}
1544
3039bcc7 1545bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
3da0dd43 1546{
e2209710 1547 bool flush = false;
1d8dd6b3 1548
e2209710
BG
1549 if (kvm_memslots_have_rmaps(kvm))
1550 flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmapp);
1d8dd6b3 1551
897218ff 1552 if (is_tdp_mmu_enabled(kvm))
3039bcc7 1553 flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
1d8dd6b3 1554
3039bcc7 1555 return flush;
e930bffe
AA
1556}
1557
3039bcc7
SC
1558static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1559 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1560 pte_t unused)
e930bffe 1561{
1e3f42f0 1562 u64 *sptep;
3f649ab7 1563 struct rmap_iterator iter;
e930bffe
AA
1564 int young = 0;
1565
f160c7b7
JS
1566 for_each_rmap_spte(rmap_head, &iter, sptep)
1567 young |= mmu_spte_age(sptep);
0d536790 1568
e930bffe
AA
1569 return young;
1570}
1571
3039bcc7
SC
1572static bool kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1573 struct kvm_memory_slot *slot, gfn_t gfn,
1574 int level, pte_t unused)
8ee53820 1575{
1e3f42f0
TY
1576 u64 *sptep;
1577 struct rmap_iterator iter;
8ee53820 1578
83ef6c81
JS
1579 for_each_rmap_spte(rmap_head, &iter, sptep)
1580 if (is_accessed_spte(*sptep))
1581 return 1;
83ef6c81 1582 return 0;
8ee53820
AA
1583}
1584
53a27b39
MT
1585#define RMAP_RECYCLE_THRESHOLD 1000
1586
852e3c19 1587static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
53a27b39 1588{
018aabb5 1589 struct kvm_rmap_head *rmap_head;
852e3c19
JR
1590 struct kvm_mmu_page *sp;
1591
57354682 1592 sp = sptep_to_sp(spte);
53a27b39 1593
018aabb5 1594 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
53a27b39 1595
3039bcc7 1596 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, __pte(0));
c3134ce2
LT
1597 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1598 KVM_PAGES_PER_HPAGE(sp->role.level));
53a27b39
MT
1599}
1600
3039bcc7 1601bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
e930bffe 1602{
e2209710 1603 bool young = false;
3039bcc7 1604
e2209710
BG
1605 if (kvm_memslots_have_rmaps(kvm))
1606 young = kvm_handle_gfn_range(kvm, range, kvm_age_rmapp);
f8e14497 1607
897218ff 1608 if (is_tdp_mmu_enabled(kvm))
3039bcc7 1609 young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
f8e14497
BG
1610
1611 return young;
e930bffe
AA
1612}
1613
3039bcc7 1614bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
8ee53820 1615{
e2209710 1616 bool young = false;
3039bcc7 1617
e2209710
BG
1618 if (kvm_memslots_have_rmaps(kvm))
1619 young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmapp);
f8e14497 1620
897218ff 1621 if (is_tdp_mmu_enabled(kvm))
3039bcc7 1622 young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
f8e14497
BG
1623
1624 return young;
8ee53820
AA
1625}
1626
d6c69ee9 1627#ifdef MMU_DEBUG
47ad8e68 1628static int is_empty_shadow_page(u64 *spt)
6aa8b732 1629{
139bdb2d
AK
1630 u64 *pos;
1631 u64 *end;
1632
47ad8e68 1633 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
3c915510 1634 if (is_shadow_present_pte(*pos)) {
b8688d51 1635 printk(KERN_ERR "%s: %p %llx\n", __func__,
139bdb2d 1636 pos, *pos);
6aa8b732 1637 return 0;
139bdb2d 1638 }
6aa8b732
AK
1639 return 1;
1640}
d6c69ee9 1641#endif
6aa8b732 1642
45221ab6
DH
1643/*
1644 * This value is the sum of all of the kvm instances's
1645 * kvm->arch.n_used_mmu_pages values. We need a global,
1646 * aggregate version in order to make the slab shrinker
1647 * faster
1648 */
bc8a3d89 1649static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
45221ab6
DH
1650{
1651 kvm->arch.n_used_mmu_pages += nr;
1652 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1653}
1654
834be0d8 1655static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
260746c0 1656{
fa4a2c08 1657 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
7775834a 1658 hlist_del(&sp->hash_link);
bd4c86ea
XG
1659 list_del(&sp->link);
1660 free_page((unsigned long)sp->spt);
834be0d8
GN
1661 if (!sp->role.direct)
1662 free_page((unsigned long)sp->gfns);
e8ad9a70 1663 kmem_cache_free(mmu_page_header_cache, sp);
260746c0
AK
1664}
1665
cea0f0e7
AK
1666static unsigned kvm_page_table_hashfn(gfn_t gfn)
1667{
114df303 1668 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
cea0f0e7
AK
1669}
1670
714b93da 1671static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
4db35314 1672 struct kvm_mmu_page *sp, u64 *parent_pte)
cea0f0e7 1673{
cea0f0e7
AK
1674 if (!parent_pte)
1675 return;
cea0f0e7 1676
67052b35 1677 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
cea0f0e7
AK
1678}
1679
4db35314 1680static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
cea0f0e7
AK
1681 u64 *parent_pte)
1682{
8daf3462 1683 __pte_list_remove(parent_pte, &sp->parent_ptes);
cea0f0e7
AK
1684}
1685
bcdd9a93
XG
1686static void drop_parent_pte(struct kvm_mmu_page *sp,
1687 u64 *parent_pte)
1688{
1689 mmu_page_remove_parent_pte(sp, parent_pte);
1df9f2dc 1690 mmu_spte_clear_no_track(parent_pte);
bcdd9a93
XG
1691}
1692
47005792 1693static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
ad8cfbe3 1694{
67052b35 1695 struct kvm_mmu_page *sp;
7ddca7e4 1696
94ce87ef
SC
1697 sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
1698 sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
67052b35 1699 if (!direct)
94ce87ef 1700 sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
67052b35 1701 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
002c5f73
SC
1702
1703 /*
1704 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
1705 * depends on valid pages being added to the head of the list. See
1706 * comments in kvm_zap_obsolete_pages().
1707 */
ca333add 1708 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
67052b35 1709 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
67052b35
XG
1710 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1711 return sp;
ad8cfbe3
MT
1712}
1713
67052b35 1714static void mark_unsync(u64 *spte);
1047df1f 1715static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
0074ff63 1716{
74c4e63a
TY
1717 u64 *sptep;
1718 struct rmap_iterator iter;
1719
1720 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1721 mark_unsync(sptep);
1722 }
0074ff63
MT
1723}
1724
67052b35 1725static void mark_unsync(u64 *spte)
0074ff63 1726{
67052b35 1727 struct kvm_mmu_page *sp;
1047df1f 1728 unsigned int index;
0074ff63 1729
57354682 1730 sp = sptep_to_sp(spte);
1047df1f
XG
1731 index = spte - sp->spt;
1732 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
0074ff63 1733 return;
1047df1f 1734 if (sp->unsync_children++)
0074ff63 1735 return;
1047df1f 1736 kvm_mmu_mark_parents_unsync(sp);
0074ff63
MT
1737}
1738
e8bc217a 1739static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
a4a8e6f7 1740 struct kvm_mmu_page *sp)
e8bc217a 1741{
1f50f1b3 1742 return 0;
e8bc217a
MT
1743}
1744
60c8aec6
MT
1745#define KVM_PAGE_ARRAY_NR 16
1746
1747struct kvm_mmu_pages {
1748 struct mmu_page_and_offset {
1749 struct kvm_mmu_page *sp;
1750 unsigned int idx;
1751 } page[KVM_PAGE_ARRAY_NR];
1752 unsigned int nr;
1753};
1754
cded19f3
HE
1755static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1756 int idx)
4731d4c7 1757{
60c8aec6 1758 int i;
4731d4c7 1759
60c8aec6
MT
1760 if (sp->unsync)
1761 for (i=0; i < pvec->nr; i++)
1762 if (pvec->page[i].sp == sp)
1763 return 0;
1764
1765 pvec->page[pvec->nr].sp = sp;
1766 pvec->page[pvec->nr].idx = idx;
1767 pvec->nr++;
1768 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1769}
1770
fd951457
TY
1771static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1772{
1773 --sp->unsync_children;
1774 WARN_ON((int)sp->unsync_children < 0);
1775 __clear_bit(idx, sp->unsync_child_bitmap);
1776}
1777
60c8aec6
MT
1778static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1779 struct kvm_mmu_pages *pvec)
1780{
1781 int i, ret, nr_unsync_leaf = 0;
4731d4c7 1782
37178b8b 1783 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
7a8f1a74 1784 struct kvm_mmu_page *child;
4731d4c7
MT
1785 u64 ent = sp->spt[i];
1786
fd951457
TY
1787 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1788 clear_unsync_child_bit(sp, i);
1789 continue;
1790 }
7a8f1a74 1791
e47c4aee 1792 child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
7a8f1a74
XG
1793
1794 if (child->unsync_children) {
1795 if (mmu_pages_add(pvec, child, i))
1796 return -ENOSPC;
1797
1798 ret = __mmu_unsync_walk(child, pvec);
fd951457
TY
1799 if (!ret) {
1800 clear_unsync_child_bit(sp, i);
1801 continue;
1802 } else if (ret > 0) {
7a8f1a74 1803 nr_unsync_leaf += ret;
fd951457 1804 } else
7a8f1a74
XG
1805 return ret;
1806 } else if (child->unsync) {
1807 nr_unsync_leaf++;
1808 if (mmu_pages_add(pvec, child, i))
1809 return -ENOSPC;
1810 } else
fd951457 1811 clear_unsync_child_bit(sp, i);
4731d4c7
MT
1812 }
1813
60c8aec6
MT
1814 return nr_unsync_leaf;
1815}
1816
e23d3fef
XG
1817#define INVALID_INDEX (-1)
1818
60c8aec6
MT
1819static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1820 struct kvm_mmu_pages *pvec)
1821{
0a47cd85 1822 pvec->nr = 0;
60c8aec6
MT
1823 if (!sp->unsync_children)
1824 return 0;
1825
e23d3fef 1826 mmu_pages_add(pvec, sp, INVALID_INDEX);
60c8aec6 1827 return __mmu_unsync_walk(sp, pvec);
4731d4c7
MT
1828}
1829
4731d4c7
MT
1830static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1831{
1832 WARN_ON(!sp->unsync);
5e1b3ddb 1833 trace_kvm_mmu_sync_page(sp);
4731d4c7
MT
1834 sp->unsync = 0;
1835 --kvm->stat.mmu_unsync;
1836}
1837
83cdb568
SC
1838static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1839 struct list_head *invalid_list);
7775834a
XG
1840static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1841 struct list_head *invalid_list);
4731d4c7 1842
ac101b7c
SC
1843#define for_each_valid_sp(_kvm, _sp, _list) \
1844 hlist_for_each_entry(_sp, _list, hash_link) \
fac026da 1845 if (is_obsolete_sp((_kvm), (_sp))) { \
f3414bc7 1846 } else
1044b030
TY
1847
1848#define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
ac101b7c
SC
1849 for_each_valid_sp(_kvm, _sp, \
1850 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
f3414bc7 1851 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
7ae680eb 1852
479a1efc
SC
1853static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1854 struct list_head *invalid_list)
4731d4c7 1855{
2640b086 1856 if (vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
d98ba053 1857 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1f50f1b3 1858 return false;
4731d4c7
MT
1859 }
1860
1f50f1b3 1861 return true;
4731d4c7
MT
1862}
1863
a2113634
SC
1864static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1865 struct list_head *invalid_list,
1866 bool remote_flush)
1867{
cfd32acf 1868 if (!remote_flush && list_empty(invalid_list))
a2113634
SC
1869 return false;
1870
1871 if (!list_empty(invalid_list))
1872 kvm_mmu_commit_zap_page(kvm, invalid_list);
1873 else
1874 kvm_flush_remote_tlbs(kvm);
1875 return true;
1876}
1877
35a70510
PB
1878static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
1879 struct list_head *invalid_list,
1880 bool remote_flush, bool local_flush)
1d9dc7e0 1881{
a2113634 1882 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
35a70510 1883 return;
d98ba053 1884
a2113634 1885 if (local_flush)
8c8560b8 1886 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1d9dc7e0
XG
1887}
1888
e37fa785
XG
1889#ifdef CONFIG_KVM_MMU_AUDIT
1890#include "mmu_audit.c"
1891#else
1892static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
1893static void mmu_audit_disable(void) { }
1894#endif
1895
002c5f73
SC
1896static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1897{
fac026da
SC
1898 return sp->role.invalid ||
1899 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
002c5f73
SC
1900}
1901
60c8aec6 1902struct mmu_page_path {
2a7266a8
YZ
1903 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1904 unsigned int idx[PT64_ROOT_MAX_LEVEL];
4731d4c7
MT
1905};
1906
60c8aec6 1907#define for_each_sp(pvec, sp, parents, i) \
0a47cd85 1908 for (i = mmu_pages_first(&pvec, &parents); \
60c8aec6
MT
1909 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
1910 i = mmu_pages_next(&pvec, &parents, i))
1911
cded19f3
HE
1912static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1913 struct mmu_page_path *parents,
1914 int i)
60c8aec6
MT
1915{
1916 int n;
1917
1918 for (n = i+1; n < pvec->nr; n++) {
1919 struct kvm_mmu_page *sp = pvec->page[n].sp;
0a47cd85
PB
1920 unsigned idx = pvec->page[n].idx;
1921 int level = sp->role.level;
60c8aec6 1922
0a47cd85 1923 parents->idx[level-1] = idx;
3bae0459 1924 if (level == PG_LEVEL_4K)
0a47cd85 1925 break;
60c8aec6 1926
0a47cd85 1927 parents->parent[level-2] = sp;
60c8aec6
MT
1928 }
1929
1930 return n;
1931}
1932
0a47cd85
PB
1933static int mmu_pages_first(struct kvm_mmu_pages *pvec,
1934 struct mmu_page_path *parents)
1935{
1936 struct kvm_mmu_page *sp;
1937 int level;
1938
1939 if (pvec->nr == 0)
1940 return 0;
1941
e23d3fef
XG
1942 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
1943
0a47cd85
PB
1944 sp = pvec->page[0].sp;
1945 level = sp->role.level;
3bae0459 1946 WARN_ON(level == PG_LEVEL_4K);
0a47cd85
PB
1947
1948 parents->parent[level-2] = sp;
1949
1950 /* Also set up a sentinel. Further entries in pvec are all
1951 * children of sp, so this element is never overwritten.
1952 */
1953 parents->parent[level-1] = NULL;
1954 return mmu_pages_next(pvec, parents, 0);
1955}
1956
cded19f3 1957static void mmu_pages_clear_parents(struct mmu_page_path *parents)
4731d4c7 1958{
60c8aec6
MT
1959 struct kvm_mmu_page *sp;
1960 unsigned int level = 0;
1961
1962 do {
1963 unsigned int idx = parents->idx[level];
60c8aec6
MT
1964 sp = parents->parent[level];
1965 if (!sp)
1966 return;
1967
e23d3fef 1968 WARN_ON(idx == INVALID_INDEX);
fd951457 1969 clear_unsync_child_bit(sp, idx);
60c8aec6 1970 level++;
0a47cd85 1971 } while (!sp->unsync_children);
60c8aec6 1972}
4731d4c7 1973
60c8aec6
MT
1974static void mmu_sync_children(struct kvm_vcpu *vcpu,
1975 struct kvm_mmu_page *parent)
1976{
1977 int i;
1978 struct kvm_mmu_page *sp;
1979 struct mmu_page_path parents;
1980 struct kvm_mmu_pages pages;
d98ba053 1981 LIST_HEAD(invalid_list);
50c9e6f3 1982 bool flush = false;
60c8aec6 1983
60c8aec6 1984 while (mmu_unsync_walk(parent, &pages)) {
2f84569f 1985 bool protected = false;
b1a36821
MT
1986
1987 for_each_sp(pages, sp, parents, i)
54bf36aa 1988 protected |= rmap_write_protect(vcpu, sp->gfn);
b1a36821 1989
50c9e6f3 1990 if (protected) {
b1a36821 1991 kvm_flush_remote_tlbs(vcpu->kvm);
50c9e6f3
PB
1992 flush = false;
1993 }
b1a36821 1994
60c8aec6 1995 for_each_sp(pages, sp, parents, i) {
479a1efc 1996 kvm_unlink_unsync_page(vcpu->kvm, sp);
1f50f1b3 1997 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
60c8aec6
MT
1998 mmu_pages_clear_parents(&parents);
1999 }
531810ca 2000 if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
50c9e6f3 2001 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
531810ca 2002 cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
50c9e6f3
PB
2003 flush = false;
2004 }
60c8aec6 2005 }
50c9e6f3
PB
2006
2007 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
4731d4c7
MT
2008}
2009
a30f47cb
XG
2010static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2011{
e5691a81 2012 atomic_set(&sp->write_flooding_count, 0);
a30f47cb
XG
2013}
2014
2015static void clear_sp_write_flooding_count(u64 *spte)
2016{
57354682 2017 __clear_sp_write_flooding_count(sptep_to_sp(spte));
a30f47cb
XG
2018}
2019
cea0f0e7
AK
2020static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2021 gfn_t gfn,
2022 gva_t gaddr,
2023 unsigned level,
f6e2c02b 2024 int direct,
0a2b64c5 2025 unsigned int access)
cea0f0e7 2026{
fb58a9c3 2027 bool direct_mmu = vcpu->arch.mmu->direct_map;
cea0f0e7 2028 union kvm_mmu_page_role role;
ac101b7c 2029 struct hlist_head *sp_list;
cea0f0e7 2030 unsigned quadrant;
9f1a122f 2031 struct kvm_mmu_page *sp;
f3414bc7 2032 int collisions = 0;
2a74003a 2033 LIST_HEAD(invalid_list);
cea0f0e7 2034
36d9594d 2035 role = vcpu->arch.mmu->mmu_role.base;
cea0f0e7 2036 role.level = level;
f6e2c02b 2037 role.direct = direct;
84b0c8c6 2038 if (role.direct)
47c42e6b 2039 role.gpte_is_8_bytes = true;
41074d07 2040 role.access = access;
fb58a9c3 2041 if (!direct_mmu && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
cea0f0e7
AK
2042 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2043 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2044 role.quadrant = quadrant;
2045 }
ac101b7c
SC
2046
2047 sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2048 for_each_valid_sp(vcpu->kvm, sp, sp_list) {
f3414bc7
DM
2049 if (sp->gfn != gfn) {
2050 collisions++;
2051 continue;
2052 }
2053
ddc16abb
SC
2054 if (sp->role.word != role.word) {
2055 /*
2056 * If the guest is creating an upper-level page, zap
2057 * unsync pages for the same gfn. While it's possible
2058 * the guest is using recursive page tables, in all
2059 * likelihood the guest has stopped using the unsync
2060 * page and is installing a completely unrelated page.
2061 * Unsync pages must not be left as is, because the new
2062 * upper-level page will be write-protected.
2063 */
2064 if (level > PG_LEVEL_4K && sp->unsync)
2065 kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
2066 &invalid_list);
7ae680eb 2067 continue;
ddc16abb 2068 }
4731d4c7 2069
fb58a9c3
SC
2070 if (direct_mmu)
2071 goto trace_get_page;
2072
2a74003a 2073 if (sp->unsync) {
07dc4f35 2074 /*
479a1efc 2075 * The page is good, but is stale. kvm_sync_page does
07dc4f35
SC
2076 * get the latest guest state, but (unlike mmu_unsync_children)
2077 * it doesn't write-protect the page or mark it synchronized!
2078 * This way the validity of the mapping is ensured, but the
2079 * overhead of write protection is not incurred until the
2080 * guest invalidates the TLB mapping. This allows multiple
2081 * SPs for a single gfn to be unsync.
2082 *
2083 * If the sync fails, the page is zapped. If so, break
2084 * in order to rebuild it.
2a74003a 2085 */
479a1efc 2086 if (!kvm_sync_page(vcpu, sp, &invalid_list))
2a74003a
PB
2087 break;
2088
2089 WARN_ON(!list_empty(&invalid_list));
8c8560b8 2090 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2a74003a 2091 }
e02aa901 2092
98bba238 2093 if (sp->unsync_children)
f6f6195b 2094 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
e02aa901 2095
a30f47cb 2096 __clear_sp_write_flooding_count(sp);
fb58a9c3
SC
2097
2098trace_get_page:
7ae680eb 2099 trace_kvm_mmu_get_page(sp, false);
f3414bc7 2100 goto out;
7ae680eb 2101 }
47005792 2102
dfc5aa00 2103 ++vcpu->kvm->stat.mmu_cache_miss;
47005792
TY
2104
2105 sp = kvm_mmu_alloc_page(vcpu, direct);
2106
4db35314
AK
2107 sp->gfn = gfn;
2108 sp->role = role;
ac101b7c 2109 hlist_add_head(&sp->hash_link, sp_list);
f6e2c02b 2110 if (!direct) {
56ca57f9 2111 account_shadowed(vcpu->kvm, sp);
3bae0459 2112 if (level == PG_LEVEL_4K && rmap_write_protect(vcpu, gfn))
c3134ce2 2113 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
4731d4c7 2114 }
f691fe1d 2115 trace_kvm_mmu_get_page(sp, true);
f3414bc7 2116out:
ddc16abb
SC
2117 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2118
f3414bc7
DM
2119 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2120 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
4db35314 2121 return sp;
cea0f0e7
AK
2122}
2123
7eb77e9f
JS
2124static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2125 struct kvm_vcpu *vcpu, hpa_t root,
2126 u64 addr)
2d11123a
AK
2127{
2128 iterator->addr = addr;
7eb77e9f 2129 iterator->shadow_addr = root;
44dd3ffa 2130 iterator->level = vcpu->arch.mmu->shadow_root_level;
81407ca5 2131
2a7266a8 2132 if (iterator->level == PT64_ROOT_4LEVEL &&
44dd3ffa
VK
2133 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2134 !vcpu->arch.mmu->direct_map)
81407ca5
JR
2135 --iterator->level;
2136
2d11123a 2137 if (iterator->level == PT32E_ROOT_LEVEL) {
7eb77e9f
JS
2138 /*
2139 * prev_root is currently only used for 64-bit hosts. So only
2140 * the active root_hpa is valid here.
2141 */
44dd3ffa 2142 BUG_ON(root != vcpu->arch.mmu->root_hpa);
7eb77e9f 2143
2d11123a 2144 iterator->shadow_addr
44dd3ffa 2145 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2d11123a
AK
2146 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2147 --iterator->level;
2148 if (!iterator->shadow_addr)
2149 iterator->level = 0;
2150 }
2151}
2152
7eb77e9f
JS
2153static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2154 struct kvm_vcpu *vcpu, u64 addr)
2155{
44dd3ffa 2156 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
7eb77e9f
JS
2157 addr);
2158}
2159
2d11123a
AK
2160static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2161{
3bae0459 2162 if (iterator->level < PG_LEVEL_4K)
2d11123a 2163 return false;
4d88954d 2164
2d11123a
AK
2165 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2166 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2167 return true;
2168}
2169
c2a2ac2b
XG
2170static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2171 u64 spte)
2d11123a 2172{
c2a2ac2b 2173 if (is_last_spte(spte, iterator->level)) {
052331be
XG
2174 iterator->level = 0;
2175 return;
2176 }
2177
c2a2ac2b 2178 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2d11123a
AK
2179 --iterator->level;
2180}
2181
c2a2ac2b
XG
2182static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2183{
bb606a9b 2184 __shadow_walk_next(iterator, *iterator->sptep);
c2a2ac2b
XG
2185}
2186
cc4674d0
BG
2187static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2188 struct kvm_mmu_page *sp)
2189{
2190 u64 spte;
2191
2192 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2193
2194 spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2195
1df9f2dc 2196 mmu_spte_set(sptep, spte);
98bba238
TY
2197
2198 mmu_page_add_parent_pte(vcpu, sp, sptep);
2199
2200 if (sp->unsync_children || sp->unsync)
2201 mark_unsync(sptep);
32ef26a3
AK
2202}
2203
a357bd22
AK
2204static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2205 unsigned direct_access)
2206{
2207 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2208 struct kvm_mmu_page *child;
2209
2210 /*
2211 * For the direct sp, if the guest pte's dirty bit
2212 * changed form clean to dirty, it will corrupt the
2213 * sp's access: allow writable in the read-only sp,
2214 * so we should update the spte at this point to get
2215 * a new sp with the correct access.
2216 */
e47c4aee 2217 child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
a357bd22
AK
2218 if (child->role.access == direct_access)
2219 return;
2220
bcdd9a93 2221 drop_parent_pte(child, sptep);
c3134ce2 2222 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
a357bd22
AK
2223 }
2224}
2225
2de4085c
BG
2226/* Returns the number of zapped non-leaf child shadow pages. */
2227static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2228 u64 *spte, struct list_head *invalid_list)
38e3b2b2
XG
2229{
2230 u64 pte;
2231 struct kvm_mmu_page *child;
2232
2233 pte = *spte;
2234 if (is_shadow_present_pte(pte)) {
505aef8f 2235 if (is_last_spte(pte, sp->role.level)) {
c3707958 2236 drop_spte(kvm, spte);
505aef8f
XG
2237 if (is_large_pte(pte))
2238 --kvm->stat.lpages;
2239 } else {
e47c4aee 2240 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
bcdd9a93 2241 drop_parent_pte(child, spte);
2de4085c
BG
2242
2243 /*
2244 * Recursively zap nested TDP SPs, parentless SPs are
2245 * unlikely to be used again in the near future. This
2246 * avoids retaining a large number of stale nested SPs.
2247 */
2248 if (tdp_enabled && invalid_list &&
2249 child->role.guest_mode && !child->parent_ptes.val)
2250 return kvm_mmu_prepare_zap_page(kvm, child,
2251 invalid_list);
38e3b2b2 2252 }
ace569e0 2253 } else if (is_mmio_spte(pte)) {
ce88decf 2254 mmu_spte_clear_no_track(spte);
ace569e0 2255 }
2de4085c 2256 return 0;
38e3b2b2
XG
2257}
2258
2de4085c
BG
2259static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2260 struct kvm_mmu_page *sp,
2261 struct list_head *invalid_list)
a436036b 2262{
2de4085c 2263 int zapped = 0;
697fe2e2 2264 unsigned i;
697fe2e2 2265
38e3b2b2 2266 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2de4085c
BG
2267 zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2268
2269 return zapped;
a436036b
AK
2270}
2271
31aa2b44 2272static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
a436036b 2273{
1e3f42f0
TY
2274 u64 *sptep;
2275 struct rmap_iterator iter;
a436036b 2276
018aabb5 2277 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
1e3f42f0 2278 drop_parent_pte(sp, sptep);
31aa2b44
AK
2279}
2280
60c8aec6 2281static int mmu_zap_unsync_children(struct kvm *kvm,
7775834a
XG
2282 struct kvm_mmu_page *parent,
2283 struct list_head *invalid_list)
4731d4c7 2284{
60c8aec6
MT
2285 int i, zapped = 0;
2286 struct mmu_page_path parents;
2287 struct kvm_mmu_pages pages;
4731d4c7 2288
3bae0459 2289 if (parent->role.level == PG_LEVEL_4K)
4731d4c7 2290 return 0;
60c8aec6 2291
60c8aec6
MT
2292 while (mmu_unsync_walk(parent, &pages)) {
2293 struct kvm_mmu_page *sp;
2294
2295 for_each_sp(pages, sp, parents, i) {
7775834a 2296 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
60c8aec6 2297 mmu_pages_clear_parents(&parents);
77662e00 2298 zapped++;
60c8aec6 2299 }
60c8aec6
MT
2300 }
2301
2302 return zapped;
4731d4c7
MT
2303}
2304
83cdb568
SC
2305static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2306 struct kvm_mmu_page *sp,
2307 struct list_head *invalid_list,
2308 int *nr_zapped)
31aa2b44 2309{
83cdb568 2310 bool list_unstable;
f691fe1d 2311
7775834a 2312 trace_kvm_mmu_prepare_zap_page(sp);
31aa2b44 2313 ++kvm->stat.mmu_shadow_zapped;
83cdb568 2314 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2de4085c 2315 *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
31aa2b44 2316 kvm_mmu_unlink_parents(kvm, sp);
5304b8d3 2317
83cdb568
SC
2318 /* Zapping children means active_mmu_pages has become unstable. */
2319 list_unstable = *nr_zapped;
2320
f6e2c02b 2321 if (!sp->role.invalid && !sp->role.direct)
3ed1a478 2322 unaccount_shadowed(kvm, sp);
5304b8d3 2323
4731d4c7
MT
2324 if (sp->unsync)
2325 kvm_unlink_unsync_page(kvm, sp);
4db35314 2326 if (!sp->root_count) {
54a4f023 2327 /* Count self */
83cdb568 2328 (*nr_zapped)++;
f95eec9b
SC
2329
2330 /*
2331 * Already invalid pages (previously active roots) are not on
2332 * the active page list. See list_del() in the "else" case of
2333 * !sp->root_count.
2334 */
2335 if (sp->role.invalid)
2336 list_add(&sp->link, invalid_list);
2337 else
2338 list_move(&sp->link, invalid_list);
aa6bd187 2339 kvm_mod_used_mmu_pages(kvm, -1);
2e53d63a 2340 } else {
f95eec9b
SC
2341 /*
2342 * Remove the active root from the active page list, the root
2343 * will be explicitly freed when the root_count hits zero.
2344 */
2345 list_del(&sp->link);
05988d72 2346
10605204
SC
2347 /*
2348 * Obsolete pages cannot be used on any vCPUs, see the comment
2349 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2350 * treats invalid shadow pages as being obsolete.
2351 */
2352 if (!is_obsolete_sp(kvm, sp))
05988d72 2353 kvm_reload_remote_mmus(kvm);
2e53d63a 2354 }
7775834a 2355
b8e8c830
PB
2356 if (sp->lpage_disallowed)
2357 unaccount_huge_nx_page(kvm, sp);
2358
7775834a 2359 sp->role.invalid = 1;
83cdb568
SC
2360 return list_unstable;
2361}
2362
2363static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2364 struct list_head *invalid_list)
2365{
2366 int nr_zapped;
2367
2368 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2369 return nr_zapped;
a436036b
AK
2370}
2371
7775834a
XG
2372static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2373 struct list_head *invalid_list)
2374{
945315b9 2375 struct kvm_mmu_page *sp, *nsp;
7775834a
XG
2376
2377 if (list_empty(invalid_list))
2378 return;
2379
c142786c 2380 /*
9753f529
LT
2381 * We need to make sure everyone sees our modifications to
2382 * the page tables and see changes to vcpu->mode here. The barrier
2383 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2384 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2385 *
2386 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2387 * guest mode and/or lockless shadow page table walks.
c142786c
AK
2388 */
2389 kvm_flush_remote_tlbs(kvm);
c2a2ac2b 2390
945315b9 2391 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
7775834a 2392 WARN_ON(!sp->role.invalid || sp->root_count);
aa6bd187 2393 kvm_mmu_free_page(sp);
945315b9 2394 }
7775834a
XG
2395}
2396
6b82ef2c
SC
2397static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2398 unsigned long nr_to_zap)
5da59607 2399{
6b82ef2c
SC
2400 unsigned long total_zapped = 0;
2401 struct kvm_mmu_page *sp, *tmp;
ba7888dd 2402 LIST_HEAD(invalid_list);
6b82ef2c
SC
2403 bool unstable;
2404 int nr_zapped;
5da59607
TY
2405
2406 if (list_empty(&kvm->arch.active_mmu_pages))
ba7888dd
SC
2407 return 0;
2408
6b82ef2c 2409restart:
8fc51726 2410 list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
6b82ef2c
SC
2411 /*
2412 * Don't zap active root pages, the page itself can't be freed
2413 * and zapping it will just force vCPUs to realloc and reload.
2414 */
2415 if (sp->root_count)
2416 continue;
2417
2418 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2419 &nr_zapped);
2420 total_zapped += nr_zapped;
2421 if (total_zapped >= nr_to_zap)
ba7888dd
SC
2422 break;
2423
6b82ef2c
SC
2424 if (unstable)
2425 goto restart;
ba7888dd 2426 }
5da59607 2427
6b82ef2c
SC
2428 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2429
2430 kvm->stat.mmu_recycled += total_zapped;
2431 return total_zapped;
2432}
2433
afe8d7e6
SC
2434static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2435{
2436 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2437 return kvm->arch.n_max_mmu_pages -
2438 kvm->arch.n_used_mmu_pages;
2439
2440 return 0;
5da59607
TY
2441}
2442
ba7888dd
SC
2443static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2444{
6b82ef2c 2445 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
ba7888dd 2446
6b82ef2c 2447 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
ba7888dd
SC
2448 return 0;
2449
6b82ef2c 2450 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
ba7888dd 2451
6e6ec584
SC
2452 /*
2453 * Note, this check is intentionally soft, it only guarantees that one
2454 * page is available, while the caller may end up allocating as many as
2455 * four pages, e.g. for PAE roots or for 5-level paging. Temporarily
2456 * exceeding the (arbitrary by default) limit will not harm the host,
c4342633 2457 * being too aggressive may unnecessarily kill the guest, and getting an
6e6ec584
SC
2458 * exact count is far more trouble than it's worth, especially in the
2459 * page fault paths.
2460 */
ba7888dd
SC
2461 if (!kvm_mmu_available_pages(vcpu->kvm))
2462 return -ENOSPC;
2463 return 0;
2464}
2465
82ce2c96
IE
2466/*
2467 * Changing the number of mmu pages allocated to the vm
49d5ca26 2468 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
82ce2c96 2469 */
bc8a3d89 2470void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
82ce2c96 2471{
531810ca 2472 write_lock(&kvm->mmu_lock);
b34cb590 2473
49d5ca26 2474 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
6b82ef2c
SC
2475 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2476 goal_nr_mmu_pages);
82ce2c96 2477
49d5ca26 2478 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
82ce2c96 2479 }
82ce2c96 2480
49d5ca26 2481 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
b34cb590 2482
531810ca 2483 write_unlock(&kvm->mmu_lock);
82ce2c96
IE
2484}
2485
1cb3f3ae 2486int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
a436036b 2487{
4db35314 2488 struct kvm_mmu_page *sp;
d98ba053 2489 LIST_HEAD(invalid_list);
a436036b
AK
2490 int r;
2491
9ad17b10 2492 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
a436036b 2493 r = 0;
531810ca 2494 write_lock(&kvm->mmu_lock);
b67bfe0d 2495 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
9ad17b10 2496 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
7ae680eb
XG
2497 sp->role.word);
2498 r = 1;
f41d335a 2499 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7ae680eb 2500 }
d98ba053 2501 kvm_mmu_commit_zap_page(kvm, &invalid_list);
531810ca 2502 write_unlock(&kvm->mmu_lock);
1cb3f3ae 2503
a436036b 2504 return r;
cea0f0e7 2505}
96ad91ae
SC
2506
2507static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2508{
2509 gpa_t gpa;
2510 int r;
2511
2512 if (vcpu->arch.mmu->direct_map)
2513 return 0;
2514
2515 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
2516
2517 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2518
2519 return r;
2520}
cea0f0e7 2521
5c520e90 2522static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
9cf5cf5a
XG
2523{
2524 trace_kvm_mmu_unsync_page(sp);
2525 ++vcpu->kvm->stat.mmu_unsync;
2526 sp->unsync = 1;
2527
2528 kvm_mmu_mark_parents_unsync(sp);
9cf5cf5a
XG
2529}
2530
0337f585
SC
2531/*
2532 * Attempt to unsync any shadow pages that can be reached by the specified gfn,
2533 * KVM is creating a writable mapping for said gfn. Returns 0 if all pages
2534 * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
2535 * be write-protected.
2536 */
2537int mmu_try_to_unsync_pages(struct kvm_vcpu *vcpu, gfn_t gfn, bool can_unsync)
4731d4c7 2538{
5c520e90 2539 struct kvm_mmu_page *sp;
4731d4c7 2540
0337f585
SC
2541 /*
2542 * Force write-protection if the page is being tracked. Note, the page
2543 * track machinery is used to write-protect upper-level shadow pages,
2544 * i.e. this guards the role.level == 4K assertion below!
2545 */
3d0c27ad 2546 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
0337f585 2547 return -EPERM;
9cf5cf5a 2548
0337f585
SC
2549 /*
2550 * The page is not write-tracked, mark existing shadow pages unsync
2551 * unless KVM is synchronizing an unsync SP (can_unsync = false). In
2552 * that case, KVM must complete emulation of the guest TLB flush before
2553 * allowing shadow pages to become unsync (writable by the guest).
2554 */
5c520e90 2555 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
36a2e677 2556 if (!can_unsync)
0337f585 2557 return -EPERM;
36a2e677 2558
5c520e90
XG
2559 if (sp->unsync)
2560 continue;
9cf5cf5a 2561
3bae0459 2562 WARN_ON(sp->role.level != PG_LEVEL_4K);
5c520e90 2563 kvm_unsync_page(vcpu, sp);
4731d4c7 2564 }
3d0c27ad 2565
578e1c4d
JS
2566 /*
2567 * We need to ensure that the marking of unsync pages is visible
2568 * before the SPTE is updated to allow writes because
2569 * kvm_mmu_sync_roots() checks the unsync flags without holding
2570 * the MMU lock and so can race with this. If the SPTE was updated
2571 * before the page had been marked as unsync-ed, something like the
2572 * following could happen:
2573 *
2574 * CPU 1 CPU 2
2575 * ---------------------------------------------------------------------
2576 * 1.2 Host updates SPTE
2577 * to be writable
2578 * 2.1 Guest writes a GPTE for GVA X.
2579 * (GPTE being in the guest page table shadowed
2580 * by the SP from CPU 1.)
2581 * This reads SPTE during the page table walk.
2582 * Since SPTE.W is read as 1, there is no
2583 * fault.
2584 *
2585 * 2.2 Guest issues TLB flush.
2586 * That causes a VM Exit.
2587 *
0337f585
SC
2588 * 2.3 Walking of unsync pages sees sp->unsync is
2589 * false and skips the page.
578e1c4d
JS
2590 *
2591 * 2.4 Guest accesses GVA X.
2592 * Since the mapping in the SP was not updated,
2593 * so the old mapping for GVA X incorrectly
2594 * gets used.
2595 * 1.1 Host marks SP
2596 * as unsync
2597 * (sp->unsync = true)
2598 *
2599 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2600 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2601 * pairs with this write barrier.
2602 */
2603 smp_wmb();
2604
0337f585 2605 return 0;
4731d4c7
MT
2606}
2607
799a4190
BG
2608static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2609 unsigned int pte_access, int level,
2610 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2611 bool can_unsync, bool host_writable)
2612{
2613 u64 spte;
2614 struct kvm_mmu_page *sp;
2615 int ret;
2616
799a4190
BG
2617 sp = sptep_to_sp(sptep);
2618
2619 ret = make_spte(vcpu, pte_access, level, gfn, pfn, *sptep, speculative,
2620 can_unsync, host_writable, sp_ad_disabled(sp), &spte);
2621
2622 if (spte & PT_WRITABLE_MASK)
2623 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2624
12703759
SC
2625 if (*sptep == spte)
2626 ret |= SET_SPTE_SPURIOUS;
2627 else if (mmu_spte_update(sptep, spte))
5ce4786f 2628 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
1e73f9dd
MT
2629 return ret;
2630}
2631
0a2b64c5 2632static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
e88b8093 2633 unsigned int pte_access, bool write_fault, int level,
0a2b64c5
BG
2634 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2635 bool host_writable)
1e73f9dd
MT
2636{
2637 int was_rmapped = 0;
53a27b39 2638 int rmap_count;
5ce4786f 2639 int set_spte_ret;
c4371c2a 2640 int ret = RET_PF_FIXED;
c2a4eadf 2641 bool flush = false;
1e73f9dd 2642
f7616203
XG
2643 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2644 *sptep, write_fault, gfn);
1e73f9dd 2645
a54aa15c
SC
2646 if (unlikely(is_noslot_pfn(pfn))) {
2647 mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2648 return RET_PF_EMULATE;
2649 }
2650
afd28fe1 2651 if (is_shadow_present_pte(*sptep)) {
1e73f9dd
MT
2652 /*
2653 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2654 * the parent of the now unreachable PTE.
2655 */
3bae0459 2656 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
1e73f9dd 2657 struct kvm_mmu_page *child;
d555c333 2658 u64 pte = *sptep;
1e73f9dd 2659
e47c4aee 2660 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
bcdd9a93 2661 drop_parent_pte(child, sptep);
c2a4eadf 2662 flush = true;
d555c333 2663 } else if (pfn != spte_to_pfn(*sptep)) {
9ad17b10 2664 pgprintk("hfn old %llx new %llx\n",
d555c333 2665 spte_to_pfn(*sptep), pfn);
c3707958 2666 drop_spte(vcpu->kvm, sptep);
c2a4eadf 2667 flush = true;
6bed6b9e
JR
2668 } else
2669 was_rmapped = 1;
1e73f9dd 2670 }
852e3c19 2671
5ce4786f
JS
2672 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
2673 speculative, true, host_writable);
2674 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
1e73f9dd 2675 if (write_fault)
9b8ebbdb 2676 ret = RET_PF_EMULATE;
8c8560b8 2677 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
a378b4e6 2678 }
c3134ce2 2679
c2a4eadf 2680 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
c3134ce2
LT
2681 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
2682 KVM_PAGES_PER_HPAGE(level));
1e73f9dd 2683
12703759
SC
2684 /*
2685 * The fault is fully spurious if and only if the new SPTE and old SPTE
2686 * are identical, and emulation is not required.
2687 */
2688 if ((set_spte_ret & SET_SPTE_SPURIOUS) && ret == RET_PF_FIXED) {
2689 WARN_ON_ONCE(!was_rmapped);
2690 return RET_PF_SPURIOUS;
2691 }
2692
d555c333 2693 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
335e192a 2694 trace_kvm_mmu_set_spte(level, gfn, sptep);
d555c333 2695 if (!was_rmapped && is_large_pte(*sptep))
05da4558
MT
2696 ++vcpu->kvm->stat.lpages;
2697
ffb61bb3 2698 if (is_shadow_present_pte(*sptep)) {
ffb61bb3
XG
2699 if (!was_rmapped) {
2700 rmap_count = rmap_add(vcpu, sptep, gfn);
ec1cf69c
PX
2701 if (rmap_count > vcpu->kvm->stat.max_mmu_rmap_size)
2702 vcpu->kvm->stat.max_mmu_rmap_size = rmap_count;
ffb61bb3
XG
2703 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
2704 rmap_recycle(vcpu, sptep, gfn);
2705 }
1c4f1fd6 2706 }
cb9aaa30 2707
9b8ebbdb 2708 return ret;
1c4f1fd6
AK
2709}
2710
ba049e93 2711static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
957ed9ef
XG
2712 bool no_dirty_log)
2713{
2714 struct kvm_memory_slot *slot;
957ed9ef 2715
5d163b1c 2716 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
903816fa 2717 if (!slot)
6c8ee57b 2718 return KVM_PFN_ERR_FAULT;
957ed9ef 2719
037d92dc 2720 return gfn_to_pfn_memslot_atomic(slot, gfn);
957ed9ef
XG
2721}
2722
2723static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2724 struct kvm_mmu_page *sp,
2725 u64 *start, u64 *end)
2726{
2727 struct page *pages[PTE_PREFETCH_NUM];
d9ef13c2 2728 struct kvm_memory_slot *slot;
0a2b64c5 2729 unsigned int access = sp->role.access;
957ed9ef
XG
2730 int i, ret;
2731 gfn_t gfn;
2732
2733 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
d9ef13c2
PB
2734 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2735 if (!slot)
957ed9ef
XG
2736 return -1;
2737
d9ef13c2 2738 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
957ed9ef
XG
2739 if (ret <= 0)
2740 return -1;
2741
43fdcda9 2742 for (i = 0; i < ret; i++, gfn++, start++) {
e88b8093 2743 mmu_set_spte(vcpu, start, access, false, sp->role.level, gfn,
029499b4 2744 page_to_pfn(pages[i]), true, true);
43fdcda9
JS
2745 put_page(pages[i]);
2746 }
957ed9ef
XG
2747
2748 return 0;
2749}
2750
2751static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2752 struct kvm_mmu_page *sp, u64 *sptep)
2753{
2754 u64 *spte, *start = NULL;
2755 int i;
2756
2757 WARN_ON(!sp->role.direct);
2758
2759 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2760 spte = sp->spt + i;
2761
2762 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
c3707958 2763 if (is_shadow_present_pte(*spte) || spte == sptep) {
957ed9ef
XG
2764 if (!start)
2765 continue;
2766 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2767 break;
2768 start = NULL;
2769 } else if (!start)
2770 start = spte;
2771 }
2772}
2773
2774static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2775{
2776 struct kvm_mmu_page *sp;
2777
57354682 2778 sp = sptep_to_sp(sptep);
ac8d57e5 2779
957ed9ef 2780 /*
ac8d57e5
PF
2781 * Without accessed bits, there's no way to distinguish between
2782 * actually accessed translations and prefetched, so disable pte
2783 * prefetch if accessed bits aren't available.
957ed9ef 2784 */
ac8d57e5 2785 if (sp_ad_disabled(sp))
957ed9ef
XG
2786 return;
2787
3bae0459 2788 if (sp->role.level > PG_LEVEL_4K)
957ed9ef
XG
2789 return;
2790
4a42d848
DS
2791 /*
2792 * If addresses are being invalidated, skip prefetching to avoid
2793 * accidentally prefetching those addresses.
2794 */
2795 if (unlikely(vcpu->kvm->mmu_notifier_count))
2796 return;
2797
957ed9ef
XG
2798 __direct_pte_prefetch(vcpu, sp, sptep);
2799}
2800
1b6d9d9e 2801static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
8ca6f063 2802 const struct kvm_memory_slot *slot)
db543216 2803{
db543216
SC
2804 unsigned long hva;
2805 pte_t *pte;
2806 int level;
2807
e851265a 2808 if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
3bae0459 2809 return PG_LEVEL_4K;
db543216 2810
293e306e
SC
2811 /*
2812 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
2813 * is not solely for performance, it's also necessary to avoid the
2814 * "writable" check in __gfn_to_hva_many(), which will always fail on
2815 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
2816 * page fault steps have already verified the guest isn't writing a
2817 * read-only memslot.
2818 */
db543216
SC
2819 hva = __gfn_to_hva_memslot(slot, gfn);
2820
1b6d9d9e 2821 pte = lookup_address_in_mm(kvm->mm, hva, &level);
db543216 2822 if (unlikely(!pte))
3bae0459 2823 return PG_LEVEL_4K;
db543216
SC
2824
2825 return level;
2826}
2827
8ca6f063
BG
2828int kvm_mmu_max_mapping_level(struct kvm *kvm,
2829 const struct kvm_memory_slot *slot, gfn_t gfn,
2830 kvm_pfn_t pfn, int max_level)
1b6d9d9e
SC
2831{
2832 struct kvm_lpage_info *linfo;
2833
2834 max_level = min(max_level, max_huge_page_level);
2835 for ( ; max_level > PG_LEVEL_4K; max_level--) {
2836 linfo = lpage_info_slot(gfn, slot, max_level);
2837 if (!linfo->disallow_lpage)
2838 break;
2839 }
2840
2841 if (max_level == PG_LEVEL_4K)
2842 return PG_LEVEL_4K;
2843
2844 return host_pfn_mapping_level(kvm, gfn, pfn, slot);
2845}
2846
bb18842e
BG
2847int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
2848 int max_level, kvm_pfn_t *pfnp,
2849 bool huge_page_disallowed, int *req_level)
0885904d 2850{
293e306e 2851 struct kvm_memory_slot *slot;
0885904d 2852 kvm_pfn_t pfn = *pfnp;
17eff019 2853 kvm_pfn_t mask;
83f06fa7 2854 int level;
17eff019 2855
3cf06612
SC
2856 *req_level = PG_LEVEL_4K;
2857
3bae0459
SC
2858 if (unlikely(max_level == PG_LEVEL_4K))
2859 return PG_LEVEL_4K;
17eff019 2860
e851265a 2861 if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
3bae0459 2862 return PG_LEVEL_4K;
17eff019 2863
293e306e
SC
2864 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
2865 if (!slot)
3bae0459 2866 return PG_LEVEL_4K;
293e306e 2867
1b6d9d9e 2868 level = kvm_mmu_max_mapping_level(vcpu->kvm, slot, gfn, pfn, max_level);
3bae0459 2869 if (level == PG_LEVEL_4K)
83f06fa7 2870 return level;
17eff019 2871
3cf06612
SC
2872 *req_level = level = min(level, max_level);
2873
2874 /*
2875 * Enforce the iTLB multihit workaround after capturing the requested
2876 * level, which will be used to do precise, accurate accounting.
2877 */
2878 if (huge_page_disallowed)
2879 return PG_LEVEL_4K;
0885904d
SC
2880
2881 /*
17eff019
SC
2882 * mmu_notifier_retry() was successful and mmu_lock is held, so
2883 * the pmd can't be split from under us.
0885904d 2884 */
17eff019
SC
2885 mask = KVM_PAGES_PER_HPAGE(level) - 1;
2886 VM_BUG_ON((gfn & mask) != (pfn & mask));
2887 *pfnp = pfn & ~mask;
83f06fa7
SC
2888
2889 return level;
0885904d
SC
2890}
2891
bb18842e
BG
2892void disallowed_hugepage_adjust(u64 spte, gfn_t gfn, int cur_level,
2893 kvm_pfn_t *pfnp, int *goal_levelp)
b8e8c830 2894{
bb18842e 2895 int level = *goal_levelp;
b8e8c830 2896
7d945312 2897 if (cur_level == level && level > PG_LEVEL_4K &&
b8e8c830
PB
2898 is_shadow_present_pte(spte) &&
2899 !is_large_pte(spte)) {
2900 /*
2901 * A small SPTE exists for this pfn, but FNAME(fetch)
2902 * and __direct_map would like to create a large PTE
2903 * instead: just force them to go down another level,
2904 * patching back for them into pfn the next 9 bits of
2905 * the address.
2906 */
7d945312
BG
2907 u64 page_mask = KVM_PAGES_PER_HPAGE(level) -
2908 KVM_PAGES_PER_HPAGE(level - 1);
b8e8c830 2909 *pfnp |= gfn & page_mask;
bb18842e 2910 (*goal_levelp)--;
b8e8c830
PB
2911 }
2912}
2913
6c2fd34f 2914static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
83f06fa7 2915 int map_writable, int max_level, kvm_pfn_t pfn,
6c2fd34f 2916 bool prefault, bool is_tdp)
140754bc 2917{
6c2fd34f
SC
2918 bool nx_huge_page_workaround_enabled = is_nx_huge_page_enabled();
2919 bool write = error_code & PFERR_WRITE_MASK;
2920 bool exec = error_code & PFERR_FETCH_MASK;
2921 bool huge_page_disallowed = exec && nx_huge_page_workaround_enabled;
3fcf2d1b 2922 struct kvm_shadow_walk_iterator it;
140754bc 2923 struct kvm_mmu_page *sp;
3cf06612 2924 int level, req_level, ret;
3fcf2d1b
PB
2925 gfn_t gfn = gpa >> PAGE_SHIFT;
2926 gfn_t base_gfn = gfn;
6aa8b732 2927
3cf06612
SC
2928 level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn,
2929 huge_page_disallowed, &req_level);
4cd071d1 2930
335e192a 2931 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3fcf2d1b 2932 for_each_shadow_entry(vcpu, gpa, it) {
b8e8c830
PB
2933 /*
2934 * We cannot overwrite existing page tables with an NX
2935 * large page, as the leaf could be executable.
2936 */
dcc70651 2937 if (nx_huge_page_workaround_enabled)
7d945312
BG
2938 disallowed_hugepage_adjust(*it.sptep, gfn, it.level,
2939 &pfn, &level);
b8e8c830 2940
3fcf2d1b
PB
2941 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
2942 if (it.level == level)
9f652d21 2943 break;
6aa8b732 2944
3fcf2d1b 2945 drop_large_spte(vcpu, it.sptep);
03fffc54
SC
2946 if (is_shadow_present_pte(*it.sptep))
2947 continue;
2948
2949 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
2950 it.level - 1, true, ACC_ALL);
2951
2952 link_shadow_page(vcpu, it.sptep, sp);
2953 if (is_tdp && huge_page_disallowed &&
2954 req_level >= it.level)
2955 account_huge_nx_page(vcpu->kvm, sp);
9f652d21 2956 }
3fcf2d1b
PB
2957
2958 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
2959 write, level, base_gfn, pfn, prefault,
2960 map_writable);
12703759
SC
2961 if (ret == RET_PF_SPURIOUS)
2962 return ret;
2963
3fcf2d1b
PB
2964 direct_pte_prefetch(vcpu, it.sptep);
2965 ++vcpu->stat.pf_fixed;
2966 return ret;
6aa8b732
AK
2967}
2968
77db5cbd 2969static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
bf998156 2970{
585a8b9b 2971 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
bf998156
HY
2972}
2973
ba049e93 2974static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
bf998156 2975{
4d8b81ab
XG
2976 /*
2977 * Do not cache the mmio info caused by writing the readonly gfn
2978 * into the spte otherwise read access on readonly gfn also can
2979 * caused mmio page fault and treat it as mmio access.
4d8b81ab
XG
2980 */
2981 if (pfn == KVM_PFN_ERR_RO_FAULT)
9b8ebbdb 2982 return RET_PF_EMULATE;
4d8b81ab 2983
e6c1502b 2984 if (pfn == KVM_PFN_ERR_HWPOISON) {
54bf36aa 2985 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
9b8ebbdb 2986 return RET_PF_RETRY;
d7c55201 2987 }
edba23e5 2988
2c151b25 2989 return -EFAULT;
bf998156
HY
2990}
2991
d7c55201 2992static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
0a2b64c5
BG
2993 kvm_pfn_t pfn, unsigned int access,
2994 int *ret_val)
d7c55201 2995{
d7c55201 2996 /* The pfn is invalid, report the error! */
81c52c56 2997 if (unlikely(is_error_pfn(pfn))) {
d7c55201 2998 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
798e88b3 2999 return true;
d7c55201
XG
3000 }
3001
30ab5901 3002 if (unlikely(is_noslot_pfn(pfn))) {
4af77151
SC
3003 vcpu_cache_mmio_info(vcpu, gva, gfn,
3004 access & shadow_mmio_access_mask);
30ab5901
SC
3005 /*
3006 * If MMIO caching is disabled, emulate immediately without
3007 * touching the shadow page tables as attempting to install an
3008 * MMIO SPTE will just be an expensive nop.
3009 */
3010 if (unlikely(!shadow_mmio_value)) {
3011 *ret_val = RET_PF_EMULATE;
3012 return true;
3013 }
3014 }
d7c55201 3015
798e88b3 3016 return false;
d7c55201
XG
3017}
3018
e5552fd2 3019static bool page_fault_can_be_fast(u32 error_code)
c7ba5b48 3020{
1c118b82
XG
3021 /*
3022 * Do not fix the mmio spte with invalid generation number which
3023 * need to be updated by slow page fault path.
3024 */
3025 if (unlikely(error_code & PFERR_RSVD_MASK))
3026 return false;
3027
f160c7b7
JS
3028 /* See if the page fault is due to an NX violation */
3029 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3030 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3031 return false;
3032
c7ba5b48 3033 /*
f160c7b7
JS
3034 * #PF can be fast if:
3035 * 1. The shadow page table entry is not present, which could mean that
3036 * the fault is potentially caused by access tracking (if enabled).
3037 * 2. The shadow page table entry is present and the fault
3038 * is caused by write-protect, that means we just need change the W
3039 * bit of the spte which can be done out of mmu-lock.
3040 *
3041 * However, if access tracking is disabled we know that a non-present
3042 * page must be a genuine page fault where we have to create a new SPTE.
3043 * So, if access tracking is disabled, we return true only for write
3044 * accesses to a present page.
c7ba5b48 3045 */
c7ba5b48 3046
f160c7b7
JS
3047 return shadow_acc_track_mask != 0 ||
3048 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3049 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
c7ba5b48
XG
3050}
3051
97dceba2
JS
3052/*
3053 * Returns true if the SPTE was fixed successfully. Otherwise,
3054 * someone else modified the SPTE from its original value.
3055 */
c7ba5b48 3056static bool
92a476cb 3057fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
d3e328f2 3058 u64 *sptep, u64 old_spte, u64 new_spte)
c7ba5b48 3059{
c7ba5b48
XG
3060 gfn_t gfn;
3061
3062 WARN_ON(!sp->role.direct);
3063
9b51a630
KH
3064 /*
3065 * Theoretically we could also set dirty bit (and flush TLB) here in
3066 * order to eliminate unnecessary PML logging. See comments in
3067 * set_spte. But fast_page_fault is very unlikely to happen with PML
3068 * enabled, so we do not do this. This might result in the same GPA
3069 * to be logged in PML buffer again when the write really happens, and
3070 * eventually to be called by mark_page_dirty twice. But it's also no
3071 * harm. This also avoids the TLB flush needed after setting dirty bit
3072 * so non-PML cases won't be impacted.
3073 *
3074 * Compare with set_spte where instead shadow_dirty_mask is set.
3075 */
f160c7b7 3076 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
97dceba2
JS
3077 return false;
3078
d3e328f2 3079 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
f160c7b7
JS
3080 /*
3081 * The gfn of direct spte is stable since it is
3082 * calculated by sp->gfn.
3083 */
3084 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3085 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3086 }
c7ba5b48
XG
3087
3088 return true;
3089}
3090
d3e328f2
JS
3091static bool is_access_allowed(u32 fault_err_code, u64 spte)
3092{
3093 if (fault_err_code & PFERR_FETCH_MASK)
3094 return is_executable_pte(spte);
3095
3096 if (fault_err_code & PFERR_WRITE_MASK)
3097 return is_writable_pte(spte);
3098
3099 /* Fault was on Read access */
3100 return spte & PT_PRESENT_MASK;
3101}
3102
c7ba5b48 3103/*
c4371c2a 3104 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
c7ba5b48 3105 */
c4371c2a
SC
3106static int fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3107 u32 error_code)
c7ba5b48
XG
3108{
3109 struct kvm_shadow_walk_iterator iterator;
92a476cb 3110 struct kvm_mmu_page *sp;
c4371c2a 3111 int ret = RET_PF_INVALID;
c7ba5b48 3112 u64 spte = 0ull;
97dceba2 3113 uint retry_count = 0;
c7ba5b48 3114
e5552fd2 3115 if (!page_fault_can_be_fast(error_code))
c4371c2a 3116 return ret;
c7ba5b48
XG
3117
3118 walk_shadow_page_lockless_begin(vcpu);
c7ba5b48 3119
97dceba2 3120 do {
d3e328f2 3121 u64 new_spte;
c7ba5b48 3122
736c291c 3123 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
f9fa2509 3124 if (!is_shadow_present_pte(spte))
d162f30a
JS
3125 break;
3126
ec89e643
SC
3127 if (!is_shadow_present_pte(spte))
3128 break;
3129
57354682 3130 sp = sptep_to_sp(iterator.sptep);
97dceba2
JS
3131 if (!is_last_spte(spte, sp->role.level))
3132 break;
c7ba5b48 3133
97dceba2 3134 /*
f160c7b7
JS
3135 * Check whether the memory access that caused the fault would
3136 * still cause it if it were to be performed right now. If not,
3137 * then this is a spurious fault caused by TLB lazily flushed,
3138 * or some other CPU has already fixed the PTE after the
3139 * current CPU took the fault.
97dceba2
JS
3140 *
3141 * Need not check the access of upper level table entries since
3142 * they are always ACC_ALL.
3143 */
d3e328f2 3144 if (is_access_allowed(error_code, spte)) {
c4371c2a 3145 ret = RET_PF_SPURIOUS;
d3e328f2
JS
3146 break;
3147 }
f160c7b7 3148
d3e328f2
JS
3149 new_spte = spte;
3150
3151 if (is_access_track_spte(spte))
3152 new_spte = restore_acc_track_spte(new_spte);
3153
3154 /*
3155 * Currently, to simplify the code, write-protection can
3156 * be removed in the fast path only if the SPTE was
3157 * write-protected for dirty-logging or access tracking.
3158 */
3159 if ((error_code & PFERR_WRITE_MASK) &&
e6302698 3160 spte_can_locklessly_be_made_writable(spte)) {
d3e328f2 3161 new_spte |= PT_WRITABLE_MASK;
f160c7b7
JS
3162
3163 /*
d3e328f2
JS
3164 * Do not fix write-permission on the large spte. Since
3165 * we only dirty the first page into the dirty-bitmap in
3166 * fast_pf_fix_direct_spte(), other pages are missed
3167 * if its slot has dirty logging enabled.
3168 *
3169 * Instead, we let the slow page fault path create a
3170 * normal spte to fix the access.
3171 *
3172 * See the comments in kvm_arch_commit_memory_region().
f160c7b7 3173 */
3bae0459 3174 if (sp->role.level > PG_LEVEL_4K)
f160c7b7 3175 break;
97dceba2 3176 }
c7ba5b48 3177
f160c7b7 3178 /* Verify that the fault can be handled in the fast path */
d3e328f2
JS
3179 if (new_spte == spte ||
3180 !is_access_allowed(error_code, new_spte))
97dceba2
JS
3181 break;
3182
3183 /*
3184 * Currently, fast page fault only works for direct mapping
3185 * since the gfn is not stable for indirect shadow page. See
3ecad8c2 3186 * Documentation/virt/kvm/locking.rst to get more detail.
97dceba2 3187 */
c4371c2a
SC
3188 if (fast_pf_fix_direct_spte(vcpu, sp, iterator.sptep, spte,
3189 new_spte)) {
3190 ret = RET_PF_FIXED;
97dceba2 3191 break;
c4371c2a 3192 }
97dceba2
JS
3193
3194 if (++retry_count > 4) {
3195 printk_once(KERN_WARNING
3196 "kvm: Fast #PF retrying more than 4 times.\n");
3197 break;
3198 }
3199
97dceba2 3200 } while (true);
c126d94f 3201
736c291c 3202 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
c4371c2a 3203 spte, ret);
c7ba5b48
XG
3204 walk_shadow_page_lockless_end(vcpu);
3205
c4371c2a 3206 return ret;
c7ba5b48
XG
3207}
3208
74b566e6
JS
3209static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3210 struct list_head *invalid_list)
17ac10ad 3211{
4db35314 3212 struct kvm_mmu_page *sp;
17ac10ad 3213
74b566e6 3214 if (!VALID_PAGE(*root_hpa))
7b53aa56 3215 return;
35af577a 3216
e47c4aee 3217 sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
02c00b3a 3218
2bdb3d84 3219 if (is_tdp_mmu_page(sp))
6103bc07 3220 kvm_tdp_mmu_put_root(kvm, sp, false);
76eb54e7
BG
3221 else if (!--sp->root_count && sp->role.invalid)
3222 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
17ac10ad 3223
74b566e6
JS
3224 *root_hpa = INVALID_PAGE;
3225}
3226
08fb59d8 3227/* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
6a82cd1c
VK
3228void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3229 ulong roots_to_free)
74b566e6 3230{
4d710de9 3231 struct kvm *kvm = vcpu->kvm;
74b566e6
JS
3232 int i;
3233 LIST_HEAD(invalid_list);
08fb59d8 3234 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
74b566e6 3235
b94742c9 3236 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
74b566e6 3237
08fb59d8 3238 /* Before acquiring the MMU lock, see if we need to do any real work. */
b94742c9
JS
3239 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3240 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3241 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3242 VALID_PAGE(mmu->prev_roots[i].hpa))
3243 break;
3244
3245 if (i == KVM_MMU_NUM_PREV_ROOTS)
3246 return;
3247 }
35af577a 3248
531810ca 3249 write_lock(&kvm->mmu_lock);
17ac10ad 3250
b94742c9
JS
3251 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3252 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
4d710de9 3253 mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
b94742c9 3254 &invalid_list);
7c390d35 3255
08fb59d8
JS
3256 if (free_active_root) {
3257 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3258 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
4d710de9 3259 mmu_free_root_page(kvm, &mmu->root_hpa, &invalid_list);
04d45551 3260 } else if (mmu->pae_root) {
c834e5e4
SC
3261 for (i = 0; i < 4; ++i) {
3262 if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3263 continue;
3264
3265 mmu_free_root_page(kvm, &mmu->pae_root[i],
3266 &invalid_list);
3267 mmu->pae_root[i] = INVALID_PAE_ROOT;
3268 }
08fb59d8 3269 }
04d45551 3270 mmu->root_hpa = INVALID_PAGE;
be01e8e2 3271 mmu->root_pgd = 0;
17ac10ad 3272 }
74b566e6 3273
4d710de9 3274 kvm_mmu_commit_zap_page(kvm, &invalid_list);
531810ca 3275 write_unlock(&kvm->mmu_lock);
17ac10ad 3276}
74b566e6 3277EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
17ac10ad 3278
25b62c62
SC
3279void kvm_mmu_free_guest_mode_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
3280{
3281 unsigned long roots_to_free = 0;
3282 hpa_t root_hpa;
3283 int i;
3284
3285 /*
3286 * This should not be called while L2 is active, L2 can't invalidate
3287 * _only_ its own roots, e.g. INVVPID unconditionally exits.
3288 */
3289 WARN_ON_ONCE(mmu->mmu_role.base.guest_mode);
3290
3291 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3292 root_hpa = mmu->prev_roots[i].hpa;
3293 if (!VALID_PAGE(root_hpa))
3294 continue;
3295
3296 if (!to_shadow_page(root_hpa) ||
3297 to_shadow_page(root_hpa)->role.guest_mode)
3298 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
3299 }
3300
3301 kvm_mmu_free_roots(vcpu, mmu, roots_to_free);
3302}
3303EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
3304
3305
8986ecc0
MT
3306static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3307{
3308 int ret = 0;
3309
995decb6 3310 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
a8eeb04a 3311 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8986ecc0
MT
3312 ret = 1;
3313 }
3314
3315 return ret;
3316}
3317
8123f265
SC
3318static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
3319 u8 level, bool direct)
651dd37a
JR
3320{
3321 struct kvm_mmu_page *sp;
8123f265 3322
8123f265
SC
3323 sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
3324 ++sp->root_count;
3325
8123f265
SC
3326 return __pa(sp->spt);
3327}
3328
3329static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3330{
b37233c9
SC
3331 struct kvm_mmu *mmu = vcpu->arch.mmu;
3332 u8 shadow_root_level = mmu->shadow_root_level;
8123f265 3333 hpa_t root;
7ebaf15e 3334 unsigned i;
4a38162e
PB
3335 int r;
3336
3337 write_lock(&vcpu->kvm->mmu_lock);
3338 r = make_mmu_pages_available(vcpu);
3339 if (r < 0)
3340 goto out_unlock;
651dd37a 3341
897218ff 3342 if (is_tdp_mmu_enabled(vcpu->kvm)) {
02c00b3a 3343 root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
b37233c9 3344 mmu->root_hpa = root;
02c00b3a 3345 } else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
6e6ec584 3346 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
b37233c9 3347 mmu->root_hpa = root;
8123f265 3348 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
4a38162e
PB
3349 if (WARN_ON_ONCE(!mmu->pae_root)) {
3350 r = -EIO;
3351 goto out_unlock;
3352 }
73ad1606 3353
651dd37a 3354 for (i = 0; i < 4; ++i) {
c834e5e4 3355 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
651dd37a 3356
8123f265
SC
3357 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
3358 i << 30, PT32_ROOT_LEVEL, true);
17e368d9
SC
3359 mmu->pae_root[i] = root | PT_PRESENT_MASK |
3360 shadow_me_mask;
651dd37a 3361 }
b37233c9 3362 mmu->root_hpa = __pa(mmu->pae_root);
73ad1606
SC
3363 } else {
3364 WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
4a38162e
PB
3365 r = -EIO;
3366 goto out_unlock;
73ad1606 3367 }
3651c7fc 3368
be01e8e2 3369 /* root_pgd is ignored for direct MMUs. */
b37233c9 3370 mmu->root_pgd = 0;
4a38162e
PB
3371out_unlock:
3372 write_unlock(&vcpu->kvm->mmu_lock);
3373 return r;
651dd37a
JR
3374}
3375
3376static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
17ac10ad 3377{
b37233c9 3378 struct kvm_mmu *mmu = vcpu->arch.mmu;
6e0918ae 3379 u64 pdptrs[4], pm_mask;
be01e8e2 3380 gfn_t root_gfn, root_pgd;
8123f265 3381 hpa_t root;
4a38162e
PB
3382 unsigned i;
3383 int r;
3bb65a22 3384
b37233c9 3385 root_pgd = mmu->get_guest_pgd(vcpu);
be01e8e2 3386 root_gfn = root_pgd >> PAGE_SHIFT;
17ac10ad 3387
651dd37a
JR
3388 if (mmu_check_root(vcpu, root_gfn))
3389 return 1;
3390
4a38162e
PB
3391 /*
3392 * On SVM, reading PDPTRs might access guest memory, which might fault
3393 * and thus might sleep. Grab the PDPTRs before acquiring mmu_lock.
3394 */
6e0918ae
SC
3395 if (mmu->root_level == PT32E_ROOT_LEVEL) {
3396 for (i = 0; i < 4; ++i) {
3397 pdptrs[i] = mmu->get_pdptr(vcpu, i);
3398 if (!(pdptrs[i] & PT_PRESENT_MASK))
3399 continue;
3400
3401 if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
3402 return 1;
3403 }
3404 }
3405
d501f747
BG
3406 r = alloc_all_memslots_rmaps(vcpu->kvm);
3407 if (r)
3408 return r;
3409
4a38162e
PB
3410 write_lock(&vcpu->kvm->mmu_lock);
3411 r = make_mmu_pages_available(vcpu);
3412 if (r < 0)
3413 goto out_unlock;
3414
651dd37a
JR
3415 /*
3416 * Do we shadow a long mode page table? If so we need to
3417 * write-protect the guests page table root.
3418 */
b37233c9 3419 if (mmu->root_level >= PT64_ROOT_4LEVEL) {
8123f265 3420 root = mmu_alloc_root(vcpu, root_gfn, 0,
b37233c9 3421 mmu->shadow_root_level, false);
b37233c9 3422 mmu->root_hpa = root;
be01e8e2 3423 goto set_root_pgd;
17ac10ad 3424 }
f87f9288 3425
4a38162e
PB
3426 if (WARN_ON_ONCE(!mmu->pae_root)) {
3427 r = -EIO;
3428 goto out_unlock;
3429 }
73ad1606 3430
651dd37a
JR
3431 /*
3432 * We shadow a 32 bit page table. This may be a legacy 2-level
81407ca5
JR
3433 * or a PAE 3-level page table. In either case we need to be aware that
3434 * the shadow page table may be a PAE or a long mode page table.
651dd37a 3435 */
17e368d9 3436 pm_mask = PT_PRESENT_MASK | shadow_me_mask;
748e52b9 3437 if (mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
81407ca5
JR
3438 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3439
03ca4589 3440 if (WARN_ON_ONCE(!mmu->pml4_root)) {
4a38162e
PB
3441 r = -EIO;
3442 goto out_unlock;
3443 }
73ad1606 3444
03ca4589 3445 mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
04d45551
SC
3446 }
3447
17ac10ad 3448 for (i = 0; i < 4; ++i) {
c834e5e4 3449 WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
6e6ec584 3450
b37233c9 3451 if (mmu->root_level == PT32E_ROOT_LEVEL) {
6e0918ae 3452 if (!(pdptrs[i] & PT_PRESENT_MASK)) {
c834e5e4 3453 mmu->pae_root[i] = INVALID_PAE_ROOT;
417726a3
AK
3454 continue;
3455 }
6e0918ae 3456 root_gfn = pdptrs[i] >> PAGE_SHIFT;
5a7388c2 3457 }
8facbbff 3458
8123f265
SC
3459 root = mmu_alloc_root(vcpu, root_gfn, i << 30,
3460 PT32_ROOT_LEVEL, false);
b37233c9 3461 mmu->pae_root[i] = root | pm_mask;
17ac10ad 3462 }
81407ca5 3463
ba0a194f 3464 if (mmu->shadow_root_level == PT64_ROOT_4LEVEL)
03ca4589 3465 mmu->root_hpa = __pa(mmu->pml4_root);
ba0a194f
SC
3466 else
3467 mmu->root_hpa = __pa(mmu->pae_root);
81407ca5 3468
be01e8e2 3469set_root_pgd:
b37233c9 3470 mmu->root_pgd = root_pgd;
4a38162e
PB
3471out_unlock:
3472 write_unlock(&vcpu->kvm->mmu_lock);
ad7dc69a 3473
8986ecc0 3474 return 0;
17ac10ad
AK
3475}
3476
748e52b9
SC
3477static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3478{
3479 struct kvm_mmu *mmu = vcpu->arch.mmu;
03ca4589 3480 u64 *pml4_root, *pae_root;
81407ca5
JR
3481
3482 /*
748e52b9
SC
3483 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3484 * tables are allocated and initialized at root creation as there is no
3485 * equivalent level in the guest's NPT to shadow. Allocate the tables
3486 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
81407ca5 3487 */
748e52b9
SC
3488 if (mmu->direct_map || mmu->root_level >= PT64_ROOT_4LEVEL ||
3489 mmu->shadow_root_level < PT64_ROOT_4LEVEL)
3490 return 0;
81407ca5 3491
748e52b9
SC
3492 /*
3493 * This mess only works with 4-level paging and needs to be updated to
3494 * work with 5-level paging.
3495 */
3496 if (WARN_ON_ONCE(mmu->shadow_root_level != PT64_ROOT_4LEVEL))
3497 return -EIO;
81407ca5 3498
03ca4589 3499 if (mmu->pae_root && mmu->pml4_root)
748e52b9 3500 return 0;
81407ca5 3501
748e52b9
SC
3502 /*
3503 * The special roots should always be allocated in concert. Yell and
3504 * bail if KVM ends up in a state where only one of the roots is valid.
3505 */
03ca4589 3506 if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root))
748e52b9 3507 return -EIO;
81407ca5 3508
4a98623d
SC
3509 /*
3510 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
3511 * doesn't need to be decrypted.
3512 */
748e52b9
SC
3513 pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3514 if (!pae_root)
3515 return -ENOMEM;
81407ca5 3516
03ca4589
SC
3517 pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3518 if (!pml4_root) {
748e52b9
SC
3519 free_page((unsigned long)pae_root);
3520 return -ENOMEM;
81407ca5
JR
3521 }
3522
748e52b9 3523 mmu->pae_root = pae_root;
03ca4589 3524 mmu->pml4_root = pml4_root;
ad7dc69a 3525
8986ecc0 3526 return 0;
17ac10ad
AK
3527}
3528
578e1c4d 3529void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
0ba73cda
MT
3530{
3531 int i;
3532 struct kvm_mmu_page *sp;
3533
44dd3ffa 3534 if (vcpu->arch.mmu->direct_map)
81407ca5
JR
3535 return;
3536
44dd3ffa 3537 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
0ba73cda 3538 return;
6903074c 3539
56f17dd3 3540 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
578e1c4d 3541
44dd3ffa
VK
3542 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3543 hpa_t root = vcpu->arch.mmu->root_hpa;
e47c4aee 3544 sp = to_shadow_page(root);
578e1c4d
JS
3545
3546 /*
3547 * Even if another CPU was marking the SP as unsync-ed
3548 * simultaneously, any guest page table changes are not
3549 * guaranteed to be visible anyway until this VCPU issues a TLB
3550 * flush strictly after those changes are made. We only need to
3551 * ensure that the other CPU sets these flags before any actual
3552 * changes to the page tables are made. The comments in
0337f585
SC
3553 * mmu_try_to_unsync_pages() describe what could go wrong if
3554 * this requirement isn't satisfied.
578e1c4d
JS
3555 */
3556 if (!smp_load_acquire(&sp->unsync) &&
3557 !smp_load_acquire(&sp->unsync_children))
3558 return;
3559
531810ca 3560 write_lock(&vcpu->kvm->mmu_lock);
578e1c4d
JS
3561 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3562
0ba73cda 3563 mmu_sync_children(vcpu, sp);
578e1c4d 3564
0375f7fa 3565 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
531810ca 3566 write_unlock(&vcpu->kvm->mmu_lock);
0ba73cda
MT
3567 return;
3568 }
578e1c4d 3569
531810ca 3570 write_lock(&vcpu->kvm->mmu_lock);
578e1c4d
JS
3571 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3572
0ba73cda 3573 for (i = 0; i < 4; ++i) {
44dd3ffa 3574 hpa_t root = vcpu->arch.mmu->pae_root[i];
0ba73cda 3575
c834e5e4 3576 if (IS_VALID_PAE_ROOT(root)) {
0ba73cda 3577 root &= PT64_BASE_ADDR_MASK;
e47c4aee 3578 sp = to_shadow_page(root);
0ba73cda
MT
3579 mmu_sync_children(vcpu, sp);
3580 }
3581 }
0ba73cda 3582
578e1c4d 3583 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
531810ca 3584 write_unlock(&vcpu->kvm->mmu_lock);
0ba73cda
MT
3585}
3586
736c291c 3587static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
ab9ae313 3588 u32 access, struct x86_exception *exception)
6aa8b732 3589{
ab9ae313
AK
3590 if (exception)
3591 exception->error_code = 0;
6aa8b732
AK
3592 return vaddr;
3593}
3594
736c291c 3595static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
ab9ae313
AK
3596 u32 access,
3597 struct x86_exception *exception)
6539e738 3598{
ab9ae313
AK
3599 if (exception)
3600 exception->error_code = 0;
54987b7a 3601 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
6539e738
JR
3602}
3603
ded58749 3604static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf 3605{
9034e6e8
PB
3606 /*
3607 * A nested guest cannot use the MMIO cache if it is using nested
3608 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3609 */
3610 if (mmu_is_nested(vcpu))
3611 return false;
3612
ce88decf
XG
3613 if (direct)
3614 return vcpu_match_mmio_gpa(vcpu, addr);
3615
3616 return vcpu_match_mmio_gva(vcpu, addr);
3617}
3618
95fb5b02
BG
3619/*
3620 * Return the level of the lowest level SPTE added to sptes.
3621 * That SPTE may be non-present.
3622 */
39b4d43e 3623static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
ce88decf
XG
3624{
3625 struct kvm_shadow_walk_iterator iterator;
2aa07893 3626 int leaf = -1;
95fb5b02 3627 u64 spte;
ce88decf
XG
3628
3629 walk_shadow_page_lockless_begin(vcpu);
47ab8751 3630
39b4d43e
SC
3631 for (shadow_walk_init(&iterator, vcpu, addr),
3632 *root_level = iterator.level;
47ab8751
XG
3633 shadow_walk_okay(&iterator);
3634 __shadow_walk_next(&iterator, spte)) {
95fb5b02 3635 leaf = iterator.level;
47ab8751
XG
3636 spte = mmu_spte_get_lockless(iterator.sptep);
3637
dde81f94 3638 sptes[leaf] = spte;
47ab8751 3639
ce88decf
XG
3640 if (!is_shadow_present_pte(spte))
3641 break;
95fb5b02
BG
3642 }
3643
3644 walk_shadow_page_lockless_end(vcpu);
3645
3646 return leaf;
3647}
3648
9aa41879 3649/* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
95fb5b02
BG
3650static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3651{
dde81f94 3652 u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
95fb5b02 3653 struct rsvd_bits_validate *rsvd_check;
39b4d43e 3654 int root, leaf, level;
95fb5b02
BG
3655 bool reserved = false;
3656
63c0cac9 3657 if (is_tdp_mmu(vcpu->arch.mmu))
39b4d43e 3658 leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
95fb5b02 3659 else
39b4d43e 3660 leaf = get_walk(vcpu, addr, sptes, &root);
95fb5b02 3661
2aa07893
SC
3662 if (unlikely(leaf < 0)) {
3663 *sptep = 0ull;
3664 return reserved;
3665 }
3666
9aa41879
SC
3667 *sptep = sptes[leaf];
3668
3669 /*
3670 * Skip reserved bits checks on the terminal leaf if it's not a valid
3671 * SPTE. Note, this also (intentionally) skips MMIO SPTEs, which, by
3672 * design, always have reserved bits set. The purpose of the checks is
3673 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
3674 */
3675 if (!is_shadow_present_pte(sptes[leaf]))
3676 leaf++;
95fb5b02
BG
3677
3678 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
3679
9aa41879 3680 for (level = root; level >= leaf; level--)
961f8445 3681 reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
47ab8751 3682
47ab8751 3683 if (reserved) {
bb4cdf3a 3684 pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
47ab8751 3685 __func__, addr);
95fb5b02 3686 for (level = root; level >= leaf; level--)
bb4cdf3a
SC
3687 pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
3688 sptes[level], level,
961f8445 3689 get_rsvd_bits(rsvd_check, sptes[level], level));
47ab8751 3690 }
ddce6208 3691
47ab8751 3692 return reserved;
ce88decf
XG
3693}
3694
e08d26f0 3695static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf
XG
3696{
3697 u64 spte;
47ab8751 3698 bool reserved;
ce88decf 3699
ded58749 3700 if (mmio_info_in_cache(vcpu, addr, direct))
9b8ebbdb 3701 return RET_PF_EMULATE;
ce88decf 3702
95fb5b02 3703 reserved = get_mmio_spte(vcpu, addr, &spte);
450869d6 3704 if (WARN_ON(reserved))
9b8ebbdb 3705 return -EINVAL;
ce88decf
XG
3706
3707 if (is_mmio_spte(spte)) {
3708 gfn_t gfn = get_mmio_spte_gfn(spte);
0a2b64c5 3709 unsigned int access = get_mmio_spte_access(spte);
ce88decf 3710
54bf36aa 3711 if (!check_mmio_spte(vcpu, spte))
9b8ebbdb 3712 return RET_PF_INVALID;
f8f55942 3713
ce88decf
XG
3714 if (direct)
3715 addr = 0;
4f022648
XG
3716
3717 trace_handle_mmio_page_fault(addr, gfn, access);
ce88decf 3718 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
9b8ebbdb 3719 return RET_PF_EMULATE;
ce88decf
XG
3720 }
3721
ce88decf
XG
3722 /*
3723 * If the page table is zapped by other cpus, let CPU fault again on
3724 * the address.
3725 */
9b8ebbdb 3726 return RET_PF_RETRY;
ce88decf 3727}
ce88decf 3728
3d0c27ad
XG
3729static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3730 u32 error_code, gfn_t gfn)
3731{
3732 if (unlikely(error_code & PFERR_RSVD_MASK))
3733 return false;
3734
3735 if (!(error_code & PFERR_PRESENT_MASK) ||
3736 !(error_code & PFERR_WRITE_MASK))
3737 return false;
3738
3739 /*
3740 * guest is writing the page which is write tracked which can
3741 * not be fixed by page fault handler.
3742 */
3743 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3744 return true;
3745
3746 return false;
3747}
3748
e5691a81
XG
3749static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3750{
3751 struct kvm_shadow_walk_iterator iterator;
3752 u64 spte;
3753
e5691a81
XG
3754 walk_shadow_page_lockless_begin(vcpu);
3755 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3756 clear_sp_write_flooding_count(iterator.sptep);
3757 if (!is_shadow_present_pte(spte))
3758 break;
3759 }
3760 walk_shadow_page_lockless_end(vcpu);
3761}
3762
e8c22266
VK
3763static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3764 gfn_t gfn)
af585b92
GN
3765{
3766 struct kvm_arch_async_pf arch;
fb67e14f 3767
7c90705b 3768 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
af585b92 3769 arch.gfn = gfn;
44dd3ffa 3770 arch.direct_map = vcpu->arch.mmu->direct_map;
d8dd54e0 3771 arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
af585b92 3772
9f1a8526
SC
3773 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
3774 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
af585b92
GN
3775}
3776
78b2c54a 3777static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4a42d848
DS
3778 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, hva_t *hva,
3779 bool write, bool *writable)
af585b92 3780{
c36b7150 3781 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
af585b92
GN
3782 bool async;
3783
e0c37868
SC
3784 /*
3785 * Retry the page fault if the gfn hit a memslot that is being deleted
3786 * or moved. This ensures any existing SPTEs for the old memslot will
3787 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
3788 */
3789 if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
3790 return true;
3791
c36b7150
PB
3792 /* Don't expose private memslots to L2. */
3793 if (is_guest_mode(vcpu) && !kvm_is_visible_memslot(slot)) {
3a2936de 3794 *pfn = KVM_PFN_NOSLOT;
c583eed6 3795 *writable = false;
3a2936de
JM
3796 return false;
3797 }
3798
3520469d 3799 async = false;
4a42d848
DS
3800 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async,
3801 write, writable, hva);
af585b92
GN
3802 if (!async)
3803 return false; /* *pfn has correct page already */
3804
9bc1f09f 3805 if (!prefault && kvm_can_do_async_pf(vcpu)) {
9f1a8526 3806 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
af585b92 3807 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
9f1a8526 3808 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
af585b92
GN
3809 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3810 return true;
9f1a8526 3811 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
af585b92
GN
3812 return true;
3813 }
3814
4a42d848
DS
3815 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL,
3816 write, writable, hva);
af585b92
GN
3817 return false;
3818}
3819
0f90e1c1
SC
3820static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3821 bool prefault, int max_level, bool is_tdp)
6aa8b732 3822{
63c0cac9 3823 bool is_tdp_mmu_fault = is_tdp_mmu(vcpu->arch.mmu);
367fd790 3824 bool write = error_code & PFERR_WRITE_MASK;
0f90e1c1 3825 bool map_writable;
6aa8b732 3826
0f90e1c1
SC
3827 gfn_t gfn = gpa >> PAGE_SHIFT;
3828 unsigned long mmu_seq;
3829 kvm_pfn_t pfn;
4a42d848 3830 hva_t hva;
83f06fa7 3831 int r;
ce88decf 3832
3d0c27ad 3833 if (page_fault_handle_page_track(vcpu, error_code, gfn))
9b8ebbdb 3834 return RET_PF_EMULATE;
ce88decf 3835
0b873fd7 3836 if (!is_tdp_mmu_fault) {
bb18842e
BG
3837 r = fast_page_fault(vcpu, gpa, error_code);
3838 if (r != RET_PF_INVALID)
3839 return r;
3840 }
83291445 3841
378f5cd6 3842 r = mmu_topup_memory_caches(vcpu, false);
e2dec939
AK
3843 if (r)
3844 return r;
714b93da 3845
367fd790
SC
3846 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3847 smp_rmb();
3848
4a42d848
DS
3849 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, &hva,
3850 write, &map_writable))
367fd790
SC
3851 return RET_PF_RETRY;
3852
0f90e1c1 3853 if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
367fd790 3854 return r;
6aa8b732 3855
367fd790 3856 r = RET_PF_RETRY;
a2855afc 3857
0b873fd7 3858 if (is_tdp_mmu_fault)
a2855afc
BG
3859 read_lock(&vcpu->kvm->mmu_lock);
3860 else
3861 write_lock(&vcpu->kvm->mmu_lock);
3862
4a42d848 3863 if (!is_noslot_pfn(pfn) && mmu_notifier_retry_hva(vcpu->kvm, mmu_seq, hva))
367fd790 3864 goto out_unlock;
7bd7ded6
SC
3865 r = make_mmu_pages_available(vcpu);
3866 if (r)
367fd790 3867 goto out_unlock;
bb18842e 3868
0b873fd7 3869 if (is_tdp_mmu_fault)
bb18842e
BG
3870 r = kvm_tdp_mmu_map(vcpu, gpa, error_code, map_writable, max_level,
3871 pfn, prefault);
3872 else
3873 r = __direct_map(vcpu, gpa, error_code, map_writable, max_level, pfn,
3874 prefault, is_tdp);
0f90e1c1 3875
367fd790 3876out_unlock:
0b873fd7 3877 if (is_tdp_mmu_fault)
a2855afc
BG
3878 read_unlock(&vcpu->kvm->mmu_lock);
3879 else
3880 write_unlock(&vcpu->kvm->mmu_lock);
367fd790
SC
3881 kvm_release_pfn_clean(pfn);
3882 return r;
6aa8b732
AK
3883}
3884
0f90e1c1
SC
3885static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
3886 u32 error_code, bool prefault)
3887{
3888 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
3889
3890 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
3891 return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
3bae0459 3892 PG_LEVEL_2M, false);
0f90e1c1
SC
3893}
3894
1261bfa3 3895int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
d0006530 3896 u64 fault_address, char *insn, int insn_len)
1261bfa3
WL
3897{
3898 int r = 1;
9ce372b3 3899 u32 flags = vcpu->arch.apf.host_apf_flags;
1261bfa3 3900
736c291c
SC
3901#ifndef CONFIG_X86_64
3902 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
3903 if (WARN_ON_ONCE(fault_address >> 32))
3904 return -EFAULT;
3905#endif
3906
c595ceee 3907 vcpu->arch.l1tf_flush_l1d = true;
9ce372b3 3908 if (!flags) {
1261bfa3
WL
3909 trace_kvm_page_fault(fault_address, error_code);
3910
d0006530 3911 if (kvm_event_needs_reinjection(vcpu))
1261bfa3
WL
3912 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
3913 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
3914 insn_len);
9ce372b3 3915 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
68fd66f1 3916 vcpu->arch.apf.host_apf_flags = 0;
1261bfa3 3917 local_irq_disable();
6bca69ad 3918 kvm_async_pf_task_wait_schedule(fault_address);
1261bfa3 3919 local_irq_enable();
9ce372b3
VK
3920 } else {
3921 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
1261bfa3 3922 }
9ce372b3 3923
1261bfa3
WL
3924 return r;
3925}
3926EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
3927
7a02674d
SC
3928int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3929 bool prefault)
fb72d167 3930{
cb9b88c6 3931 int max_level;
fb72d167 3932
e662ec3e 3933 for (max_level = KVM_MAX_HUGEPAGE_LEVEL;
3bae0459 3934 max_level > PG_LEVEL_4K;
cb9b88c6
SC
3935 max_level--) {
3936 int page_num = KVM_PAGES_PER_HPAGE(max_level);
0f90e1c1 3937 gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
ce88decf 3938
cb9b88c6
SC
3939 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
3940 break;
fd136902 3941 }
852e3c19 3942
0f90e1c1
SC
3943 return direct_page_fault(vcpu, gpa, error_code, prefault,
3944 max_level, true);
fb72d167
JR
3945}
3946
84a16226 3947static void nonpaging_init_context(struct kvm_mmu *context)
6aa8b732 3948{
6aa8b732 3949 context->page_fault = nonpaging_page_fault;
6aa8b732 3950 context->gva_to_gpa = nonpaging_gva_to_gpa;
e8bc217a 3951 context->sync_page = nonpaging_sync_page;
5efac074 3952 context->invlpg = NULL;
c5a78f2b 3953 context->direct_map = true;
6aa8b732
AK
3954}
3955
be01e8e2 3956static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
0be44352
SC
3957 union kvm_mmu_page_role role)
3958{
be01e8e2 3959 return (role.direct || pgd == root->pgd) &&
e47c4aee
SC
3960 VALID_PAGE(root->hpa) && to_shadow_page(root->hpa) &&
3961 role.word == to_shadow_page(root->hpa)->role.word;
0be44352
SC
3962}
3963
b94742c9 3964/*
be01e8e2 3965 * Find out if a previously cached root matching the new pgd/role is available.
b94742c9
JS
3966 * The current root is also inserted into the cache.
3967 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
3968 * returned.
3969 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
3970 * false is returned. This root should now be freed by the caller.
3971 */
be01e8e2 3972static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_pgd,
b94742c9
JS
3973 union kvm_mmu_page_role new_role)
3974{
3975 uint i;
3976 struct kvm_mmu_root_info root;
44dd3ffa 3977 struct kvm_mmu *mmu = vcpu->arch.mmu;
b94742c9 3978
be01e8e2 3979 root.pgd = mmu->root_pgd;
b94742c9
JS
3980 root.hpa = mmu->root_hpa;
3981
be01e8e2 3982 if (is_root_usable(&root, new_pgd, new_role))
0be44352
SC
3983 return true;
3984
b94742c9
JS
3985 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3986 swap(root, mmu->prev_roots[i]);
3987
be01e8e2 3988 if (is_root_usable(&root, new_pgd, new_role))
b94742c9
JS
3989 break;
3990 }
3991
3992 mmu->root_hpa = root.hpa;
be01e8e2 3993 mmu->root_pgd = root.pgd;
b94742c9
JS
3994
3995 return i < KVM_MMU_NUM_PREV_ROOTS;
3996}
3997
be01e8e2 3998static bool fast_pgd_switch(struct kvm_vcpu *vcpu, gpa_t new_pgd,
b869855b 3999 union kvm_mmu_page_role new_role)
6aa8b732 4000{
44dd3ffa 4001 struct kvm_mmu *mmu = vcpu->arch.mmu;
7c390d35
JS
4002
4003 /*
4004 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4005 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4006 * later if necessary.
4007 */
4008 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
b869855b 4009 mmu->root_level >= PT64_ROOT_4LEVEL)
fe9304d3 4010 return cached_root_available(vcpu, new_pgd, new_role);
7c390d35
JS
4011
4012 return false;
6aa8b732
AK
4013}
4014
be01e8e2 4015static void __kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd,
b5129100 4016 union kvm_mmu_page_role new_role)
6aa8b732 4017{
be01e8e2 4018 if (!fast_pgd_switch(vcpu, new_pgd, new_role)) {
b869855b
SC
4019 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, KVM_MMU_ROOT_CURRENT);
4020 return;
4021 }
4022
4023 /*
4024 * It's possible that the cached previous root page is obsolete because
4025 * of a change in the MMU generation number. However, changing the
4026 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
4027 * free the root set here and allocate a new one.
4028 */
4029 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4030
b5129100 4031 if (force_flush_and_sync_on_reuse) {
b869855b
SC
4032 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4033 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
b5129100 4034 }
b869855b
SC
4035
4036 /*
4037 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4038 * switching to a new CR3, that GVA->GPA mapping may no longer be
4039 * valid. So clear any cached MMIO info even when we don't need to sync
4040 * the shadow page tables.
4041 */
4042 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4043
daa5b6c1
BG
4044 /*
4045 * If this is a direct root page, it doesn't have a write flooding
4046 * count. Otherwise, clear the write flooding count.
4047 */
4048 if (!new_role.direct)
4049 __clear_sp_write_flooding_count(
4050 to_shadow_page(vcpu->arch.mmu->root_hpa));
6aa8b732
AK
4051}
4052
b5129100 4053void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
0aab33e4 4054{
b5129100 4055 __kvm_mmu_new_pgd(vcpu, new_pgd, kvm_mmu_calc_root_page_role(vcpu));
0aab33e4 4056}
be01e8e2 4057EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
0aab33e4 4058
5777ed34
JR
4059static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4060{
9f8fe504 4061 return kvm_read_cr3(vcpu);
5777ed34
JR
4062}
4063
54bf36aa 4064static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
0a2b64c5 4065 unsigned int access, int *nr_present)
ce88decf
XG
4066{
4067 if (unlikely(is_mmio_spte(*sptep))) {
4068 if (gfn != get_mmio_spte_gfn(*sptep)) {
4069 mmu_spte_clear_no_track(sptep);
4070 return true;
4071 }
4072
4073 (*nr_present)++;
54bf36aa 4074 mark_mmio_spte(vcpu, sptep, gfn, access);
ce88decf
XG
4075 return true;
4076 }
4077
4078 return false;
4079}
4080
37406aaa
NHE
4081#define PTTYPE_EPT 18 /* arbitrary */
4082#define PTTYPE PTTYPE_EPT
4083#include "paging_tmpl.h"
4084#undef PTTYPE
4085
6aa8b732
AK
4086#define PTTYPE 64
4087#include "paging_tmpl.h"
4088#undef PTTYPE
4089
4090#define PTTYPE 32
4091#include "paging_tmpl.h"
4092#undef PTTYPE
4093
6dc98b86 4094static void
b705a277 4095__reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
5b7f575c 4096 u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
6fec2144 4097 bool pse, bool amd)
82725b20 4098{
5f7dde7b 4099 u64 gbpages_bit_rsvd = 0;
a0c0feb5 4100 u64 nonleaf_bit8_rsvd = 0;
5b7f575c 4101 u64 high_bits_rsvd;
82725b20 4102
a0a64f50 4103 rsvd_check->bad_mt_xwr = 0;
25d92081 4104
6dc98b86 4105 if (!gbpages)
5f7dde7b 4106 gbpages_bit_rsvd = rsvd_bits(7, 7);
a0c0feb5 4107
5b7f575c
SC
4108 if (level == PT32E_ROOT_LEVEL)
4109 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
4110 else
4111 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4112
4113 /* Note, NX doesn't exist in PDPTEs, this is handled below. */
4114 if (!nx)
4115 high_bits_rsvd |= rsvd_bits(63, 63);
4116
a0c0feb5
PB
4117 /*
4118 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4119 * leaf entries) on AMD CPUs only.
4120 */
6fec2144 4121 if (amd)
a0c0feb5
PB
4122 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4123
6dc98b86 4124 switch (level) {
82725b20
DE
4125 case PT32_ROOT_LEVEL:
4126 /* no rsvd bits for 2 level 4K page table entries */
a0a64f50
XG
4127 rsvd_check->rsvd_bits_mask[0][1] = 0;
4128 rsvd_check->rsvd_bits_mask[0][0] = 0;
4129 rsvd_check->rsvd_bits_mask[1][0] =
4130 rsvd_check->rsvd_bits_mask[0][0];
f815bce8 4131
6dc98b86 4132 if (!pse) {
a0a64f50 4133 rsvd_check->rsvd_bits_mask[1][1] = 0;
f815bce8
XG
4134 break;
4135 }
4136
82725b20
DE
4137 if (is_cpuid_PSE36())
4138 /* 36bits PSE 4MB page */
a0a64f50 4139 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
82725b20
DE
4140 else
4141 /* 32 bits PSE 4MB page */
a0a64f50 4142 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
82725b20
DE
4143 break;
4144 case PT32E_ROOT_LEVEL:
5b7f575c
SC
4145 rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
4146 high_bits_rsvd |
4147 rsvd_bits(5, 8) |
4148 rsvd_bits(1, 2); /* PDPTE */
4149 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd; /* PDE */
4150 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd; /* PTE */
4151 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4152 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
4153 rsvd_check->rsvd_bits_mask[1][0] =
4154 rsvd_check->rsvd_bits_mask[0][0];
82725b20 4155 break;
855feb67 4156 case PT64_ROOT_5LEVEL:
5b7f575c
SC
4157 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
4158 nonleaf_bit8_rsvd |
4159 rsvd_bits(7, 7);
855feb67
YZ
4160 rsvd_check->rsvd_bits_mask[1][4] =
4161 rsvd_check->rsvd_bits_mask[0][4];
df561f66 4162 fallthrough;
2a7266a8 4163 case PT64_ROOT_4LEVEL:
5b7f575c
SC
4164 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
4165 nonleaf_bit8_rsvd |
4166 rsvd_bits(7, 7);
4167 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
4168 gbpages_bit_rsvd;
4169 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
4170 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
a0a64f50
XG
4171 rsvd_check->rsvd_bits_mask[1][3] =
4172 rsvd_check->rsvd_bits_mask[0][3];
5b7f575c
SC
4173 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
4174 gbpages_bit_rsvd |
4175 rsvd_bits(13, 29);
4176 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4177 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
4178 rsvd_check->rsvd_bits_mask[1][0] =
4179 rsvd_check->rsvd_bits_mask[0][0];
82725b20
DE
4180 break;
4181 }
4182}
4183
27de9250
SC
4184static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
4185{
4186 /*
4187 * If TDP is enabled, let the guest use GBPAGES if they're supported in
4188 * hardware. The hardware page walker doesn't let KVM disable GBPAGES,
4189 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
4190 * walk for performance and complexity reasons. Not to mention KVM
4191 * _can't_ solve the problem because GVA->GPA walks aren't visible to
4192 * KVM once a TDP translation is installed. Mimic hardware behavior so
4193 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
4194 */
4195 return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
4196 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
4197}
4198
6dc98b86
XG
4199static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4200 struct kvm_mmu *context)
4201{
b705a277 4202 __reset_rsvds_bits_mask(&context->guest_rsvd_check,
5b7f575c 4203 vcpu->arch.reserved_gpa_bits,
90599c28 4204 context->root_level, is_efer_nx(context),
27de9250 4205 guest_can_use_gbpages(vcpu),
4e9c0d80 4206 is_cr4_pse(context),
23493d0a 4207 guest_cpuid_is_amd_or_hygon(vcpu));
6dc98b86
XG
4208}
4209
81b8eebb
XG
4210static void
4211__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
5b7f575c 4212 u64 pa_bits_rsvd, bool execonly)
25d92081 4213{
5b7f575c 4214 u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
951f9fd7 4215 u64 bad_mt_xwr;
25d92081 4216
5b7f575c
SC
4217 rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
4218 rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
4219 rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6);
4220 rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6);
4221 rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
25d92081
YZ
4222
4223 /* large page */
855feb67 4224 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
a0a64f50 4225 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
5b7f575c
SC
4226 rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29);
4227 rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20);
a0a64f50 4228 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
25d92081 4229
951f9fd7
PB
4230 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4231 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4232 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4233 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4234 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4235 if (!execonly) {
4236 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4237 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
25d92081 4238 }
951f9fd7 4239 rsvd_check->bad_mt_xwr = bad_mt_xwr;
25d92081
YZ
4240}
4241
81b8eebb
XG
4242static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4243 struct kvm_mmu *context, bool execonly)
4244{
4245 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
5b7f575c 4246 vcpu->arch.reserved_gpa_bits, execonly);
81b8eebb
XG
4247}
4248
6f8e65a6
SC
4249static inline u64 reserved_hpa_bits(void)
4250{
4251 return rsvd_bits(shadow_phys_bits, 63);
4252}
4253
c258b62b
XG
4254/*
4255 * the page table on host is the shadow page table for the page
4256 * table in guest or amd nested guest, its mmu features completely
4257 * follow the features in guest.
4258 */
16be1d12
SC
4259static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4260 struct kvm_mmu *context)
c258b62b 4261{
112022bd
SC
4262 /*
4263 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
4264 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
4265 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
4266 * The iTLB multi-hit workaround can be toggled at any time, so assume
4267 * NX can be used by any non-nested shadow MMU to avoid having to reset
4268 * MMU contexts. Note, KVM forces EFER.NX=1 when TDP is disabled.
4269 */
90599c28 4270 bool uses_nx = is_efer_nx(context) || !tdp_enabled;
8c985b2d
SC
4271
4272 /* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
4273 bool is_amd = true;
4274 /* KVM doesn't use 2-level page tables for the shadow MMU. */
4275 bool is_pse = false;
ea2800dd
BS
4276 struct rsvd_bits_validate *shadow_zero_check;
4277 int i;
5f0b8199 4278
8c985b2d
SC
4279 WARN_ON_ONCE(context->shadow_root_level < PT32E_ROOT_LEVEL);
4280
ea2800dd 4281 shadow_zero_check = &context->shadow_zero_check;
b705a277 4282 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
5f0b8199 4283 context->shadow_root_level, uses_nx,
27de9250 4284 guest_can_use_gbpages(vcpu), is_pse, is_amd);
ea2800dd
BS
4285
4286 if (!shadow_me_mask)
4287 return;
4288
4289 for (i = context->shadow_root_level; --i >= 0;) {
4290 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4291 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4292 }
4293
c258b62b 4294}
c258b62b 4295
6fec2144
PB
4296static inline bool boot_cpu_is_amd(void)
4297{
4298 WARN_ON_ONCE(!tdp_enabled);
4299 return shadow_x_mask == 0;
4300}
4301
c258b62b
XG
4302/*
4303 * the direct page table on host, use as much mmu features as
4304 * possible, however, kvm currently does not do execution-protection.
4305 */
4306static void
4307reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4308 struct kvm_mmu *context)
4309{
ea2800dd
BS
4310 struct rsvd_bits_validate *shadow_zero_check;
4311 int i;
4312
4313 shadow_zero_check = &context->shadow_zero_check;
4314
6fec2144 4315 if (boot_cpu_is_amd())
b705a277 4316 __reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
c258b62b 4317 context->shadow_root_level, false,
b8291adc 4318 boot_cpu_has(X86_FEATURE_GBPAGES),
8c985b2d 4319 false, true);
c258b62b 4320 else
ea2800dd 4321 __reset_rsvds_bits_mask_ept(shadow_zero_check,
6f8e65a6 4322 reserved_hpa_bits(), false);
c258b62b 4323
ea2800dd
BS
4324 if (!shadow_me_mask)
4325 return;
4326
4327 for (i = context->shadow_root_level; --i >= 0;) {
4328 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4329 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4330 }
c258b62b
XG
4331}
4332
4333/*
4334 * as the comments in reset_shadow_zero_bits_mask() except it
4335 * is the shadow page table for intel nested guest.
4336 */
4337static void
4338reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4339 struct kvm_mmu *context, bool execonly)
4340{
4341 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
6f8e65a6 4342 reserved_hpa_bits(), execonly);
c258b62b
XG
4343}
4344
09f037aa
PB
4345#define BYTE_MASK(access) \
4346 ((1 & (access) ? 2 : 0) | \
4347 (2 & (access) ? 4 : 0) | \
4348 (3 & (access) ? 8 : 0) | \
4349 (4 & (access) ? 16 : 0) | \
4350 (5 & (access) ? 32 : 0) | \
4351 (6 & (access) ? 64 : 0) | \
4352 (7 & (access) ? 128 : 0))
4353
4354
c596f147 4355static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
97d64b78 4356{
09f037aa
PB
4357 unsigned byte;
4358
4359 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4360 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4361 const u8 u = BYTE_MASK(ACC_USER_MASK);
4362
c596f147
SC
4363 bool cr4_smep = is_cr4_smep(mmu);
4364 bool cr4_smap = is_cr4_smap(mmu);
4365 bool cr0_wp = is_cr0_wp(mmu);
90599c28 4366 bool efer_nx = is_efer_nx(mmu);
97d64b78 4367
97d64b78 4368 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
09f037aa
PB
4369 unsigned pfec = byte << 1;
4370
97ec8c06 4371 /*
09f037aa
PB
4372 * Each "*f" variable has a 1 bit for each UWX value
4373 * that causes a fault with the given PFEC.
97ec8c06 4374 */
97d64b78 4375
09f037aa 4376 /* Faults from writes to non-writable pages */
a6a6d3b1 4377 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
09f037aa 4378 /* Faults from user mode accesses to supervisor pages */
a6a6d3b1 4379 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
09f037aa 4380 /* Faults from fetches of non-executable pages*/
a6a6d3b1 4381 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
09f037aa
PB
4382 /* Faults from kernel mode fetches of user pages */
4383 u8 smepf = 0;
4384 /* Faults from kernel mode accesses of user pages */
4385 u8 smapf = 0;
4386
4387 if (!ept) {
4388 /* Faults from kernel mode accesses to user pages */
4389 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4390
4391 /* Not really needed: !nx will cause pte.nx to fault */
90599c28 4392 if (!efer_nx)
09f037aa
PB
4393 ff = 0;
4394
4395 /* Allow supervisor writes if !cr0.wp */
4396 if (!cr0_wp)
4397 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4398
4399 /* Disallow supervisor fetches of user code if cr4.smep */
4400 if (cr4_smep)
4401 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4402
4403 /*
4404 * SMAP:kernel-mode data accesses from user-mode
4405 * mappings should fault. A fault is considered
4406 * as a SMAP violation if all of the following
39337ad1 4407 * conditions are true:
09f037aa
PB
4408 * - X86_CR4_SMAP is set in CR4
4409 * - A user page is accessed
4410 * - The access is not a fetch
4411 * - Page fault in kernel mode
4412 * - if CPL = 3 or X86_EFLAGS_AC is clear
4413 *
4414 * Here, we cover the first three conditions.
4415 * The fourth is computed dynamically in permission_fault();
4416 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4417 * *not* subject to SMAP restrictions.
4418 */
4419 if (cr4_smap)
4420 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
97d64b78 4421 }
09f037aa
PB
4422
4423 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
97d64b78
AK
4424 }
4425}
4426
2d344105
HH
4427/*
4428* PKU is an additional mechanism by which the paging controls access to
4429* user-mode addresses based on the value in the PKRU register. Protection
4430* key violations are reported through a bit in the page fault error code.
4431* Unlike other bits of the error code, the PK bit is not known at the
4432* call site of e.g. gva_to_gpa; it must be computed directly in
4433* permission_fault based on two bits of PKRU, on some machine state (CR4,
4434* CR0, EFER, CPL), and on other bits of the error code and the page tables.
4435*
4436* In particular the following conditions come from the error code, the
4437* page tables and the machine state:
4438* - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4439* - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4440* - PK is always zero if U=0 in the page tables
4441* - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4442*
4443* The PKRU bitmask caches the result of these four conditions. The error
4444* code (minus the P bit) and the page table's U bit form an index into the
4445* PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4446* with the two bits of the PKRU register corresponding to the protection key.
4447* For the first three conditions above the bits will be 00, thus masking
4448* away both AD and WD. For all reads or if the last condition holds, WD
4449* only will be masked away.
4450*/
2e4c0661 4451static void update_pkru_bitmask(struct kvm_mmu *mmu)
2d344105
HH
4452{
4453 unsigned bit;
4454 bool wp;
4455
2e4c0661 4456 if (!is_cr4_pke(mmu)) {
2d344105
HH
4457 mmu->pkru_mask = 0;
4458 return;
4459 }
4460
2e4c0661 4461 wp = is_cr0_wp(mmu);
2d344105
HH
4462
4463 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4464 unsigned pfec, pkey_bits;
4465 bool check_pkey, check_write, ff, uf, wf, pte_user;
4466
4467 pfec = bit << 1;
4468 ff = pfec & PFERR_FETCH_MASK;
4469 uf = pfec & PFERR_USER_MASK;
4470 wf = pfec & PFERR_WRITE_MASK;
4471
4472 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4473 pte_user = pfec & PFERR_RSVD_MASK;
4474
4475 /*
4476 * Only need to check the access which is not an
4477 * instruction fetch and is to a user page.
4478 */
4479 check_pkey = (!ff && pte_user);
4480 /*
4481 * write access is controlled by PKRU if it is a
4482 * user access or CR0.WP = 1.
4483 */
4484 check_write = check_pkey && wf && (uf || wp);
4485
4486 /* PKRU.AD stops both read and write access. */
4487 pkey_bits = !!check_pkey;
4488 /* PKRU.WD stops write access. */
4489 pkey_bits |= (!!check_write) << 1;
4490
4491 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4492 }
4493}
4494
533f9a4b
SC
4495static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
4496 struct kvm_mmu *mmu)
6fd01b71 4497{
533f9a4b
SC
4498 if (!is_cr0_pg(mmu))
4499 return;
6bb69c9b 4500
533f9a4b
SC
4501 reset_rsvds_bits_mask(vcpu, mmu);
4502 update_permission_bitmask(mmu, false);
4503 update_pkru_bitmask(mmu);
6fd01b71
AK
4504}
4505
fe660f72 4506static void paging64_init_context(struct kvm_mmu *context)
6aa8b732 4507{
6aa8b732 4508 context->page_fault = paging64_page_fault;
6aa8b732 4509 context->gva_to_gpa = paging64_gva_to_gpa;
e8bc217a 4510 context->sync_page = paging64_sync_page;
a7052897 4511 context->invlpg = paging64_invlpg;
c5a78f2b 4512 context->direct_map = false;
6aa8b732
AK
4513}
4514
84a16226 4515static void paging32_init_context(struct kvm_mmu *context)
6aa8b732 4516{
6aa8b732 4517 context->page_fault = paging32_page_fault;
6aa8b732 4518 context->gva_to_gpa = paging32_gva_to_gpa;
e8bc217a 4519 context->sync_page = paging32_sync_page;
a7052897 4520 context->invlpg = paging32_invlpg;
c5a78f2b 4521 context->direct_map = false;
6aa8b732
AK
4522}
4523
8626c120
SC
4524static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu,
4525 struct kvm_mmu_role_regs *regs)
a336282d
VK
4526{
4527 union kvm_mmu_extended_role ext = {0};
4528
ca8d664f
SC
4529 if (____is_cr0_pg(regs)) {
4530 ext.cr0_pg = 1;
4531 ext.cr4_pae = ____is_cr4_pae(regs);
4532 ext.cr4_smep = ____is_cr4_smep(regs);
4533 ext.cr4_smap = ____is_cr4_smap(regs);
4534 ext.cr4_pse = ____is_cr4_pse(regs);
84c679f5
SC
4535
4536 /* PKEY and LA57 are active iff long mode is active. */
4537 ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
4538 ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
ca8d664f 4539 }
a336282d
VK
4540
4541 ext.valid = 1;
4542
4543 return ext;
4544}
4545
7dcd5755 4546static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
8626c120 4547 struct kvm_mmu_role_regs *regs,
7dcd5755
VK
4548 bool base_only)
4549{
4550 union kvm_mmu_role role = {0};
4551
4552 role.base.access = ACC_ALL;
ca8d664f
SC
4553 if (____is_cr0_pg(regs)) {
4554 role.base.efer_nx = ____is_efer_nx(regs);
4555 role.base.cr0_wp = ____is_cr0_wp(regs);
4556 }
7dcd5755
VK
4557 role.base.smm = is_smm(vcpu);
4558 role.base.guest_mode = is_guest_mode(vcpu);
4559
4560 if (base_only)
4561 return role;
4562
8626c120 4563 role.ext = kvm_calc_mmu_role_ext(vcpu, regs);
7dcd5755
VK
4564
4565 return role;
4566}
4567
d468d94b
SC
4568static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4569{
4570 /* Use 5-level TDP if and only if it's useful/necessary. */
83013059 4571 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
d468d94b
SC
4572 return 4;
4573
83013059 4574 return max_tdp_level;
d468d94b
SC
4575}
4576
7dcd5755 4577static union kvm_mmu_role
8626c120
SC
4578kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
4579 struct kvm_mmu_role_regs *regs, bool base_only)
9fa72119 4580{
8626c120 4581 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, regs, base_only);
9fa72119 4582
7dcd5755 4583 role.base.ad_disabled = (shadow_accessed_mask == 0);
d468d94b 4584 role.base.level = kvm_mmu_get_tdp_level(vcpu);
7dcd5755 4585 role.base.direct = true;
47c42e6b 4586 role.base.gpte_is_8_bytes = true;
9fa72119
JS
4587
4588 return role;
4589}
4590
8a3c1a33 4591static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
fb72d167 4592{
8c008659 4593 struct kvm_mmu *context = &vcpu->arch.root_mmu;
8626c120 4594 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
7dcd5755 4595 union kvm_mmu_role new_role =
8626c120 4596 kvm_calc_tdp_mmu_root_page_role(vcpu, &regs, false);
fb72d167 4597
7dcd5755
VK
4598 if (new_role.as_u64 == context->mmu_role.as_u64)
4599 return;
4600
4601 context->mmu_role.as_u64 = new_role.as_u64;
7a02674d 4602 context->page_fault = kvm_tdp_page_fault;
e8bc217a 4603 context->sync_page = nonpaging_sync_page;
5efac074 4604 context->invlpg = NULL;
d468d94b 4605 context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
c5a78f2b 4606 context->direct_map = true;
d8dd54e0 4607 context->get_guest_pgd = get_cr3;
e4e517b4 4608 context->get_pdptr = kvm_pdptr_read;
cb659db8 4609 context->inject_page_fault = kvm_inject_page_fault;
f4bd6f73 4610 context->root_level = role_regs_to_root_level(&regs);
fb72d167 4611
36f26787 4612 if (!is_cr0_pg(context))
fb72d167 4613 context->gva_to_gpa = nonpaging_gva_to_gpa;
36f26787 4614 else if (is_cr4_pae(context))
4d6931c3 4615 context->gva_to_gpa = paging64_gva_to_gpa;
f4bd6f73 4616 else
4d6931c3 4617 context->gva_to_gpa = paging32_gva_to_gpa;
fb72d167 4618
533f9a4b 4619 reset_guest_paging_metadata(vcpu, context);
c258b62b 4620 reset_tdp_shadow_zero_bits_mask(vcpu, context);
fb72d167
JR
4621}
4622
7dcd5755 4623static union kvm_mmu_role
8626c120
SC
4624kvm_calc_shadow_root_page_role_common(struct kvm_vcpu *vcpu,
4625 struct kvm_mmu_role_regs *regs, bool base_only)
7dcd5755 4626{
8626c120 4627 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, regs, base_only);
7dcd5755 4628
8626c120
SC
4629 role.base.smep_andnot_wp = role.ext.cr4_smep && !____is_cr0_wp(regs);
4630 role.base.smap_andnot_wp = role.ext.cr4_smap && !____is_cr0_wp(regs);
ca8d664f 4631 role.base.gpte_is_8_bytes = ____is_cr0_pg(regs) && ____is_cr4_pae(regs);
9fa72119 4632
59505b55
SC
4633 return role;
4634}
4635
4636static union kvm_mmu_role
8626c120
SC
4637kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu,
4638 struct kvm_mmu_role_regs *regs, bool base_only)
59505b55
SC
4639{
4640 union kvm_mmu_role role =
8626c120 4641 kvm_calc_shadow_root_page_role_common(vcpu, regs, base_only);
59505b55 4642
8626c120 4643 role.base.direct = !____is_cr0_pg(regs);
59505b55 4644
8626c120 4645 if (!____is_efer_lma(regs))
7dcd5755 4646 role.base.level = PT32E_ROOT_LEVEL;
8626c120 4647 else if (____is_cr4_la57(regs))
7dcd5755 4648 role.base.level = PT64_ROOT_5LEVEL;
9fa72119 4649 else
7dcd5755 4650 role.base.level = PT64_ROOT_4LEVEL;
9fa72119
JS
4651
4652 return role;
4653}
4654
8c008659 4655static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
594e91a1 4656 struct kvm_mmu_role_regs *regs,
8c008659 4657 union kvm_mmu_role new_role)
9fa72119 4658{
18db1b17
SC
4659 if (new_role.as_u64 == context->mmu_role.as_u64)
4660 return;
a770f6f2 4661
7dcd5755 4662 context->mmu_role.as_u64 = new_role.as_u64;
18db1b17 4663
36f26787 4664 if (!is_cr0_pg(context))
84a16226 4665 nonpaging_init_context(context);
36f26787 4666 else if (is_cr4_pae(context))
fe660f72 4667 paging64_init_context(context);
6aa8b732 4668 else
84a16226 4669 paging32_init_context(context);
f4bd6f73 4670 context->root_level = role_regs_to_root_level(regs);
a770f6f2 4671
533f9a4b 4672 reset_guest_paging_metadata(vcpu, context);
d555f705
SC
4673 context->shadow_root_level = new_role.base.level;
4674
c258b62b 4675 reset_shadow_zero_bits_mask(vcpu, context);
52fde8df 4676}
0f04a2ac 4677
594e91a1
SC
4678static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
4679 struct kvm_mmu_role_regs *regs)
0f04a2ac 4680{
8c008659 4681 struct kvm_mmu *context = &vcpu->arch.root_mmu;
0f04a2ac 4682 union kvm_mmu_role new_role =
8626c120 4683 kvm_calc_shadow_mmu_root_page_role(vcpu, regs, false);
0f04a2ac 4684
18db1b17 4685 shadow_mmu_init_context(vcpu, context, regs, new_role);
0f04a2ac
VK
4686}
4687
59505b55 4688static union kvm_mmu_role
8626c120
SC
4689kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu,
4690 struct kvm_mmu_role_regs *regs)
59505b55
SC
4691{
4692 union kvm_mmu_role role =
8626c120 4693 kvm_calc_shadow_root_page_role_common(vcpu, regs, false);
59505b55
SC
4694
4695 role.base.direct = false;
d468d94b 4696 role.base.level = kvm_mmu_get_tdp_level(vcpu);
59505b55
SC
4697
4698 return role;
4699}
4700
dbc4739b
SC
4701void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
4702 unsigned long cr4, u64 efer, gpa_t nested_cr3)
0f04a2ac 4703{
8c008659 4704 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
594e91a1
SC
4705 struct kvm_mmu_role_regs regs = {
4706 .cr0 = cr0,
4707 .cr4 = cr4,
4708 .efer = efer,
4709 };
8626c120 4710 union kvm_mmu_role new_role;
0f04a2ac 4711
8626c120 4712 new_role = kvm_calc_shadow_npt_root_page_role(vcpu, &regs);
a506fdd2 4713
b5129100 4714 __kvm_mmu_new_pgd(vcpu, nested_cr3, new_role.base);
a3322d5c 4715
18db1b17 4716 shadow_mmu_init_context(vcpu, context, &regs, new_role);
0f04a2ac
VK
4717}
4718EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
52fde8df 4719
a336282d
VK
4720static union kvm_mmu_role
4721kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
bb1fcc70 4722 bool execonly, u8 level)
9fa72119 4723{
552c69b1 4724 union kvm_mmu_role role = {0};
14c07ad8 4725
47c42e6b
SC
4726 /* SMM flag is inherited from root_mmu */
4727 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
9fa72119 4728
bb1fcc70 4729 role.base.level = level;
47c42e6b 4730 role.base.gpte_is_8_bytes = true;
a336282d
VK
4731 role.base.direct = false;
4732 role.base.ad_disabled = !accessed_dirty;
4733 role.base.guest_mode = true;
4734 role.base.access = ACC_ALL;
9fa72119 4735
cd6767c3
SC
4736 /* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
4737 role.ext.word = 0;
a336282d 4738 role.ext.execonly = execonly;
cd6767c3 4739 role.ext.valid = 1;
9fa72119
JS
4740
4741 return role;
4742}
4743
ae1e2d10 4744void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
50c28f21 4745 bool accessed_dirty, gpa_t new_eptp)
155a97a3 4746{
8c008659 4747 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
bb1fcc70 4748 u8 level = vmx_eptp_page_walk_level(new_eptp);
a336282d
VK
4749 union kvm_mmu_role new_role =
4750 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
bb1fcc70 4751 execonly, level);
a336282d 4752
b5129100 4753 __kvm_mmu_new_pgd(vcpu, new_eptp, new_role.base);
a336282d 4754
a336282d
VK
4755 if (new_role.as_u64 == context->mmu_role.as_u64)
4756 return;
ad896af0 4757
18db1b17
SC
4758 context->mmu_role.as_u64 = new_role.as_u64;
4759
bb1fcc70 4760 context->shadow_root_level = level;
155a97a3 4761
ae1e2d10 4762 context->ept_ad = accessed_dirty;
155a97a3
NHE
4763 context->page_fault = ept_page_fault;
4764 context->gva_to_gpa = ept_gva_to_gpa;
4765 context->sync_page = ept_sync_page;
4766 context->invlpg = ept_invlpg;
bb1fcc70 4767 context->root_level = level;
155a97a3 4768 context->direct_map = false;
3dc773e7 4769
c596f147 4770 update_permission_bitmask(context, true);
2e4c0661 4771 update_pkru_bitmask(context);
155a97a3 4772 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
c258b62b 4773 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
155a97a3
NHE
4774}
4775EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4776
8a3c1a33 4777static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
52fde8df 4778{
8c008659 4779 struct kvm_mmu *context = &vcpu->arch.root_mmu;
594e91a1 4780 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
ad896af0 4781
594e91a1 4782 kvm_init_shadow_mmu(vcpu, &regs);
929d1cfa 4783
d8dd54e0 4784 context->get_guest_pgd = get_cr3;
ad896af0
PB
4785 context->get_pdptr = kvm_pdptr_read;
4786 context->inject_page_fault = kvm_inject_page_fault;
6aa8b732
AK
4787}
4788
8626c120
SC
4789static union kvm_mmu_role
4790kvm_calc_nested_mmu_role(struct kvm_vcpu *vcpu, struct kvm_mmu_role_regs *regs)
654430ef 4791{
8626c120
SC
4792 union kvm_mmu_role role;
4793
4794 role = kvm_calc_shadow_root_page_role_common(vcpu, regs, false);
654430ef
SC
4795
4796 /*
4797 * Nested MMUs are used only for walking L2's gva->gpa, they never have
4798 * shadow pages of their own and so "direct" has no meaning. Set it
4799 * to "true" to try to detect bogus usage of the nested MMU.
4800 */
4801 role.base.direct = true;
f4bd6f73 4802 role.base.level = role_regs_to_root_level(regs);
654430ef
SC
4803 return role;
4804}
4805
8a3c1a33 4806static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
02f59dc9 4807{
8626c120
SC
4808 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
4809 union kvm_mmu_role new_role = kvm_calc_nested_mmu_role(vcpu, &regs);
02f59dc9
JR
4810 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4811
bf627a92
VK
4812 if (new_role.as_u64 == g_context->mmu_role.as_u64)
4813 return;
4814
4815 g_context->mmu_role.as_u64 = new_role.as_u64;
d8dd54e0 4816 g_context->get_guest_pgd = get_cr3;
e4e517b4 4817 g_context->get_pdptr = kvm_pdptr_read;
02f59dc9 4818 g_context->inject_page_fault = kvm_inject_page_fault;
5472fcd4 4819 g_context->root_level = new_role.base.level;
02f59dc9 4820
5efac074
PB
4821 /*
4822 * L2 page tables are never shadowed, so there is no need to sync
4823 * SPTEs.
4824 */
4825 g_context->invlpg = NULL;
4826
02f59dc9 4827 /*
44dd3ffa 4828 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
0af2593b
DM
4829 * L1's nested page tables (e.g. EPT12). The nested translation
4830 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4831 * L2's page tables as the first level of translation and L1's
4832 * nested page tables as the second level of translation. Basically
4833 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
02f59dc9 4834 */
fa4b5588 4835 if (!is_paging(vcpu))
02f59dc9 4836 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
fa4b5588 4837 else if (is_long_mode(vcpu))
02f59dc9 4838 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
fa4b5588 4839 else if (is_pae(vcpu))
02f59dc9 4840 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
fa4b5588 4841 else
02f59dc9 4842 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
02f59dc9 4843
533f9a4b 4844 reset_guest_paging_metadata(vcpu, g_context);
02f59dc9
JR
4845}
4846
c9060662 4847void kvm_init_mmu(struct kvm_vcpu *vcpu)
fb72d167 4848{
02f59dc9 4849 if (mmu_is_nested(vcpu))
e0c6db3e 4850 init_kvm_nested_mmu(vcpu);
02f59dc9 4851 else if (tdp_enabled)
e0c6db3e 4852 init_kvm_tdp_mmu(vcpu);
fb72d167 4853 else
e0c6db3e 4854 init_kvm_softmmu(vcpu);
fb72d167 4855}
1c53da3f 4856EXPORT_SYMBOL_GPL(kvm_init_mmu);
fb72d167 4857
9fa72119
JS
4858static union kvm_mmu_page_role
4859kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
4860{
8626c120 4861 struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
7dcd5755
VK
4862 union kvm_mmu_role role;
4863
9fa72119 4864 if (tdp_enabled)
8626c120 4865 role = kvm_calc_tdp_mmu_root_page_role(vcpu, &regs, true);
9fa72119 4866 else
8626c120 4867 role = kvm_calc_shadow_mmu_root_page_role(vcpu, &regs, true);
7dcd5755
VK
4868
4869 return role.base;
9fa72119 4870}
fb72d167 4871
49c6f875
SC
4872void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
4873{
4874 /*
4875 * Invalidate all MMU roles to force them to reinitialize as CPUID
4876 * information is factored into reserved bit calculations.
4877 */
4878 vcpu->arch.root_mmu.mmu_role.ext.valid = 0;
4879 vcpu->arch.guest_mmu.mmu_role.ext.valid = 0;
4880 vcpu->arch.nested_mmu.mmu_role.ext.valid = 0;
4881 kvm_mmu_reset_context(vcpu);
63f5a190
SC
4882
4883 /*
4884 * KVM does not correctly handle changing guest CPUID after KVM_RUN, as
4885 * MAXPHYADDR, GBPAGES support, AMD reserved bit behavior, etc.. aren't
4886 * tracked in kvm_mmu_page_role. As a result, KVM may miss guest page
4887 * faults due to reusing SPs/SPTEs. Alert userspace, but otherwise
4888 * sweep the problem under the rug.
4889 *
4890 * KVM's horrific CPUID ABI makes the problem all but impossible to
4891 * solve, as correctly handling multiple vCPU models (with respect to
4892 * paging and physical address properties) in a single VM would require
4893 * tracking all relevant CPUID information in kvm_mmu_page_role. That
4894 * is very undesirable as it would double the memory requirements for
4895 * gfn_track (see struct kvm_mmu_page_role comments), and in practice
4896 * no sane VMM mucks with the core vCPU model on the fly.
4897 */
4898 if (vcpu->arch.last_vmentry_cpu != -1) {
4899 pr_warn_ratelimited("KVM: KVM_SET_CPUID{,2} after KVM_RUN may cause guest instability\n");
4900 pr_warn_ratelimited("KVM: KVM_SET_CPUID{,2} will fail after KVM_RUN starting with Linux 5.16\n");
4901 }
49c6f875
SC
4902}
4903
8a3c1a33 4904void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
6aa8b732 4905{
95f93af4 4906 kvm_mmu_unload(vcpu);
c9060662 4907 kvm_init_mmu(vcpu);
17c3ba9d 4908}
8668a3c4 4909EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
17c3ba9d
AK
4910
4911int kvm_mmu_load(struct kvm_vcpu *vcpu)
6aa8b732 4912{
714b93da
AK
4913 int r;
4914
378f5cd6 4915 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
17c3ba9d
AK
4916 if (r)
4917 goto out;
748e52b9 4918 r = mmu_alloc_special_roots(vcpu);
17c3ba9d
AK
4919 if (r)
4920 goto out;
4a38162e 4921 if (vcpu->arch.mmu->direct_map)
6e6ec584
SC
4922 r = mmu_alloc_direct_roots(vcpu);
4923 else
4924 r = mmu_alloc_shadow_roots(vcpu);
8986ecc0
MT
4925 if (r)
4926 goto out;
a91f387b
SC
4927
4928 kvm_mmu_sync_roots(vcpu);
4929
727a7e27 4930 kvm_mmu_load_pgd(vcpu);
b3646477 4931 static_call(kvm_x86_tlb_flush_current)(vcpu);
714b93da
AK
4932out:
4933 return r;
6aa8b732 4934}
17c3ba9d
AK
4935
4936void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4937{
14c07ad8
VK
4938 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
4939 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
4940 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
4941 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
17c3ba9d 4942}
6aa8b732 4943
79539cec
AK
4944static bool need_remote_flush(u64 old, u64 new)
4945{
4946 if (!is_shadow_present_pte(old))
4947 return false;
4948 if (!is_shadow_present_pte(new))
4949 return true;
4950 if ((old ^ new) & PT64_BASE_ADDR_MASK)
4951 return true;
53166229
GN
4952 old ^= shadow_nx_mask;
4953 new ^= shadow_nx_mask;
79539cec
AK
4954 return (old & ~new & PT64_PERM_MASK) != 0;
4955}
4956
889e5cbc 4957static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
0e0fee5c 4958 int *bytes)
da4a00f0 4959{
0e0fee5c 4960 u64 gentry = 0;
889e5cbc 4961 int r;
72016f3a 4962
72016f3a
AK
4963 /*
4964 * Assume that the pte write on a page table of the same type
49b26e26
XG
4965 * as the current vcpu paging mode since we update the sptes only
4966 * when they have the same mode.
72016f3a 4967 */
889e5cbc 4968 if (is_pae(vcpu) && *bytes == 4) {
72016f3a 4969 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
889e5cbc
XG
4970 *gpa &= ~(gpa_t)7;
4971 *bytes = 8;
08e850c6
AK
4972 }
4973
0e0fee5c
JS
4974 if (*bytes == 4 || *bytes == 8) {
4975 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
4976 if (r)
4977 gentry = 0;
72016f3a
AK
4978 }
4979
889e5cbc
XG
4980 return gentry;
4981}
4982
4983/*
4984 * If we're seeing too many writes to a page, it may no longer be a page table,
4985 * or we may be forking, in which case it is better to unmap the page.
4986 */
a138fe75 4987static bool detect_write_flooding(struct kvm_mmu_page *sp)
889e5cbc 4988{
a30f47cb
XG
4989 /*
4990 * Skip write-flooding detected for the sp whose level is 1, because
4991 * it can become unsync, then the guest page is not write-protected.
4992 */
3bae0459 4993 if (sp->role.level == PG_LEVEL_4K)
a30f47cb 4994 return false;
3246af0e 4995
e5691a81
XG
4996 atomic_inc(&sp->write_flooding_count);
4997 return atomic_read(&sp->write_flooding_count) >= 3;
889e5cbc
XG
4998}
4999
5000/*
5001 * Misaligned accesses are too much trouble to fix up; also, they usually
5002 * indicate a page is not used as a page table.
5003 */
5004static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5005 int bytes)
5006{
5007 unsigned offset, pte_size, misaligned;
5008
5009 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5010 gpa, bytes, sp->role.word);
5011
5012 offset = offset_in_page(gpa);
47c42e6b 5013 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5d9ca30e
XG
5014
5015 /*
5016 * Sometimes, the OS only writes the last one bytes to update status
5017 * bits, for example, in linux, andb instruction is used in clear_bit().
5018 */
5019 if (!(offset & (pte_size - 1)) && bytes == 1)
5020 return false;
5021
889e5cbc
XG
5022 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5023 misaligned |= bytes < 4;
5024
5025 return misaligned;
5026}
5027
5028static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5029{
5030 unsigned page_offset, quadrant;
5031 u64 *spte;
5032 int level;
5033
5034 page_offset = offset_in_page(gpa);
5035 level = sp->role.level;
5036 *nspte = 1;
47c42e6b 5037 if (!sp->role.gpte_is_8_bytes) {
889e5cbc
XG
5038 page_offset <<= 1; /* 32->64 */
5039 /*
5040 * A 32-bit pde maps 4MB while the shadow pdes map
5041 * only 2MB. So we need to double the offset again
5042 * and zap two pdes instead of one.
5043 */
5044 if (level == PT32_ROOT_LEVEL) {
5045 page_offset &= ~7; /* kill rounding error */
5046 page_offset <<= 1;
5047 *nspte = 2;
5048 }
5049 quadrant = page_offset >> PAGE_SHIFT;
5050 page_offset &= ~PAGE_MASK;
5051 if (quadrant != sp->role.quadrant)
5052 return NULL;
5053 }
5054
5055 spte = &sp->spt[page_offset / sizeof(*spte)];
5056 return spte;
5057}
5058
13d268ca 5059static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
d126363d
JS
5060 const u8 *new, int bytes,
5061 struct kvm_page_track_notifier_node *node)
889e5cbc
XG
5062{
5063 gfn_t gfn = gpa >> PAGE_SHIFT;
889e5cbc 5064 struct kvm_mmu_page *sp;
889e5cbc
XG
5065 LIST_HEAD(invalid_list);
5066 u64 entry, gentry, *spte;
5067 int npte;
b8c67b7a 5068 bool remote_flush, local_flush;
889e5cbc
XG
5069
5070 /*
5071 * If we don't have indirect shadow pages, it means no page is
5072 * write-protected, so we can exit simply.
5073 */
6aa7de05 5074 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
889e5cbc
XG
5075 return;
5076
b8c67b7a 5077 remote_flush = local_flush = false;
889e5cbc
XG
5078
5079 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5080
889e5cbc
XG
5081 /*
5082 * No need to care whether allocation memory is successful
d9f6e12f 5083 * or not since pte prefetch is skipped if it does not have
889e5cbc
XG
5084 * enough objects in the cache.
5085 */
378f5cd6 5086 mmu_topup_memory_caches(vcpu, true);
889e5cbc 5087
531810ca 5088 write_lock(&vcpu->kvm->mmu_lock);
0e0fee5c
JS
5089
5090 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5091
889e5cbc 5092 ++vcpu->kvm->stat.mmu_pte_write;
0375f7fa 5093 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
889e5cbc 5094
b67bfe0d 5095 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
a30f47cb 5096 if (detect_write_misaligned(sp, gpa, bytes) ||
a138fe75 5097 detect_write_flooding(sp)) {
b8c67b7a 5098 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
4cee5764 5099 ++vcpu->kvm->stat.mmu_flooded;
0e7bc4b9
AK
5100 continue;
5101 }
889e5cbc
XG
5102
5103 spte = get_written_sptes(sp, gpa, &npte);
5104 if (!spte)
5105 continue;
5106
0671a8e7 5107 local_flush = true;
ac1b714e 5108 while (npte--) {
79539cec 5109 entry = *spte;
2de4085c 5110 mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
c5e2184d
SC
5111 if (gentry && sp->role.level != PG_LEVEL_4K)
5112 ++vcpu->kvm->stat.mmu_pde_zapped;
9bb4f6b1 5113 if (need_remote_flush(entry, *spte))
0671a8e7 5114 remote_flush = true;
ac1b714e 5115 ++spte;
9b7a0325 5116 }
9b7a0325 5117 }
b8c67b7a 5118 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
0375f7fa 5119 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
531810ca 5120 write_unlock(&vcpu->kvm->mmu_lock);
da4a00f0
AK
5121}
5122
736c291c 5123int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
dc25e89e 5124 void *insn, int insn_len)
3067714c 5125{
92daa48b 5126 int r, emulation_type = EMULTYPE_PF;
44dd3ffa 5127 bool direct = vcpu->arch.mmu->direct_map;
3067714c 5128
6948199a 5129 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
ddce6208
SC
5130 return RET_PF_RETRY;
5131
9b8ebbdb 5132 r = RET_PF_INVALID;
e9ee956e 5133 if (unlikely(error_code & PFERR_RSVD_MASK)) {
736c291c 5134 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
472faffa 5135 if (r == RET_PF_EMULATE)
e9ee956e 5136 goto emulate;
e9ee956e 5137 }
3067714c 5138
9b8ebbdb 5139 if (r == RET_PF_INVALID) {
7a02674d
SC
5140 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5141 lower_32_bits(error_code), false);
19025e7b 5142 if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
7b367bc9 5143 return -EIO;
9b8ebbdb
PB
5144 }
5145
3067714c 5146 if (r < 0)
e9ee956e 5147 return r;
83a2ba4c
SC
5148 if (r != RET_PF_EMULATE)
5149 return 1;
3067714c 5150
14727754
TL
5151 /*
5152 * Before emulating the instruction, check if the error code
5153 * was due to a RO violation while translating the guest page.
5154 * This can occur when using nested virtualization with nested
5155 * paging in both guests. If true, we simply unprotect the page
5156 * and resume the guest.
14727754 5157 */
44dd3ffa 5158 if (vcpu->arch.mmu->direct_map &&
eebed243 5159 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
736c291c 5160 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
14727754
TL
5161 return 1;
5162 }
5163
472faffa
SC
5164 /*
5165 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5166 * optimistically try to just unprotect the page and let the processor
5167 * re-execute the instruction that caused the page fault. Do not allow
5168 * retrying MMIO emulation, as it's not only pointless but could also
5169 * cause us to enter an infinite loop because the processor will keep
6c3dfeb6
SC
5170 * faulting on the non-existent MMIO address. Retrying an instruction
5171 * from a nested guest is also pointless and dangerous as we are only
5172 * explicitly shadowing L1's page tables, i.e. unprotecting something
5173 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
472faffa 5174 */
736c291c 5175 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
92daa48b 5176 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
e9ee956e 5177emulate:
736c291c 5178 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
60fc3d02 5179 insn_len);
3067714c
AK
5180}
5181EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5182
5efac074
PB
5183void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5184 gva_t gva, hpa_t root_hpa)
a7052897 5185{
b94742c9 5186 int i;
7eb77e9f 5187
5efac074
PB
5188 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5189 if (mmu != &vcpu->arch.guest_mmu) {
5190 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5191 if (is_noncanonical_address(gva, vcpu))
5192 return;
5193
b3646477 5194 static_call(kvm_x86_tlb_flush_gva)(vcpu, gva);
5efac074
PB
5195 }
5196
5197 if (!mmu->invlpg)
faff8758
JS
5198 return;
5199
5efac074
PB
5200 if (root_hpa == INVALID_PAGE) {
5201 mmu->invlpg(vcpu, gva, mmu->root_hpa);
956bf353 5202
5efac074
PB
5203 /*
5204 * INVLPG is required to invalidate any global mappings for the VA,
5205 * irrespective of PCID. Since it would take us roughly similar amount
5206 * of work to determine whether any of the prev_root mappings of the VA
5207 * is marked global, or to just sync it blindly, so we might as well
5208 * just always sync it.
5209 *
5210 * Mappings not reachable via the current cr3 or the prev_roots will be
5211 * synced when switching to that cr3, so nothing needs to be done here
5212 * for them.
5213 */
5214 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5215 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5216 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5217 } else {
5218 mmu->invlpg(vcpu, gva, root_hpa);
5219 }
5220}
956bf353 5221
5efac074
PB
5222void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5223{
5224 kvm_mmu_invalidate_gva(vcpu, vcpu->arch.mmu, gva, INVALID_PAGE);
a7052897
MT
5225 ++vcpu->stat.invlpg;
5226}
5227EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5228
5efac074 5229
eb4b248e
JS
5230void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5231{
44dd3ffa 5232 struct kvm_mmu *mmu = vcpu->arch.mmu;
faff8758 5233 bool tlb_flush = false;
b94742c9 5234 uint i;
eb4b248e
JS
5235
5236 if (pcid == kvm_get_active_pcid(vcpu)) {
7eb77e9f 5237 mmu->invlpg(vcpu, gva, mmu->root_hpa);
faff8758 5238 tlb_flush = true;
eb4b248e
JS
5239 }
5240
b94742c9
JS
5241 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5242 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
be01e8e2 5243 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
b94742c9
JS
5244 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5245 tlb_flush = true;
5246 }
956bf353 5247 }
ade61e28 5248
faff8758 5249 if (tlb_flush)
b3646477 5250 static_call(kvm_x86_tlb_flush_gva)(vcpu, gva);
faff8758 5251
eb4b248e
JS
5252 ++vcpu->stat.invlpg;
5253
5254 /*
b94742c9
JS
5255 * Mappings not reachable via the current cr3 or the prev_roots will be
5256 * synced when switching to that cr3, so nothing needs to be done here
5257 * for them.
eb4b248e
JS
5258 */
5259}
eb4b248e 5260
83013059
SC
5261void kvm_configure_mmu(bool enable_tdp, int tdp_max_root_level,
5262 int tdp_huge_page_level)
18552672 5263{
bde77235 5264 tdp_enabled = enable_tdp;
83013059 5265 max_tdp_level = tdp_max_root_level;
703c335d
SC
5266
5267 /*
1d92d2e8 5268 * max_huge_page_level reflects KVM's MMU capabilities irrespective
703c335d
SC
5269 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5270 * the kernel is not. But, KVM never creates a page size greater than
5271 * what is used by the kernel for any given HVA, i.e. the kernel's
5272 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5273 */
5274 if (tdp_enabled)
1d92d2e8 5275 max_huge_page_level = tdp_huge_page_level;
703c335d 5276 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
1d92d2e8 5277 max_huge_page_level = PG_LEVEL_1G;
703c335d 5278 else
1d92d2e8 5279 max_huge_page_level = PG_LEVEL_2M;
18552672 5280}
bde77235 5281EXPORT_SYMBOL_GPL(kvm_configure_mmu);
85875a13
SC
5282
5283/* The return value indicates if tlb flush on all vcpus is needed. */
0a234f5d
SC
5284typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head,
5285 struct kvm_memory_slot *slot);
85875a13
SC
5286
5287/* The caller should hold mmu-lock before calling this function. */
5288static __always_inline bool
5289slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5290 slot_level_handler fn, int start_level, int end_level,
1a61b7db
SC
5291 gfn_t start_gfn, gfn_t end_gfn, bool flush_on_yield,
5292 bool flush)
85875a13
SC
5293{
5294 struct slot_rmap_walk_iterator iterator;
85875a13
SC
5295
5296 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5297 end_gfn, &iterator) {
5298 if (iterator.rmap)
0a234f5d 5299 flush |= fn(kvm, iterator.rmap, memslot);
85875a13 5300
531810ca 5301 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
302695a5 5302 if (flush && flush_on_yield) {
f285c633
BG
5303 kvm_flush_remote_tlbs_with_address(kvm,
5304 start_gfn,
5305 iterator.gfn - start_gfn + 1);
85875a13
SC
5306 flush = false;
5307 }
531810ca 5308 cond_resched_rwlock_write(&kvm->mmu_lock);
85875a13
SC
5309 }
5310 }
5311
85875a13
SC
5312 return flush;
5313}
5314
5315static __always_inline bool
5316slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5317 slot_level_handler fn, int start_level, int end_level,
302695a5 5318 bool flush_on_yield)
85875a13
SC
5319{
5320 return slot_handle_level_range(kvm, memslot, fn, start_level,
5321 end_level, memslot->base_gfn,
5322 memslot->base_gfn + memslot->npages - 1,
1a61b7db 5323 flush_on_yield, false);
85875a13
SC
5324}
5325
85875a13
SC
5326static __always_inline bool
5327slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
302695a5 5328 slot_level_handler fn, bool flush_on_yield)
85875a13 5329{
3bae0459 5330 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
302695a5 5331 PG_LEVEL_4K, flush_on_yield);
85875a13
SC
5332}
5333
1cfff4d9 5334static void free_mmu_pages(struct kvm_mmu *mmu)
6aa8b732 5335{
4a98623d
SC
5336 if (!tdp_enabled && mmu->pae_root)
5337 set_memory_encrypted((unsigned long)mmu->pae_root, 1);
1cfff4d9 5338 free_page((unsigned long)mmu->pae_root);
03ca4589 5339 free_page((unsigned long)mmu->pml4_root);
6aa8b732
AK
5340}
5341
04d28e37 5342static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6aa8b732 5343{
17ac10ad 5344 struct page *page;
6aa8b732
AK
5345 int i;
5346
04d28e37
SC
5347 mmu->root_hpa = INVALID_PAGE;
5348 mmu->root_pgd = 0;
5349 mmu->translate_gpa = translate_gpa;
5350 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5351 mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5352
17ac10ad 5353 /*
b6b80c78
SC
5354 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5355 * while the PDP table is a per-vCPU construct that's allocated at MMU
5356 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5357 * x86_64. Therefore we need to allocate the PDP table in the first
04d45551
SC
5358 * 4GB of memory, which happens to fit the DMA32 zone. TDP paging
5359 * generally doesn't use PAE paging and can skip allocating the PDP
5360 * table. The main exception, handled here, is SVM's 32-bit NPT. The
5361 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
5362 * KVM; that horror is handled on-demand by mmu_alloc_shadow_roots().
17ac10ad 5363 */
d468d94b 5364 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
b6b80c78
SC
5365 return 0;
5366
254272ce 5367 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
17ac10ad 5368 if (!page)
d7fa6ab2
WY
5369 return -ENOMEM;
5370
1cfff4d9 5371 mmu->pae_root = page_address(page);
4a98623d
SC
5372
5373 /*
5374 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
5375 * get the CPU to treat the PDPTEs as encrypted. Decrypt the page so
5376 * that KVM's writes and the CPU's reads get along. Note, this is
5377 * only necessary when using shadow paging, as 64-bit NPT can get at
5378 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
5379 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
5380 */
5381 if (!tdp_enabled)
5382 set_memory_decrypted((unsigned long)mmu->pae_root, 1);
5383 else
5384 WARN_ON_ONCE(shadow_me_mask);
5385
17ac10ad 5386 for (i = 0; i < 4; ++i)
c834e5e4 5387 mmu->pae_root[i] = INVALID_PAE_ROOT;
17ac10ad 5388
6aa8b732 5389 return 0;
6aa8b732
AK
5390}
5391
8018c27b 5392int kvm_mmu_create(struct kvm_vcpu *vcpu)
6aa8b732 5393{
1cfff4d9 5394 int ret;
b94742c9 5395
5962bfb7 5396 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
5f6078f9
SC
5397 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
5398
5962bfb7 5399 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
5f6078f9 5400 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
5962bfb7 5401
96880883
SC
5402 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
5403
44dd3ffa
VK
5404 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5405 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6aa8b732 5406
14c07ad8 5407 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
1cfff4d9 5408
04d28e37 5409 ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
1cfff4d9
JP
5410 if (ret)
5411 return ret;
5412
04d28e37 5413 ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
1cfff4d9
JP
5414 if (ret)
5415 goto fail_allocate_root;
5416
5417 return ret;
5418 fail_allocate_root:
5419 free_mmu_pages(&vcpu->arch.guest_mmu);
5420 return ret;
6aa8b732
AK
5421}
5422
fbb158cb 5423#define BATCH_ZAP_PAGES 10
002c5f73
SC
5424static void kvm_zap_obsolete_pages(struct kvm *kvm)
5425{
5426 struct kvm_mmu_page *sp, *node;
fbb158cb 5427 int nr_zapped, batch = 0;
002c5f73
SC
5428
5429restart:
5430 list_for_each_entry_safe_reverse(sp, node,
5431 &kvm->arch.active_mmu_pages, link) {
5432 /*
5433 * No obsolete valid page exists before a newly created page
5434 * since active_mmu_pages is a FIFO list.
5435 */
5436 if (!is_obsolete_sp(kvm, sp))
5437 break;
5438
5439 /*
f95eec9b
SC
5440 * Invalid pages should never land back on the list of active
5441 * pages. Skip the bogus page, otherwise we'll get stuck in an
5442 * infinite loop if the page gets put back on the list (again).
002c5f73 5443 */
f95eec9b 5444 if (WARN_ON(sp->role.invalid))
002c5f73
SC
5445 continue;
5446
4506ecf4
SC
5447 /*
5448 * No need to flush the TLB since we're only zapping shadow
5449 * pages with an obsolete generation number and all vCPUS have
5450 * loaded a new root, i.e. the shadow pages being zapped cannot
5451 * be in active use by the guest.
5452 */
fbb158cb 5453 if (batch >= BATCH_ZAP_PAGES &&
531810ca 5454 cond_resched_rwlock_write(&kvm->mmu_lock)) {
fbb158cb 5455 batch = 0;
002c5f73
SC
5456 goto restart;
5457 }
5458
10605204
SC
5459 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5460 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
fbb158cb 5461 batch += nr_zapped;
002c5f73 5462 goto restart;
fbb158cb 5463 }
002c5f73
SC
5464 }
5465
4506ecf4
SC
5466 /*
5467 * Trigger a remote TLB flush before freeing the page tables to ensure
5468 * KVM is not in the middle of a lockless shadow page table walk, which
5469 * may reference the pages.
5470 */
10605204 5471 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
002c5f73
SC
5472}
5473
5474/*
5475 * Fast invalidate all shadow pages and use lock-break technique
5476 * to zap obsolete pages.
5477 *
5478 * It's required when memslot is being deleted or VM is being
5479 * destroyed, in these cases, we should ensure that KVM MMU does
5480 * not use any resource of the being-deleted slot or all slots
5481 * after calling the function.
5482 */
5483static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5484{
ca333add
SC
5485 lockdep_assert_held(&kvm->slots_lock);
5486
531810ca 5487 write_lock(&kvm->mmu_lock);
14a3c4f4 5488 trace_kvm_mmu_zap_all_fast(kvm);
ca333add
SC
5489
5490 /*
5491 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5492 * held for the entire duration of zapping obsolete pages, it's
5493 * impossible for there to be multiple invalid generations associated
5494 * with *valid* shadow pages at any given time, i.e. there is exactly
5495 * one valid generation and (at most) one invalid generation.
5496 */
5497 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
002c5f73 5498
b7cccd39
BG
5499 /* In order to ensure all threads see this change when
5500 * handling the MMU reload signal, this must happen in the
5501 * same critical section as kvm_reload_remote_mmus, and
5502 * before kvm_zap_obsolete_pages as kvm_zap_obsolete_pages
5503 * could drop the MMU lock and yield.
5504 */
5505 if (is_tdp_mmu_enabled(kvm))
5506 kvm_tdp_mmu_invalidate_all_roots(kvm);
5507
4506ecf4
SC
5508 /*
5509 * Notify all vcpus to reload its shadow page table and flush TLB.
5510 * Then all vcpus will switch to new shadow page table with the new
5511 * mmu_valid_gen.
5512 *
5513 * Note: we need to do this under the protection of mmu_lock,
5514 * otherwise, vcpu would purge shadow page but miss tlb flush.
5515 */
5516 kvm_reload_remote_mmus(kvm);
5517
002c5f73 5518 kvm_zap_obsolete_pages(kvm);
faaf05b0 5519
531810ca 5520 write_unlock(&kvm->mmu_lock);
4c6654bd
BG
5521
5522 if (is_tdp_mmu_enabled(kvm)) {
5523 read_lock(&kvm->mmu_lock);
5524 kvm_tdp_mmu_zap_invalidated_roots(kvm);
5525 read_unlock(&kvm->mmu_lock);
5526 }
002c5f73
SC
5527}
5528
10605204
SC
5529static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5530{
5531 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5532}
5533
b5f5fdca 5534static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
d126363d
JS
5535 struct kvm_memory_slot *slot,
5536 struct kvm_page_track_notifier_node *node)
b5f5fdca 5537{
002c5f73 5538 kvm_mmu_zap_all_fast(kvm);
1bad2b2a
XG
5539}
5540
13d268ca 5541void kvm_mmu_init_vm(struct kvm *kvm)
1bad2b2a 5542{
13d268ca 5543 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
1bad2b2a 5544
d501f747
BG
5545 if (!kvm_mmu_init_tdp_mmu(kvm))
5546 /*
5547 * No smp_load/store wrappers needed here as we are in
5548 * VM init and there cannot be any memslots / other threads
5549 * accessing this struct kvm yet.
5550 */
5551 kvm->arch.memslots_have_rmaps = true;
fe5db27d 5552
13d268ca 5553 node->track_write = kvm_mmu_pte_write;
b5f5fdca 5554 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
13d268ca 5555 kvm_page_track_register_notifier(kvm, node);
1bad2b2a
XG
5556}
5557
13d268ca 5558void kvm_mmu_uninit_vm(struct kvm *kvm)
1bad2b2a 5559{
13d268ca 5560 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
1bad2b2a 5561
13d268ca 5562 kvm_page_track_unregister_notifier(kvm, node);
fe5db27d
BG
5563
5564 kvm_mmu_uninit_tdp_mmu(kvm);
1bad2b2a
XG
5565}
5566
efdfe536
XG
5567void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5568{
5569 struct kvm_memslots *slots;
5570 struct kvm_memory_slot *memslot;
9da0e4d5 5571 int i;
1a61b7db 5572 bool flush = false;
efdfe536 5573
e2209710
BG
5574 if (kvm_memslots_have_rmaps(kvm)) {
5575 write_lock(&kvm->mmu_lock);
5576 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5577 slots = __kvm_memslots(kvm, i);
5578 kvm_for_each_memslot(memslot, slots) {
5579 gfn_t start, end;
5580
5581 start = max(gfn_start, memslot->base_gfn);
5582 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5583 if (start >= end)
5584 continue;
efdfe536 5585
e2209710
BG
5586 flush = slot_handle_level_range(kvm, memslot,
5587 kvm_zap_rmapp, PG_LEVEL_4K,
5588 KVM_MAX_HUGEPAGE_LEVEL, start,
5589 end - 1, true, flush);
5590 }
9da0e4d5 5591 }
e2209710
BG
5592 if (flush)
5593 kvm_flush_remote_tlbs_with_address(kvm, gfn_start, gfn_end);
5594 write_unlock(&kvm->mmu_lock);
efdfe536
XG
5595 }
5596
897218ff 5597 if (is_tdp_mmu_enabled(kvm)) {
6103bc07
BG
5598 flush = false;
5599
5600 read_lock(&kvm->mmu_lock);
5601 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
5602 flush = kvm_tdp_mmu_zap_gfn_range(kvm, i, gfn_start,
5603 gfn_end, flush, true);
faaf05b0 5604 if (flush)
6103bc07
BG
5605 kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
5606 gfn_end);
faaf05b0 5607
6103bc07
BG
5608 read_unlock(&kvm->mmu_lock);
5609 }
efdfe536
XG
5610}
5611
018aabb5 5612static bool slot_rmap_write_protect(struct kvm *kvm,
0a234f5d
SC
5613 struct kvm_rmap_head *rmap_head,
5614 struct kvm_memory_slot *slot)
d77aa73c 5615{
018aabb5 5616 return __rmap_write_protect(kvm, rmap_head, false);
d77aa73c
XG
5617}
5618
1c91cad4 5619void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
3c9bd400
JZ
5620 struct kvm_memory_slot *memslot,
5621 int start_level)
6aa8b732 5622{
e2209710 5623 bool flush = false;
6aa8b732 5624
e2209710
BG
5625 if (kvm_memslots_have_rmaps(kvm)) {
5626 write_lock(&kvm->mmu_lock);
5627 flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5628 start_level, KVM_MAX_HUGEPAGE_LEVEL,
5629 false);
5630 write_unlock(&kvm->mmu_lock);
5631 }
198c74f4 5632
24ae4cfa
BG
5633 if (is_tdp_mmu_enabled(kvm)) {
5634 read_lock(&kvm->mmu_lock);
5635 flush |= kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
5636 read_unlock(&kvm->mmu_lock);
5637 }
5638
198c74f4
XG
5639 /*
5640 * We can flush all the TLBs out of the mmu lock without TLB
5641 * corruption since we just change the spte from writable to
5642 * readonly so that we only need to care the case of changing
5643 * spte from present to present (changing the spte from present
5644 * to nonpresent will flush all the TLBs immediately), in other
5645 * words, the only case we care is mmu_spte_update() where we
5fc3424f
SC
5646 * have checked Host-writable | MMU-writable instead of
5647 * PT_WRITABLE_MASK, that means it does not depend on PT_WRITABLE_MASK
5648 * anymore.
198c74f4 5649 */
d91ffee9 5650 if (flush)
7f42aa76 5651 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6aa8b732 5652}
37a7d8b0 5653
3ea3b7fa 5654static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
0a234f5d
SC
5655 struct kvm_rmap_head *rmap_head,
5656 struct kvm_memory_slot *slot)
3ea3b7fa
WL
5657{
5658 u64 *sptep;
5659 struct rmap_iterator iter;
5660 int need_tlb_flush = 0;
ba049e93 5661 kvm_pfn_t pfn;
3ea3b7fa
WL
5662 struct kvm_mmu_page *sp;
5663
0d536790 5664restart:
018aabb5 5665 for_each_rmap_spte(rmap_head, &iter, sptep) {
57354682 5666 sp = sptep_to_sp(sptep);
3ea3b7fa
WL
5667 pfn = spte_to_pfn(*sptep);
5668
5669 /*
decf6333
XG
5670 * We cannot do huge page mapping for indirect shadow pages,
5671 * which are found on the last rmap (level = 1) when not using
5672 * tdp; such shadow pages are synced with the page table in
5673 * the guest, and the guest page table is using 4K page size
5674 * mapping if the indirect sp has level = 1.
3ea3b7fa 5675 */
a78986aa 5676 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
9eba50f8
SC
5677 sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
5678 pfn, PG_LEVEL_NUM)) {
e7912386 5679 pte_list_remove(rmap_head, sptep);
40ef75a7
LT
5680
5681 if (kvm_available_flush_tlb_with_range())
5682 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5683 KVM_PAGES_PER_HPAGE(sp->role.level));
5684 else
5685 need_tlb_flush = 1;
5686
0d536790
XG
5687 goto restart;
5688 }
3ea3b7fa
WL
5689 }
5690
5691 return need_tlb_flush;
5692}
5693
5694void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
f36f3f28 5695 const struct kvm_memory_slot *memslot)
3ea3b7fa 5696{
f36f3f28 5697 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
9eba50f8 5698 struct kvm_memory_slot *slot = (struct kvm_memory_slot *)memslot;
31c65657 5699 bool flush = false;
14881998 5700
e2209710
BG
5701 if (kvm_memslots_have_rmaps(kvm)) {
5702 write_lock(&kvm->mmu_lock);
5703 flush = slot_handle_leaf(kvm, slot, kvm_mmu_zap_collapsible_spte, true);
5704 if (flush)
5705 kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
5706 write_unlock(&kvm->mmu_lock);
5707 }
2db6f772
BG
5708
5709 if (is_tdp_mmu_enabled(kvm)) {
2db6f772
BG
5710 read_lock(&kvm->mmu_lock);
5711 flush = kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot, flush);
5712 if (flush)
5713 kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
5714 read_unlock(&kvm->mmu_lock);
5715 }
3ea3b7fa
WL
5716}
5717
b3594ffb 5718void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
6c9dd6d2 5719 const struct kvm_memory_slot *memslot)
b3594ffb
SC
5720{
5721 /*
7f42aa76 5722 * All current use cases for flushing the TLBs for a specific memslot
302695a5 5723 * related to dirty logging, and many do the TLB flush out of mmu_lock.
7f42aa76
SC
5724 * The interaction between the various operations on memslot must be
5725 * serialized by slots_locks to ensure the TLB flush from one operation
5726 * is observed by any other operation on the same memslot.
b3594ffb
SC
5727 */
5728 lockdep_assert_held(&kvm->slots_lock);
cec37648
SC
5729 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5730 memslot->npages);
b3594ffb
SC
5731}
5732
f4b4b180
KH
5733void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5734 struct kvm_memory_slot *memslot)
5735{
e2209710 5736 bool flush = false;
f4b4b180 5737
e2209710
BG
5738 if (kvm_memslots_have_rmaps(kvm)) {
5739 write_lock(&kvm->mmu_lock);
5740 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty,
5741 false);
5742 write_unlock(&kvm->mmu_lock);
5743 }
f4b4b180 5744
24ae4cfa
BG
5745 if (is_tdp_mmu_enabled(kvm)) {
5746 read_lock(&kvm->mmu_lock);
5747 flush |= kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
5748 read_unlock(&kvm->mmu_lock);
5749 }
5750
f4b4b180
KH
5751 /*
5752 * It's also safe to flush TLBs out of mmu lock here as currently this
5753 * function is only used for dirty logging, in which case flushing TLB
5754 * out of mmu lock also guarantees no dirty pages will be lost in
5755 * dirty_bitmap.
5756 */
5757 if (flush)
7f42aa76 5758 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
f4b4b180 5759}
f4b4b180 5760
92f58b5c 5761void kvm_mmu_zap_all(struct kvm *kvm)
5304b8d3
XG
5762{
5763 struct kvm_mmu_page *sp, *node;
7390de1e 5764 LIST_HEAD(invalid_list);
83cdb568 5765 int ign;
5304b8d3 5766
531810ca 5767 write_lock(&kvm->mmu_lock);
5304b8d3 5768restart:
8a674adc 5769 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
f95eec9b 5770 if (WARN_ON(sp->role.invalid))
4771450c 5771 continue;
92f58b5c 5772 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5304b8d3 5773 goto restart;
531810ca 5774 if (cond_resched_rwlock_write(&kvm->mmu_lock))
5304b8d3
XG
5775 goto restart;
5776 }
5777
4771450c 5778 kvm_mmu_commit_zap_page(kvm, &invalid_list);
faaf05b0 5779
897218ff 5780 if (is_tdp_mmu_enabled(kvm))
faaf05b0
BG
5781 kvm_tdp_mmu_zap_all(kvm);
5782
531810ca 5783 write_unlock(&kvm->mmu_lock);
5304b8d3
XG
5784}
5785
15248258 5786void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
f8f55942 5787{
164bf7e5 5788 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
e1359e2b 5789
164bf7e5 5790 gen &= MMIO_SPTE_GEN_MASK;
e1359e2b 5791
f8f55942 5792 /*
e1359e2b
SC
5793 * Generation numbers are incremented in multiples of the number of
5794 * address spaces in order to provide unique generations across all
5795 * address spaces. Strip what is effectively the address space
5796 * modifier prior to checking for a wrap of the MMIO generation so
5797 * that a wrap in any address space is detected.
5798 */
5799 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5800
f8f55942 5801 /*
e1359e2b 5802 * The very rare case: if the MMIO generation number has wrapped,
f8f55942 5803 * zap all shadow pages.
f8f55942 5804 */
e1359e2b 5805 if (unlikely(gen == 0)) {
ae0f5499 5806 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
92f58b5c 5807 kvm_mmu_zap_all_fast(kvm);
7a2e8aaf 5808 }
f8f55942
XG
5809}
5810
70534a73
DC
5811static unsigned long
5812mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
3ee16c81
IE
5813{
5814 struct kvm *kvm;
1495f230 5815 int nr_to_scan = sc->nr_to_scan;
70534a73 5816 unsigned long freed = 0;
3ee16c81 5817
0d9ce162 5818 mutex_lock(&kvm_lock);
3ee16c81
IE
5819
5820 list_for_each_entry(kvm, &vm_list, vm_list) {
3d56cbdf 5821 int idx;
d98ba053 5822 LIST_HEAD(invalid_list);
3ee16c81 5823
35f2d16b
TY
5824 /*
5825 * Never scan more than sc->nr_to_scan VM instances.
5826 * Will not hit this condition practically since we do not try
5827 * to shrink more than one VM and it is very unlikely to see
5828 * !n_used_mmu_pages so many times.
5829 */
5830 if (!nr_to_scan--)
5831 break;
19526396
GN
5832 /*
5833 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5834 * here. We may skip a VM instance errorneosly, but we do not
5835 * want to shrink a VM that only started to populate its MMU
5836 * anyway.
5837 */
10605204
SC
5838 if (!kvm->arch.n_used_mmu_pages &&
5839 !kvm_has_zapped_obsolete_pages(kvm))
19526396 5840 continue;
19526396 5841
f656ce01 5842 idx = srcu_read_lock(&kvm->srcu);
531810ca 5843 write_lock(&kvm->mmu_lock);
3ee16c81 5844
10605204
SC
5845 if (kvm_has_zapped_obsolete_pages(kvm)) {
5846 kvm_mmu_commit_zap_page(kvm,
5847 &kvm->arch.zapped_obsolete_pages);
5848 goto unlock;
5849 }
5850
ebdb292d 5851 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
19526396 5852
10605204 5853unlock:
531810ca 5854 write_unlock(&kvm->mmu_lock);
f656ce01 5855 srcu_read_unlock(&kvm->srcu, idx);
19526396 5856
70534a73
DC
5857 /*
5858 * unfair on small ones
5859 * per-vm shrinkers cry out
5860 * sadness comes quickly
5861 */
19526396
GN
5862 list_move_tail(&kvm->vm_list, &vm_list);
5863 break;
3ee16c81 5864 }
3ee16c81 5865
0d9ce162 5866 mutex_unlock(&kvm_lock);
70534a73 5867 return freed;
70534a73
DC
5868}
5869
5870static unsigned long
5871mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5872{
45221ab6 5873 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
3ee16c81
IE
5874}
5875
5876static struct shrinker mmu_shrinker = {
70534a73
DC
5877 .count_objects = mmu_shrink_count,
5878 .scan_objects = mmu_shrink_scan,
3ee16c81
IE
5879 .seeks = DEFAULT_SEEKS * 10,
5880};
5881
2ddfd20e 5882static void mmu_destroy_caches(void)
b5a33a75 5883{
c1bd743e
TH
5884 kmem_cache_destroy(pte_list_desc_cache);
5885 kmem_cache_destroy(mmu_page_header_cache);
b5a33a75
AK
5886}
5887
b8e8c830
PB
5888static bool get_nx_auto_mode(void)
5889{
5890 /* Return true when CPU has the bug, and mitigations are ON */
5891 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
5892}
5893
5894static void __set_nx_huge_pages(bool val)
5895{
5896 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
5897}
5898
5899static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
5900{
5901 bool old_val = nx_huge_pages;
5902 bool new_val;
5903
5904 /* In "auto" mode deploy workaround only if CPU has the bug. */
5905 if (sysfs_streq(val, "off"))
5906 new_val = 0;
5907 else if (sysfs_streq(val, "force"))
5908 new_val = 1;
5909 else if (sysfs_streq(val, "auto"))
5910 new_val = get_nx_auto_mode();
5911 else if (strtobool(val, &new_val) < 0)
5912 return -EINVAL;
5913
5914 __set_nx_huge_pages(new_val);
5915
5916 if (new_val != old_val) {
5917 struct kvm *kvm;
b8e8c830
PB
5918
5919 mutex_lock(&kvm_lock);
5920
5921 list_for_each_entry(kvm, &vm_list, vm_list) {
ed69a6cb 5922 mutex_lock(&kvm->slots_lock);
b8e8c830 5923 kvm_mmu_zap_all_fast(kvm);
ed69a6cb 5924 mutex_unlock(&kvm->slots_lock);
1aa9b957
JS
5925
5926 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
b8e8c830
PB
5927 }
5928 mutex_unlock(&kvm_lock);
5929 }
5930
5931 return 0;
5932}
5933
b5a33a75
AK
5934int kvm_mmu_module_init(void)
5935{
ab271bd4
AB
5936 int ret = -ENOMEM;
5937
b8e8c830
PB
5938 if (nx_huge_pages == -1)
5939 __set_nx_huge_pages(get_nx_auto_mode());
5940
36d9594d
VK
5941 /*
5942 * MMU roles use union aliasing which is, generally speaking, an
5943 * undefined behavior. However, we supposedly know how compilers behave
5944 * and the current status quo is unlikely to change. Guardians below are
5945 * supposed to let us know if the assumption becomes false.
5946 */
5947 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
5948 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
5949 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
5950
28a1f3ac 5951 kvm_mmu_reset_all_pte_masks();
f160c7b7 5952
53c07b18
XG
5953 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
5954 sizeof(struct pte_list_desc),
46bea48a 5955 0, SLAB_ACCOUNT, NULL);
53c07b18 5956 if (!pte_list_desc_cache)
ab271bd4 5957 goto out;
b5a33a75 5958
d3d25b04
AK
5959 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
5960 sizeof(struct kvm_mmu_page),
46bea48a 5961 0, SLAB_ACCOUNT, NULL);
d3d25b04 5962 if (!mmu_page_header_cache)
ab271bd4 5963 goto out;
d3d25b04 5964
908c7f19 5965 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
ab271bd4 5966 goto out;
45bf21a8 5967
ab271bd4
AB
5968 ret = register_shrinker(&mmu_shrinker);
5969 if (ret)
5970 goto out;
3ee16c81 5971
b5a33a75
AK
5972 return 0;
5973
ab271bd4 5974out:
3ee16c81 5975 mmu_destroy_caches();
ab271bd4 5976 return ret;
b5a33a75
AK
5977}
5978
3ad82a7e 5979/*
39337ad1 5980 * Calculate mmu pages needed for kvm.
3ad82a7e 5981 */
bc8a3d89 5982unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
3ad82a7e 5983{
bc8a3d89
BG
5984 unsigned long nr_mmu_pages;
5985 unsigned long nr_pages = 0;
bc6678a3 5986 struct kvm_memslots *slots;
be6ba0f0 5987 struct kvm_memory_slot *memslot;
9da0e4d5 5988 int i;
3ad82a7e 5989
9da0e4d5
PB
5990 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5991 slots = __kvm_memslots(kvm, i);
90d83dc3 5992
9da0e4d5
PB
5993 kvm_for_each_memslot(memslot, slots)
5994 nr_pages += memslot->npages;
5995 }
3ad82a7e
ZX
5996
5997 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
bc8a3d89 5998 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
3ad82a7e
ZX
5999
6000 return nr_mmu_pages;
6001}
6002
c42fffe3
XG
6003void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6004{
95f93af4 6005 kvm_mmu_unload(vcpu);
1cfff4d9
JP
6006 free_mmu_pages(&vcpu->arch.root_mmu);
6007 free_mmu_pages(&vcpu->arch.guest_mmu);
c42fffe3 6008 mmu_free_memory_caches(vcpu);
b034cf01
XG
6009}
6010
b034cf01
XG
6011void kvm_mmu_module_exit(void)
6012{
6013 mmu_destroy_caches();
6014 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6015 unregister_shrinker(&mmu_shrinker);
c42fffe3
XG
6016 mmu_audit_disable();
6017}
1aa9b957
JS
6018
6019static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6020{
6021 unsigned int old_val;
6022 int err;
6023
6024 old_val = nx_huge_pages_recovery_ratio;
6025 err = param_set_uint(val, kp);
6026 if (err)
6027 return err;
6028
6029 if (READ_ONCE(nx_huge_pages) &&
6030 !old_val && nx_huge_pages_recovery_ratio) {
6031 struct kvm *kvm;
6032
6033 mutex_lock(&kvm_lock);
6034
6035 list_for_each_entry(kvm, &vm_list, vm_list)
6036 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6037
6038 mutex_unlock(&kvm_lock);
6039 }
6040
6041 return err;
6042}
6043
6044static void kvm_recover_nx_lpages(struct kvm *kvm)
6045{
ade74e14 6046 unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
1aa9b957
JS
6047 int rcu_idx;
6048 struct kvm_mmu_page *sp;
6049 unsigned int ratio;
6050 LIST_HEAD(invalid_list);
048f4980 6051 bool flush = false;
1aa9b957
JS
6052 ulong to_zap;
6053
6054 rcu_idx = srcu_read_lock(&kvm->srcu);
531810ca 6055 write_lock(&kvm->mmu_lock);
1aa9b957
JS
6056
6057 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
ade74e14 6058 to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
7d919c7a
SC
6059 for ( ; to_zap; --to_zap) {
6060 if (list_empty(&kvm->arch.lpage_disallowed_mmu_pages))
6061 break;
6062
1aa9b957
JS
6063 /*
6064 * We use a separate list instead of just using active_mmu_pages
6065 * because the number of lpage_disallowed pages is expected to
6066 * be relatively small compared to the total.
6067 */
6068 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6069 struct kvm_mmu_page,
6070 lpage_disallowed_link);
6071 WARN_ON_ONCE(!sp->lpage_disallowed);
897218ff 6072 if (is_tdp_mmu_page(sp)) {
315f02c6 6073 flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
8d1a182e 6074 } else {
29cf0f50
BG
6075 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6076 WARN_ON_ONCE(sp->lpage_disallowed);
6077 }
1aa9b957 6078
531810ca 6079 if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
048f4980 6080 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
531810ca 6081 cond_resched_rwlock_write(&kvm->mmu_lock);
048f4980 6082 flush = false;
1aa9b957
JS
6083 }
6084 }
048f4980 6085 kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
1aa9b957 6086
531810ca 6087 write_unlock(&kvm->mmu_lock);
1aa9b957
JS
6088 srcu_read_unlock(&kvm->srcu, rcu_idx);
6089}
6090
6091static long get_nx_lpage_recovery_timeout(u64 start_time)
6092{
6093 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6094 ? start_time + 60 * HZ - get_jiffies_64()
6095 : MAX_SCHEDULE_TIMEOUT;
6096}
6097
6098static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6099{
6100 u64 start_time;
6101 long remaining_time;
6102
6103 while (true) {
6104 start_time = get_jiffies_64();
6105 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6106
6107 set_current_state(TASK_INTERRUPTIBLE);
6108 while (!kthread_should_stop() && remaining_time > 0) {
6109 schedule_timeout(remaining_time);
6110 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6111 set_current_state(TASK_INTERRUPTIBLE);
6112 }
6113
6114 set_current_state(TASK_RUNNING);
6115
6116 if (kthread_should_stop())
6117 return 0;
6118
6119 kvm_recover_nx_lpages(kvm);
6120 }
6121}
6122
6123int kvm_mmu_post_init_vm(struct kvm *kvm)
6124{
6125 int err;
6126
6127 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6128 "kvm-nx-lpage-recovery",
6129 &kvm->arch.nx_lpage_recovery_thread);
6130 if (!err)
6131 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6132
6133 return err;
6134}
6135
6136void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6137{
6138 if (kvm->arch.nx_lpage_recovery_thread)
6139 kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6140}