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