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