]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - arch/x86/kvm/mmu/mmu.c
KVM: x86/mmu: Refactor the zap loop for recovering NX lpages
[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
PB
66
67static struct kernel_param_ops nx_huge_pages_ops = {
68 .set = set_nx_huge_pages,
69 .get = param_get_bool,
70};
71
1aa9b957
JS
72static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
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
018aabb5 1750static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
8a9522d2
ALC
1751 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1752 unsigned long data)
3da0dd43 1753{
1e3f42f0
TY
1754 u64 *sptep;
1755 struct rmap_iterator iter;
3da0dd43 1756 int need_flush = 0;
1e3f42f0 1757 u64 new_spte;
3da0dd43 1758 pte_t *ptep = (pte_t *)data;
ba049e93 1759 kvm_pfn_t new_pfn;
3da0dd43
IE
1760
1761 WARN_ON(pte_huge(*ptep));
1762 new_pfn = pte_pfn(*ptep);
1e3f42f0 1763
0d536790 1764restart:
018aabb5 1765 for_each_rmap_spte(rmap_head, &iter, sptep) {
8a9522d2 1766 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
f160c7b7 1767 sptep, *sptep, gfn, level);
1e3f42f0 1768
3da0dd43 1769 need_flush = 1;
1e3f42f0 1770
3da0dd43 1771 if (pte_write(*ptep)) {
e7912386 1772 pte_list_remove(rmap_head, sptep);
0d536790 1773 goto restart;
3da0dd43 1774 } else {
1e3f42f0 1775 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
3da0dd43
IE
1776 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1777
1778 new_spte &= ~PT_WRITABLE_MASK;
1779 new_spte &= ~SPTE_HOST_WRITEABLE;
f160c7b7
JS
1780
1781 new_spte = mark_spte_for_access_track(new_spte);
1e3f42f0
TY
1782
1783 mmu_spte_clear_track_bits(sptep);
1784 mmu_spte_set(sptep, new_spte);
3da0dd43
IE
1785 }
1786 }
1e3f42f0 1787
3cc5ea94
LT
1788 if (need_flush && kvm_available_flush_tlb_with_range()) {
1789 kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1790 return 0;
1791 }
1792
0cf853c5 1793 return need_flush;
3da0dd43
IE
1794}
1795
6ce1f4e2
XG
1796struct slot_rmap_walk_iterator {
1797 /* input fields. */
1798 struct kvm_memory_slot *slot;
1799 gfn_t start_gfn;
1800 gfn_t end_gfn;
1801 int start_level;
1802 int end_level;
1803
1804 /* output fields. */
1805 gfn_t gfn;
018aabb5 1806 struct kvm_rmap_head *rmap;
6ce1f4e2
XG
1807 int level;
1808
1809 /* private field. */
018aabb5 1810 struct kvm_rmap_head *end_rmap;
6ce1f4e2
XG
1811};
1812
1813static void
1814rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1815{
1816 iterator->level = level;
1817 iterator->gfn = iterator->start_gfn;
1818 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1819 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1820 iterator->slot);
1821}
1822
1823static void
1824slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1825 struct kvm_memory_slot *slot, int start_level,
1826 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1827{
1828 iterator->slot = slot;
1829 iterator->start_level = start_level;
1830 iterator->end_level = end_level;
1831 iterator->start_gfn = start_gfn;
1832 iterator->end_gfn = end_gfn;
1833
1834 rmap_walk_init_level(iterator, iterator->start_level);
1835}
1836
1837static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1838{
1839 return !!iterator->rmap;
1840}
1841
1842static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1843{
1844 if (++iterator->rmap <= iterator->end_rmap) {
1845 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1846 return;
1847 }
1848
1849 if (++iterator->level > iterator->end_level) {
1850 iterator->rmap = NULL;
1851 return;
1852 }
1853
1854 rmap_walk_init_level(iterator, iterator->level);
1855}
1856
1857#define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1858 _start_gfn, _end_gfn, _iter_) \
1859 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1860 _end_level_, _start_gfn, _end_gfn); \
1861 slot_rmap_walk_okay(_iter_); \
1862 slot_rmap_walk_next(_iter_))
1863
84504ef3
TY
1864static int kvm_handle_hva_range(struct kvm *kvm,
1865 unsigned long start,
1866 unsigned long end,
1867 unsigned long data,
1868 int (*handler)(struct kvm *kvm,
018aabb5 1869 struct kvm_rmap_head *rmap_head,
048212d0 1870 struct kvm_memory_slot *slot,
8a9522d2
ALC
1871 gfn_t gfn,
1872 int level,
84504ef3 1873 unsigned long data))
e930bffe 1874{
bc6678a3 1875 struct kvm_memslots *slots;
be6ba0f0 1876 struct kvm_memory_slot *memslot;
6ce1f4e2
XG
1877 struct slot_rmap_walk_iterator iterator;
1878 int ret = 0;
9da0e4d5 1879 int i;
bc6678a3 1880
9da0e4d5
PB
1881 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1882 slots = __kvm_memslots(kvm, i);
1883 kvm_for_each_memslot(memslot, slots) {
1884 unsigned long hva_start, hva_end;
1885 gfn_t gfn_start, gfn_end;
e930bffe 1886
9da0e4d5
PB
1887 hva_start = max(start, memslot->userspace_addr);
1888 hva_end = min(end, memslot->userspace_addr +
1889 (memslot->npages << PAGE_SHIFT));
1890 if (hva_start >= hva_end)
1891 continue;
1892 /*
1893 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1894 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1895 */
1896 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1897 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1898
3bae0459 1899 for_each_slot_rmap_range(memslot, PG_LEVEL_4K,
e662ec3e 1900 KVM_MAX_HUGEPAGE_LEVEL,
9da0e4d5
PB
1901 gfn_start, gfn_end - 1,
1902 &iterator)
1903 ret |= handler(kvm, iterator.rmap, memslot,
1904 iterator.gfn, iterator.level, data);
1905 }
e930bffe
AA
1906 }
1907
f395302e 1908 return ret;
e930bffe
AA
1909}
1910
84504ef3
TY
1911static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1912 unsigned long data,
018aabb5
TY
1913 int (*handler)(struct kvm *kvm,
1914 struct kvm_rmap_head *rmap_head,
048212d0 1915 struct kvm_memory_slot *slot,
8a9522d2 1916 gfn_t gfn, int level,
84504ef3
TY
1917 unsigned long data))
1918{
1919 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
e930bffe
AA
1920}
1921
fdfe7cbd
WD
1922int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end,
1923 unsigned flags)
b3ae2096
TY
1924{
1925 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1926}
1927
748c0e31 1928int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
3da0dd43 1929{
0cf853c5 1930 return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
e930bffe
AA
1931}
1932
018aabb5 1933static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
8a9522d2
ALC
1934 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1935 unsigned long data)
e930bffe 1936{
1e3f42f0 1937 u64 *sptep;
3f649ab7 1938 struct rmap_iterator iter;
e930bffe
AA
1939 int young = 0;
1940
f160c7b7
JS
1941 for_each_rmap_spte(rmap_head, &iter, sptep)
1942 young |= mmu_spte_age(sptep);
0d536790 1943
8a9522d2 1944 trace_kvm_age_page(gfn, level, slot, young);
e930bffe
AA
1945 return young;
1946}
1947
018aabb5 1948static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
8a9522d2
ALC
1949 struct kvm_memory_slot *slot, gfn_t gfn,
1950 int level, unsigned long data)
8ee53820 1951{
1e3f42f0
TY
1952 u64 *sptep;
1953 struct rmap_iterator iter;
8ee53820 1954
83ef6c81
JS
1955 for_each_rmap_spte(rmap_head, &iter, sptep)
1956 if (is_accessed_spte(*sptep))
1957 return 1;
83ef6c81 1958 return 0;
8ee53820
AA
1959}
1960
53a27b39
MT
1961#define RMAP_RECYCLE_THRESHOLD 1000
1962
852e3c19 1963static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
53a27b39 1964{
018aabb5 1965 struct kvm_rmap_head *rmap_head;
852e3c19
JR
1966 struct kvm_mmu_page *sp;
1967
57354682 1968 sp = sptep_to_sp(spte);
53a27b39 1969
018aabb5 1970 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
53a27b39 1971
018aabb5 1972 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
c3134ce2
LT
1973 kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1974 KVM_PAGES_PER_HPAGE(sp->role.level));
53a27b39
MT
1975}
1976
57128468 1977int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
e930bffe 1978{
57128468 1979 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
e930bffe
AA
1980}
1981
8ee53820
AA
1982int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1983{
1984 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1985}
1986
d6c69ee9 1987#ifdef MMU_DEBUG
47ad8e68 1988static int is_empty_shadow_page(u64 *spt)
6aa8b732 1989{
139bdb2d
AK
1990 u64 *pos;
1991 u64 *end;
1992
47ad8e68 1993 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
3c915510 1994 if (is_shadow_present_pte(*pos)) {
b8688d51 1995 printk(KERN_ERR "%s: %p %llx\n", __func__,
139bdb2d 1996 pos, *pos);
6aa8b732 1997 return 0;
139bdb2d 1998 }
6aa8b732
AK
1999 return 1;
2000}
d6c69ee9 2001#endif
6aa8b732 2002
45221ab6
DH
2003/*
2004 * This value is the sum of all of the kvm instances's
2005 * kvm->arch.n_used_mmu_pages values. We need a global,
2006 * aggregate version in order to make the slab shrinker
2007 * faster
2008 */
bc8a3d89 2009static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
45221ab6
DH
2010{
2011 kvm->arch.n_used_mmu_pages += nr;
2012 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2013}
2014
834be0d8 2015static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
260746c0 2016{
fa4a2c08 2017 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
7775834a 2018 hlist_del(&sp->hash_link);
bd4c86ea
XG
2019 list_del(&sp->link);
2020 free_page((unsigned long)sp->spt);
834be0d8
GN
2021 if (!sp->role.direct)
2022 free_page((unsigned long)sp->gfns);
e8ad9a70 2023 kmem_cache_free(mmu_page_header_cache, sp);
260746c0
AK
2024}
2025
cea0f0e7
AK
2026static unsigned kvm_page_table_hashfn(gfn_t gfn)
2027{
114df303 2028 return hash_64(gfn, KVM_MMU_HASH_SHIFT);
cea0f0e7
AK
2029}
2030
714b93da 2031static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
4db35314 2032 struct kvm_mmu_page *sp, u64 *parent_pte)
cea0f0e7 2033{
cea0f0e7
AK
2034 if (!parent_pte)
2035 return;
cea0f0e7 2036
67052b35 2037 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
cea0f0e7
AK
2038}
2039
4db35314 2040static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
cea0f0e7
AK
2041 u64 *parent_pte)
2042{
8daf3462 2043 __pte_list_remove(parent_pte, &sp->parent_ptes);
cea0f0e7
AK
2044}
2045
bcdd9a93
XG
2046static void drop_parent_pte(struct kvm_mmu_page *sp,
2047 u64 *parent_pte)
2048{
2049 mmu_page_remove_parent_pte(sp, parent_pte);
1df9f2dc 2050 mmu_spte_clear_no_track(parent_pte);
bcdd9a93
XG
2051}
2052
47005792 2053static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
ad8cfbe3 2054{
67052b35 2055 struct kvm_mmu_page *sp;
7ddca7e4 2056
94ce87ef
SC
2057 sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2058 sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
67052b35 2059 if (!direct)
94ce87ef 2060 sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
67052b35 2061 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
002c5f73
SC
2062
2063 /*
2064 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2065 * depends on valid pages being added to the head of the list. See
2066 * comments in kvm_zap_obsolete_pages().
2067 */
ca333add 2068 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
67052b35 2069 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
67052b35
XG
2070 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2071 return sp;
ad8cfbe3
MT
2072}
2073
67052b35 2074static void mark_unsync(u64 *spte);
1047df1f 2075static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
0074ff63 2076{
74c4e63a
TY
2077 u64 *sptep;
2078 struct rmap_iterator iter;
2079
2080 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2081 mark_unsync(sptep);
2082 }
0074ff63
MT
2083}
2084
67052b35 2085static void mark_unsync(u64 *spte)
0074ff63 2086{
67052b35 2087 struct kvm_mmu_page *sp;
1047df1f 2088 unsigned int index;
0074ff63 2089
57354682 2090 sp = sptep_to_sp(spte);
1047df1f
XG
2091 index = spte - sp->spt;
2092 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
0074ff63 2093 return;
1047df1f 2094 if (sp->unsync_children++)
0074ff63 2095 return;
1047df1f 2096 kvm_mmu_mark_parents_unsync(sp);
0074ff63
MT
2097}
2098
e8bc217a 2099static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
a4a8e6f7 2100 struct kvm_mmu_page *sp)
e8bc217a 2101{
1f50f1b3 2102 return 0;
e8bc217a
MT
2103}
2104
0f53b5b1
XG
2105static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2106 struct kvm_mmu_page *sp, u64 *spte,
7c562522 2107 const void *pte)
0f53b5b1
XG
2108{
2109 WARN_ON(1);
2110}
2111
60c8aec6
MT
2112#define KVM_PAGE_ARRAY_NR 16
2113
2114struct kvm_mmu_pages {
2115 struct mmu_page_and_offset {
2116 struct kvm_mmu_page *sp;
2117 unsigned int idx;
2118 } page[KVM_PAGE_ARRAY_NR];
2119 unsigned int nr;
2120};
2121
cded19f3
HE
2122static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2123 int idx)
4731d4c7 2124{
60c8aec6 2125 int i;
4731d4c7 2126
60c8aec6
MT
2127 if (sp->unsync)
2128 for (i=0; i < pvec->nr; i++)
2129 if (pvec->page[i].sp == sp)
2130 return 0;
2131
2132 pvec->page[pvec->nr].sp = sp;
2133 pvec->page[pvec->nr].idx = idx;
2134 pvec->nr++;
2135 return (pvec->nr == KVM_PAGE_ARRAY_NR);
2136}
2137
fd951457
TY
2138static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2139{
2140 --sp->unsync_children;
2141 WARN_ON((int)sp->unsync_children < 0);
2142 __clear_bit(idx, sp->unsync_child_bitmap);
2143}
2144
60c8aec6
MT
2145static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2146 struct kvm_mmu_pages *pvec)
2147{
2148 int i, ret, nr_unsync_leaf = 0;
4731d4c7 2149
37178b8b 2150 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
7a8f1a74 2151 struct kvm_mmu_page *child;
4731d4c7
MT
2152 u64 ent = sp->spt[i];
2153
fd951457
TY
2154 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2155 clear_unsync_child_bit(sp, i);
2156 continue;
2157 }
7a8f1a74 2158
e47c4aee 2159 child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
7a8f1a74
XG
2160
2161 if (child->unsync_children) {
2162 if (mmu_pages_add(pvec, child, i))
2163 return -ENOSPC;
2164
2165 ret = __mmu_unsync_walk(child, pvec);
fd951457
TY
2166 if (!ret) {
2167 clear_unsync_child_bit(sp, i);
2168 continue;
2169 } else if (ret > 0) {
7a8f1a74 2170 nr_unsync_leaf += ret;
fd951457 2171 } else
7a8f1a74
XG
2172 return ret;
2173 } else if (child->unsync) {
2174 nr_unsync_leaf++;
2175 if (mmu_pages_add(pvec, child, i))
2176 return -ENOSPC;
2177 } else
fd951457 2178 clear_unsync_child_bit(sp, i);
4731d4c7
MT
2179 }
2180
60c8aec6
MT
2181 return nr_unsync_leaf;
2182}
2183
e23d3fef
XG
2184#define INVALID_INDEX (-1)
2185
60c8aec6
MT
2186static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2187 struct kvm_mmu_pages *pvec)
2188{
0a47cd85 2189 pvec->nr = 0;
60c8aec6
MT
2190 if (!sp->unsync_children)
2191 return 0;
2192
e23d3fef 2193 mmu_pages_add(pvec, sp, INVALID_INDEX);
60c8aec6 2194 return __mmu_unsync_walk(sp, pvec);
4731d4c7
MT
2195}
2196
4731d4c7
MT
2197static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2198{
2199 WARN_ON(!sp->unsync);
5e1b3ddb 2200 trace_kvm_mmu_sync_page(sp);
4731d4c7
MT
2201 sp->unsync = 0;
2202 --kvm->stat.mmu_unsync;
2203}
2204
83cdb568
SC
2205static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2206 struct list_head *invalid_list);
7775834a
XG
2207static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2208 struct list_head *invalid_list);
4731d4c7 2209
ac101b7c
SC
2210#define for_each_valid_sp(_kvm, _sp, _list) \
2211 hlist_for_each_entry(_sp, _list, hash_link) \
fac026da 2212 if (is_obsolete_sp((_kvm), (_sp))) { \
f3414bc7 2213 } else
1044b030
TY
2214
2215#define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
ac101b7c
SC
2216 for_each_valid_sp(_kvm, _sp, \
2217 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)]) \
f3414bc7 2218 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
7ae680eb 2219
47c42e6b
SC
2220static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2221{
2222 return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2223}
2224
f918b443 2225/* @sp->gfn should be write-protected at the call site */
1f50f1b3
PB
2226static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2227 struct list_head *invalid_list)
4731d4c7 2228{
47c42e6b
SC
2229 if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2230 vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
d98ba053 2231 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1f50f1b3 2232 return false;
4731d4c7
MT
2233 }
2234
1f50f1b3 2235 return true;
4731d4c7
MT
2236}
2237
a2113634
SC
2238static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2239 struct list_head *invalid_list,
2240 bool remote_flush)
2241{
cfd32acf 2242 if (!remote_flush && list_empty(invalid_list))
a2113634
SC
2243 return false;
2244
2245 if (!list_empty(invalid_list))
2246 kvm_mmu_commit_zap_page(kvm, invalid_list);
2247 else
2248 kvm_flush_remote_tlbs(kvm);
2249 return true;
2250}
2251
35a70510
PB
2252static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2253 struct list_head *invalid_list,
2254 bool remote_flush, bool local_flush)
1d9dc7e0 2255{
a2113634 2256 if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
35a70510 2257 return;
d98ba053 2258
a2113634 2259 if (local_flush)
8c8560b8 2260 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1d9dc7e0
XG
2261}
2262
e37fa785
XG
2263#ifdef CONFIG_KVM_MMU_AUDIT
2264#include "mmu_audit.c"
2265#else
2266static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2267static void mmu_audit_disable(void) { }
2268#endif
2269
002c5f73
SC
2270static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2271{
fac026da
SC
2272 return sp->role.invalid ||
2273 unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
002c5f73
SC
2274}
2275
1f50f1b3 2276static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
d98ba053 2277 struct list_head *invalid_list)
1d9dc7e0 2278{
9a43c5d9
PB
2279 kvm_unlink_unsync_page(vcpu->kvm, sp);
2280 return __kvm_sync_page(vcpu, sp, invalid_list);
1d9dc7e0
XG
2281}
2282
9f1a122f 2283/* @gfn should be write-protected at the call site */
2a74003a
PB
2284static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2285 struct list_head *invalid_list)
9f1a122f 2286{
9f1a122f 2287 struct kvm_mmu_page *s;
2a74003a 2288 bool ret = false;
9f1a122f 2289
b67bfe0d 2290 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
7ae680eb 2291 if (!s->unsync)
9f1a122f
XG
2292 continue;
2293
3bae0459 2294 WARN_ON(s->role.level != PG_LEVEL_4K);
2a74003a 2295 ret |= kvm_sync_page(vcpu, s, invalid_list);
9f1a122f
XG
2296 }
2297
2a74003a 2298 return ret;
9f1a122f
XG
2299}
2300
60c8aec6 2301struct mmu_page_path {
2a7266a8
YZ
2302 struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2303 unsigned int idx[PT64_ROOT_MAX_LEVEL];
4731d4c7
MT
2304};
2305
60c8aec6 2306#define for_each_sp(pvec, sp, parents, i) \
0a47cd85 2307 for (i = mmu_pages_first(&pvec, &parents); \
60c8aec6
MT
2308 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
2309 i = mmu_pages_next(&pvec, &parents, i))
2310
cded19f3
HE
2311static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2312 struct mmu_page_path *parents,
2313 int i)
60c8aec6
MT
2314{
2315 int n;
2316
2317 for (n = i+1; n < pvec->nr; n++) {
2318 struct kvm_mmu_page *sp = pvec->page[n].sp;
0a47cd85
PB
2319 unsigned idx = pvec->page[n].idx;
2320 int level = sp->role.level;
60c8aec6 2321
0a47cd85 2322 parents->idx[level-1] = idx;
3bae0459 2323 if (level == PG_LEVEL_4K)
0a47cd85 2324 break;
60c8aec6 2325
0a47cd85 2326 parents->parent[level-2] = sp;
60c8aec6
MT
2327 }
2328
2329 return n;
2330}
2331
0a47cd85
PB
2332static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2333 struct mmu_page_path *parents)
2334{
2335 struct kvm_mmu_page *sp;
2336 int level;
2337
2338 if (pvec->nr == 0)
2339 return 0;
2340
e23d3fef
XG
2341 WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2342
0a47cd85
PB
2343 sp = pvec->page[0].sp;
2344 level = sp->role.level;
3bae0459 2345 WARN_ON(level == PG_LEVEL_4K);
0a47cd85
PB
2346
2347 parents->parent[level-2] = sp;
2348
2349 /* Also set up a sentinel. Further entries in pvec are all
2350 * children of sp, so this element is never overwritten.
2351 */
2352 parents->parent[level-1] = NULL;
2353 return mmu_pages_next(pvec, parents, 0);
2354}
2355
cded19f3 2356static void mmu_pages_clear_parents(struct mmu_page_path *parents)
4731d4c7 2357{
60c8aec6
MT
2358 struct kvm_mmu_page *sp;
2359 unsigned int level = 0;
2360
2361 do {
2362 unsigned int idx = parents->idx[level];
60c8aec6
MT
2363 sp = parents->parent[level];
2364 if (!sp)
2365 return;
2366
e23d3fef 2367 WARN_ON(idx == INVALID_INDEX);
fd951457 2368 clear_unsync_child_bit(sp, idx);
60c8aec6 2369 level++;
0a47cd85 2370 } while (!sp->unsync_children);
60c8aec6 2371}
4731d4c7 2372
60c8aec6
MT
2373static void mmu_sync_children(struct kvm_vcpu *vcpu,
2374 struct kvm_mmu_page *parent)
2375{
2376 int i;
2377 struct kvm_mmu_page *sp;
2378 struct mmu_page_path parents;
2379 struct kvm_mmu_pages pages;
d98ba053 2380 LIST_HEAD(invalid_list);
50c9e6f3 2381 bool flush = false;
60c8aec6 2382
60c8aec6 2383 while (mmu_unsync_walk(parent, &pages)) {
2f84569f 2384 bool protected = false;
b1a36821
MT
2385
2386 for_each_sp(pages, sp, parents, i)
54bf36aa 2387 protected |= rmap_write_protect(vcpu, sp->gfn);
b1a36821 2388
50c9e6f3 2389 if (protected) {
b1a36821 2390 kvm_flush_remote_tlbs(vcpu->kvm);
50c9e6f3
PB
2391 flush = false;
2392 }
b1a36821 2393
60c8aec6 2394 for_each_sp(pages, sp, parents, i) {
1f50f1b3 2395 flush |= kvm_sync_page(vcpu, sp, &invalid_list);
60c8aec6
MT
2396 mmu_pages_clear_parents(&parents);
2397 }
50c9e6f3
PB
2398 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2399 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2400 cond_resched_lock(&vcpu->kvm->mmu_lock);
2401 flush = false;
2402 }
60c8aec6 2403 }
50c9e6f3
PB
2404
2405 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
4731d4c7
MT
2406}
2407
a30f47cb
XG
2408static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2409{
e5691a81 2410 atomic_set(&sp->write_flooding_count, 0);
a30f47cb
XG
2411}
2412
2413static void clear_sp_write_flooding_count(u64 *spte)
2414{
57354682 2415 __clear_sp_write_flooding_count(sptep_to_sp(spte));
a30f47cb
XG
2416}
2417
cea0f0e7
AK
2418static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2419 gfn_t gfn,
2420 gva_t gaddr,
2421 unsigned level,
f6e2c02b 2422 int direct,
0a2b64c5 2423 unsigned int access)
cea0f0e7 2424{
fb58a9c3 2425 bool direct_mmu = vcpu->arch.mmu->direct_map;
cea0f0e7 2426 union kvm_mmu_page_role role;
ac101b7c 2427 struct hlist_head *sp_list;
cea0f0e7 2428 unsigned quadrant;
9f1a122f 2429 struct kvm_mmu_page *sp;
9f1a122f 2430 bool need_sync = false;
2a74003a 2431 bool flush = false;
f3414bc7 2432 int collisions = 0;
2a74003a 2433 LIST_HEAD(invalid_list);
cea0f0e7 2434
36d9594d 2435 role = vcpu->arch.mmu->mmu_role.base;
cea0f0e7 2436 role.level = level;
f6e2c02b 2437 role.direct = direct;
84b0c8c6 2438 if (role.direct)
47c42e6b 2439 role.gpte_is_8_bytes = true;
41074d07 2440 role.access = access;
fb58a9c3 2441 if (!direct_mmu && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
cea0f0e7
AK
2442 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2443 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2444 role.quadrant = quadrant;
2445 }
ac101b7c
SC
2446
2447 sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2448 for_each_valid_sp(vcpu->kvm, sp, sp_list) {
f3414bc7
DM
2449 if (sp->gfn != gfn) {
2450 collisions++;
2451 continue;
2452 }
2453
7ae680eb
XG
2454 if (!need_sync && sp->unsync)
2455 need_sync = true;
4731d4c7 2456
7ae680eb
XG
2457 if (sp->role.word != role.word)
2458 continue;
4731d4c7 2459
fb58a9c3
SC
2460 if (direct_mmu)
2461 goto trace_get_page;
2462
2a74003a
PB
2463 if (sp->unsync) {
2464 /* The page is good, but __kvm_sync_page might still end
2465 * up zapping it. If so, break in order to rebuild it.
2466 */
2467 if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2468 break;
2469
2470 WARN_ON(!list_empty(&invalid_list));
8c8560b8 2471 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2a74003a 2472 }
e02aa901 2473
98bba238 2474 if (sp->unsync_children)
f6f6195b 2475 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
e02aa901 2476
a30f47cb 2477 __clear_sp_write_flooding_count(sp);
fb58a9c3
SC
2478
2479trace_get_page:
7ae680eb 2480 trace_kvm_mmu_get_page(sp, false);
f3414bc7 2481 goto out;
7ae680eb 2482 }
47005792 2483
dfc5aa00 2484 ++vcpu->kvm->stat.mmu_cache_miss;
47005792
TY
2485
2486 sp = kvm_mmu_alloc_page(vcpu, direct);
2487
4db35314
AK
2488 sp->gfn = gfn;
2489 sp->role = role;
ac101b7c 2490 hlist_add_head(&sp->hash_link, sp_list);
f6e2c02b 2491 if (!direct) {
56ca57f9
XG
2492 /*
2493 * we should do write protection before syncing pages
2494 * otherwise the content of the synced shadow page may
2495 * be inconsistent with guest page table.
2496 */
2497 account_shadowed(vcpu->kvm, sp);
3bae0459 2498 if (level == PG_LEVEL_4K && rmap_write_protect(vcpu, gfn))
c3134ce2 2499 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
9f1a122f 2500
3bae0459 2501 if (level > PG_LEVEL_4K && need_sync)
2a74003a 2502 flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
4731d4c7 2503 }
f691fe1d 2504 trace_kvm_mmu_get_page(sp, true);
2a74003a
PB
2505
2506 kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
f3414bc7
DM
2507out:
2508 if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2509 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
4db35314 2510 return sp;
cea0f0e7
AK
2511}
2512
7eb77e9f
JS
2513static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2514 struct kvm_vcpu *vcpu, hpa_t root,
2515 u64 addr)
2d11123a
AK
2516{
2517 iterator->addr = addr;
7eb77e9f 2518 iterator->shadow_addr = root;
44dd3ffa 2519 iterator->level = vcpu->arch.mmu->shadow_root_level;
81407ca5 2520
2a7266a8 2521 if (iterator->level == PT64_ROOT_4LEVEL &&
44dd3ffa
VK
2522 vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2523 !vcpu->arch.mmu->direct_map)
81407ca5
JR
2524 --iterator->level;
2525
2d11123a 2526 if (iterator->level == PT32E_ROOT_LEVEL) {
7eb77e9f
JS
2527 /*
2528 * prev_root is currently only used for 64-bit hosts. So only
2529 * the active root_hpa is valid here.
2530 */
44dd3ffa 2531 BUG_ON(root != vcpu->arch.mmu->root_hpa);
7eb77e9f 2532
2d11123a 2533 iterator->shadow_addr
44dd3ffa 2534 = vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2d11123a
AK
2535 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2536 --iterator->level;
2537 if (!iterator->shadow_addr)
2538 iterator->level = 0;
2539 }
2540}
2541
7eb77e9f
JS
2542static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2543 struct kvm_vcpu *vcpu, u64 addr)
2544{
44dd3ffa 2545 shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
7eb77e9f
JS
2546 addr);
2547}
2548
2d11123a
AK
2549static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2550{
3bae0459 2551 if (iterator->level < PG_LEVEL_4K)
2d11123a 2552 return false;
4d88954d 2553
2d11123a
AK
2554 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2555 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2556 return true;
2557}
2558
c2a2ac2b
XG
2559static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2560 u64 spte)
2d11123a 2561{
c2a2ac2b 2562 if (is_last_spte(spte, iterator->level)) {
052331be
XG
2563 iterator->level = 0;
2564 return;
2565 }
2566
c2a2ac2b 2567 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2d11123a
AK
2568 --iterator->level;
2569}
2570
c2a2ac2b
XG
2571static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2572{
bb606a9b 2573 __shadow_walk_next(iterator, *iterator->sptep);
c2a2ac2b
XG
2574}
2575
98bba238
TY
2576static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2577 struct kvm_mmu_page *sp)
32ef26a3
AK
2578{
2579 u64 spte;
2580
ffb128c8 2581 BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
7a1638ce 2582
ffb128c8 2583 spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
d0ec49d4 2584 shadow_user_mask | shadow_x_mask | shadow_me_mask;
ac8d57e5
PF
2585
2586 if (sp_ad_disabled(sp))
6eeb4ef0 2587 spte |= SPTE_AD_DISABLED_MASK;
ac8d57e5
PF
2588 else
2589 spte |= shadow_accessed_mask;
24db2734 2590
1df9f2dc 2591 mmu_spte_set(sptep, spte);
98bba238
TY
2592
2593 mmu_page_add_parent_pte(vcpu, sp, sptep);
2594
2595 if (sp->unsync_children || sp->unsync)
2596 mark_unsync(sptep);
32ef26a3
AK
2597}
2598
a357bd22
AK
2599static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2600 unsigned direct_access)
2601{
2602 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2603 struct kvm_mmu_page *child;
2604
2605 /*
2606 * For the direct sp, if the guest pte's dirty bit
2607 * changed form clean to dirty, it will corrupt the
2608 * sp's access: allow writable in the read-only sp,
2609 * so we should update the spte at this point to get
2610 * a new sp with the correct access.
2611 */
e47c4aee 2612 child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
a357bd22
AK
2613 if (child->role.access == direct_access)
2614 return;
2615
bcdd9a93 2616 drop_parent_pte(child, sptep);
c3134ce2 2617 kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
a357bd22
AK
2618 }
2619}
2620
2de4085c
BG
2621/* Returns the number of zapped non-leaf child shadow pages. */
2622static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2623 u64 *spte, struct list_head *invalid_list)
38e3b2b2
XG
2624{
2625 u64 pte;
2626 struct kvm_mmu_page *child;
2627
2628 pte = *spte;
2629 if (is_shadow_present_pte(pte)) {
505aef8f 2630 if (is_last_spte(pte, sp->role.level)) {
c3707958 2631 drop_spte(kvm, spte);
505aef8f
XG
2632 if (is_large_pte(pte))
2633 --kvm->stat.lpages;
2634 } else {
e47c4aee 2635 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
bcdd9a93 2636 drop_parent_pte(child, spte);
2de4085c
BG
2637
2638 /*
2639 * Recursively zap nested TDP SPs, parentless SPs are
2640 * unlikely to be used again in the near future. This
2641 * avoids retaining a large number of stale nested SPs.
2642 */
2643 if (tdp_enabled && invalid_list &&
2644 child->role.guest_mode && !child->parent_ptes.val)
2645 return kvm_mmu_prepare_zap_page(kvm, child,
2646 invalid_list);
38e3b2b2 2647 }
ace569e0 2648 } else if (is_mmio_spte(pte)) {
ce88decf 2649 mmu_spte_clear_no_track(spte);
ace569e0 2650 }
2de4085c 2651 return 0;
38e3b2b2
XG
2652}
2653
2de4085c
BG
2654static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2655 struct kvm_mmu_page *sp,
2656 struct list_head *invalid_list)
a436036b 2657{
2de4085c 2658 int zapped = 0;
697fe2e2 2659 unsigned i;
697fe2e2 2660
38e3b2b2 2661 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2de4085c
BG
2662 zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2663
2664 return zapped;
a436036b
AK
2665}
2666
31aa2b44 2667static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
a436036b 2668{
1e3f42f0
TY
2669 u64 *sptep;
2670 struct rmap_iterator iter;
a436036b 2671
018aabb5 2672 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
1e3f42f0 2673 drop_parent_pte(sp, sptep);
31aa2b44
AK
2674}
2675
60c8aec6 2676static int mmu_zap_unsync_children(struct kvm *kvm,
7775834a
XG
2677 struct kvm_mmu_page *parent,
2678 struct list_head *invalid_list)
4731d4c7 2679{
60c8aec6
MT
2680 int i, zapped = 0;
2681 struct mmu_page_path parents;
2682 struct kvm_mmu_pages pages;
4731d4c7 2683
3bae0459 2684 if (parent->role.level == PG_LEVEL_4K)
4731d4c7 2685 return 0;
60c8aec6 2686
60c8aec6
MT
2687 while (mmu_unsync_walk(parent, &pages)) {
2688 struct kvm_mmu_page *sp;
2689
2690 for_each_sp(pages, sp, parents, i) {
7775834a 2691 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
60c8aec6 2692 mmu_pages_clear_parents(&parents);
77662e00 2693 zapped++;
60c8aec6 2694 }
60c8aec6
MT
2695 }
2696
2697 return zapped;
4731d4c7
MT
2698}
2699
83cdb568
SC
2700static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2701 struct kvm_mmu_page *sp,
2702 struct list_head *invalid_list,
2703 int *nr_zapped)
31aa2b44 2704{
83cdb568 2705 bool list_unstable;
f691fe1d 2706
7775834a 2707 trace_kvm_mmu_prepare_zap_page(sp);
31aa2b44 2708 ++kvm->stat.mmu_shadow_zapped;
83cdb568 2709 *nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2de4085c 2710 *nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
31aa2b44 2711 kvm_mmu_unlink_parents(kvm, sp);
5304b8d3 2712
83cdb568
SC
2713 /* Zapping children means active_mmu_pages has become unstable. */
2714 list_unstable = *nr_zapped;
2715
f6e2c02b 2716 if (!sp->role.invalid && !sp->role.direct)
3ed1a478 2717 unaccount_shadowed(kvm, sp);
5304b8d3 2718
4731d4c7
MT
2719 if (sp->unsync)
2720 kvm_unlink_unsync_page(kvm, sp);
4db35314 2721 if (!sp->root_count) {
54a4f023 2722 /* Count self */
83cdb568 2723 (*nr_zapped)++;
f95eec9b
SC
2724
2725 /*
2726 * Already invalid pages (previously active roots) are not on
2727 * the active page list. See list_del() in the "else" case of
2728 * !sp->root_count.
2729 */
2730 if (sp->role.invalid)
2731 list_add(&sp->link, invalid_list);
2732 else
2733 list_move(&sp->link, invalid_list);
aa6bd187 2734 kvm_mod_used_mmu_pages(kvm, -1);
2e53d63a 2735 } else {
f95eec9b
SC
2736 /*
2737 * Remove the active root from the active page list, the root
2738 * will be explicitly freed when the root_count hits zero.
2739 */
2740 list_del(&sp->link);
05988d72 2741
10605204
SC
2742 /*
2743 * Obsolete pages cannot be used on any vCPUs, see the comment
2744 * in kvm_mmu_zap_all_fast(). Note, is_obsolete_sp() also
2745 * treats invalid shadow pages as being obsolete.
2746 */
2747 if (!is_obsolete_sp(kvm, sp))
05988d72 2748 kvm_reload_remote_mmus(kvm);
2e53d63a 2749 }
7775834a 2750
b8e8c830
PB
2751 if (sp->lpage_disallowed)
2752 unaccount_huge_nx_page(kvm, sp);
2753
7775834a 2754 sp->role.invalid = 1;
83cdb568
SC
2755 return list_unstable;
2756}
2757
2758static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2759 struct list_head *invalid_list)
2760{
2761 int nr_zapped;
2762
2763 __kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2764 return nr_zapped;
a436036b
AK
2765}
2766
7775834a
XG
2767static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2768 struct list_head *invalid_list)
2769{
945315b9 2770 struct kvm_mmu_page *sp, *nsp;
7775834a
XG
2771
2772 if (list_empty(invalid_list))
2773 return;
2774
c142786c 2775 /*
9753f529
LT
2776 * We need to make sure everyone sees our modifications to
2777 * the page tables and see changes to vcpu->mode here. The barrier
2778 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2779 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2780 *
2781 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2782 * guest mode and/or lockless shadow page table walks.
c142786c
AK
2783 */
2784 kvm_flush_remote_tlbs(kvm);
c2a2ac2b 2785
945315b9 2786 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
7775834a 2787 WARN_ON(!sp->role.invalid || sp->root_count);
aa6bd187 2788 kvm_mmu_free_page(sp);
945315b9 2789 }
7775834a
XG
2790}
2791
6b82ef2c
SC
2792static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2793 unsigned long nr_to_zap)
5da59607 2794{
6b82ef2c
SC
2795 unsigned long total_zapped = 0;
2796 struct kvm_mmu_page *sp, *tmp;
ba7888dd 2797 LIST_HEAD(invalid_list);
6b82ef2c
SC
2798 bool unstable;
2799 int nr_zapped;
5da59607
TY
2800
2801 if (list_empty(&kvm->arch.active_mmu_pages))
ba7888dd
SC
2802 return 0;
2803
6b82ef2c
SC
2804restart:
2805 list_for_each_entry_safe(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2806 /*
2807 * Don't zap active root pages, the page itself can't be freed
2808 * and zapping it will just force vCPUs to realloc and reload.
2809 */
2810 if (sp->root_count)
2811 continue;
2812
2813 unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2814 &nr_zapped);
2815 total_zapped += nr_zapped;
2816 if (total_zapped >= nr_to_zap)
ba7888dd
SC
2817 break;
2818
6b82ef2c
SC
2819 if (unstable)
2820 goto restart;
ba7888dd 2821 }
5da59607 2822
6b82ef2c
SC
2823 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2824
2825 kvm->stat.mmu_recycled += total_zapped;
2826 return total_zapped;
2827}
2828
afe8d7e6
SC
2829static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2830{
2831 if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2832 return kvm->arch.n_max_mmu_pages -
2833 kvm->arch.n_used_mmu_pages;
2834
2835 return 0;
5da59607
TY
2836}
2837
ba7888dd
SC
2838static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2839{
6b82ef2c 2840 unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
ba7888dd 2841
6b82ef2c 2842 if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
ba7888dd
SC
2843 return 0;
2844
6b82ef2c 2845 kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
ba7888dd
SC
2846
2847 if (!kvm_mmu_available_pages(vcpu->kvm))
2848 return -ENOSPC;
2849 return 0;
2850}
2851
82ce2c96
IE
2852/*
2853 * Changing the number of mmu pages allocated to the vm
49d5ca26 2854 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
82ce2c96 2855 */
bc8a3d89 2856void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
82ce2c96 2857{
b34cb590
TY
2858 spin_lock(&kvm->mmu_lock);
2859
49d5ca26 2860 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
6b82ef2c
SC
2861 kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2862 goal_nr_mmu_pages);
82ce2c96 2863
49d5ca26 2864 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
82ce2c96 2865 }
82ce2c96 2866
49d5ca26 2867 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
b34cb590
TY
2868
2869 spin_unlock(&kvm->mmu_lock);
82ce2c96
IE
2870}
2871
1cb3f3ae 2872int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
a436036b 2873{
4db35314 2874 struct kvm_mmu_page *sp;
d98ba053 2875 LIST_HEAD(invalid_list);
a436036b
AK
2876 int r;
2877
9ad17b10 2878 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
a436036b 2879 r = 0;
1cb3f3ae 2880 spin_lock(&kvm->mmu_lock);
b67bfe0d 2881 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
9ad17b10 2882 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
7ae680eb
XG
2883 sp->role.word);
2884 r = 1;
f41d335a 2885 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7ae680eb 2886 }
d98ba053 2887 kvm_mmu_commit_zap_page(kvm, &invalid_list);
1cb3f3ae
XG
2888 spin_unlock(&kvm->mmu_lock);
2889
a436036b 2890 return r;
cea0f0e7 2891}
1cb3f3ae 2892EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
cea0f0e7 2893
5c520e90 2894static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
9cf5cf5a
XG
2895{
2896 trace_kvm_mmu_unsync_page(sp);
2897 ++vcpu->kvm->stat.mmu_unsync;
2898 sp->unsync = 1;
2899
2900 kvm_mmu_mark_parents_unsync(sp);
9cf5cf5a
XG
2901}
2902
3d0c27ad
XG
2903static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2904 bool can_unsync)
4731d4c7 2905{
5c520e90 2906 struct kvm_mmu_page *sp;
4731d4c7 2907
3d0c27ad
XG
2908 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2909 return true;
9cf5cf5a 2910
5c520e90 2911 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
36a2e677 2912 if (!can_unsync)
3d0c27ad 2913 return true;
36a2e677 2914
5c520e90
XG
2915 if (sp->unsync)
2916 continue;
9cf5cf5a 2917
3bae0459 2918 WARN_ON(sp->role.level != PG_LEVEL_4K);
5c520e90 2919 kvm_unsync_page(vcpu, sp);
4731d4c7 2920 }
3d0c27ad 2921
578e1c4d
JS
2922 /*
2923 * We need to ensure that the marking of unsync pages is visible
2924 * before the SPTE is updated to allow writes because
2925 * kvm_mmu_sync_roots() checks the unsync flags without holding
2926 * the MMU lock and so can race with this. If the SPTE was updated
2927 * before the page had been marked as unsync-ed, something like the
2928 * following could happen:
2929 *
2930 * CPU 1 CPU 2
2931 * ---------------------------------------------------------------------
2932 * 1.2 Host updates SPTE
2933 * to be writable
2934 * 2.1 Guest writes a GPTE for GVA X.
2935 * (GPTE being in the guest page table shadowed
2936 * by the SP from CPU 1.)
2937 * This reads SPTE during the page table walk.
2938 * Since SPTE.W is read as 1, there is no
2939 * fault.
2940 *
2941 * 2.2 Guest issues TLB flush.
2942 * That causes a VM Exit.
2943 *
2944 * 2.3 kvm_mmu_sync_pages() reads sp->unsync.
2945 * Since it is false, so it just returns.
2946 *
2947 * 2.4 Guest accesses GVA X.
2948 * Since the mapping in the SP was not updated,
2949 * so the old mapping for GVA X incorrectly
2950 * gets used.
2951 * 1.1 Host marks SP
2952 * as unsync
2953 * (sp->unsync = true)
2954 *
2955 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2956 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2957 * pairs with this write barrier.
2958 */
2959 smp_wmb();
2960
3d0c27ad 2961 return false;
4731d4c7
MT
2962}
2963
ba049e93 2964static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
d1fe9219
PB
2965{
2966 if (pfn_valid(pfn))
aa2e063a
HZ
2967 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2968 /*
2969 * Some reserved pages, such as those from NVDIMM
2970 * DAX devices, are not for MMIO, and can be mapped
2971 * with cached memory type for better performance.
2972 * However, the above check misconceives those pages
2973 * as MMIO, and results in KVM mapping them with UC
2974 * memory type, which would hurt the performance.
2975 * Therefore, we check the host memory type in addition
2976 * and only treat UC/UC-/WC pages as MMIO.
2977 */
2978 (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
d1fe9219 2979
0c55671f
KA
2980 return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2981 pfn_to_hpa(pfn + 1) - 1,
2982 E820_TYPE_RAM);
d1fe9219
PB
2983}
2984
5ce4786f
JS
2985/* Bits which may be returned by set_spte() */
2986#define SET_SPTE_WRITE_PROTECTED_PT BIT(0)
2987#define SET_SPTE_NEED_REMOTE_TLB_FLUSH BIT(1)
12703759 2988#define SET_SPTE_SPURIOUS BIT(2)
5ce4786f 2989
d555c333 2990static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
0a2b64c5 2991 unsigned int pte_access, int level,
ba049e93 2992 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
9bdbba13 2993 bool can_unsync, bool host_writable)
1c4f1fd6 2994{
ffb128c8 2995 u64 spte = 0;
1e73f9dd 2996 int ret = 0;
ac8d57e5 2997 struct kvm_mmu_page *sp;
64d4d521 2998
54bf36aa 2999 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
ce88decf
XG
3000 return 0;
3001
57354682 3002 sp = sptep_to_sp(sptep);
ac8d57e5 3003 if (sp_ad_disabled(sp))
6eeb4ef0 3004 spte |= SPTE_AD_DISABLED_MASK;
1f4e5fc8
PB
3005 else if (kvm_vcpu_ad_need_write_protect(vcpu))
3006 spte |= SPTE_AD_WRPROT_ONLY_MASK;
ac8d57e5 3007
d95c5568
BD
3008 /*
3009 * For the EPT case, shadow_present_mask is 0 if hardware
3010 * supports exec-only page table entries. In that case,
3011 * ACC_USER_MASK and shadow_user_mask are used to represent
3012 * read access. See FNAME(gpte_access) in paging_tmpl.h.
3013 */
ffb128c8 3014 spte |= shadow_present_mask;
947da538 3015 if (!speculative)
ac8d57e5 3016 spte |= spte_shadow_accessed_mask(spte);
640d9b0d 3017
3bae0459 3018 if (level > PG_LEVEL_4K && (pte_access & ACC_EXEC_MASK) &&
b8e8c830
PB
3019 is_nx_huge_page_enabled()) {
3020 pte_access &= ~ACC_EXEC_MASK;
3021 }
3022
7b52345e
SY
3023 if (pte_access & ACC_EXEC_MASK)
3024 spte |= shadow_x_mask;
3025 else
3026 spte |= shadow_nx_mask;
49fde340 3027
1c4f1fd6 3028 if (pte_access & ACC_USER_MASK)
7b52345e 3029 spte |= shadow_user_mask;
49fde340 3030
3bae0459 3031 if (level > PG_LEVEL_4K)
05da4558 3032 spte |= PT_PAGE_SIZE_MASK;
b0bc3ee2 3033 if (tdp_enabled)
afaf0b2f 3034 spte |= kvm_x86_ops.get_mt_mask(vcpu, gfn,
d1fe9219 3035 kvm_is_mmio_pfn(pfn));
1c4f1fd6 3036
9bdbba13 3037 if (host_writable)
1403283a 3038 spte |= SPTE_HOST_WRITEABLE;
f8e453b0
XG
3039 else
3040 pte_access &= ~ACC_WRITE_MASK;
1403283a 3041
daaf216c
TL
3042 if (!kvm_is_mmio_pfn(pfn))
3043 spte |= shadow_me_mask;
3044
35149e21 3045 spte |= (u64)pfn << PAGE_SHIFT;
1c4f1fd6 3046
c2288505 3047 if (pte_access & ACC_WRITE_MASK) {
49fde340 3048 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
1c4f1fd6 3049
ecc5589f
MT
3050 /*
3051 * Optimization: for pte sync, if spte was writable the hash
3052 * lookup is unnecessary (and expensive). Write protection
3053 * is responsibility of mmu_get_page / kvm_sync_page.
3054 * Same reasoning can be applied to dirty page accounting.
3055 */
8dae4445 3056 if (!can_unsync && is_writable_pte(*sptep))
ecc5589f
MT
3057 goto set_pte;
3058
4731d4c7 3059 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
9ad17b10 3060 pgprintk("%s: found shadow page for %llx, marking ro\n",
b8688d51 3061 __func__, gfn);
5ce4786f 3062 ret |= SET_SPTE_WRITE_PROTECTED_PT;
1c4f1fd6 3063 pte_access &= ~ACC_WRITE_MASK;
49fde340 3064 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
1c4f1fd6
AK
3065 }
3066 }
3067
9b51a630 3068 if (pte_access & ACC_WRITE_MASK) {
54bf36aa 3069 kvm_vcpu_mark_page_dirty(vcpu, gfn);
ac8d57e5 3070 spte |= spte_shadow_dirty_mask(spte);
9b51a630 3071 }
1c4f1fd6 3072
f160c7b7
JS
3073 if (speculative)
3074 spte = mark_spte_for_access_track(spte);
3075
38187c83 3076set_pte:
12703759
SC
3077 if (*sptep == spte)
3078 ret |= SET_SPTE_SPURIOUS;
3079 else if (mmu_spte_update(sptep, spte))
5ce4786f 3080 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
1e73f9dd
MT
3081 return ret;
3082}
3083
0a2b64c5
BG
3084static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
3085 unsigned int pte_access, int write_fault, int level,
3086 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
3087 bool host_writable)
1e73f9dd
MT
3088{
3089 int was_rmapped = 0;
53a27b39 3090 int rmap_count;
5ce4786f 3091 int set_spte_ret;
c4371c2a 3092 int ret = RET_PF_FIXED;
c2a4eadf 3093 bool flush = false;
1e73f9dd 3094
f7616203
XG
3095 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3096 *sptep, write_fault, gfn);
1e73f9dd 3097
afd28fe1 3098 if (is_shadow_present_pte(*sptep)) {
1e73f9dd
MT
3099 /*
3100 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3101 * the parent of the now unreachable PTE.
3102 */
3bae0459 3103 if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
1e73f9dd 3104 struct kvm_mmu_page *child;
d555c333 3105 u64 pte = *sptep;
1e73f9dd 3106
e47c4aee 3107 child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
bcdd9a93 3108 drop_parent_pte(child, sptep);
c2a4eadf 3109 flush = true;
d555c333 3110 } else if (pfn != spte_to_pfn(*sptep)) {
9ad17b10 3111 pgprintk("hfn old %llx new %llx\n",
d555c333 3112 spte_to_pfn(*sptep), pfn);
c3707958 3113 drop_spte(vcpu->kvm, sptep);
c2a4eadf 3114 flush = true;
6bed6b9e
JR
3115 } else
3116 was_rmapped = 1;
1e73f9dd 3117 }
852e3c19 3118
5ce4786f
JS
3119 set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3120 speculative, true, host_writable);
3121 if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
1e73f9dd 3122 if (write_fault)
9b8ebbdb 3123 ret = RET_PF_EMULATE;
8c8560b8 3124 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
a378b4e6 3125 }
c3134ce2 3126
c2a4eadf 3127 if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
c3134ce2
LT
3128 kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3129 KVM_PAGES_PER_HPAGE(level));
1e73f9dd 3130
029499b4 3131 if (unlikely(is_mmio_spte(*sptep)))
9b8ebbdb 3132 ret = RET_PF_EMULATE;
ce88decf 3133
12703759
SC
3134 /*
3135 * The fault is fully spurious if and only if the new SPTE and old SPTE
3136 * are identical, and emulation is not required.
3137 */
3138 if ((set_spte_ret & SET_SPTE_SPURIOUS) && ret == RET_PF_FIXED) {
3139 WARN_ON_ONCE(!was_rmapped);
3140 return RET_PF_SPURIOUS;
3141 }
3142
d555c333 3143 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
335e192a 3144 trace_kvm_mmu_set_spte(level, gfn, sptep);
d555c333 3145 if (!was_rmapped && is_large_pte(*sptep))
05da4558
MT
3146 ++vcpu->kvm->stat.lpages;
3147
ffb61bb3 3148 if (is_shadow_present_pte(*sptep)) {
ffb61bb3
XG
3149 if (!was_rmapped) {
3150 rmap_count = rmap_add(vcpu, sptep, gfn);
3151 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3152 rmap_recycle(vcpu, sptep, gfn);
3153 }
1c4f1fd6 3154 }
cb9aaa30 3155
9b8ebbdb 3156 return ret;
1c4f1fd6
AK
3157}
3158
ba049e93 3159static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
957ed9ef
XG
3160 bool no_dirty_log)
3161{
3162 struct kvm_memory_slot *slot;
957ed9ef 3163
5d163b1c 3164 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
903816fa 3165 if (!slot)
6c8ee57b 3166 return KVM_PFN_ERR_FAULT;
957ed9ef 3167
037d92dc 3168 return gfn_to_pfn_memslot_atomic(slot, gfn);
957ed9ef
XG
3169}
3170
3171static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3172 struct kvm_mmu_page *sp,
3173 u64 *start, u64 *end)
3174{
3175 struct page *pages[PTE_PREFETCH_NUM];
d9ef13c2 3176 struct kvm_memory_slot *slot;
0a2b64c5 3177 unsigned int access = sp->role.access;
957ed9ef
XG
3178 int i, ret;
3179 gfn_t gfn;
3180
3181 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
d9ef13c2
PB
3182 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3183 if (!slot)
957ed9ef
XG
3184 return -1;
3185
d9ef13c2 3186 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
957ed9ef
XG
3187 if (ret <= 0)
3188 return -1;
3189
43fdcda9 3190 for (i = 0; i < ret; i++, gfn++, start++) {
029499b4
TY
3191 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3192 page_to_pfn(pages[i]), true, true);
43fdcda9
JS
3193 put_page(pages[i]);
3194 }
957ed9ef
XG
3195
3196 return 0;
3197}
3198
3199static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3200 struct kvm_mmu_page *sp, u64 *sptep)
3201{
3202 u64 *spte, *start = NULL;
3203 int i;
3204
3205 WARN_ON(!sp->role.direct);
3206
3207 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3208 spte = sp->spt + i;
3209
3210 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
c3707958 3211 if (is_shadow_present_pte(*spte) || spte == sptep) {
957ed9ef
XG
3212 if (!start)
3213 continue;
3214 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3215 break;
3216 start = NULL;
3217 } else if (!start)
3218 start = spte;
3219 }
3220}
3221
3222static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3223{
3224 struct kvm_mmu_page *sp;
3225
57354682 3226 sp = sptep_to_sp(sptep);
ac8d57e5 3227
957ed9ef 3228 /*
ac8d57e5
PF
3229 * Without accessed bits, there's no way to distinguish between
3230 * actually accessed translations and prefetched, so disable pte
3231 * prefetch if accessed bits aren't available.
957ed9ef 3232 */
ac8d57e5 3233 if (sp_ad_disabled(sp))
957ed9ef
XG
3234 return;
3235
3bae0459 3236 if (sp->role.level > PG_LEVEL_4K)
957ed9ef
XG
3237 return;
3238
3239 __direct_pte_prefetch(vcpu, sp, sptep);
3240}
3241
db543216 3242static int host_pfn_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
293e306e 3243 kvm_pfn_t pfn, struct kvm_memory_slot *slot)
db543216 3244{
db543216
SC
3245 unsigned long hva;
3246 pte_t *pte;
3247 int level;
3248
e851265a 3249 if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
3bae0459 3250 return PG_LEVEL_4K;
db543216 3251
293e306e
SC
3252 /*
3253 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3254 * is not solely for performance, it's also necessary to avoid the
3255 * "writable" check in __gfn_to_hva_many(), which will always fail on
3256 * read-only memslots due to gfn_to_hva() assuming writes. Earlier
3257 * page fault steps have already verified the guest isn't writing a
3258 * read-only memslot.
3259 */
db543216
SC
3260 hva = __gfn_to_hva_memslot(slot, gfn);
3261
3262 pte = lookup_address_in_mm(vcpu->kvm->mm, hva, &level);
3263 if (unlikely(!pte))
3bae0459 3264 return PG_LEVEL_4K;
db543216
SC
3265
3266 return level;
3267}
3268
83f06fa7
SC
3269static int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
3270 int max_level, kvm_pfn_t *pfnp)
0885904d 3271{
293e306e 3272 struct kvm_memory_slot *slot;
2c0629f4 3273 struct kvm_lpage_info *linfo;
0885904d 3274 kvm_pfn_t pfn = *pfnp;
17eff019 3275 kvm_pfn_t mask;
83f06fa7 3276 int level;
17eff019 3277
3bae0459
SC
3278 if (unlikely(max_level == PG_LEVEL_4K))
3279 return PG_LEVEL_4K;
17eff019 3280
e851265a 3281 if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
3bae0459 3282 return PG_LEVEL_4K;
17eff019 3283
293e306e
SC
3284 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
3285 if (!slot)
3bae0459 3286 return PG_LEVEL_4K;
293e306e 3287
1d92d2e8 3288 max_level = min(max_level, max_huge_page_level);
3bae0459 3289 for ( ; max_level > PG_LEVEL_4K; max_level--) {
2c0629f4
SC
3290 linfo = lpage_info_slot(gfn, slot, max_level);
3291 if (!linfo->disallow_lpage)
293e306e
SC
3292 break;
3293 }
3294
3bae0459
SC
3295 if (max_level == PG_LEVEL_4K)
3296 return PG_LEVEL_4K;
293e306e
SC
3297
3298 level = host_pfn_mapping_level(vcpu, gfn, pfn, slot);
3bae0459 3299 if (level == PG_LEVEL_4K)
83f06fa7 3300 return level;
17eff019 3301
db543216 3302 level = min(level, max_level);
0885904d
SC
3303
3304 /*
17eff019
SC
3305 * mmu_notifier_retry() was successful and mmu_lock is held, so
3306 * the pmd can't be split from under us.
0885904d 3307 */
17eff019
SC
3308 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3309 VM_BUG_ON((gfn & mask) != (pfn & mask));
3310 *pfnp = pfn & ~mask;
83f06fa7
SC
3311
3312 return level;
0885904d
SC
3313}
3314
b8e8c830
PB
3315static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3316 gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3317{
3318 int level = *levelp;
3319 u64 spte = *it.sptep;
3320
3bae0459 3321 if (it.level == level && level > PG_LEVEL_4K &&
b8e8c830
PB
3322 is_nx_huge_page_enabled() &&
3323 is_shadow_present_pte(spte) &&
3324 !is_large_pte(spte)) {
3325 /*
3326 * A small SPTE exists for this pfn, but FNAME(fetch)
3327 * and __direct_map would like to create a large PTE
3328 * instead: just force them to go down another level,
3329 * patching back for them into pfn the next 9 bits of
3330 * the address.
3331 */
3332 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3333 *pfnp |= gfn & page_mask;
3334 (*levelp)--;
3335 }
3336}
3337
3fcf2d1b 3338static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
83f06fa7
SC
3339 int map_writable, int max_level, kvm_pfn_t pfn,
3340 bool prefault, bool account_disallowed_nx_lpage)
140754bc 3341{
3fcf2d1b 3342 struct kvm_shadow_walk_iterator it;
140754bc 3343 struct kvm_mmu_page *sp;
83f06fa7 3344 int level, ret;
3fcf2d1b
PB
3345 gfn_t gfn = gpa >> PAGE_SHIFT;
3346 gfn_t base_gfn = gfn;
6aa8b732 3347
0c7a98e3 3348 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
3fcf2d1b 3349 return RET_PF_RETRY;
989c6b34 3350
83f06fa7 3351 level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn);
4cd071d1 3352
335e192a 3353 trace_kvm_mmu_spte_requested(gpa, level, pfn);
3fcf2d1b 3354 for_each_shadow_entry(vcpu, gpa, it) {
b8e8c830
PB
3355 /*
3356 * We cannot overwrite existing page tables with an NX
3357 * large page, as the leaf could be executable.
3358 */
3359 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3360
3fcf2d1b
PB
3361 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3362 if (it.level == level)
9f652d21 3363 break;
6aa8b732 3364
3fcf2d1b
PB
3365 drop_large_spte(vcpu, it.sptep);
3366 if (!is_shadow_present_pte(*it.sptep)) {
3367 sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3368 it.level - 1, true, ACC_ALL);
c9fa0b3b 3369
3fcf2d1b 3370 link_shadow_page(vcpu, it.sptep, sp);
2cb70fd4 3371 if (account_disallowed_nx_lpage)
b8e8c830 3372 account_huge_nx_page(vcpu->kvm, sp);
9f652d21
AK
3373 }
3374 }
3fcf2d1b
PB
3375
3376 ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3377 write, level, base_gfn, pfn, prefault,
3378 map_writable);
12703759
SC
3379 if (ret == RET_PF_SPURIOUS)
3380 return ret;
3381
3fcf2d1b
PB
3382 direct_pte_prefetch(vcpu, it.sptep);
3383 ++vcpu->stat.pf_fixed;
3384 return ret;
6aa8b732
AK
3385}
3386
77db5cbd 3387static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
bf998156 3388{
585a8b9b 3389 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
bf998156
HY
3390}
3391
ba049e93 3392static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
bf998156 3393{
4d8b81ab
XG
3394 /*
3395 * Do not cache the mmio info caused by writing the readonly gfn
3396 * into the spte otherwise read access on readonly gfn also can
3397 * caused mmio page fault and treat it as mmio access.
4d8b81ab
XG
3398 */
3399 if (pfn == KVM_PFN_ERR_RO_FAULT)
9b8ebbdb 3400 return RET_PF_EMULATE;
4d8b81ab 3401
e6c1502b 3402 if (pfn == KVM_PFN_ERR_HWPOISON) {
54bf36aa 3403 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
9b8ebbdb 3404 return RET_PF_RETRY;
d7c55201 3405 }
edba23e5 3406
2c151b25 3407 return -EFAULT;
bf998156
HY
3408}
3409
d7c55201 3410static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
0a2b64c5
BG
3411 kvm_pfn_t pfn, unsigned int access,
3412 int *ret_val)
d7c55201 3413{
d7c55201 3414 /* The pfn is invalid, report the error! */
81c52c56 3415 if (unlikely(is_error_pfn(pfn))) {
d7c55201 3416 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
798e88b3 3417 return true;
d7c55201
XG
3418 }
3419
ce88decf 3420 if (unlikely(is_noslot_pfn(pfn)))
4af77151
SC
3421 vcpu_cache_mmio_info(vcpu, gva, gfn,
3422 access & shadow_mmio_access_mask);
d7c55201 3423
798e88b3 3424 return false;
d7c55201
XG
3425}
3426
e5552fd2 3427static bool page_fault_can_be_fast(u32 error_code)
c7ba5b48 3428{
1c118b82
XG
3429 /*
3430 * Do not fix the mmio spte with invalid generation number which
3431 * need to be updated by slow page fault path.
3432 */
3433 if (unlikely(error_code & PFERR_RSVD_MASK))
3434 return false;
3435
f160c7b7
JS
3436 /* See if the page fault is due to an NX violation */
3437 if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3438 == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3439 return false;
3440
c7ba5b48 3441 /*
f160c7b7
JS
3442 * #PF can be fast if:
3443 * 1. The shadow page table entry is not present, which could mean that
3444 * the fault is potentially caused by access tracking (if enabled).
3445 * 2. The shadow page table entry is present and the fault
3446 * is caused by write-protect, that means we just need change the W
3447 * bit of the spte which can be done out of mmu-lock.
3448 *
3449 * However, if access tracking is disabled we know that a non-present
3450 * page must be a genuine page fault where we have to create a new SPTE.
3451 * So, if access tracking is disabled, we return true only for write
3452 * accesses to a present page.
c7ba5b48 3453 */
c7ba5b48 3454
f160c7b7
JS
3455 return shadow_acc_track_mask != 0 ||
3456 ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3457 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
c7ba5b48
XG
3458}
3459
97dceba2
JS
3460/*
3461 * Returns true if the SPTE was fixed successfully. Otherwise,
3462 * someone else modified the SPTE from its original value.
3463 */
c7ba5b48 3464static bool
92a476cb 3465fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
d3e328f2 3466 u64 *sptep, u64 old_spte, u64 new_spte)
c7ba5b48 3467{
c7ba5b48
XG
3468 gfn_t gfn;
3469
3470 WARN_ON(!sp->role.direct);
3471
9b51a630
KH
3472 /*
3473 * Theoretically we could also set dirty bit (and flush TLB) here in
3474 * order to eliminate unnecessary PML logging. See comments in
3475 * set_spte. But fast_page_fault is very unlikely to happen with PML
3476 * enabled, so we do not do this. This might result in the same GPA
3477 * to be logged in PML buffer again when the write really happens, and
3478 * eventually to be called by mark_page_dirty twice. But it's also no
3479 * harm. This also avoids the TLB flush needed after setting dirty bit
3480 * so non-PML cases won't be impacted.
3481 *
3482 * Compare with set_spte where instead shadow_dirty_mask is set.
3483 */
f160c7b7 3484 if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
97dceba2
JS
3485 return false;
3486
d3e328f2 3487 if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
f160c7b7
JS
3488 /*
3489 * The gfn of direct spte is stable since it is
3490 * calculated by sp->gfn.
3491 */
3492 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3493 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3494 }
c7ba5b48
XG
3495
3496 return true;
3497}
3498
d3e328f2
JS
3499static bool is_access_allowed(u32 fault_err_code, u64 spte)
3500{
3501 if (fault_err_code & PFERR_FETCH_MASK)
3502 return is_executable_pte(spte);
3503
3504 if (fault_err_code & PFERR_WRITE_MASK)
3505 return is_writable_pte(spte);
3506
3507 /* Fault was on Read access */
3508 return spte & PT_PRESENT_MASK;
3509}
3510
c7ba5b48 3511/*
c4371c2a 3512 * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
c7ba5b48 3513 */
c4371c2a
SC
3514static int fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3515 u32 error_code)
c7ba5b48
XG
3516{
3517 struct kvm_shadow_walk_iterator iterator;
92a476cb 3518 struct kvm_mmu_page *sp;
c4371c2a 3519 int ret = RET_PF_INVALID;
c7ba5b48 3520 u64 spte = 0ull;
97dceba2 3521 uint retry_count = 0;
c7ba5b48 3522
e5552fd2 3523 if (!page_fault_can_be_fast(error_code))
c4371c2a 3524 return ret;
c7ba5b48
XG
3525
3526 walk_shadow_page_lockless_begin(vcpu);
c7ba5b48 3527
97dceba2 3528 do {
d3e328f2 3529 u64 new_spte;
c7ba5b48 3530
736c291c 3531 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
f9fa2509 3532 if (!is_shadow_present_pte(spte))
d162f30a
JS
3533 break;
3534
57354682 3535 sp = sptep_to_sp(iterator.sptep);
97dceba2
JS
3536 if (!is_last_spte(spte, sp->role.level))
3537 break;
c7ba5b48 3538
97dceba2 3539 /*
f160c7b7
JS
3540 * Check whether the memory access that caused the fault would
3541 * still cause it if it were to be performed right now. If not,
3542 * then this is a spurious fault caused by TLB lazily flushed,
3543 * or some other CPU has already fixed the PTE after the
3544 * current CPU took the fault.
97dceba2
JS
3545 *
3546 * Need not check the access of upper level table entries since
3547 * they are always ACC_ALL.
3548 */
d3e328f2 3549 if (is_access_allowed(error_code, spte)) {
c4371c2a 3550 ret = RET_PF_SPURIOUS;
d3e328f2
JS
3551 break;
3552 }
f160c7b7 3553
d3e328f2
JS
3554 new_spte = spte;
3555
3556 if (is_access_track_spte(spte))
3557 new_spte = restore_acc_track_spte(new_spte);
3558
3559 /*
3560 * Currently, to simplify the code, write-protection can
3561 * be removed in the fast path only if the SPTE was
3562 * write-protected for dirty-logging or access tracking.
3563 */
3564 if ((error_code & PFERR_WRITE_MASK) &&
e6302698 3565 spte_can_locklessly_be_made_writable(spte)) {
d3e328f2 3566 new_spte |= PT_WRITABLE_MASK;
f160c7b7
JS
3567
3568 /*
d3e328f2
JS
3569 * Do not fix write-permission on the large spte. Since
3570 * we only dirty the first page into the dirty-bitmap in
3571 * fast_pf_fix_direct_spte(), other pages are missed
3572 * if its slot has dirty logging enabled.
3573 *
3574 * Instead, we let the slow page fault path create a
3575 * normal spte to fix the access.
3576 *
3577 * See the comments in kvm_arch_commit_memory_region().
f160c7b7 3578 */
3bae0459 3579 if (sp->role.level > PG_LEVEL_4K)
f160c7b7 3580 break;
97dceba2 3581 }
c7ba5b48 3582
f160c7b7 3583 /* Verify that the fault can be handled in the fast path */
d3e328f2
JS
3584 if (new_spte == spte ||
3585 !is_access_allowed(error_code, new_spte))
97dceba2
JS
3586 break;
3587
3588 /*
3589 * Currently, fast page fault only works for direct mapping
3590 * since the gfn is not stable for indirect shadow page. See
3ecad8c2 3591 * Documentation/virt/kvm/locking.rst to get more detail.
97dceba2 3592 */
c4371c2a
SC
3593 if (fast_pf_fix_direct_spte(vcpu, sp, iterator.sptep, spte,
3594 new_spte)) {
3595 ret = RET_PF_FIXED;
97dceba2 3596 break;
c4371c2a 3597 }
97dceba2
JS
3598
3599 if (++retry_count > 4) {
3600 printk_once(KERN_WARNING
3601 "kvm: Fast #PF retrying more than 4 times.\n");
3602 break;
3603 }
3604
97dceba2 3605 } while (true);
c126d94f 3606
736c291c 3607 trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
c4371c2a 3608 spte, ret);
c7ba5b48
XG
3609 walk_shadow_page_lockless_end(vcpu);
3610
c4371c2a 3611 return ret;
c7ba5b48
XG
3612}
3613
74b566e6
JS
3614static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3615 struct list_head *invalid_list)
17ac10ad 3616{
4db35314 3617 struct kvm_mmu_page *sp;
17ac10ad 3618
74b566e6 3619 if (!VALID_PAGE(*root_hpa))
7b53aa56 3620 return;
35af577a 3621
e47c4aee 3622 sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
74b566e6
JS
3623 --sp->root_count;
3624 if (!sp->root_count && sp->role.invalid)
3625 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
17ac10ad 3626
74b566e6
JS
3627 *root_hpa = INVALID_PAGE;
3628}
3629
08fb59d8 3630/* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
6a82cd1c
VK
3631void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3632 ulong roots_to_free)
74b566e6 3633{
4d710de9 3634 struct kvm *kvm = vcpu->kvm;
74b566e6
JS
3635 int i;
3636 LIST_HEAD(invalid_list);
08fb59d8 3637 bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
74b566e6 3638
b94742c9 3639 BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
74b566e6 3640
08fb59d8 3641 /* Before acquiring the MMU lock, see if we need to do any real work. */
b94742c9
JS
3642 if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3643 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3644 if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3645 VALID_PAGE(mmu->prev_roots[i].hpa))
3646 break;
3647
3648 if (i == KVM_MMU_NUM_PREV_ROOTS)
3649 return;
3650 }
35af577a 3651
4d710de9 3652 spin_lock(&kvm->mmu_lock);
17ac10ad 3653
b94742c9
JS
3654 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3655 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
4d710de9 3656 mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
b94742c9 3657 &invalid_list);
7c390d35 3658
08fb59d8
JS
3659 if (free_active_root) {
3660 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3661 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
4d710de9 3662 mmu_free_root_page(kvm, &mmu->root_hpa, &invalid_list);
08fb59d8
JS
3663 } else {
3664 for (i = 0; i < 4; ++i)
3665 if (mmu->pae_root[i] != 0)
4d710de9 3666 mmu_free_root_page(kvm,
08fb59d8
JS
3667 &mmu->pae_root[i],
3668 &invalid_list);
3669 mmu->root_hpa = INVALID_PAGE;
3670 }
be01e8e2 3671 mmu->root_pgd = 0;
17ac10ad 3672 }
74b566e6 3673
4d710de9
SC
3674 kvm_mmu_commit_zap_page(kvm, &invalid_list);
3675 spin_unlock(&kvm->mmu_lock);
17ac10ad 3676}
74b566e6 3677EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
17ac10ad 3678
8986ecc0
MT
3679static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3680{
3681 int ret = 0;
3682
995decb6 3683 if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
a8eeb04a 3684 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8986ecc0
MT
3685 ret = 1;
3686 }
3687
3688 return ret;
3689}
3690
8123f265
SC
3691static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
3692 u8 level, bool direct)
651dd37a
JR
3693{
3694 struct kvm_mmu_page *sp;
8123f265
SC
3695
3696 spin_lock(&vcpu->kvm->mmu_lock);
3697
3698 if (make_mmu_pages_available(vcpu)) {
3699 spin_unlock(&vcpu->kvm->mmu_lock);
3700 return INVALID_PAGE;
3701 }
3702 sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
3703 ++sp->root_count;
3704
3705 spin_unlock(&vcpu->kvm->mmu_lock);
3706 return __pa(sp->spt);
3707}
3708
3709static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3710{
3711 u8 shadow_root_level = vcpu->arch.mmu->shadow_root_level;
3712 hpa_t root;
7ebaf15e 3713 unsigned i;
651dd37a 3714
8123f265
SC
3715 if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3716 root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
3717 if (!VALID_PAGE(root))
ed52870f 3718 return -ENOSPC;
8123f265
SC
3719 vcpu->arch.mmu->root_hpa = root;
3720 } else if (shadow_root_level == PT32E_ROOT_LEVEL) {
651dd37a 3721 for (i = 0; i < 4; ++i) {
8123f265 3722 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
651dd37a 3723
8123f265
SC
3724 root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
3725 i << 30, PT32_ROOT_LEVEL, true);
3726 if (!VALID_PAGE(root))
ed52870f 3727 return -ENOSPC;
44dd3ffa 3728 vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
651dd37a 3729 }
44dd3ffa 3730 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
651dd37a
JR
3731 } else
3732 BUG();
3651c7fc 3733
be01e8e2
SC
3734 /* root_pgd is ignored for direct MMUs. */
3735 vcpu->arch.mmu->root_pgd = 0;
651dd37a
JR
3736
3737 return 0;
3738}
3739
3740static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
17ac10ad 3741{
81407ca5 3742 u64 pdptr, pm_mask;
be01e8e2 3743 gfn_t root_gfn, root_pgd;
8123f265 3744 hpa_t root;
81407ca5 3745 int i;
3bb65a22 3746
be01e8e2
SC
3747 root_pgd = vcpu->arch.mmu->get_guest_pgd(vcpu);
3748 root_gfn = root_pgd >> PAGE_SHIFT;
17ac10ad 3749
651dd37a
JR
3750 if (mmu_check_root(vcpu, root_gfn))
3751 return 1;
3752
3753 /*
3754 * Do we shadow a long mode page table? If so we need to
3755 * write-protect the guests page table root.
3756 */
44dd3ffa 3757 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
8123f265 3758 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->root_hpa));
651dd37a 3759
8123f265
SC
3760 root = mmu_alloc_root(vcpu, root_gfn, 0,
3761 vcpu->arch.mmu->shadow_root_level, false);
3762 if (!VALID_PAGE(root))
ed52870f 3763 return -ENOSPC;
44dd3ffa 3764 vcpu->arch.mmu->root_hpa = root;
be01e8e2 3765 goto set_root_pgd;
17ac10ad 3766 }
f87f9288 3767
651dd37a
JR
3768 /*
3769 * We shadow a 32 bit page table. This may be a legacy 2-level
81407ca5
JR
3770 * or a PAE 3-level page table. In either case we need to be aware that
3771 * the shadow page table may be a PAE or a long mode page table.
651dd37a 3772 */
81407ca5 3773 pm_mask = PT_PRESENT_MASK;
44dd3ffa 3774 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
81407ca5
JR
3775 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3776
17ac10ad 3777 for (i = 0; i < 4; ++i) {
8123f265 3778 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
44dd3ffa
VK
3779 if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3780 pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
812f30b2 3781 if (!(pdptr & PT_PRESENT_MASK)) {
44dd3ffa 3782 vcpu->arch.mmu->pae_root[i] = 0;
417726a3
AK
3783 continue;
3784 }
6de4f3ad 3785 root_gfn = pdptr >> PAGE_SHIFT;
f87f9288
JR
3786 if (mmu_check_root(vcpu, root_gfn))
3787 return 1;
5a7388c2 3788 }
8facbbff 3789
8123f265
SC
3790 root = mmu_alloc_root(vcpu, root_gfn, i << 30,
3791 PT32_ROOT_LEVEL, false);
3792 if (!VALID_PAGE(root))
3793 return -ENOSPC;
44dd3ffa 3794 vcpu->arch.mmu->pae_root[i] = root | pm_mask;
17ac10ad 3795 }
44dd3ffa 3796 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
81407ca5
JR
3797
3798 /*
3799 * If we shadow a 32 bit page table with a long mode page
3800 * table we enter this path.
3801 */
44dd3ffa
VK
3802 if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3803 if (vcpu->arch.mmu->lm_root == NULL) {
81407ca5
JR
3804 /*
3805 * The additional page necessary for this is only
3806 * allocated on demand.
3807 */
3808
3809 u64 *lm_root;
3810
254272ce 3811 lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
81407ca5
JR
3812 if (lm_root == NULL)
3813 return 1;
3814
44dd3ffa 3815 lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
81407ca5 3816
44dd3ffa 3817 vcpu->arch.mmu->lm_root = lm_root;
81407ca5
JR
3818 }
3819
44dd3ffa 3820 vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
81407ca5
JR
3821 }
3822
be01e8e2
SC
3823set_root_pgd:
3824 vcpu->arch.mmu->root_pgd = root_pgd;
ad7dc69a 3825
8986ecc0 3826 return 0;
17ac10ad
AK
3827}
3828
651dd37a
JR
3829static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3830{
44dd3ffa 3831 if (vcpu->arch.mmu->direct_map)
651dd37a
JR
3832 return mmu_alloc_direct_roots(vcpu);
3833 else
3834 return mmu_alloc_shadow_roots(vcpu);
3835}
3836
578e1c4d 3837void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
0ba73cda
MT
3838{
3839 int i;
3840 struct kvm_mmu_page *sp;
3841
44dd3ffa 3842 if (vcpu->arch.mmu->direct_map)
81407ca5
JR
3843 return;
3844
44dd3ffa 3845 if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
0ba73cda 3846 return;
6903074c 3847
56f17dd3 3848 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
578e1c4d 3849
44dd3ffa
VK
3850 if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3851 hpa_t root = vcpu->arch.mmu->root_hpa;
e47c4aee 3852 sp = to_shadow_page(root);
578e1c4d
JS
3853
3854 /*
3855 * Even if another CPU was marking the SP as unsync-ed
3856 * simultaneously, any guest page table changes are not
3857 * guaranteed to be visible anyway until this VCPU issues a TLB
3858 * flush strictly after those changes are made. We only need to
3859 * ensure that the other CPU sets these flags before any actual
3860 * changes to the page tables are made. The comments in
3861 * mmu_need_write_protect() describe what could go wrong if this
3862 * requirement isn't satisfied.
3863 */
3864 if (!smp_load_acquire(&sp->unsync) &&
3865 !smp_load_acquire(&sp->unsync_children))
3866 return;
3867
3868 spin_lock(&vcpu->kvm->mmu_lock);
3869 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3870
0ba73cda 3871 mmu_sync_children(vcpu, sp);
578e1c4d 3872
0375f7fa 3873 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
578e1c4d 3874 spin_unlock(&vcpu->kvm->mmu_lock);
0ba73cda
MT
3875 return;
3876 }
578e1c4d
JS
3877
3878 spin_lock(&vcpu->kvm->mmu_lock);
3879 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3880
0ba73cda 3881 for (i = 0; i < 4; ++i) {
44dd3ffa 3882 hpa_t root = vcpu->arch.mmu->pae_root[i];
0ba73cda 3883
8986ecc0 3884 if (root && VALID_PAGE(root)) {
0ba73cda 3885 root &= PT64_BASE_ADDR_MASK;
e47c4aee 3886 sp = to_shadow_page(root);
0ba73cda
MT
3887 mmu_sync_children(vcpu, sp);
3888 }
3889 }
0ba73cda 3890
578e1c4d 3891 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
6cffe8ca 3892 spin_unlock(&vcpu->kvm->mmu_lock);
0ba73cda 3893}
bfd0a56b 3894EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
0ba73cda 3895
736c291c 3896static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
ab9ae313 3897 u32 access, struct x86_exception *exception)
6aa8b732 3898{
ab9ae313
AK
3899 if (exception)
3900 exception->error_code = 0;
6aa8b732
AK
3901 return vaddr;
3902}
3903
736c291c 3904static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
ab9ae313
AK
3905 u32 access,
3906 struct x86_exception *exception)
6539e738 3907{
ab9ae313
AK
3908 if (exception)
3909 exception->error_code = 0;
54987b7a 3910 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
6539e738
JR
3911}
3912
d625b155
XG
3913static bool
3914__is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3915{
b5c3c1b3 3916 int bit7 = (pte >> 7) & 1;
d625b155 3917
b5c3c1b3 3918 return pte & rsvd_check->rsvd_bits_mask[bit7][level-1];
d625b155
XG
3919}
3920
b5c3c1b3 3921static bool __is_bad_mt_xwr(struct rsvd_bits_validate *rsvd_check, u64 pte)
d625b155 3922{
b5c3c1b3 3923 return rsvd_check->bad_mt_xwr & BIT_ULL(pte & 0x3f);
d625b155
XG
3924}
3925
ded58749 3926static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf 3927{
9034e6e8
PB
3928 /*
3929 * A nested guest cannot use the MMIO cache if it is using nested
3930 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3931 */
3932 if (mmu_is_nested(vcpu))
3933 return false;
3934
ce88decf
XG
3935 if (direct)
3936 return vcpu_match_mmio_gpa(vcpu, addr);
3937
3938 return vcpu_match_mmio_gva(vcpu, addr);
3939}
3940
47ab8751
XG
3941/* return true if reserved bit is detected on spte. */
3942static bool
3943walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
ce88decf
XG
3944{
3945 struct kvm_shadow_walk_iterator iterator;
2a7266a8 3946 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
b5c3c1b3 3947 struct rsvd_bits_validate *rsvd_check;
47ab8751
XG
3948 int root, leaf;
3949 bool reserved = false;
ce88decf 3950
b5c3c1b3 3951 rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
37f6a4e2 3952
ce88decf 3953 walk_shadow_page_lockless_begin(vcpu);
47ab8751 3954
29ecd660
PB
3955 for (shadow_walk_init(&iterator, vcpu, addr),
3956 leaf = root = iterator.level;
47ab8751
XG
3957 shadow_walk_okay(&iterator);
3958 __shadow_walk_next(&iterator, spte)) {
47ab8751
XG
3959 spte = mmu_spte_get_lockless(iterator.sptep);
3960
3961 sptes[leaf - 1] = spte;
29ecd660 3962 leaf--;
47ab8751 3963
ce88decf
XG
3964 if (!is_shadow_present_pte(spte))
3965 break;
47ab8751 3966
b5c3c1b3
SC
3967 /*
3968 * Use a bitwise-OR instead of a logical-OR to aggregate the
3969 * reserved bit and EPT's invalid memtype/XWR checks to avoid
3970 * adding a Jcc in the loop.
3971 */
3972 reserved |= __is_bad_mt_xwr(rsvd_check, spte) |
3973 __is_rsvd_bits_set(rsvd_check, spte, iterator.level);
47ab8751
XG
3974 }
3975
ce88decf
XG
3976 walk_shadow_page_lockless_end(vcpu);
3977
47ab8751
XG
3978 if (reserved) {
3979 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3980 __func__, addr);
29ecd660 3981 while (root > leaf) {
47ab8751
XG
3982 pr_err("------ spte 0x%llx level %d.\n",
3983 sptes[root - 1], root);
3984 root--;
3985 }
3986 }
ddce6208 3987
47ab8751
XG
3988 *sptep = spte;
3989 return reserved;
ce88decf
XG
3990}
3991
e08d26f0 3992static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf
XG
3993{
3994 u64 spte;
47ab8751 3995 bool reserved;
ce88decf 3996
ded58749 3997 if (mmio_info_in_cache(vcpu, addr, direct))
9b8ebbdb 3998 return RET_PF_EMULATE;
ce88decf 3999
47ab8751 4000 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
450869d6 4001 if (WARN_ON(reserved))
9b8ebbdb 4002 return -EINVAL;
ce88decf
XG
4003
4004 if (is_mmio_spte(spte)) {
4005 gfn_t gfn = get_mmio_spte_gfn(spte);
0a2b64c5 4006 unsigned int access = get_mmio_spte_access(spte);
ce88decf 4007
54bf36aa 4008 if (!check_mmio_spte(vcpu, spte))
9b8ebbdb 4009 return RET_PF_INVALID;
f8f55942 4010
ce88decf
XG
4011 if (direct)
4012 addr = 0;
4f022648
XG
4013
4014 trace_handle_mmio_page_fault(addr, gfn, access);
ce88decf 4015 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
9b8ebbdb 4016 return RET_PF_EMULATE;
ce88decf
XG
4017 }
4018
ce88decf
XG
4019 /*
4020 * If the page table is zapped by other cpus, let CPU fault again on
4021 * the address.
4022 */
9b8ebbdb 4023 return RET_PF_RETRY;
ce88decf 4024}
ce88decf 4025
3d0c27ad
XG
4026static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4027 u32 error_code, gfn_t gfn)
4028{
4029 if (unlikely(error_code & PFERR_RSVD_MASK))
4030 return false;
4031
4032 if (!(error_code & PFERR_PRESENT_MASK) ||
4033 !(error_code & PFERR_WRITE_MASK))
4034 return false;
4035
4036 /*
4037 * guest is writing the page which is write tracked which can
4038 * not be fixed by page fault handler.
4039 */
4040 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4041 return true;
4042
4043 return false;
4044}
4045
e5691a81
XG
4046static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4047{
4048 struct kvm_shadow_walk_iterator iterator;
4049 u64 spte;
4050
e5691a81
XG
4051 walk_shadow_page_lockless_begin(vcpu);
4052 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4053 clear_sp_write_flooding_count(iterator.sptep);
4054 if (!is_shadow_present_pte(spte))
4055 break;
4056 }
4057 walk_shadow_page_lockless_end(vcpu);
4058}
4059
e8c22266
VK
4060static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4061 gfn_t gfn)
af585b92
GN
4062{
4063 struct kvm_arch_async_pf arch;
fb67e14f 4064
7c90705b 4065 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
af585b92 4066 arch.gfn = gfn;
44dd3ffa 4067 arch.direct_map = vcpu->arch.mmu->direct_map;
d8dd54e0 4068 arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
af585b92 4069
9f1a8526
SC
4070 return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4071 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
af585b92
GN
4072}
4073
78b2c54a 4074static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
9f1a8526
SC
4075 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4076 bool *writable)
af585b92 4077{
c36b7150 4078 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
af585b92
GN
4079 bool async;
4080
c36b7150
PB
4081 /* Don't expose private memslots to L2. */
4082 if (is_guest_mode(vcpu) && !kvm_is_visible_memslot(slot)) {
3a2936de 4083 *pfn = KVM_PFN_NOSLOT;
c583eed6 4084 *writable = false;
3a2936de
JM
4085 return false;
4086 }
4087
3520469d
PB
4088 async = false;
4089 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
af585b92
GN
4090 if (!async)
4091 return false; /* *pfn has correct page already */
4092
9bc1f09f 4093 if (!prefault && kvm_can_do_async_pf(vcpu)) {
9f1a8526 4094 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
af585b92 4095 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
9f1a8526 4096 trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
af585b92
GN
4097 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4098 return true;
9f1a8526 4099 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
af585b92
GN
4100 return true;
4101 }
4102
3520469d 4103 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
af585b92
GN
4104 return false;
4105}
4106
0f90e1c1
SC
4107static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4108 bool prefault, int max_level, bool is_tdp)
6aa8b732 4109{
367fd790 4110 bool write = error_code & PFERR_WRITE_MASK;
367fd790
SC
4111 bool exec = error_code & PFERR_FETCH_MASK;
4112 bool lpage_disallowed = exec && is_nx_huge_page_enabled();
0f90e1c1 4113 bool map_writable;
6aa8b732 4114
0f90e1c1
SC
4115 gfn_t gfn = gpa >> PAGE_SHIFT;
4116 unsigned long mmu_seq;
4117 kvm_pfn_t pfn;
83f06fa7 4118 int r;
ce88decf 4119
3d0c27ad 4120 if (page_fault_handle_page_track(vcpu, error_code, gfn))
9b8ebbdb 4121 return RET_PF_EMULATE;
ce88decf 4122
c4371c2a
SC
4123 r = fast_page_fault(vcpu, gpa, error_code);
4124 if (r != RET_PF_INVALID)
4125 return r;
83291445 4126
378f5cd6 4127 r = mmu_topup_memory_caches(vcpu, false);
e2dec939
AK
4128 if (r)
4129 return r;
714b93da 4130
0f90e1c1 4131 if (lpage_disallowed)
3bae0459 4132 max_level = PG_LEVEL_4K;
367fd790 4133
367fd790
SC
4134 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4135 smp_rmb();
4136
4137 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4138 return RET_PF_RETRY;
4139
0f90e1c1 4140 if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
367fd790 4141 return r;
6aa8b732 4142
367fd790
SC
4143 r = RET_PF_RETRY;
4144 spin_lock(&vcpu->kvm->mmu_lock);
4145 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4146 goto out_unlock;
7bd7ded6
SC
4147 r = make_mmu_pages_available(vcpu);
4148 if (r)
367fd790 4149 goto out_unlock;
83f06fa7 4150 r = __direct_map(vcpu, gpa, write, map_writable, max_level, pfn,
4cd071d1 4151 prefault, is_tdp && lpage_disallowed);
0f90e1c1 4152
367fd790
SC
4153out_unlock:
4154 spin_unlock(&vcpu->kvm->mmu_lock);
4155 kvm_release_pfn_clean(pfn);
4156 return r;
6aa8b732
AK
4157}
4158
0f90e1c1
SC
4159static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4160 u32 error_code, bool prefault)
4161{
4162 pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4163
4164 /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4165 return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
3bae0459 4166 PG_LEVEL_2M, false);
0f90e1c1
SC
4167}
4168
1261bfa3 4169int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
d0006530 4170 u64 fault_address, char *insn, int insn_len)
1261bfa3
WL
4171{
4172 int r = 1;
9ce372b3 4173 u32 flags = vcpu->arch.apf.host_apf_flags;
1261bfa3 4174
736c291c
SC
4175#ifndef CONFIG_X86_64
4176 /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4177 if (WARN_ON_ONCE(fault_address >> 32))
4178 return -EFAULT;
4179#endif
4180
c595ceee 4181 vcpu->arch.l1tf_flush_l1d = true;
9ce372b3 4182 if (!flags) {
1261bfa3
WL
4183 trace_kvm_page_fault(fault_address, error_code);
4184
d0006530 4185 if (kvm_event_needs_reinjection(vcpu))
1261bfa3
WL
4186 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4187 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4188 insn_len);
9ce372b3 4189 } else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
68fd66f1 4190 vcpu->arch.apf.host_apf_flags = 0;
1261bfa3 4191 local_irq_disable();
6bca69ad 4192 kvm_async_pf_task_wait_schedule(fault_address);
1261bfa3 4193 local_irq_enable();
9ce372b3
VK
4194 } else {
4195 WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
1261bfa3 4196 }
9ce372b3 4197
1261bfa3
WL
4198 return r;
4199}
4200EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4201
7a02674d
SC
4202int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4203 bool prefault)
fb72d167 4204{
cb9b88c6 4205 int max_level;
fb72d167 4206
e662ec3e 4207 for (max_level = KVM_MAX_HUGEPAGE_LEVEL;
3bae0459 4208 max_level > PG_LEVEL_4K;
cb9b88c6
SC
4209 max_level--) {
4210 int page_num = KVM_PAGES_PER_HPAGE(max_level);
0f90e1c1 4211 gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
ce88decf 4212
cb9b88c6
SC
4213 if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4214 break;
fd136902 4215 }
852e3c19 4216
0f90e1c1
SC
4217 return direct_page_fault(vcpu, gpa, error_code, prefault,
4218 max_level, true);
fb72d167
JR
4219}
4220
8a3c1a33
PB
4221static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4222 struct kvm_mmu *context)
6aa8b732 4223{
6aa8b732 4224 context->page_fault = nonpaging_page_fault;
6aa8b732 4225 context->gva_to_gpa = nonpaging_gva_to_gpa;
e8bc217a 4226 context->sync_page = nonpaging_sync_page;
5efac074 4227 context->invlpg = NULL;
0f53b5b1 4228 context->update_pte = nonpaging_update_pte;
cea0f0e7 4229 context->root_level = 0;
6aa8b732 4230 context->shadow_root_level = PT32E_ROOT_LEVEL;
c5a78f2b 4231 context->direct_map = true;
2d48a985 4232 context->nx = false;
6aa8b732
AK
4233}
4234
be01e8e2 4235static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
0be44352
SC
4236 union kvm_mmu_page_role role)
4237{
be01e8e2 4238 return (role.direct || pgd == root->pgd) &&
e47c4aee
SC
4239 VALID_PAGE(root->hpa) && to_shadow_page(root->hpa) &&
4240 role.word == to_shadow_page(root->hpa)->role.word;
0be44352
SC
4241}
4242
b94742c9 4243/*
be01e8e2 4244 * Find out if a previously cached root matching the new pgd/role is available.
b94742c9
JS
4245 * The current root is also inserted into the cache.
4246 * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4247 * returned.
4248 * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4249 * false is returned. This root should now be freed by the caller.
4250 */
be01e8e2 4251static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_pgd,
b94742c9
JS
4252 union kvm_mmu_page_role new_role)
4253{
4254 uint i;
4255 struct kvm_mmu_root_info root;
44dd3ffa 4256 struct kvm_mmu *mmu = vcpu->arch.mmu;
b94742c9 4257
be01e8e2 4258 root.pgd = mmu->root_pgd;
b94742c9
JS
4259 root.hpa = mmu->root_hpa;
4260
be01e8e2 4261 if (is_root_usable(&root, new_pgd, new_role))
0be44352
SC
4262 return true;
4263
b94742c9
JS
4264 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4265 swap(root, mmu->prev_roots[i]);
4266
be01e8e2 4267 if (is_root_usable(&root, new_pgd, new_role))
b94742c9
JS
4268 break;
4269 }
4270
4271 mmu->root_hpa = root.hpa;
be01e8e2 4272 mmu->root_pgd = root.pgd;
b94742c9
JS
4273
4274 return i < KVM_MMU_NUM_PREV_ROOTS;
4275}
4276
be01e8e2 4277static bool fast_pgd_switch(struct kvm_vcpu *vcpu, gpa_t new_pgd,
b869855b 4278 union kvm_mmu_page_role new_role)
6aa8b732 4279{
44dd3ffa 4280 struct kvm_mmu *mmu = vcpu->arch.mmu;
7c390d35
JS
4281
4282 /*
4283 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4284 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4285 * later if necessary.
4286 */
4287 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
b869855b 4288 mmu->root_level >= PT64_ROOT_4LEVEL)
fe9304d3 4289 return cached_root_available(vcpu, new_pgd, new_role);
7c390d35
JS
4290
4291 return false;
6aa8b732
AK
4292}
4293
be01e8e2 4294static void __kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd,
ade61e28 4295 union kvm_mmu_page_role new_role,
4a632ac6 4296 bool skip_tlb_flush, bool skip_mmu_sync)
6aa8b732 4297{
be01e8e2 4298 if (!fast_pgd_switch(vcpu, new_pgd, new_role)) {
b869855b
SC
4299 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, KVM_MMU_ROOT_CURRENT);
4300 return;
4301 }
4302
4303 /*
4304 * It's possible that the cached previous root page is obsolete because
4305 * of a change in the MMU generation number. However, changing the
4306 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
4307 * free the root set here and allocate a new one.
4308 */
4309 kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4310
71fe7013 4311 if (!skip_mmu_sync || force_flush_and_sync_on_reuse)
b869855b 4312 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
71fe7013 4313 if (!skip_tlb_flush || force_flush_and_sync_on_reuse)
b869855b 4314 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
b869855b
SC
4315
4316 /*
4317 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4318 * switching to a new CR3, that GVA->GPA mapping may no longer be
4319 * valid. So clear any cached MMIO info even when we don't need to sync
4320 * the shadow page tables.
4321 */
4322 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4323
e47c4aee 4324 __clear_sp_write_flooding_count(to_shadow_page(vcpu->arch.mmu->root_hpa));
6aa8b732
AK
4325}
4326
be01e8e2 4327void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd, bool skip_tlb_flush,
4a632ac6 4328 bool skip_mmu_sync)
0aab33e4 4329{
be01e8e2 4330 __kvm_mmu_new_pgd(vcpu, new_pgd, kvm_mmu_calc_root_page_role(vcpu),
4a632ac6 4331 skip_tlb_flush, skip_mmu_sync);
0aab33e4 4332}
be01e8e2 4333EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
0aab33e4 4334
5777ed34
JR
4335static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4336{
9f8fe504 4337 return kvm_read_cr3(vcpu);
5777ed34
JR
4338}
4339
54bf36aa 4340static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
0a2b64c5 4341 unsigned int access, int *nr_present)
ce88decf
XG
4342{
4343 if (unlikely(is_mmio_spte(*sptep))) {
4344 if (gfn != get_mmio_spte_gfn(*sptep)) {
4345 mmu_spte_clear_no_track(sptep);
4346 return true;
4347 }
4348
4349 (*nr_present)++;
54bf36aa 4350 mark_mmio_spte(vcpu, sptep, gfn, access);
ce88decf
XG
4351 return true;
4352 }
4353
4354 return false;
4355}
4356
6bb69c9b
PB
4357static inline bool is_last_gpte(struct kvm_mmu *mmu,
4358 unsigned level, unsigned gpte)
6fd01b71 4359{
6bb69c9b
PB
4360 /*
4361 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4362 * If it is clear, there are no large pages at this level, so clear
4363 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4364 */
4365 gpte &= level - mmu->last_nonleaf_level;
4366
829ee279 4367 /*
3bae0459
SC
4368 * PG_LEVEL_4K always terminates. The RHS has bit 7 set
4369 * iff level <= PG_LEVEL_4K, which for our purpose means
4370 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
829ee279 4371 */
3bae0459 4372 gpte |= level - PG_LEVEL_4K - 1;
829ee279 4373
6bb69c9b 4374 return gpte & PT_PAGE_SIZE_MASK;
6fd01b71
AK
4375}
4376
37406aaa
NHE
4377#define PTTYPE_EPT 18 /* arbitrary */
4378#define PTTYPE PTTYPE_EPT
4379#include "paging_tmpl.h"
4380#undef PTTYPE
4381
6aa8b732
AK
4382#define PTTYPE 64
4383#include "paging_tmpl.h"
4384#undef PTTYPE
4385
4386#define PTTYPE 32
4387#include "paging_tmpl.h"
4388#undef PTTYPE
4389
6dc98b86
XG
4390static void
4391__reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4392 struct rsvd_bits_validate *rsvd_check,
4393 int maxphyaddr, int level, bool nx, bool gbpages,
6fec2144 4394 bool pse, bool amd)
82725b20 4395{
82725b20 4396 u64 exb_bit_rsvd = 0;
5f7dde7b 4397 u64 gbpages_bit_rsvd = 0;
a0c0feb5 4398 u64 nonleaf_bit8_rsvd = 0;
82725b20 4399
a0a64f50 4400 rsvd_check->bad_mt_xwr = 0;
25d92081 4401
6dc98b86 4402 if (!nx)
82725b20 4403 exb_bit_rsvd = rsvd_bits(63, 63);
6dc98b86 4404 if (!gbpages)
5f7dde7b 4405 gbpages_bit_rsvd = rsvd_bits(7, 7);
a0c0feb5
PB
4406
4407 /*
4408 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4409 * leaf entries) on AMD CPUs only.
4410 */
6fec2144 4411 if (amd)
a0c0feb5
PB
4412 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4413
6dc98b86 4414 switch (level) {
82725b20
DE
4415 case PT32_ROOT_LEVEL:
4416 /* no rsvd bits for 2 level 4K page table entries */
a0a64f50
XG
4417 rsvd_check->rsvd_bits_mask[0][1] = 0;
4418 rsvd_check->rsvd_bits_mask[0][0] = 0;
4419 rsvd_check->rsvd_bits_mask[1][0] =
4420 rsvd_check->rsvd_bits_mask[0][0];
f815bce8 4421
6dc98b86 4422 if (!pse) {
a0a64f50 4423 rsvd_check->rsvd_bits_mask[1][1] = 0;
f815bce8
XG
4424 break;
4425 }
4426
82725b20
DE
4427 if (is_cpuid_PSE36())
4428 /* 36bits PSE 4MB page */
a0a64f50 4429 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
82725b20
DE
4430 else
4431 /* 32 bits PSE 4MB page */
a0a64f50 4432 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
82725b20
DE
4433 break;
4434 case PT32E_ROOT_LEVEL:
a0a64f50 4435 rsvd_check->rsvd_bits_mask[0][2] =
20c466b5 4436 rsvd_bits(maxphyaddr, 63) |
cd9ae5fe 4437 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
a0a64f50 4438 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4c26b4cd 4439 rsvd_bits(maxphyaddr, 62); /* PDE */
a0a64f50 4440 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
82725b20 4441 rsvd_bits(maxphyaddr, 62); /* PTE */
a0a64f50 4442 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
82725b20
DE
4443 rsvd_bits(maxphyaddr, 62) |
4444 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
4445 rsvd_check->rsvd_bits_mask[1][0] =
4446 rsvd_check->rsvd_bits_mask[0][0];
82725b20 4447 break;
855feb67
YZ
4448 case PT64_ROOT_5LEVEL:
4449 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4450 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4451 rsvd_bits(maxphyaddr, 51);
4452 rsvd_check->rsvd_bits_mask[1][4] =
4453 rsvd_check->rsvd_bits_mask[0][4];
df561f66 4454 fallthrough;
2a7266a8 4455 case PT64_ROOT_4LEVEL:
a0a64f50
XG
4456 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4457 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4c26b4cd 4458 rsvd_bits(maxphyaddr, 51);
a0a64f50 4459 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
5ecad245 4460 gbpages_bit_rsvd |
82725b20 4461 rsvd_bits(maxphyaddr, 51);
a0a64f50
XG
4462 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4463 rsvd_bits(maxphyaddr, 51);
4464 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4465 rsvd_bits(maxphyaddr, 51);
4466 rsvd_check->rsvd_bits_mask[1][3] =
4467 rsvd_check->rsvd_bits_mask[0][3];
4468 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
5f7dde7b 4469 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
e04da980 4470 rsvd_bits(13, 29);
a0a64f50 4471 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4c26b4cd
SY
4472 rsvd_bits(maxphyaddr, 51) |
4473 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
4474 rsvd_check->rsvd_bits_mask[1][0] =
4475 rsvd_check->rsvd_bits_mask[0][0];
82725b20
DE
4476 break;
4477 }
4478}
4479
6dc98b86
XG
4480static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4481 struct kvm_mmu *context)
4482{
4483 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4484 cpuid_maxphyaddr(vcpu), context->root_level,
d6321d49
RK
4485 context->nx,
4486 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
23493d0a
SC
4487 is_pse(vcpu),
4488 guest_cpuid_is_amd_or_hygon(vcpu));
6dc98b86
XG
4489}
4490
81b8eebb
XG
4491static void
4492__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4493 int maxphyaddr, bool execonly)
25d92081 4494{
951f9fd7 4495 u64 bad_mt_xwr;
25d92081 4496
855feb67
YZ
4497 rsvd_check->rsvd_bits_mask[0][4] =
4498 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
a0a64f50 4499 rsvd_check->rsvd_bits_mask[0][3] =
25d92081 4500 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
a0a64f50 4501 rsvd_check->rsvd_bits_mask[0][2] =
25d92081 4502 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
a0a64f50 4503 rsvd_check->rsvd_bits_mask[0][1] =
25d92081 4504 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
a0a64f50 4505 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
25d92081
YZ
4506
4507 /* large page */
855feb67 4508 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
a0a64f50
XG
4509 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4510 rsvd_check->rsvd_bits_mask[1][2] =
25d92081 4511 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
a0a64f50 4512 rsvd_check->rsvd_bits_mask[1][1] =
25d92081 4513 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
a0a64f50 4514 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
25d92081 4515
951f9fd7
PB
4516 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4517 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4518 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4519 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4520 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4521 if (!execonly) {
4522 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4523 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
25d92081 4524 }
951f9fd7 4525 rsvd_check->bad_mt_xwr = bad_mt_xwr;
25d92081
YZ
4526}
4527
81b8eebb
XG
4528static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4529 struct kvm_mmu *context, bool execonly)
4530{
4531 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4532 cpuid_maxphyaddr(vcpu), execonly);
4533}
4534
c258b62b
XG
4535/*
4536 * the page table on host is the shadow page table for the page
4537 * table in guest or amd nested guest, its mmu features completely
4538 * follow the features in guest.
4539 */
4540void
4541reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4542{
36d9594d
VK
4543 bool uses_nx = context->nx ||
4544 context->mmu_role.base.smep_andnot_wp;
ea2800dd
BS
4545 struct rsvd_bits_validate *shadow_zero_check;
4546 int i;
5f0b8199 4547
6fec2144
PB
4548 /*
4549 * Passing "true" to the last argument is okay; it adds a check
4550 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4551 */
ea2800dd
BS
4552 shadow_zero_check = &context->shadow_zero_check;
4553 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
f3ecb59d 4554 shadow_phys_bits,
5f0b8199 4555 context->shadow_root_level, uses_nx,
d6321d49
RK
4556 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4557 is_pse(vcpu), true);
ea2800dd
BS
4558
4559 if (!shadow_me_mask)
4560 return;
4561
4562 for (i = context->shadow_root_level; --i >= 0;) {
4563 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4564 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4565 }
4566
c258b62b
XG
4567}
4568EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4569
6fec2144
PB
4570static inline bool boot_cpu_is_amd(void)
4571{
4572 WARN_ON_ONCE(!tdp_enabled);
4573 return shadow_x_mask == 0;
4574}
4575
c258b62b
XG
4576/*
4577 * the direct page table on host, use as much mmu features as
4578 * possible, however, kvm currently does not do execution-protection.
4579 */
4580static void
4581reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4582 struct kvm_mmu *context)
4583{
ea2800dd
BS
4584 struct rsvd_bits_validate *shadow_zero_check;
4585 int i;
4586
4587 shadow_zero_check = &context->shadow_zero_check;
4588
6fec2144 4589 if (boot_cpu_is_amd())
ea2800dd 4590 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
f3ecb59d 4591 shadow_phys_bits,
c258b62b 4592 context->shadow_root_level, false,
b8291adc
BP
4593 boot_cpu_has(X86_FEATURE_GBPAGES),
4594 true, true);
c258b62b 4595 else
ea2800dd 4596 __reset_rsvds_bits_mask_ept(shadow_zero_check,
f3ecb59d 4597 shadow_phys_bits,
c258b62b
XG
4598 false);
4599
ea2800dd
BS
4600 if (!shadow_me_mask)
4601 return;
4602
4603 for (i = context->shadow_root_level; --i >= 0;) {
4604 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4605 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4606 }
c258b62b
XG
4607}
4608
4609/*
4610 * as the comments in reset_shadow_zero_bits_mask() except it
4611 * is the shadow page table for intel nested guest.
4612 */
4613static void
4614reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4615 struct kvm_mmu *context, bool execonly)
4616{
4617 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
f3ecb59d 4618 shadow_phys_bits, execonly);
c258b62b
XG
4619}
4620
09f037aa
PB
4621#define BYTE_MASK(access) \
4622 ((1 & (access) ? 2 : 0) | \
4623 (2 & (access) ? 4 : 0) | \
4624 (3 & (access) ? 8 : 0) | \
4625 (4 & (access) ? 16 : 0) | \
4626 (5 & (access) ? 32 : 0) | \
4627 (6 & (access) ? 64 : 0) | \
4628 (7 & (access) ? 128 : 0))
4629
4630
edc90b7d
XG
4631static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4632 struct kvm_mmu *mmu, bool ept)
97d64b78 4633{
09f037aa
PB
4634 unsigned byte;
4635
4636 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4637 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4638 const u8 u = BYTE_MASK(ACC_USER_MASK);
4639
4640 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4641 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4642 bool cr0_wp = is_write_protection(vcpu);
97d64b78 4643
97d64b78 4644 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
09f037aa
PB
4645 unsigned pfec = byte << 1;
4646
97ec8c06 4647 /*
09f037aa
PB
4648 * Each "*f" variable has a 1 bit for each UWX value
4649 * that causes a fault with the given PFEC.
97ec8c06 4650 */
97d64b78 4651
09f037aa 4652 /* Faults from writes to non-writable pages */
a6a6d3b1 4653 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
09f037aa 4654 /* Faults from user mode accesses to supervisor pages */
a6a6d3b1 4655 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
09f037aa 4656 /* Faults from fetches of non-executable pages*/
a6a6d3b1 4657 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
09f037aa
PB
4658 /* Faults from kernel mode fetches of user pages */
4659 u8 smepf = 0;
4660 /* Faults from kernel mode accesses of user pages */
4661 u8 smapf = 0;
4662
4663 if (!ept) {
4664 /* Faults from kernel mode accesses to user pages */
4665 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4666
4667 /* Not really needed: !nx will cause pte.nx to fault */
4668 if (!mmu->nx)
4669 ff = 0;
4670
4671 /* Allow supervisor writes if !cr0.wp */
4672 if (!cr0_wp)
4673 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4674
4675 /* Disallow supervisor fetches of user code if cr4.smep */
4676 if (cr4_smep)
4677 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4678
4679 /*
4680 * SMAP:kernel-mode data accesses from user-mode
4681 * mappings should fault. A fault is considered
4682 * as a SMAP violation if all of the following
39337ad1 4683 * conditions are true:
09f037aa
PB
4684 * - X86_CR4_SMAP is set in CR4
4685 * - A user page is accessed
4686 * - The access is not a fetch
4687 * - Page fault in kernel mode
4688 * - if CPL = 3 or X86_EFLAGS_AC is clear
4689 *
4690 * Here, we cover the first three conditions.
4691 * The fourth is computed dynamically in permission_fault();
4692 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4693 * *not* subject to SMAP restrictions.
4694 */
4695 if (cr4_smap)
4696 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
97d64b78 4697 }
09f037aa
PB
4698
4699 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
97d64b78
AK
4700 }
4701}
4702
2d344105
HH
4703/*
4704* PKU is an additional mechanism by which the paging controls access to
4705* user-mode addresses based on the value in the PKRU register. Protection
4706* key violations are reported through a bit in the page fault error code.
4707* Unlike other bits of the error code, the PK bit is not known at the
4708* call site of e.g. gva_to_gpa; it must be computed directly in
4709* permission_fault based on two bits of PKRU, on some machine state (CR4,
4710* CR0, EFER, CPL), and on other bits of the error code and the page tables.
4711*
4712* In particular the following conditions come from the error code, the
4713* page tables and the machine state:
4714* - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4715* - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4716* - PK is always zero if U=0 in the page tables
4717* - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4718*
4719* The PKRU bitmask caches the result of these four conditions. The error
4720* code (minus the P bit) and the page table's U bit form an index into the
4721* PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4722* with the two bits of the PKRU register corresponding to the protection key.
4723* For the first three conditions above the bits will be 00, thus masking
4724* away both AD and WD. For all reads or if the last condition holds, WD
4725* only will be masked away.
4726*/
4727static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4728 bool ept)
4729{
4730 unsigned bit;
4731 bool wp;
4732
4733 if (ept) {
4734 mmu->pkru_mask = 0;
4735 return;
4736 }
4737
4738 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4739 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4740 mmu->pkru_mask = 0;
4741 return;
4742 }
4743
4744 wp = is_write_protection(vcpu);
4745
4746 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4747 unsigned pfec, pkey_bits;
4748 bool check_pkey, check_write, ff, uf, wf, pte_user;
4749
4750 pfec = bit << 1;
4751 ff = pfec & PFERR_FETCH_MASK;
4752 uf = pfec & PFERR_USER_MASK;
4753 wf = pfec & PFERR_WRITE_MASK;
4754
4755 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4756 pte_user = pfec & PFERR_RSVD_MASK;
4757
4758 /*
4759 * Only need to check the access which is not an
4760 * instruction fetch and is to a user page.
4761 */
4762 check_pkey = (!ff && pte_user);
4763 /*
4764 * write access is controlled by PKRU if it is a
4765 * user access or CR0.WP = 1.
4766 */
4767 check_write = check_pkey && wf && (uf || wp);
4768
4769 /* PKRU.AD stops both read and write access. */
4770 pkey_bits = !!check_pkey;
4771 /* PKRU.WD stops write access. */
4772 pkey_bits |= (!!check_write) << 1;
4773
4774 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4775 }
4776}
4777
6bb69c9b 4778static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6fd01b71 4779{
6bb69c9b
PB
4780 unsigned root_level = mmu->root_level;
4781
4782 mmu->last_nonleaf_level = root_level;
4783 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4784 mmu->last_nonleaf_level++;
6fd01b71
AK
4785}
4786
8a3c1a33
PB
4787static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4788 struct kvm_mmu *context,
4789 int level)
6aa8b732 4790{
2d48a985 4791 context->nx = is_nx(vcpu);
4d6931c3 4792 context->root_level = level;
2d48a985 4793
4d6931c3 4794 reset_rsvds_bits_mask(vcpu, context);
25d92081 4795 update_permission_bitmask(vcpu, context, false);
2d344105 4796 update_pkru_bitmask(vcpu, context, false);
6bb69c9b 4797 update_last_nonleaf_level(vcpu, context);
6aa8b732 4798
fa4a2c08 4799 MMU_WARN_ON(!is_pae(vcpu));
6aa8b732 4800 context->page_fault = paging64_page_fault;
6aa8b732 4801 context->gva_to_gpa = paging64_gva_to_gpa;
e8bc217a 4802 context->sync_page = paging64_sync_page;
a7052897 4803 context->invlpg = paging64_invlpg;
0f53b5b1 4804 context->update_pte = paging64_update_pte;
17ac10ad 4805 context->shadow_root_level = level;
c5a78f2b 4806 context->direct_map = false;
6aa8b732
AK
4807}
4808
8a3c1a33
PB
4809static void paging64_init_context(struct kvm_vcpu *vcpu,
4810 struct kvm_mmu *context)
17ac10ad 4811{
855feb67
YZ
4812 int root_level = is_la57_mode(vcpu) ?
4813 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4814
4815 paging64_init_context_common(vcpu, context, root_level);
17ac10ad
AK
4816}
4817
8a3c1a33
PB
4818static void paging32_init_context(struct kvm_vcpu *vcpu,
4819 struct kvm_mmu *context)
6aa8b732 4820{
2d48a985 4821 context->nx = false;
4d6931c3 4822 context->root_level = PT32_ROOT_LEVEL;
2d48a985 4823
4d6931c3 4824 reset_rsvds_bits_mask(vcpu, context);
25d92081 4825 update_permission_bitmask(vcpu, context, false);
2d344105 4826 update_pkru_bitmask(vcpu, context, false);
6bb69c9b 4827 update_last_nonleaf_level(vcpu, context);
6aa8b732 4828
6aa8b732 4829 context->page_fault = paging32_page_fault;
6aa8b732 4830 context->gva_to_gpa = paging32_gva_to_gpa;
e8bc217a 4831 context->sync_page = paging32_sync_page;
a7052897 4832 context->invlpg = paging32_invlpg;
0f53b5b1 4833 context->update_pte = paging32_update_pte;
6aa8b732 4834 context->shadow_root_level = PT32E_ROOT_LEVEL;
c5a78f2b 4835 context->direct_map = false;
6aa8b732
AK
4836}
4837
8a3c1a33
PB
4838static void paging32E_init_context(struct kvm_vcpu *vcpu,
4839 struct kvm_mmu *context)
6aa8b732 4840{
8a3c1a33 4841 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
6aa8b732
AK
4842}
4843
a336282d
VK
4844static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4845{
4846 union kvm_mmu_extended_role ext = {0};
4847
7dcd5755 4848 ext.cr0_pg = !!is_paging(vcpu);
0699c64a 4849 ext.cr4_pae = !!is_pae(vcpu);
a336282d
VK
4850 ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4851 ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4852 ext.cr4_pse = !!is_pse(vcpu);
4853 ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
de3ccd26 4854 ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
a336282d
VK
4855
4856 ext.valid = 1;
4857
4858 return ext;
4859}
4860
7dcd5755
VK
4861static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4862 bool base_only)
4863{
4864 union kvm_mmu_role role = {0};
4865
4866 role.base.access = ACC_ALL;
4867 role.base.nxe = !!is_nx(vcpu);
7dcd5755
VK
4868 role.base.cr0_wp = is_write_protection(vcpu);
4869 role.base.smm = is_smm(vcpu);
4870 role.base.guest_mode = is_guest_mode(vcpu);
4871
4872 if (base_only)
4873 return role;
4874
4875 role.ext = kvm_calc_mmu_role_ext(vcpu);
4876
4877 return role;
4878}
4879
d468d94b
SC
4880static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4881{
4882 /* Use 5-level TDP if and only if it's useful/necessary. */
83013059 4883 if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
d468d94b
SC
4884 return 4;
4885
83013059 4886 return max_tdp_level;
d468d94b
SC
4887}
4888
7dcd5755
VK
4889static union kvm_mmu_role
4890kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
9fa72119 4891{
7dcd5755 4892 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
9fa72119 4893
7dcd5755 4894 role.base.ad_disabled = (shadow_accessed_mask == 0);
d468d94b 4895 role.base.level = kvm_mmu_get_tdp_level(vcpu);
7dcd5755 4896 role.base.direct = true;
47c42e6b 4897 role.base.gpte_is_8_bytes = true;
9fa72119
JS
4898
4899 return role;
4900}
4901
8a3c1a33 4902static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
fb72d167 4903{
8c008659 4904 struct kvm_mmu *context = &vcpu->arch.root_mmu;
7dcd5755
VK
4905 union kvm_mmu_role new_role =
4906 kvm_calc_tdp_mmu_root_page_role(vcpu, false);
fb72d167 4907
7dcd5755
VK
4908 if (new_role.as_u64 == context->mmu_role.as_u64)
4909 return;
4910
4911 context->mmu_role.as_u64 = new_role.as_u64;
7a02674d 4912 context->page_fault = kvm_tdp_page_fault;
e8bc217a 4913 context->sync_page = nonpaging_sync_page;
5efac074 4914 context->invlpg = NULL;
0f53b5b1 4915 context->update_pte = nonpaging_update_pte;
d468d94b 4916 context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
c5a78f2b 4917 context->direct_map = true;
d8dd54e0 4918 context->get_guest_pgd = get_cr3;
e4e517b4 4919 context->get_pdptr = kvm_pdptr_read;
cb659db8 4920 context->inject_page_fault = kvm_inject_page_fault;
fb72d167
JR
4921
4922 if (!is_paging(vcpu)) {
2d48a985 4923 context->nx = false;
fb72d167
JR
4924 context->gva_to_gpa = nonpaging_gva_to_gpa;
4925 context->root_level = 0;
4926 } else if (is_long_mode(vcpu)) {
2d48a985 4927 context->nx = is_nx(vcpu);
855feb67
YZ
4928 context->root_level = is_la57_mode(vcpu) ?
4929 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4d6931c3
DB
4930 reset_rsvds_bits_mask(vcpu, context);
4931 context->gva_to_gpa = paging64_gva_to_gpa;
fb72d167 4932 } else if (is_pae(vcpu)) {
2d48a985 4933 context->nx = is_nx(vcpu);
fb72d167 4934 context->root_level = PT32E_ROOT_LEVEL;
4d6931c3
DB
4935 reset_rsvds_bits_mask(vcpu, context);
4936 context->gva_to_gpa = paging64_gva_to_gpa;
fb72d167 4937 } else {
2d48a985 4938 context->nx = false;
fb72d167 4939 context->root_level = PT32_ROOT_LEVEL;
4d6931c3
DB
4940 reset_rsvds_bits_mask(vcpu, context);
4941 context->gva_to_gpa = paging32_gva_to_gpa;
fb72d167
JR
4942 }
4943
25d92081 4944 update_permission_bitmask(vcpu, context, false);
2d344105 4945 update_pkru_bitmask(vcpu, context, false);
6bb69c9b 4946 update_last_nonleaf_level(vcpu, context);
c258b62b 4947 reset_tdp_shadow_zero_bits_mask(vcpu, context);
fb72d167
JR
4948}
4949
7dcd5755 4950static union kvm_mmu_role
59505b55 4951kvm_calc_shadow_root_page_role_common(struct kvm_vcpu *vcpu, bool base_only)
7dcd5755
VK
4952{
4953 union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4954
4955 role.base.smep_andnot_wp = role.ext.cr4_smep &&
4956 !is_write_protection(vcpu);
4957 role.base.smap_andnot_wp = role.ext.cr4_smap &&
4958 !is_write_protection(vcpu);
47c42e6b 4959 role.base.gpte_is_8_bytes = !!is_pae(vcpu);
9fa72119 4960
59505b55
SC
4961 return role;
4962}
4963
4964static union kvm_mmu_role
4965kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4966{
4967 union kvm_mmu_role role =
4968 kvm_calc_shadow_root_page_role_common(vcpu, base_only);
4969
4970 role.base.direct = !is_paging(vcpu);
4971
9fa72119 4972 if (!is_long_mode(vcpu))
7dcd5755 4973 role.base.level = PT32E_ROOT_LEVEL;
9fa72119 4974 else if (is_la57_mode(vcpu))
7dcd5755 4975 role.base.level = PT64_ROOT_5LEVEL;
9fa72119 4976 else
7dcd5755 4977 role.base.level = PT64_ROOT_4LEVEL;
9fa72119
JS
4978
4979 return role;
4980}
4981
8c008659
PB
4982static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
4983 u32 cr0, u32 cr4, u32 efer,
4984 union kvm_mmu_role new_role)
9fa72119 4985{
929d1cfa 4986 if (!(cr0 & X86_CR0_PG))
8a3c1a33 4987 nonpaging_init_context(vcpu, context);
929d1cfa 4988 else if (efer & EFER_LMA)
8a3c1a33 4989 paging64_init_context(vcpu, context);
929d1cfa 4990 else if (cr4 & X86_CR4_PAE)
8a3c1a33 4991 paging32E_init_context(vcpu, context);
6aa8b732 4992 else
8a3c1a33 4993 paging32_init_context(vcpu, context);
a770f6f2 4994
7dcd5755 4995 context->mmu_role.as_u64 = new_role.as_u64;
c258b62b 4996 reset_shadow_zero_bits_mask(vcpu, context);
52fde8df 4997}
0f04a2ac
VK
4998
4999static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer)
5000{
8c008659 5001 struct kvm_mmu *context = &vcpu->arch.root_mmu;
0f04a2ac
VK
5002 union kvm_mmu_role new_role =
5003 kvm_calc_shadow_mmu_root_page_role(vcpu, false);
5004
5005 if (new_role.as_u64 != context->mmu_role.as_u64)
8c008659 5006 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
0f04a2ac
VK
5007}
5008
59505b55
SC
5009static union kvm_mmu_role
5010kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu)
5011{
5012 union kvm_mmu_role role =
5013 kvm_calc_shadow_root_page_role_common(vcpu, false);
5014
5015 role.base.direct = false;
d468d94b 5016 role.base.level = kvm_mmu_get_tdp_level(vcpu);
59505b55
SC
5017
5018 return role;
5019}
5020
0f04a2ac
VK
5021void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer,
5022 gpa_t nested_cr3)
5023{
8c008659 5024 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
59505b55 5025 union kvm_mmu_role new_role = kvm_calc_shadow_npt_root_page_role(vcpu);
0f04a2ac 5026
096586fd
SC
5027 context->shadow_root_level = new_role.base.level;
5028
a506fdd2
VK
5029 __kvm_mmu_new_pgd(vcpu, nested_cr3, new_role.base, false, false);
5030
0f04a2ac 5031 if (new_role.as_u64 != context->mmu_role.as_u64)
8c008659 5032 shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
0f04a2ac
VK
5033}
5034EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
52fde8df 5035
a336282d
VK
5036static union kvm_mmu_role
5037kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
bb1fcc70 5038 bool execonly, u8 level)
9fa72119 5039{
552c69b1 5040 union kvm_mmu_role role = {0};
14c07ad8 5041
47c42e6b
SC
5042 /* SMM flag is inherited from root_mmu */
5043 role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
9fa72119 5044
bb1fcc70 5045 role.base.level = level;
47c42e6b 5046 role.base.gpte_is_8_bytes = true;
a336282d
VK
5047 role.base.direct = false;
5048 role.base.ad_disabled = !accessed_dirty;
5049 role.base.guest_mode = true;
5050 role.base.access = ACC_ALL;
9fa72119 5051
47c42e6b
SC
5052 /*
5053 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5054 * SMAP variation to denote shadow EPT entries.
5055 */
5056 role.base.cr0_wp = true;
5057 role.base.smap_andnot_wp = true;
5058
552c69b1 5059 role.ext = kvm_calc_mmu_role_ext(vcpu);
a336282d 5060 role.ext.execonly = execonly;
9fa72119
JS
5061
5062 return role;
5063}
5064
ae1e2d10 5065void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
50c28f21 5066 bool accessed_dirty, gpa_t new_eptp)
155a97a3 5067{
8c008659 5068 struct kvm_mmu *context = &vcpu->arch.guest_mmu;
bb1fcc70 5069 u8 level = vmx_eptp_page_walk_level(new_eptp);
a336282d
VK
5070 union kvm_mmu_role new_role =
5071 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
bb1fcc70 5072 execonly, level);
a336282d 5073
be01e8e2 5074 __kvm_mmu_new_pgd(vcpu, new_eptp, new_role.base, true, true);
a336282d 5075
a336282d
VK
5076 if (new_role.as_u64 == context->mmu_role.as_u64)
5077 return;
ad896af0 5078
bb1fcc70 5079 context->shadow_root_level = level;
155a97a3
NHE
5080
5081 context->nx = true;
ae1e2d10 5082 context->ept_ad = accessed_dirty;
155a97a3
NHE
5083 context->page_fault = ept_page_fault;
5084 context->gva_to_gpa = ept_gva_to_gpa;
5085 context->sync_page = ept_sync_page;
5086 context->invlpg = ept_invlpg;
5087 context->update_pte = ept_update_pte;
bb1fcc70 5088 context->root_level = level;
155a97a3 5089 context->direct_map = false;
a336282d 5090 context->mmu_role.as_u64 = new_role.as_u64;
3dc773e7 5091
155a97a3 5092 update_permission_bitmask(vcpu, context, true);
2d344105 5093 update_pkru_bitmask(vcpu, context, true);
fd19d3b4 5094 update_last_nonleaf_level(vcpu, context);
155a97a3 5095 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
c258b62b 5096 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
155a97a3
NHE
5097}
5098EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5099
8a3c1a33 5100static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
52fde8df 5101{
8c008659 5102 struct kvm_mmu *context = &vcpu->arch.root_mmu;
ad896af0 5103
929d1cfa
PB
5104 kvm_init_shadow_mmu(vcpu,
5105 kvm_read_cr0_bits(vcpu, X86_CR0_PG),
5106 kvm_read_cr4_bits(vcpu, X86_CR4_PAE),
5107 vcpu->arch.efer);
5108
d8dd54e0 5109 context->get_guest_pgd = get_cr3;
ad896af0
PB
5110 context->get_pdptr = kvm_pdptr_read;
5111 context->inject_page_fault = kvm_inject_page_fault;
6aa8b732
AK
5112}
5113
8a3c1a33 5114static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
02f59dc9 5115{
bf627a92 5116 union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
02f59dc9
JR
5117 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5118
bf627a92
VK
5119 if (new_role.as_u64 == g_context->mmu_role.as_u64)
5120 return;
5121
5122 g_context->mmu_role.as_u64 = new_role.as_u64;
d8dd54e0 5123 g_context->get_guest_pgd = get_cr3;
e4e517b4 5124 g_context->get_pdptr = kvm_pdptr_read;
02f59dc9
JR
5125 g_context->inject_page_fault = kvm_inject_page_fault;
5126
5efac074
PB
5127 /*
5128 * L2 page tables are never shadowed, so there is no need to sync
5129 * SPTEs.
5130 */
5131 g_context->invlpg = NULL;
5132
02f59dc9 5133 /*
44dd3ffa 5134 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
0af2593b
DM
5135 * L1's nested page tables (e.g. EPT12). The nested translation
5136 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5137 * L2's page tables as the first level of translation and L1's
5138 * nested page tables as the second level of translation. Basically
5139 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
02f59dc9
JR
5140 */
5141 if (!is_paging(vcpu)) {
2d48a985 5142 g_context->nx = false;
02f59dc9
JR
5143 g_context->root_level = 0;
5144 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5145 } else if (is_long_mode(vcpu)) {
2d48a985 5146 g_context->nx = is_nx(vcpu);
855feb67
YZ
5147 g_context->root_level = is_la57_mode(vcpu) ?
5148 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4d6931c3 5149 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
5150 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5151 } else if (is_pae(vcpu)) {
2d48a985 5152 g_context->nx = is_nx(vcpu);
02f59dc9 5153 g_context->root_level = PT32E_ROOT_LEVEL;
4d6931c3 5154 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
5155 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5156 } else {
2d48a985 5157 g_context->nx = false;
02f59dc9 5158 g_context->root_level = PT32_ROOT_LEVEL;
4d6931c3 5159 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
5160 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5161 }
5162
25d92081 5163 update_permission_bitmask(vcpu, g_context, false);
2d344105 5164 update_pkru_bitmask(vcpu, g_context, false);
6bb69c9b 5165 update_last_nonleaf_level(vcpu, g_context);
02f59dc9
JR
5166}
5167
1c53da3f 5168void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
fb72d167 5169{
1c53da3f 5170 if (reset_roots) {
b94742c9
JS
5171 uint i;
5172
44dd3ffa 5173 vcpu->arch.mmu->root_hpa = INVALID_PAGE;
b94742c9
JS
5174
5175 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
44dd3ffa 5176 vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
1c53da3f
JS
5177 }
5178
02f59dc9 5179 if (mmu_is_nested(vcpu))
e0c6db3e 5180 init_kvm_nested_mmu(vcpu);
02f59dc9 5181 else if (tdp_enabled)
e0c6db3e 5182 init_kvm_tdp_mmu(vcpu);
fb72d167 5183 else
e0c6db3e 5184 init_kvm_softmmu(vcpu);
fb72d167 5185}
1c53da3f 5186EXPORT_SYMBOL_GPL(kvm_init_mmu);
fb72d167 5187
9fa72119
JS
5188static union kvm_mmu_page_role
5189kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5190{
7dcd5755
VK
5191 union kvm_mmu_role role;
5192
9fa72119 5193 if (tdp_enabled)
7dcd5755 5194 role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
9fa72119 5195 else
7dcd5755
VK
5196 role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5197
5198 return role.base;
9fa72119 5199}
fb72d167 5200
8a3c1a33 5201void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
6aa8b732 5202{
95f93af4 5203 kvm_mmu_unload(vcpu);
1c53da3f 5204 kvm_init_mmu(vcpu, true);
17c3ba9d 5205}
8668a3c4 5206EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
17c3ba9d
AK
5207
5208int kvm_mmu_load(struct kvm_vcpu *vcpu)
6aa8b732 5209{
714b93da
AK
5210 int r;
5211
378f5cd6 5212 r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
17c3ba9d
AK
5213 if (r)
5214 goto out;
8986ecc0 5215 r = mmu_alloc_roots(vcpu);
e2858b4a 5216 kvm_mmu_sync_roots(vcpu);
8986ecc0
MT
5217 if (r)
5218 goto out;
727a7e27 5219 kvm_mmu_load_pgd(vcpu);
8c8560b8 5220 kvm_x86_ops.tlb_flush_current(vcpu);
714b93da
AK
5221out:
5222 return r;
6aa8b732 5223}
17c3ba9d
AK
5224EXPORT_SYMBOL_GPL(kvm_mmu_load);
5225
5226void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5227{
14c07ad8
VK
5228 kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5229 WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5230 kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5231 WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
17c3ba9d 5232}
4b16184c 5233EXPORT_SYMBOL_GPL(kvm_mmu_unload);
6aa8b732 5234
0028425f 5235static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
7c562522
XG
5236 struct kvm_mmu_page *sp, u64 *spte,
5237 const void *new)
0028425f 5238{
3bae0459 5239 if (sp->role.level != PG_LEVEL_4K) {
7e4e4056
JR
5240 ++vcpu->kvm->stat.mmu_pde_zapped;
5241 return;
30945387 5242 }
0028425f 5243
4cee5764 5244 ++vcpu->kvm->stat.mmu_pte_updated;
44dd3ffa 5245 vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
0028425f
AK
5246}
5247
79539cec
AK
5248static bool need_remote_flush(u64 old, u64 new)
5249{
5250 if (!is_shadow_present_pte(old))
5251 return false;
5252 if (!is_shadow_present_pte(new))
5253 return true;
5254 if ((old ^ new) & PT64_BASE_ADDR_MASK)
5255 return true;
53166229
GN
5256 old ^= shadow_nx_mask;
5257 new ^= shadow_nx_mask;
79539cec
AK
5258 return (old & ~new & PT64_PERM_MASK) != 0;
5259}
5260
889e5cbc 5261static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
0e0fee5c 5262 int *bytes)
da4a00f0 5263{
0e0fee5c 5264 u64 gentry = 0;
889e5cbc 5265 int r;
72016f3a 5266
72016f3a
AK
5267 /*
5268 * Assume that the pte write on a page table of the same type
49b26e26
XG
5269 * as the current vcpu paging mode since we update the sptes only
5270 * when they have the same mode.
72016f3a 5271 */
889e5cbc 5272 if (is_pae(vcpu) && *bytes == 4) {
72016f3a 5273 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
889e5cbc
XG
5274 *gpa &= ~(gpa_t)7;
5275 *bytes = 8;
08e850c6
AK
5276 }
5277
0e0fee5c
JS
5278 if (*bytes == 4 || *bytes == 8) {
5279 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5280 if (r)
5281 gentry = 0;
72016f3a
AK
5282 }
5283
889e5cbc
XG
5284 return gentry;
5285}
5286
5287/*
5288 * If we're seeing too many writes to a page, it may no longer be a page table,
5289 * or we may be forking, in which case it is better to unmap the page.
5290 */
a138fe75 5291static bool detect_write_flooding(struct kvm_mmu_page *sp)
889e5cbc 5292{
a30f47cb
XG
5293 /*
5294 * Skip write-flooding detected for the sp whose level is 1, because
5295 * it can become unsync, then the guest page is not write-protected.
5296 */
3bae0459 5297 if (sp->role.level == PG_LEVEL_4K)
a30f47cb 5298 return false;
3246af0e 5299
e5691a81
XG
5300 atomic_inc(&sp->write_flooding_count);
5301 return atomic_read(&sp->write_flooding_count) >= 3;
889e5cbc
XG
5302}
5303
5304/*
5305 * Misaligned accesses are too much trouble to fix up; also, they usually
5306 * indicate a page is not used as a page table.
5307 */
5308static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5309 int bytes)
5310{
5311 unsigned offset, pte_size, misaligned;
5312
5313 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5314 gpa, bytes, sp->role.word);
5315
5316 offset = offset_in_page(gpa);
47c42e6b 5317 pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5d9ca30e
XG
5318
5319 /*
5320 * Sometimes, the OS only writes the last one bytes to update status
5321 * bits, for example, in linux, andb instruction is used in clear_bit().
5322 */
5323 if (!(offset & (pte_size - 1)) && bytes == 1)
5324 return false;
5325
889e5cbc
XG
5326 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5327 misaligned |= bytes < 4;
5328
5329 return misaligned;
5330}
5331
5332static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5333{
5334 unsigned page_offset, quadrant;
5335 u64 *spte;
5336 int level;
5337
5338 page_offset = offset_in_page(gpa);
5339 level = sp->role.level;
5340 *nspte = 1;
47c42e6b 5341 if (!sp->role.gpte_is_8_bytes) {
889e5cbc
XG
5342 page_offset <<= 1; /* 32->64 */
5343 /*
5344 * A 32-bit pde maps 4MB while the shadow pdes map
5345 * only 2MB. So we need to double the offset again
5346 * and zap two pdes instead of one.
5347 */
5348 if (level == PT32_ROOT_LEVEL) {
5349 page_offset &= ~7; /* kill rounding error */
5350 page_offset <<= 1;
5351 *nspte = 2;
5352 }
5353 quadrant = page_offset >> PAGE_SHIFT;
5354 page_offset &= ~PAGE_MASK;
5355 if (quadrant != sp->role.quadrant)
5356 return NULL;
5357 }
5358
5359 spte = &sp->spt[page_offset / sizeof(*spte)];
5360 return spte;
5361}
5362
a102a674
SC
5363/*
5364 * Ignore various flags when determining if a SPTE can be immediately
5365 * overwritten for the current MMU.
5366 * - level: explicitly checked in mmu_pte_write_new_pte(), and will never
5367 * match the current MMU role, as MMU's level tracks the root level.
5368 * - access: updated based on the new guest PTE
5369 * - quadrant: handled by get_written_sptes()
5370 * - invalid: always false (loop only walks valid shadow pages)
5371 */
5372static const union kvm_mmu_page_role role_ign = {
5373 .level = 0xf,
5374 .access = 0x7,
5375 .quadrant = 0x3,
5376 .invalid = 0x1,
5377};
5378
13d268ca 5379static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
d126363d
JS
5380 const u8 *new, int bytes,
5381 struct kvm_page_track_notifier_node *node)
889e5cbc
XG
5382{
5383 gfn_t gfn = gpa >> PAGE_SHIFT;
889e5cbc 5384 struct kvm_mmu_page *sp;
889e5cbc
XG
5385 LIST_HEAD(invalid_list);
5386 u64 entry, gentry, *spte;
5387 int npte;
b8c67b7a 5388 bool remote_flush, local_flush;
889e5cbc
XG
5389
5390 /*
5391 * If we don't have indirect shadow pages, it means no page is
5392 * write-protected, so we can exit simply.
5393 */
6aa7de05 5394 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
889e5cbc
XG
5395 return;
5396
b8c67b7a 5397 remote_flush = local_flush = false;
889e5cbc
XG
5398
5399 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5400
889e5cbc
XG
5401 /*
5402 * No need to care whether allocation memory is successful
5403 * or not since pte prefetch is skiped if it does not have
5404 * enough objects in the cache.
5405 */
378f5cd6 5406 mmu_topup_memory_caches(vcpu, true);
889e5cbc
XG
5407
5408 spin_lock(&vcpu->kvm->mmu_lock);
0e0fee5c
JS
5409
5410 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5411
889e5cbc 5412 ++vcpu->kvm->stat.mmu_pte_write;
0375f7fa 5413 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
889e5cbc 5414
b67bfe0d 5415 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
a30f47cb 5416 if (detect_write_misaligned(sp, gpa, bytes) ||
a138fe75 5417 detect_write_flooding(sp)) {
b8c67b7a 5418 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
4cee5764 5419 ++vcpu->kvm->stat.mmu_flooded;
0e7bc4b9
AK
5420 continue;
5421 }
889e5cbc
XG
5422
5423 spte = get_written_sptes(sp, gpa, &npte);
5424 if (!spte)
5425 continue;
5426
0671a8e7 5427 local_flush = true;
ac1b714e 5428 while (npte--) {
36d9594d
VK
5429 u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5430
79539cec 5431 entry = *spte;
2de4085c 5432 mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
fa1de2bf 5433 if (gentry &&
a102a674
SC
5434 !((sp->role.word ^ base_role) & ~role_ign.word) &&
5435 rmap_can_add(vcpu))
7c562522 5436 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
9bb4f6b1 5437 if (need_remote_flush(entry, *spte))
0671a8e7 5438 remote_flush = true;
ac1b714e 5439 ++spte;
9b7a0325 5440 }
9b7a0325 5441 }
b8c67b7a 5442 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
0375f7fa 5443 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
aaee2c94 5444 spin_unlock(&vcpu->kvm->mmu_lock);
da4a00f0
AK
5445}
5446
a436036b
AK
5447int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5448{
10589a46
MT
5449 gpa_t gpa;
5450 int r;
a436036b 5451
44dd3ffa 5452 if (vcpu->arch.mmu->direct_map)
60f24784
AK
5453 return 0;
5454
1871c602 5455 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
10589a46 5456
10589a46 5457 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1cb3f3ae 5458
10589a46 5459 return r;
a436036b 5460}
577bdc49 5461EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
a436036b 5462
736c291c 5463int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
dc25e89e 5464 void *insn, int insn_len)
3067714c 5465{
92daa48b 5466 int r, emulation_type = EMULTYPE_PF;
44dd3ffa 5467 bool direct = vcpu->arch.mmu->direct_map;
3067714c 5468
6948199a 5469 if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
ddce6208
SC
5470 return RET_PF_RETRY;
5471
9b8ebbdb 5472 r = RET_PF_INVALID;
e9ee956e 5473 if (unlikely(error_code & PFERR_RSVD_MASK)) {
736c291c 5474 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
472faffa 5475 if (r == RET_PF_EMULATE)
e9ee956e 5476 goto emulate;
e9ee956e 5477 }
3067714c 5478
9b8ebbdb 5479 if (r == RET_PF_INVALID) {
7a02674d
SC
5480 r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5481 lower_32_bits(error_code), false);
7b367bc9
SC
5482 if (WARN_ON_ONCE(r == RET_PF_INVALID))
5483 return -EIO;
9b8ebbdb
PB
5484 }
5485
3067714c 5486 if (r < 0)
e9ee956e 5487 return r;
83a2ba4c
SC
5488 if (r != RET_PF_EMULATE)
5489 return 1;
3067714c 5490
14727754
TL
5491 /*
5492 * Before emulating the instruction, check if the error code
5493 * was due to a RO violation while translating the guest page.
5494 * This can occur when using nested virtualization with nested
5495 * paging in both guests. If true, we simply unprotect the page
5496 * and resume the guest.
14727754 5497 */
44dd3ffa 5498 if (vcpu->arch.mmu->direct_map &&
eebed243 5499 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
736c291c 5500 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
14727754
TL
5501 return 1;
5502 }
5503
472faffa
SC
5504 /*
5505 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5506 * optimistically try to just unprotect the page and let the processor
5507 * re-execute the instruction that caused the page fault. Do not allow
5508 * retrying MMIO emulation, as it's not only pointless but could also
5509 * cause us to enter an infinite loop because the processor will keep
6c3dfeb6
SC
5510 * faulting on the non-existent MMIO address. Retrying an instruction
5511 * from a nested guest is also pointless and dangerous as we are only
5512 * explicitly shadowing L1's page tables, i.e. unprotecting something
5513 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
472faffa 5514 */
736c291c 5515 if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
92daa48b 5516 emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
e9ee956e 5517emulate:
736c291c 5518 return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
60fc3d02 5519 insn_len);
3067714c
AK
5520}
5521EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5522
5efac074
PB
5523void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5524 gva_t gva, hpa_t root_hpa)
a7052897 5525{
b94742c9 5526 int i;
7eb77e9f 5527
5efac074
PB
5528 /* It's actually a GPA for vcpu->arch.guest_mmu. */
5529 if (mmu != &vcpu->arch.guest_mmu) {
5530 /* INVLPG on a non-canonical address is a NOP according to the SDM. */
5531 if (is_noncanonical_address(gva, vcpu))
5532 return;
5533
5534 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5535 }
5536
5537 if (!mmu->invlpg)
faff8758
JS
5538 return;
5539
5efac074
PB
5540 if (root_hpa == INVALID_PAGE) {
5541 mmu->invlpg(vcpu, gva, mmu->root_hpa);
956bf353 5542
5efac074
PB
5543 /*
5544 * INVLPG is required to invalidate any global mappings for the VA,
5545 * irrespective of PCID. Since it would take us roughly similar amount
5546 * of work to determine whether any of the prev_root mappings of the VA
5547 * is marked global, or to just sync it blindly, so we might as well
5548 * just always sync it.
5549 *
5550 * Mappings not reachable via the current cr3 or the prev_roots will be
5551 * synced when switching to that cr3, so nothing needs to be done here
5552 * for them.
5553 */
5554 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5555 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5556 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5557 } else {
5558 mmu->invlpg(vcpu, gva, root_hpa);
5559 }
5560}
5561EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_gva);
956bf353 5562
5efac074
PB
5563void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5564{
5565 kvm_mmu_invalidate_gva(vcpu, vcpu->arch.mmu, gva, INVALID_PAGE);
a7052897
MT
5566 ++vcpu->stat.invlpg;
5567}
5568EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5569
5efac074 5570
eb4b248e
JS
5571void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5572{
44dd3ffa 5573 struct kvm_mmu *mmu = vcpu->arch.mmu;
faff8758 5574 bool tlb_flush = false;
b94742c9 5575 uint i;
eb4b248e
JS
5576
5577 if (pcid == kvm_get_active_pcid(vcpu)) {
7eb77e9f 5578 mmu->invlpg(vcpu, gva, mmu->root_hpa);
faff8758 5579 tlb_flush = true;
eb4b248e
JS
5580 }
5581
b94742c9
JS
5582 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5583 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
be01e8e2 5584 pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
b94742c9
JS
5585 mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5586 tlb_flush = true;
5587 }
956bf353 5588 }
ade61e28 5589
faff8758 5590 if (tlb_flush)
afaf0b2f 5591 kvm_x86_ops.tlb_flush_gva(vcpu, gva);
faff8758 5592
eb4b248e
JS
5593 ++vcpu->stat.invlpg;
5594
5595 /*
b94742c9
JS
5596 * Mappings not reachable via the current cr3 or the prev_roots will be
5597 * synced when switching to that cr3, so nothing needs to be done here
5598 * for them.
eb4b248e
JS
5599 */
5600}
5601EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5602
83013059
SC
5603void kvm_configure_mmu(bool enable_tdp, int tdp_max_root_level,
5604 int tdp_huge_page_level)
18552672 5605{
bde77235 5606 tdp_enabled = enable_tdp;
83013059 5607 max_tdp_level = tdp_max_root_level;
703c335d
SC
5608
5609 /*
1d92d2e8 5610 * max_huge_page_level reflects KVM's MMU capabilities irrespective
703c335d
SC
5611 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5612 * the kernel is not. But, KVM never creates a page size greater than
5613 * what is used by the kernel for any given HVA, i.e. the kernel's
5614 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5615 */
5616 if (tdp_enabled)
1d92d2e8 5617 max_huge_page_level = tdp_huge_page_level;
703c335d 5618 else if (boot_cpu_has(X86_FEATURE_GBPAGES))
1d92d2e8 5619 max_huge_page_level = PG_LEVEL_1G;
703c335d 5620 else
1d92d2e8 5621 max_huge_page_level = PG_LEVEL_2M;
18552672 5622}
bde77235 5623EXPORT_SYMBOL_GPL(kvm_configure_mmu);
85875a13
SC
5624
5625/* The return value indicates if tlb flush on all vcpus is needed. */
5626typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5627
5628/* The caller should hold mmu-lock before calling this function. */
5629static __always_inline bool
5630slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5631 slot_level_handler fn, int start_level, int end_level,
5632 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5633{
5634 struct slot_rmap_walk_iterator iterator;
5635 bool flush = false;
5636
5637 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5638 end_gfn, &iterator) {
5639 if (iterator.rmap)
5640 flush |= fn(kvm, iterator.rmap);
5641
5642 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5643 if (flush && lock_flush_tlb) {
f285c633
BG
5644 kvm_flush_remote_tlbs_with_address(kvm,
5645 start_gfn,
5646 iterator.gfn - start_gfn + 1);
85875a13
SC
5647 flush = false;
5648 }
5649 cond_resched_lock(&kvm->mmu_lock);
5650 }
5651 }
5652
5653 if (flush && lock_flush_tlb) {
f285c633
BG
5654 kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5655 end_gfn - start_gfn + 1);
85875a13
SC
5656 flush = false;
5657 }
5658
5659 return flush;
5660}
5661
5662static __always_inline bool
5663slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5664 slot_level_handler fn, int start_level, int end_level,
5665 bool lock_flush_tlb)
5666{
5667 return slot_handle_level_range(kvm, memslot, fn, start_level,
5668 end_level, memslot->base_gfn,
5669 memslot->base_gfn + memslot->npages - 1,
5670 lock_flush_tlb);
5671}
5672
5673static __always_inline bool
5674slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5675 slot_level_handler fn, bool lock_flush_tlb)
5676{
3bae0459 5677 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
e662ec3e 5678 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
85875a13
SC
5679}
5680
5681static __always_inline bool
5682slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5683 slot_level_handler fn, bool lock_flush_tlb)
5684{
3bae0459 5685 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K + 1,
e662ec3e 5686 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
85875a13
SC
5687}
5688
5689static __always_inline bool
5690slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5691 slot_level_handler fn, bool lock_flush_tlb)
5692{
3bae0459
SC
5693 return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5694 PG_LEVEL_4K, lock_flush_tlb);
85875a13
SC
5695}
5696
1cfff4d9 5697static void free_mmu_pages(struct kvm_mmu *mmu)
6aa8b732 5698{
1cfff4d9
JP
5699 free_page((unsigned long)mmu->pae_root);
5700 free_page((unsigned long)mmu->lm_root);
6aa8b732
AK
5701}
5702
1cfff4d9 5703static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6aa8b732 5704{
17ac10ad 5705 struct page *page;
6aa8b732
AK
5706 int i;
5707
17ac10ad 5708 /*
b6b80c78
SC
5709 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5710 * while the PDP table is a per-vCPU construct that's allocated at MMU
5711 * creation. When emulating 32-bit mode, cr3 is only 32 bits even on
5712 * x86_64. Therefore we need to allocate the PDP table in the first
5713 * 4GB of memory, which happens to fit the DMA32 zone. Except for
5714 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5715 * skip allocating the PDP table.
17ac10ad 5716 */
d468d94b 5717 if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
b6b80c78
SC
5718 return 0;
5719
254272ce 5720 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
17ac10ad 5721 if (!page)
d7fa6ab2
WY
5722 return -ENOMEM;
5723
1cfff4d9 5724 mmu->pae_root = page_address(page);
17ac10ad 5725 for (i = 0; i < 4; ++i)
1cfff4d9 5726 mmu->pae_root[i] = INVALID_PAGE;
17ac10ad 5727
6aa8b732 5728 return 0;
6aa8b732
AK
5729}
5730
8018c27b 5731int kvm_mmu_create(struct kvm_vcpu *vcpu)
6aa8b732 5732{
b94742c9 5733 uint i;
1cfff4d9 5734 int ret;
b94742c9 5735
5962bfb7 5736 vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
5f6078f9
SC
5737 vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
5738
5962bfb7 5739 vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
5f6078f9 5740 vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
5962bfb7 5741
96880883
SC
5742 vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
5743
44dd3ffa
VK
5744 vcpu->arch.mmu = &vcpu->arch.root_mmu;
5745 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6aa8b732 5746
44dd3ffa 5747 vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
be01e8e2 5748 vcpu->arch.root_mmu.root_pgd = 0;
44dd3ffa 5749 vcpu->arch.root_mmu.translate_gpa = translate_gpa;
b94742c9 5750 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
44dd3ffa 5751 vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
6aa8b732 5752
14c07ad8 5753 vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
be01e8e2 5754 vcpu->arch.guest_mmu.root_pgd = 0;
14c07ad8
VK
5755 vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5756 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5757 vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
2c264957 5758
14c07ad8 5759 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
1cfff4d9
JP
5760
5761 ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5762 if (ret)
5763 return ret;
5764
5765 ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5766 if (ret)
5767 goto fail_allocate_root;
5768
5769 return ret;
5770 fail_allocate_root:
5771 free_mmu_pages(&vcpu->arch.guest_mmu);
5772 return ret;
6aa8b732
AK
5773}
5774
fbb158cb 5775#define BATCH_ZAP_PAGES 10
002c5f73
SC
5776static void kvm_zap_obsolete_pages(struct kvm *kvm)
5777{
5778 struct kvm_mmu_page *sp, *node;
fbb158cb 5779 int nr_zapped, batch = 0;
002c5f73
SC
5780
5781restart:
5782 list_for_each_entry_safe_reverse(sp, node,
5783 &kvm->arch.active_mmu_pages, link) {
5784 /*
5785 * No obsolete valid page exists before a newly created page
5786 * since active_mmu_pages is a FIFO list.
5787 */
5788 if (!is_obsolete_sp(kvm, sp))
5789 break;
5790
5791 /*
f95eec9b
SC
5792 * Invalid pages should never land back on the list of active
5793 * pages. Skip the bogus page, otherwise we'll get stuck in an
5794 * infinite loop if the page gets put back on the list (again).
002c5f73 5795 */
f95eec9b 5796 if (WARN_ON(sp->role.invalid))
002c5f73
SC
5797 continue;
5798
4506ecf4
SC
5799 /*
5800 * No need to flush the TLB since we're only zapping shadow
5801 * pages with an obsolete generation number and all vCPUS have
5802 * loaded a new root, i.e. the shadow pages being zapped cannot
5803 * be in active use by the guest.
5804 */
fbb158cb 5805 if (batch >= BATCH_ZAP_PAGES &&
4506ecf4 5806 cond_resched_lock(&kvm->mmu_lock)) {
fbb158cb 5807 batch = 0;
002c5f73
SC
5808 goto restart;
5809 }
5810
10605204
SC
5811 if (__kvm_mmu_prepare_zap_page(kvm, sp,
5812 &kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
fbb158cb 5813 batch += nr_zapped;
002c5f73 5814 goto restart;
fbb158cb 5815 }
002c5f73
SC
5816 }
5817
4506ecf4
SC
5818 /*
5819 * Trigger a remote TLB flush before freeing the page tables to ensure
5820 * KVM is not in the middle of a lockless shadow page table walk, which
5821 * may reference the pages.
5822 */
10605204 5823 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
002c5f73
SC
5824}
5825
5826/*
5827 * Fast invalidate all shadow pages and use lock-break technique
5828 * to zap obsolete pages.
5829 *
5830 * It's required when memslot is being deleted or VM is being
5831 * destroyed, in these cases, we should ensure that KVM MMU does
5832 * not use any resource of the being-deleted slot or all slots
5833 * after calling the function.
5834 */
5835static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5836{
ca333add
SC
5837 lockdep_assert_held(&kvm->slots_lock);
5838
002c5f73 5839 spin_lock(&kvm->mmu_lock);
14a3c4f4 5840 trace_kvm_mmu_zap_all_fast(kvm);
ca333add
SC
5841
5842 /*
5843 * Toggle mmu_valid_gen between '0' and '1'. Because slots_lock is
5844 * held for the entire duration of zapping obsolete pages, it's
5845 * impossible for there to be multiple invalid generations associated
5846 * with *valid* shadow pages at any given time, i.e. there is exactly
5847 * one valid generation and (at most) one invalid generation.
5848 */
5849 kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
002c5f73 5850
4506ecf4
SC
5851 /*
5852 * Notify all vcpus to reload its shadow page table and flush TLB.
5853 * Then all vcpus will switch to new shadow page table with the new
5854 * mmu_valid_gen.
5855 *
5856 * Note: we need to do this under the protection of mmu_lock,
5857 * otherwise, vcpu would purge shadow page but miss tlb flush.
5858 */
5859 kvm_reload_remote_mmus(kvm);
5860
002c5f73
SC
5861 kvm_zap_obsolete_pages(kvm);
5862 spin_unlock(&kvm->mmu_lock);
5863}
5864
10605204
SC
5865static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5866{
5867 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5868}
5869
b5f5fdca 5870static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
d126363d
JS
5871 struct kvm_memory_slot *slot,
5872 struct kvm_page_track_notifier_node *node)
b5f5fdca 5873{
002c5f73 5874 kvm_mmu_zap_all_fast(kvm);
1bad2b2a
XG
5875}
5876
13d268ca 5877void kvm_mmu_init_vm(struct kvm *kvm)
1bad2b2a 5878{
13d268ca 5879 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
1bad2b2a 5880
13d268ca 5881 node->track_write = kvm_mmu_pte_write;
b5f5fdca 5882 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
13d268ca 5883 kvm_page_track_register_notifier(kvm, node);
1bad2b2a
XG
5884}
5885
13d268ca 5886void kvm_mmu_uninit_vm(struct kvm *kvm)
1bad2b2a 5887{
13d268ca 5888 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
1bad2b2a 5889
13d268ca 5890 kvm_page_track_unregister_notifier(kvm, node);
1bad2b2a
XG
5891}
5892
efdfe536
XG
5893void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5894{
5895 struct kvm_memslots *slots;
5896 struct kvm_memory_slot *memslot;
9da0e4d5 5897 int i;
efdfe536
XG
5898
5899 spin_lock(&kvm->mmu_lock);
9da0e4d5
PB
5900 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5901 slots = __kvm_memslots(kvm, i);
5902 kvm_for_each_memslot(memslot, slots) {
5903 gfn_t start, end;
5904
5905 start = max(gfn_start, memslot->base_gfn);
5906 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5907 if (start >= end)
5908 continue;
efdfe536 5909
92da008f 5910 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
3bae0459 5911 PG_LEVEL_4K,
e662ec3e 5912 KVM_MAX_HUGEPAGE_LEVEL,
92da008f 5913 start, end - 1, true);
9da0e4d5 5914 }
efdfe536
XG
5915 }
5916
5917 spin_unlock(&kvm->mmu_lock);
5918}
5919
018aabb5
TY
5920static bool slot_rmap_write_protect(struct kvm *kvm,
5921 struct kvm_rmap_head *rmap_head)
d77aa73c 5922{
018aabb5 5923 return __rmap_write_protect(kvm, rmap_head, false);
d77aa73c
XG
5924}
5925
1c91cad4 5926void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
3c9bd400
JZ
5927 struct kvm_memory_slot *memslot,
5928 int start_level)
6aa8b732 5929{
d77aa73c 5930 bool flush;
6aa8b732 5931
9d1beefb 5932 spin_lock(&kvm->mmu_lock);
3c9bd400 5933 flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
e662ec3e 5934 start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
9d1beefb 5935 spin_unlock(&kvm->mmu_lock);
198c74f4 5936
198c74f4
XG
5937 /*
5938 * We can flush all the TLBs out of the mmu lock without TLB
5939 * corruption since we just change the spte from writable to
5940 * readonly so that we only need to care the case of changing
5941 * spte from present to present (changing the spte from present
5942 * to nonpresent will flush all the TLBs immediately), in other
5943 * words, the only case we care is mmu_spte_update() where we
bdd303cb 5944 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
198c74f4
XG
5945 * instead of PT_WRITABLE_MASK, that means it does not depend
5946 * on PT_WRITABLE_MASK anymore.
5947 */
d91ffee9 5948 if (flush)
7f42aa76 5949 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6aa8b732 5950}
37a7d8b0 5951
3ea3b7fa 5952static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
018aabb5 5953 struct kvm_rmap_head *rmap_head)
3ea3b7fa
WL
5954{
5955 u64 *sptep;
5956 struct rmap_iterator iter;
5957 int need_tlb_flush = 0;
ba049e93 5958 kvm_pfn_t pfn;
3ea3b7fa
WL
5959 struct kvm_mmu_page *sp;
5960
0d536790 5961restart:
018aabb5 5962 for_each_rmap_spte(rmap_head, &iter, sptep) {
57354682 5963 sp = sptep_to_sp(sptep);
3ea3b7fa
WL
5964 pfn = spte_to_pfn(*sptep);
5965
5966 /*
decf6333
XG
5967 * We cannot do huge page mapping for indirect shadow pages,
5968 * which are found on the last rmap (level = 1) when not using
5969 * tdp; such shadow pages are synced with the page table in
5970 * the guest, and the guest page table is using 4K page size
5971 * mapping if the indirect sp has level = 1.
3ea3b7fa 5972 */
a78986aa 5973 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
e851265a
SC
5974 (kvm_is_zone_device_pfn(pfn) ||
5975 PageCompound(pfn_to_page(pfn)))) {
e7912386 5976 pte_list_remove(rmap_head, sptep);
40ef75a7
LT
5977
5978 if (kvm_available_flush_tlb_with_range())
5979 kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5980 KVM_PAGES_PER_HPAGE(sp->role.level));
5981 else
5982 need_tlb_flush = 1;
5983
0d536790
XG
5984 goto restart;
5985 }
3ea3b7fa
WL
5986 }
5987
5988 return need_tlb_flush;
5989}
5990
5991void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
f36f3f28 5992 const struct kvm_memory_slot *memslot)
3ea3b7fa 5993{
f36f3f28 5994 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
3ea3b7fa 5995 spin_lock(&kvm->mmu_lock);
f36f3f28
PB
5996 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5997 kvm_mmu_zap_collapsible_spte, true);
3ea3b7fa
WL
5998 spin_unlock(&kvm->mmu_lock);
5999}
6000
b3594ffb
SC
6001void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
6002 struct kvm_memory_slot *memslot)
6003{
6004 /*
7f42aa76
SC
6005 * All current use cases for flushing the TLBs for a specific memslot
6006 * are related to dirty logging, and do the TLB flush out of mmu_lock.
6007 * The interaction between the various operations on memslot must be
6008 * serialized by slots_locks to ensure the TLB flush from one operation
6009 * is observed by any other operation on the same memslot.
b3594ffb
SC
6010 */
6011 lockdep_assert_held(&kvm->slots_lock);
cec37648
SC
6012 kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6013 memslot->npages);
b3594ffb
SC
6014}
6015
f4b4b180
KH
6016void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6017 struct kvm_memory_slot *memslot)
6018{
d77aa73c 6019 bool flush;
f4b4b180
KH
6020
6021 spin_lock(&kvm->mmu_lock);
d77aa73c 6022 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
f4b4b180
KH
6023 spin_unlock(&kvm->mmu_lock);
6024
f4b4b180
KH
6025 /*
6026 * It's also safe to flush TLBs out of mmu lock here as currently this
6027 * function is only used for dirty logging, in which case flushing TLB
6028 * out of mmu lock also guarantees no dirty pages will be lost in
6029 * dirty_bitmap.
6030 */
6031 if (flush)
7f42aa76 6032 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
f4b4b180
KH
6033}
6034EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
6035
6036void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
6037 struct kvm_memory_slot *memslot)
6038{
d77aa73c 6039 bool flush;
f4b4b180
KH
6040
6041 spin_lock(&kvm->mmu_lock);
d77aa73c
XG
6042 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
6043 false);
f4b4b180
KH
6044 spin_unlock(&kvm->mmu_lock);
6045
f4b4b180 6046 if (flush)
7f42aa76 6047 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
f4b4b180
KH
6048}
6049EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
6050
6051void kvm_mmu_slot_set_dirty(struct kvm *kvm,
6052 struct kvm_memory_slot *memslot)
6053{
d77aa73c 6054 bool flush;
f4b4b180
KH
6055
6056 spin_lock(&kvm->mmu_lock);
d77aa73c 6057 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
f4b4b180
KH
6058 spin_unlock(&kvm->mmu_lock);
6059
f4b4b180 6060 if (flush)
7f42aa76 6061 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
f4b4b180
KH
6062}
6063EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6064
92f58b5c 6065void kvm_mmu_zap_all(struct kvm *kvm)
5304b8d3
XG
6066{
6067 struct kvm_mmu_page *sp, *node;
7390de1e 6068 LIST_HEAD(invalid_list);
83cdb568 6069 int ign;
5304b8d3 6070
7390de1e 6071 spin_lock(&kvm->mmu_lock);
5304b8d3 6072restart:
8a674adc 6073 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
f95eec9b 6074 if (WARN_ON(sp->role.invalid))
4771450c 6075 continue;
92f58b5c 6076 if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5304b8d3 6077 goto restart;
24efe61f 6078 if (cond_resched_lock(&kvm->mmu_lock))
5304b8d3
XG
6079 goto restart;
6080 }
6081
4771450c 6082 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5304b8d3
XG
6083 spin_unlock(&kvm->mmu_lock);
6084}
6085
15248258 6086void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
f8f55942 6087{
164bf7e5 6088 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
e1359e2b 6089
164bf7e5 6090 gen &= MMIO_SPTE_GEN_MASK;
e1359e2b 6091
f8f55942 6092 /*
e1359e2b
SC
6093 * Generation numbers are incremented in multiples of the number of
6094 * address spaces in order to provide unique generations across all
6095 * address spaces. Strip what is effectively the address space
6096 * modifier prior to checking for a wrap of the MMIO generation so
6097 * that a wrap in any address space is detected.
6098 */
6099 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6100
f8f55942 6101 /*
e1359e2b 6102 * The very rare case: if the MMIO generation number has wrapped,
f8f55942 6103 * zap all shadow pages.
f8f55942 6104 */
e1359e2b 6105 if (unlikely(gen == 0)) {
ae0f5499 6106 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
92f58b5c 6107 kvm_mmu_zap_all_fast(kvm);
7a2e8aaf 6108 }
f8f55942
XG
6109}
6110
70534a73
DC
6111static unsigned long
6112mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
3ee16c81
IE
6113{
6114 struct kvm *kvm;
1495f230 6115 int nr_to_scan = sc->nr_to_scan;
70534a73 6116 unsigned long freed = 0;
3ee16c81 6117
0d9ce162 6118 mutex_lock(&kvm_lock);
3ee16c81
IE
6119
6120 list_for_each_entry(kvm, &vm_list, vm_list) {
3d56cbdf 6121 int idx;
d98ba053 6122 LIST_HEAD(invalid_list);
3ee16c81 6123
35f2d16b
TY
6124 /*
6125 * Never scan more than sc->nr_to_scan VM instances.
6126 * Will not hit this condition practically since we do not try
6127 * to shrink more than one VM and it is very unlikely to see
6128 * !n_used_mmu_pages so many times.
6129 */
6130 if (!nr_to_scan--)
6131 break;
19526396
GN
6132 /*
6133 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6134 * here. We may skip a VM instance errorneosly, but we do not
6135 * want to shrink a VM that only started to populate its MMU
6136 * anyway.
6137 */
10605204
SC
6138 if (!kvm->arch.n_used_mmu_pages &&
6139 !kvm_has_zapped_obsolete_pages(kvm))
19526396 6140 continue;
19526396 6141
f656ce01 6142 idx = srcu_read_lock(&kvm->srcu);
3ee16c81 6143 spin_lock(&kvm->mmu_lock);
3ee16c81 6144
10605204
SC
6145 if (kvm_has_zapped_obsolete_pages(kvm)) {
6146 kvm_mmu_commit_zap_page(kvm,
6147 &kvm->arch.zapped_obsolete_pages);
6148 goto unlock;
6149 }
6150
ebdb292d 6151 freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
19526396 6152
10605204 6153unlock:
3ee16c81 6154 spin_unlock(&kvm->mmu_lock);
f656ce01 6155 srcu_read_unlock(&kvm->srcu, idx);
19526396 6156
70534a73
DC
6157 /*
6158 * unfair on small ones
6159 * per-vm shrinkers cry out
6160 * sadness comes quickly
6161 */
19526396
GN
6162 list_move_tail(&kvm->vm_list, &vm_list);
6163 break;
3ee16c81 6164 }
3ee16c81 6165
0d9ce162 6166 mutex_unlock(&kvm_lock);
70534a73 6167 return freed;
70534a73
DC
6168}
6169
6170static unsigned long
6171mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6172{
45221ab6 6173 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
3ee16c81
IE
6174}
6175
6176static struct shrinker mmu_shrinker = {
70534a73
DC
6177 .count_objects = mmu_shrink_count,
6178 .scan_objects = mmu_shrink_scan,
3ee16c81
IE
6179 .seeks = DEFAULT_SEEKS * 10,
6180};
6181
2ddfd20e 6182static void mmu_destroy_caches(void)
b5a33a75 6183{
c1bd743e
TH
6184 kmem_cache_destroy(pte_list_desc_cache);
6185 kmem_cache_destroy(mmu_page_header_cache);
b5a33a75
AK
6186}
6187
7b6f8a06
KH
6188static void kvm_set_mmio_spte_mask(void)
6189{
6190 u64 mask;
7b6f8a06
KH
6191
6192 /*
6129ed87
SC
6193 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
6194 * PFEC.RSVD=1 on MMIO accesses. 64-bit PTEs (PAE, x86-64, and EPT
6195 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
6196 * 52-bit physical addresses then there are no reserved PA bits in the
6197 * PTEs and so the reserved PA approach must be disabled.
7b6f8a06 6198 */
6129ed87
SC
6199 if (shadow_phys_bits < 52)
6200 mask = BIT_ULL(51) | PT_PRESENT_MASK;
6201 else
6202 mask = 0;
7b6f8a06 6203
e7581cac 6204 kvm_mmu_set_mmio_spte_mask(mask, ACC_WRITE_MASK | ACC_USER_MASK);
7b6f8a06
KH
6205}
6206
b8e8c830
PB
6207static bool get_nx_auto_mode(void)
6208{
6209 /* Return true when CPU has the bug, and mitigations are ON */
6210 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6211}
6212
6213static void __set_nx_huge_pages(bool val)
6214{
6215 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6216}
6217
6218static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6219{
6220 bool old_val = nx_huge_pages;
6221 bool new_val;
6222
6223 /* In "auto" mode deploy workaround only if CPU has the bug. */
6224 if (sysfs_streq(val, "off"))
6225 new_val = 0;
6226 else if (sysfs_streq(val, "force"))
6227 new_val = 1;
6228 else if (sysfs_streq(val, "auto"))
6229 new_val = get_nx_auto_mode();
6230 else if (strtobool(val, &new_val) < 0)
6231 return -EINVAL;
6232
6233 __set_nx_huge_pages(new_val);
6234
6235 if (new_val != old_val) {
6236 struct kvm *kvm;
b8e8c830
PB
6237
6238 mutex_lock(&kvm_lock);
6239
6240 list_for_each_entry(kvm, &vm_list, vm_list) {
ed69a6cb 6241 mutex_lock(&kvm->slots_lock);
b8e8c830 6242 kvm_mmu_zap_all_fast(kvm);
ed69a6cb 6243 mutex_unlock(&kvm->slots_lock);
1aa9b957
JS
6244
6245 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
b8e8c830
PB
6246 }
6247 mutex_unlock(&kvm_lock);
6248 }
6249
6250 return 0;
6251}
6252
b5a33a75
AK
6253int kvm_mmu_module_init(void)
6254{
ab271bd4
AB
6255 int ret = -ENOMEM;
6256
b8e8c830
PB
6257 if (nx_huge_pages == -1)
6258 __set_nx_huge_pages(get_nx_auto_mode());
6259
36d9594d
VK
6260 /*
6261 * MMU roles use union aliasing which is, generally speaking, an
6262 * undefined behavior. However, we supposedly know how compilers behave
6263 * and the current status quo is unlikely to change. Guardians below are
6264 * supposed to let us know if the assumption becomes false.
6265 */
6266 BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6267 BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6268 BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6269
28a1f3ac 6270 kvm_mmu_reset_all_pte_masks();
f160c7b7 6271
7b6f8a06
KH
6272 kvm_set_mmio_spte_mask();
6273
53c07b18
XG
6274 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6275 sizeof(struct pte_list_desc),
46bea48a 6276 0, SLAB_ACCOUNT, NULL);
53c07b18 6277 if (!pte_list_desc_cache)
ab271bd4 6278 goto out;
b5a33a75 6279
d3d25b04
AK
6280 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6281 sizeof(struct kvm_mmu_page),
46bea48a 6282 0, SLAB_ACCOUNT, NULL);
d3d25b04 6283 if (!mmu_page_header_cache)
ab271bd4 6284 goto out;
d3d25b04 6285
908c7f19 6286 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
ab271bd4 6287 goto out;
45bf21a8 6288
ab271bd4
AB
6289 ret = register_shrinker(&mmu_shrinker);
6290 if (ret)
6291 goto out;
3ee16c81 6292
b5a33a75
AK
6293 return 0;
6294
ab271bd4 6295out:
3ee16c81 6296 mmu_destroy_caches();
ab271bd4 6297 return ret;
b5a33a75
AK
6298}
6299
3ad82a7e 6300/*
39337ad1 6301 * Calculate mmu pages needed for kvm.
3ad82a7e 6302 */
bc8a3d89 6303unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
3ad82a7e 6304{
bc8a3d89
BG
6305 unsigned long nr_mmu_pages;
6306 unsigned long nr_pages = 0;
bc6678a3 6307 struct kvm_memslots *slots;
be6ba0f0 6308 struct kvm_memory_slot *memslot;
9da0e4d5 6309 int i;
3ad82a7e 6310
9da0e4d5
PB
6311 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6312 slots = __kvm_memslots(kvm, i);
90d83dc3 6313
9da0e4d5
PB
6314 kvm_for_each_memslot(memslot, slots)
6315 nr_pages += memslot->npages;
6316 }
3ad82a7e
ZX
6317
6318 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
bc8a3d89 6319 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
3ad82a7e
ZX
6320
6321 return nr_mmu_pages;
6322}
6323
c42fffe3
XG
6324void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6325{
95f93af4 6326 kvm_mmu_unload(vcpu);
1cfff4d9
JP
6327 free_mmu_pages(&vcpu->arch.root_mmu);
6328 free_mmu_pages(&vcpu->arch.guest_mmu);
c42fffe3 6329 mmu_free_memory_caches(vcpu);
b034cf01
XG
6330}
6331
b034cf01
XG
6332void kvm_mmu_module_exit(void)
6333{
6334 mmu_destroy_caches();
6335 percpu_counter_destroy(&kvm_total_used_mmu_pages);
6336 unregister_shrinker(&mmu_shrinker);
c42fffe3
XG
6337 mmu_audit_disable();
6338}
1aa9b957
JS
6339
6340static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6341{
6342 unsigned int old_val;
6343 int err;
6344
6345 old_val = nx_huge_pages_recovery_ratio;
6346 err = param_set_uint(val, kp);
6347 if (err)
6348 return err;
6349
6350 if (READ_ONCE(nx_huge_pages) &&
6351 !old_val && nx_huge_pages_recovery_ratio) {
6352 struct kvm *kvm;
6353
6354 mutex_lock(&kvm_lock);
6355
6356 list_for_each_entry(kvm, &vm_list, vm_list)
6357 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6358
6359 mutex_unlock(&kvm_lock);
6360 }
6361
6362 return err;
6363}
6364
6365static void kvm_recover_nx_lpages(struct kvm *kvm)
6366{
6367 int rcu_idx;
6368 struct kvm_mmu_page *sp;
6369 unsigned int ratio;
6370 LIST_HEAD(invalid_list);
6371 ulong to_zap;
6372
6373 rcu_idx = srcu_read_lock(&kvm->srcu);
6374 spin_lock(&kvm->mmu_lock);
6375
6376 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6377 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
7d919c7a
SC
6378 for ( ; to_zap; --to_zap) {
6379 if (list_empty(&kvm->arch.lpage_disallowed_mmu_pages))
6380 break;
6381
1aa9b957
JS
6382 /*
6383 * We use a separate list instead of just using active_mmu_pages
6384 * because the number of lpage_disallowed pages is expected to
6385 * be relatively small compared to the total.
6386 */
6387 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6388 struct kvm_mmu_page,
6389 lpage_disallowed_link);
6390 WARN_ON_ONCE(!sp->lpage_disallowed);
6391 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6392 WARN_ON_ONCE(sp->lpage_disallowed);
6393
7d919c7a 6394 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
1aa9b957 6395 kvm_mmu_commit_zap_page(kvm, &invalid_list);
7d919c7a 6396 cond_resched_lock(&kvm->mmu_lock);
1aa9b957
JS
6397 }
6398 }
e8950569 6399 kvm_mmu_commit_zap_page(kvm, &invalid_list);
1aa9b957
JS
6400
6401 spin_unlock(&kvm->mmu_lock);
6402 srcu_read_unlock(&kvm->srcu, rcu_idx);
6403}
6404
6405static long get_nx_lpage_recovery_timeout(u64 start_time)
6406{
6407 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6408 ? start_time + 60 * HZ - get_jiffies_64()
6409 : MAX_SCHEDULE_TIMEOUT;
6410}
6411
6412static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6413{
6414 u64 start_time;
6415 long remaining_time;
6416
6417 while (true) {
6418 start_time = get_jiffies_64();
6419 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6420
6421 set_current_state(TASK_INTERRUPTIBLE);
6422 while (!kthread_should_stop() && remaining_time > 0) {
6423 schedule_timeout(remaining_time);
6424 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6425 set_current_state(TASK_INTERRUPTIBLE);
6426 }
6427
6428 set_current_state(TASK_RUNNING);
6429
6430 if (kthread_should_stop())
6431 return 0;
6432
6433 kvm_recover_nx_lpages(kvm);
6434 }
6435}
6436
6437int kvm_mmu_post_init_vm(struct kvm *kvm)
6438{
6439 int err;
6440
6441 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6442 "kvm-nx-lpage-recovery",
6443 &kvm->arch.nx_lpage_recovery_thread);
6444 if (!err)
6445 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6446
6447 return err;
6448}
6449
6450void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6451{
6452 if (kvm->arch.nx_lpage_recovery_thread)
6453 kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6454}