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