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