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