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