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