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