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