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