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