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