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