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