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