]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - arch/x86/kvm/mmu.c
KVM: MMU: introduce kvm_mmu_gfn_{allow,disallow}_lpage
[mirror_ubuntu-bionic-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>
32#include <linux/module.h>
448353ca 33#include <linux/swap.h>
05da4558 34#include <linux/hugetlb.h>
2f333bcb 35#include <linux/compiler.h>
bc6678a3 36#include <linux/srcu.h>
5a0e3ad6 37#include <linux/slab.h>
bf998156 38#include <linux/uaccess.h>
6aa8b732 39
e495606d
AK
40#include <asm/page.h>
41#include <asm/cmpxchg.h>
4e542370 42#include <asm/io.h>
13673a90 43#include <asm/vmx.h>
6aa8b732 44
18552672
JR
45/*
46 * When setting this variable to true it enables Two-Dimensional-Paging
47 * where the hardware walks 2 page tables:
48 * 1. the guest-virtual to guest-physical
49 * 2. while doing 1. it walks guest-physical to host-physical
50 * If the hardware supports that we don't need to do shadow paging.
51 */
2f333bcb 52bool tdp_enabled = false;
18552672 53
8b1fe17c
XG
54enum {
55 AUDIT_PRE_PAGE_FAULT,
56 AUDIT_POST_PAGE_FAULT,
57 AUDIT_PRE_PTE_WRITE,
6903074c
XG
58 AUDIT_POST_PTE_WRITE,
59 AUDIT_PRE_SYNC,
60 AUDIT_POST_SYNC
8b1fe17c 61};
37a7d8b0 62
8b1fe17c 63#undef MMU_DEBUG
37a7d8b0
AK
64
65#ifdef MMU_DEBUG
fa4a2c08
PB
66static bool dbg = 0;
67module_param(dbg, bool, 0644);
37a7d8b0
AK
68
69#define pgprintk(x...) do { if (dbg) printk(x); } while (0)
70#define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
fa4a2c08 71#define MMU_WARN_ON(x) WARN_ON(x)
37a7d8b0 72#else
37a7d8b0
AK
73#define pgprintk(x...) do { } while (0)
74#define rmap_printk(x...) do { } while (0)
fa4a2c08 75#define MMU_WARN_ON(x) do { } while (0)
d6c69ee9 76#endif
6aa8b732 77
957ed9ef
XG
78#define PTE_PREFETCH_NUM 8
79
00763e41 80#define PT_FIRST_AVAIL_BITS_SHIFT 10
6aa8b732
AK
81#define PT64_SECOND_AVAIL_BITS_SHIFT 52
82
6aa8b732
AK
83#define PT64_LEVEL_BITS 9
84
85#define PT64_LEVEL_SHIFT(level) \
d77c26fc 86 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
6aa8b732 87
6aa8b732
AK
88#define PT64_INDEX(address, level)\
89 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
90
91
92#define PT32_LEVEL_BITS 10
93
94#define PT32_LEVEL_SHIFT(level) \
d77c26fc 95 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
6aa8b732 96
e04da980
JR
97#define PT32_LVL_OFFSET_MASK(level) \
98 (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
99 * PT32_LEVEL_BITS))) - 1))
6aa8b732
AK
100
101#define PT32_INDEX(address, level)\
102 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
103
104
27aba766 105#define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
6aa8b732
AK
106#define PT64_DIR_BASE_ADDR_MASK \
107 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
e04da980
JR
108#define PT64_LVL_ADDR_MASK(level) \
109 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
110 * PT64_LEVEL_BITS))) - 1))
111#define PT64_LVL_OFFSET_MASK(level) \
112 (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
113 * PT64_LEVEL_BITS))) - 1))
6aa8b732
AK
114
115#define PT32_BASE_ADDR_MASK PAGE_MASK
116#define PT32_DIR_BASE_ADDR_MASK \
117 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
e04da980
JR
118#define PT32_LVL_ADDR_MASK(level) \
119 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
120 * PT32_LEVEL_BITS))) - 1))
6aa8b732 121
53166229
GN
122#define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
123 | shadow_x_mask | shadow_nx_mask)
6aa8b732 124
fe135d2c
AK
125#define ACC_EXEC_MASK 1
126#define ACC_WRITE_MASK PT_WRITABLE_MASK
127#define ACC_USER_MASK PT_USER_MASK
128#define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
129
90bb6fc5
AK
130#include <trace/events/kvm.h>
131
07420171
AK
132#define CREATE_TRACE_POINTS
133#include "mmutrace.h"
134
49fde340
XG
135#define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
136#define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
1403283a 137
135f8c2b
AK
138#define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
139
220f773a
TY
140/* make pte_list_desc fit well in cache line */
141#define PTE_LIST_EXT 3
142
53c07b18
XG
143struct pte_list_desc {
144 u64 *sptes[PTE_LIST_EXT];
145 struct pte_list_desc *more;
cd4a4e53
AK
146};
147
2d11123a
AK
148struct kvm_shadow_walk_iterator {
149 u64 addr;
150 hpa_t shadow_addr;
2d11123a 151 u64 *sptep;
dd3bfd59 152 int level;
2d11123a
AK
153 unsigned index;
154};
155
156#define for_each_shadow_entry(_vcpu, _addr, _walker) \
157 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
158 shadow_walk_okay(&(_walker)); \
159 shadow_walk_next(&(_walker)))
160
c2a2ac2b
XG
161#define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
162 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
163 shadow_walk_okay(&(_walker)) && \
164 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
165 __shadow_walk_next(&(_walker), spte))
166
53c07b18 167static struct kmem_cache *pte_list_desc_cache;
d3d25b04 168static struct kmem_cache *mmu_page_header_cache;
45221ab6 169static struct percpu_counter kvm_total_used_mmu_pages;
b5a33a75 170
7b52345e
SY
171static u64 __read_mostly shadow_nx_mask;
172static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
173static u64 __read_mostly shadow_user_mask;
174static u64 __read_mostly shadow_accessed_mask;
175static u64 __read_mostly shadow_dirty_mask;
ce88decf
XG
176static u64 __read_mostly shadow_mmio_mask;
177
178static void mmu_spte_set(u64 *sptep, u64 spte);
e676505a 179static void mmu_free_roots(struct kvm_vcpu *vcpu);
ce88decf
XG
180
181void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask)
182{
183 shadow_mmio_mask = mmio_mask;
184}
185EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
186
f2fd125d 187/*
ee3d1570
DM
188 * the low bit of the generation number is always presumed to be zero.
189 * This disables mmio caching during memslot updates. The concept is
190 * similar to a seqcount but instead of retrying the access we just punt
191 * and ignore the cache.
192 *
193 * spte bits 3-11 are used as bits 1-9 of the generation number,
194 * the bits 52-61 are used as bits 10-19 of the generation number.
f2fd125d 195 */
ee3d1570 196#define MMIO_SPTE_GEN_LOW_SHIFT 2
f2fd125d
XG
197#define MMIO_SPTE_GEN_HIGH_SHIFT 52
198
ee3d1570
DM
199#define MMIO_GEN_SHIFT 20
200#define MMIO_GEN_LOW_SHIFT 10
201#define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 2)
f8f55942 202#define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
f2fd125d
XG
203
204static u64 generation_mmio_spte_mask(unsigned int gen)
205{
206 u64 mask;
207
842bb26a 208 WARN_ON(gen & ~MMIO_GEN_MASK);
f2fd125d
XG
209
210 mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
211 mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
212 return mask;
213}
214
215static unsigned int get_mmio_spte_generation(u64 spte)
216{
217 unsigned int gen;
218
219 spte &= ~shadow_mmio_mask;
220
221 gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
222 gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
223 return gen;
224}
225
54bf36aa 226static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
f8f55942 227{
54bf36aa 228 return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
f8f55942
XG
229}
230
54bf36aa 231static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
f2fd125d 232 unsigned access)
ce88decf 233{
54bf36aa 234 unsigned int gen = kvm_current_mmio_generation(vcpu);
f8f55942 235 u64 mask = generation_mmio_spte_mask(gen);
95b0430d 236
ce88decf 237 access &= ACC_WRITE_MASK | ACC_USER_MASK;
f2fd125d 238 mask |= shadow_mmio_mask | access | gfn << PAGE_SHIFT;
f2fd125d 239
f8f55942 240 trace_mark_mmio_spte(sptep, gfn, access, gen);
f2fd125d 241 mmu_spte_set(sptep, mask);
ce88decf
XG
242}
243
244static bool is_mmio_spte(u64 spte)
245{
246 return (spte & shadow_mmio_mask) == shadow_mmio_mask;
247}
248
249static gfn_t get_mmio_spte_gfn(u64 spte)
250{
842bb26a 251 u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
f2fd125d 252 return (spte & ~mask) >> PAGE_SHIFT;
ce88decf
XG
253}
254
255static unsigned get_mmio_spte_access(u64 spte)
256{
842bb26a 257 u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
f2fd125d 258 return (spte & ~mask) & ~PAGE_MASK;
ce88decf
XG
259}
260
54bf36aa 261static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
ba049e93 262 kvm_pfn_t pfn, unsigned access)
ce88decf
XG
263{
264 if (unlikely(is_noslot_pfn(pfn))) {
54bf36aa 265 mark_mmio_spte(vcpu, sptep, gfn, access);
ce88decf
XG
266 return true;
267 }
268
269 return false;
270}
c7addb90 271
54bf36aa 272static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
f8f55942 273{
089504c0
XG
274 unsigned int kvm_gen, spte_gen;
275
54bf36aa 276 kvm_gen = kvm_current_mmio_generation(vcpu);
089504c0
XG
277 spte_gen = get_mmio_spte_generation(spte);
278
279 trace_check_mmio_spte(spte, kvm_gen, spte_gen);
280 return likely(kvm_gen == spte_gen);
f8f55942
XG
281}
282
7b52345e 283void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
4b12f0de 284 u64 dirty_mask, u64 nx_mask, u64 x_mask)
7b52345e
SY
285{
286 shadow_user_mask = user_mask;
287 shadow_accessed_mask = accessed_mask;
288 shadow_dirty_mask = dirty_mask;
289 shadow_nx_mask = nx_mask;
290 shadow_x_mask = x_mask;
291}
292EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
293
6aa8b732
AK
294static int is_cpuid_PSE36(void)
295{
296 return 1;
297}
298
73b1087e
AK
299static int is_nx(struct kvm_vcpu *vcpu)
300{
f6801dff 301 return vcpu->arch.efer & EFER_NX;
73b1087e
AK
302}
303
c7addb90
AK
304static int is_shadow_present_pte(u64 pte)
305{
ce88decf 306 return pte & PT_PRESENT_MASK && !is_mmio_spte(pte);
c7addb90
AK
307}
308
05da4558
MT
309static int is_large_pte(u64 pte)
310{
311 return pte & PT_PAGE_SIZE_MASK;
312}
313
776e6633
MT
314static int is_last_spte(u64 pte, int level)
315{
316 if (level == PT_PAGE_TABLE_LEVEL)
317 return 1;
852e3c19 318 if (is_large_pte(pte))
776e6633
MT
319 return 1;
320 return 0;
321}
322
ba049e93 323static kvm_pfn_t spte_to_pfn(u64 pte)
0b49ea86 324{
35149e21 325 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
0b49ea86
AK
326}
327
da928521
AK
328static gfn_t pse36_gfn_delta(u32 gpte)
329{
330 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
331
332 return (gpte & PT32_DIR_PSE36_MASK) << shift;
333}
334
603e0651 335#ifdef CONFIG_X86_64
d555c333 336static void __set_spte(u64 *sptep, u64 spte)
e663ee64 337{
603e0651 338 *sptep = spte;
e663ee64
AK
339}
340
603e0651 341static void __update_clear_spte_fast(u64 *sptep, u64 spte)
a9221dd5 342{
603e0651
XG
343 *sptep = spte;
344}
345
346static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
347{
348 return xchg(sptep, spte);
349}
c2a2ac2b
XG
350
351static u64 __get_spte_lockless(u64 *sptep)
352{
353 return ACCESS_ONCE(*sptep);
354}
a9221dd5 355#else
603e0651
XG
356union split_spte {
357 struct {
358 u32 spte_low;
359 u32 spte_high;
360 };
361 u64 spte;
362};
a9221dd5 363
c2a2ac2b
XG
364static void count_spte_clear(u64 *sptep, u64 spte)
365{
366 struct kvm_mmu_page *sp = page_header(__pa(sptep));
367
368 if (is_shadow_present_pte(spte))
369 return;
370
371 /* Ensure the spte is completely set before we increase the count */
372 smp_wmb();
373 sp->clear_spte_count++;
374}
375
603e0651
XG
376static void __set_spte(u64 *sptep, u64 spte)
377{
378 union split_spte *ssptep, sspte;
a9221dd5 379
603e0651
XG
380 ssptep = (union split_spte *)sptep;
381 sspte = (union split_spte)spte;
382
383 ssptep->spte_high = sspte.spte_high;
384
385 /*
386 * If we map the spte from nonpresent to present, We should store
387 * the high bits firstly, then set present bit, so cpu can not
388 * fetch this spte while we are setting the spte.
389 */
390 smp_wmb();
391
392 ssptep->spte_low = sspte.spte_low;
a9221dd5
AK
393}
394
603e0651
XG
395static void __update_clear_spte_fast(u64 *sptep, u64 spte)
396{
397 union split_spte *ssptep, sspte;
398
399 ssptep = (union split_spte *)sptep;
400 sspte = (union split_spte)spte;
401
402 ssptep->spte_low = sspte.spte_low;
403
404 /*
405 * If we map the spte from present to nonpresent, we should clear
406 * present bit firstly to avoid vcpu fetch the old high bits.
407 */
408 smp_wmb();
409
410 ssptep->spte_high = sspte.spte_high;
c2a2ac2b 411 count_spte_clear(sptep, spte);
603e0651
XG
412}
413
414static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
415{
416 union split_spte *ssptep, sspte, orig;
417
418 ssptep = (union split_spte *)sptep;
419 sspte = (union split_spte)spte;
420
421 /* xchg acts as a barrier before the setting of the high bits */
422 orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
41bc3186
ZJ
423 orig.spte_high = ssptep->spte_high;
424 ssptep->spte_high = sspte.spte_high;
c2a2ac2b 425 count_spte_clear(sptep, spte);
603e0651
XG
426
427 return orig.spte;
428}
c2a2ac2b
XG
429
430/*
431 * The idea using the light way get the spte on x86_32 guest is from
432 * gup_get_pte(arch/x86/mm/gup.c).
accaefe0
XG
433 *
434 * An spte tlb flush may be pending, because kvm_set_pte_rmapp
435 * coalesces them and we are running out of the MMU lock. Therefore
436 * we need to protect against in-progress updates of the spte.
437 *
438 * Reading the spte while an update is in progress may get the old value
439 * for the high part of the spte. The race is fine for a present->non-present
440 * change (because the high part of the spte is ignored for non-present spte),
441 * but for a present->present change we must reread the spte.
442 *
443 * All such changes are done in two steps (present->non-present and
444 * non-present->present), hence it is enough to count the number of
445 * present->non-present updates: if it changed while reading the spte,
446 * we might have hit the race. This is done using clear_spte_count.
c2a2ac2b
XG
447 */
448static u64 __get_spte_lockless(u64 *sptep)
449{
450 struct kvm_mmu_page *sp = page_header(__pa(sptep));
451 union split_spte spte, *orig = (union split_spte *)sptep;
452 int count;
453
454retry:
455 count = sp->clear_spte_count;
456 smp_rmb();
457
458 spte.spte_low = orig->spte_low;
459 smp_rmb();
460
461 spte.spte_high = orig->spte_high;
462 smp_rmb();
463
464 if (unlikely(spte.spte_low != orig->spte_low ||
465 count != sp->clear_spte_count))
466 goto retry;
467
468 return spte.spte;
469}
603e0651
XG
470#endif
471
c7ba5b48
XG
472static bool spte_is_locklessly_modifiable(u64 spte)
473{
feb3eb70
GN
474 return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
475 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
c7ba5b48
XG
476}
477
8672b721
XG
478static bool spte_has_volatile_bits(u64 spte)
479{
c7ba5b48
XG
480 /*
481 * Always atomicly update spte if it can be updated
482 * out of mmu-lock, it can ensure dirty bit is not lost,
483 * also, it can help us to get a stable is_writable_pte()
484 * to ensure tlb flush is not missed.
485 */
486 if (spte_is_locklessly_modifiable(spte))
487 return true;
488
8672b721
XG
489 if (!shadow_accessed_mask)
490 return false;
491
492 if (!is_shadow_present_pte(spte))
493 return false;
494
4132779b
XG
495 if ((spte & shadow_accessed_mask) &&
496 (!is_writable_pte(spte) || (spte & shadow_dirty_mask)))
8672b721
XG
497 return false;
498
499 return true;
500}
501
4132779b
XG
502static bool spte_is_bit_cleared(u64 old_spte, u64 new_spte, u64 bit_mask)
503{
504 return (old_spte & bit_mask) && !(new_spte & bit_mask);
505}
506
7e71a59b
KH
507static bool spte_is_bit_changed(u64 old_spte, u64 new_spte, u64 bit_mask)
508{
509 return (old_spte & bit_mask) != (new_spte & bit_mask);
510}
511
1df9f2dc
XG
512/* Rules for using mmu_spte_set:
513 * Set the sptep from nonpresent to present.
514 * Note: the sptep being assigned *must* be either not present
515 * or in a state where the hardware will not attempt to update
516 * the spte.
517 */
518static void mmu_spte_set(u64 *sptep, u64 new_spte)
519{
520 WARN_ON(is_shadow_present_pte(*sptep));
521 __set_spte(sptep, new_spte);
522}
523
524/* Rules for using mmu_spte_update:
525 * Update the state bits, it means the mapped pfn is not changged.
6e7d0354
XG
526 *
527 * Whenever we overwrite a writable spte with a read-only one we
528 * should flush remote TLBs. Otherwise rmap_write_protect
529 * will find a read-only spte, even though the writable spte
530 * might be cached on a CPU's TLB, the return value indicates this
531 * case.
1df9f2dc 532 */
6e7d0354 533static bool mmu_spte_update(u64 *sptep, u64 new_spte)
b79b93f9 534{
c7ba5b48 535 u64 old_spte = *sptep;
6e7d0354 536 bool ret = false;
4132779b 537
afd28fe1 538 WARN_ON(!is_shadow_present_pte(new_spte));
b79b93f9 539
6e7d0354
XG
540 if (!is_shadow_present_pte(old_spte)) {
541 mmu_spte_set(sptep, new_spte);
542 return ret;
543 }
4132779b 544
c7ba5b48 545 if (!spte_has_volatile_bits(old_spte))
603e0651 546 __update_clear_spte_fast(sptep, new_spte);
4132779b 547 else
603e0651 548 old_spte = __update_clear_spte_slow(sptep, new_spte);
4132779b 549
c7ba5b48
XG
550 /*
551 * For the spte updated out of mmu-lock is safe, since
552 * we always atomicly update it, see the comments in
553 * spte_has_volatile_bits().
554 */
7f31c959
XG
555 if (spte_is_locklessly_modifiable(old_spte) &&
556 !is_writable_pte(new_spte))
6e7d0354
XG
557 ret = true;
558
4132779b 559 if (!shadow_accessed_mask)
6e7d0354 560 return ret;
4132779b 561
7e71a59b
KH
562 /*
563 * Flush TLB when accessed/dirty bits are changed in the page tables,
564 * to guarantee consistency between TLB and page tables.
565 */
566 if (spte_is_bit_changed(old_spte, new_spte,
567 shadow_accessed_mask | shadow_dirty_mask))
568 ret = true;
569
4132779b
XG
570 if (spte_is_bit_cleared(old_spte, new_spte, shadow_accessed_mask))
571 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
572 if (spte_is_bit_cleared(old_spte, new_spte, shadow_dirty_mask))
573 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
6e7d0354
XG
574
575 return ret;
b79b93f9
AK
576}
577
1df9f2dc
XG
578/*
579 * Rules for using mmu_spte_clear_track_bits:
580 * It sets the sptep from present to nonpresent, and track the
581 * state bits, it is used to clear the last level sptep.
582 */
583static int mmu_spte_clear_track_bits(u64 *sptep)
584{
ba049e93 585 kvm_pfn_t pfn;
1df9f2dc
XG
586 u64 old_spte = *sptep;
587
588 if (!spte_has_volatile_bits(old_spte))
603e0651 589 __update_clear_spte_fast(sptep, 0ull);
1df9f2dc 590 else
603e0651 591 old_spte = __update_clear_spte_slow(sptep, 0ull);
1df9f2dc 592
afd28fe1 593 if (!is_shadow_present_pte(old_spte))
1df9f2dc
XG
594 return 0;
595
596 pfn = spte_to_pfn(old_spte);
86fde74c
XG
597
598 /*
599 * KVM does not hold the refcount of the page used by
600 * kvm mmu, before reclaiming the page, we should
601 * unmap it from mmu first.
602 */
bf4bea8e 603 WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
86fde74c 604
1df9f2dc
XG
605 if (!shadow_accessed_mask || old_spte & shadow_accessed_mask)
606 kvm_set_pfn_accessed(pfn);
607 if (!shadow_dirty_mask || (old_spte & shadow_dirty_mask))
608 kvm_set_pfn_dirty(pfn);
609 return 1;
610}
611
612/*
613 * Rules for using mmu_spte_clear_no_track:
614 * Directly clear spte without caring the state bits of sptep,
615 * it is used to set the upper level spte.
616 */
617static void mmu_spte_clear_no_track(u64 *sptep)
618{
603e0651 619 __update_clear_spte_fast(sptep, 0ull);
1df9f2dc
XG
620}
621
c2a2ac2b
XG
622static u64 mmu_spte_get_lockless(u64 *sptep)
623{
624 return __get_spte_lockless(sptep);
625}
626
627static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
628{
c142786c
AK
629 /*
630 * Prevent page table teardown by making any free-er wait during
631 * kvm_flush_remote_tlbs() IPI to all active vcpus.
632 */
633 local_irq_disable();
634 vcpu->mode = READING_SHADOW_PAGE_TABLES;
635 /*
636 * Make sure a following spte read is not reordered ahead of the write
637 * to vcpu->mode.
638 */
639 smp_mb();
c2a2ac2b
XG
640}
641
642static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
643{
c142786c
AK
644 /*
645 * Make sure the write to vcpu->mode is not reordered in front of
646 * reads to sptes. If it does, kvm_commit_zap_page() can see us
647 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
648 */
649 smp_mb();
650 vcpu->mode = OUTSIDE_GUEST_MODE;
651 local_irq_enable();
c2a2ac2b
XG
652}
653
e2dec939 654static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
2e3e5882 655 struct kmem_cache *base_cache, int min)
714b93da
AK
656{
657 void *obj;
658
659 if (cache->nobjs >= min)
e2dec939 660 return 0;
714b93da 661 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
2e3e5882 662 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
714b93da 663 if (!obj)
e2dec939 664 return -ENOMEM;
714b93da
AK
665 cache->objects[cache->nobjs++] = obj;
666 }
e2dec939 667 return 0;
714b93da
AK
668}
669
f759e2b4
XG
670static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
671{
672 return cache->nobjs;
673}
674
e8ad9a70
XG
675static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
676 struct kmem_cache *cache)
714b93da
AK
677{
678 while (mc->nobjs)
e8ad9a70 679 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
714b93da
AK
680}
681
c1158e63 682static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
2e3e5882 683 int min)
c1158e63 684{
842f22ed 685 void *page;
c1158e63
AK
686
687 if (cache->nobjs >= min)
688 return 0;
689 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
842f22ed 690 page = (void *)__get_free_page(GFP_KERNEL);
c1158e63
AK
691 if (!page)
692 return -ENOMEM;
842f22ed 693 cache->objects[cache->nobjs++] = page;
c1158e63
AK
694 }
695 return 0;
696}
697
698static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
699{
700 while (mc->nobjs)
c4d198d5 701 free_page((unsigned long)mc->objects[--mc->nobjs]);
c1158e63
AK
702}
703
2e3e5882 704static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
714b93da 705{
e2dec939
AK
706 int r;
707
53c07b18 708 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
67052b35 709 pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
d3d25b04
AK
710 if (r)
711 goto out;
ad312c7c 712 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
d3d25b04
AK
713 if (r)
714 goto out;
ad312c7c 715 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
2e3e5882 716 mmu_page_header_cache, 4);
e2dec939
AK
717out:
718 return r;
714b93da
AK
719}
720
721static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
722{
53c07b18
XG
723 mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
724 pte_list_desc_cache);
ad312c7c 725 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
e8ad9a70
XG
726 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
727 mmu_page_header_cache);
714b93da
AK
728}
729
80feb89a 730static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
714b93da
AK
731{
732 void *p;
733
734 BUG_ON(!mc->nobjs);
735 p = mc->objects[--mc->nobjs];
714b93da
AK
736 return p;
737}
738
53c07b18 739static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
714b93da 740{
80feb89a 741 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
714b93da
AK
742}
743
53c07b18 744static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
714b93da 745{
53c07b18 746 kmem_cache_free(pte_list_desc_cache, pte_list_desc);
714b93da
AK
747}
748
2032a93d
LJ
749static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
750{
751 if (!sp->role.direct)
752 return sp->gfns[index];
753
754 return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
755}
756
757static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
758{
759 if (sp->role.direct)
760 BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
761 else
762 sp->gfns[index] = gfn;
763}
764
05da4558 765/*
d4dbf470
TY
766 * Return the pointer to the large page information for a given gfn,
767 * handling slots that are not large page aligned.
05da4558 768 */
d4dbf470
TY
769static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
770 struct kvm_memory_slot *slot,
771 int level)
05da4558
MT
772{
773 unsigned long idx;
774
fb03cb6f 775 idx = gfn_to_index(gfn, slot->base_gfn, level);
db3fe4eb 776 return &slot->arch.lpage_info[level - 2][idx];
05da4558
MT
777}
778
547ffaed
XG
779static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
780 gfn_t gfn, int count)
781{
782 struct kvm_lpage_info *linfo;
783 int i;
784
785 for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
786 linfo = lpage_info_slot(gfn, slot, i);
787 linfo->disallow_lpage += count;
788 WARN_ON(linfo->disallow_lpage < 0);
789 }
790}
791
792void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
793{
794 update_gfn_disallow_lpage_count(slot, gfn, 1);
795}
796
797void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
798{
799 update_gfn_disallow_lpage_count(slot, gfn, -1);
800}
801
3ed1a478 802static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
05da4558 803{
699023e2 804 struct kvm_memslots *slots;
d25797b2 805 struct kvm_memory_slot *slot;
3ed1a478 806 gfn_t gfn;
05da4558 807
3ed1a478 808 gfn = sp->gfn;
699023e2
PB
809 slots = kvm_memslots_for_spte_role(kvm, sp->role);
810 slot = __gfn_to_memslot(slots, gfn);
547ffaed 811 kvm_mmu_gfn_disallow_lpage(slot, gfn);
332b207d 812 kvm->arch.indirect_shadow_pages++;
05da4558
MT
813}
814
3ed1a478 815static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
05da4558 816{
699023e2 817 struct kvm_memslots *slots;
d25797b2 818 struct kvm_memory_slot *slot;
3ed1a478 819 gfn_t gfn;
05da4558 820
3ed1a478 821 gfn = sp->gfn;
699023e2
PB
822 slots = kvm_memslots_for_spte_role(kvm, sp->role);
823 slot = __gfn_to_memslot(slots, gfn);
547ffaed 824 kvm_mmu_gfn_allow_lpage(slot, gfn);
332b207d 825 kvm->arch.indirect_shadow_pages--;
05da4558
MT
826}
827
92f94f1e
XG
828static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
829 struct kvm_memory_slot *slot)
05da4558 830{
d4dbf470 831 struct kvm_lpage_info *linfo;
05da4558
MT
832
833 if (slot) {
d4dbf470 834 linfo = lpage_info_slot(gfn, slot, level);
92f94f1e 835 return !!linfo->disallow_lpage;
05da4558
MT
836 }
837
92f94f1e 838 return true;
05da4558
MT
839}
840
92f94f1e
XG
841static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
842 int level)
5225fdf8
TY
843{
844 struct kvm_memory_slot *slot;
845
846 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
92f94f1e 847 return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
5225fdf8
TY
848}
849
d25797b2 850static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
05da4558 851{
8f0b1ab6 852 unsigned long page_size;
d25797b2 853 int i, ret = 0;
05da4558 854
8f0b1ab6 855 page_size = kvm_host_page_size(kvm, gfn);
05da4558 856
8a3d08f1 857 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
d25797b2
JR
858 if (page_size >= KVM_HPAGE_SIZE(i))
859 ret = i;
860 else
861 break;
862 }
863
4c2155ce 864 return ret;
05da4558
MT
865}
866
d8aacf5d
TY
867static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
868 bool no_dirty_log)
869{
870 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
871 return false;
872 if (no_dirty_log && slot->dirty_bitmap)
873 return false;
874
875 return true;
876}
877
5d163b1c
XG
878static struct kvm_memory_slot *
879gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
880 bool no_dirty_log)
05da4558
MT
881{
882 struct kvm_memory_slot *slot;
5d163b1c 883
54bf36aa 884 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
d8aacf5d 885 if (!memslot_valid_for_gpte(slot, no_dirty_log))
5d163b1c
XG
886 slot = NULL;
887
888 return slot;
889}
890
fd136902
TY
891static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
892 bool *force_pt_level)
936a5fe6
AA
893{
894 int host_level, level, max_level;
d8aacf5d
TY
895 struct kvm_memory_slot *slot;
896
8c85ac1c
TY
897 if (unlikely(*force_pt_level))
898 return PT_PAGE_TABLE_LEVEL;
05da4558 899
8c85ac1c
TY
900 slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
901 *force_pt_level = !memslot_valid_for_gpte(slot, true);
fd136902
TY
902 if (unlikely(*force_pt_level))
903 return PT_PAGE_TABLE_LEVEL;
904
d25797b2
JR
905 host_level = host_mapping_level(vcpu->kvm, large_gfn);
906
907 if (host_level == PT_PAGE_TABLE_LEVEL)
908 return host_level;
909
55dd98c3 910 max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
878403b7
SY
911
912 for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
92f94f1e 913 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
d25797b2 914 break;
d25797b2
JR
915
916 return level - 1;
05da4558
MT
917}
918
290fc38d 919/*
018aabb5 920 * About rmap_head encoding:
cd4a4e53 921 *
018aabb5
TY
922 * If the bit zero of rmap_head->val is clear, then it points to the only spte
923 * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
53c07b18 924 * pte_list_desc containing more mappings.
018aabb5
TY
925 */
926
927/*
928 * Returns the number of pointers in the rmap chain, not counting the new one.
cd4a4e53 929 */
53c07b18 930static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
018aabb5 931 struct kvm_rmap_head *rmap_head)
cd4a4e53 932{
53c07b18 933 struct pte_list_desc *desc;
53a27b39 934 int i, count = 0;
cd4a4e53 935
018aabb5 936 if (!rmap_head->val) {
53c07b18 937 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
018aabb5
TY
938 rmap_head->val = (unsigned long)spte;
939 } else if (!(rmap_head->val & 1)) {
53c07b18
XG
940 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
941 desc = mmu_alloc_pte_list_desc(vcpu);
018aabb5 942 desc->sptes[0] = (u64 *)rmap_head->val;
d555c333 943 desc->sptes[1] = spte;
018aabb5 944 rmap_head->val = (unsigned long)desc | 1;
cb16a7b3 945 ++count;
cd4a4e53 946 } else {
53c07b18 947 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
018aabb5 948 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
53c07b18 949 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
cd4a4e53 950 desc = desc->more;
53c07b18 951 count += PTE_LIST_EXT;
53a27b39 952 }
53c07b18
XG
953 if (desc->sptes[PTE_LIST_EXT-1]) {
954 desc->more = mmu_alloc_pte_list_desc(vcpu);
cd4a4e53
AK
955 desc = desc->more;
956 }
d555c333 957 for (i = 0; desc->sptes[i]; ++i)
cb16a7b3 958 ++count;
d555c333 959 desc->sptes[i] = spte;
cd4a4e53 960 }
53a27b39 961 return count;
cd4a4e53
AK
962}
963
53c07b18 964static void
018aabb5
TY
965pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
966 struct pte_list_desc *desc, int i,
967 struct pte_list_desc *prev_desc)
cd4a4e53
AK
968{
969 int j;
970
53c07b18 971 for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
cd4a4e53 972 ;
d555c333
AK
973 desc->sptes[i] = desc->sptes[j];
974 desc->sptes[j] = NULL;
cd4a4e53
AK
975 if (j != 0)
976 return;
977 if (!prev_desc && !desc->more)
018aabb5 978 rmap_head->val = (unsigned long)desc->sptes[0];
cd4a4e53
AK
979 else
980 if (prev_desc)
981 prev_desc->more = desc->more;
982 else
018aabb5 983 rmap_head->val = (unsigned long)desc->more | 1;
53c07b18 984 mmu_free_pte_list_desc(desc);
cd4a4e53
AK
985}
986
018aabb5 987static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
cd4a4e53 988{
53c07b18
XG
989 struct pte_list_desc *desc;
990 struct pte_list_desc *prev_desc;
cd4a4e53
AK
991 int i;
992
018aabb5 993 if (!rmap_head->val) {
53c07b18 994 printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
cd4a4e53 995 BUG();
018aabb5 996 } else if (!(rmap_head->val & 1)) {
53c07b18 997 rmap_printk("pte_list_remove: %p 1->0\n", spte);
018aabb5 998 if ((u64 *)rmap_head->val != spte) {
53c07b18 999 printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte);
cd4a4e53
AK
1000 BUG();
1001 }
018aabb5 1002 rmap_head->val = 0;
cd4a4e53 1003 } else {
53c07b18 1004 rmap_printk("pte_list_remove: %p many->many\n", spte);
018aabb5 1005 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
cd4a4e53
AK
1006 prev_desc = NULL;
1007 while (desc) {
018aabb5 1008 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
d555c333 1009 if (desc->sptes[i] == spte) {
018aabb5
TY
1010 pte_list_desc_remove_entry(rmap_head,
1011 desc, i, prev_desc);
cd4a4e53
AK
1012 return;
1013 }
018aabb5 1014 }
cd4a4e53
AK
1015 prev_desc = desc;
1016 desc = desc->more;
1017 }
53c07b18 1018 pr_err("pte_list_remove: %p many->many\n", spte);
cd4a4e53
AK
1019 BUG();
1020 }
1021}
1022
018aabb5
TY
1023static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1024 struct kvm_memory_slot *slot)
53c07b18 1025{
77d11309 1026 unsigned long idx;
53c07b18 1027
77d11309 1028 idx = gfn_to_index(gfn, slot->base_gfn, level);
d89cc617 1029 return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
53c07b18
XG
1030}
1031
018aabb5
TY
1032static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1033 struct kvm_mmu_page *sp)
9b9b1492 1034{
699023e2 1035 struct kvm_memslots *slots;
9b9b1492
TY
1036 struct kvm_memory_slot *slot;
1037
699023e2
PB
1038 slots = kvm_memslots_for_spte_role(kvm, sp->role);
1039 slot = __gfn_to_memslot(slots, gfn);
e4cd1da9 1040 return __gfn_to_rmap(gfn, sp->role.level, slot);
9b9b1492
TY
1041}
1042
f759e2b4
XG
1043static bool rmap_can_add(struct kvm_vcpu *vcpu)
1044{
1045 struct kvm_mmu_memory_cache *cache;
1046
1047 cache = &vcpu->arch.mmu_pte_list_desc_cache;
1048 return mmu_memory_cache_free_objects(cache);
1049}
1050
53c07b18
XG
1051static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1052{
1053 struct kvm_mmu_page *sp;
018aabb5 1054 struct kvm_rmap_head *rmap_head;
53c07b18 1055
53c07b18
XG
1056 sp = page_header(__pa(spte));
1057 kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
018aabb5
TY
1058 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1059 return pte_list_add(vcpu, spte, rmap_head);
53c07b18
XG
1060}
1061
53c07b18
XG
1062static void rmap_remove(struct kvm *kvm, u64 *spte)
1063{
1064 struct kvm_mmu_page *sp;
1065 gfn_t gfn;
018aabb5 1066 struct kvm_rmap_head *rmap_head;
53c07b18
XG
1067
1068 sp = page_header(__pa(spte));
1069 gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
018aabb5
TY
1070 rmap_head = gfn_to_rmap(kvm, gfn, sp);
1071 pte_list_remove(spte, rmap_head);
53c07b18
XG
1072}
1073
1e3f42f0
TY
1074/*
1075 * Used by the following functions to iterate through the sptes linked by a
1076 * rmap. All fields are private and not assumed to be used outside.
1077 */
1078struct rmap_iterator {
1079 /* private fields */
1080 struct pte_list_desc *desc; /* holds the sptep if not NULL */
1081 int pos; /* index of the sptep */
1082};
1083
1084/*
1085 * Iteration must be started by this function. This should also be used after
1086 * removing/dropping sptes from the rmap link because in such cases the
1087 * information in the itererator may not be valid.
1088 *
1089 * Returns sptep if found, NULL otherwise.
1090 */
018aabb5
TY
1091static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1092 struct rmap_iterator *iter)
1e3f42f0 1093{
77fbbbd2
TY
1094 u64 *sptep;
1095
018aabb5 1096 if (!rmap_head->val)
1e3f42f0
TY
1097 return NULL;
1098
018aabb5 1099 if (!(rmap_head->val & 1)) {
1e3f42f0 1100 iter->desc = NULL;
77fbbbd2
TY
1101 sptep = (u64 *)rmap_head->val;
1102 goto out;
1e3f42f0
TY
1103 }
1104
018aabb5 1105 iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1e3f42f0 1106 iter->pos = 0;
77fbbbd2
TY
1107 sptep = iter->desc->sptes[iter->pos];
1108out:
1109 BUG_ON(!is_shadow_present_pte(*sptep));
1110 return sptep;
1e3f42f0
TY
1111}
1112
1113/*
1114 * Must be used with a valid iterator: e.g. after rmap_get_first().
1115 *
1116 * Returns sptep if found, NULL otherwise.
1117 */
1118static u64 *rmap_get_next(struct rmap_iterator *iter)
1119{
77fbbbd2
TY
1120 u64 *sptep;
1121
1e3f42f0
TY
1122 if (iter->desc) {
1123 if (iter->pos < PTE_LIST_EXT - 1) {
1e3f42f0
TY
1124 ++iter->pos;
1125 sptep = iter->desc->sptes[iter->pos];
1126 if (sptep)
77fbbbd2 1127 goto out;
1e3f42f0
TY
1128 }
1129
1130 iter->desc = iter->desc->more;
1131
1132 if (iter->desc) {
1133 iter->pos = 0;
1134 /* desc->sptes[0] cannot be NULL */
77fbbbd2
TY
1135 sptep = iter->desc->sptes[iter->pos];
1136 goto out;
1e3f42f0
TY
1137 }
1138 }
1139
1140 return NULL;
77fbbbd2
TY
1141out:
1142 BUG_ON(!is_shadow_present_pte(*sptep));
1143 return sptep;
1e3f42f0
TY
1144}
1145
018aabb5
TY
1146#define for_each_rmap_spte(_rmap_head_, _iter_, _spte_) \
1147 for (_spte_ = rmap_get_first(_rmap_head_, _iter_); \
77fbbbd2 1148 _spte_; _spte_ = rmap_get_next(_iter_))
0d536790 1149
c3707958 1150static void drop_spte(struct kvm *kvm, u64 *sptep)
e4b502ea 1151{
1df9f2dc 1152 if (mmu_spte_clear_track_bits(sptep))
eb45fda4 1153 rmap_remove(kvm, sptep);
be38d276
AK
1154}
1155
8e22f955
XG
1156
1157static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1158{
1159 if (is_large_pte(*sptep)) {
1160 WARN_ON(page_header(__pa(sptep))->role.level ==
1161 PT_PAGE_TABLE_LEVEL);
1162 drop_spte(kvm, sptep);
1163 --kvm->stat.lpages;
1164 return true;
1165 }
1166
1167 return false;
1168}
1169
1170static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1171{
1172 if (__drop_large_spte(vcpu->kvm, sptep))
1173 kvm_flush_remote_tlbs(vcpu->kvm);
1174}
1175
1176/*
49fde340 1177 * Write-protect on the specified @sptep, @pt_protect indicates whether
c126d94f 1178 * spte write-protection is caused by protecting shadow page table.
49fde340 1179 *
b4619660 1180 * Note: write protection is difference between dirty logging and spte
49fde340
XG
1181 * protection:
1182 * - for dirty logging, the spte can be set to writable at anytime if
1183 * its dirty bitmap is properly set.
1184 * - for spte protection, the spte can be writable only after unsync-ing
1185 * shadow page.
8e22f955 1186 *
c126d94f 1187 * Return true if tlb need be flushed.
8e22f955 1188 */
c126d94f 1189static bool spte_write_protect(struct kvm *kvm, u64 *sptep, bool pt_protect)
d13bc5b5
XG
1190{
1191 u64 spte = *sptep;
1192
49fde340
XG
1193 if (!is_writable_pte(spte) &&
1194 !(pt_protect && spte_is_locklessly_modifiable(spte)))
d13bc5b5
XG
1195 return false;
1196
1197 rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1198
49fde340
XG
1199 if (pt_protect)
1200 spte &= ~SPTE_MMU_WRITEABLE;
d13bc5b5 1201 spte = spte & ~PT_WRITABLE_MASK;
49fde340 1202
c126d94f 1203 return mmu_spte_update(sptep, spte);
d13bc5b5
XG
1204}
1205
018aabb5
TY
1206static bool __rmap_write_protect(struct kvm *kvm,
1207 struct kvm_rmap_head *rmap_head,
245c3912 1208 bool pt_protect)
98348e95 1209{
1e3f42f0
TY
1210 u64 *sptep;
1211 struct rmap_iterator iter;
d13bc5b5 1212 bool flush = false;
374cbac0 1213
018aabb5 1214 for_each_rmap_spte(rmap_head, &iter, sptep)
c126d94f 1215 flush |= spte_write_protect(kvm, sptep, pt_protect);
855149aa 1216
d13bc5b5 1217 return flush;
a0ed4607
TY
1218}
1219
f4b4b180
KH
1220static bool spte_clear_dirty(struct kvm *kvm, u64 *sptep)
1221{
1222 u64 spte = *sptep;
1223
1224 rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1225
1226 spte &= ~shadow_dirty_mask;
1227
1228 return mmu_spte_update(sptep, spte);
1229}
1230
018aabb5 1231static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
f4b4b180
KH
1232{
1233 u64 *sptep;
1234 struct rmap_iterator iter;
1235 bool flush = false;
1236
018aabb5 1237 for_each_rmap_spte(rmap_head, &iter, sptep)
f4b4b180 1238 flush |= spte_clear_dirty(kvm, sptep);
f4b4b180
KH
1239
1240 return flush;
1241}
1242
1243static bool spte_set_dirty(struct kvm *kvm, u64 *sptep)
1244{
1245 u64 spte = *sptep;
1246
1247 rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1248
1249 spte |= shadow_dirty_mask;
1250
1251 return mmu_spte_update(sptep, spte);
1252}
1253
018aabb5 1254static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
f4b4b180
KH
1255{
1256 u64 *sptep;
1257 struct rmap_iterator iter;
1258 bool flush = false;
1259
018aabb5 1260 for_each_rmap_spte(rmap_head, &iter, sptep)
f4b4b180 1261 flush |= spte_set_dirty(kvm, sptep);
f4b4b180
KH
1262
1263 return flush;
1264}
1265
5dc99b23 1266/**
3b0f1d01 1267 * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
5dc99b23
TY
1268 * @kvm: kvm instance
1269 * @slot: slot to protect
1270 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1271 * @mask: indicates which pages we should protect
1272 *
1273 * Used when we do not need to care about huge page mappings: e.g. during dirty
1274 * logging we do not have any such mappings.
1275 */
3b0f1d01 1276static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
5dc99b23
TY
1277 struct kvm_memory_slot *slot,
1278 gfn_t gfn_offset, unsigned long mask)
a0ed4607 1279{
018aabb5 1280 struct kvm_rmap_head *rmap_head;
a0ed4607 1281
5dc99b23 1282 while (mask) {
018aabb5
TY
1283 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1284 PT_PAGE_TABLE_LEVEL, slot);
1285 __rmap_write_protect(kvm, rmap_head, false);
05da4558 1286
5dc99b23
TY
1287 /* clear the first set bit */
1288 mask &= mask - 1;
1289 }
374cbac0
AK
1290}
1291
f4b4b180
KH
1292/**
1293 * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages
1294 * @kvm: kvm instance
1295 * @slot: slot to clear D-bit
1296 * @gfn_offset: start of the BITS_PER_LONG pages we care about
1297 * @mask: indicates which pages we should clear D-bit
1298 *
1299 * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1300 */
1301void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1302 struct kvm_memory_slot *slot,
1303 gfn_t gfn_offset, unsigned long mask)
1304{
018aabb5 1305 struct kvm_rmap_head *rmap_head;
f4b4b180
KH
1306
1307 while (mask) {
018aabb5
TY
1308 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1309 PT_PAGE_TABLE_LEVEL, slot);
1310 __rmap_clear_dirty(kvm, rmap_head);
f4b4b180
KH
1311
1312 /* clear the first set bit */
1313 mask &= mask - 1;
1314 }
1315}
1316EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1317
3b0f1d01
KH
1318/**
1319 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1320 * PT level pages.
1321 *
1322 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1323 * enable dirty logging for them.
1324 *
1325 * Used when we do not need to care about huge page mappings: e.g. during dirty
1326 * logging we do not have any such mappings.
1327 */
1328void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1329 struct kvm_memory_slot *slot,
1330 gfn_t gfn_offset, unsigned long mask)
1331{
88178fd4
KH
1332 if (kvm_x86_ops->enable_log_dirty_pt_masked)
1333 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1334 mask);
1335 else
1336 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
3b0f1d01
KH
1337}
1338
54bf36aa 1339static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
95d4c16c
TY
1340{
1341 struct kvm_memory_slot *slot;
018aabb5 1342 struct kvm_rmap_head *rmap_head;
5dc99b23 1343 int i;
2f84569f 1344 bool write_protected = false;
95d4c16c 1345
54bf36aa 1346 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
5dc99b23 1347
8a3d08f1 1348 for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
018aabb5
TY
1349 rmap_head = __gfn_to_rmap(gfn, i, slot);
1350 write_protected |= __rmap_write_protect(vcpu->kvm, rmap_head, true);
5dc99b23
TY
1351 }
1352
1353 return write_protected;
95d4c16c
TY
1354}
1355
018aabb5 1356static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
e930bffe 1357{
1e3f42f0
TY
1358 u64 *sptep;
1359 struct rmap_iterator iter;
6a49f85c 1360 bool flush = false;
e930bffe 1361
018aabb5 1362 while ((sptep = rmap_get_first(rmap_head, &iter))) {
6a49f85c 1363 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1e3f42f0
TY
1364
1365 drop_spte(kvm, sptep);
6a49f85c 1366 flush = true;
e930bffe 1367 }
1e3f42f0 1368
6a49f85c
XG
1369 return flush;
1370}
1371
018aabb5 1372static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
6a49f85c
XG
1373 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1374 unsigned long data)
1375{
018aabb5 1376 return kvm_zap_rmapp(kvm, rmap_head);
e930bffe
AA
1377}
1378
018aabb5 1379static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
8a9522d2
ALC
1380 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1381 unsigned long data)
3da0dd43 1382{
1e3f42f0
TY
1383 u64 *sptep;
1384 struct rmap_iterator iter;
3da0dd43 1385 int need_flush = 0;
1e3f42f0 1386 u64 new_spte;
3da0dd43 1387 pte_t *ptep = (pte_t *)data;
ba049e93 1388 kvm_pfn_t new_pfn;
3da0dd43
IE
1389
1390 WARN_ON(pte_huge(*ptep));
1391 new_pfn = pte_pfn(*ptep);
1e3f42f0 1392
0d536790 1393restart:
018aabb5 1394 for_each_rmap_spte(rmap_head, &iter, sptep) {
8a9522d2
ALC
1395 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1396 sptep, *sptep, gfn, level);
1e3f42f0 1397
3da0dd43 1398 need_flush = 1;
1e3f42f0 1399
3da0dd43 1400 if (pte_write(*ptep)) {
1e3f42f0 1401 drop_spte(kvm, sptep);
0d536790 1402 goto restart;
3da0dd43 1403 } else {
1e3f42f0 1404 new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
3da0dd43
IE
1405 new_spte |= (u64)new_pfn << PAGE_SHIFT;
1406
1407 new_spte &= ~PT_WRITABLE_MASK;
1408 new_spte &= ~SPTE_HOST_WRITEABLE;
b79b93f9 1409 new_spte &= ~shadow_accessed_mask;
1e3f42f0
TY
1410
1411 mmu_spte_clear_track_bits(sptep);
1412 mmu_spte_set(sptep, new_spte);
3da0dd43
IE
1413 }
1414 }
1e3f42f0 1415
3da0dd43
IE
1416 if (need_flush)
1417 kvm_flush_remote_tlbs(kvm);
1418
1419 return 0;
1420}
1421
6ce1f4e2
XG
1422struct slot_rmap_walk_iterator {
1423 /* input fields. */
1424 struct kvm_memory_slot *slot;
1425 gfn_t start_gfn;
1426 gfn_t end_gfn;
1427 int start_level;
1428 int end_level;
1429
1430 /* output fields. */
1431 gfn_t gfn;
018aabb5 1432 struct kvm_rmap_head *rmap;
6ce1f4e2
XG
1433 int level;
1434
1435 /* private field. */
018aabb5 1436 struct kvm_rmap_head *end_rmap;
6ce1f4e2
XG
1437};
1438
1439static void
1440rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1441{
1442 iterator->level = level;
1443 iterator->gfn = iterator->start_gfn;
1444 iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1445 iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1446 iterator->slot);
1447}
1448
1449static void
1450slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1451 struct kvm_memory_slot *slot, int start_level,
1452 int end_level, gfn_t start_gfn, gfn_t end_gfn)
1453{
1454 iterator->slot = slot;
1455 iterator->start_level = start_level;
1456 iterator->end_level = end_level;
1457 iterator->start_gfn = start_gfn;
1458 iterator->end_gfn = end_gfn;
1459
1460 rmap_walk_init_level(iterator, iterator->start_level);
1461}
1462
1463static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1464{
1465 return !!iterator->rmap;
1466}
1467
1468static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1469{
1470 if (++iterator->rmap <= iterator->end_rmap) {
1471 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1472 return;
1473 }
1474
1475 if (++iterator->level > iterator->end_level) {
1476 iterator->rmap = NULL;
1477 return;
1478 }
1479
1480 rmap_walk_init_level(iterator, iterator->level);
1481}
1482
1483#define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_, \
1484 _start_gfn, _end_gfn, _iter_) \
1485 for (slot_rmap_walk_init(_iter_, _slot_, _start_level_, \
1486 _end_level_, _start_gfn, _end_gfn); \
1487 slot_rmap_walk_okay(_iter_); \
1488 slot_rmap_walk_next(_iter_))
1489
84504ef3
TY
1490static int kvm_handle_hva_range(struct kvm *kvm,
1491 unsigned long start,
1492 unsigned long end,
1493 unsigned long data,
1494 int (*handler)(struct kvm *kvm,
018aabb5 1495 struct kvm_rmap_head *rmap_head,
048212d0 1496 struct kvm_memory_slot *slot,
8a9522d2
ALC
1497 gfn_t gfn,
1498 int level,
84504ef3 1499 unsigned long data))
e930bffe 1500{
bc6678a3 1501 struct kvm_memslots *slots;
be6ba0f0 1502 struct kvm_memory_slot *memslot;
6ce1f4e2
XG
1503 struct slot_rmap_walk_iterator iterator;
1504 int ret = 0;
9da0e4d5 1505 int i;
bc6678a3 1506
9da0e4d5
PB
1507 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1508 slots = __kvm_memslots(kvm, i);
1509 kvm_for_each_memslot(memslot, slots) {
1510 unsigned long hva_start, hva_end;
1511 gfn_t gfn_start, gfn_end;
e930bffe 1512
9da0e4d5
PB
1513 hva_start = max(start, memslot->userspace_addr);
1514 hva_end = min(end, memslot->userspace_addr +
1515 (memslot->npages << PAGE_SHIFT));
1516 if (hva_start >= hva_end)
1517 continue;
1518 /*
1519 * {gfn(page) | page intersects with [hva_start, hva_end)} =
1520 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1521 */
1522 gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1523 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1524
1525 for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1526 PT_MAX_HUGEPAGE_LEVEL,
1527 gfn_start, gfn_end - 1,
1528 &iterator)
1529 ret |= handler(kvm, iterator.rmap, memslot,
1530 iterator.gfn, iterator.level, data);
1531 }
e930bffe
AA
1532 }
1533
f395302e 1534 return ret;
e930bffe
AA
1535}
1536
84504ef3
TY
1537static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1538 unsigned long data,
018aabb5
TY
1539 int (*handler)(struct kvm *kvm,
1540 struct kvm_rmap_head *rmap_head,
048212d0 1541 struct kvm_memory_slot *slot,
8a9522d2 1542 gfn_t gfn, int level,
84504ef3
TY
1543 unsigned long data))
1544{
1545 return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
e930bffe
AA
1546}
1547
1548int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
1549{
3da0dd43
IE
1550 return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp);
1551}
1552
b3ae2096
TY
1553int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
1554{
1555 return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1556}
1557
3da0dd43
IE
1558void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1559{
8a8365c5 1560 kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
e930bffe
AA
1561}
1562
018aabb5 1563static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
8a9522d2
ALC
1564 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1565 unsigned long data)
e930bffe 1566{
1e3f42f0 1567 u64 *sptep;
79f702a6 1568 struct rmap_iterator uninitialized_var(iter);
e930bffe
AA
1569 int young = 0;
1570
57128468 1571 BUG_ON(!shadow_accessed_mask);
534e38b4 1572
018aabb5 1573 for_each_rmap_spte(rmap_head, &iter, sptep) {
3f6d8c8a 1574 if (*sptep & shadow_accessed_mask) {
e930bffe 1575 young = 1;
3f6d8c8a
XH
1576 clear_bit((ffs(shadow_accessed_mask) - 1),
1577 (unsigned long *)sptep);
e930bffe 1578 }
018aabb5 1579 }
0d536790 1580
8a9522d2 1581 trace_kvm_age_page(gfn, level, slot, young);
e930bffe
AA
1582 return young;
1583}
1584
018aabb5 1585static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
8a9522d2
ALC
1586 struct kvm_memory_slot *slot, gfn_t gfn,
1587 int level, unsigned long data)
8ee53820 1588{
1e3f42f0
TY
1589 u64 *sptep;
1590 struct rmap_iterator iter;
8ee53820
AA
1591 int young = 0;
1592
1593 /*
1594 * If there's no access bit in the secondary pte set by the
1595 * hardware it's up to gup-fast/gup to set the access bit in
1596 * the primary pte or in the page structure.
1597 */
1598 if (!shadow_accessed_mask)
1599 goto out;
1600
018aabb5 1601 for_each_rmap_spte(rmap_head, &iter, sptep) {
3f6d8c8a 1602 if (*sptep & shadow_accessed_mask) {
8ee53820
AA
1603 young = 1;
1604 break;
1605 }
018aabb5 1606 }
8ee53820
AA
1607out:
1608 return young;
1609}
1610
53a27b39
MT
1611#define RMAP_RECYCLE_THRESHOLD 1000
1612
852e3c19 1613static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
53a27b39 1614{
018aabb5 1615 struct kvm_rmap_head *rmap_head;
852e3c19
JR
1616 struct kvm_mmu_page *sp;
1617
1618 sp = page_header(__pa(spte));
53a27b39 1619
018aabb5 1620 rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
53a27b39 1621
018aabb5 1622 kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
53a27b39
MT
1623 kvm_flush_remote_tlbs(vcpu->kvm);
1624}
1625
57128468 1626int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
e930bffe 1627{
57128468
ALC
1628 /*
1629 * In case of absence of EPT Access and Dirty Bits supports,
1630 * emulate the accessed bit for EPT, by checking if this page has
1631 * an EPT mapping, and clearing it if it does. On the next access,
1632 * a new EPT mapping will be established.
1633 * This has some overhead, but not as much as the cost of swapping
1634 * out actively used pages or breaking up actively used hugepages.
1635 */
1636 if (!shadow_accessed_mask) {
1637 /*
1638 * We are holding the kvm->mmu_lock, and we are blowing up
1639 * shadow PTEs. MMU notifier consumers need to be kept at bay.
1640 * This is correct as long as we don't decouple the mmu_lock
1641 * protected regions (like invalidate_range_start|end does).
1642 */
1643 kvm->mmu_notifier_seq++;
1644 return kvm_handle_hva_range(kvm, start, end, 0,
1645 kvm_unmap_rmapp);
1646 }
1647
1648 return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
e930bffe
AA
1649}
1650
8ee53820
AA
1651int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1652{
1653 return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1654}
1655
d6c69ee9 1656#ifdef MMU_DEBUG
47ad8e68 1657static int is_empty_shadow_page(u64 *spt)
6aa8b732 1658{
139bdb2d
AK
1659 u64 *pos;
1660 u64 *end;
1661
47ad8e68 1662 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
3c915510 1663 if (is_shadow_present_pte(*pos)) {
b8688d51 1664 printk(KERN_ERR "%s: %p %llx\n", __func__,
139bdb2d 1665 pos, *pos);
6aa8b732 1666 return 0;
139bdb2d 1667 }
6aa8b732
AK
1668 return 1;
1669}
d6c69ee9 1670#endif
6aa8b732 1671
45221ab6
DH
1672/*
1673 * This value is the sum of all of the kvm instances's
1674 * kvm->arch.n_used_mmu_pages values. We need a global,
1675 * aggregate version in order to make the slab shrinker
1676 * faster
1677 */
1678static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
1679{
1680 kvm->arch.n_used_mmu_pages += nr;
1681 percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1682}
1683
834be0d8 1684static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
260746c0 1685{
fa4a2c08 1686 MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
7775834a 1687 hlist_del(&sp->hash_link);
bd4c86ea
XG
1688 list_del(&sp->link);
1689 free_page((unsigned long)sp->spt);
834be0d8
GN
1690 if (!sp->role.direct)
1691 free_page((unsigned long)sp->gfns);
e8ad9a70 1692 kmem_cache_free(mmu_page_header_cache, sp);
260746c0
AK
1693}
1694
cea0f0e7
AK
1695static unsigned kvm_page_table_hashfn(gfn_t gfn)
1696{
1ae0a13d 1697 return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
cea0f0e7
AK
1698}
1699
714b93da 1700static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
4db35314 1701 struct kvm_mmu_page *sp, u64 *parent_pte)
cea0f0e7 1702{
cea0f0e7
AK
1703 if (!parent_pte)
1704 return;
cea0f0e7 1705
67052b35 1706 pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
cea0f0e7
AK
1707}
1708
4db35314 1709static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
cea0f0e7
AK
1710 u64 *parent_pte)
1711{
67052b35 1712 pte_list_remove(parent_pte, &sp->parent_ptes);
cea0f0e7
AK
1713}
1714
bcdd9a93
XG
1715static void drop_parent_pte(struct kvm_mmu_page *sp,
1716 u64 *parent_pte)
1717{
1718 mmu_page_remove_parent_pte(sp, parent_pte);
1df9f2dc 1719 mmu_spte_clear_no_track(parent_pte);
bcdd9a93
XG
1720}
1721
47005792 1722static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
ad8cfbe3 1723{
67052b35 1724 struct kvm_mmu_page *sp;
7ddca7e4 1725
80feb89a
TY
1726 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
1727 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
67052b35 1728 if (!direct)
80feb89a 1729 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
67052b35 1730 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
5304b8d3
XG
1731
1732 /*
1733 * The active_mmu_pages list is the FIFO list, do not move the
1734 * page until it is zapped. kvm_zap_obsolete_pages depends on
1735 * this feature. See the comments in kvm_zap_obsolete_pages().
1736 */
67052b35 1737 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
67052b35
XG
1738 kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1739 return sp;
ad8cfbe3
MT
1740}
1741
67052b35 1742static void mark_unsync(u64 *spte);
1047df1f 1743static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
0074ff63 1744{
74c4e63a
TY
1745 u64 *sptep;
1746 struct rmap_iterator iter;
1747
1748 for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1749 mark_unsync(sptep);
1750 }
0074ff63
MT
1751}
1752
67052b35 1753static void mark_unsync(u64 *spte)
0074ff63 1754{
67052b35 1755 struct kvm_mmu_page *sp;
1047df1f 1756 unsigned int index;
0074ff63 1757
67052b35 1758 sp = page_header(__pa(spte));
1047df1f
XG
1759 index = spte - sp->spt;
1760 if (__test_and_set_bit(index, sp->unsync_child_bitmap))
0074ff63 1761 return;
1047df1f 1762 if (sp->unsync_children++)
0074ff63 1763 return;
1047df1f 1764 kvm_mmu_mark_parents_unsync(sp);
0074ff63
MT
1765}
1766
e8bc217a 1767static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
a4a8e6f7 1768 struct kvm_mmu_page *sp)
e8bc217a
MT
1769{
1770 return 1;
1771}
1772
a7052897
MT
1773static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
1774{
1775}
1776
0f53b5b1
XG
1777static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
1778 struct kvm_mmu_page *sp, u64 *spte,
7c562522 1779 const void *pte)
0f53b5b1
XG
1780{
1781 WARN_ON(1);
1782}
1783
60c8aec6
MT
1784#define KVM_PAGE_ARRAY_NR 16
1785
1786struct kvm_mmu_pages {
1787 struct mmu_page_and_offset {
1788 struct kvm_mmu_page *sp;
1789 unsigned int idx;
1790 } page[KVM_PAGE_ARRAY_NR];
1791 unsigned int nr;
1792};
1793
cded19f3
HE
1794static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1795 int idx)
4731d4c7 1796{
60c8aec6 1797 int i;
4731d4c7 1798
60c8aec6
MT
1799 if (sp->unsync)
1800 for (i=0; i < pvec->nr; i++)
1801 if (pvec->page[i].sp == sp)
1802 return 0;
1803
1804 pvec->page[pvec->nr].sp = sp;
1805 pvec->page[pvec->nr].idx = idx;
1806 pvec->nr++;
1807 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1808}
1809
fd951457
TY
1810static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1811{
1812 --sp->unsync_children;
1813 WARN_ON((int)sp->unsync_children < 0);
1814 __clear_bit(idx, sp->unsync_child_bitmap);
1815}
1816
60c8aec6
MT
1817static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1818 struct kvm_mmu_pages *pvec)
1819{
1820 int i, ret, nr_unsync_leaf = 0;
4731d4c7 1821
37178b8b 1822 for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
7a8f1a74 1823 struct kvm_mmu_page *child;
4731d4c7
MT
1824 u64 ent = sp->spt[i];
1825
fd951457
TY
1826 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1827 clear_unsync_child_bit(sp, i);
1828 continue;
1829 }
7a8f1a74
XG
1830
1831 child = page_header(ent & PT64_BASE_ADDR_MASK);
1832
1833 if (child->unsync_children) {
1834 if (mmu_pages_add(pvec, child, i))
1835 return -ENOSPC;
1836
1837 ret = __mmu_unsync_walk(child, pvec);
fd951457
TY
1838 if (!ret) {
1839 clear_unsync_child_bit(sp, i);
1840 continue;
1841 } else if (ret > 0) {
7a8f1a74 1842 nr_unsync_leaf += ret;
fd951457 1843 } else
7a8f1a74
XG
1844 return ret;
1845 } else if (child->unsync) {
1846 nr_unsync_leaf++;
1847 if (mmu_pages_add(pvec, child, i))
1848 return -ENOSPC;
1849 } else
fd951457 1850 clear_unsync_child_bit(sp, i);
4731d4c7
MT
1851 }
1852
60c8aec6
MT
1853 return nr_unsync_leaf;
1854}
1855
1856static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1857 struct kvm_mmu_pages *pvec)
1858{
1859 if (!sp->unsync_children)
1860 return 0;
1861
1862 mmu_pages_add(pvec, sp, 0);
1863 return __mmu_unsync_walk(sp, pvec);
4731d4c7
MT
1864}
1865
4731d4c7
MT
1866static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1867{
1868 WARN_ON(!sp->unsync);
5e1b3ddb 1869 trace_kvm_mmu_sync_page(sp);
4731d4c7
MT
1870 sp->unsync = 0;
1871 --kvm->stat.mmu_unsync;
1872}
1873
7775834a
XG
1874static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1875 struct list_head *invalid_list);
1876static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1877 struct list_head *invalid_list);
4731d4c7 1878
f34d251d
XG
1879/*
1880 * NOTE: we should pay more attention on the zapped-obsolete page
1881 * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
1882 * since it has been deleted from active_mmu_pages but still can be found
1883 * at hast list.
1884 *
1885 * for_each_gfn_indirect_valid_sp has skipped that kind of page and
1886 * kvm_mmu_get_page(), the only user of for_each_gfn_sp(), has skipped
1887 * all the obsolete pages.
1888 */
1044b030
TY
1889#define for_each_gfn_sp(_kvm, _sp, _gfn) \
1890 hlist_for_each_entry(_sp, \
1891 &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
1892 if ((_sp)->gfn != (_gfn)) {} else
1893
1894#define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
1895 for_each_gfn_sp(_kvm, _sp, _gfn) \
1896 if ((_sp)->role.direct || (_sp)->role.invalid) {} else
7ae680eb 1897
f918b443 1898/* @sp->gfn should be write-protected at the call site */
1d9dc7e0 1899static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
d98ba053 1900 struct list_head *invalid_list, bool clear_unsync)
4731d4c7 1901{
5b7e0102 1902 if (sp->role.cr4_pae != !!is_pae(vcpu)) {
d98ba053 1903 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
4731d4c7
MT
1904 return 1;
1905 }
1906
f918b443 1907 if (clear_unsync)
1d9dc7e0 1908 kvm_unlink_unsync_page(vcpu->kvm, sp);
1d9dc7e0 1909
a4a8e6f7 1910 if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
d98ba053 1911 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
4731d4c7
MT
1912 return 1;
1913 }
1914
77c3913b 1915 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4731d4c7
MT
1916 return 0;
1917}
1918
1d9dc7e0
XG
1919static int kvm_sync_page_transient(struct kvm_vcpu *vcpu,
1920 struct kvm_mmu_page *sp)
1921{
d98ba053 1922 LIST_HEAD(invalid_list);
1d9dc7e0
XG
1923 int ret;
1924
d98ba053 1925 ret = __kvm_sync_page(vcpu, sp, &invalid_list, false);
be71e061 1926 if (ret)
d98ba053
XG
1927 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
1928
1d9dc7e0
XG
1929 return ret;
1930}
1931
e37fa785
XG
1932#ifdef CONFIG_KVM_MMU_AUDIT
1933#include "mmu_audit.c"
1934#else
1935static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
1936static void mmu_audit_disable(void) { }
1937#endif
1938
d98ba053
XG
1939static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1940 struct list_head *invalid_list)
1d9dc7e0 1941{
d98ba053 1942 return __kvm_sync_page(vcpu, sp, invalid_list, true);
1d9dc7e0
XG
1943}
1944
9f1a122f
XG
1945/* @gfn should be write-protected at the call site */
1946static void kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn)
1947{
9f1a122f 1948 struct kvm_mmu_page *s;
d98ba053 1949 LIST_HEAD(invalid_list);
9f1a122f
XG
1950 bool flush = false;
1951
b67bfe0d 1952 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
7ae680eb 1953 if (!s->unsync)
9f1a122f
XG
1954 continue;
1955
1956 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
a4a8e6f7 1957 kvm_unlink_unsync_page(vcpu->kvm, s);
9f1a122f 1958 if ((s->role.cr4_pae != !!is_pae(vcpu)) ||
a4a8e6f7 1959 (vcpu->arch.mmu.sync_page(vcpu, s))) {
d98ba053 1960 kvm_mmu_prepare_zap_page(vcpu->kvm, s, &invalid_list);
9f1a122f
XG
1961 continue;
1962 }
9f1a122f
XG
1963 flush = true;
1964 }
1965
d98ba053 1966 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
9f1a122f 1967 if (flush)
77c3913b 1968 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9f1a122f
XG
1969}
1970
60c8aec6
MT
1971struct mmu_page_path {
1972 struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
1973 unsigned int idx[PT64_ROOT_LEVEL-1];
4731d4c7
MT
1974};
1975
60c8aec6
MT
1976#define for_each_sp(pvec, sp, parents, i) \
1977 for (i = mmu_pages_next(&pvec, &parents, -1), \
1978 sp = pvec.page[i].sp; \
1979 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
1980 i = mmu_pages_next(&pvec, &parents, i))
1981
cded19f3
HE
1982static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1983 struct mmu_page_path *parents,
1984 int i)
60c8aec6
MT
1985{
1986 int n;
1987
1988 for (n = i+1; n < pvec->nr; n++) {
1989 struct kvm_mmu_page *sp = pvec->page[n].sp;
1990
1991 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1992 parents->idx[0] = pvec->page[n].idx;
1993 return n;
1994 }
1995
1996 parents->parent[sp->role.level-2] = sp;
1997 parents->idx[sp->role.level-1] = pvec->page[n].idx;
1998 }
1999
2000 return n;
2001}
2002
cded19f3 2003static void mmu_pages_clear_parents(struct mmu_page_path *parents)
4731d4c7 2004{
60c8aec6
MT
2005 struct kvm_mmu_page *sp;
2006 unsigned int level = 0;
2007
2008 do {
2009 unsigned int idx = parents->idx[level];
4731d4c7 2010
60c8aec6
MT
2011 sp = parents->parent[level];
2012 if (!sp)
2013 return;
2014
fd951457 2015 clear_unsync_child_bit(sp, idx);
60c8aec6
MT
2016 level++;
2017 } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
4731d4c7
MT
2018}
2019
60c8aec6
MT
2020static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
2021 struct mmu_page_path *parents,
2022 struct kvm_mmu_pages *pvec)
4731d4c7 2023{
60c8aec6
MT
2024 parents->parent[parent->role.level-1] = NULL;
2025 pvec->nr = 0;
2026}
4731d4c7 2027
60c8aec6
MT
2028static void mmu_sync_children(struct kvm_vcpu *vcpu,
2029 struct kvm_mmu_page *parent)
2030{
2031 int i;
2032 struct kvm_mmu_page *sp;
2033 struct mmu_page_path parents;
2034 struct kvm_mmu_pages pages;
d98ba053 2035 LIST_HEAD(invalid_list);
60c8aec6
MT
2036
2037 kvm_mmu_pages_init(parent, &parents, &pages);
2038 while (mmu_unsync_walk(parent, &pages)) {
2f84569f 2039 bool protected = false;
b1a36821
MT
2040
2041 for_each_sp(pages, sp, parents, i)
54bf36aa 2042 protected |= rmap_write_protect(vcpu, sp->gfn);
b1a36821
MT
2043
2044 if (protected)
2045 kvm_flush_remote_tlbs(vcpu->kvm);
2046
60c8aec6 2047 for_each_sp(pages, sp, parents, i) {
d98ba053 2048 kvm_sync_page(vcpu, sp, &invalid_list);
60c8aec6
MT
2049 mmu_pages_clear_parents(&parents);
2050 }
d98ba053 2051 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
4731d4c7 2052 cond_resched_lock(&vcpu->kvm->mmu_lock);
60c8aec6
MT
2053 kvm_mmu_pages_init(parent, &parents, &pages);
2054 }
4731d4c7
MT
2055}
2056
a30f47cb
XG
2057static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2058{
2059 sp->write_flooding_count = 0;
2060}
2061
2062static void clear_sp_write_flooding_count(u64 *spte)
2063{
2064 struct kvm_mmu_page *sp = page_header(__pa(spte));
2065
2066 __clear_sp_write_flooding_count(sp);
2067}
2068
5304b8d3
XG
2069static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2070{
2071 return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2072}
2073
cea0f0e7
AK
2074static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2075 gfn_t gfn,
2076 gva_t gaddr,
2077 unsigned level,
f6e2c02b 2078 int direct,
bb11c6c9 2079 unsigned access)
cea0f0e7
AK
2080{
2081 union kvm_mmu_page_role role;
cea0f0e7 2082 unsigned quadrant;
9f1a122f 2083 struct kvm_mmu_page *sp;
9f1a122f 2084 bool need_sync = false;
cea0f0e7 2085
a770f6f2 2086 role = vcpu->arch.mmu.base_role;
cea0f0e7 2087 role.level = level;
f6e2c02b 2088 role.direct = direct;
84b0c8c6 2089 if (role.direct)
5b7e0102 2090 role.cr4_pae = 0;
41074d07 2091 role.access = access;
c5a78f2b
JR
2092 if (!vcpu->arch.mmu.direct_map
2093 && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
cea0f0e7
AK
2094 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2095 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2096 role.quadrant = quadrant;
2097 }
b67bfe0d 2098 for_each_gfn_sp(vcpu->kvm, sp, gfn) {
7f52af74
XG
2099 if (is_obsolete_sp(vcpu->kvm, sp))
2100 continue;
2101
7ae680eb
XG
2102 if (!need_sync && sp->unsync)
2103 need_sync = true;
4731d4c7 2104
7ae680eb
XG
2105 if (sp->role.word != role.word)
2106 continue;
4731d4c7 2107
7ae680eb
XG
2108 if (sp->unsync && kvm_sync_page_transient(vcpu, sp))
2109 break;
e02aa901 2110
98bba238 2111 if (sp->unsync_children)
a8eeb04a 2112 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
e02aa901 2113
a30f47cb 2114 __clear_sp_write_flooding_count(sp);
7ae680eb
XG
2115 trace_kvm_mmu_get_page(sp, false);
2116 return sp;
2117 }
47005792 2118
dfc5aa00 2119 ++vcpu->kvm->stat.mmu_cache_miss;
47005792
TY
2120
2121 sp = kvm_mmu_alloc_page(vcpu, direct);
2122
4db35314
AK
2123 sp->gfn = gfn;
2124 sp->role = role;
7ae680eb
XG
2125 hlist_add_head(&sp->hash_link,
2126 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
f6e2c02b 2127 if (!direct) {
54bf36aa 2128 if (rmap_write_protect(vcpu, gfn))
b1a36821 2129 kvm_flush_remote_tlbs(vcpu->kvm);
9f1a122f
XG
2130 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2131 kvm_sync_pages(vcpu, gfn);
2132
3ed1a478 2133 account_shadowed(vcpu->kvm, sp);
4731d4c7 2134 }
5304b8d3 2135 sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
77492664 2136 clear_page(sp->spt);
f691fe1d 2137 trace_kvm_mmu_get_page(sp, true);
4db35314 2138 return sp;
cea0f0e7
AK
2139}
2140
2d11123a
AK
2141static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2142 struct kvm_vcpu *vcpu, u64 addr)
2143{
2144 iterator->addr = addr;
2145 iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
2146 iterator->level = vcpu->arch.mmu.shadow_root_level;
81407ca5
JR
2147
2148 if (iterator->level == PT64_ROOT_LEVEL &&
2149 vcpu->arch.mmu.root_level < PT64_ROOT_LEVEL &&
2150 !vcpu->arch.mmu.direct_map)
2151 --iterator->level;
2152
2d11123a
AK
2153 if (iterator->level == PT32E_ROOT_LEVEL) {
2154 iterator->shadow_addr
2155 = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
2156 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2157 --iterator->level;
2158 if (!iterator->shadow_addr)
2159 iterator->level = 0;
2160 }
2161}
2162
2163static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2164{
2165 if (iterator->level < PT_PAGE_TABLE_LEVEL)
2166 return false;
4d88954d 2167
2d11123a
AK
2168 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2169 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2170 return true;
2171}
2172
c2a2ac2b
XG
2173static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2174 u64 spte)
2d11123a 2175{
c2a2ac2b 2176 if (is_last_spte(spte, iterator->level)) {
052331be
XG
2177 iterator->level = 0;
2178 return;
2179 }
2180
c2a2ac2b 2181 iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2d11123a
AK
2182 --iterator->level;
2183}
2184
c2a2ac2b
XG
2185static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2186{
2187 return __shadow_walk_next(iterator, *iterator->sptep);
2188}
2189
98bba238
TY
2190static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2191 struct kvm_mmu_page *sp)
32ef26a3
AK
2192{
2193 u64 spte;
2194
7a1638ce
YZ
2195 BUILD_BUG_ON(VMX_EPT_READABLE_MASK != PT_PRESENT_MASK ||
2196 VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2197
24db2734 2198 spte = __pa(sp->spt) | PT_PRESENT_MASK | PT_WRITABLE_MASK |
0e3d0648 2199 shadow_user_mask | shadow_x_mask | shadow_accessed_mask;
24db2734 2200
1df9f2dc 2201 mmu_spte_set(sptep, spte);
98bba238
TY
2202
2203 mmu_page_add_parent_pte(vcpu, sp, sptep);
2204
2205 if (sp->unsync_children || sp->unsync)
2206 mark_unsync(sptep);
32ef26a3
AK
2207}
2208
a357bd22
AK
2209static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2210 unsigned direct_access)
2211{
2212 if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2213 struct kvm_mmu_page *child;
2214
2215 /*
2216 * For the direct sp, if the guest pte's dirty bit
2217 * changed form clean to dirty, it will corrupt the
2218 * sp's access: allow writable in the read-only sp,
2219 * so we should update the spte at this point to get
2220 * a new sp with the correct access.
2221 */
2222 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2223 if (child->role.access == direct_access)
2224 return;
2225
bcdd9a93 2226 drop_parent_pte(child, sptep);
a357bd22
AK
2227 kvm_flush_remote_tlbs(vcpu->kvm);
2228 }
2229}
2230
505aef8f 2231static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
38e3b2b2
XG
2232 u64 *spte)
2233{
2234 u64 pte;
2235 struct kvm_mmu_page *child;
2236
2237 pte = *spte;
2238 if (is_shadow_present_pte(pte)) {
505aef8f 2239 if (is_last_spte(pte, sp->role.level)) {
c3707958 2240 drop_spte(kvm, spte);
505aef8f
XG
2241 if (is_large_pte(pte))
2242 --kvm->stat.lpages;
2243 } else {
38e3b2b2 2244 child = page_header(pte & PT64_BASE_ADDR_MASK);
bcdd9a93 2245 drop_parent_pte(child, spte);
38e3b2b2 2246 }
505aef8f
XG
2247 return true;
2248 }
2249
2250 if (is_mmio_spte(pte))
ce88decf 2251 mmu_spte_clear_no_track(spte);
c3707958 2252
505aef8f 2253 return false;
38e3b2b2
XG
2254}
2255
90cb0529 2256static void kvm_mmu_page_unlink_children(struct kvm *kvm,
4db35314 2257 struct kvm_mmu_page *sp)
a436036b 2258{
697fe2e2 2259 unsigned i;
697fe2e2 2260
38e3b2b2
XG
2261 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2262 mmu_page_zap_pte(kvm, sp, sp->spt + i);
a436036b
AK
2263}
2264
31aa2b44 2265static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
a436036b 2266{
1e3f42f0
TY
2267 u64 *sptep;
2268 struct rmap_iterator iter;
a436036b 2269
018aabb5 2270 while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
1e3f42f0 2271 drop_parent_pte(sp, sptep);
31aa2b44
AK
2272}
2273
60c8aec6 2274static int mmu_zap_unsync_children(struct kvm *kvm,
7775834a
XG
2275 struct kvm_mmu_page *parent,
2276 struct list_head *invalid_list)
4731d4c7 2277{
60c8aec6
MT
2278 int i, zapped = 0;
2279 struct mmu_page_path parents;
2280 struct kvm_mmu_pages pages;
4731d4c7 2281
60c8aec6 2282 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
4731d4c7 2283 return 0;
60c8aec6
MT
2284
2285 kvm_mmu_pages_init(parent, &parents, &pages);
2286 while (mmu_unsync_walk(parent, &pages)) {
2287 struct kvm_mmu_page *sp;
2288
2289 for_each_sp(pages, sp, parents, i) {
7775834a 2290 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
60c8aec6 2291 mmu_pages_clear_parents(&parents);
77662e00 2292 zapped++;
60c8aec6 2293 }
60c8aec6
MT
2294 kvm_mmu_pages_init(parent, &parents, &pages);
2295 }
2296
2297 return zapped;
4731d4c7
MT
2298}
2299
7775834a
XG
2300static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2301 struct list_head *invalid_list)
31aa2b44 2302{
4731d4c7 2303 int ret;
f691fe1d 2304
7775834a 2305 trace_kvm_mmu_prepare_zap_page(sp);
31aa2b44 2306 ++kvm->stat.mmu_shadow_zapped;
7775834a 2307 ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
4db35314 2308 kvm_mmu_page_unlink_children(kvm, sp);
31aa2b44 2309 kvm_mmu_unlink_parents(kvm, sp);
5304b8d3 2310
f6e2c02b 2311 if (!sp->role.invalid && !sp->role.direct)
3ed1a478 2312 unaccount_shadowed(kvm, sp);
5304b8d3 2313
4731d4c7
MT
2314 if (sp->unsync)
2315 kvm_unlink_unsync_page(kvm, sp);
4db35314 2316 if (!sp->root_count) {
54a4f023
GJ
2317 /* Count self */
2318 ret++;
7775834a 2319 list_move(&sp->link, invalid_list);
aa6bd187 2320 kvm_mod_used_mmu_pages(kvm, -1);
2e53d63a 2321 } else {
5b5c6a5a 2322 list_move(&sp->link, &kvm->arch.active_mmu_pages);
05988d72
GN
2323
2324 /*
2325 * The obsolete pages can not be used on any vcpus.
2326 * See the comments in kvm_mmu_invalidate_zap_all_pages().
2327 */
2328 if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2329 kvm_reload_remote_mmus(kvm);
2e53d63a 2330 }
7775834a
XG
2331
2332 sp->role.invalid = 1;
4731d4c7 2333 return ret;
a436036b
AK
2334}
2335
7775834a
XG
2336static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2337 struct list_head *invalid_list)
2338{
945315b9 2339 struct kvm_mmu_page *sp, *nsp;
7775834a
XG
2340
2341 if (list_empty(invalid_list))
2342 return;
2343
c142786c
AK
2344 /*
2345 * wmb: make sure everyone sees our modifications to the page tables
2346 * rmb: make sure we see changes to vcpu->mode
2347 */
2348 smp_mb();
4f022648 2349
c142786c
AK
2350 /*
2351 * Wait for all vcpus to exit guest mode and/or lockless shadow
2352 * page table walks.
2353 */
2354 kvm_flush_remote_tlbs(kvm);
c2a2ac2b 2355
945315b9 2356 list_for_each_entry_safe(sp, nsp, invalid_list, link) {
7775834a 2357 WARN_ON(!sp->role.invalid || sp->root_count);
aa6bd187 2358 kvm_mmu_free_page(sp);
945315b9 2359 }
7775834a
XG
2360}
2361
5da59607
TY
2362static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2363 struct list_head *invalid_list)
2364{
2365 struct kvm_mmu_page *sp;
2366
2367 if (list_empty(&kvm->arch.active_mmu_pages))
2368 return false;
2369
d74c0e6b
GT
2370 sp = list_last_entry(&kvm->arch.active_mmu_pages,
2371 struct kvm_mmu_page, link);
5da59607
TY
2372 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2373
2374 return true;
2375}
2376
82ce2c96
IE
2377/*
2378 * Changing the number of mmu pages allocated to the vm
49d5ca26 2379 * Note: if goal_nr_mmu_pages is too small, you will get dead lock
82ce2c96 2380 */
49d5ca26 2381void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
82ce2c96 2382{
d98ba053 2383 LIST_HEAD(invalid_list);
82ce2c96 2384
b34cb590
TY
2385 spin_lock(&kvm->mmu_lock);
2386
49d5ca26 2387 if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
5da59607
TY
2388 /* Need to free some mmu pages to achieve the goal. */
2389 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2390 if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2391 break;
82ce2c96 2392
aa6bd187 2393 kvm_mmu_commit_zap_page(kvm, &invalid_list);
49d5ca26 2394 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
82ce2c96 2395 }
82ce2c96 2396
49d5ca26 2397 kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
b34cb590
TY
2398
2399 spin_unlock(&kvm->mmu_lock);
82ce2c96
IE
2400}
2401
1cb3f3ae 2402int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
a436036b 2403{
4db35314 2404 struct kvm_mmu_page *sp;
d98ba053 2405 LIST_HEAD(invalid_list);
a436036b
AK
2406 int r;
2407
9ad17b10 2408 pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
a436036b 2409 r = 0;
1cb3f3ae 2410 spin_lock(&kvm->mmu_lock);
b67bfe0d 2411 for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
9ad17b10 2412 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
7ae680eb
XG
2413 sp->role.word);
2414 r = 1;
f41d335a 2415 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7ae680eb 2416 }
d98ba053 2417 kvm_mmu_commit_zap_page(kvm, &invalid_list);
1cb3f3ae
XG
2418 spin_unlock(&kvm->mmu_lock);
2419
a436036b 2420 return r;
cea0f0e7 2421}
1cb3f3ae 2422EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
cea0f0e7 2423
9cf5cf5a
XG
2424static void __kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2425{
2426 trace_kvm_mmu_unsync_page(sp);
2427 ++vcpu->kvm->stat.mmu_unsync;
2428 sp->unsync = 1;
2429
2430 kvm_mmu_mark_parents_unsync(sp);
9cf5cf5a
XG
2431}
2432
2433static void kvm_unsync_pages(struct kvm_vcpu *vcpu, gfn_t gfn)
4731d4c7 2434{
4731d4c7 2435 struct kvm_mmu_page *s;
9cf5cf5a 2436
b67bfe0d 2437 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
7ae680eb 2438 if (s->unsync)
4731d4c7 2439 continue;
9cf5cf5a
XG
2440 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2441 __kvm_unsync_page(vcpu, s);
4731d4c7 2442 }
4731d4c7
MT
2443}
2444
2445static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2446 bool can_unsync)
2447{
9cf5cf5a 2448 struct kvm_mmu_page *s;
9cf5cf5a
XG
2449 bool need_unsync = false;
2450
b67bfe0d 2451 for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
36a2e677
XG
2452 if (!can_unsync)
2453 return 1;
2454
9cf5cf5a 2455 if (s->role.level != PT_PAGE_TABLE_LEVEL)
4731d4c7 2456 return 1;
9cf5cf5a 2457
9bb4f6b1 2458 if (!s->unsync)
9cf5cf5a 2459 need_unsync = true;
4731d4c7 2460 }
9cf5cf5a
XG
2461 if (need_unsync)
2462 kvm_unsync_pages(vcpu, gfn);
4731d4c7
MT
2463 return 0;
2464}
2465
ba049e93 2466static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
d1fe9219
PB
2467{
2468 if (pfn_valid(pfn))
2469 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn));
2470
2471 return true;
2472}
2473
d555c333 2474static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
c2288505 2475 unsigned pte_access, int level,
ba049e93 2476 gfn_t gfn, kvm_pfn_t pfn, bool speculative,
9bdbba13 2477 bool can_unsync, bool host_writable)
1c4f1fd6 2478{
6e7d0354 2479 u64 spte;
1e73f9dd 2480 int ret = 0;
64d4d521 2481
54bf36aa 2482 if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
ce88decf
XG
2483 return 0;
2484
982c2565 2485 spte = PT_PRESENT_MASK;
947da538 2486 if (!speculative)
3201b5d9 2487 spte |= shadow_accessed_mask;
640d9b0d 2488
7b52345e
SY
2489 if (pte_access & ACC_EXEC_MASK)
2490 spte |= shadow_x_mask;
2491 else
2492 spte |= shadow_nx_mask;
49fde340 2493
1c4f1fd6 2494 if (pte_access & ACC_USER_MASK)
7b52345e 2495 spte |= shadow_user_mask;
49fde340 2496
852e3c19 2497 if (level > PT_PAGE_TABLE_LEVEL)
05da4558 2498 spte |= PT_PAGE_SIZE_MASK;
b0bc3ee2 2499 if (tdp_enabled)
4b12f0de 2500 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
d1fe9219 2501 kvm_is_mmio_pfn(pfn));
1c4f1fd6 2502
9bdbba13 2503 if (host_writable)
1403283a 2504 spte |= SPTE_HOST_WRITEABLE;
f8e453b0
XG
2505 else
2506 pte_access &= ~ACC_WRITE_MASK;
1403283a 2507
35149e21 2508 spte |= (u64)pfn << PAGE_SHIFT;
1c4f1fd6 2509
c2288505 2510 if (pte_access & ACC_WRITE_MASK) {
1c4f1fd6 2511
c2193463 2512 /*
7751babd
XG
2513 * Other vcpu creates new sp in the window between
2514 * mapping_level() and acquiring mmu-lock. We can
2515 * allow guest to retry the access, the mapping can
2516 * be fixed if guest refault.
c2193463 2517 */
852e3c19 2518 if (level > PT_PAGE_TABLE_LEVEL &&
92f94f1e 2519 mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
be38d276 2520 goto done;
38187c83 2521
49fde340 2522 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
1c4f1fd6 2523
ecc5589f
MT
2524 /*
2525 * Optimization: for pte sync, if spte was writable the hash
2526 * lookup is unnecessary (and expensive). Write protection
2527 * is responsibility of mmu_get_page / kvm_sync_page.
2528 * Same reasoning can be applied to dirty page accounting.
2529 */
8dae4445 2530 if (!can_unsync && is_writable_pte(*sptep))
ecc5589f
MT
2531 goto set_pte;
2532
4731d4c7 2533 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
9ad17b10 2534 pgprintk("%s: found shadow page for %llx, marking ro\n",
b8688d51 2535 __func__, gfn);
1e73f9dd 2536 ret = 1;
1c4f1fd6 2537 pte_access &= ~ACC_WRITE_MASK;
49fde340 2538 spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
1c4f1fd6
AK
2539 }
2540 }
2541
9b51a630 2542 if (pte_access & ACC_WRITE_MASK) {
54bf36aa 2543 kvm_vcpu_mark_page_dirty(vcpu, gfn);
9b51a630
KH
2544 spte |= shadow_dirty_mask;
2545 }
1c4f1fd6 2546
38187c83 2547set_pte:
6e7d0354 2548 if (mmu_spte_update(sptep, spte))
b330aa0c 2549 kvm_flush_remote_tlbs(vcpu->kvm);
be38d276 2550done:
1e73f9dd
MT
2551 return ret;
2552}
2553
029499b4 2554static bool mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
ba049e93 2555 int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
029499b4 2556 bool speculative, bool host_writable)
1e73f9dd
MT
2557{
2558 int was_rmapped = 0;
53a27b39 2559 int rmap_count;
029499b4 2560 bool emulate = false;
1e73f9dd 2561
f7616203
XG
2562 pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2563 *sptep, write_fault, gfn);
1e73f9dd 2564
afd28fe1 2565 if (is_shadow_present_pte(*sptep)) {
1e73f9dd
MT
2566 /*
2567 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2568 * the parent of the now unreachable PTE.
2569 */
852e3c19
JR
2570 if (level > PT_PAGE_TABLE_LEVEL &&
2571 !is_large_pte(*sptep)) {
1e73f9dd 2572 struct kvm_mmu_page *child;
d555c333 2573 u64 pte = *sptep;
1e73f9dd
MT
2574
2575 child = page_header(pte & PT64_BASE_ADDR_MASK);
bcdd9a93 2576 drop_parent_pte(child, sptep);
3be2264b 2577 kvm_flush_remote_tlbs(vcpu->kvm);
d555c333 2578 } else if (pfn != spte_to_pfn(*sptep)) {
9ad17b10 2579 pgprintk("hfn old %llx new %llx\n",
d555c333 2580 spte_to_pfn(*sptep), pfn);
c3707958 2581 drop_spte(vcpu->kvm, sptep);
91546356 2582 kvm_flush_remote_tlbs(vcpu->kvm);
6bed6b9e
JR
2583 } else
2584 was_rmapped = 1;
1e73f9dd 2585 }
852e3c19 2586
c2288505
XG
2587 if (set_spte(vcpu, sptep, pte_access, level, gfn, pfn, speculative,
2588 true, host_writable)) {
1e73f9dd 2589 if (write_fault)
029499b4 2590 emulate = true;
77c3913b 2591 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
a378b4e6 2592 }
1e73f9dd 2593
029499b4
TY
2594 if (unlikely(is_mmio_spte(*sptep)))
2595 emulate = true;
ce88decf 2596
d555c333 2597 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
9ad17b10 2598 pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
d555c333 2599 is_large_pte(*sptep)? "2MB" : "4kB",
a205bc19
JR
2600 *sptep & PT_PRESENT_MASK ?"RW":"R", gfn,
2601 *sptep, sptep);
d555c333 2602 if (!was_rmapped && is_large_pte(*sptep))
05da4558
MT
2603 ++vcpu->kvm->stat.lpages;
2604
ffb61bb3 2605 if (is_shadow_present_pte(*sptep)) {
ffb61bb3
XG
2606 if (!was_rmapped) {
2607 rmap_count = rmap_add(vcpu, sptep, gfn);
2608 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
2609 rmap_recycle(vcpu, sptep, gfn);
2610 }
1c4f1fd6 2611 }
cb9aaa30 2612
f3ac1a4b 2613 kvm_release_pfn_clean(pfn);
029499b4
TY
2614
2615 return emulate;
1c4f1fd6
AK
2616}
2617
ba049e93 2618static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
957ed9ef
XG
2619 bool no_dirty_log)
2620{
2621 struct kvm_memory_slot *slot;
957ed9ef 2622
5d163b1c 2623 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
903816fa 2624 if (!slot)
6c8ee57b 2625 return KVM_PFN_ERR_FAULT;
957ed9ef 2626
037d92dc 2627 return gfn_to_pfn_memslot_atomic(slot, gfn);
957ed9ef
XG
2628}
2629
2630static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2631 struct kvm_mmu_page *sp,
2632 u64 *start, u64 *end)
2633{
2634 struct page *pages[PTE_PREFETCH_NUM];
d9ef13c2 2635 struct kvm_memory_slot *slot;
957ed9ef
XG
2636 unsigned access = sp->role.access;
2637 int i, ret;
2638 gfn_t gfn;
2639
2640 gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
d9ef13c2
PB
2641 slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2642 if (!slot)
957ed9ef
XG
2643 return -1;
2644
d9ef13c2 2645 ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
957ed9ef
XG
2646 if (ret <= 0)
2647 return -1;
2648
2649 for (i = 0; i < ret; i++, gfn++, start++)
029499b4
TY
2650 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
2651 page_to_pfn(pages[i]), true, true);
957ed9ef
XG
2652
2653 return 0;
2654}
2655
2656static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2657 struct kvm_mmu_page *sp, u64 *sptep)
2658{
2659 u64 *spte, *start = NULL;
2660 int i;
2661
2662 WARN_ON(!sp->role.direct);
2663
2664 i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2665 spte = sp->spt + i;
2666
2667 for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
c3707958 2668 if (is_shadow_present_pte(*spte) || spte == sptep) {
957ed9ef
XG
2669 if (!start)
2670 continue;
2671 if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2672 break;
2673 start = NULL;
2674 } else if (!start)
2675 start = spte;
2676 }
2677}
2678
2679static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2680{
2681 struct kvm_mmu_page *sp;
2682
2683 /*
2684 * Since it's no accessed bit on EPT, it's no way to
2685 * distinguish between actually accessed translations
2686 * and prefetched, so disable pte prefetch if EPT is
2687 * enabled.
2688 */
2689 if (!shadow_accessed_mask)
2690 return;
2691
2692 sp = page_header(__pa(sptep));
2693 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
2694 return;
2695
2696 __direct_pte_prefetch(vcpu, sp, sptep);
2697}
2698
7ee0e5b2 2699static int __direct_map(struct kvm_vcpu *vcpu, int write, int map_writable,
ba049e93 2700 int level, gfn_t gfn, kvm_pfn_t pfn, bool prefault)
140754bc 2701{
9f652d21 2702 struct kvm_shadow_walk_iterator iterator;
140754bc 2703 struct kvm_mmu_page *sp;
b90a0e6c 2704 int emulate = 0;
140754bc 2705 gfn_t pseudo_gfn;
6aa8b732 2706
989c6b34
MT
2707 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2708 return 0;
2709
9f652d21 2710 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
852e3c19 2711 if (iterator.level == level) {
029499b4
TY
2712 emulate = mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
2713 write, level, gfn, pfn, prefault,
2714 map_writable);
957ed9ef 2715 direct_pte_prefetch(vcpu, iterator.sptep);
9f652d21
AK
2716 ++vcpu->stat.pf_fixed;
2717 break;
6aa8b732
AK
2718 }
2719
404381c5 2720 drop_large_spte(vcpu, iterator.sptep);
c3707958 2721 if (!is_shadow_present_pte(*iterator.sptep)) {
c9fa0b3b
LJ
2722 u64 base_addr = iterator.addr;
2723
2724 base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
2725 pseudo_gfn = base_addr >> PAGE_SHIFT;
9f652d21 2726 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
bb11c6c9 2727 iterator.level - 1, 1, ACC_ALL);
140754bc 2728
98bba238 2729 link_shadow_page(vcpu, iterator.sptep, sp);
9f652d21
AK
2730 }
2731 }
b90a0e6c 2732 return emulate;
6aa8b732
AK
2733}
2734
77db5cbd 2735static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
bf998156 2736{
77db5cbd
HY
2737 siginfo_t info;
2738
2739 info.si_signo = SIGBUS;
2740 info.si_errno = 0;
2741 info.si_code = BUS_MCEERR_AR;
2742 info.si_addr = (void __user *)address;
2743 info.si_addr_lsb = PAGE_SHIFT;
bf998156 2744
77db5cbd 2745 send_sig_info(SIGBUS, &info, tsk);
bf998156
HY
2746}
2747
ba049e93 2748static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
bf998156 2749{
4d8b81ab
XG
2750 /*
2751 * Do not cache the mmio info caused by writing the readonly gfn
2752 * into the spte otherwise read access on readonly gfn also can
2753 * caused mmio page fault and treat it as mmio access.
2754 * Return 1 to tell kvm to emulate it.
2755 */
2756 if (pfn == KVM_PFN_ERR_RO_FAULT)
2757 return 1;
2758
e6c1502b 2759 if (pfn == KVM_PFN_ERR_HWPOISON) {
54bf36aa 2760 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
bf998156 2761 return 0;
d7c55201 2762 }
edba23e5 2763
d7c55201 2764 return -EFAULT;
bf998156
HY
2765}
2766
936a5fe6 2767static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
ba049e93
DW
2768 gfn_t *gfnp, kvm_pfn_t *pfnp,
2769 int *levelp)
936a5fe6 2770{
ba049e93 2771 kvm_pfn_t pfn = *pfnp;
936a5fe6
AA
2772 gfn_t gfn = *gfnp;
2773 int level = *levelp;
2774
2775 /*
2776 * Check if it's a transparent hugepage. If this would be an
2777 * hugetlbfs page, level wouldn't be set to
2778 * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
2779 * here.
2780 */
bf4bea8e 2781 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
936a5fe6
AA
2782 level == PT_PAGE_TABLE_LEVEL &&
2783 PageTransCompound(pfn_to_page(pfn)) &&
92f94f1e 2784 !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
936a5fe6
AA
2785 unsigned long mask;
2786 /*
2787 * mmu_notifier_retry was successful and we hold the
2788 * mmu_lock here, so the pmd can't become splitting
2789 * from under us, and in turn
2790 * __split_huge_page_refcount() can't run from under
2791 * us and we can safely transfer the refcount from
2792 * PG_tail to PG_head as we switch the pfn to tail to
2793 * head.
2794 */
2795 *levelp = level = PT_DIRECTORY_LEVEL;
2796 mask = KVM_PAGES_PER_HPAGE(level) - 1;
2797 VM_BUG_ON((gfn & mask) != (pfn & mask));
2798 if (pfn & mask) {
2799 gfn &= ~mask;
2800 *gfnp = gfn;
2801 kvm_release_pfn_clean(pfn);
2802 pfn &= ~mask;
c3586667 2803 kvm_get_pfn(pfn);
936a5fe6
AA
2804 *pfnp = pfn;
2805 }
2806 }
2807}
2808
d7c55201 2809static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
ba049e93 2810 kvm_pfn_t pfn, unsigned access, int *ret_val)
d7c55201
XG
2811{
2812 bool ret = true;
2813
2814 /* The pfn is invalid, report the error! */
81c52c56 2815 if (unlikely(is_error_pfn(pfn))) {
d7c55201
XG
2816 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
2817 goto exit;
2818 }
2819
ce88decf 2820 if (unlikely(is_noslot_pfn(pfn)))
d7c55201 2821 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
d7c55201
XG
2822
2823 ret = false;
2824exit:
2825 return ret;
2826}
2827
e5552fd2 2828static bool page_fault_can_be_fast(u32 error_code)
c7ba5b48 2829{
1c118b82
XG
2830 /*
2831 * Do not fix the mmio spte with invalid generation number which
2832 * need to be updated by slow page fault path.
2833 */
2834 if (unlikely(error_code & PFERR_RSVD_MASK))
2835 return false;
2836
c7ba5b48
XG
2837 /*
2838 * #PF can be fast only if the shadow page table is present and it
2839 * is caused by write-protect, that means we just need change the
2840 * W bit of the spte which can be done out of mmu-lock.
2841 */
2842 if (!(error_code & PFERR_PRESENT_MASK) ||
2843 !(error_code & PFERR_WRITE_MASK))
2844 return false;
2845
2846 return true;
2847}
2848
2849static bool
92a476cb
XG
2850fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2851 u64 *sptep, u64 spte)
c7ba5b48 2852{
c7ba5b48
XG
2853 gfn_t gfn;
2854
2855 WARN_ON(!sp->role.direct);
2856
2857 /*
2858 * The gfn of direct spte is stable since it is calculated
2859 * by sp->gfn.
2860 */
2861 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
2862
9b51a630
KH
2863 /*
2864 * Theoretically we could also set dirty bit (and flush TLB) here in
2865 * order to eliminate unnecessary PML logging. See comments in
2866 * set_spte. But fast_page_fault is very unlikely to happen with PML
2867 * enabled, so we do not do this. This might result in the same GPA
2868 * to be logged in PML buffer again when the write really happens, and
2869 * eventually to be called by mark_page_dirty twice. But it's also no
2870 * harm. This also avoids the TLB flush needed after setting dirty bit
2871 * so non-PML cases won't be impacted.
2872 *
2873 * Compare with set_spte where instead shadow_dirty_mask is set.
2874 */
c7ba5b48 2875 if (cmpxchg64(sptep, spte, spte | PT_WRITABLE_MASK) == spte)
54bf36aa 2876 kvm_vcpu_mark_page_dirty(vcpu, gfn);
c7ba5b48
XG
2877
2878 return true;
2879}
2880
2881/*
2882 * Return value:
2883 * - true: let the vcpu to access on the same address again.
2884 * - false: let the real page fault path to fix it.
2885 */
2886static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
2887 u32 error_code)
2888{
2889 struct kvm_shadow_walk_iterator iterator;
92a476cb 2890 struct kvm_mmu_page *sp;
c7ba5b48
XG
2891 bool ret = false;
2892 u64 spte = 0ull;
2893
37f6a4e2
MT
2894 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2895 return false;
2896
e5552fd2 2897 if (!page_fault_can_be_fast(error_code))
c7ba5b48
XG
2898 return false;
2899
2900 walk_shadow_page_lockless_begin(vcpu);
2901 for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
2902 if (!is_shadow_present_pte(spte) || iterator.level < level)
2903 break;
2904
2905 /*
2906 * If the mapping has been changed, let the vcpu fault on the
2907 * same address again.
2908 */
afd28fe1 2909 if (!is_shadow_present_pte(spte)) {
c7ba5b48
XG
2910 ret = true;
2911 goto exit;
2912 }
2913
92a476cb
XG
2914 sp = page_header(__pa(iterator.sptep));
2915 if (!is_last_spte(spte, sp->role.level))
c7ba5b48
XG
2916 goto exit;
2917
2918 /*
2919 * Check if it is a spurious fault caused by TLB lazily flushed.
2920 *
2921 * Need not check the access of upper level table entries since
2922 * they are always ACC_ALL.
2923 */
2924 if (is_writable_pte(spte)) {
2925 ret = true;
2926 goto exit;
2927 }
2928
2929 /*
2930 * Currently, to simplify the code, only the spte write-protected
2931 * by dirty-log can be fast fixed.
2932 */
2933 if (!spte_is_locklessly_modifiable(spte))
2934 goto exit;
2935
c126d94f
XG
2936 /*
2937 * Do not fix write-permission on the large spte since we only dirty
2938 * the first page into the dirty-bitmap in fast_pf_fix_direct_spte()
2939 * that means other pages are missed if its slot is dirty-logged.
2940 *
2941 * Instead, we let the slow page fault path create a normal spte to
2942 * fix the access.
2943 *
2944 * See the comments in kvm_arch_commit_memory_region().
2945 */
2946 if (sp->role.level > PT_PAGE_TABLE_LEVEL)
2947 goto exit;
2948
c7ba5b48
XG
2949 /*
2950 * Currently, fast page fault only works for direct mapping since
2951 * the gfn is not stable for indirect shadow page.
2952 * See Documentation/virtual/kvm/locking.txt to get more detail.
2953 */
92a476cb 2954 ret = fast_pf_fix_direct_spte(vcpu, sp, iterator.sptep, spte);
c7ba5b48 2955exit:
a72faf25
XG
2956 trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
2957 spte, ret);
c7ba5b48
XG
2958 walk_shadow_page_lockless_end(vcpu);
2959
2960 return ret;
2961}
2962
78b2c54a 2963static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
ba049e93 2964 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
450e0b41 2965static void make_mmu_pages_available(struct kvm_vcpu *vcpu);
060c2abe 2966
c7ba5b48
XG
2967static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
2968 gfn_t gfn, bool prefault)
10589a46
MT
2969{
2970 int r;
852e3c19 2971 int level;
fd136902 2972 bool force_pt_level = false;
ba049e93 2973 kvm_pfn_t pfn;
e930bffe 2974 unsigned long mmu_seq;
c7ba5b48 2975 bool map_writable, write = error_code & PFERR_WRITE_MASK;
aaee2c94 2976
fd136902 2977 level = mapping_level(vcpu, gfn, &force_pt_level);
936a5fe6 2978 if (likely(!force_pt_level)) {
936a5fe6
AA
2979 /*
2980 * This path builds a PAE pagetable - so we can map
2981 * 2mb pages at maximum. Therefore check if the level
2982 * is larger than that.
2983 */
2984 if (level > PT_DIRECTORY_LEVEL)
2985 level = PT_DIRECTORY_LEVEL;
852e3c19 2986
936a5fe6 2987 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
fd136902 2988 }
05da4558 2989
c7ba5b48
XG
2990 if (fast_page_fault(vcpu, v, level, error_code))
2991 return 0;
2992
e930bffe 2993 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4c2155ce 2994 smp_rmb();
060c2abe 2995
78b2c54a 2996 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
060c2abe 2997 return 0;
aaee2c94 2998
d7c55201
XG
2999 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3000 return r;
d196e343 3001
aaee2c94 3002 spin_lock(&vcpu->kvm->mmu_lock);
8ca40a70 3003 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
e930bffe 3004 goto out_unlock;
450e0b41 3005 make_mmu_pages_available(vcpu);
936a5fe6
AA
3006 if (likely(!force_pt_level))
3007 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
7ee0e5b2 3008 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
aaee2c94
MT
3009 spin_unlock(&vcpu->kvm->mmu_lock);
3010
10589a46 3011 return r;
e930bffe
AA
3012
3013out_unlock:
3014 spin_unlock(&vcpu->kvm->mmu_lock);
3015 kvm_release_pfn_clean(pfn);
3016 return 0;
10589a46
MT
3017}
3018
3019
17ac10ad
AK
3020static void mmu_free_roots(struct kvm_vcpu *vcpu)
3021{
3022 int i;
4db35314 3023 struct kvm_mmu_page *sp;
d98ba053 3024 LIST_HEAD(invalid_list);
17ac10ad 3025
ad312c7c 3026 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
7b53aa56 3027 return;
35af577a 3028
81407ca5
JR
3029 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL &&
3030 (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL ||
3031 vcpu->arch.mmu.direct_map)) {
ad312c7c 3032 hpa_t root = vcpu->arch.mmu.root_hpa;
17ac10ad 3033
35af577a 3034 spin_lock(&vcpu->kvm->mmu_lock);
4db35314
AK
3035 sp = page_header(root);
3036 --sp->root_count;
d98ba053
XG
3037 if (!sp->root_count && sp->role.invalid) {
3038 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
3039 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3040 }
aaee2c94 3041 spin_unlock(&vcpu->kvm->mmu_lock);
35af577a 3042 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
17ac10ad
AK
3043 return;
3044 }
35af577a
GN
3045
3046 spin_lock(&vcpu->kvm->mmu_lock);
17ac10ad 3047 for (i = 0; i < 4; ++i) {
ad312c7c 3048 hpa_t root = vcpu->arch.mmu.pae_root[i];
17ac10ad 3049
417726a3 3050 if (root) {
417726a3 3051 root &= PT64_BASE_ADDR_MASK;
4db35314
AK
3052 sp = page_header(root);
3053 --sp->root_count;
2e53d63a 3054 if (!sp->root_count && sp->role.invalid)
d98ba053
XG
3055 kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
3056 &invalid_list);
417726a3 3057 }
ad312c7c 3058 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
17ac10ad 3059 }
d98ba053 3060 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
aaee2c94 3061 spin_unlock(&vcpu->kvm->mmu_lock);
ad312c7c 3062 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
17ac10ad
AK
3063}
3064
8986ecc0
MT
3065static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3066{
3067 int ret = 0;
3068
3069 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
a8eeb04a 3070 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8986ecc0
MT
3071 ret = 1;
3072 }
3073
3074 return ret;
3075}
3076
651dd37a
JR
3077static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3078{
3079 struct kvm_mmu_page *sp;
7ebaf15e 3080 unsigned i;
651dd37a
JR
3081
3082 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3083 spin_lock(&vcpu->kvm->mmu_lock);
450e0b41 3084 make_mmu_pages_available(vcpu);
bb11c6c9 3085 sp = kvm_mmu_get_page(vcpu, 0, 0, PT64_ROOT_LEVEL, 1, ACC_ALL);
651dd37a
JR
3086 ++sp->root_count;
3087 spin_unlock(&vcpu->kvm->mmu_lock);
3088 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3089 } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3090 for (i = 0; i < 4; ++i) {
3091 hpa_t root = vcpu->arch.mmu.pae_root[i];
3092
fa4a2c08 3093 MMU_WARN_ON(VALID_PAGE(root));
651dd37a 3094 spin_lock(&vcpu->kvm->mmu_lock);
450e0b41 3095 make_mmu_pages_available(vcpu);
649497d1 3096 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
bb11c6c9 3097 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
651dd37a
JR
3098 root = __pa(sp->spt);
3099 ++sp->root_count;
3100 spin_unlock(&vcpu->kvm->mmu_lock);
3101 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
651dd37a 3102 }
6292757f 3103 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
651dd37a
JR
3104 } else
3105 BUG();
3106
3107 return 0;
3108}
3109
3110static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
17ac10ad 3111{
4db35314 3112 struct kvm_mmu_page *sp;
81407ca5
JR
3113 u64 pdptr, pm_mask;
3114 gfn_t root_gfn;
3115 int i;
3bb65a22 3116
5777ed34 3117 root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
17ac10ad 3118
651dd37a
JR
3119 if (mmu_check_root(vcpu, root_gfn))
3120 return 1;
3121
3122 /*
3123 * Do we shadow a long mode page table? If so we need to
3124 * write-protect the guests page table root.
3125 */
3126 if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
ad312c7c 3127 hpa_t root = vcpu->arch.mmu.root_hpa;
17ac10ad 3128
fa4a2c08 3129 MMU_WARN_ON(VALID_PAGE(root));
651dd37a 3130
8facbbff 3131 spin_lock(&vcpu->kvm->mmu_lock);
450e0b41 3132 make_mmu_pages_available(vcpu);
651dd37a 3133 sp = kvm_mmu_get_page(vcpu, root_gfn, 0, PT64_ROOT_LEVEL,
bb11c6c9 3134 0, ACC_ALL);
4db35314
AK
3135 root = __pa(sp->spt);
3136 ++sp->root_count;
8facbbff 3137 spin_unlock(&vcpu->kvm->mmu_lock);
ad312c7c 3138 vcpu->arch.mmu.root_hpa = root;
8986ecc0 3139 return 0;
17ac10ad 3140 }
f87f9288 3141
651dd37a
JR
3142 /*
3143 * We shadow a 32 bit page table. This may be a legacy 2-level
81407ca5
JR
3144 * or a PAE 3-level page table. In either case we need to be aware that
3145 * the shadow page table may be a PAE or a long mode page table.
651dd37a 3146 */
81407ca5
JR
3147 pm_mask = PT_PRESENT_MASK;
3148 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL)
3149 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3150
17ac10ad 3151 for (i = 0; i < 4; ++i) {
ad312c7c 3152 hpa_t root = vcpu->arch.mmu.pae_root[i];
17ac10ad 3153
fa4a2c08 3154 MMU_WARN_ON(VALID_PAGE(root));
ad312c7c 3155 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
e4e517b4 3156 pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
43a3795a 3157 if (!is_present_gpte(pdptr)) {
ad312c7c 3158 vcpu->arch.mmu.pae_root[i] = 0;
417726a3
AK
3159 continue;
3160 }
6de4f3ad 3161 root_gfn = pdptr >> PAGE_SHIFT;
f87f9288
JR
3162 if (mmu_check_root(vcpu, root_gfn))
3163 return 1;
5a7388c2 3164 }
8facbbff 3165 spin_lock(&vcpu->kvm->mmu_lock);
450e0b41 3166 make_mmu_pages_available(vcpu);
bb11c6c9
TY
3167 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3168 0, ACC_ALL);
4db35314
AK
3169 root = __pa(sp->spt);
3170 ++sp->root_count;
8facbbff
AK
3171 spin_unlock(&vcpu->kvm->mmu_lock);
3172
81407ca5 3173 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
17ac10ad 3174 }
6292757f 3175 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
81407ca5
JR
3176
3177 /*
3178 * If we shadow a 32 bit page table with a long mode page
3179 * table we enter this path.
3180 */
3181 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3182 if (vcpu->arch.mmu.lm_root == NULL) {
3183 /*
3184 * The additional page necessary for this is only
3185 * allocated on demand.
3186 */
3187
3188 u64 *lm_root;
3189
3190 lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3191 if (lm_root == NULL)
3192 return 1;
3193
3194 lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3195
3196 vcpu->arch.mmu.lm_root = lm_root;
3197 }
3198
3199 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3200 }
3201
8986ecc0 3202 return 0;
17ac10ad
AK
3203}
3204
651dd37a
JR
3205static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3206{
3207 if (vcpu->arch.mmu.direct_map)
3208 return mmu_alloc_direct_roots(vcpu);
3209 else
3210 return mmu_alloc_shadow_roots(vcpu);
3211}
3212
0ba73cda
MT
3213static void mmu_sync_roots(struct kvm_vcpu *vcpu)
3214{
3215 int i;
3216 struct kvm_mmu_page *sp;
3217
81407ca5
JR
3218 if (vcpu->arch.mmu.direct_map)
3219 return;
3220
0ba73cda
MT
3221 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3222 return;
6903074c 3223
56f17dd3 3224 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
0375f7fa 3225 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
81407ca5 3226 if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
0ba73cda
MT
3227 hpa_t root = vcpu->arch.mmu.root_hpa;
3228 sp = page_header(root);
3229 mmu_sync_children(vcpu, sp);
0375f7fa 3230 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
0ba73cda
MT
3231 return;
3232 }
3233 for (i = 0; i < 4; ++i) {
3234 hpa_t root = vcpu->arch.mmu.pae_root[i];
3235
8986ecc0 3236 if (root && VALID_PAGE(root)) {
0ba73cda
MT
3237 root &= PT64_BASE_ADDR_MASK;
3238 sp = page_header(root);
3239 mmu_sync_children(vcpu, sp);
3240 }
3241 }
0375f7fa 3242 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
0ba73cda
MT
3243}
3244
3245void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3246{
3247 spin_lock(&vcpu->kvm->mmu_lock);
3248 mmu_sync_roots(vcpu);
6cffe8ca 3249 spin_unlock(&vcpu->kvm->mmu_lock);
0ba73cda 3250}
bfd0a56b 3251EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
0ba73cda 3252
1871c602 3253static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
ab9ae313 3254 u32 access, struct x86_exception *exception)
6aa8b732 3255{
ab9ae313
AK
3256 if (exception)
3257 exception->error_code = 0;
6aa8b732
AK
3258 return vaddr;
3259}
3260
6539e738 3261static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
ab9ae313
AK
3262 u32 access,
3263 struct x86_exception *exception)
6539e738 3264{
ab9ae313
AK
3265 if (exception)
3266 exception->error_code = 0;
54987b7a 3267 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
6539e738
JR
3268}
3269
d625b155
XG
3270static bool
3271__is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3272{
3273 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3274
3275 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3276 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3277}
3278
3279static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3280{
3281 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3282}
3283
3284static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3285{
3286 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3287}
3288
ded58749 3289static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf
XG
3290{
3291 if (direct)
3292 return vcpu_match_mmio_gpa(vcpu, addr);
3293
3294 return vcpu_match_mmio_gva(vcpu, addr);
3295}
3296
47ab8751
XG
3297/* return true if reserved bit is detected on spte. */
3298static bool
3299walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
ce88decf
XG
3300{
3301 struct kvm_shadow_walk_iterator iterator;
47ab8751
XG
3302 u64 sptes[PT64_ROOT_LEVEL], spte = 0ull;
3303 int root, leaf;
3304 bool reserved = false;
ce88decf 3305
37f6a4e2 3306 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
47ab8751 3307 goto exit;
37f6a4e2 3308
ce88decf 3309 walk_shadow_page_lockless_begin(vcpu);
47ab8751 3310
29ecd660
PB
3311 for (shadow_walk_init(&iterator, vcpu, addr),
3312 leaf = root = iterator.level;
47ab8751
XG
3313 shadow_walk_okay(&iterator);
3314 __shadow_walk_next(&iterator, spte)) {
47ab8751
XG
3315 spte = mmu_spte_get_lockless(iterator.sptep);
3316
3317 sptes[leaf - 1] = spte;
29ecd660 3318 leaf--;
47ab8751 3319
ce88decf
XG
3320 if (!is_shadow_present_pte(spte))
3321 break;
47ab8751
XG
3322
3323 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
58c95070 3324 iterator.level);
47ab8751
XG
3325 }
3326
ce88decf
XG
3327 walk_shadow_page_lockless_end(vcpu);
3328
47ab8751
XG
3329 if (reserved) {
3330 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3331 __func__, addr);
29ecd660 3332 while (root > leaf) {
47ab8751
XG
3333 pr_err("------ spte 0x%llx level %d.\n",
3334 sptes[root - 1], root);
3335 root--;
3336 }
3337 }
3338exit:
3339 *sptep = spte;
3340 return reserved;
ce88decf
XG
3341}
3342
450869d6 3343int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
ce88decf
XG
3344{
3345 u64 spte;
47ab8751 3346 bool reserved;
ce88decf 3347
ded58749 3348 if (mmio_info_in_cache(vcpu, addr, direct))
b37fbea6 3349 return RET_MMIO_PF_EMULATE;
ce88decf 3350
47ab8751 3351 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
450869d6 3352 if (WARN_ON(reserved))
47ab8751 3353 return RET_MMIO_PF_BUG;
ce88decf
XG
3354
3355 if (is_mmio_spte(spte)) {
3356 gfn_t gfn = get_mmio_spte_gfn(spte);
3357 unsigned access = get_mmio_spte_access(spte);
3358
54bf36aa 3359 if (!check_mmio_spte(vcpu, spte))
f8f55942
XG
3360 return RET_MMIO_PF_INVALID;
3361
ce88decf
XG
3362 if (direct)
3363 addr = 0;
4f022648
XG
3364
3365 trace_handle_mmio_page_fault(addr, gfn, access);
ce88decf 3366 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
b37fbea6 3367 return RET_MMIO_PF_EMULATE;
ce88decf
XG
3368 }
3369
ce88decf
XG
3370 /*
3371 * If the page table is zapped by other cpus, let CPU fault again on
3372 * the address.
3373 */
b37fbea6 3374 return RET_MMIO_PF_RETRY;
ce88decf 3375}
450869d6 3376EXPORT_SYMBOL_GPL(handle_mmio_page_fault);
ce88decf 3377
6aa8b732 3378static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
78b2c54a 3379 u32 error_code, bool prefault)
6aa8b732 3380{
e833240f 3381 gfn_t gfn;
e2dec939 3382 int r;
6aa8b732 3383
b8688d51 3384 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
ce88decf 3385
e2dec939
AK
3386 r = mmu_topup_memory_caches(vcpu);
3387 if (r)
3388 return r;
714b93da 3389
fa4a2c08 3390 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
6aa8b732 3391
e833240f 3392 gfn = gva >> PAGE_SHIFT;
6aa8b732 3393
e833240f 3394 return nonpaging_map(vcpu, gva & PAGE_MASK,
c7ba5b48 3395 error_code, gfn, prefault);
6aa8b732
AK
3396}
3397
7e1fbeac 3398static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
af585b92
GN
3399{
3400 struct kvm_arch_async_pf arch;
fb67e14f 3401
7c90705b 3402 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
af585b92 3403 arch.gfn = gfn;
c4806acd 3404 arch.direct_map = vcpu->arch.mmu.direct_map;
fb67e14f 3405 arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
af585b92 3406
54bf36aa 3407 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
af585b92
GN
3408}
3409
3410static bool can_do_async_pf(struct kvm_vcpu *vcpu)
3411{
35754c98 3412 if (unlikely(!lapic_in_kernel(vcpu) ||
af585b92
GN
3413 kvm_event_needs_reinjection(vcpu)))
3414 return false;
3415
3416 return kvm_x86_ops->interrupt_allowed(vcpu);
3417}
3418
78b2c54a 3419static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
ba049e93 3420 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
af585b92 3421{
3520469d 3422 struct kvm_memory_slot *slot;
af585b92
GN
3423 bool async;
3424
54bf36aa 3425 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3520469d
PB
3426 async = false;
3427 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
af585b92
GN
3428 if (!async)
3429 return false; /* *pfn has correct page already */
3430
78b2c54a 3431 if (!prefault && can_do_async_pf(vcpu)) {
c9b263d2 3432 trace_kvm_try_async_get_page(gva, gfn);
af585b92
GN
3433 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3434 trace_kvm_async_pf_doublefault(gva, gfn);
3435 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3436 return true;
3437 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
3438 return true;
3439 }
3440
3520469d 3441 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
af585b92
GN
3442 return false;
3443}
3444
6a39bbc5
XG
3445static bool
3446check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
3447{
3448 int page_num = KVM_PAGES_PER_HPAGE(level);
3449
3450 gfn &= ~(page_num - 1);
3451
3452 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
3453}
3454
56028d08 3455static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
78b2c54a 3456 bool prefault)
fb72d167 3457{
ba049e93 3458 kvm_pfn_t pfn;
fb72d167 3459 int r;
852e3c19 3460 int level;
cd1872f0 3461 bool force_pt_level;
05da4558 3462 gfn_t gfn = gpa >> PAGE_SHIFT;
e930bffe 3463 unsigned long mmu_seq;
612819c3
MT
3464 int write = error_code & PFERR_WRITE_MASK;
3465 bool map_writable;
fb72d167 3466
fa4a2c08 3467 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
fb72d167
JR
3468
3469 r = mmu_topup_memory_caches(vcpu);
3470 if (r)
3471 return r;
3472
fd136902
TY
3473 force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
3474 PT_DIRECTORY_LEVEL);
3475 level = mapping_level(vcpu, gfn, &force_pt_level);
936a5fe6 3476 if (likely(!force_pt_level)) {
6a39bbc5
XG
3477 if (level > PT_DIRECTORY_LEVEL &&
3478 !check_hugepage_cache_consistency(vcpu, gfn, level))
3479 level = PT_DIRECTORY_LEVEL;
936a5fe6 3480 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
fd136902 3481 }
852e3c19 3482
c7ba5b48
XG
3483 if (fast_page_fault(vcpu, gpa, level, error_code))
3484 return 0;
3485
e930bffe 3486 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4c2155ce 3487 smp_rmb();
af585b92 3488
78b2c54a 3489 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
af585b92
GN
3490 return 0;
3491
d7c55201
XG
3492 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
3493 return r;
3494
fb72d167 3495 spin_lock(&vcpu->kvm->mmu_lock);
8ca40a70 3496 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
e930bffe 3497 goto out_unlock;
450e0b41 3498 make_mmu_pages_available(vcpu);
936a5fe6
AA
3499 if (likely(!force_pt_level))
3500 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
7ee0e5b2 3501 r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
fb72d167 3502 spin_unlock(&vcpu->kvm->mmu_lock);
fb72d167
JR
3503
3504 return r;
e930bffe
AA
3505
3506out_unlock:
3507 spin_unlock(&vcpu->kvm->mmu_lock);
3508 kvm_release_pfn_clean(pfn);
3509 return 0;
fb72d167
JR
3510}
3511
8a3c1a33
PB
3512static void nonpaging_init_context(struct kvm_vcpu *vcpu,
3513 struct kvm_mmu *context)
6aa8b732 3514{
6aa8b732 3515 context->page_fault = nonpaging_page_fault;
6aa8b732 3516 context->gva_to_gpa = nonpaging_gva_to_gpa;
e8bc217a 3517 context->sync_page = nonpaging_sync_page;
a7052897 3518 context->invlpg = nonpaging_invlpg;
0f53b5b1 3519 context->update_pte = nonpaging_update_pte;
cea0f0e7 3520 context->root_level = 0;
6aa8b732 3521 context->shadow_root_level = PT32E_ROOT_LEVEL;
17c3ba9d 3522 context->root_hpa = INVALID_PAGE;
c5a78f2b 3523 context->direct_map = true;
2d48a985 3524 context->nx = false;
6aa8b732
AK
3525}
3526
d8d173da 3527void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu)
6aa8b732 3528{
cea0f0e7 3529 mmu_free_roots(vcpu);
6aa8b732
AK
3530}
3531
5777ed34
JR
3532static unsigned long get_cr3(struct kvm_vcpu *vcpu)
3533{
9f8fe504 3534 return kvm_read_cr3(vcpu);
5777ed34
JR
3535}
3536
6389ee94
AK
3537static void inject_page_fault(struct kvm_vcpu *vcpu,
3538 struct x86_exception *fault)
6aa8b732 3539{
6389ee94 3540 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
6aa8b732
AK
3541}
3542
54bf36aa 3543static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
f2fd125d 3544 unsigned access, int *nr_present)
ce88decf
XG
3545{
3546 if (unlikely(is_mmio_spte(*sptep))) {
3547 if (gfn != get_mmio_spte_gfn(*sptep)) {
3548 mmu_spte_clear_no_track(sptep);
3549 return true;
3550 }
3551
3552 (*nr_present)++;
54bf36aa 3553 mark_mmio_spte(vcpu, sptep, gfn, access);
ce88decf
XG
3554 return true;
3555 }
3556
3557 return false;
3558}
3559
6fd01b71
AK
3560static inline bool is_last_gpte(struct kvm_mmu *mmu, unsigned level, unsigned gpte)
3561{
3562 unsigned index;
3563
3564 index = level - 1;
3565 index |= (gpte & PT_PAGE_SIZE_MASK) >> (PT_PAGE_SIZE_SHIFT - 2);
3566 return mmu->last_pte_bitmap & (1 << index);
3567}
3568
37406aaa
NHE
3569#define PTTYPE_EPT 18 /* arbitrary */
3570#define PTTYPE PTTYPE_EPT
3571#include "paging_tmpl.h"
3572#undef PTTYPE
3573
6aa8b732
AK
3574#define PTTYPE 64
3575#include "paging_tmpl.h"
3576#undef PTTYPE
3577
3578#define PTTYPE 32
3579#include "paging_tmpl.h"
3580#undef PTTYPE
3581
6dc98b86
XG
3582static void
3583__reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3584 struct rsvd_bits_validate *rsvd_check,
3585 int maxphyaddr, int level, bool nx, bool gbpages,
6fec2144 3586 bool pse, bool amd)
82725b20 3587{
82725b20 3588 u64 exb_bit_rsvd = 0;
5f7dde7b 3589 u64 gbpages_bit_rsvd = 0;
a0c0feb5 3590 u64 nonleaf_bit8_rsvd = 0;
82725b20 3591
a0a64f50 3592 rsvd_check->bad_mt_xwr = 0;
25d92081 3593
6dc98b86 3594 if (!nx)
82725b20 3595 exb_bit_rsvd = rsvd_bits(63, 63);
6dc98b86 3596 if (!gbpages)
5f7dde7b 3597 gbpages_bit_rsvd = rsvd_bits(7, 7);
a0c0feb5
PB
3598
3599 /*
3600 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
3601 * leaf entries) on AMD CPUs only.
3602 */
6fec2144 3603 if (amd)
a0c0feb5
PB
3604 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
3605
6dc98b86 3606 switch (level) {
82725b20
DE
3607 case PT32_ROOT_LEVEL:
3608 /* no rsvd bits for 2 level 4K page table entries */
a0a64f50
XG
3609 rsvd_check->rsvd_bits_mask[0][1] = 0;
3610 rsvd_check->rsvd_bits_mask[0][0] = 0;
3611 rsvd_check->rsvd_bits_mask[1][0] =
3612 rsvd_check->rsvd_bits_mask[0][0];
f815bce8 3613
6dc98b86 3614 if (!pse) {
a0a64f50 3615 rsvd_check->rsvd_bits_mask[1][1] = 0;
f815bce8
XG
3616 break;
3617 }
3618
82725b20
DE
3619 if (is_cpuid_PSE36())
3620 /* 36bits PSE 4MB page */
a0a64f50 3621 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
82725b20
DE
3622 else
3623 /* 32 bits PSE 4MB page */
a0a64f50 3624 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
82725b20
DE
3625 break;
3626 case PT32E_ROOT_LEVEL:
a0a64f50 3627 rsvd_check->rsvd_bits_mask[0][2] =
20c466b5 3628 rsvd_bits(maxphyaddr, 63) |
cd9ae5fe 3629 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
a0a64f50 3630 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4c26b4cd 3631 rsvd_bits(maxphyaddr, 62); /* PDE */
a0a64f50 3632 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
82725b20 3633 rsvd_bits(maxphyaddr, 62); /* PTE */
a0a64f50 3634 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
82725b20
DE
3635 rsvd_bits(maxphyaddr, 62) |
3636 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
3637 rsvd_check->rsvd_bits_mask[1][0] =
3638 rsvd_check->rsvd_bits_mask[0][0];
82725b20
DE
3639 break;
3640 case PT64_ROOT_LEVEL:
a0a64f50
XG
3641 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
3642 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4c26b4cd 3643 rsvd_bits(maxphyaddr, 51);
a0a64f50
XG
3644 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
3645 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
82725b20 3646 rsvd_bits(maxphyaddr, 51);
a0a64f50
XG
3647 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3648 rsvd_bits(maxphyaddr, 51);
3649 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3650 rsvd_bits(maxphyaddr, 51);
3651 rsvd_check->rsvd_bits_mask[1][3] =
3652 rsvd_check->rsvd_bits_mask[0][3];
3653 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
5f7dde7b 3654 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
e04da980 3655 rsvd_bits(13, 29);
a0a64f50 3656 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4c26b4cd
SY
3657 rsvd_bits(maxphyaddr, 51) |
3658 rsvd_bits(13, 20); /* large page */
a0a64f50
XG
3659 rsvd_check->rsvd_bits_mask[1][0] =
3660 rsvd_check->rsvd_bits_mask[0][0];
82725b20
DE
3661 break;
3662 }
3663}
3664
6dc98b86
XG
3665static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3666 struct kvm_mmu *context)
3667{
3668 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
3669 cpuid_maxphyaddr(vcpu), context->root_level,
3670 context->nx, guest_cpuid_has_gbpages(vcpu),
6fec2144 3671 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
6dc98b86
XG
3672}
3673
81b8eebb
XG
3674static void
3675__reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
3676 int maxphyaddr, bool execonly)
25d92081 3677{
951f9fd7 3678 u64 bad_mt_xwr;
25d92081 3679
a0a64f50 3680 rsvd_check->rsvd_bits_mask[0][3] =
25d92081 3681 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
a0a64f50 3682 rsvd_check->rsvd_bits_mask[0][2] =
25d92081 3683 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
a0a64f50 3684 rsvd_check->rsvd_bits_mask[0][1] =
25d92081 3685 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
a0a64f50 3686 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
25d92081
YZ
3687
3688 /* large page */
a0a64f50
XG
3689 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
3690 rsvd_check->rsvd_bits_mask[1][2] =
25d92081 3691 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
a0a64f50 3692 rsvd_check->rsvd_bits_mask[1][1] =
25d92081 3693 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
a0a64f50 3694 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
25d92081 3695
951f9fd7
PB
3696 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
3697 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
3698 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
3699 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
3700 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
3701 if (!execonly) {
3702 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
3703 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
25d92081 3704 }
951f9fd7 3705 rsvd_check->bad_mt_xwr = bad_mt_xwr;
25d92081
YZ
3706}
3707
81b8eebb
XG
3708static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
3709 struct kvm_mmu *context, bool execonly)
3710{
3711 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
3712 cpuid_maxphyaddr(vcpu), execonly);
3713}
3714
c258b62b
XG
3715/*
3716 * the page table on host is the shadow page table for the page
3717 * table in guest or amd nested guest, its mmu features completely
3718 * follow the features in guest.
3719 */
3720void
3721reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
3722{
6fec2144
PB
3723 /*
3724 * Passing "true" to the last argument is okay; it adds a check
3725 * on bit 8 of the SPTEs which KVM doesn't use anyway.
3726 */
c258b62b
XG
3727 __reset_rsvds_bits_mask(vcpu, &context->shadow_zero_check,
3728 boot_cpu_data.x86_phys_bits,
3729 context->shadow_root_level, context->nx,
6fec2144
PB
3730 guest_cpuid_has_gbpages(vcpu), is_pse(vcpu),
3731 true);
c258b62b
XG
3732}
3733EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
3734
6fec2144
PB
3735static inline bool boot_cpu_is_amd(void)
3736{
3737 WARN_ON_ONCE(!tdp_enabled);
3738 return shadow_x_mask == 0;
3739}
3740
c258b62b
XG
3741/*
3742 * the direct page table on host, use as much mmu features as
3743 * possible, however, kvm currently does not do execution-protection.
3744 */
3745static void
3746reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
3747 struct kvm_mmu *context)
3748{
6fec2144 3749 if (boot_cpu_is_amd())
c258b62b
XG
3750 __reset_rsvds_bits_mask(vcpu, &context->shadow_zero_check,
3751 boot_cpu_data.x86_phys_bits,
3752 context->shadow_root_level, false,
6fec2144 3753 cpu_has_gbpages, true, true);
c258b62b
XG
3754 else
3755 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
3756 boot_cpu_data.x86_phys_bits,
3757 false);
3758
3759}
3760
3761/*
3762 * as the comments in reset_shadow_zero_bits_mask() except it
3763 * is the shadow page table for intel nested guest.
3764 */
3765static void
3766reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
3767 struct kvm_mmu *context, bool execonly)
3768{
3769 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
3770 boot_cpu_data.x86_phys_bits, execonly);
3771}
3772
edc90b7d
XG
3773static void update_permission_bitmask(struct kvm_vcpu *vcpu,
3774 struct kvm_mmu *mmu, bool ept)
97d64b78
AK
3775{
3776 unsigned bit, byte, pfec;
3777 u8 map;
66386ade 3778 bool fault, x, w, u, wf, uf, ff, smapf, cr4_smap, cr4_smep, smap = 0;
97d64b78 3779
66386ade 3780 cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
97ec8c06 3781 cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
97d64b78
AK
3782 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
3783 pfec = byte << 1;
3784 map = 0;
3785 wf = pfec & PFERR_WRITE_MASK;
3786 uf = pfec & PFERR_USER_MASK;
3787 ff = pfec & PFERR_FETCH_MASK;
97ec8c06
FW
3788 /*
3789 * PFERR_RSVD_MASK bit is set in PFEC if the access is not
3790 * subject to SMAP restrictions, and cleared otherwise. The
3791 * bit is only meaningful if the SMAP bit is set in CR4.
3792 */
3793 smapf = !(pfec & PFERR_RSVD_MASK);
97d64b78
AK
3794 for (bit = 0; bit < 8; ++bit) {
3795 x = bit & ACC_EXEC_MASK;
3796 w = bit & ACC_WRITE_MASK;
3797 u = bit & ACC_USER_MASK;
3798
25d92081
YZ
3799 if (!ept) {
3800 /* Not really needed: !nx will cause pte.nx to fault */
3801 x |= !mmu->nx;
3802 /* Allow supervisor writes if !cr0.wp */
3803 w |= !is_write_protection(vcpu) && !uf;
3804 /* Disallow supervisor fetches of user code if cr4.smep */
66386ade 3805 x &= !(cr4_smep && u && !uf);
97ec8c06
FW
3806
3807 /*
3808 * SMAP:kernel-mode data accesses from user-mode
3809 * mappings should fault. A fault is considered
3810 * as a SMAP violation if all of the following
3811 * conditions are ture:
3812 * - X86_CR4_SMAP is set in CR4
3813 * - An user page is accessed
3814 * - Page fault in kernel mode
3815 * - if CPL = 3 or X86_EFLAGS_AC is clear
3816 *
3817 * Here, we cover the first three conditions.
3818 * The fourth is computed dynamically in
3819 * permission_fault() and is in smapf.
3820 *
3821 * Also, SMAP does not affect instruction
3822 * fetches, add the !ff check here to make it
3823 * clearer.
3824 */
3825 smap = cr4_smap && u && !uf && !ff;
25d92081
YZ
3826 } else
3827 /* Not really needed: no U/S accesses on ept */
3828 u = 1;
97d64b78 3829
97ec8c06
FW
3830 fault = (ff && !x) || (uf && !u) || (wf && !w) ||
3831 (smapf && smap);
97d64b78
AK
3832 map |= fault << bit;
3833 }
3834 mmu->permissions[byte] = map;
3835 }
3836}
3837
6fd01b71
AK
3838static void update_last_pte_bitmap(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
3839{
3840 u8 map;
3841 unsigned level, root_level = mmu->root_level;
3842 const unsigned ps_set_index = 1 << 2; /* bit 2 of index: ps */
3843
3844 if (root_level == PT32E_ROOT_LEVEL)
3845 --root_level;
3846 /* PT_PAGE_TABLE_LEVEL always terminates */
3847 map = 1 | (1 << ps_set_index);
3848 for (level = PT_DIRECTORY_LEVEL; level <= root_level; ++level) {
3849 if (level <= PT_PDPE_LEVEL
3850 && (mmu->root_level >= PT32E_ROOT_LEVEL || is_pse(vcpu)))
3851 map |= 1 << (ps_set_index | (level - 1));
3852 }
3853 mmu->last_pte_bitmap = map;
3854}
3855
8a3c1a33
PB
3856static void paging64_init_context_common(struct kvm_vcpu *vcpu,
3857 struct kvm_mmu *context,
3858 int level)
6aa8b732 3859{
2d48a985 3860 context->nx = is_nx(vcpu);
4d6931c3 3861 context->root_level = level;
2d48a985 3862
4d6931c3 3863 reset_rsvds_bits_mask(vcpu, context);
25d92081 3864 update_permission_bitmask(vcpu, context, false);
6fd01b71 3865 update_last_pte_bitmap(vcpu, context);
6aa8b732 3866
fa4a2c08 3867 MMU_WARN_ON(!is_pae(vcpu));
6aa8b732 3868 context->page_fault = paging64_page_fault;
6aa8b732 3869 context->gva_to_gpa = paging64_gva_to_gpa;
e8bc217a 3870 context->sync_page = paging64_sync_page;
a7052897 3871 context->invlpg = paging64_invlpg;
0f53b5b1 3872 context->update_pte = paging64_update_pte;
17ac10ad 3873 context->shadow_root_level = level;
17c3ba9d 3874 context->root_hpa = INVALID_PAGE;
c5a78f2b 3875 context->direct_map = false;
6aa8b732
AK
3876}
3877
8a3c1a33
PB
3878static void paging64_init_context(struct kvm_vcpu *vcpu,
3879 struct kvm_mmu *context)
17ac10ad 3880{
8a3c1a33 3881 paging64_init_context_common(vcpu, context, PT64_ROOT_LEVEL);
17ac10ad
AK
3882}
3883
8a3c1a33
PB
3884static void paging32_init_context(struct kvm_vcpu *vcpu,
3885 struct kvm_mmu *context)
6aa8b732 3886{
2d48a985 3887 context->nx = false;
4d6931c3 3888 context->root_level = PT32_ROOT_LEVEL;
2d48a985 3889
4d6931c3 3890 reset_rsvds_bits_mask(vcpu, context);
25d92081 3891 update_permission_bitmask(vcpu, context, false);
6fd01b71 3892 update_last_pte_bitmap(vcpu, context);
6aa8b732 3893
6aa8b732 3894 context->page_fault = paging32_page_fault;
6aa8b732 3895 context->gva_to_gpa = paging32_gva_to_gpa;
e8bc217a 3896 context->sync_page = paging32_sync_page;
a7052897 3897 context->invlpg = paging32_invlpg;
0f53b5b1 3898 context->update_pte = paging32_update_pte;
6aa8b732 3899 context->shadow_root_level = PT32E_ROOT_LEVEL;
17c3ba9d 3900 context->root_hpa = INVALID_PAGE;
c5a78f2b 3901 context->direct_map = false;
6aa8b732
AK
3902}
3903
8a3c1a33
PB
3904static void paging32E_init_context(struct kvm_vcpu *vcpu,
3905 struct kvm_mmu *context)
6aa8b732 3906{
8a3c1a33 3907 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
6aa8b732
AK
3908}
3909
8a3c1a33 3910static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
fb72d167 3911{
ad896af0 3912 struct kvm_mmu *context = &vcpu->arch.mmu;
fb72d167 3913
c445f8ef 3914 context->base_role.word = 0;
699023e2 3915 context->base_role.smm = is_smm(vcpu);
fb72d167 3916 context->page_fault = tdp_page_fault;
e8bc217a 3917 context->sync_page = nonpaging_sync_page;
a7052897 3918 context->invlpg = nonpaging_invlpg;
0f53b5b1 3919 context->update_pte = nonpaging_update_pte;
67253af5 3920 context->shadow_root_level = kvm_x86_ops->get_tdp_level();
fb72d167 3921 context->root_hpa = INVALID_PAGE;
c5a78f2b 3922 context->direct_map = true;
1c97f0a0 3923 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
5777ed34 3924 context->get_cr3 = get_cr3;
e4e517b4 3925 context->get_pdptr = kvm_pdptr_read;
cb659db8 3926 context->inject_page_fault = kvm_inject_page_fault;
fb72d167
JR
3927
3928 if (!is_paging(vcpu)) {
2d48a985 3929 context->nx = false;
fb72d167
JR
3930 context->gva_to_gpa = nonpaging_gva_to_gpa;
3931 context->root_level = 0;
3932 } else if (is_long_mode(vcpu)) {
2d48a985 3933 context->nx = is_nx(vcpu);
fb72d167 3934 context->root_level = PT64_ROOT_LEVEL;
4d6931c3
DB
3935 reset_rsvds_bits_mask(vcpu, context);
3936 context->gva_to_gpa = paging64_gva_to_gpa;
fb72d167 3937 } else if (is_pae(vcpu)) {
2d48a985 3938 context->nx = is_nx(vcpu);
fb72d167 3939 context->root_level = PT32E_ROOT_LEVEL;
4d6931c3
DB
3940 reset_rsvds_bits_mask(vcpu, context);
3941 context->gva_to_gpa = paging64_gva_to_gpa;
fb72d167 3942 } else {
2d48a985 3943 context->nx = false;
fb72d167 3944 context->root_level = PT32_ROOT_LEVEL;
4d6931c3
DB
3945 reset_rsvds_bits_mask(vcpu, context);
3946 context->gva_to_gpa = paging32_gva_to_gpa;
fb72d167
JR
3947 }
3948
25d92081 3949 update_permission_bitmask(vcpu, context, false);
6fd01b71 3950 update_last_pte_bitmap(vcpu, context);
c258b62b 3951 reset_tdp_shadow_zero_bits_mask(vcpu, context);
fb72d167
JR
3952}
3953
ad896af0 3954void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
6aa8b732 3955{
411c588d 3956 bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
edc90b7d 3957 bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
ad896af0
PB
3958 struct kvm_mmu *context = &vcpu->arch.mmu;
3959
fa4a2c08 3960 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
6aa8b732
AK
3961
3962 if (!is_paging(vcpu))
8a3c1a33 3963 nonpaging_init_context(vcpu, context);
a9058ecd 3964 else if (is_long_mode(vcpu))
8a3c1a33 3965 paging64_init_context(vcpu, context);
6aa8b732 3966 else if (is_pae(vcpu))
8a3c1a33 3967 paging32E_init_context(vcpu, context);
6aa8b732 3968 else
8a3c1a33 3969 paging32_init_context(vcpu, context);
a770f6f2 3970
ad896af0
PB
3971 context->base_role.nxe = is_nx(vcpu);
3972 context->base_role.cr4_pae = !!is_pae(vcpu);
3973 context->base_role.cr0_wp = is_write_protection(vcpu);
3974 context->base_role.smep_andnot_wp
411c588d 3975 = smep && !is_write_protection(vcpu);
edc90b7d
XG
3976 context->base_role.smap_andnot_wp
3977 = smap && !is_write_protection(vcpu);
699023e2 3978 context->base_role.smm = is_smm(vcpu);
c258b62b 3979 reset_shadow_zero_bits_mask(vcpu, context);
52fde8df
JR
3980}
3981EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
3982
ad896af0 3983void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly)
155a97a3 3984{
ad896af0
PB
3985 struct kvm_mmu *context = &vcpu->arch.mmu;
3986
fa4a2c08 3987 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
155a97a3
NHE
3988
3989 context->shadow_root_level = kvm_x86_ops->get_tdp_level();
3990
3991 context->nx = true;
155a97a3
NHE
3992 context->page_fault = ept_page_fault;
3993 context->gva_to_gpa = ept_gva_to_gpa;
3994 context->sync_page = ept_sync_page;
3995 context->invlpg = ept_invlpg;
3996 context->update_pte = ept_update_pte;
155a97a3
NHE
3997 context->root_level = context->shadow_root_level;
3998 context->root_hpa = INVALID_PAGE;
3999 context->direct_map = false;
4000
4001 update_permission_bitmask(vcpu, context, true);
4002 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
c258b62b 4003 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
155a97a3
NHE
4004}
4005EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4006
8a3c1a33 4007static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
52fde8df 4008{
ad896af0
PB
4009 struct kvm_mmu *context = &vcpu->arch.mmu;
4010
4011 kvm_init_shadow_mmu(vcpu);
4012 context->set_cr3 = kvm_x86_ops->set_cr3;
4013 context->get_cr3 = get_cr3;
4014 context->get_pdptr = kvm_pdptr_read;
4015 context->inject_page_fault = kvm_inject_page_fault;
6aa8b732
AK
4016}
4017
8a3c1a33 4018static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
02f59dc9
JR
4019{
4020 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4021
4022 g_context->get_cr3 = get_cr3;
e4e517b4 4023 g_context->get_pdptr = kvm_pdptr_read;
02f59dc9
JR
4024 g_context->inject_page_fault = kvm_inject_page_fault;
4025
4026 /*
0af2593b
DM
4027 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
4028 * L1's nested page tables (e.g. EPT12). The nested translation
4029 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4030 * L2's page tables as the first level of translation and L1's
4031 * nested page tables as the second level of translation. Basically
4032 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
02f59dc9
JR
4033 */
4034 if (!is_paging(vcpu)) {
2d48a985 4035 g_context->nx = false;
02f59dc9
JR
4036 g_context->root_level = 0;
4037 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4038 } else if (is_long_mode(vcpu)) {
2d48a985 4039 g_context->nx = is_nx(vcpu);
02f59dc9 4040 g_context->root_level = PT64_ROOT_LEVEL;
4d6931c3 4041 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
4042 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4043 } else if (is_pae(vcpu)) {
2d48a985 4044 g_context->nx = is_nx(vcpu);
02f59dc9 4045 g_context->root_level = PT32E_ROOT_LEVEL;
4d6931c3 4046 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
4047 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4048 } else {
2d48a985 4049 g_context->nx = false;
02f59dc9 4050 g_context->root_level = PT32_ROOT_LEVEL;
4d6931c3 4051 reset_rsvds_bits_mask(vcpu, g_context);
02f59dc9
JR
4052 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4053 }
4054
25d92081 4055 update_permission_bitmask(vcpu, g_context, false);
6fd01b71 4056 update_last_pte_bitmap(vcpu, g_context);
02f59dc9
JR
4057}
4058
8a3c1a33 4059static void init_kvm_mmu(struct kvm_vcpu *vcpu)
fb72d167 4060{
02f59dc9 4061 if (mmu_is_nested(vcpu))
e0c6db3e 4062 init_kvm_nested_mmu(vcpu);
02f59dc9 4063 else if (tdp_enabled)
e0c6db3e 4064 init_kvm_tdp_mmu(vcpu);
fb72d167 4065 else
e0c6db3e 4066 init_kvm_softmmu(vcpu);
fb72d167
JR
4067}
4068
8a3c1a33 4069void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
6aa8b732 4070{
95f93af4 4071 kvm_mmu_unload(vcpu);
8a3c1a33 4072 init_kvm_mmu(vcpu);
17c3ba9d 4073}
8668a3c4 4074EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
17c3ba9d
AK
4075
4076int kvm_mmu_load(struct kvm_vcpu *vcpu)
6aa8b732 4077{
714b93da
AK
4078 int r;
4079
e2dec939 4080 r = mmu_topup_memory_caches(vcpu);
17c3ba9d
AK
4081 if (r)
4082 goto out;
8986ecc0 4083 r = mmu_alloc_roots(vcpu);
e2858b4a 4084 kvm_mmu_sync_roots(vcpu);
8986ecc0
MT
4085 if (r)
4086 goto out;
3662cb1c 4087 /* set_cr3() should ensure TLB has been flushed */
f43addd4 4088 vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
714b93da
AK
4089out:
4090 return r;
6aa8b732 4091}
17c3ba9d
AK
4092EXPORT_SYMBOL_GPL(kvm_mmu_load);
4093
4094void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4095{
4096 mmu_free_roots(vcpu);
95f93af4 4097 WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
17c3ba9d 4098}
4b16184c 4099EXPORT_SYMBOL_GPL(kvm_mmu_unload);
6aa8b732 4100
0028425f 4101static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
7c562522
XG
4102 struct kvm_mmu_page *sp, u64 *spte,
4103 const void *new)
0028425f 4104{
30945387 4105 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
7e4e4056
JR
4106 ++vcpu->kvm->stat.mmu_pde_zapped;
4107 return;
30945387 4108 }
0028425f 4109
4cee5764 4110 ++vcpu->kvm->stat.mmu_pte_updated;
7c562522 4111 vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
0028425f
AK
4112}
4113
79539cec
AK
4114static bool need_remote_flush(u64 old, u64 new)
4115{
4116 if (!is_shadow_present_pte(old))
4117 return false;
4118 if (!is_shadow_present_pte(new))
4119 return true;
4120 if ((old ^ new) & PT64_BASE_ADDR_MASK)
4121 return true;
53166229
GN
4122 old ^= shadow_nx_mask;
4123 new ^= shadow_nx_mask;
79539cec
AK
4124 return (old & ~new & PT64_PERM_MASK) != 0;
4125}
4126
0671a8e7
XG
4127static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, bool zap_page,
4128 bool remote_flush, bool local_flush)
79539cec 4129{
0671a8e7
XG
4130 if (zap_page)
4131 return;
4132
4133 if (remote_flush)
79539cec 4134 kvm_flush_remote_tlbs(vcpu->kvm);
0671a8e7 4135 else if (local_flush)
77c3913b 4136 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
79539cec
AK
4137}
4138
889e5cbc
XG
4139static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4140 const u8 *new, int *bytes)
da4a00f0 4141{
889e5cbc
XG
4142 u64 gentry;
4143 int r;
72016f3a 4144
72016f3a
AK
4145 /*
4146 * Assume that the pte write on a page table of the same type
49b26e26
XG
4147 * as the current vcpu paging mode since we update the sptes only
4148 * when they have the same mode.
72016f3a 4149 */
889e5cbc 4150 if (is_pae(vcpu) && *bytes == 4) {
72016f3a 4151 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
889e5cbc
XG
4152 *gpa &= ~(gpa_t)7;
4153 *bytes = 8;
54bf36aa 4154 r = kvm_vcpu_read_guest(vcpu, *gpa, &gentry, 8);
72016f3a
AK
4155 if (r)
4156 gentry = 0;
08e850c6
AK
4157 new = (const u8 *)&gentry;
4158 }
4159
889e5cbc 4160 switch (*bytes) {
08e850c6
AK
4161 case 4:
4162 gentry = *(const u32 *)new;
4163 break;
4164 case 8:
4165 gentry = *(const u64 *)new;
4166 break;
4167 default:
4168 gentry = 0;
4169 break;
72016f3a
AK
4170 }
4171
889e5cbc
XG
4172 return gentry;
4173}
4174
4175/*
4176 * If we're seeing too many writes to a page, it may no longer be a page table,
4177 * or we may be forking, in which case it is better to unmap the page.
4178 */
a138fe75 4179static bool detect_write_flooding(struct kvm_mmu_page *sp)
889e5cbc 4180{
a30f47cb
XG
4181 /*
4182 * Skip write-flooding detected for the sp whose level is 1, because
4183 * it can become unsync, then the guest page is not write-protected.
4184 */
f71fa31f 4185 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
a30f47cb 4186 return false;
3246af0e 4187
a30f47cb 4188 return ++sp->write_flooding_count >= 3;
889e5cbc
XG
4189}
4190
4191/*
4192 * Misaligned accesses are too much trouble to fix up; also, they usually
4193 * indicate a page is not used as a page table.
4194 */
4195static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4196 int bytes)
4197{
4198 unsigned offset, pte_size, misaligned;
4199
4200 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4201 gpa, bytes, sp->role.word);
4202
4203 offset = offset_in_page(gpa);
4204 pte_size = sp->role.cr4_pae ? 8 : 4;
5d9ca30e
XG
4205
4206 /*
4207 * Sometimes, the OS only writes the last one bytes to update status
4208 * bits, for example, in linux, andb instruction is used in clear_bit().
4209 */
4210 if (!(offset & (pte_size - 1)) && bytes == 1)
4211 return false;
4212
889e5cbc
XG
4213 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4214 misaligned |= bytes < 4;
4215
4216 return misaligned;
4217}
4218
4219static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
4220{
4221 unsigned page_offset, quadrant;
4222 u64 *spte;
4223 int level;
4224
4225 page_offset = offset_in_page(gpa);
4226 level = sp->role.level;
4227 *nspte = 1;
4228 if (!sp->role.cr4_pae) {
4229 page_offset <<= 1; /* 32->64 */
4230 /*
4231 * A 32-bit pde maps 4MB while the shadow pdes map
4232 * only 2MB. So we need to double the offset again
4233 * and zap two pdes instead of one.
4234 */
4235 if (level == PT32_ROOT_LEVEL) {
4236 page_offset &= ~7; /* kill rounding error */
4237 page_offset <<= 1;
4238 *nspte = 2;
4239 }
4240 quadrant = page_offset >> PAGE_SHIFT;
4241 page_offset &= ~PAGE_MASK;
4242 if (quadrant != sp->role.quadrant)
4243 return NULL;
4244 }
4245
4246 spte = &sp->spt[page_offset / sizeof(*spte)];
4247 return spte;
4248}
4249
4250void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
4251 const u8 *new, int bytes)
4252{
4253 gfn_t gfn = gpa >> PAGE_SHIFT;
889e5cbc 4254 struct kvm_mmu_page *sp;
889e5cbc
XG
4255 LIST_HEAD(invalid_list);
4256 u64 entry, gentry, *spte;
4257 int npte;
a30f47cb 4258 bool remote_flush, local_flush, zap_page;
4141259b
AM
4259 union kvm_mmu_page_role mask = { };
4260
4261 mask.cr0_wp = 1;
4262 mask.cr4_pae = 1;
4263 mask.nxe = 1;
4264 mask.smep_andnot_wp = 1;
4265 mask.smap_andnot_wp = 1;
699023e2 4266 mask.smm = 1;
889e5cbc
XG
4267
4268 /*
4269 * If we don't have indirect shadow pages, it means no page is
4270 * write-protected, so we can exit simply.
4271 */
4272 if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
4273 return;
4274
4275 zap_page = remote_flush = local_flush = false;
4276
4277 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
4278
4279 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes);
4280
4281 /*
4282 * No need to care whether allocation memory is successful
4283 * or not since pte prefetch is skiped if it does not have
4284 * enough objects in the cache.
4285 */
4286 mmu_topup_memory_caches(vcpu);
4287
4288 spin_lock(&vcpu->kvm->mmu_lock);
4289 ++vcpu->kvm->stat.mmu_pte_write;
0375f7fa 4290 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
889e5cbc 4291
b67bfe0d 4292 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
a30f47cb 4293 if (detect_write_misaligned(sp, gpa, bytes) ||
a138fe75 4294 detect_write_flooding(sp)) {
0671a8e7 4295 zap_page |= !!kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
f41d335a 4296 &invalid_list);
4cee5764 4297 ++vcpu->kvm->stat.mmu_flooded;
0e7bc4b9
AK
4298 continue;
4299 }
889e5cbc
XG
4300
4301 spte = get_written_sptes(sp, gpa, &npte);
4302 if (!spte)
4303 continue;
4304
0671a8e7 4305 local_flush = true;
ac1b714e 4306 while (npte--) {
79539cec 4307 entry = *spte;
38e3b2b2 4308 mmu_page_zap_pte(vcpu->kvm, sp, spte);
fa1de2bf
XG
4309 if (gentry &&
4310 !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
f759e2b4 4311 & mask.word) && rmap_can_add(vcpu))
7c562522 4312 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
9bb4f6b1 4313 if (need_remote_flush(entry, *spte))
0671a8e7 4314 remote_flush = true;
ac1b714e 4315 ++spte;
9b7a0325 4316 }
9b7a0325 4317 }
0671a8e7 4318 mmu_pte_write_flush_tlb(vcpu, zap_page, remote_flush, local_flush);
d98ba053 4319 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
0375f7fa 4320 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
aaee2c94 4321 spin_unlock(&vcpu->kvm->mmu_lock);
da4a00f0
AK
4322}
4323
a436036b
AK
4324int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
4325{
10589a46
MT
4326 gpa_t gpa;
4327 int r;
a436036b 4328
c5a78f2b 4329 if (vcpu->arch.mmu.direct_map)
60f24784
AK
4330 return 0;
4331
1871c602 4332 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
10589a46 4333
10589a46 4334 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1cb3f3ae 4335
10589a46 4336 return r;
a436036b 4337}
577bdc49 4338EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
a436036b 4339
81f4f76b 4340static void make_mmu_pages_available(struct kvm_vcpu *vcpu)
ebeace86 4341{
d98ba053 4342 LIST_HEAD(invalid_list);
103ad25a 4343
81f4f76b
TY
4344 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
4345 return;
4346
5da59607
TY
4347 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
4348 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
4349 break;
ebeace86 4350
4cee5764 4351 ++vcpu->kvm->stat.mmu_recycled;
ebeace86 4352 }
aa6bd187 4353 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
ebeace86 4354}
ebeace86 4355
dc25e89e
AP
4356int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code,
4357 void *insn, int insn_len)
3067714c 4358{
1cb3f3ae 4359 int r, emulation_type = EMULTYPE_RETRY;
3067714c 4360 enum emulation_result er;
ded58749 4361 bool direct = vcpu->arch.mmu.direct_map || mmu_is_nested(vcpu);
3067714c 4362
e9ee956e
TY
4363 if (unlikely(error_code & PFERR_RSVD_MASK)) {
4364 r = handle_mmio_page_fault(vcpu, cr2, direct);
4365 if (r == RET_MMIO_PF_EMULATE) {
4366 emulation_type = 0;
4367 goto emulate;
4368 }
4369 if (r == RET_MMIO_PF_RETRY)
4370 return 1;
4371 if (r < 0)
4372 return r;
4373 }
4374
56028d08 4375 r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
3067714c 4376 if (r < 0)
e9ee956e
TY
4377 return r;
4378 if (!r)
4379 return 1;
3067714c 4380
ded58749 4381 if (mmio_info_in_cache(vcpu, cr2, direct))
1cb3f3ae 4382 emulation_type = 0;
e9ee956e 4383emulate:
1cb3f3ae 4384 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
3067714c
AK
4385
4386 switch (er) {
4387 case EMULATE_DONE:
4388 return 1;
ac0a48c3 4389 case EMULATE_USER_EXIT:
3067714c 4390 ++vcpu->stat.mmio_exits;
6d77dbfc 4391 /* fall through */
3067714c 4392 case EMULATE_FAIL:
3f5d18a9 4393 return 0;
3067714c
AK
4394 default:
4395 BUG();
4396 }
3067714c
AK
4397}
4398EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
4399
a7052897
MT
4400void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
4401{
a7052897 4402 vcpu->arch.mmu.invlpg(vcpu, gva);
77c3913b 4403 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
a7052897
MT
4404 ++vcpu->stat.invlpg;
4405}
4406EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
4407
18552672
JR
4408void kvm_enable_tdp(void)
4409{
4410 tdp_enabled = true;
4411}
4412EXPORT_SYMBOL_GPL(kvm_enable_tdp);
4413
5f4cb662
JR
4414void kvm_disable_tdp(void)
4415{
4416 tdp_enabled = false;
4417}
4418EXPORT_SYMBOL_GPL(kvm_disable_tdp);
4419
6aa8b732
AK
4420static void free_mmu_pages(struct kvm_vcpu *vcpu)
4421{
ad312c7c 4422 free_page((unsigned long)vcpu->arch.mmu.pae_root);
81407ca5
JR
4423 if (vcpu->arch.mmu.lm_root != NULL)
4424 free_page((unsigned long)vcpu->arch.mmu.lm_root);
6aa8b732
AK
4425}
4426
4427static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
4428{
17ac10ad 4429 struct page *page;
6aa8b732
AK
4430 int i;
4431
17ac10ad
AK
4432 /*
4433 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
4434 * Therefore we need to allocate shadow page tables in the first
4435 * 4GB of memory, which happens to fit the DMA32 zone.
4436 */
4437 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
4438 if (!page)
d7fa6ab2
WY
4439 return -ENOMEM;
4440
ad312c7c 4441 vcpu->arch.mmu.pae_root = page_address(page);
17ac10ad 4442 for (i = 0; i < 4; ++i)
ad312c7c 4443 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
17ac10ad 4444
6aa8b732 4445 return 0;
6aa8b732
AK
4446}
4447
8018c27b 4448int kvm_mmu_create(struct kvm_vcpu *vcpu)
6aa8b732 4449{
e459e322
XG
4450 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
4451 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4452 vcpu->arch.mmu.translate_gpa = translate_gpa;
4453 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
6aa8b732 4454
8018c27b
IM
4455 return alloc_mmu_pages(vcpu);
4456}
6aa8b732 4457
8a3c1a33 4458void kvm_mmu_setup(struct kvm_vcpu *vcpu)
8018c27b 4459{
fa4a2c08 4460 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2c264957 4461
8a3c1a33 4462 init_kvm_mmu(vcpu);
6aa8b732
AK
4463}
4464
1bad2b2a 4465/* The return value indicates if tlb flush on all vcpus is needed. */
018aabb5 4466typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
1bad2b2a
XG
4467
4468/* The caller should hold mmu-lock before calling this function. */
4469static bool
4470slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
4471 slot_level_handler fn, int start_level, int end_level,
4472 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
4473{
4474 struct slot_rmap_walk_iterator iterator;
4475 bool flush = false;
4476
4477 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
4478 end_gfn, &iterator) {
4479 if (iterator.rmap)
4480 flush |= fn(kvm, iterator.rmap);
4481
4482 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
4483 if (flush && lock_flush_tlb) {
4484 kvm_flush_remote_tlbs(kvm);
4485 flush = false;
4486 }
4487 cond_resched_lock(&kvm->mmu_lock);
4488 }
4489 }
4490
4491 if (flush && lock_flush_tlb) {
4492 kvm_flush_remote_tlbs(kvm);
4493 flush = false;
4494 }
4495
4496 return flush;
4497}
4498
4499static bool
4500slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4501 slot_level_handler fn, int start_level, int end_level,
4502 bool lock_flush_tlb)
4503{
4504 return slot_handle_level_range(kvm, memslot, fn, start_level,
4505 end_level, memslot->base_gfn,
4506 memslot->base_gfn + memslot->npages - 1,
4507 lock_flush_tlb);
4508}
4509
4510static bool
4511slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4512 slot_level_handler fn, bool lock_flush_tlb)
4513{
4514 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
4515 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
4516}
4517
4518static bool
4519slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4520 slot_level_handler fn, bool lock_flush_tlb)
4521{
4522 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
4523 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
4524}
4525
4526static bool
4527slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
4528 slot_level_handler fn, bool lock_flush_tlb)
4529{
4530 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
4531 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
4532}
4533
efdfe536
XG
4534void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
4535{
4536 struct kvm_memslots *slots;
4537 struct kvm_memory_slot *memslot;
9da0e4d5 4538 int i;
efdfe536
XG
4539
4540 spin_lock(&kvm->mmu_lock);
9da0e4d5
PB
4541 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
4542 slots = __kvm_memslots(kvm, i);
4543 kvm_for_each_memslot(memslot, slots) {
4544 gfn_t start, end;
4545
4546 start = max(gfn_start, memslot->base_gfn);
4547 end = min(gfn_end, memslot->base_gfn + memslot->npages);
4548 if (start >= end)
4549 continue;
efdfe536 4550
9da0e4d5
PB
4551 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
4552 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
4553 start, end - 1, true);
4554 }
efdfe536
XG
4555 }
4556
4557 spin_unlock(&kvm->mmu_lock);
4558}
4559
018aabb5
TY
4560static bool slot_rmap_write_protect(struct kvm *kvm,
4561 struct kvm_rmap_head *rmap_head)
d77aa73c 4562{
018aabb5 4563 return __rmap_write_protect(kvm, rmap_head, false);
d77aa73c
XG
4564}
4565
1c91cad4
KH
4566void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
4567 struct kvm_memory_slot *memslot)
6aa8b732 4568{
d77aa73c 4569 bool flush;
6aa8b732 4570
9d1beefb 4571 spin_lock(&kvm->mmu_lock);
d77aa73c
XG
4572 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
4573 false);
9d1beefb 4574 spin_unlock(&kvm->mmu_lock);
198c74f4
XG
4575
4576 /*
4577 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
4578 * which do tlb flush out of mmu-lock should be serialized by
4579 * kvm->slots_lock otherwise tlb flush would be missed.
4580 */
4581 lockdep_assert_held(&kvm->slots_lock);
4582
4583 /*
4584 * We can flush all the TLBs out of the mmu lock without TLB
4585 * corruption since we just change the spte from writable to
4586 * readonly so that we only need to care the case of changing
4587 * spte from present to present (changing the spte from present
4588 * to nonpresent will flush all the TLBs immediately), in other
4589 * words, the only case we care is mmu_spte_update() where we
4590 * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
4591 * instead of PT_WRITABLE_MASK, that means it does not depend
4592 * on PT_WRITABLE_MASK anymore.
4593 */
d91ffee9
KH
4594 if (flush)
4595 kvm_flush_remote_tlbs(kvm);
6aa8b732 4596}
37a7d8b0 4597
3ea3b7fa 4598static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
018aabb5 4599 struct kvm_rmap_head *rmap_head)
3ea3b7fa
WL
4600{
4601 u64 *sptep;
4602 struct rmap_iterator iter;
4603 int need_tlb_flush = 0;
ba049e93 4604 kvm_pfn_t pfn;
3ea3b7fa
WL
4605 struct kvm_mmu_page *sp;
4606
0d536790 4607restart:
018aabb5 4608 for_each_rmap_spte(rmap_head, &iter, sptep) {
3ea3b7fa
WL
4609 sp = page_header(__pa(sptep));
4610 pfn = spte_to_pfn(*sptep);
4611
4612 /*
decf6333
XG
4613 * We cannot do huge page mapping for indirect shadow pages,
4614 * which are found on the last rmap (level = 1) when not using
4615 * tdp; such shadow pages are synced with the page table in
4616 * the guest, and the guest page table is using 4K page size
4617 * mapping if the indirect sp has level = 1.
3ea3b7fa
WL
4618 */
4619 if (sp->role.direct &&
4620 !kvm_is_reserved_pfn(pfn) &&
4621 PageTransCompound(pfn_to_page(pfn))) {
4622 drop_spte(kvm, sptep);
3ea3b7fa 4623 need_tlb_flush = 1;
0d536790
XG
4624 goto restart;
4625 }
3ea3b7fa
WL
4626 }
4627
4628 return need_tlb_flush;
4629}
4630
4631void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
f36f3f28 4632 const struct kvm_memory_slot *memslot)
3ea3b7fa 4633{
f36f3f28 4634 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
3ea3b7fa 4635 spin_lock(&kvm->mmu_lock);
f36f3f28
PB
4636 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
4637 kvm_mmu_zap_collapsible_spte, true);
3ea3b7fa
WL
4638 spin_unlock(&kvm->mmu_lock);
4639}
4640
f4b4b180
KH
4641void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
4642 struct kvm_memory_slot *memslot)
4643{
d77aa73c 4644 bool flush;
f4b4b180
KH
4645
4646 spin_lock(&kvm->mmu_lock);
d77aa73c 4647 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
f4b4b180
KH
4648 spin_unlock(&kvm->mmu_lock);
4649
4650 lockdep_assert_held(&kvm->slots_lock);
4651
4652 /*
4653 * It's also safe to flush TLBs out of mmu lock here as currently this
4654 * function is only used for dirty logging, in which case flushing TLB
4655 * out of mmu lock also guarantees no dirty pages will be lost in
4656 * dirty_bitmap.
4657 */
4658 if (flush)
4659 kvm_flush_remote_tlbs(kvm);
4660}
4661EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
4662
4663void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
4664 struct kvm_memory_slot *memslot)
4665{
d77aa73c 4666 bool flush;
f4b4b180
KH
4667
4668 spin_lock(&kvm->mmu_lock);
d77aa73c
XG
4669 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
4670 false);
f4b4b180
KH
4671 spin_unlock(&kvm->mmu_lock);
4672
4673 /* see kvm_mmu_slot_remove_write_access */
4674 lockdep_assert_held(&kvm->slots_lock);
4675
4676 if (flush)
4677 kvm_flush_remote_tlbs(kvm);
4678}
4679EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
4680
4681void kvm_mmu_slot_set_dirty(struct kvm *kvm,
4682 struct kvm_memory_slot *memslot)
4683{
d77aa73c 4684 bool flush;
f4b4b180
KH
4685
4686 spin_lock(&kvm->mmu_lock);
d77aa73c 4687 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
f4b4b180
KH
4688 spin_unlock(&kvm->mmu_lock);
4689
4690 lockdep_assert_held(&kvm->slots_lock);
4691
4692 /* see kvm_mmu_slot_leaf_clear_dirty */
4693 if (flush)
4694 kvm_flush_remote_tlbs(kvm);
4695}
4696EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
4697
e7d11c7a 4698#define BATCH_ZAP_PAGES 10
5304b8d3
XG
4699static void kvm_zap_obsolete_pages(struct kvm *kvm)
4700{
4701 struct kvm_mmu_page *sp, *node;
e7d11c7a 4702 int batch = 0;
5304b8d3
XG
4703
4704restart:
4705 list_for_each_entry_safe_reverse(sp, node,
4706 &kvm->arch.active_mmu_pages, link) {
e7d11c7a
XG
4707 int ret;
4708
5304b8d3
XG
4709 /*
4710 * No obsolete page exists before new created page since
4711 * active_mmu_pages is the FIFO list.
4712 */
4713 if (!is_obsolete_sp(kvm, sp))
4714 break;
4715
4716 /*
5304b8d3
XG
4717 * Since we are reversely walking the list and the invalid
4718 * list will be moved to the head, skip the invalid page
4719 * can help us to avoid the infinity list walking.
4720 */
4721 if (sp->role.invalid)
4722 continue;
4723
f34d251d
XG
4724 /*
4725 * Need not flush tlb since we only zap the sp with invalid
4726 * generation number.
4727 */
e7d11c7a 4728 if (batch >= BATCH_ZAP_PAGES &&
f34d251d 4729 cond_resched_lock(&kvm->mmu_lock)) {
e7d11c7a 4730 batch = 0;
5304b8d3
XG
4731 goto restart;
4732 }
4733
365c8868
XG
4734 ret = kvm_mmu_prepare_zap_page(kvm, sp,
4735 &kvm->arch.zapped_obsolete_pages);
e7d11c7a
XG
4736 batch += ret;
4737
4738 if (ret)
5304b8d3
XG
4739 goto restart;
4740 }
4741
f34d251d
XG
4742 /*
4743 * Should flush tlb before free page tables since lockless-walking
4744 * may use the pages.
4745 */
365c8868 4746 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5304b8d3
XG
4747}
4748
4749/*
4750 * Fast invalidate all shadow pages and use lock-break technique
4751 * to zap obsolete pages.
4752 *
4753 * It's required when memslot is being deleted or VM is being
4754 * destroyed, in these cases, we should ensure that KVM MMU does
4755 * not use any resource of the being-deleted slot or all slots
4756 * after calling the function.
4757 */
4758void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
4759{
4760 spin_lock(&kvm->mmu_lock);
35006126 4761 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5304b8d3
XG
4762 kvm->arch.mmu_valid_gen++;
4763
f34d251d
XG
4764 /*
4765 * Notify all vcpus to reload its shadow page table
4766 * and flush TLB. Then all vcpus will switch to new
4767 * shadow page table with the new mmu_valid_gen.
4768 *
4769 * Note: we should do this under the protection of
4770 * mmu-lock, otherwise, vcpu would purge shadow page
4771 * but miss tlb flush.
4772 */
4773 kvm_reload_remote_mmus(kvm);
4774
5304b8d3
XG
4775 kvm_zap_obsolete_pages(kvm);
4776 spin_unlock(&kvm->mmu_lock);
4777}
4778
365c8868
XG
4779static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
4780{
4781 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
4782}
4783
54bf36aa 4784void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, struct kvm_memslots *slots)
f8f55942
XG
4785{
4786 /*
4787 * The very rare case: if the generation-number is round,
4788 * zap all shadow pages.
f8f55942 4789 */
54bf36aa 4790 if (unlikely((slots->generation & MMIO_GEN_MASK) == 0)) {
a629df7e 4791 printk_ratelimited(KERN_DEBUG "kvm: zapping shadow pages for mmio generation wraparound\n");
a8eca9dc 4792 kvm_mmu_invalidate_zap_all_pages(kvm);
7a2e8aaf 4793 }
f8f55942
XG
4794}
4795
70534a73
DC
4796static unsigned long
4797mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
3ee16c81
IE
4798{
4799 struct kvm *kvm;
1495f230 4800 int nr_to_scan = sc->nr_to_scan;
70534a73 4801 unsigned long freed = 0;
3ee16c81 4802
2f303b74 4803 spin_lock(&kvm_lock);
3ee16c81
IE
4804
4805 list_for_each_entry(kvm, &vm_list, vm_list) {
3d56cbdf 4806 int idx;
d98ba053 4807 LIST_HEAD(invalid_list);
3ee16c81 4808
35f2d16b
TY
4809 /*
4810 * Never scan more than sc->nr_to_scan VM instances.
4811 * Will not hit this condition practically since we do not try
4812 * to shrink more than one VM and it is very unlikely to see
4813 * !n_used_mmu_pages so many times.
4814 */
4815 if (!nr_to_scan--)
4816 break;
19526396
GN
4817 /*
4818 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
4819 * here. We may skip a VM instance errorneosly, but we do not
4820 * want to shrink a VM that only started to populate its MMU
4821 * anyway.
4822 */
365c8868
XG
4823 if (!kvm->arch.n_used_mmu_pages &&
4824 !kvm_has_zapped_obsolete_pages(kvm))
19526396 4825 continue;
19526396 4826
f656ce01 4827 idx = srcu_read_lock(&kvm->srcu);
3ee16c81 4828 spin_lock(&kvm->mmu_lock);
3ee16c81 4829
365c8868
XG
4830 if (kvm_has_zapped_obsolete_pages(kvm)) {
4831 kvm_mmu_commit_zap_page(kvm,
4832 &kvm->arch.zapped_obsolete_pages);
4833 goto unlock;
4834 }
4835
70534a73
DC
4836 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
4837 freed++;
d98ba053 4838 kvm_mmu_commit_zap_page(kvm, &invalid_list);
19526396 4839
365c8868 4840unlock:
3ee16c81 4841 spin_unlock(&kvm->mmu_lock);
f656ce01 4842 srcu_read_unlock(&kvm->srcu, idx);
19526396 4843
70534a73
DC
4844 /*
4845 * unfair on small ones
4846 * per-vm shrinkers cry out
4847 * sadness comes quickly
4848 */
19526396
GN
4849 list_move_tail(&kvm->vm_list, &vm_list);
4850 break;
3ee16c81 4851 }
3ee16c81 4852
2f303b74 4853 spin_unlock(&kvm_lock);
70534a73 4854 return freed;
70534a73
DC
4855}
4856
4857static unsigned long
4858mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
4859{
45221ab6 4860 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
3ee16c81
IE
4861}
4862
4863static struct shrinker mmu_shrinker = {
70534a73
DC
4864 .count_objects = mmu_shrink_count,
4865 .scan_objects = mmu_shrink_scan,
3ee16c81
IE
4866 .seeks = DEFAULT_SEEKS * 10,
4867};
4868
2ddfd20e 4869static void mmu_destroy_caches(void)
b5a33a75 4870{
53c07b18
XG
4871 if (pte_list_desc_cache)
4872 kmem_cache_destroy(pte_list_desc_cache);
d3d25b04
AK
4873 if (mmu_page_header_cache)
4874 kmem_cache_destroy(mmu_page_header_cache);
b5a33a75
AK
4875}
4876
4877int kvm_mmu_module_init(void)
4878{
53c07b18
XG
4879 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
4880 sizeof(struct pte_list_desc),
20c2df83 4881 0, 0, NULL);
53c07b18 4882 if (!pte_list_desc_cache)
b5a33a75
AK
4883 goto nomem;
4884
d3d25b04
AK
4885 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
4886 sizeof(struct kvm_mmu_page),
20c2df83 4887 0, 0, NULL);
d3d25b04
AK
4888 if (!mmu_page_header_cache)
4889 goto nomem;
4890
908c7f19 4891 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
45bf21a8
WY
4892 goto nomem;
4893
3ee16c81
IE
4894 register_shrinker(&mmu_shrinker);
4895
b5a33a75
AK
4896 return 0;
4897
4898nomem:
3ee16c81 4899 mmu_destroy_caches();
b5a33a75
AK
4900 return -ENOMEM;
4901}
4902
3ad82a7e
ZX
4903/*
4904 * Caculate mmu pages needed for kvm.
4905 */
4906unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
4907{
3ad82a7e
ZX
4908 unsigned int nr_mmu_pages;
4909 unsigned int nr_pages = 0;
bc6678a3 4910 struct kvm_memslots *slots;
be6ba0f0 4911 struct kvm_memory_slot *memslot;
9da0e4d5 4912 int i;
3ad82a7e 4913
9da0e4d5
PB
4914 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
4915 slots = __kvm_memslots(kvm, i);
90d83dc3 4916
9da0e4d5
PB
4917 kvm_for_each_memslot(memslot, slots)
4918 nr_pages += memslot->npages;
4919 }
3ad82a7e
ZX
4920
4921 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
4922 nr_mmu_pages = max(nr_mmu_pages,
9da0e4d5 4923 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
3ad82a7e
ZX
4924
4925 return nr_mmu_pages;
4926}
4927
c42fffe3
XG
4928void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
4929{
95f93af4 4930 kvm_mmu_unload(vcpu);
c42fffe3
XG
4931 free_mmu_pages(vcpu);
4932 mmu_free_memory_caches(vcpu);
b034cf01
XG
4933}
4934
b034cf01
XG
4935void kvm_mmu_module_exit(void)
4936{
4937 mmu_destroy_caches();
4938 percpu_counter_destroy(&kvm_total_used_mmu_pages);
4939 unregister_shrinker(&mmu_shrinker);
c42fffe3
XG
4940 mmu_audit_disable();
4941}