]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - arch/x86/kvm/mmu.c
kvm: x86: Add a root_hpa parameter to kvm_mmu->invlpg()
[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
7c390d35 3441void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, bool free_prev_root)
74b566e6
JS
3442{
3443 int i;
3444 LIST_HEAD(invalid_list);
3445 struct kvm_mmu *mmu = &vcpu->arch.mmu;
3446
7c390d35
JS
3447 if (!VALID_PAGE(mmu->root_hpa) &&
3448 (!VALID_PAGE(mmu->prev_root.hpa) || !free_prev_root))
17ac10ad 3449 return;
35af577a
GN
3450
3451 spin_lock(&vcpu->kvm->mmu_lock);
17ac10ad 3452
7c390d35
JS
3453 if (free_prev_root)
3454 mmu_free_root_page(vcpu->kvm, &mmu->prev_root.hpa,
3455 &invalid_list);
3456
74b566e6
JS
3457 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3458 (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3459 mmu_free_root_page(vcpu->kvm, &mmu->root_hpa, &invalid_list);
3460 } else {
3461 for (i = 0; i < 4; ++i)
3462 if (mmu->pae_root[i] != 0)
3463 mmu_free_root_page(vcpu->kvm, &mmu->pae_root[i],
3464 &invalid_list);
3465 mmu->root_hpa = INVALID_PAGE;
17ac10ad 3466 }
74b566e6 3467
d98ba053 3468 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
aaee2c94 3469 spin_unlock(&vcpu->kvm->mmu_lock);
17ac10ad 3470}
74b566e6 3471EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
17ac10ad 3472
8986ecc0
MT
3473static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3474{
3475 int ret = 0;
3476
3477 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
a8eeb04a 3478 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8986ecc0
MT
3479 ret = 1;
3480 }
3481
3482 return ret;
3483}
3484
651dd37a
JR
3485static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3486{
3487 struct kvm_mmu_page *sp;
7ebaf15e 3488 unsigned i;
651dd37a 3489
855feb67 3490 if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) {
651dd37a 3491 spin_lock(&vcpu->kvm->mmu_lock);
26eeb53c
WL
3492 if(make_mmu_pages_available(vcpu) < 0) {
3493 spin_unlock(&vcpu->kvm->mmu_lock);
ed52870f 3494 return -ENOSPC;
26eeb53c 3495 }
855feb67
YZ
3496 sp = kvm_mmu_get_page(vcpu, 0, 0,
3497 vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL);
651dd37a
JR
3498 ++sp->root_count;
3499 spin_unlock(&vcpu->kvm->mmu_lock);
3500 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3501 } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3502 for (i = 0; i < 4; ++i) {
3503 hpa_t root = vcpu->arch.mmu.pae_root[i];
3504
fa4a2c08 3505 MMU_WARN_ON(VALID_PAGE(root));
651dd37a 3506 spin_lock(&vcpu->kvm->mmu_lock);
26eeb53c
WL
3507 if (make_mmu_pages_available(vcpu) < 0) {
3508 spin_unlock(&vcpu->kvm->mmu_lock);
ed52870f 3509 return -ENOSPC;
26eeb53c 3510 }
649497d1 3511 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
bb11c6c9 3512 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
651dd37a
JR
3513 root = __pa(sp->spt);
3514 ++sp->root_count;
3515 spin_unlock(&vcpu->kvm->mmu_lock);
3516 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
651dd37a 3517 }
6292757f 3518 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
651dd37a
JR
3519 } else
3520 BUG();
3521
3522 return 0;
3523}
3524
3525static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
17ac10ad 3526{
4db35314 3527 struct kvm_mmu_page *sp;
81407ca5
JR
3528 u64 pdptr, pm_mask;
3529 gfn_t root_gfn;
3530 int i;
3bb65a22 3531
5777ed34 3532 root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
17ac10ad 3533
651dd37a
JR
3534 if (mmu_check_root(vcpu, root_gfn))
3535 return 1;
3536
3537 /*
3538 * Do we shadow a long mode page table? If so we need to
3539 * write-protect the guests page table root.
3540 */
855feb67 3541 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
ad312c7c 3542 hpa_t root = vcpu->arch.mmu.root_hpa;
17ac10ad 3543
fa4a2c08 3544 MMU_WARN_ON(VALID_PAGE(root));
651dd37a 3545
8facbbff 3546 spin_lock(&vcpu->kvm->mmu_lock);
26eeb53c
WL
3547 if (make_mmu_pages_available(vcpu) < 0) {
3548 spin_unlock(&vcpu->kvm->mmu_lock);
ed52870f 3549 return -ENOSPC;
26eeb53c 3550 }
855feb67
YZ
3551 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3552 vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL);
4db35314
AK
3553 root = __pa(sp->spt);
3554 ++sp->root_count;
8facbbff 3555 spin_unlock(&vcpu->kvm->mmu_lock);
ad312c7c 3556 vcpu->arch.mmu.root_hpa = root;
8986ecc0 3557 return 0;
17ac10ad 3558 }
f87f9288 3559
651dd37a
JR
3560 /*
3561 * We shadow a 32 bit page table. This may be a legacy 2-level
81407ca5
JR
3562 * or a PAE 3-level page table. In either case we need to be aware that
3563 * the shadow page table may be a PAE or a long mode page table.
651dd37a 3564 */
81407ca5 3565 pm_mask = PT_PRESENT_MASK;
2a7266a8 3566 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL)
81407ca5
JR
3567 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3568
17ac10ad 3569 for (i = 0; i < 4; ++i) {
ad312c7c 3570 hpa_t root = vcpu->arch.mmu.pae_root[i];
17ac10ad 3571
fa4a2c08 3572 MMU_WARN_ON(VALID_PAGE(root));
ad312c7c 3573 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
e4e517b4 3574 pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
812f30b2 3575 if (!(pdptr & PT_PRESENT_MASK)) {
ad312c7c 3576 vcpu->arch.mmu.pae_root[i] = 0;
417726a3
AK
3577 continue;
3578 }
6de4f3ad 3579 root_gfn = pdptr >> PAGE_SHIFT;
f87f9288
JR
3580 if (mmu_check_root(vcpu, root_gfn))
3581 return 1;
5a7388c2 3582 }
8facbbff 3583 spin_lock(&vcpu->kvm->mmu_lock);
26eeb53c
WL
3584 if (make_mmu_pages_available(vcpu) < 0) {
3585 spin_unlock(&vcpu->kvm->mmu_lock);
ed52870f 3586 return -ENOSPC;
26eeb53c 3587 }
bb11c6c9
TY
3588 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3589 0, ACC_ALL);
4db35314
AK
3590 root = __pa(sp->spt);
3591 ++sp->root_count;
8facbbff
AK
3592 spin_unlock(&vcpu->kvm->mmu_lock);
3593
81407ca5 3594 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
17ac10ad 3595 }
6292757f 3596 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
81407ca5
JR
3597
3598 /*
3599 * If we shadow a 32 bit page table with a long mode page
3600 * table we enter this path.
3601 */
2a7266a8 3602 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) {
81407ca5
JR
3603 if (vcpu->arch.mmu.lm_root == NULL) {
3604 /*
3605 * The additional page necessary for this is only
3606 * allocated on demand.
3607 */
3608
3609 u64 *lm_root;
3610
3611 lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3612 if (lm_root == NULL)
3613 return 1;
3614
3615 lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3616
3617 vcpu->arch.mmu.lm_root = lm_root;
3618 }
3619
3620 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3621 }
3622
8986ecc0 3623 return 0;
17ac10ad
AK
3624}
3625
651dd37a
JR
3626static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3627{
3628 if (vcpu->arch.mmu.direct_map)
3629 return mmu_alloc_direct_roots(vcpu);
3630 else
3631 return mmu_alloc_shadow_roots(vcpu);
3632}
3633
578e1c4d 3634void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
0ba73cda
MT
3635{
3636 int i;
3637 struct kvm_mmu_page *sp;
3638
81407ca5
JR
3639 if (vcpu->arch.mmu.direct_map)
3640 return;
3641
0ba73cda
MT
3642 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3643 return;
6903074c 3644
56f17dd3 3645 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
578e1c4d 3646
855feb67 3647 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
0ba73cda 3648 hpa_t root = vcpu->arch.mmu.root_hpa;
578e1c4d 3649
0ba73cda 3650 sp = page_header(root);
578e1c4d
JS
3651
3652 /*
3653 * Even if another CPU was marking the SP as unsync-ed
3654 * simultaneously, any guest page table changes are not
3655 * guaranteed to be visible anyway until this VCPU issues a TLB
3656 * flush strictly after those changes are made. We only need to
3657 * ensure that the other CPU sets these flags before any actual
3658 * changes to the page tables are made. The comments in
3659 * mmu_need_write_protect() describe what could go wrong if this
3660 * requirement isn't satisfied.
3661 */
3662 if (!smp_load_acquire(&sp->unsync) &&
3663 !smp_load_acquire(&sp->unsync_children))
3664 return;
3665
3666 spin_lock(&vcpu->kvm->mmu_lock);
3667 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3668
0ba73cda 3669 mmu_sync_children(vcpu, sp);
578e1c4d 3670
0375f7fa 3671 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
578e1c4d 3672 spin_unlock(&vcpu->kvm->mmu_lock);
0ba73cda
MT
3673 return;
3674 }
578e1c4d
JS
3675
3676 spin_lock(&vcpu->kvm->mmu_lock);
3677 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3678
0ba73cda
MT
3679 for (i = 0; i < 4; ++i) {
3680 hpa_t root = vcpu->arch.mmu.pae_root[i];
3681
8986ecc0 3682 if (root && VALID_PAGE(root)) {
0ba73cda
MT
3683 root &= PT64_BASE_ADDR_MASK;
3684 sp = page_header(root);
3685 mmu_sync_children(vcpu, sp);
3686 }
3687 }
0ba73cda 3688
578e1c4d 3689 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
6cffe8ca 3690 spin_unlock(&vcpu->kvm->mmu_lock);
0ba73cda 3691}
bfd0a56b 3692EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
0ba73cda 3693
1871c602 3694static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
ab9ae313 3695 u32 access, struct x86_exception *exception)
6aa8b732 3696{
ab9ae313
AK
3697 if (exception)
3698 exception->error_code = 0;
6aa8b732
AK
3699 return vaddr;
3700}
3701
6539e738 3702static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
ab9ae313
AK
3703 u32 access,
3704 struct x86_exception *exception)
6539e738 3705{
ab9ae313
AK
3706 if (exception)
3707 exception->error_code = 0;
54987b7a 3708 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
6539e738
JR
3709}
3710
d625b155
XG
3711static bool
3712__is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3713{
3714 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3715
3716 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3717 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3718}
3719
3720static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3721{
3722 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3723}
3724
3725static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3726{
3727 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3728}
3729
ded58749 3730static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf 3731{
9034e6e8
PB
3732 /*
3733 * A nested guest cannot use the MMIO cache if it is using nested
3734 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3735 */
3736 if (mmu_is_nested(vcpu))
3737 return false;
3738
ce88decf
XG
3739 if (direct)
3740 return vcpu_match_mmio_gpa(vcpu, addr);
3741
3742 return vcpu_match_mmio_gva(vcpu, addr);
3743}
3744
47ab8751
XG
3745/* return true if reserved bit is detected on spte. */
3746static bool
3747walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
ce88decf
XG
3748{
3749 struct kvm_shadow_walk_iterator iterator;
2a7266a8 3750 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
47ab8751
XG
3751 int root, leaf;
3752 bool reserved = false;
ce88decf 3753
37f6a4e2 3754 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
47ab8751 3755 goto exit;
37f6a4e2 3756
ce88decf 3757 walk_shadow_page_lockless_begin(vcpu);
47ab8751 3758
29ecd660
PB
3759 for (shadow_walk_init(&iterator, vcpu, addr),
3760 leaf = root = iterator.level;
47ab8751
XG
3761 shadow_walk_okay(&iterator);
3762 __shadow_walk_next(&iterator, spte)) {
47ab8751
XG
3763 spte = mmu_spte_get_lockless(iterator.sptep);
3764
3765 sptes[leaf - 1] = spte;
29ecd660 3766 leaf--;
47ab8751 3767
ce88decf
XG
3768 if (!is_shadow_present_pte(spte))
3769 break;
47ab8751
XG
3770
3771 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
58c95070 3772 iterator.level);
47ab8751
XG
3773 }
3774
ce88decf
XG
3775 walk_shadow_page_lockless_end(vcpu);
3776
47ab8751
XG
3777 if (reserved) {
3778 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3779 __func__, addr);
29ecd660 3780 while (root > leaf) {
47ab8751
XG
3781 pr_err("------ spte 0x%llx level %d.\n",
3782 sptes[root - 1], root);
3783 root--;
3784 }
3785 }
3786exit:
3787 *sptep = spte;
3788 return reserved;
ce88decf
XG
3789}
3790
e08d26f0 3791static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf
XG
3792{
3793 u64 spte;
47ab8751 3794 bool reserved;
ce88decf 3795
ded58749 3796 if (mmio_info_in_cache(vcpu, addr, direct))
9b8ebbdb 3797 return RET_PF_EMULATE;
ce88decf 3798
47ab8751 3799 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
450869d6 3800 if (WARN_ON(reserved))
9b8ebbdb 3801 return -EINVAL;
ce88decf
XG
3802
3803 if (is_mmio_spte(spte)) {
3804 gfn_t gfn = get_mmio_spte_gfn(spte);
3805 unsigned access = get_mmio_spte_access(spte);
3806
54bf36aa 3807 if (!check_mmio_spte(vcpu, spte))
9b8ebbdb 3808 return RET_PF_INVALID;
f8f55942 3809
ce88decf
XG
3810 if (direct)
3811 addr = 0;
4f022648
XG
3812
3813 trace_handle_mmio_page_fault(addr, gfn, access);
ce88decf 3814 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
9b8ebbdb 3815 return RET_PF_EMULATE;
ce88decf
XG
3816 }
3817
ce88decf
XG
3818 /*
3819 * If the page table is zapped by other cpus, let CPU fault again on
3820 * the address.
3821 */
9b8ebbdb 3822 return RET_PF_RETRY;
ce88decf 3823}
ce88decf 3824
3d0c27ad
XG
3825static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3826 u32 error_code, gfn_t gfn)
3827{
3828 if (unlikely(error_code & PFERR_RSVD_MASK))
3829 return false;
3830
3831 if (!(error_code & PFERR_PRESENT_MASK) ||
3832 !(error_code & PFERR_WRITE_MASK))
3833 return false;
3834
3835 /*
3836 * guest is writing the page which is write tracked which can
3837 * not be fixed by page fault handler.
3838 */
3839 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3840 return true;
3841
3842 return false;
3843}
3844
e5691a81
XG
3845static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3846{
3847 struct kvm_shadow_walk_iterator iterator;
3848 u64 spte;
3849
3850 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3851 return;
3852
3853 walk_shadow_page_lockless_begin(vcpu);
3854 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3855 clear_sp_write_flooding_count(iterator.sptep);
3856 if (!is_shadow_present_pte(spte))
3857 break;
3858 }
3859 walk_shadow_page_lockless_end(vcpu);
3860}
3861
6aa8b732 3862static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
78b2c54a 3863 u32 error_code, bool prefault)
6aa8b732 3864{
3d0c27ad 3865 gfn_t gfn = gva >> PAGE_SHIFT;
e2dec939 3866 int r;
6aa8b732 3867
b8688d51 3868 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
ce88decf 3869
3d0c27ad 3870 if (page_fault_handle_page_track(vcpu, error_code, gfn))
9b8ebbdb 3871 return RET_PF_EMULATE;
ce88decf 3872
e2dec939
AK
3873 r = mmu_topup_memory_caches(vcpu);
3874 if (r)
3875 return r;
714b93da 3876
fa4a2c08 3877 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
6aa8b732 3878
6aa8b732 3879
e833240f 3880 return nonpaging_map(vcpu, gva & PAGE_MASK,
c7ba5b48 3881 error_code, gfn, prefault);
6aa8b732
AK
3882}
3883
7e1fbeac 3884static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
af585b92
GN
3885{
3886 struct kvm_arch_async_pf arch;
fb67e14f 3887
7c90705b 3888 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
af585b92 3889 arch.gfn = gfn;
c4806acd 3890 arch.direct_map = vcpu->arch.mmu.direct_map;
fb67e14f 3891 arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
af585b92 3892
54bf36aa 3893 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
af585b92
GN
3894}
3895
9bc1f09f 3896bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
af585b92 3897{
35754c98 3898 if (unlikely(!lapic_in_kernel(vcpu) ||
2a266f23
HZ
3899 kvm_event_needs_reinjection(vcpu) ||
3900 vcpu->arch.exception.pending))
af585b92
GN
3901 return false;
3902
52a5c155 3903 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
9bc1f09f
WL
3904 return false;
3905
af585b92
GN
3906 return kvm_x86_ops->interrupt_allowed(vcpu);
3907}
3908
78b2c54a 3909static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
ba049e93 3910 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
af585b92 3911{
3520469d 3912 struct kvm_memory_slot *slot;
af585b92
GN
3913 bool async;
3914
3a2936de
JM
3915 /*
3916 * Don't expose private memslots to L2.
3917 */
3918 if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
3919 *pfn = KVM_PFN_NOSLOT;
3920 return false;
3921 }
3922
54bf36aa 3923 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3520469d
PB
3924 async = false;
3925 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
af585b92
GN
3926 if (!async)
3927 return false; /* *pfn has correct page already */
3928
9bc1f09f 3929 if (!prefault && kvm_can_do_async_pf(vcpu)) {
c9b263d2 3930 trace_kvm_try_async_get_page(gva, gfn);
af585b92
GN
3931 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3932 trace_kvm_async_pf_doublefault(gva, gfn);
3933 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3934 return true;
3935 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
3936 return true;
3937 }
3938
3520469d 3939 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
af585b92
GN
3940 return false;
3941}
3942
1261bfa3 3943int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
d0006530 3944 u64 fault_address, char *insn, int insn_len)
1261bfa3
WL
3945{
3946 int r = 1;
3947
3948 switch (vcpu->arch.apf.host_apf_reason) {
3949 default:
3950 trace_kvm_page_fault(fault_address, error_code);
3951
d0006530 3952 if (kvm_event_needs_reinjection(vcpu))
1261bfa3
WL
3953 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
3954 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
3955 insn_len);
3956 break;
3957 case KVM_PV_REASON_PAGE_NOT_PRESENT:
3958 vcpu->arch.apf.host_apf_reason = 0;
3959 local_irq_disable();
a2b7861b 3960 kvm_async_pf_task_wait(fault_address, 0);
1261bfa3
WL
3961 local_irq_enable();
3962 break;
3963 case KVM_PV_REASON_PAGE_READY:
3964 vcpu->arch.apf.host_apf_reason = 0;
3965 local_irq_disable();
3966 kvm_async_pf_task_wake(fault_address);
3967 local_irq_enable();
3968 break;
3969 }
3970 return r;
3971}
3972EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
3973
6a39bbc5
XG
3974static bool
3975check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
3976{
3977 int page_num = KVM_PAGES_PER_HPAGE(level);
3978
3979 gfn &= ~(page_num - 1);
3980
3981 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
3982}
3983
56028d08 3984static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
78b2c54a 3985 bool prefault)
fb72d167 3986{
ba049e93 3987 kvm_pfn_t pfn;
fb72d167 3988 int r;
852e3c19 3989 int level;
cd1872f0 3990 bool force_pt_level;
05da4558 3991 gfn_t gfn = gpa >> PAGE_SHIFT;
e930bffe 3992 unsigned long mmu_seq;
612819c3
MT
3993 int write = error_code & PFERR_WRITE_MASK;
3994 bool map_writable;
fb72d167 3995
fa4a2c08 3996 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
fb72d167 3997
3d0c27ad 3998 if (page_fault_handle_page_track(vcpu, error_code, gfn))
9b8ebbdb 3999 return RET_PF_EMULATE;
ce88decf 4000
fb72d167
JR
4001 r = mmu_topup_memory_caches(vcpu);
4002 if (r)
4003 return r;
4004
fd136902
TY
4005 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
4006 PT_DIRECTORY_LEVEL);
4007 level = mapping_level(vcpu, gfn, &force_pt_level);
936a5fe6 4008 if (likely(!force_pt_level)) {
6a39bbc5
XG
4009 if (level > PT_DIRECTORY_LEVEL &&
4010 !check_hugepage_cache_consistency(vcpu, gfn, level))
4011 level = PT_DIRECTORY_LEVEL;
936a5fe6 4012 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
fd136902 4013 }
852e3c19 4014
c7ba5b48 4015 if (fast_page_fault(vcpu, gpa, level, error_code))
9b8ebbdb 4016 return RET_PF_RETRY;
c7ba5b48 4017
e930bffe 4018 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4c2155ce 4019 smp_rmb();
af585b92 4020
78b2c54a 4021 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
9b8ebbdb 4022 return RET_PF_RETRY;
af585b92 4023
d7c55201
XG
4024 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4025 return r;
4026
fb72d167 4027 spin_lock(&vcpu->kvm->mmu_lock);
8ca40a70 4028 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
e930bffe 4029 goto out_unlock;
26eeb53c
WL
4030 if (make_mmu_pages_available(vcpu) < 0)
4031 goto out_unlock;
936a5fe6
AA
4032 if (likely(!force_pt_level))
4033 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
7ee0e5b2 4034 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
fb72d167 4035 spin_unlock(&vcpu->kvm->mmu_lock);
fb72d167
JR
4036
4037 return r;
e930bffe
AA
4038
4039out_unlock:
4040 spin_unlock(&vcpu->kvm->mmu_lock);
4041 kvm_release_pfn_clean(pfn);
9b8ebbdb 4042 return RET_PF_RETRY;
fb72d167
JR
4043}
4044
8a3c1a33
PB
4045static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4046 struct kvm_mmu *context)
6aa8b732 4047{
6aa8b732 4048 context->page_fault = nonpaging_page_fault;
6aa8b732 4049 context->gva_to_gpa = nonpaging_gva_to_gpa;
e8bc217a 4050 context->sync_page = nonpaging_sync_page;
a7052897 4051 context->invlpg = nonpaging_invlpg;
0f53b5b1 4052 context->update_pte = nonpaging_update_pte;
cea0f0e7 4053 context->root_level = 0;
6aa8b732 4054 context->shadow_root_level = PT32E_ROOT_LEVEL;
c5a78f2b 4055 context->direct_map = true;
2d48a985 4056 context->nx = false;
6aa8b732
AK
4057}
4058
0aab33e4 4059static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
ade61e28
JS
4060 union kvm_mmu_page_role new_role,
4061 bool skip_tlb_flush)
7c390d35
JS
4062{
4063 struct kvm_mmu *mmu = &vcpu->arch.mmu;
4064
4065 /*
4066 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4067 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4068 * later if necessary.
4069 */
4070 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4071 mmu->root_level >= PT64_ROOT_4LEVEL) {
4072 gpa_t prev_cr3 = mmu->prev_root.cr3;
4073
4074 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4075 return false;
4076
4077 swap(mmu->root_hpa, mmu->prev_root.hpa);
50c28f21 4078 mmu->prev_root.cr3 = mmu->get_cr3(vcpu);
7c390d35 4079
0aab33e4
JS
4080 if (new_cr3 == prev_cr3 &&
4081 VALID_PAGE(mmu->root_hpa) &&
4082 page_header(mmu->root_hpa) != NULL &&
4083 new_role.word == page_header(mmu->root_hpa)->role.word) {
7c390d35
JS
4084 /*
4085 * It is possible that the cached previous root page is
4086 * obsolete because of a change in the MMU
4087 * generation number. However, that is accompanied by
4088 * KVM_REQ_MMU_RELOAD, which will free the root that we
4089 * have set here and allocate a new one.
4090 */
4091
0aab33e4 4092 kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
7c390d35 4093 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
ade61e28
JS
4094 if (!skip_tlb_flush)
4095 kvm_x86_ops->tlb_flush(vcpu, true);
4096
7c390d35
JS
4097 __clear_sp_write_flooding_count(
4098 page_header(mmu->root_hpa));
4099
7c390d35
JS
4100 return true;
4101 }
4102 }
4103
4104 return false;
4105}
4106
0aab33e4 4107static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
ade61e28
JS
4108 union kvm_mmu_page_role new_role,
4109 bool skip_tlb_flush)
6aa8b732 4110{
ade61e28 4111 if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
7c390d35 4112 kvm_mmu_free_roots(vcpu, false);
6aa8b732
AK
4113}
4114
ade61e28 4115void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
0aab33e4 4116{
ade61e28
JS
4117 __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4118 skip_tlb_flush);
0aab33e4 4119}
50c28f21 4120EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
0aab33e4 4121
5777ed34
JR
4122static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4123{
9f8fe504 4124 return kvm_read_cr3(vcpu);
5777ed34
JR
4125}
4126
6389ee94
AK
4127static void inject_page_fault(struct kvm_vcpu *vcpu,
4128 struct x86_exception *fault)
6aa8b732 4129{
6389ee94 4130 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
6aa8b732
AK
4131}
4132
54bf36aa 4133static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
f2fd125d 4134 unsigned access, int *nr_present)
ce88decf
XG
4135{
4136 if (unlikely(is_mmio_spte(*sptep))) {
4137 if (gfn != get_mmio_spte_gfn(*sptep)) {
4138 mmu_spte_clear_no_track(sptep);
4139 return true;
4140 }
4141
4142 (*nr_present)++;
54bf36aa 4143 mark_mmio_spte(vcpu, sptep, gfn, access);
ce88decf
XG
4144 return true;
4145 }
4146
4147 return false;
4148}
4149
6bb69c9b
PB
4150static inline bool is_last_gpte(struct kvm_mmu *mmu,
4151 unsigned level, unsigned gpte)
6fd01b71 4152{
6bb69c9b
PB
4153 /*
4154 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4155 * If it is clear, there are no large pages at this level, so clear
4156 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4157 */
4158 gpte &= level - mmu->last_nonleaf_level;
4159
829ee279
LP
4160 /*
4161 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4162 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4163 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4164 */
4165 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4166
6bb69c9b 4167 return gpte & PT_PAGE_SIZE_MASK;
6fd01b71
AK
4168}
4169
37406aaa
NHE
4170#define PTTYPE_EPT 18 /* arbitrary */
4171#define PTTYPE PTTYPE_EPT
4172#include "paging_tmpl.h"
4173#undef PTTYPE
4174
6aa8b732
AK
4175#define PTTYPE 64
4176#include "paging_tmpl.h"
4177#undef PTTYPE
4178
4179#define PTTYPE 32
4180#include "paging_tmpl.h"
4181#undef PTTYPE
4182
6dc98b86
XG
4183static void
4184__reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4185 struct rsvd_bits_validate *rsvd_check,
4186 int maxphyaddr, int level, bool nx, bool gbpages,
6fec2144 4187 bool pse, bool amd)
82725b20 4188{
82725b20 4189 u64 exb_bit_rsvd = 0;
5f7dde7b 4190 u64 gbpages_bit_rsvd = 0;
a0c0feb5 4191 u64 nonleaf_bit8_rsvd = 0;
82725b20 4192
a0a64f50 4193 rsvd_check->bad_mt_xwr = 0;
25d92081 4194
6dc98b86 4195 if (!nx)
82725b20 4196 exb_bit_rsvd = rsvd_bits(63, 63);
6dc98b86 4197 if (!gbpages)
5f7dde7b 4198 gbpages_bit_rsvd = rsvd_bits(7, 7);
a0c0feb5
PB
4199
4200 /*
4201 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4202 * leaf entries) on AMD CPUs only.
4203 */
6fec2144 4204 if (amd)
a0c0feb5
PB
4205 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4206
6dc98b86 4207 switch (level) {
82725b20
DE
4208 case PT32_ROOT_LEVEL:
4209 /* no rsvd bits for 2 level 4K page table entries */
a0a64f50
XG
4210 rsvd_check->rsvd_bits_mask[0][1] = 0;
4211 rsvd_check->rsvd_bits_mask[0][0] = 0;
4212 rsvd_check->rsvd_bits_mask[1][0] =
4213 rsvd_check->rsvd_bits_mask[0][0];
f815bce8 4214
6dc98b86 4215 if (!pse) {
a0a64f50 4216 rsvd_check->rsvd_bits_mask[1][1] = 0;
f815bce8
XG
4217 break;
4218 }
4219
82725b20
DE
4220 if (is_cpuid_PSE36())
4221 /* 36bits PSE 4MB page */
a0a64f50 4222 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
82725b20
DE
4223 else
4224 /* 32 bits PSE 4MB page */
a0a64f50 4225 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
82725b20
DE
4226 break;
4227 case PT32E_ROOT_LEVEL:
a0a64f50 4228 rsvd_check->rsvd_bits_mask[0][2] =
20c466b5 4229 rsvd_bits(maxphyaddr, 63) |
cd9ae5fe 4230 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
a0a64f50 4231 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4c26b4cd 4232 rsvd_bits(maxphyaddr, 62); /* PDE */
a0a64f50 4233 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
82725b20 4234 rsvd_bits(maxphyaddr, 62); /* PTE */
a0a64f50 4235 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
82725b20
DE
4236 rsvd_bits(maxphyaddr, 62) |
4237 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
4238 rsvd_check->rsvd_bits_mask[1][0] =
4239 rsvd_check->rsvd_bits_mask[0][0];
82725b20 4240 break;
855feb67
YZ
4241 case PT64_ROOT_5LEVEL:
4242 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4243 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4244 rsvd_bits(maxphyaddr, 51);
4245 rsvd_check->rsvd_bits_mask[1][4] =
4246 rsvd_check->rsvd_bits_mask[0][4];
2a7266a8 4247 case PT64_ROOT_4LEVEL:
a0a64f50
XG
4248 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4249 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4c26b4cd 4250 rsvd_bits(maxphyaddr, 51);
a0a64f50
XG
4251 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4252 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
82725b20 4253 rsvd_bits(maxphyaddr, 51);
a0a64f50
XG
4254 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4255 rsvd_bits(maxphyaddr, 51);
4256 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4257 rsvd_bits(maxphyaddr, 51);
4258 rsvd_check->rsvd_bits_mask[1][3] =
4259 rsvd_check->rsvd_bits_mask[0][3];
4260 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
5f7dde7b 4261 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
e04da980 4262 rsvd_bits(13, 29);
a0a64f50 4263 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4c26b4cd
SY
4264 rsvd_bits(maxphyaddr, 51) |
4265 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
4266 rsvd_check->rsvd_bits_mask[1][0] =
4267 rsvd_check->rsvd_bits_mask[0][0];
82725b20
DE
4268 break;
4269 }
4270}
4271
6dc98b86
XG
4272static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4273 struct kvm_mmu *context)
4274{
4275 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4276 cpuid_maxphyaddr(vcpu), context->root_level,
d6321d49
RK
4277 context->nx,
4278 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
6fec2144 4279 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
6dc98b86
XG
4280}
4281
81b8eebb
XG
4282static void
4283__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4284 int maxphyaddr, bool execonly)
25d92081 4285{
951f9fd7 4286 u64 bad_mt_xwr;
25d92081 4287
855feb67
YZ
4288 rsvd_check->rsvd_bits_mask[0][4] =
4289 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
a0a64f50 4290 rsvd_check->rsvd_bits_mask[0][3] =
25d92081 4291 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
a0a64f50 4292 rsvd_check->rsvd_bits_mask[0][2] =
25d92081 4293 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
a0a64f50 4294 rsvd_check->rsvd_bits_mask[0][1] =
25d92081 4295 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
a0a64f50 4296 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
25d92081
YZ
4297
4298 /* large page */
855feb67 4299 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
a0a64f50
XG
4300 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4301 rsvd_check->rsvd_bits_mask[1][2] =
25d92081 4302 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
a0a64f50 4303 rsvd_check->rsvd_bits_mask[1][1] =
25d92081 4304 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
a0a64f50 4305 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
25d92081 4306
951f9fd7
PB
4307 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4308 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4309 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4310 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4311 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4312 if (!execonly) {
4313 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4314 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
25d92081 4315 }
951f9fd7 4316 rsvd_check->bad_mt_xwr = bad_mt_xwr;
25d92081
YZ
4317}
4318
81b8eebb
XG
4319static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4320 struct kvm_mmu *context, bool execonly)
4321{
4322 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4323 cpuid_maxphyaddr(vcpu), execonly);
4324}
4325
c258b62b
XG
4326/*
4327 * the page table on host is the shadow page table for the page
4328 * table in guest or amd nested guest, its mmu features completely
4329 * follow the features in guest.
4330 */
4331void
4332reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4333{
5f0b8199 4334 bool uses_nx = context->nx || context->base_role.smep_andnot_wp;
ea2800dd
BS
4335 struct rsvd_bits_validate *shadow_zero_check;
4336 int i;
5f0b8199 4337
6fec2144
PB
4338 /*
4339 * Passing "true" to the last argument is okay; it adds a check
4340 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4341 */
ea2800dd
BS
4342 shadow_zero_check = &context->shadow_zero_check;
4343 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
c258b62b 4344 boot_cpu_data.x86_phys_bits,
5f0b8199 4345 context->shadow_root_level, uses_nx,
d6321d49
RK
4346 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4347 is_pse(vcpu), true);
ea2800dd
BS
4348
4349 if (!shadow_me_mask)
4350 return;
4351
4352 for (i = context->shadow_root_level; --i >= 0;) {
4353 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4354 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4355 }
4356
c258b62b
XG
4357}
4358EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4359
6fec2144
PB
4360static inline bool boot_cpu_is_amd(void)
4361{
4362 WARN_ON_ONCE(!tdp_enabled);
4363 return shadow_x_mask == 0;
4364}
4365
c258b62b
XG
4366/*
4367 * the direct page table on host, use as much mmu features as
4368 * possible, however, kvm currently does not do execution-protection.
4369 */
4370static void
4371reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4372 struct kvm_mmu *context)
4373{
ea2800dd
BS
4374 struct rsvd_bits_validate *shadow_zero_check;
4375 int i;
4376
4377 shadow_zero_check = &context->shadow_zero_check;
4378
6fec2144 4379 if (boot_cpu_is_amd())
ea2800dd 4380 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
c258b62b
XG
4381 boot_cpu_data.x86_phys_bits,
4382 context->shadow_root_level, false,
b8291adc
BP
4383 boot_cpu_has(X86_FEATURE_GBPAGES),
4384 true, true);
c258b62b 4385 else
ea2800dd 4386 __reset_rsvds_bits_mask_ept(shadow_zero_check,
c258b62b
XG
4387 boot_cpu_data.x86_phys_bits,
4388 false);
4389
ea2800dd
BS
4390 if (!shadow_me_mask)
4391 return;
4392
4393 for (i = context->shadow_root_level; --i >= 0;) {
4394 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4395 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4396 }
c258b62b
XG
4397}
4398
4399/*
4400 * as the comments in reset_shadow_zero_bits_mask() except it
4401 * is the shadow page table for intel nested guest.
4402 */
4403static void
4404reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4405 struct kvm_mmu *context, bool execonly)
4406{
4407 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4408 boot_cpu_data.x86_phys_bits, execonly);
4409}
4410
09f037aa
PB
4411#define BYTE_MASK(access) \
4412 ((1 & (access) ? 2 : 0) | \
4413 (2 & (access) ? 4 : 0) | \
4414 (3 & (access) ? 8 : 0) | \
4415 (4 & (access) ? 16 : 0) | \
4416 (5 & (access) ? 32 : 0) | \
4417 (6 & (access) ? 64 : 0) | \
4418 (7 & (access) ? 128 : 0))
4419
4420
edc90b7d
XG
4421static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4422 struct kvm_mmu *mmu, bool ept)
97d64b78 4423{
09f037aa
PB
4424 unsigned byte;
4425
4426 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4427 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4428 const u8 u = BYTE_MASK(ACC_USER_MASK);
4429
4430 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4431 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4432 bool cr0_wp = is_write_protection(vcpu);
97d64b78 4433
97d64b78 4434 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
09f037aa
PB
4435 unsigned pfec = byte << 1;
4436
97ec8c06 4437 /*
09f037aa
PB
4438 * Each "*f" variable has a 1 bit for each UWX value
4439 * that causes a fault with the given PFEC.
97ec8c06 4440 */
97d64b78 4441
09f037aa
PB
4442 /* Faults from writes to non-writable pages */
4443 u8 wf = (pfec & PFERR_WRITE_MASK) ? ~w : 0;
4444 /* Faults from user mode accesses to supervisor pages */
4445 u8 uf = (pfec & PFERR_USER_MASK) ? ~u : 0;
4446 /* Faults from fetches of non-executable pages*/
4447 u8 ff = (pfec & PFERR_FETCH_MASK) ? ~x : 0;
4448 /* Faults from kernel mode fetches of user pages */
4449 u8 smepf = 0;
4450 /* Faults from kernel mode accesses of user pages */
4451 u8 smapf = 0;
4452
4453 if (!ept) {
4454 /* Faults from kernel mode accesses to user pages */
4455 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4456
4457 /* Not really needed: !nx will cause pte.nx to fault */
4458 if (!mmu->nx)
4459 ff = 0;
4460
4461 /* Allow supervisor writes if !cr0.wp */
4462 if (!cr0_wp)
4463 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4464
4465 /* Disallow supervisor fetches of user code if cr4.smep */
4466 if (cr4_smep)
4467 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4468
4469 /*
4470 * SMAP:kernel-mode data accesses from user-mode
4471 * mappings should fault. A fault is considered
4472 * as a SMAP violation if all of the following
4473 * conditions are ture:
4474 * - X86_CR4_SMAP is set in CR4
4475 * - A user page is accessed
4476 * - The access is not a fetch
4477 * - Page fault in kernel mode
4478 * - if CPL = 3 or X86_EFLAGS_AC is clear
4479 *
4480 * Here, we cover the first three conditions.
4481 * The fourth is computed dynamically in permission_fault();
4482 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4483 * *not* subject to SMAP restrictions.
4484 */
4485 if (cr4_smap)
4486 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
97d64b78 4487 }
09f037aa
PB
4488
4489 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
97d64b78
AK
4490 }
4491}
4492
2d344105
HH
4493/*
4494* PKU is an additional mechanism by which the paging controls access to
4495* user-mode addresses based on the value in the PKRU register. Protection
4496* key violations are reported through a bit in the page fault error code.
4497* Unlike other bits of the error code, the PK bit is not known at the
4498* call site of e.g. gva_to_gpa; it must be computed directly in
4499* permission_fault based on two bits of PKRU, on some machine state (CR4,
4500* CR0, EFER, CPL), and on other bits of the error code and the page tables.
4501*
4502* In particular the following conditions come from the error code, the
4503* page tables and the machine state:
4504* - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4505* - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4506* - PK is always zero if U=0 in the page tables
4507* - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4508*
4509* The PKRU bitmask caches the result of these four conditions. The error
4510* code (minus the P bit) and the page table's U bit form an index into the
4511* PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4512* with the two bits of the PKRU register corresponding to the protection key.
4513* For the first three conditions above the bits will be 00, thus masking
4514* away both AD and WD. For all reads or if the last condition holds, WD
4515* only will be masked away.
4516*/
4517static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4518 bool ept)
4519{
4520 unsigned bit;
4521 bool wp;
4522
4523 if (ept) {
4524 mmu->pkru_mask = 0;
4525 return;
4526 }
4527
4528 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4529 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4530 mmu->pkru_mask = 0;
4531 return;
4532 }
4533
4534 wp = is_write_protection(vcpu);
4535
4536 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4537 unsigned pfec, pkey_bits;
4538 bool check_pkey, check_write, ff, uf, wf, pte_user;
4539
4540 pfec = bit << 1;
4541 ff = pfec & PFERR_FETCH_MASK;
4542 uf = pfec & PFERR_USER_MASK;
4543 wf = pfec & PFERR_WRITE_MASK;
4544
4545 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4546 pte_user = pfec & PFERR_RSVD_MASK;
4547
4548 /*
4549 * Only need to check the access which is not an
4550 * instruction fetch and is to a user page.
4551 */
4552 check_pkey = (!ff && pte_user);
4553 /*
4554 * write access is controlled by PKRU if it is a
4555 * user access or CR0.WP = 1.
4556 */
4557 check_write = check_pkey && wf && (uf || wp);
4558
4559 /* PKRU.AD stops both read and write access. */
4560 pkey_bits = !!check_pkey;
4561 /* PKRU.WD stops write access. */
4562 pkey_bits |= (!!check_write) << 1;
4563
4564 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4565 }
4566}
4567
6bb69c9b 4568static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6fd01b71 4569{
6bb69c9b
PB
4570 unsigned root_level = mmu->root_level;
4571
4572 mmu->last_nonleaf_level = root_level;
4573 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4574 mmu->last_nonleaf_level++;
6fd01b71
AK
4575}
4576
8a3c1a33
PB
4577static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4578 struct kvm_mmu *context,
4579 int level)
6aa8b732 4580{
2d48a985 4581 context->nx = is_nx(vcpu);
4d6931c3 4582 context->root_level = level;
2d48a985 4583
4d6931c3 4584 reset_rsvds_bits_mask(vcpu, context);
25d92081 4585 update_permission_bitmask(vcpu, context, false);
2d344105 4586 update_pkru_bitmask(vcpu, context, false);
6bb69c9b 4587 update_last_nonleaf_level(vcpu, context);
6aa8b732 4588
fa4a2c08 4589 MMU_WARN_ON(!is_pae(vcpu));
6aa8b732 4590 context->page_fault = paging64_page_fault;
6aa8b732 4591 context->gva_to_gpa = paging64_gva_to_gpa;
e8bc217a 4592 context->sync_page = paging64_sync_page;
a7052897 4593 context->invlpg = paging64_invlpg;
0f53b5b1 4594 context->update_pte = paging64_update_pte;
17ac10ad 4595 context->shadow_root_level = level;
c5a78f2b 4596 context->direct_map = false;
6aa8b732
AK
4597}
4598
8a3c1a33
PB
4599static void paging64_init_context(struct kvm_vcpu *vcpu,
4600 struct kvm_mmu *context)
17ac10ad 4601{
855feb67
YZ
4602 int root_level = is_la57_mode(vcpu) ?
4603 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4604
4605 paging64_init_context_common(vcpu, context, root_level);
17ac10ad
AK
4606}
4607
8a3c1a33
PB
4608static void paging32_init_context(struct kvm_vcpu *vcpu,
4609 struct kvm_mmu *context)
6aa8b732 4610{
2d48a985 4611 context->nx = false;
4d6931c3 4612 context->root_level = PT32_ROOT_LEVEL;
2d48a985 4613
4d6931c3 4614 reset_rsvds_bits_mask(vcpu, context);
25d92081 4615 update_permission_bitmask(vcpu, context, false);
2d344105 4616 update_pkru_bitmask(vcpu, context, false);
6bb69c9b 4617 update_last_nonleaf_level(vcpu, context);
6aa8b732 4618
6aa8b732 4619 context->page_fault = paging32_page_fault;
6aa8b732 4620 context->gva_to_gpa = paging32_gva_to_gpa;
e8bc217a 4621 context->sync_page = paging32_sync_page;
a7052897 4622 context->invlpg = paging32_invlpg;
0f53b5b1 4623 context->update_pte = paging32_update_pte;
6aa8b732 4624 context->shadow_root_level = PT32E_ROOT_LEVEL;
c5a78f2b 4625 context->direct_map = false;
6aa8b732
AK
4626}
4627
8a3c1a33
PB
4628static void paging32E_init_context(struct kvm_vcpu *vcpu,
4629 struct kvm_mmu *context)
6aa8b732 4630{
8a3c1a33 4631 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
6aa8b732
AK
4632}
4633
9fa72119
JS
4634static union kvm_mmu_page_role
4635kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu)
4636{
4637 union kvm_mmu_page_role role = {0};
4638
4639 role.guest_mode = is_guest_mode(vcpu);
4640 role.smm = is_smm(vcpu);
4641 role.ad_disabled = (shadow_accessed_mask == 0);
4642 role.level = kvm_x86_ops->get_tdp_level(vcpu);
4643 role.direct = true;
4644 role.access = ACC_ALL;
4645
4646 return role;
4647}
4648
8a3c1a33 4649static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
fb72d167 4650{
ad896af0 4651 struct kvm_mmu *context = &vcpu->arch.mmu;
fb72d167 4652
9fa72119
JS
4653 context->base_role.word = mmu_base_role_mask.word &
4654 kvm_calc_tdp_mmu_root_page_role(vcpu).word;
fb72d167 4655 context->page_fault = tdp_page_fault;
e8bc217a 4656 context->sync_page = nonpaging_sync_page;
a7052897 4657 context->invlpg = nonpaging_invlpg;
0f53b5b1 4658 context->update_pte = nonpaging_update_pte;
855feb67 4659 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
c5a78f2b 4660 context->direct_map = true;
1c97f0a0 4661 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
5777ed34 4662 context->get_cr3 = get_cr3;
e4e517b4 4663 context->get_pdptr = kvm_pdptr_read;
cb659db8 4664 context->inject_page_fault = kvm_inject_page_fault;
fb72d167
JR
4665
4666 if (!is_paging(vcpu)) {
2d48a985 4667 context->nx = false;
fb72d167
JR
4668 context->gva_to_gpa = nonpaging_gva_to_gpa;
4669 context->root_level = 0;
4670 } else if (is_long_mode(vcpu)) {
2d48a985 4671 context->nx = is_nx(vcpu);
855feb67
YZ
4672 context->root_level = is_la57_mode(vcpu) ?
4673 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4d6931c3
DB
4674 reset_rsvds_bits_mask(vcpu, context);
4675 context->gva_to_gpa = paging64_gva_to_gpa;
fb72d167 4676 } else if (is_pae(vcpu)) {
2d48a985 4677 context->nx = is_nx(vcpu);
fb72d167 4678 context->root_level = PT32E_ROOT_LEVEL;
4d6931c3
DB
4679 reset_rsvds_bits_mask(vcpu, context);
4680 context->gva_to_gpa = paging64_gva_to_gpa;
fb72d167 4681 } else {
2d48a985 4682 context->nx = false;
fb72d167 4683 context->root_level = PT32_ROOT_LEVEL;
4d6931c3
DB
4684 reset_rsvds_bits_mask(vcpu, context);
4685 context->gva_to_gpa = paging32_gva_to_gpa;
fb72d167
JR
4686 }
4687
25d92081 4688 update_permission_bitmask(vcpu, context, false);
2d344105 4689 update_pkru_bitmask(vcpu, context, false);
6bb69c9b 4690 update_last_nonleaf_level(vcpu, context);
c258b62b 4691 reset_tdp_shadow_zero_bits_mask(vcpu, context);
fb72d167
JR
4692}
4693
9fa72119
JS
4694static union kvm_mmu_page_role
4695kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu)
6aa8b732 4696{
9fa72119 4697 union kvm_mmu_page_role role = {0};
411c588d 4698 bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
edc90b7d 4699 bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
9fa72119
JS
4700
4701 role.nxe = is_nx(vcpu);
4702 role.cr4_pae = !!is_pae(vcpu);
4703 role.cr0_wp = is_write_protection(vcpu);
4704 role.smep_andnot_wp = smep && !is_write_protection(vcpu);
4705 role.smap_andnot_wp = smap && !is_write_protection(vcpu);
4706 role.guest_mode = is_guest_mode(vcpu);
4707 role.smm = is_smm(vcpu);
4708 role.direct = !is_paging(vcpu);
4709 role.access = ACC_ALL;
4710
4711 if (!is_long_mode(vcpu))
4712 role.level = PT32E_ROOT_LEVEL;
4713 else if (is_la57_mode(vcpu))
4714 role.level = PT64_ROOT_5LEVEL;
4715 else
4716 role.level = PT64_ROOT_4LEVEL;
4717
4718 return role;
4719}
4720
4721void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4722{
ad896af0
PB
4723 struct kvm_mmu *context = &vcpu->arch.mmu;
4724
6aa8b732 4725 if (!is_paging(vcpu))
8a3c1a33 4726 nonpaging_init_context(vcpu, context);
a9058ecd 4727 else if (is_long_mode(vcpu))
8a3c1a33 4728 paging64_init_context(vcpu, context);
6aa8b732 4729 else if (is_pae(vcpu))
8a3c1a33 4730 paging32E_init_context(vcpu, context);
6aa8b732 4731 else
8a3c1a33 4732 paging32_init_context(vcpu, context);
a770f6f2 4733
9fa72119
JS
4734 context->base_role.word = mmu_base_role_mask.word &
4735 kvm_calc_shadow_mmu_root_page_role(vcpu).word;
c258b62b 4736 reset_shadow_zero_bits_mask(vcpu, context);
52fde8df
JR
4737}
4738EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4739
9fa72119
JS
4740static union kvm_mmu_page_role
4741kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty)
4742{
4743 union kvm_mmu_page_role role = vcpu->arch.mmu.base_role;
4744
4745 role.level = PT64_ROOT_4LEVEL;
4746 role.direct = false;
4747 role.ad_disabled = !accessed_dirty;
4748 role.guest_mode = true;
4749 role.access = ACC_ALL;
4750
4751 return role;
4752}
4753
ae1e2d10 4754void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
50c28f21 4755 bool accessed_dirty, gpa_t new_eptp)
155a97a3 4756{
ad896af0 4757 struct kvm_mmu *context = &vcpu->arch.mmu;
9fa72119
JS
4758 union kvm_mmu_page_role root_page_role =
4759 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty);
ad896af0 4760
ade61e28 4761 __kvm_mmu_new_cr3(vcpu, new_eptp, root_page_role, false);
855feb67 4762 context->shadow_root_level = PT64_ROOT_4LEVEL;
155a97a3
NHE
4763
4764 context->nx = true;
ae1e2d10 4765 context->ept_ad = accessed_dirty;
155a97a3
NHE
4766 context->page_fault = ept_page_fault;
4767 context->gva_to_gpa = ept_gva_to_gpa;
4768 context->sync_page = ept_sync_page;
4769 context->invlpg = ept_invlpg;
4770 context->update_pte = ept_update_pte;
855feb67 4771 context->root_level = PT64_ROOT_4LEVEL;
155a97a3 4772 context->direct_map = false;
9fa72119 4773 context->base_role.word = root_page_role.word & mmu_base_role_mask.word;
155a97a3 4774 update_permission_bitmask(vcpu, context, true);
2d344105 4775 update_pkru_bitmask(vcpu, context, true);
fd19d3b4 4776 update_last_nonleaf_level(vcpu, context);
155a97a3 4777 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
c258b62b 4778 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
155a97a3
NHE
4779}
4780EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4781
8a3c1a33 4782static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
52fde8df 4783{
ad896af0
PB
4784 struct kvm_mmu *context = &vcpu->arch.mmu;
4785
4786 kvm_init_shadow_mmu(vcpu);
4787 context->set_cr3 = kvm_x86_ops->set_cr3;
4788 context->get_cr3 = get_cr3;
4789 context->get_pdptr = kvm_pdptr_read;
4790 context->inject_page_fault = kvm_inject_page_fault;
6aa8b732
AK
4791}
4792
8a3c1a33 4793static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
02f59dc9
JR
4794{
4795 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4796
4797 g_context->get_cr3 = get_cr3;
e4e517b4 4798 g_context->get_pdptr = kvm_pdptr_read;
02f59dc9
JR
4799 g_context->inject_page_fault = kvm_inject_page_fault;
4800
4801 /*
0af2593b
DM
4802 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
4803 * L1's nested page tables (e.g. EPT12). The nested translation
4804 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4805 * L2's page tables as the first level of translation and L1's
4806 * nested page tables as the second level of translation. Basically
4807 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
02f59dc9
JR
4808 */
4809 if (!is_paging(vcpu)) {
2d48a985 4810 g_context->nx = false;
02f59dc9
JR
4811 g_context->root_level = 0;
4812 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4813 } else if (is_long_mode(vcpu)) {
2d48a985 4814 g_context->nx = is_nx(vcpu);
855feb67
YZ
4815 g_context->root_level = is_la57_mode(vcpu) ?
4816 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4d6931c3 4817 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
4818 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4819 } else if (is_pae(vcpu)) {
2d48a985 4820 g_context->nx = is_nx(vcpu);
02f59dc9 4821 g_context->root_level = PT32E_ROOT_LEVEL;
4d6931c3 4822 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
4823 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4824 } else {
2d48a985 4825 g_context->nx = false;
02f59dc9 4826 g_context->root_level = PT32_ROOT_LEVEL;
4d6931c3 4827 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
4828 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4829 }
4830
25d92081 4831 update_permission_bitmask(vcpu, g_context, false);
2d344105 4832 update_pkru_bitmask(vcpu, g_context, false);
6bb69c9b 4833 update_last_nonleaf_level(vcpu, g_context);
02f59dc9
JR
4834}
4835
1c53da3f 4836void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
fb72d167 4837{
1c53da3f
JS
4838 if (reset_roots) {
4839 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4840 vcpu->arch.mmu.prev_root = KVM_MMU_ROOT_INFO_INVALID;
4841 }
4842
02f59dc9 4843 if (mmu_is_nested(vcpu))
e0c6db3e 4844 init_kvm_nested_mmu(vcpu);
02f59dc9 4845 else if (tdp_enabled)
e0c6db3e 4846 init_kvm_tdp_mmu(vcpu);
fb72d167 4847 else
e0c6db3e 4848 init_kvm_softmmu(vcpu);
fb72d167 4849}
1c53da3f 4850EXPORT_SYMBOL_GPL(kvm_init_mmu);
fb72d167 4851
9fa72119
JS
4852static union kvm_mmu_page_role
4853kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
4854{
4855 if (tdp_enabled)
4856 return kvm_calc_tdp_mmu_root_page_role(vcpu);
4857 else
4858 return kvm_calc_shadow_mmu_root_page_role(vcpu);
4859}
4860
8a3c1a33 4861void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
6aa8b732 4862{
95f93af4 4863 kvm_mmu_unload(vcpu);
1c53da3f 4864 kvm_init_mmu(vcpu, true);
17c3ba9d 4865}
8668a3c4 4866EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
17c3ba9d
AK
4867
4868int kvm_mmu_load(struct kvm_vcpu *vcpu)
6aa8b732 4869{
714b93da
AK
4870 int r;
4871
e2dec939 4872 r = mmu_topup_memory_caches(vcpu);
17c3ba9d
AK
4873 if (r)
4874 goto out;
8986ecc0 4875 r = mmu_alloc_roots(vcpu);
e2858b4a 4876 kvm_mmu_sync_roots(vcpu);
8986ecc0
MT
4877 if (r)
4878 goto out;
6e42782f 4879 kvm_mmu_load_cr3(vcpu);
afe828d1 4880 kvm_x86_ops->tlb_flush(vcpu, true);
714b93da
AK
4881out:
4882 return r;
6aa8b732 4883}
17c3ba9d
AK
4884EXPORT_SYMBOL_GPL(kvm_mmu_load);
4885
4886void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4887{
7c390d35 4888 kvm_mmu_free_roots(vcpu, true);
95f93af4 4889 WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
17c3ba9d 4890}
4b16184c 4891EXPORT_SYMBOL_GPL(kvm_mmu_unload);
6aa8b732 4892
0028425f 4893static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
7c562522
XG
4894 struct kvm_mmu_page *sp, u64 *spte,
4895 const void *new)
0028425f 4896{
30945387 4897 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
7e4e4056
JR
4898 ++vcpu->kvm->stat.mmu_pde_zapped;
4899 return;
30945387 4900 }
0028425f 4901
4cee5764 4902 ++vcpu->kvm->stat.mmu_pte_updated;
7c562522 4903 vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
0028425f
AK
4904}
4905
79539cec
AK
4906static bool need_remote_flush(u64 old, u64 new)
4907{
4908 if (!is_shadow_present_pte(old))
4909 return false;
4910 if (!is_shadow_present_pte(new))
4911 return true;
4912 if ((old ^ new) & PT64_BASE_ADDR_MASK)
4913 return true;
53166229
GN
4914 old ^= shadow_nx_mask;
4915 new ^= shadow_nx_mask;
79539cec
AK
4916 return (old & ~new & PT64_PERM_MASK) != 0;
4917}
4918
889e5cbc
XG
4919static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4920 const u8 *new, int *bytes)
da4a00f0 4921{
889e5cbc
XG
4922 u64 gentry;
4923 int r;
72016f3a 4924
72016f3a
AK
4925 /*
4926 * Assume that the pte write on a page table of the same type
49b26e26
XG
4927 * as the current vcpu paging mode since we update the sptes only
4928 * when they have the same mode.
72016f3a 4929 */
889e5cbc 4930 if (is_pae(vcpu) && *bytes == 4) {
72016f3a 4931 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
889e5cbc
XG
4932 *gpa &= ~(gpa_t)7;
4933 *bytes = 8;
54bf36aa 4934 r = kvm_vcpu_read_guest(vcpu, *gpa, &gentry, 8);
72016f3a
AK
4935 if (r)
4936 gentry = 0;
08e850c6
AK
4937 new = (const u8 *)&gentry;
4938 }
4939
889e5cbc 4940 switch (*bytes) {
08e850c6
AK
4941 case 4:
4942 gentry = *(const u32 *)new;
4943 break;
4944 case 8:
4945 gentry = *(const u64 *)new;
4946 break;
4947 default:
4948 gentry = 0;
4949 break;
72016f3a
AK
4950 }
4951
889e5cbc
XG
4952 return gentry;
4953}
4954
4955/*
4956 * If we're seeing too many writes to a page, it may no longer be a page table,
4957 * or we may be forking, in which case it is better to unmap the page.
4958 */
a138fe75 4959static bool detect_write_flooding(struct kvm_mmu_page *sp)
889e5cbc 4960{
a30f47cb
XG
4961 /*
4962 * Skip write-flooding detected for the sp whose level is 1, because
4963 * it can become unsync, then the guest page is not write-protected.
4964 */
f71fa31f 4965 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
a30f47cb 4966 return false;
3246af0e 4967
e5691a81
XG
4968 atomic_inc(&sp->write_flooding_count);
4969 return atomic_read(&sp->write_flooding_count) >= 3;
889e5cbc
XG
4970}
4971
4972/*
4973 * Misaligned accesses are too much trouble to fix up; also, they usually
4974 * indicate a page is not used as a page table.
4975 */
4976static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4977 int bytes)
4978{
4979 unsigned offset, pte_size, misaligned;
4980
4981 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4982 gpa, bytes, sp->role.word);
4983
4984 offset = offset_in_page(gpa);
4985 pte_size = sp->role.cr4_pae ? 8 : 4;
5d9ca30e
XG
4986
4987 /*
4988 * Sometimes, the OS only writes the last one bytes to update status
4989 * bits, for example, in linux, andb instruction is used in clear_bit().
4990 */
4991 if (!(offset & (pte_size - 1)) && bytes == 1)
4992 return false;
4993
889e5cbc
XG
4994 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4995 misaligned |= bytes < 4;
4996
4997 return misaligned;
4998}
4999
5000static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5001{
5002 unsigned page_offset, quadrant;
5003 u64 *spte;
5004 int level;
5005
5006 page_offset = offset_in_page(gpa);
5007 level = sp->role.level;
5008 *nspte = 1;
5009 if (!sp->role.cr4_pae) {
5010 page_offset <<= 1; /* 32->64 */
5011 /*
5012 * A 32-bit pde maps 4MB while the shadow pdes map
5013 * only 2MB. So we need to double the offset again
5014 * and zap two pdes instead of one.
5015 */
5016 if (level == PT32_ROOT_LEVEL) {
5017 page_offset &= ~7; /* kill rounding error */
5018 page_offset <<= 1;
5019 *nspte = 2;
5020 }
5021 quadrant = page_offset >> PAGE_SHIFT;
5022 page_offset &= ~PAGE_MASK;
5023 if (quadrant != sp->role.quadrant)
5024 return NULL;
5025 }
5026
5027 spte = &sp->spt[page_offset / sizeof(*spte)];
5028 return spte;
5029}
5030
13d268ca 5031static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
d126363d
JS
5032 const u8 *new, int bytes,
5033 struct kvm_page_track_notifier_node *node)
889e5cbc
XG
5034{
5035 gfn_t gfn = gpa >> PAGE_SHIFT;
889e5cbc 5036 struct kvm_mmu_page *sp;
889e5cbc
XG
5037 LIST_HEAD(invalid_list);
5038 u64 entry, gentry, *spte;
5039 int npte;
b8c67b7a 5040 bool remote_flush, local_flush;
889e5cbc
XG
5041
5042 /*
5043 * If we don't have indirect shadow pages, it means no page is
5044 * write-protected, so we can exit simply.
5045 */
6aa7de05 5046 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
889e5cbc
XG
5047 return;
5048
b8c67b7a 5049 remote_flush = local_flush = false;
889e5cbc
XG
5050
5051 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5052
5053 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes);
5054
5055 /*
5056 * No need to care whether allocation memory is successful
5057 * or not since pte prefetch is skiped if it does not have
5058 * enough objects in the cache.
5059 */
5060 mmu_topup_memory_caches(vcpu);
5061
5062 spin_lock(&vcpu->kvm->mmu_lock);
5063 ++vcpu->kvm->stat.mmu_pte_write;
0375f7fa 5064 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
889e5cbc 5065
b67bfe0d 5066 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
a30f47cb 5067 if (detect_write_misaligned(sp, gpa, bytes) ||
a138fe75 5068 detect_write_flooding(sp)) {
b8c67b7a 5069 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
4cee5764 5070 ++vcpu->kvm->stat.mmu_flooded;
0e7bc4b9
AK
5071 continue;
5072 }
889e5cbc
XG
5073
5074 spte = get_written_sptes(sp, gpa, &npte);
5075 if (!spte)
5076 continue;
5077
0671a8e7 5078 local_flush = true;
ac1b714e 5079 while (npte--) {
79539cec 5080 entry = *spte;
38e3b2b2 5081 mmu_page_zap_pte(vcpu->kvm, sp, spte);
fa1de2bf
XG
5082 if (gentry &&
5083 !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
9fa72119 5084 & mmu_base_role_mask.word) && rmap_can_add(vcpu))
7c562522 5085 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
9bb4f6b1 5086 if (need_remote_flush(entry, *spte))
0671a8e7 5087 remote_flush = true;
ac1b714e 5088 ++spte;
9b7a0325 5089 }
9b7a0325 5090 }
b8c67b7a 5091 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
0375f7fa 5092 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
aaee2c94 5093 spin_unlock(&vcpu->kvm->mmu_lock);
da4a00f0
AK
5094}
5095
a436036b
AK
5096int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5097{
10589a46
MT
5098 gpa_t gpa;
5099 int r;
a436036b 5100
c5a78f2b 5101 if (vcpu->arch.mmu.direct_map)
60f24784
AK
5102 return 0;
5103
1871c602 5104 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
10589a46 5105
10589a46 5106 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1cb3f3ae 5107
10589a46 5108 return r;
a436036b 5109}
577bdc49 5110EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
a436036b 5111
26eeb53c 5112static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
ebeace86 5113{
d98ba053 5114 LIST_HEAD(invalid_list);
103ad25a 5115
81f4f76b 5116 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
26eeb53c 5117 return 0;
81f4f76b 5118
5da59607
TY
5119 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5120 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5121 break;
ebeace86 5122
4cee5764 5123 ++vcpu->kvm->stat.mmu_recycled;
ebeace86 5124 }
aa6bd187 5125 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
26eeb53c
WL
5126
5127 if (!kvm_mmu_available_pages(vcpu->kvm))
5128 return -ENOSPC;
5129 return 0;
ebeace86 5130}
ebeace86 5131
14727754 5132int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
dc25e89e 5133 void *insn, int insn_len)
3067714c 5134{
1cb3f3ae 5135 int r, emulation_type = EMULTYPE_RETRY;
3067714c 5136 enum emulation_result er;
9034e6e8 5137 bool direct = vcpu->arch.mmu.direct_map;
3067714c 5138
618232e2
BS
5139 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5140 if (vcpu->arch.mmu.direct_map) {
5141 vcpu->arch.gpa_available = true;
5142 vcpu->arch.gpa_val = cr2;
5143 }
3067714c 5144
9b8ebbdb 5145 r = RET_PF_INVALID;
e9ee956e
TY
5146 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5147 r = handle_mmio_page_fault(vcpu, cr2, direct);
9b8ebbdb 5148 if (r == RET_PF_EMULATE) {
e9ee956e
TY
5149 emulation_type = 0;
5150 goto emulate;
5151 }
e9ee956e 5152 }
3067714c 5153
9b8ebbdb
PB
5154 if (r == RET_PF_INVALID) {
5155 r = vcpu->arch.mmu.page_fault(vcpu, cr2, lower_32_bits(error_code),
5156 false);
5157 WARN_ON(r == RET_PF_INVALID);
5158 }
5159
5160 if (r == RET_PF_RETRY)
5161 return 1;
3067714c 5162 if (r < 0)
e9ee956e 5163 return r;
3067714c 5164
14727754
TL
5165 /*
5166 * Before emulating the instruction, check if the error code
5167 * was due to a RO violation while translating the guest page.
5168 * This can occur when using nested virtualization with nested
5169 * paging in both guests. If true, we simply unprotect the page
5170 * and resume the guest.
14727754 5171 */
64531a3b 5172 if (vcpu->arch.mmu.direct_map &&
eebed243 5173 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
14727754
TL
5174 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5175 return 1;
5176 }
5177
ded58749 5178 if (mmio_info_in_cache(vcpu, cr2, direct))
1cb3f3ae 5179 emulation_type = 0;
e9ee956e 5180emulate:
00b10fe1
BS
5181 /*
5182 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5183 * This can happen if a guest gets a page-fault on data access but the HW
5184 * table walker is not able to read the instruction page (e.g instruction
5185 * page is not present in memory). In those cases we simply restart the
5186 * guest.
5187 */
5188 if (unlikely(insn && !insn_len))
5189 return 1;
5190
1cb3f3ae 5191 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
3067714c
AK
5192
5193 switch (er) {
5194 case EMULATE_DONE:
5195 return 1;
ac0a48c3 5196 case EMULATE_USER_EXIT:
3067714c 5197 ++vcpu->stat.mmio_exits;
6d77dbfc 5198 /* fall through */
3067714c 5199 case EMULATE_FAIL:
3f5d18a9 5200 return 0;
3067714c
AK
5201 default:
5202 BUG();
5203 }
3067714c
AK
5204}
5205EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5206
a7052897
MT
5207void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5208{
7eb77e9f
JS
5209 struct kvm_mmu *mmu = &vcpu->arch.mmu;
5210
5211 mmu->invlpg(vcpu, gva, mmu->root_hpa);
77c3913b 5212 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
a7052897
MT
5213 ++vcpu->stat.invlpg;
5214}
5215EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5216
eb4b248e
JS
5217void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5218{
5219 struct kvm_mmu *mmu = &vcpu->arch.mmu;
5220
5221 if (pcid == kvm_get_active_pcid(vcpu)) {
7eb77e9f 5222 mmu->invlpg(vcpu, gva, mmu->root_hpa);
eb4b248e
JS
5223 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5224 }
5225
ade61e28
JS
5226 if (VALID_PAGE(mmu->prev_root.hpa) &&
5227 pcid == kvm_get_pcid(vcpu, mmu->prev_root.cr3))
5228 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5229
eb4b248e
JS
5230 ++vcpu->stat.invlpg;
5231
5232 /*
ade61e28
JS
5233 * Mappings not reachable via the current cr3 or the prev_root.cr3 will
5234 * be synced when switching to that cr3, so nothing needs to be done
5235 * here for them.
eb4b248e
JS
5236 */
5237}
5238EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5239
18552672
JR
5240void kvm_enable_tdp(void)
5241{
5242 tdp_enabled = true;
5243}
5244EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5245
5f4cb662
JR
5246void kvm_disable_tdp(void)
5247{
5248 tdp_enabled = false;
5249}
5250EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5251
6aa8b732
AK
5252static void free_mmu_pages(struct kvm_vcpu *vcpu)
5253{
ad312c7c 5254 free_page((unsigned long)vcpu->arch.mmu.pae_root);
87ca74ad 5255 free_page((unsigned long)vcpu->arch.mmu.lm_root);
6aa8b732
AK
5256}
5257
5258static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5259{
17ac10ad 5260 struct page *page;
6aa8b732
AK
5261 int i;
5262
17ac10ad
AK
5263 /*
5264 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5265 * Therefore we need to allocate shadow page tables in the first
5266 * 4GB of memory, which happens to fit the DMA32 zone.
5267 */
5268 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
5269 if (!page)
d7fa6ab2
WY
5270 return -ENOMEM;
5271
ad312c7c 5272 vcpu->arch.mmu.pae_root = page_address(page);
17ac10ad 5273 for (i = 0; i < 4; ++i)
ad312c7c 5274 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
17ac10ad 5275
6aa8b732 5276 return 0;
6aa8b732
AK
5277}
5278
8018c27b 5279int kvm_mmu_create(struct kvm_vcpu *vcpu)
6aa8b732 5280{
e459e322
XG
5281 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
5282 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
7c390d35 5283 vcpu->arch.mmu.prev_root = KVM_MMU_ROOT_INFO_INVALID;
e459e322
XG
5284 vcpu->arch.mmu.translate_gpa = translate_gpa;
5285 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
6aa8b732 5286
8018c27b
IM
5287 return alloc_mmu_pages(vcpu);
5288}
6aa8b732 5289
8a3c1a33 5290void kvm_mmu_setup(struct kvm_vcpu *vcpu)
8018c27b 5291{
fa4a2c08 5292 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2c264957 5293
1c53da3f 5294 kvm_init_mmu(vcpu, true);
6aa8b732
AK
5295}
5296
b5f5fdca 5297static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
d126363d
JS
5298 struct kvm_memory_slot *slot,
5299 struct kvm_page_track_notifier_node *node)
b5f5fdca
XC
5300{
5301 kvm_mmu_invalidate_zap_all_pages(kvm);
5302}
5303
13d268ca
XG
5304void kvm_mmu_init_vm(struct kvm *kvm)
5305{
5306 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5307
5308 node->track_write = kvm_mmu_pte_write;
b5f5fdca 5309 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
13d268ca
XG
5310 kvm_page_track_register_notifier(kvm, node);
5311}
5312
5313void kvm_mmu_uninit_vm(struct kvm *kvm)
5314{
5315 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5316
5317 kvm_page_track_unregister_notifier(kvm, node);
5318}
5319
1bad2b2a 5320/* The return value indicates if tlb flush on all vcpus is needed. */
018aabb5 5321typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
1bad2b2a
XG
5322
5323/* The caller should hold mmu-lock before calling this function. */
928a4c39 5324static __always_inline bool
1bad2b2a
XG
5325slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5326 slot_level_handler fn, int start_level, int end_level,
5327 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5328{
5329 struct slot_rmap_walk_iterator iterator;
5330 bool flush = false;
5331
5332 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5333 end_gfn, &iterator) {
5334 if (iterator.rmap)
5335 flush |= fn(kvm, iterator.rmap);
5336
5337 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5338 if (flush && lock_flush_tlb) {
5339 kvm_flush_remote_tlbs(kvm);
5340 flush = false;
5341 }
5342 cond_resched_lock(&kvm->mmu_lock);
5343 }
5344 }
5345
5346 if (flush && lock_flush_tlb) {
5347 kvm_flush_remote_tlbs(kvm);
5348 flush = false;
5349 }
5350
5351 return flush;
5352}
5353
928a4c39 5354static __always_inline bool
1bad2b2a
XG
5355slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5356 slot_level_handler fn, int start_level, int end_level,
5357 bool lock_flush_tlb)
5358{
5359 return slot_handle_level_range(kvm, memslot, fn, start_level,
5360 end_level, memslot->base_gfn,
5361 memslot->base_gfn + memslot->npages - 1,
5362 lock_flush_tlb);
5363}
5364
928a4c39 5365static __always_inline bool
1bad2b2a
XG
5366slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5367 slot_level_handler fn, bool lock_flush_tlb)
5368{
5369 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5370 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5371}
5372
928a4c39 5373static __always_inline bool
1bad2b2a
XG
5374slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5375 slot_level_handler fn, bool lock_flush_tlb)
5376{
5377 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5378 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5379}
5380
928a4c39 5381static __always_inline bool
1bad2b2a
XG
5382slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5383 slot_level_handler fn, bool lock_flush_tlb)
5384{
5385 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5386 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5387}
5388
efdfe536
XG
5389void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5390{
5391 struct kvm_memslots *slots;
5392 struct kvm_memory_slot *memslot;
9da0e4d5 5393 int i;
efdfe536
XG
5394
5395 spin_lock(&kvm->mmu_lock);
9da0e4d5
PB
5396 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5397 slots = __kvm_memslots(kvm, i);
5398 kvm_for_each_memslot(memslot, slots) {
5399 gfn_t start, end;
5400
5401 start = max(gfn_start, memslot->base_gfn);
5402 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5403 if (start >= end)
5404 continue;
efdfe536 5405
9da0e4d5
PB
5406 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5407 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5408 start, end - 1, true);
5409 }
efdfe536
XG
5410 }
5411
5412 spin_unlock(&kvm->mmu_lock);
5413}
5414
018aabb5
TY
5415static bool slot_rmap_write_protect(struct kvm *kvm,
5416 struct kvm_rmap_head *rmap_head)
d77aa73c 5417{
018aabb5 5418 return __rmap_write_protect(kvm, rmap_head, false);
d77aa73c
XG
5419}
5420
1c91cad4
KH
5421void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5422 struct kvm_memory_slot *memslot)
6aa8b732 5423{
d77aa73c 5424 bool flush;
6aa8b732 5425
9d1beefb 5426 spin_lock(&kvm->mmu_lock);
d77aa73c
XG
5427 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5428 false);
9d1beefb 5429 spin_unlock(&kvm->mmu_lock);
198c74f4
XG
5430
5431 /*
5432 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5433 * which do tlb flush out of mmu-lock should be serialized by
5434 * kvm->slots_lock otherwise tlb flush would be missed.
5435 */
5436 lockdep_assert_held(&kvm->slots_lock);
5437
5438 /*
5439 * We can flush all the TLBs out of the mmu lock without TLB
5440 * corruption since we just change the spte from writable to
5441 * readonly so that we only need to care the case of changing
5442 * spte from present to present (changing the spte from present
5443 * to nonpresent will flush all the TLBs immediately), in other
5444 * words, the only case we care is mmu_spte_update() where we
5445 * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5446 * instead of PT_WRITABLE_MASK, that means it does not depend
5447 * on PT_WRITABLE_MASK anymore.
5448 */
d91ffee9
KH
5449 if (flush)
5450 kvm_flush_remote_tlbs(kvm);
6aa8b732 5451}
37a7d8b0 5452
3ea3b7fa 5453static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
018aabb5 5454 struct kvm_rmap_head *rmap_head)
3ea3b7fa
WL
5455{
5456 u64 *sptep;
5457 struct rmap_iterator iter;
5458 int need_tlb_flush = 0;
ba049e93 5459 kvm_pfn_t pfn;
3ea3b7fa
WL
5460 struct kvm_mmu_page *sp;
5461
0d536790 5462restart:
018aabb5 5463 for_each_rmap_spte(rmap_head, &iter, sptep) {
3ea3b7fa
WL
5464 sp = page_header(__pa(sptep));
5465 pfn = spte_to_pfn(*sptep);
5466
5467 /*
decf6333
XG
5468 * We cannot do huge page mapping for indirect shadow pages,
5469 * which are found on the last rmap (level = 1) when not using
5470 * tdp; such shadow pages are synced with the page table in
5471 * the guest, and the guest page table is using 4K page size
5472 * mapping if the indirect sp has level = 1.
3ea3b7fa
WL
5473 */
5474 if (sp->role.direct &&
5475 !kvm_is_reserved_pfn(pfn) &&
127393fb 5476 PageTransCompoundMap(pfn_to_page(pfn))) {
3ea3b7fa 5477 drop_spte(kvm, sptep);
3ea3b7fa 5478 need_tlb_flush = 1;
0d536790
XG
5479 goto restart;
5480 }
3ea3b7fa
WL
5481 }
5482
5483 return need_tlb_flush;
5484}
5485
5486void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
f36f3f28 5487 const struct kvm_memory_slot *memslot)
3ea3b7fa 5488{
f36f3f28 5489 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
3ea3b7fa 5490 spin_lock(&kvm->mmu_lock);
f36f3f28
PB
5491 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5492 kvm_mmu_zap_collapsible_spte, true);
3ea3b7fa
WL
5493 spin_unlock(&kvm->mmu_lock);
5494}
5495
f4b4b180
KH
5496void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5497 struct kvm_memory_slot *memslot)
5498{
d77aa73c 5499 bool flush;
f4b4b180
KH
5500
5501 spin_lock(&kvm->mmu_lock);
d77aa73c 5502 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
f4b4b180
KH
5503 spin_unlock(&kvm->mmu_lock);
5504
5505 lockdep_assert_held(&kvm->slots_lock);
5506
5507 /*
5508 * It's also safe to flush TLBs out of mmu lock here as currently this
5509 * function is only used for dirty logging, in which case flushing TLB
5510 * out of mmu lock also guarantees no dirty pages will be lost in
5511 * dirty_bitmap.
5512 */
5513 if (flush)
5514 kvm_flush_remote_tlbs(kvm);
5515}
5516EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5517
5518void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5519 struct kvm_memory_slot *memslot)
5520{
d77aa73c 5521 bool flush;
f4b4b180
KH
5522
5523 spin_lock(&kvm->mmu_lock);
d77aa73c
XG
5524 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5525 false);
f4b4b180
KH
5526 spin_unlock(&kvm->mmu_lock);
5527
5528 /* see kvm_mmu_slot_remove_write_access */
5529 lockdep_assert_held(&kvm->slots_lock);
5530
5531 if (flush)
5532 kvm_flush_remote_tlbs(kvm);
5533}
5534EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5535
5536void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5537 struct kvm_memory_slot *memslot)
5538{
d77aa73c 5539 bool flush;
f4b4b180
KH
5540
5541 spin_lock(&kvm->mmu_lock);
d77aa73c 5542 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
f4b4b180
KH
5543 spin_unlock(&kvm->mmu_lock);
5544
5545 lockdep_assert_held(&kvm->slots_lock);
5546
5547 /* see kvm_mmu_slot_leaf_clear_dirty */
5548 if (flush)
5549 kvm_flush_remote_tlbs(kvm);
5550}
5551EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5552
e7d11c7a 5553#define BATCH_ZAP_PAGES 10
5304b8d3
XG
5554static void kvm_zap_obsolete_pages(struct kvm *kvm)
5555{
5556 struct kvm_mmu_page *sp, *node;
e7d11c7a 5557 int batch = 0;
5304b8d3
XG
5558
5559restart:
5560 list_for_each_entry_safe_reverse(sp, node,
5561 &kvm->arch.active_mmu_pages, link) {
e7d11c7a
XG
5562 int ret;
5563
5304b8d3
XG
5564 /*
5565 * No obsolete page exists before new created page since
5566 * active_mmu_pages is the FIFO list.
5567 */
5568 if (!is_obsolete_sp(kvm, sp))
5569 break;
5570
5571 /*
5304b8d3
XG
5572 * Since we are reversely walking the list and the invalid
5573 * list will be moved to the head, skip the invalid page
5574 * can help us to avoid the infinity list walking.
5575 */
5576 if (sp->role.invalid)
5577 continue;
5578
f34d251d
XG
5579 /*
5580 * Need not flush tlb since we only zap the sp with invalid
5581 * generation number.
5582 */
e7d11c7a 5583 if (batch >= BATCH_ZAP_PAGES &&
f34d251d 5584 cond_resched_lock(&kvm->mmu_lock)) {
e7d11c7a 5585 batch = 0;
5304b8d3
XG
5586 goto restart;
5587 }
5588
365c8868
XG
5589 ret = kvm_mmu_prepare_zap_page(kvm, sp,
5590 &kvm->arch.zapped_obsolete_pages);
e7d11c7a
XG
5591 batch += ret;
5592
5593 if (ret)
5304b8d3
XG
5594 goto restart;
5595 }
5596
f34d251d
XG
5597 /*
5598 * Should flush tlb before free page tables since lockless-walking
5599 * may use the pages.
5600 */
365c8868 5601 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5304b8d3
XG
5602}
5603
5604/*
5605 * Fast invalidate all shadow pages and use lock-break technique
5606 * to zap obsolete pages.
5607 *
5608 * It's required when memslot is being deleted or VM is being
5609 * destroyed, in these cases, we should ensure that KVM MMU does
5610 * not use any resource of the being-deleted slot or all slots
5611 * after calling the function.
5612 */
5613void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5614{
5615 spin_lock(&kvm->mmu_lock);
35006126 5616 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5304b8d3
XG
5617 kvm->arch.mmu_valid_gen++;
5618
f34d251d
XG
5619 /*
5620 * Notify all vcpus to reload its shadow page table
5621 * and flush TLB. Then all vcpus will switch to new
5622 * shadow page table with the new mmu_valid_gen.
5623 *
5624 * Note: we should do this under the protection of
5625 * mmu-lock, otherwise, vcpu would purge shadow page
5626 * but miss tlb flush.
5627 */
5628 kvm_reload_remote_mmus(kvm);
5629
5304b8d3
XG
5630 kvm_zap_obsolete_pages(kvm);
5631 spin_unlock(&kvm->mmu_lock);
5632}
5633
365c8868
XG
5634static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5635{
5636 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5637}
5638
54bf36aa 5639void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, struct kvm_memslots *slots)
f8f55942
XG
5640{
5641 /*
5642 * The very rare case: if the generation-number is round,
5643 * zap all shadow pages.
f8f55942 5644 */
54bf36aa 5645 if (unlikely((slots->generation & MMIO_GEN_MASK) == 0)) {
ae0f5499 5646 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
a8eca9dc 5647 kvm_mmu_invalidate_zap_all_pages(kvm);
7a2e8aaf 5648 }
f8f55942
XG
5649}
5650
70534a73
DC
5651static unsigned long
5652mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
3ee16c81
IE
5653{
5654 struct kvm *kvm;
1495f230 5655 int nr_to_scan = sc->nr_to_scan;
70534a73 5656 unsigned long freed = 0;
3ee16c81 5657
2f303b74 5658 spin_lock(&kvm_lock);
3ee16c81
IE
5659
5660 list_for_each_entry(kvm, &vm_list, vm_list) {
3d56cbdf 5661 int idx;
d98ba053 5662 LIST_HEAD(invalid_list);
3ee16c81 5663
35f2d16b
TY
5664 /*
5665 * Never scan more than sc->nr_to_scan VM instances.
5666 * Will not hit this condition practically since we do not try
5667 * to shrink more than one VM and it is very unlikely to see
5668 * !n_used_mmu_pages so many times.
5669 */
5670 if (!nr_to_scan--)
5671 break;
19526396
GN
5672 /*
5673 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5674 * here. We may skip a VM instance errorneosly, but we do not
5675 * want to shrink a VM that only started to populate its MMU
5676 * anyway.
5677 */
365c8868
XG
5678 if (!kvm->arch.n_used_mmu_pages &&
5679 !kvm_has_zapped_obsolete_pages(kvm))
19526396 5680 continue;
19526396 5681
f656ce01 5682 idx = srcu_read_lock(&kvm->srcu);
3ee16c81 5683 spin_lock(&kvm->mmu_lock);
3ee16c81 5684
365c8868
XG
5685 if (kvm_has_zapped_obsolete_pages(kvm)) {
5686 kvm_mmu_commit_zap_page(kvm,
5687 &kvm->arch.zapped_obsolete_pages);
5688 goto unlock;
5689 }
5690
70534a73
DC
5691 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5692 freed++;
d98ba053 5693 kvm_mmu_commit_zap_page(kvm, &invalid_list);
19526396 5694
365c8868 5695unlock:
3ee16c81 5696 spin_unlock(&kvm->mmu_lock);
f656ce01 5697 srcu_read_unlock(&kvm->srcu, idx);
19526396 5698
70534a73
DC
5699 /*
5700 * unfair on small ones
5701 * per-vm shrinkers cry out
5702 * sadness comes quickly
5703 */
19526396
GN
5704 list_move_tail(&kvm->vm_list, &vm_list);
5705 break;
3ee16c81 5706 }
3ee16c81 5707
2f303b74 5708 spin_unlock(&kvm_lock);
70534a73 5709 return freed;
70534a73
DC
5710}
5711
5712static unsigned long
5713mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5714{
45221ab6 5715 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
3ee16c81
IE
5716}
5717
5718static struct shrinker mmu_shrinker = {
70534a73
DC
5719 .count_objects = mmu_shrink_count,
5720 .scan_objects = mmu_shrink_scan,
3ee16c81
IE
5721 .seeks = DEFAULT_SEEKS * 10,
5722};
5723
2ddfd20e 5724static void mmu_destroy_caches(void)
b5a33a75 5725{
c1bd743e
TH
5726 kmem_cache_destroy(pte_list_desc_cache);
5727 kmem_cache_destroy(mmu_page_header_cache);
b5a33a75
AK
5728}
5729
5730int kvm_mmu_module_init(void)
5731{
ab271bd4
AB
5732 int ret = -ENOMEM;
5733
f160c7b7
JS
5734 kvm_mmu_clear_all_pte_masks();
5735
53c07b18
XG
5736 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
5737 sizeof(struct pte_list_desc),
46bea48a 5738 0, SLAB_ACCOUNT, NULL);
53c07b18 5739 if (!pte_list_desc_cache)
ab271bd4 5740 goto out;
b5a33a75 5741
d3d25b04
AK
5742 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
5743 sizeof(struct kvm_mmu_page),
46bea48a 5744 0, SLAB_ACCOUNT, NULL);
d3d25b04 5745 if (!mmu_page_header_cache)
ab271bd4 5746 goto out;
d3d25b04 5747
908c7f19 5748 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
ab271bd4 5749 goto out;
45bf21a8 5750
ab271bd4
AB
5751 ret = register_shrinker(&mmu_shrinker);
5752 if (ret)
5753 goto out;
3ee16c81 5754
b5a33a75
AK
5755 return 0;
5756
ab271bd4 5757out:
3ee16c81 5758 mmu_destroy_caches();
ab271bd4 5759 return ret;
b5a33a75
AK
5760}
5761
3ad82a7e
ZX
5762/*
5763 * Caculate mmu pages needed for kvm.
5764 */
5765unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
5766{
3ad82a7e
ZX
5767 unsigned int nr_mmu_pages;
5768 unsigned int nr_pages = 0;
bc6678a3 5769 struct kvm_memslots *slots;
be6ba0f0 5770 struct kvm_memory_slot *memslot;
9da0e4d5 5771 int i;
3ad82a7e 5772
9da0e4d5
PB
5773 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5774 slots = __kvm_memslots(kvm, i);
90d83dc3 5775
9da0e4d5
PB
5776 kvm_for_each_memslot(memslot, slots)
5777 nr_pages += memslot->npages;
5778 }
3ad82a7e
ZX
5779
5780 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
5781 nr_mmu_pages = max(nr_mmu_pages,
9da0e4d5 5782 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
3ad82a7e
ZX
5783
5784 return nr_mmu_pages;
5785}
5786
c42fffe3
XG
5787void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
5788{
95f93af4 5789 kvm_mmu_unload(vcpu);
c42fffe3
XG
5790 free_mmu_pages(vcpu);
5791 mmu_free_memory_caches(vcpu);
b034cf01
XG
5792}
5793
b034cf01
XG
5794void kvm_mmu_module_exit(void)
5795{
5796 mmu_destroy_caches();
5797 percpu_counter_destroy(&kvm_total_used_mmu_pages);
5798 unregister_shrinker(&mmu_shrinker);
c42fffe3
XG
5799 mmu_audit_disable();
5800}