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