420a5ca3c0ee445d83f8b155726806fbe90f0810
[linux-2.6-block.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                           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 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         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         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(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, 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, 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 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, 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, 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, pfn_t *pfnp, int *levelp)
2756 {
2757         pfn_t pfn = *pfnp;
2758         gfn_t gfn = *gfnp;
2759         int level = *levelp;
2760
2761         /*
2762          * Check if it's a transparent hugepage. If this would be an
2763          * hugetlbfs page, level wouldn't be set to
2764          * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
2765          * here.
2766          */
2767         if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
2768             level == PT_PAGE_TABLE_LEVEL &&
2769             PageTransCompound(pfn_to_page(pfn)) &&
2770             !has_wrprotected_page(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
2771                 unsigned long mask;
2772                 /*
2773                  * mmu_notifier_retry was successful and we hold the
2774                  * mmu_lock here, so the pmd can't become splitting
2775                  * from under us, and in turn
2776                  * __split_huge_page_refcount() can't run from under
2777                  * us and we can safely transfer the refcount from
2778                  * PG_tail to PG_head as we switch the pfn to tail to
2779                  * head.
2780                  */
2781                 *levelp = level = PT_DIRECTORY_LEVEL;
2782                 mask = KVM_PAGES_PER_HPAGE(level) - 1;
2783                 VM_BUG_ON((gfn & mask) != (pfn & mask));
2784                 if (pfn & mask) {
2785                         gfn &= ~mask;
2786                         *gfnp = gfn;
2787                         kvm_release_pfn_clean(pfn);
2788                         pfn &= ~mask;
2789                         kvm_get_pfn(pfn);
2790                         *pfnp = pfn;
2791                 }
2792         }
2793 }
2794
2795 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
2796                                 pfn_t pfn, unsigned access, int *ret_val)
2797 {
2798         bool ret = true;
2799
2800         /* The pfn is invalid, report the error! */
2801         if (unlikely(is_error_pfn(pfn))) {
2802                 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
2803                 goto exit;
2804         }
2805
2806         if (unlikely(is_noslot_pfn(pfn)))
2807                 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
2808
2809         ret = false;
2810 exit:
2811         return ret;
2812 }
2813
2814 static bool page_fault_can_be_fast(u32 error_code)
2815 {
2816         /*
2817          * Do not fix the mmio spte with invalid generation number which
2818          * need to be updated by slow page fault path.
2819          */
2820         if (unlikely(error_code & PFERR_RSVD_MASK))
2821                 return false;
2822
2823         /*
2824          * #PF can be fast only if the shadow page table is present and it
2825          * is caused by write-protect, that means we just need change the
2826          * W bit of the spte which can be done out of mmu-lock.
2827          */
2828         if (!(error_code & PFERR_PRESENT_MASK) ||
2829               !(error_code & PFERR_WRITE_MASK))
2830                 return false;
2831
2832         return true;
2833 }
2834
2835 static bool
2836 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2837                         u64 *sptep, u64 spte)
2838 {
2839         gfn_t gfn;
2840
2841         WARN_ON(!sp->role.direct);
2842
2843         /*
2844          * The gfn of direct spte is stable since it is calculated
2845          * by sp->gfn.
2846          */
2847         gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
2848
2849         /*
2850          * Theoretically we could also set dirty bit (and flush TLB) here in
2851          * order to eliminate unnecessary PML logging. See comments in
2852          * set_spte. But fast_page_fault is very unlikely to happen with PML
2853          * enabled, so we do not do this. This might result in the same GPA
2854          * to be logged in PML buffer again when the write really happens, and
2855          * eventually to be called by mark_page_dirty twice. But it's also no
2856          * harm. This also avoids the TLB flush needed after setting dirty bit
2857          * so non-PML cases won't be impacted.
2858          *
2859          * Compare with set_spte where instead shadow_dirty_mask is set.
2860          */
2861         if (cmpxchg64(sptep, spte, spte | PT_WRITABLE_MASK) == spte)
2862                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
2863
2864         return true;
2865 }
2866
2867 /*
2868  * Return value:
2869  * - true: let the vcpu to access on the same address again.
2870  * - false: let the real page fault path to fix it.
2871  */
2872 static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
2873                             u32 error_code)
2874 {
2875         struct kvm_shadow_walk_iterator iterator;
2876         struct kvm_mmu_page *sp;
2877         bool ret = false;
2878         u64 spte = 0ull;
2879
2880         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2881                 return false;
2882
2883         if (!page_fault_can_be_fast(error_code))
2884                 return false;
2885
2886         walk_shadow_page_lockless_begin(vcpu);
2887         for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
2888                 if (!is_shadow_present_pte(spte) || iterator.level < level)
2889                         break;
2890
2891         /*
2892          * If the mapping has been changed, let the vcpu fault on the
2893          * same address again.
2894          */
2895         if (!is_shadow_present_pte(spte)) {
2896                 ret = true;
2897                 goto exit;
2898         }
2899
2900         sp = page_header(__pa(iterator.sptep));
2901         if (!is_last_spte(spte, sp->role.level))
2902                 goto exit;
2903
2904         /*
2905          * Check if it is a spurious fault caused by TLB lazily flushed.
2906          *
2907          * Need not check the access of upper level table entries since
2908          * they are always ACC_ALL.
2909          */
2910          if (is_writable_pte(spte)) {
2911                 ret = true;
2912                 goto exit;
2913         }
2914
2915         /*
2916          * Currently, to simplify the code, only the spte write-protected
2917          * by dirty-log can be fast fixed.
2918          */
2919         if (!spte_is_locklessly_modifiable(spte))
2920                 goto exit;
2921
2922         /*
2923          * Do not fix write-permission on the large spte since we only dirty
2924          * the first page into the dirty-bitmap in fast_pf_fix_direct_spte()
2925          * that means other pages are missed if its slot is dirty-logged.
2926          *
2927          * Instead, we let the slow page fault path create a normal spte to
2928          * fix the access.
2929          *
2930          * See the comments in kvm_arch_commit_memory_region().
2931          */
2932         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
2933                 goto exit;
2934
2935         /*
2936          * Currently, fast page fault only works for direct mapping since
2937          * the gfn is not stable for indirect shadow page.
2938          * See Documentation/virtual/kvm/locking.txt to get more detail.
2939          */
2940         ret = fast_pf_fix_direct_spte(vcpu, sp, iterator.sptep, spte);
2941 exit:
2942         trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
2943                               spte, ret);
2944         walk_shadow_page_lockless_end(vcpu);
2945
2946         return ret;
2947 }
2948
2949 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
2950                          gva_t gva, pfn_t *pfn, bool write, bool *writable);
2951 static void make_mmu_pages_available(struct kvm_vcpu *vcpu);
2952
2953 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
2954                          gfn_t gfn, bool prefault)
2955 {
2956         int r;
2957         int level;
2958         bool force_pt_level = false;
2959         pfn_t pfn;
2960         unsigned long mmu_seq;
2961         bool map_writable, write = error_code & PFERR_WRITE_MASK;
2962
2963         level = mapping_level(vcpu, gfn, &force_pt_level);
2964         if (likely(!force_pt_level)) {
2965                 /*
2966                  * This path builds a PAE pagetable - so we can map
2967                  * 2mb pages at maximum. Therefore check if the level
2968                  * is larger than that.
2969                  */
2970                 if (level > PT_DIRECTORY_LEVEL)
2971                         level = PT_DIRECTORY_LEVEL;
2972
2973                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
2974         }
2975
2976         if (fast_page_fault(vcpu, v, level, error_code))
2977                 return 0;
2978
2979         mmu_seq = vcpu->kvm->mmu_notifier_seq;
2980         smp_rmb();
2981
2982         if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
2983                 return 0;
2984
2985         if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
2986                 return r;
2987
2988         spin_lock(&vcpu->kvm->mmu_lock);
2989         if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
2990                 goto out_unlock;
2991         make_mmu_pages_available(vcpu);
2992         if (likely(!force_pt_level))
2993                 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
2994         r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
2995         spin_unlock(&vcpu->kvm->mmu_lock);
2996
2997         return r;
2998
2999 out_unlock:
3000         spin_unlock(&vcpu->kvm->mmu_lock);
3001         kvm_release_pfn_clean(pfn);
3002         return 0;
3003 }
3004
3005
3006 static void mmu_free_roots(struct kvm_vcpu *vcpu)
3007 {
3008         int i;
3009         struct kvm_mmu_page *sp;
3010         LIST_HEAD(invalid_list);
3011
3012         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3013                 return;
3014
3015         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL &&
3016             (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL ||
3017              vcpu->arch.mmu.direct_map)) {
3018                 hpa_t root = vcpu->arch.mmu.root_hpa;
3019
3020                 spin_lock(&vcpu->kvm->mmu_lock);
3021                 sp = page_header(root);
3022                 --sp->root_count;
3023                 if (!sp->root_count && sp->role.invalid) {
3024                         kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
3025                         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3026                 }
3027                 spin_unlock(&vcpu->kvm->mmu_lock);
3028                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3029                 return;
3030         }
3031
3032         spin_lock(&vcpu->kvm->mmu_lock);
3033         for (i = 0; i < 4; ++i) {
3034                 hpa_t root = vcpu->arch.mmu.pae_root[i];
3035
3036                 if (root) {
3037                         root &= PT64_BASE_ADDR_MASK;
3038                         sp = page_header(root);
3039                         --sp->root_count;
3040                         if (!sp->root_count && sp->role.invalid)
3041                                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
3042                                                          &invalid_list);
3043                 }
3044                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
3045         }
3046         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3047         spin_unlock(&vcpu->kvm->mmu_lock);
3048         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3049 }
3050
3051 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3052 {
3053         int ret = 0;
3054
3055         if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3056                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3057                 ret = 1;
3058         }
3059
3060         return ret;
3061 }
3062
3063 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3064 {
3065         struct kvm_mmu_page *sp;
3066         unsigned i;
3067
3068         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3069                 spin_lock(&vcpu->kvm->mmu_lock);
3070                 make_mmu_pages_available(vcpu);
3071                 sp = kvm_mmu_get_page(vcpu, 0, 0, PT64_ROOT_LEVEL, 1, ACC_ALL);
3072                 ++sp->root_count;
3073                 spin_unlock(&vcpu->kvm->mmu_lock);
3074                 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3075         } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3076                 for (i = 0; i < 4; ++i) {
3077                         hpa_t root = vcpu->arch.mmu.pae_root[i];
3078
3079                         MMU_WARN_ON(VALID_PAGE(root));
3080                         spin_lock(&vcpu->kvm->mmu_lock);
3081                         make_mmu_pages_available(vcpu);
3082                         sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3083                                         i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3084                         root = __pa(sp->spt);
3085                         ++sp->root_count;
3086                         spin_unlock(&vcpu->kvm->mmu_lock);
3087                         vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3088                 }
3089                 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3090         } else
3091                 BUG();
3092
3093         return 0;
3094 }
3095
3096 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3097 {
3098         struct kvm_mmu_page *sp;
3099         u64 pdptr, pm_mask;
3100         gfn_t root_gfn;
3101         int i;
3102
3103         root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3104
3105         if (mmu_check_root(vcpu, root_gfn))
3106                 return 1;
3107
3108         /*
3109          * Do we shadow a long mode page table? If so we need to
3110          * write-protect the guests page table root.
3111          */
3112         if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
3113                 hpa_t root = vcpu->arch.mmu.root_hpa;
3114
3115                 MMU_WARN_ON(VALID_PAGE(root));
3116
3117                 spin_lock(&vcpu->kvm->mmu_lock);
3118                 make_mmu_pages_available(vcpu);
3119                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0, PT64_ROOT_LEVEL,
3120                                       0, ACC_ALL);
3121                 root = __pa(sp->spt);
3122                 ++sp->root_count;
3123                 spin_unlock(&vcpu->kvm->mmu_lock);
3124                 vcpu->arch.mmu.root_hpa = root;
3125                 return 0;
3126         }
3127
3128         /*
3129          * We shadow a 32 bit page table. This may be a legacy 2-level
3130          * or a PAE 3-level page table. In either case we need to be aware that
3131          * the shadow page table may be a PAE or a long mode page table.
3132          */
3133         pm_mask = PT_PRESENT_MASK;
3134         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL)
3135                 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3136
3137         for (i = 0; i < 4; ++i) {
3138                 hpa_t root = vcpu->arch.mmu.pae_root[i];
3139
3140                 MMU_WARN_ON(VALID_PAGE(root));
3141                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3142                         pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3143                         if (!is_present_gpte(pdptr)) {
3144                                 vcpu->arch.mmu.pae_root[i] = 0;
3145                                 continue;
3146                         }
3147                         root_gfn = pdptr >> PAGE_SHIFT;
3148                         if (mmu_check_root(vcpu, root_gfn))
3149                                 return 1;
3150                 }
3151                 spin_lock(&vcpu->kvm->mmu_lock);
3152                 make_mmu_pages_available(vcpu);
3153                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3154                                       0, ACC_ALL);
3155                 root = __pa(sp->spt);
3156                 ++sp->root_count;
3157                 spin_unlock(&vcpu->kvm->mmu_lock);
3158
3159                 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3160         }
3161         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3162
3163         /*
3164          * If we shadow a 32 bit page table with a long mode page
3165          * table we enter this path.
3166          */
3167         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3168                 if (vcpu->arch.mmu.lm_root == NULL) {
3169                         /*
3170                          * The additional page necessary for this is only
3171                          * allocated on demand.
3172                          */
3173
3174                         u64 *lm_root;
3175
3176                         lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3177                         if (lm_root == NULL)
3178                                 return 1;
3179
3180                         lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3181
3182                         vcpu->arch.mmu.lm_root = lm_root;
3183                 }
3184
3185                 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3186         }
3187
3188         return 0;
3189 }
3190
3191 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3192 {
3193         if (vcpu->arch.mmu.direct_map)
3194                 return mmu_alloc_direct_roots(vcpu);
3195         else
3196                 return mmu_alloc_shadow_roots(vcpu);
3197 }
3198
3199 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
3200 {
3201         int i;
3202         struct kvm_mmu_page *sp;
3203
3204         if (vcpu->arch.mmu.direct_map)
3205                 return;
3206
3207         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3208                 return;
3209
3210         vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3211         kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3212         if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
3213                 hpa_t root = vcpu->arch.mmu.root_hpa;
3214                 sp = page_header(root);
3215                 mmu_sync_children(vcpu, sp);
3216                 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3217                 return;
3218         }
3219         for (i = 0; i < 4; ++i) {
3220                 hpa_t root = vcpu->arch.mmu.pae_root[i];
3221
3222                 if (root && VALID_PAGE(root)) {
3223                         root &= PT64_BASE_ADDR_MASK;
3224                         sp = page_header(root);
3225                         mmu_sync_children(vcpu, sp);
3226                 }
3227         }
3228         kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3229 }
3230
3231 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3232 {
3233         spin_lock(&vcpu->kvm->mmu_lock);
3234         mmu_sync_roots(vcpu);
3235         spin_unlock(&vcpu->kvm->mmu_lock);
3236 }
3237 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3238
3239 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3240                                   u32 access, struct x86_exception *exception)
3241 {
3242         if (exception)
3243                 exception->error_code = 0;
3244         return vaddr;
3245 }
3246
3247 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3248                                          u32 access,
3249                                          struct x86_exception *exception)
3250 {
3251         if (exception)
3252                 exception->error_code = 0;
3253         return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3254 }
3255
3256 static bool
3257 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3258 {
3259         int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3260
3261         return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3262                 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3263 }
3264
3265 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3266 {
3267         return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3268 }
3269
3270 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3271 {
3272         return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3273 }
3274
3275 static bool quickly_check_mmio_pf(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3276 {
3277         if (direct)
3278                 return vcpu_match_mmio_gpa(vcpu, addr);
3279
3280         return vcpu_match_mmio_gva(vcpu, addr);
3281 }
3282
3283 /* return true if reserved bit is detected on spte. */
3284 static bool
3285 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3286 {
3287         struct kvm_shadow_walk_iterator iterator;
3288         u64 sptes[PT64_ROOT_LEVEL], spte = 0ull;
3289         int root, leaf;
3290         bool reserved = false;
3291
3292         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3293                 goto exit;
3294
3295         walk_shadow_page_lockless_begin(vcpu);
3296
3297         for (shadow_walk_init(&iterator, vcpu, addr),
3298                  leaf = root = iterator.level;
3299              shadow_walk_okay(&iterator);
3300              __shadow_walk_next(&iterator, spte)) {
3301                 spte = mmu_spte_get_lockless(iterator.sptep);
3302
3303                 sptes[leaf - 1] = spte;
3304                 leaf--;
3305
3306                 if (!is_shadow_present_pte(spte))
3307                         break;
3308
3309                 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3310                                                     iterator.level);
3311         }
3312
3313         walk_shadow_page_lockless_end(vcpu);
3314
3315         if (reserved) {
3316                 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3317                        __func__, addr);
3318                 while (root > leaf) {
3319                         pr_err("------ spte 0x%llx level %d.\n",
3320                                sptes[root - 1], root);
3321                         root--;
3322                 }
3323         }
3324 exit:
3325         *sptep = spte;
3326         return reserved;
3327 }
3328
3329 int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3330 {
3331         u64 spte;
3332         bool reserved;
3333
3334         if (quickly_check_mmio_pf(vcpu, addr, direct))
3335                 return RET_MMIO_PF_EMULATE;
3336
3337         reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3338         if (WARN_ON(reserved))
3339                 return RET_MMIO_PF_BUG;
3340
3341         if (is_mmio_spte(spte)) {
3342                 gfn_t gfn = get_mmio_spte_gfn(spte);
3343                 unsigned access = get_mmio_spte_access(spte);
3344
3345                 if (!check_mmio_spte(vcpu, spte))
3346                         return RET_MMIO_PF_INVALID;
3347
3348                 if (direct)
3349                         addr = 0;
3350
3351                 trace_handle_mmio_page_fault(addr, gfn, access);
3352                 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3353                 return RET_MMIO_PF_EMULATE;
3354         }
3355
3356         /*
3357          * If the page table is zapped by other cpus, let CPU fault again on
3358          * the address.
3359          */
3360         return RET_MMIO_PF_RETRY;
3361 }
3362 EXPORT_SYMBOL_GPL(handle_mmio_page_fault);
3363
3364 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3365                                 u32 error_code, bool prefault)
3366 {
3367         gfn_t gfn;
3368         int r;
3369
3370         pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3371
3372         if (unlikely(error_code & PFERR_RSVD_MASK)) {
3373                 r = handle_mmio_page_fault(vcpu, gva, true);
3374
3375                 if (likely(r != RET_MMIO_PF_INVALID))
3376                         return r;
3377         }
3378
3379         r = mmu_topup_memory_caches(vcpu);
3380         if (r)
3381                 return r;
3382
3383         MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3384
3385         gfn = gva >> PAGE_SHIFT;
3386
3387         return nonpaging_map(vcpu, gva & PAGE_MASK,
3388                              error_code, gfn, prefault);
3389 }
3390
3391 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3392 {
3393         struct kvm_arch_async_pf arch;
3394
3395         arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3396         arch.gfn = gfn;
3397         arch.direct_map = vcpu->arch.mmu.direct_map;
3398         arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
3399
3400         return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3401 }
3402
3403 static bool can_do_async_pf(struct kvm_vcpu *vcpu)
3404 {
3405         if (unlikely(!lapic_in_kernel(vcpu) ||
3406                      kvm_event_needs_reinjection(vcpu)))
3407                 return false;
3408
3409         return kvm_x86_ops->interrupt_allowed(vcpu);
3410 }
3411
3412 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3413                          gva_t gva, pfn_t *pfn, bool write, bool *writable)
3414 {
3415         struct kvm_memory_slot *slot;
3416         bool async;
3417
3418         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3419         async = false;
3420         *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
3421         if (!async)
3422                 return false; /* *pfn has correct page already */
3423
3424         if (!prefault && can_do_async_pf(vcpu)) {
3425                 trace_kvm_try_async_get_page(gva, gfn);
3426                 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3427                         trace_kvm_async_pf_doublefault(gva, gfn);
3428                         kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3429                         return true;
3430                 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
3431                         return true;
3432         }
3433
3434         *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
3435         return false;
3436 }
3437
3438 static bool
3439 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
3440 {
3441         int page_num = KVM_PAGES_PER_HPAGE(level);
3442
3443         gfn &= ~(page_num - 1);
3444
3445         return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
3446 }
3447
3448 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
3449                           bool prefault)
3450 {
3451         pfn_t pfn;
3452         int r;
3453         int level;
3454         bool force_pt_level;
3455         gfn_t gfn = gpa >> PAGE_SHIFT;
3456         unsigned long mmu_seq;
3457         int write = error_code & PFERR_WRITE_MASK;
3458         bool map_writable;
3459
3460         MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3461
3462         if (unlikely(error_code & PFERR_RSVD_MASK)) {
3463                 r = handle_mmio_page_fault(vcpu, gpa, true);
3464
3465                 if (likely(r != RET_MMIO_PF_INVALID))
3466                         return r;
3467         }
3468
3469         r = mmu_topup_memory_caches(vcpu);
3470         if (r)
3471                 return r;
3472
3473         force_pt_level = !check_hugepage_cache_consistency(vcpu, gfn,
3474                                                            PT_DIRECTORY_LEVEL);
3475         level = mapping_level(vcpu, gfn, &force_pt_level);
3476         if (likely(!force_pt_level)) {
3477                 if (level > PT_DIRECTORY_LEVEL &&
3478                     !check_hugepage_cache_consistency(vcpu, gfn, level))
3479                         level = PT_DIRECTORY_LEVEL;
3480                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3481         }
3482
3483         if (fast_page_fault(vcpu, gpa, level, error_code))
3484                 return 0;
3485
3486         mmu_seq = vcpu->kvm->mmu_notifier_seq;
3487         smp_rmb();
3488
3489         if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3490                 return 0;
3491
3492         if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
3493                 return r;
3494
3495         spin_lock(&vcpu->kvm->mmu_lock);
3496         if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3497                 goto out_unlock;
3498         make_mmu_pages_available(vcpu);
3499         if (likely(!force_pt_level))
3500                 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3501         r = __direct_map(vcpu, write, map_writable, level, gfn, pfn, prefault);
3502         spin_unlock(&vcpu->kvm->mmu_lock);
3503
3504         return r;
3505
3506 out_unlock:
3507         spin_unlock(&vcpu->kvm->mmu_lock);
3508         kvm_release_pfn_clean(pfn);
3509         return 0;
3510 }
3511
3512 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
3513                                    struct kvm_mmu *context)
3514 {
3515         context->page_fault = nonpaging_page_fault;
3516         context->gva_to_gpa = nonpaging_gva_to_gpa;
3517         context->sync_page = nonpaging_sync_page;
3518         context->invlpg = nonpaging_invlpg;
3519         context->update_pte = nonpaging_update_pte;
3520         context->root_level = 0;
3521         context->shadow_root_level = PT32E_ROOT_LEVEL;
3522         context->root_hpa = INVALID_PAGE;
3523         context->direct_map = true;
3524         context->nx = false;
3525 }
3526
3527 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu)
3528 {
3529         mmu_free_roots(vcpu);
3530 }
3531
3532 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
3533 {
3534         return kvm_read_cr3(vcpu);
3535 }
3536
3537 static void inject_page_fault(struct kvm_vcpu *vcpu,
3538                               struct x86_exception *fault)
3539 {
3540         vcpu->arch.mmu.inject_page_fault(vcpu, fault);
3541 }
3542
3543 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
3544                            unsigned access, int *nr_present)
3545 {
3546         if (unlikely(is_mmio_spte(*sptep))) {
3547                 if (gfn != get_mmio_spte_gfn(*sptep)) {
3548                         mmu_spte_clear_no_track(sptep);
3549                         return true;
3550                 }
3551
3552                 (*nr_present)++;
3553                 mark_mmio_spte(vcpu, sptep, gfn, access);
3554                 return true;
3555         }
3556
3557         return false;
3558 }
3559
3560 static inline bool is_last_gpte(struct kvm_mmu *mmu, unsigned level, unsigned gpte)
3561 {
3562         unsigned index;
3563
3564         index = level - 1;
3565         index |= (gpte & PT_PAGE_SIZE_MASK) >> (PT_PAGE_SIZE_SHIFT - 2);
3566         return mmu->last_pte_bitmap & (1 << index);
3567 }
3568
3569 #define PTTYPE_EPT 18 /* arbitrary */
3570 #define PTTYPE PTTYPE_EPT
3571 #include "paging_tmpl.h"
3572 #undef PTTYPE
3573
3574 #define PTTYPE 64
3575 #include "paging_tmpl.h"
3576 #undef PTTYPE
3577
3578 #define PTTYPE 32
3579 #include "paging_tmpl.h"
3580 #undef PTTYPE
3581
3582 static void
3583 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3584                         struct rsvd_bits_validate *rsvd_check,
3585                         int maxphyaddr, int level, bool nx, bool gbpages,
3586                         bool pse, bool amd)
3587 {
3588         u64 exb_bit_rsvd = 0;
3589         u64 gbpages_bit_rsvd = 0;
3590         u64 nonleaf_bit8_rsvd = 0;
3591
3592         rsvd_check->bad_mt_xwr = 0;
3593
3594         if (!nx)
3595                 exb_bit_rsvd = rsvd_bits(63, 63);
3596         if (!gbpages)
3597                 gbpages_bit_rsvd = rsvd_bits(7, 7);
3598
3599         /*
3600          * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
3601          * leaf entries) on AMD CPUs only.
3602          */
3603         if (amd)
3604                 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
3605
3606         switch (level) {
3607         case PT32_ROOT_LEVEL:
3608                 /* no rsvd bits for 2 level 4K page table entries */
3609                 rsvd_check->rsvd_bits_mask[0][1] = 0;
3610                 rsvd_check->rsvd_bits_mask[0][0] = 0;
3611                 rsvd_check->rsvd_bits_mask[1][0] =
3612                         rsvd_check->rsvd_bits_mask[0][0];
3613
3614                 if (!pse) {
3615                         rsvd_check->rsvd_bits_mask[1][1] = 0;
3616                         break;
3617                 }
3618
3619                 if (is_cpuid_PSE36())
3620                         /* 36bits PSE 4MB page */
3621                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
3622                 else
3623                         /* 32 bits PSE 4MB page */
3624                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
3625                 break;
3626         case PT32E_ROOT_LEVEL:
3627                 rsvd_check->rsvd_bits_mask[0][2] =
3628                         rsvd_bits(maxphyaddr, 63) |
3629                         rsvd_bits(5, 8) | rsvd_bits(1, 2);      /* PDPTE */
3630                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3631                         rsvd_bits(maxphyaddr, 62);      /* PDE */
3632                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3633                         rsvd_bits(maxphyaddr, 62);      /* PTE */
3634                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3635                         rsvd_bits(maxphyaddr, 62) |
3636                         rsvd_bits(13, 20);              /* large page */
3637                 rsvd_check->rsvd_bits_mask[1][0] =
3638                         rsvd_check->rsvd_bits_mask[0][0];
3639                 break;
3640         case PT64_ROOT_LEVEL:
3641                 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
3642                         nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
3643                         rsvd_bits(maxphyaddr, 51);
3644                 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
3645                         nonleaf_bit8_rsvd | gbpages_bit_rsvd |
3646                         rsvd_bits(maxphyaddr, 51);
3647                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3648                         rsvd_bits(maxphyaddr, 51);
3649                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3650                         rsvd_bits(maxphyaddr, 51);
3651                 rsvd_check->rsvd_bits_mask[1][3] =
3652                         rsvd_check->rsvd_bits_mask[0][3];
3653                 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
3654                         gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
3655                         rsvd_bits(13, 29);
3656                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3657                         rsvd_bits(maxphyaddr, 51) |
3658                         rsvd_bits(13, 20);              /* large page */
3659                 rsvd_check->rsvd_bits_mask[1][0] =
3660                         rsvd_check->rsvd_bits_mask[0][0];
3661                 break;
3662         }
3663 }
3664
3665 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3666                                   struct kvm_mmu *context)
3667 {
3668         __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
3669                                 cpuid_maxphyaddr(vcpu), context->root_level,
3670                                 context->nx, guest_cpuid_has_gbpages(vcpu),
3671                                 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
3672 }
3673
3674 static void
3675 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
3676                             int maxphyaddr, bool execonly)
3677 {
3678         u64 bad_mt_xwr;
3679
3680         rsvd_check->rsvd_bits_mask[0][3] =
3681                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
3682         rsvd_check->rsvd_bits_mask[0][2] =
3683                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
3684         rsvd_check->rsvd_bits_mask[0][1] =
3685                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
3686         rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
3687
3688         /* large page */
3689         rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
3690         rsvd_check->rsvd_bits_mask[1][2] =
3691                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
3692         rsvd_check->rsvd_bits_mask[1][1] =
3693                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
3694         rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
3695
3696         bad_mt_xwr = 0xFFull << (2 * 8);        /* bits 3..5 must not be 2 */
3697         bad_mt_xwr |= 0xFFull << (3 * 8);       /* bits 3..5 must not be 3 */
3698         bad_mt_xwr |= 0xFFull << (7 * 8);       /* bits 3..5 must not be 7 */
3699         bad_mt_xwr |= REPEAT_BYTE(1ull << 2);   /* bits 0..2 must not be 010 */
3700         bad_mt_xwr |= REPEAT_BYTE(1ull << 6);   /* bits 0..2 must not be 110 */
3701         if (!execonly) {
3702                 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
3703                 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
3704         }
3705         rsvd_check->bad_mt_xwr = bad_mt_xwr;
3706 }
3707
3708 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
3709                 struct kvm_mmu *context, bool execonly)
3710 {
3711         __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
3712                                     cpuid_maxphyaddr(vcpu), execonly);
3713 }
3714
3715 /*
3716  * the page table on host is the shadow page table for the page
3717  * table in guest or amd nested guest, its mmu features completely
3718  * follow the features in guest.
3719  */
3720 void
3721 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
3722 {
3723         /*
3724          * Passing "true" to the last argument is okay; it adds a check
3725          * on bit 8 of the SPTEs which KVM doesn't use anyway.
3726          */
3727         __reset_rsvds_bits_mask(vcpu, &context->shadow_zero_check,
3728                                 boot_cpu_data.x86_phys_bits,
3729                                 context->shadow_root_level, context->nx,
3730                                 guest_cpuid_has_gbpages(vcpu), is_pse(vcpu),
3731                                 true);
3732 }
3733 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
3734
3735 static inline bool boot_cpu_is_amd(void)
3736 {
3737         WARN_ON_ONCE(!tdp_enabled);
3738         return shadow_x_mask == 0;
3739 }
3740
3741 /*
3742  * the direct page table on host, use as much mmu features as
3743  * possible, however, kvm currently does not do execution-protection.
3744  */
3745 static void
3746 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
3747                                 struct kvm_mmu *context)
3748 {
3749         if (boot_cpu_is_amd())
3750                 __reset_rsvds_bits_mask(vcpu, &context->shadow_zero_check,
3751                                         boot_cpu_data.x86_phys_bits,
3752                                         context->shadow_root_level, false,
3753                                         cpu_has_gbpages, true, true);
3754         else
3755                 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
3756                                             boot_cpu_data.x86_phys_bits,
3757                                             false);
3758
3759 }
3760
3761 /*
3762  * as the comments in reset_shadow_zero_bits_mask() except it
3763  * is the shadow page table for intel nested guest.
3764  */
3765 static void
3766 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
3767                                 struct kvm_mmu *context, bool execonly)
3768 {
3769         __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
3770                                     boot_cpu_data.x86_phys_bits, execonly);
3771 }
3772
3773 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
3774                                       struct kvm_mmu *mmu, bool ept)
3775 {
3776         unsigned bit, byte, pfec;
3777         u8 map;
3778         bool fault, x, w, u, wf, uf, ff, smapf, cr4_smap, cr4_smep, smap = 0;
3779
3780         cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
3781         cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
3782         for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
3783                 pfec = byte << 1;
3784                 map = 0;
3785                 wf = pfec & PFERR_WRITE_MASK;
3786                 uf = pfec & PFERR_USER_MASK;
3787                 ff = pfec & PFERR_FETCH_MASK;
3788                 /*
3789                  * PFERR_RSVD_MASK bit is set in PFEC if the access is not
3790                  * subject to SMAP restrictions, and cleared otherwise. The
3791                  * bit is only meaningful if the SMAP bit is set in CR4.
3792                  */
3793                 smapf = !(pfec & PFERR_RSVD_MASK);
3794                 for (bit = 0; bit < 8; ++bit) {
3795                         x = bit & ACC_EXEC_MASK;
3796                         w = bit & ACC_WRITE_MASK;
3797                         u = bit & ACC_USER_MASK;
3798
3799                         if (!ept) {
3800                                 /* Not really needed: !nx will cause pte.nx to fault */
3801                                 x |= !mmu->nx;
3802                                 /* Allow supervisor writes if !cr0.wp */
3803                                 w |= !is_write_protection(vcpu) && !uf;
3804                                 /* Disallow supervisor fetches of user code if cr4.smep */
3805                                 x &= !(cr4_smep && u && !uf);
3806
3807                                 /*
3808                                  * SMAP:kernel-mode data accesses from user-mode
3809                                  * mappings should fault. A fault is considered
3810                                  * as a SMAP violation if all of the following
3811                                  * conditions are ture:
3812                                  *   - X86_CR4_SMAP is set in CR4
3813                                  *   - An user page is accessed
3814                                  *   - Page fault in kernel mode
3815                                  *   - if CPL = 3 or X86_EFLAGS_AC is clear
3816                                  *
3817                                  *   Here, we cover the first three conditions.
3818                                  *   The fourth is computed dynamically in
3819                                  *   permission_fault() and is in smapf.
3820                                  *
3821                                  *   Also, SMAP does not affect instruction
3822                                  *   fetches, add the !ff check here to make it
3823                                  *   clearer.
3824                                  */
3825                                 smap = cr4_smap && u && !uf && !ff;
3826                         } else
3827                                 /* Not really needed: no U/S accesses on ept  */
3828                                 u = 1;
3829
3830                         fault = (ff && !x) || (uf && !u) || (wf && !w) ||
3831                                 (smapf && smap);
3832                         map |= fault << bit;
3833                 }
3834                 mmu->permissions[byte] = map;
3835         }
3836 }
3837
3838 static void update_last_pte_bitmap(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
3839 {
3840         u8 map;
3841         unsigned level, root_level = mmu->root_level;
3842         const unsigned ps_set_index = 1 << 2;  /* bit 2 of index: ps */
3843
3844         if (root_level == PT32E_ROOT_LEVEL)
3845                 --root_level;
3846         /* PT_PAGE_TABLE_LEVEL always terminates */
3847         map = 1 | (1 << ps_set_index);
3848         for (level = PT_DIRECTORY_LEVEL; level <= root_level; ++level) {
3849                 if (level <= PT_PDPE_LEVEL
3850                     && (mmu->root_level >= PT32E_ROOT_LEVEL || is_pse(vcpu)))
3851                         map |= 1 << (ps_set_index | (level - 1));
3852         }
3853         mmu->last_pte_bitmap = map;
3854 }
3855
3856 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
3857                                          struct kvm_mmu *context,
3858                                          int level)
3859 {
3860         context->nx = is_nx(vcpu);
3861         context->root_level = level;
3862
3863         reset_rsvds_bits_mask(vcpu, context);
3864         update_permission_bitmask(vcpu, context, false);
3865         update_last_pte_bitmap(vcpu, context);
3866
3867         MMU_WARN_ON(!is_pae(vcpu));
3868         context->page_fault = paging64_page_fault;
3869         context->gva_to_gpa = paging64_gva_to_gpa;
3870         context->sync_page = paging64_sync_page;
3871         context->invlpg = paging64_invlpg;
3872         context->update_pte = paging64_update_pte;
3873         context->shadow_root_level = level;
3874         context->root_hpa = INVALID_PAGE;
3875         context->direct_map = false;
3876 }
3877
3878 static void paging64_init_context(struct kvm_vcpu *vcpu,
3879                                   struct kvm_mmu *context)
3880 {
3881         paging64_init_context_common(vcpu, context, PT64_ROOT_LEVEL);
3882 }
3883
3884 static void paging32_init_context(struct kvm_vcpu *vcpu,
3885                                   struct kvm_mmu *context)
3886 {
3887         context->nx = false;
3888         context->root_level = PT32_ROOT_LEVEL;
3889
3890         reset_rsvds_bits_mask(vcpu, context);
3891         update_permission_bitmask(vcpu, context, false);
3892         update_last_pte_bitmap(vcpu, context);
3893
3894         context->page_fault = paging32_page_fault;
3895         context->gva_to_gpa = paging32_gva_to_gpa;
3896         context->sync_page = paging32_sync_page;
3897         context->invlpg = paging32_invlpg;
3898         context->update_pte = paging32_update_pte;
3899         context->shadow_root_level = PT32E_ROOT_LEVEL;
3900         context->root_hpa = INVALID_PAGE;
3901         context->direct_map = false;
3902 }
3903
3904 static void paging32E_init_context(struct kvm_vcpu *vcpu,
3905                                    struct kvm_mmu *context)
3906 {
3907         paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
3908 }
3909
3910 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
3911 {
3912         struct kvm_mmu *context = &vcpu->arch.mmu;
3913
3914         context->base_role.word = 0;
3915         context->base_role.smm = is_smm(vcpu);
3916         context->page_fault = tdp_page_fault;
3917         context->sync_page = nonpaging_sync_page;
3918         context->invlpg = nonpaging_invlpg;
3919         context->update_pte = nonpaging_update_pte;
3920         context->shadow_root_level = kvm_x86_ops->get_tdp_level();
3921         context->root_hpa = INVALID_PAGE;
3922         context->direct_map = true;
3923         context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
3924         context->get_cr3 = get_cr3;
3925         context->get_pdptr = kvm_pdptr_read;
3926         context->inject_page_fault = kvm_inject_page_fault;
3927
3928         if (!is_paging(vcpu)) {
3929                 context->nx = false;
3930                 context->gva_to_gpa = nonpaging_gva_to_gpa;
3931                 context->root_level = 0;
3932         } else if (is_long_mode(vcpu)) {
3933                 context->nx = is_nx(vcpu);
3934                 context->root_level = PT64_ROOT_LEVEL;
3935                 reset_rsvds_bits_mask(vcpu, context);
3936                 context->gva_to_gpa = paging64_gva_to_gpa;
3937         } else if (is_pae(vcpu)) {
3938                 context->nx = is_nx(vcpu);
3939                 context->root_level = PT32E_ROOT_LEVEL;
3940                 reset_rsvds_bits_mask(vcpu, context);
3941                 context->gva_to_gpa = paging64_gva_to_gpa;
3942         } else {
3943                 context->nx = false;
3944                 context->root_level = PT32_ROOT_LEVEL;
3945                 reset_rsvds_bits_mask(vcpu, context);
3946                 context->gva_to_gpa = paging32_gva_to_gpa;
3947         }
3948
3949         update_permission_bitmask(vcpu, context, false);
3950         update_last_pte_bitmap(vcpu, context);
3951         reset_tdp_shadow_zero_bits_mask(vcpu, context);
3952 }
3953
3954 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
3955 {
3956         bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
3957         bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
3958         struct kvm_mmu *context = &vcpu->arch.mmu;
3959
3960         MMU_WARN_ON(VALID_PAGE(context->root_hpa));
3961
3962         if (!is_paging(vcpu))
3963                 nonpaging_init_context(vcpu, context);
3964         else if (is_long_mode(vcpu))
3965                 paging64_init_context(vcpu, context);
3966         else if (is_pae(vcpu))
3967                 paging32E_init_context(vcpu, context);
3968         else
3969                 paging32_init_context(vcpu, context);
3970
3971         context->base_role.nxe = is_nx(vcpu);
3972         context->base_role.cr4_pae = !!is_pae(vcpu);
3973         context->base_role.cr0_wp  = is_write_protection(vcpu);
3974         context->base_role.smep_andnot_wp
3975                 = smep && !is_write_protection(vcpu);
3976         context->base_role.smap_andnot_wp
3977                 = smap && !is_write_protection(vcpu);
3978         context->base_role.smm = is_smm(vcpu);
3979         reset_shadow_zero_bits_mask(vcpu, context);
3980 }
3981 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
3982
3983 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly)
3984 {
3985         struct kvm_mmu *context = &vcpu->arch.mmu;
3986
3987         MMU_WARN_ON(VALID_PAGE(context->root_hpa));
3988
3989         context->shadow_root_level = kvm_x86_ops->get_tdp_level();
3990
3991         context->nx = true;
3992         context->page_fault = ept_page_fault;
3993         context->gva_to_gpa = ept_gva_to_gpa;
3994         context->sync_page = ept_sync_page;
3995         context->invlpg = ept_invlpg;
3996         context->update_pte = ept_update_pte;
3997         context->root_level = context->shadow_root_level;
3998         context->root_hpa = INVALID_PAGE;
3999         context->direct_map = false;
4000
4001         update_permission_bitmask(vcpu, context, true);
4002         reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4003         reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4004 }
4005 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4006
4007 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4008 {
4009         struct kvm_mmu *context = &vcpu->arch.mmu;
4010
4011         kvm_init_shadow_mmu(vcpu);
4012         context->set_cr3           = kvm_x86_ops->set_cr3;
4013         context->get_cr3           = get_cr3;
4014         context->get_pdptr         = kvm_pdptr_read;
4015         context->inject_page_fault = kvm_inject_page_fault;
4016 }
4017
4018 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4019 {
4020         struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4021
4022         g_context->get_cr3           = get_cr3;
4023         g_context->get_pdptr         = kvm_pdptr_read;
4024         g_context->inject_page_fault = kvm_inject_page_fault;
4025
4026         /*
4027          * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
4028          * L1's nested page tables (e.g. EPT12). The nested translation
4029          * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4030          * L2's page tables as the first level of translation and L1's
4031          * nested page tables as the second level of translation. Basically
4032          * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4033          */
4034         if (!is_paging(vcpu)) {
4035                 g_context->nx = false;
4036                 g_context->root_level = 0;
4037                 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4038         } else if (is_long_mode(vcpu)) {
4039                 g_context->nx = is_nx(vcpu);
4040                 g_context->root_level = PT64_ROOT_LEVEL;
4041                 reset_rsvds_bits_mask(vcpu, g_context);
4042                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4043         } else if (is_pae(vcpu)) {
4044                 g_context->nx = is_nx(vcpu);
4045                 g_context->root_level = PT32E_ROOT_LEVEL;
4046                 reset_rsvds_bits_mask(vcpu, g_context);
4047                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4048         } else {
4049                 g_context->nx = false;
4050                 g_context->root_level = PT32_ROOT_LEVEL;
4051                 reset_rsvds_bits_mask(vcpu, g_context);
4052                 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4053         }
4054
4055         update_permission_bitmask(vcpu, g_context, false);
4056         update_last_pte_bitmap(vcpu, g_context);
4057 }
4058
4059 static void init_kvm_mmu(struct kvm_vcpu *vcpu)
4060 {
4061         if (mmu_is_nested(vcpu))
4062                 init_kvm_nested_mmu(vcpu);
4063         else if (tdp_enabled)
4064                 init_kvm_tdp_mmu(vcpu);
4065         else
4066                 init_kvm_softmmu(vcpu);
4067 }
4068
4069 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
4070 {
4071         kvm_mmu_unload(vcpu);
4072         init_kvm_mmu(vcpu);
4073 }
4074 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
4075
4076 int kvm_mmu_load(struct kvm_vcpu *vcpu)
4077 {
4078         int r;
4079
4080         r = mmu_topup_memory_caches(vcpu);
4081         if (r)
4082                 goto out;
4083         r = mmu_alloc_roots(vcpu);
4084         kvm_mmu_sync_roots(vcpu);
4085         if (r)
4086                 goto out;
4087         /* set_cr3() should ensure TLB has been flushed */
4088         vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
4089 out:
4090         return r;
4091 }
4092 EXPORT_SYMBOL_GPL(kvm_mmu_load);
4093
4094 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4095 {
4096         mmu_free_roots(vcpu);
4097         WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4098 }
4099 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
4100
4101 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
4102                                   struct kvm_mmu_page *sp, u64 *spte,
4103                                   const void *new)
4104 {
4105         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
4106                 ++vcpu->kvm->stat.mmu_pde_zapped;
4107                 return;
4108         }
4109
4110         ++vcpu->kvm->stat.mmu_pte_updated;
4111         vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
4112 }
4113
4114 static bool need_remote_flush(u64 old, u64 new)
4115 {
4116         if (!is_shadow_present_pte(old))
4117                 return false;
4118         if (!is_shadow_present_pte(new))
4119                 return true;
4120         if ((old ^ new) & PT64_BASE_ADDR_MASK)
4121                 return true;
4122         old ^= shadow_nx_mask;
4123         new ^= shadow_nx_mask;
4124         return (old & ~new & PT64_PERM_MASK) != 0;
4125 }
4126
4127 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, bool zap_page,
4128                                     bool remote_flush, bool local_flush)
4129 {
4130         if (zap_page)
4131                 return;
4132
4133         if (remote_flush)
4134                 kvm_flush_remote_tlbs(vcpu->kvm);
4135         else if (local_flush)
4136                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4137 }
4138
4139 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4140                                     const u8 *new, int *bytes)
4141 {
4142         u64 gentry;
4143         int r;
4144
4145         /*
4146          * Assume that the pte write on a page table of the same type
4147          * as the current vcpu paging mode since we update the sptes only
4148          * when they have the same mode.
4149          */
4150         if (is_pae(vcpu) && *bytes == 4) {
4151                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
4152                 *gpa &= ~(gpa_t)7;
4153                 *bytes = 8;
4154                 r = kvm_vcpu_read_guest(vcpu, *gpa, &gentry, 8);
4155                 if (r)
4156                         gentry = 0;
4157                 new = (const u8 *)&gentry;
4158         }
4159
4160         switch (*bytes) {
4161         case 4:
4162                 gentry = *(const u32 *)new;
4163                 break;
4164         case 8:
4165                 gentry = *(const u64 *)new;
4166                 break;
4167         default:
4168                 gentry = 0;
4169                 break;
4170         }
4171
4172         return gentry;
4173 }
4174
4175 /*
4176  * If we're seeing too many writes to a page, it may no longer be a page table,
4177  * or we may be forking, in which case it is better to unmap the page.
4178  */
4179 static bool detect_write_flooding(struct kvm_mmu_page *sp)
4180 {
4181         /*
4182          * Skip write-flooding detected for the sp whose level is 1, because
4183          * it can become unsync, then the guest page is not write-protected.
4184          */
4185         if (sp->role.level == PT_PAGE_TABLE_LEVEL)
4186                 return false;
4187
4188         return ++sp->write_flooding_count >= 3;
4189 }
4190
4191 /*
4192  * Misaligned accesses are too much trouble to fix up; also, they usually
4193  * indicate a page is not used as a page table.
4194  */
4195 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4196                                     int bytes)
4197 {
4198         unsigned offset, pte_size, misaligned;
4199
4200         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4201                  gpa, bytes, sp->role.word);
4202
4203         offset = offset_in_page(gpa);
4204         pte_size = sp->role.cr4_pae ? 8 : 4;
4205
4206         /*
4207          * Sometimes, the OS only writes the last one bytes to update status
4208          * bits, for example, in linux, andb instruction is used in clear_bit().
4209          */
4210         if (!(offset & (pte_size - 1)) && bytes == 1)
4211                 return false;
4212
4213         misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4214         misaligned |= bytes < 4;
4215
4216         return misaligned;
4217 }
4218
4219 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
4220 {
4221         unsigned page_offset, quadrant;
4222         u64 *spte;
4223         int level;
4224
4225         page_offset = offset_in_page(gpa);
4226         level = sp->role.level;
4227         *nspte = 1;
4228         if (!sp->role.cr4_pae) {
4229                 page_offset <<= 1;      /* 32->64 */
4230                 /*
4231                  * A 32-bit pde maps 4MB while the shadow pdes map
4232                  * only 2MB.  So we need to double the offset again
4233                  * and zap two pdes instead of one.
4234                  */
4235                 if (level == PT32_ROOT_LEVEL) {
4236                         page_offset &= ~7; /* kill rounding error */
4237                         page_offset <<= 1;
4238                         *nspte = 2;
4239                 }
4240                 quadrant = page_offset >> PAGE_SHIFT;
4241                 page_offset &= ~PAGE_MASK;
4242                 if (quadrant != sp->role.quadrant)
4243                         return NULL;
4244         }
4245
4246         spte = &sp->spt[page_offset / sizeof(*spte)];
4247         return spte;
4248 }
4249
4250 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
4251                        const u8 *new, int bytes)
4252 {
4253         gfn_t gfn = gpa >> PAGE_SHIFT;
4254         struct kvm_mmu_page *sp;
4255         LIST_HEAD(invalid_list);
4256         u64 entry, gentry, *spte;
4257         int npte;
4258         bool remote_flush, local_flush, zap_page;
4259         union kvm_mmu_page_role mask = { };
4260
4261         mask.cr0_wp = 1;
4262         mask.cr4_pae = 1;
4263         mask.nxe = 1;
4264         mask.smep_andnot_wp = 1;
4265         mask.smap_andnot_wp = 1;
4266         mask.smm = 1;
4267
4268         /*
4269          * If we don't have indirect shadow pages, it means no page is
4270          * write-protected, so we can exit simply.
4271          */
4272         if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
4273                 return;
4274
4275         zap_page = remote_flush = local_flush = false;
4276
4277         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
4278
4279         gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes);
4280
4281         /*
4282          * No need to care whether allocation memory is successful
4283          * or not since pte prefetch is skiped if it does not have
4284          * enough objects in the cache.
4285          */
4286         mmu_topup_memory_caches(vcpu);
4287
4288         spin_lock(&vcpu->kvm->mmu_lock);
4289         ++vcpu->kvm->stat.mmu_pte_write;
4290         kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
4291
4292         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
4293                 if (detect_write_misaligned(sp, gpa, bytes) ||
4294                       detect_write_flooding(sp)) {
4295                         zap_page |= !!kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
4296                                                      &invalid_list);
4297                         ++vcpu->kvm->stat.mmu_flooded;
4298                         continue;
4299                 }
4300
4301                 spte = get_written_sptes(sp, gpa, &npte);
4302                 if (!spte)
4303                         continue;
4304
4305                 local_flush = true;
4306                 while (npte--) {
4307                         entry = *spte;
4308                         mmu_page_zap_pte(vcpu->kvm, sp, spte);
4309                         if (gentry &&
4310                               !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
4311                               & mask.word) && rmap_can_add(vcpu))
4312                                 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
4313                         if (need_remote_flush(entry, *spte))
4314                                 remote_flush = true;
4315                         ++spte;
4316                 }
4317         }
4318         mmu_pte_write_flush_tlb(vcpu, zap_page, remote_flush, local_flush);
4319         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
4320         kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
4321         spin_unlock(&vcpu->kvm->mmu_lock);
4322 }
4323
4324 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
4325 {
4326         gpa_t gpa;
4327         int r;
4328
4329         if (vcpu->arch.mmu.direct_map)
4330                 return 0;
4331
4332         gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
4333
4334         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
4335
4336         return r;
4337 }
4338 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
4339
4340 static void make_mmu_pages_available(struct kvm_vcpu *vcpu)
4341 {
4342         LIST_HEAD(invalid_list);
4343
4344         if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
4345                 return;
4346
4347         while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
4348                 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
4349                         break;
4350
4351                 ++vcpu->kvm->stat.mmu_recycled;
4352         }
4353         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
4354 }
4355
4356 static bool is_mmio_page_fault(struct kvm_vcpu *vcpu, gva_t addr)
4357 {
4358         if (vcpu->arch.mmu.direct_map || mmu_is_nested(vcpu))
4359                 return vcpu_match_mmio_gpa(vcpu, addr);
4360
4361         return vcpu_match_mmio_gva(vcpu, addr);
4362 }
4363
4364 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code,
4365                        void *insn, int insn_len)
4366 {
4367         int r, emulation_type = EMULTYPE_RETRY;
4368         enum emulation_result er;
4369
4370         r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
4371         if (r < 0)
4372                 goto out;
4373
4374         if (!r) {
4375                 r = 1;
4376                 goto out;
4377         }
4378
4379         if (is_mmio_page_fault(vcpu, cr2))
4380                 emulation_type = 0;
4381
4382         er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
4383
4384         switch (er) {
4385         case EMULATE_DONE:
4386                 return 1;
4387         case EMULATE_USER_EXIT:
4388                 ++vcpu->stat.mmio_exits;
4389                 /* fall through */
4390         case EMULATE_FAIL:
4391                 return 0;
4392         default:
4393                 BUG();
4394         }
4395 out:
4396         return r;
4397 }
4398 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
4399
4400 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
4401 {
4402         vcpu->arch.mmu.invlpg(vcpu, gva);
4403         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
4404         ++vcpu->stat.invlpg;
4405 }
4406 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
4407
4408 void kvm_enable_tdp(void)
4409 {
4410         tdp_enabled = true;
4411 }
4412 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
4413
4414 void kvm_disable_tdp(void)
4415 {
4416         tdp_enabled = false;
4417 }
4418 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
4419
4420 static void free_mmu_pages(struct kvm_vcpu *vcpu)
4421 {
4422         free_page((unsigned long)vcpu->arch.mmu.pae_root);
4423         if (vcpu->arch.mmu.lm_root != NULL)
4424                 free_page((unsigned long)vcpu->arch.mmu.lm_root);
4425 }
4426
4427 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
4428 {
4429         struct page *page;
4430         int i;
4431
4432         /*
4433          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
4434          * Therefore we need to allocate shadow page tables in the first
4435          * 4GB of memory, which happens to fit the DMA32 zone.
4436          */
4437         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
4438         if (!page)
4439                 return -ENOMEM;
4440
4441         vcpu->arch.mmu.pae_root = page_address(page);
4442         for (i = 0; i < 4; ++i)
4443                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
4444
4445         return 0;
4446 }
4447
4448 int kvm_mmu_create(struct kvm_vcpu *vcpu)
4449 {
4450         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
4451         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
4452         vcpu->arch.mmu.translate_gpa = translate_gpa;
4453         vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
4454
4455         return alloc_mmu_pages(vcpu);
4456 }
4457
4458 void kvm_mmu_setup(struct kvm_vcpu *vcpu)
4459 {
4460         MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4461
4462         init_kvm_mmu(vcpu);
4463 }
4464
4465 /* The return value indicates if tlb flush on all vcpus is needed. */
4466 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
4467
4468 /* The caller should hold mmu-lock before calling this function. */
4469 static bool
4470 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
4471                         slot_level_handler fn, int start_level, int end_level,
4472                         gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
4473 {
4474         struct slot_rmap_walk_iterator iterator;
4475         bool flush = false;
4476
4477         for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
4478                         end_gfn, &iterator) {
4479                 if (iterator.rmap)
4480                         flush |= fn(kvm, iterator.rmap);
4481
4482                 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
4483                         if (flush && lock_flush_tlb) {
4484                                 kvm_flush_remote_tlbs(kvm);
4485                                 flush = false;
4486                         }
4487                         cond_resched_lock(&kvm->mmu_lock);
4488                 }
4489         }
4490
4491         if (flush && lock_flush_tlb) {
4492                 kvm_flush_remote_tlbs(kvm);
4493                 flush = false;
4494         }
4495
4496         return flush;
4497 }
4498
4499 static bool
4500 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4501                   slot_level_handler fn, int start_level, int end_level,
4502                   bool lock_flush_tlb)
4503 {
4504         return slot_handle_level_range(kvm, memslot, fn, start_level,
4505                         end_level, memslot->base_gfn,
4506                         memslot->base_gfn + memslot->npages - 1,
4507                         lock_flush_tlb);
4508 }
4509
4510 static bool
4511 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4512                       slot_level_handler fn, bool lock_flush_tlb)
4513 {
4514         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
4515                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
4516 }
4517
4518 static bool
4519 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
4520                         slot_level_handler fn, bool lock_flush_tlb)
4521 {
4522         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
4523                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
4524 }
4525
4526 static bool
4527 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
4528                  slot_level_handler fn, bool lock_flush_tlb)
4529 {
4530         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
4531                                  PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
4532 }
4533
4534 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
4535 {
4536         struct kvm_memslots *slots;
4537         struct kvm_memory_slot *memslot;
4538         int i;
4539
4540         spin_lock(&kvm->mmu_lock);
4541         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
4542                 slots = __kvm_memslots(kvm, i);
4543                 kvm_for_each_memslot(memslot, slots) {
4544                         gfn_t start, end;
4545
4546                         start = max(gfn_start, memslot->base_gfn);
4547                         end = min(gfn_end, memslot->base_gfn + memslot->npages);
4548                         if (start >= end)
4549                                 continue;
4550
4551                         slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
4552                                                 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
4553                                                 start, end - 1, true);
4554                 }
4555         }
4556
4557         spin_unlock(&kvm->mmu_lock);
4558 }
4559
4560 static bool slot_rmap_write_protect(struct kvm *kvm,
4561                                     struct kvm_rmap_head *rmap_head)
4562 {
4563         return __rmap_write_protect(kvm, rmap_head, false);
4564 }
4565
4566 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
4567                                       struct kvm_memory_slot *memslot)
4568 {
4569         bool flush;
4570
4571         spin_lock(&kvm->mmu_lock);
4572         flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
4573                                       false);
4574         spin_unlock(&kvm->mmu_lock);
4575
4576         /*
4577          * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
4578          * which do tlb flush out of mmu-lock should be serialized by
4579          * kvm->slots_lock otherwise tlb flush would be missed.
4580          */
4581         lockdep_assert_held(&kvm->slots_lock);
4582
4583         /*
4584          * We can flush all the TLBs out of the mmu lock without TLB
4585          * corruption since we just change the spte from writable to
4586          * readonly so that we only need to care the case of changing
4587          * spte from present to present (changing the spte from present
4588          * to nonpresent will flush all the TLBs immediately), in other
4589          * words, the only case we care is mmu_spte_update() where we
4590          * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
4591          * instead of PT_WRITABLE_MASK, that means it does not depend
4592          * on PT_WRITABLE_MASK anymore.
4593          */
4594         if (flush)
4595                 kvm_flush_remote_tlbs(kvm);
4596 }
4597
4598 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
4599                                          struct kvm_rmap_head *rmap_head)
4600 {
4601         u64 *sptep;
4602         struct rmap_iterator iter;
4603         int need_tlb_flush = 0;
4604         pfn_t pfn;
4605         struct kvm_mmu_page *sp;
4606
4607 restart:
4608         for_each_rmap_spte(rmap_head, &iter, sptep) {
4609                 sp = page_header(__pa(sptep));
4610                 pfn = spte_to_pfn(*sptep);
4611
4612                 /*
4613                  * We cannot do huge page mapping for indirect shadow pages,
4614                  * which are found on the last rmap (level = 1) when not using
4615                  * tdp; such shadow pages are synced with the page table in
4616                  * the guest, and the guest page table is using 4K page size
4617                  * mapping if the indirect sp has level = 1.
4618                  */
4619                 if (sp->role.direct &&
4620                         !kvm_is_reserved_pfn(pfn) &&
4621                         PageTransCompound(pfn_to_page(pfn))) {
4622                         drop_spte(kvm, sptep);
4623                         need_tlb_flush = 1;
4624                         goto restart;
4625                 }
4626         }
4627
4628         return need_tlb_flush;
4629 }
4630
4631 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
4632                                    const struct kvm_memory_slot *memslot)
4633 {
4634         /* FIXME: const-ify all uses of struct kvm_memory_slot.  */
4635         spin_lock(&kvm->mmu_lock);
4636         slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
4637                          kvm_mmu_zap_collapsible_spte, true);
4638         spin_unlock(&kvm->mmu_lock);
4639 }
4640
4641 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
4642                                    struct kvm_memory_slot *memslot)
4643 {
4644         bool flush;
4645
4646         spin_lock(&kvm->mmu_lock);
4647         flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
4648         spin_unlock(&kvm->mmu_lock);
4649
4650         lockdep_assert_held(&kvm->slots_lock);
4651
4652         /*
4653          * It's also safe to flush TLBs out of mmu lock here as currently this
4654          * function is only used for dirty logging, in which case flushing TLB
4655          * out of mmu lock also guarantees no dirty pages will be lost in
4656          * dirty_bitmap.
4657          */
4658         if (flush)
4659                 kvm_flush_remote_tlbs(kvm);
4660 }
4661 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
4662
4663 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
4664                                         struct kvm_memory_slot *memslot)
4665 {
4666         bool flush;
4667
4668         spin_lock(&kvm->mmu_lock);
4669         flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
4670                                         false);
4671         spin_unlock(&kvm->mmu_lock);
4672
4673         /* see kvm_mmu_slot_remove_write_access */
4674         lockdep_assert_held(&kvm->slots_lock);
4675
4676         if (flush)
4677                 kvm_flush_remote_tlbs(kvm);
4678 }
4679 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
4680
4681 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
4682                             struct kvm_memory_slot *memslot)
4683 {
4684         bool flush;
4685
4686         spin_lock(&kvm->mmu_lock);
4687         flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
4688         spin_unlock(&kvm->mmu_lock);
4689
4690         lockdep_assert_held(&kvm->slots_lock);
4691
4692         /* see kvm_mmu_slot_leaf_clear_dirty */
4693         if (flush)
4694                 kvm_flush_remote_tlbs(kvm);
4695 }
4696 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
4697
4698 #define BATCH_ZAP_PAGES 10
4699 static void kvm_zap_obsolete_pages(struct kvm *kvm)
4700 {
4701         struct kvm_mmu_page *sp, *node;
4702         int batch = 0;
4703
4704 restart:
4705         list_for_each_entry_safe_reverse(sp, node,
4706               &kvm->arch.active_mmu_pages, link) {
4707                 int ret;
4708
4709                 /*
4710                  * No obsolete page exists before new created page since
4711                  * active_mmu_pages is the FIFO list.
4712                  */
4713                 if (!is_obsolete_sp(kvm, sp))
4714                         break;
4715
4716                 /*
4717                  * Since we are reversely walking the list and the invalid
4718                  * list will be moved to the head, skip the invalid page
4719                  * can help us to avoid the infinity list walking.
4720                  */
4721                 if (sp->role.invalid)
4722                         continue;
4723
4724                 /*
4725                  * Need not flush tlb since we only zap the sp with invalid
4726                  * generation number.
4727                  */
4728                 if (batch >= BATCH_ZAP_PAGES &&
4729                       cond_resched_lock(&kvm->mmu_lock)) {
4730                         batch = 0;
4731                         goto restart;
4732                 }
4733
4734                 ret = kvm_mmu_prepare_zap_page(kvm, sp,
4735                                 &kvm->arch.zapped_obsolete_pages);
4736                 batch += ret;
4737
4738                 if (ret)
4739                         goto restart;
4740         }
4741
4742         /*
4743          * Should flush tlb before free page tables since lockless-walking
4744          * may use the pages.
4745          */
4746         kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
4747 }
4748
4749 /*
4750  * Fast invalidate all shadow pages and use lock-break technique
4751  * to zap obsolete pages.
4752  *
4753  * It's required when memslot is being deleted or VM is being
4754  * destroyed, in these cases, we should ensure that KVM MMU does
4755  * not use any resource of the being-deleted slot or all slots
4756  * after calling the function.
4757  */
4758 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
4759 {
4760         spin_lock(&kvm->mmu_lock);
4761         trace_kvm_mmu_invalidate_zap_all_pages(kvm);
4762         kvm->arch.mmu_valid_gen++;
4763
4764         /*
4765          * Notify all vcpus to reload its shadow page table
4766          * and flush TLB. Then all vcpus will switch to new
4767          * shadow page table with the new mmu_valid_gen.
4768          *
4769          * Note: we should do this under the protection of
4770          * mmu-lock, otherwise, vcpu would purge shadow page
4771          * but miss tlb flush.
4772          */
4773         kvm_reload_remote_mmus(kvm);
4774
4775         kvm_zap_obsolete_pages(kvm);
4776         spin_unlock(&kvm->mmu_lock);
4777 }
4778
4779 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
4780 {
4781         return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
4782 }
4783
4784 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, struct kvm_memslots *slots)
4785 {
4786         /*
4787          * The very rare case: if the generation-number is round,
4788          * zap all shadow pages.
4789          */
4790         if (unlikely((slots->generation & MMIO_GEN_MASK) == 0)) {
4791                 printk_ratelimited(KERN_DEBUG "kvm: zapping shadow pages for mmio generation wraparound\n");
4792                 kvm_mmu_invalidate_zap_all_pages(kvm);
4793         }
4794 }
4795
4796 static unsigned long
4797 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
4798 {
4799         struct kvm *kvm;
4800         int nr_to_scan = sc->nr_to_scan;
4801         unsigned long freed = 0;
4802
4803         spin_lock(&kvm_lock);
4804
4805         list_for_each_entry(kvm, &vm_list, vm_list) {
4806                 int idx;
4807                 LIST_HEAD(invalid_list);
4808
4809                 /*
4810                  * Never scan more than sc->nr_to_scan VM instances.
4811                  * Will not hit this condition practically since we do not try
4812                  * to shrink more than one VM and it is very unlikely to see
4813                  * !n_used_mmu_pages so many times.
4814                  */
4815                 if (!nr_to_scan--)
4816                         break;
4817                 /*
4818                  * n_used_mmu_pages is accessed without holding kvm->mmu_lock
4819                  * here. We may skip a VM instance errorneosly, but we do not
4820                  * want to shrink a VM that only started to populate its MMU
4821                  * anyway.
4822                  */
4823                 if (!kvm->arch.n_used_mmu_pages &&
4824                       !kvm_has_zapped_obsolete_pages(kvm))
4825                         continue;
4826
4827                 idx = srcu_read_lock(&kvm->srcu);
4828                 spin_lock(&kvm->mmu_lock);
4829
4830                 if (kvm_has_zapped_obsolete_pages(kvm)) {
4831                         kvm_mmu_commit_zap_page(kvm,
4832                               &kvm->arch.zapped_obsolete_pages);
4833                         goto unlock;
4834                 }
4835
4836                 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
4837                         freed++;
4838                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
4839
4840 unlock:
4841                 spin_unlock(&kvm->mmu_lock);
4842                 srcu_read_unlock(&kvm->srcu, idx);
4843
4844                 /*
4845                  * unfair on small ones
4846                  * per-vm shrinkers cry out
4847                  * sadness comes quickly
4848                  */
4849                 list_move_tail(&kvm->vm_list, &vm_list);
4850                 break;
4851         }
4852
4853         spin_unlock(&kvm_lock);
4854         return freed;
4855 }
4856
4857 static unsigned long
4858 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
4859 {
4860         return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
4861 }
4862
4863 static struct shrinker mmu_shrinker = {
4864         .count_objects = mmu_shrink_count,
4865         .scan_objects = mmu_shrink_scan,
4866         .seeks = DEFAULT_SEEKS * 10,
4867 };
4868
4869 static void mmu_destroy_caches(void)
4870 {
4871         if (pte_list_desc_cache)
4872                 kmem_cache_destroy(pte_list_desc_cache);
4873         if (mmu_page_header_cache)
4874                 kmem_cache_destroy(mmu_page_header_cache);
4875 }
4876
4877 int kvm_mmu_module_init(void)
4878 {
4879         pte_list_desc_cache = kmem_cache_create("pte_list_desc",
4880                                             sizeof(struct pte_list_desc),
4881                                             0, 0, NULL);
4882         if (!pte_list_desc_cache)
4883                 goto nomem;
4884
4885         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
4886                                                   sizeof(struct kvm_mmu_page),
4887                                                   0, 0, NULL);
4888         if (!mmu_page_header_cache)
4889                 goto nomem;
4890
4891         if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
4892                 goto nomem;
4893
4894         register_shrinker(&mmu_shrinker);
4895
4896         return 0;
4897
4898 nomem:
4899         mmu_destroy_caches();
4900         return -ENOMEM;
4901 }
4902
4903 /*
4904  * Caculate mmu pages needed for kvm.
4905  */
4906 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
4907 {
4908         unsigned int nr_mmu_pages;
4909         unsigned int  nr_pages = 0;
4910         struct kvm_memslots *slots;
4911         struct kvm_memory_slot *memslot;
4912         int i;
4913
4914         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
4915                 slots = __kvm_memslots(kvm, i);
4916
4917                 kvm_for_each_memslot(memslot, slots)
4918                         nr_pages += memslot->npages;
4919         }
4920
4921         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
4922         nr_mmu_pages = max(nr_mmu_pages,
4923                            (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
4924
4925         return nr_mmu_pages;
4926 }
4927
4928 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
4929 {
4930         kvm_mmu_unload(vcpu);
4931         free_mmu_pages(vcpu);
4932         mmu_free_memory_caches(vcpu);
4933 }
4934
4935 void kvm_mmu_module_exit(void)
4936 {
4937         mmu_destroy_caches();
4938         percpu_counter_destroy(&kvm_total_used_mmu_pages);
4939         unregister_shrinker(&mmu_shrinker);
4940         mmu_audit_disable();
4941 }