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