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