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