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