cac7b2b5595f5bd465e788fe78454a29b5754308
[pandora-kernel.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
26 #include <linux/kvm_host.h>
27 #include <linux/types.h>
28 #include <linux/string.h>
29 #include <linux/mm.h>
30 #include <linux/highmem.h>
31 #include <linux/module.h>
32 #include <linux/swap.h>
33 #include <linux/hugetlb.h>
34 #include <linux/compiler.h>
35 #include <linux/srcu.h>
36 #include <linux/slab.h>
37 #include <linux/uaccess.h>
38
39 #include <asm/page.h>
40 #include <asm/cmpxchg.h>
41 #include <asm/io.h>
42 #include <asm/vmx.h>
43
44 /*
45  * When setting this variable to true it enables Two-Dimensional-Paging
46  * where the hardware walks 2 page tables:
47  * 1. the guest-virtual to guest-physical
48  * 2. while doing 1. it walks guest-physical to host-physical
49  * If the hardware supports that we don't need to do shadow paging.
50  */
51 bool tdp_enabled = false;
52
53 enum {
54         AUDIT_PRE_PAGE_FAULT,
55         AUDIT_POST_PAGE_FAULT,
56         AUDIT_PRE_PTE_WRITE,
57         AUDIT_POST_PTE_WRITE,
58         AUDIT_PRE_SYNC,
59         AUDIT_POST_SYNC
60 };
61
62 char *audit_point_name[] = {
63         "pre page fault",
64         "post page fault",
65         "pre pte write",
66         "post pte write",
67         "pre sync",
68         "post sync"
69 };
70
71 #undef MMU_DEBUG
72
73 #ifdef MMU_DEBUG
74
75 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
76 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
77
78 #else
79
80 #define pgprintk(x...) do { } while (0)
81 #define rmap_printk(x...) do { } while (0)
82
83 #endif
84
85 #ifdef MMU_DEBUG
86 static int dbg = 0;
87 module_param(dbg, bool, 0644);
88 #endif
89
90 static int oos_shadow = 1;
91 module_param(oos_shadow, bool, 0644);
92
93 #ifndef MMU_DEBUG
94 #define ASSERT(x) do { } while (0)
95 #else
96 #define ASSERT(x)                                                       \
97         if (!(x)) {                                                     \
98                 printk(KERN_WARNING "assertion failed %s:%d: %s\n",     \
99                        __FILE__, __LINE__, #x);                         \
100         }
101 #endif
102
103 #define PTE_PREFETCH_NUM                8
104
105 #define PT_FIRST_AVAIL_BITS_SHIFT 9
106 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
107
108 #define PT64_LEVEL_BITS 9
109
110 #define PT64_LEVEL_SHIFT(level) \
111                 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
112
113 #define PT64_INDEX(address, level)\
114         (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
115
116
117 #define PT32_LEVEL_BITS 10
118
119 #define PT32_LEVEL_SHIFT(level) \
120                 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
121
122 #define PT32_LVL_OFFSET_MASK(level) \
123         (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
124                                                 * PT32_LEVEL_BITS))) - 1))
125
126 #define PT32_INDEX(address, level)\
127         (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
128
129
130 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
131 #define PT64_DIR_BASE_ADDR_MASK \
132         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
133 #define PT64_LVL_ADDR_MASK(level) \
134         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
135                                                 * PT64_LEVEL_BITS))) - 1))
136 #define PT64_LVL_OFFSET_MASK(level) \
137         (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
138                                                 * PT64_LEVEL_BITS))) - 1))
139
140 #define PT32_BASE_ADDR_MASK PAGE_MASK
141 #define PT32_DIR_BASE_ADDR_MASK \
142         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
143 #define PT32_LVL_ADDR_MASK(level) \
144         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
145                                             * PT32_LEVEL_BITS))) - 1))
146
147 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK \
148                         | PT64_NX_MASK)
149
150 #define PTE_LIST_EXT 4
151
152 #define ACC_EXEC_MASK    1
153 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
154 #define ACC_USER_MASK    PT_USER_MASK
155 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
156
157 #include <trace/events/kvm.h>
158
159 #define CREATE_TRACE_POINTS
160 #include "mmutrace.h"
161
162 #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
163
164 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
165
166 struct pte_list_desc {
167         u64 *sptes[PTE_LIST_EXT];
168         struct pte_list_desc *more;
169 };
170
171 struct kvm_shadow_walk_iterator {
172         u64 addr;
173         hpa_t shadow_addr;
174         u64 *sptep;
175         int level;
176         unsigned index;
177 };
178
179 #define for_each_shadow_entry(_vcpu, _addr, _walker)    \
180         for (shadow_walk_init(&(_walker), _vcpu, _addr);        \
181              shadow_walk_okay(&(_walker));                      \
182              shadow_walk_next(&(_walker)))
183
184 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)     \
185         for (shadow_walk_init(&(_walker), _vcpu, _addr);                \
186              shadow_walk_okay(&(_walker)) &&                            \
187                 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });  \
188              __shadow_walk_next(&(_walker), spte))
189
190 static struct kmem_cache *pte_list_desc_cache;
191 static struct kmem_cache *mmu_page_header_cache;
192 static struct percpu_counter kvm_total_used_mmu_pages;
193
194 static u64 __read_mostly shadow_nx_mask;
195 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
196 static u64 __read_mostly shadow_user_mask;
197 static u64 __read_mostly shadow_accessed_mask;
198 static u64 __read_mostly shadow_dirty_mask;
199 static u64 __read_mostly shadow_mmio_mask;
200
201 static void mmu_spte_set(u64 *sptep, u64 spte);
202
203 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask)
204 {
205         shadow_mmio_mask = mmio_mask;
206 }
207 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
208
209 static void mark_mmio_spte(u64 *sptep, u64 gfn, unsigned access)
210 {
211         access &= ACC_WRITE_MASK | ACC_USER_MASK;
212
213         trace_mark_mmio_spte(sptep, gfn, access);
214         mmu_spte_set(sptep, shadow_mmio_mask | access | gfn << PAGE_SHIFT);
215 }
216
217 static bool is_mmio_spte(u64 spte)
218 {
219         return (spte & shadow_mmio_mask) == shadow_mmio_mask;
220 }
221
222 static gfn_t get_mmio_spte_gfn(u64 spte)
223 {
224         return (spte & ~shadow_mmio_mask) >> PAGE_SHIFT;
225 }
226
227 static unsigned get_mmio_spte_access(u64 spte)
228 {
229         return (spte & ~shadow_mmio_mask) & ~PAGE_MASK;
230 }
231
232 static bool set_mmio_spte(u64 *sptep, gfn_t gfn, pfn_t pfn, unsigned access)
233 {
234         if (unlikely(is_noslot_pfn(pfn))) {
235                 mark_mmio_spte(sptep, gfn, access);
236                 return true;
237         }
238
239         return false;
240 }
241
242 static inline u64 rsvd_bits(int s, int e)
243 {
244         return ((1ULL << (e - s + 1)) - 1) << s;
245 }
246
247 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
248                 u64 dirty_mask, u64 nx_mask, u64 x_mask)
249 {
250         shadow_user_mask = user_mask;
251         shadow_accessed_mask = accessed_mask;
252         shadow_dirty_mask = dirty_mask;
253         shadow_nx_mask = nx_mask;
254         shadow_x_mask = x_mask;
255 }
256 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
257
258 static int is_cpuid_PSE36(void)
259 {
260         return 1;
261 }
262
263 static int is_nx(struct kvm_vcpu *vcpu)
264 {
265         return vcpu->arch.efer & EFER_NX;
266 }
267
268 static int is_shadow_present_pte(u64 pte)
269 {
270         return pte & PT_PRESENT_MASK && !is_mmio_spte(pte);
271 }
272
273 static int is_large_pte(u64 pte)
274 {
275         return pte & PT_PAGE_SIZE_MASK;
276 }
277
278 static int is_dirty_gpte(unsigned long pte)
279 {
280         return pte & PT_DIRTY_MASK;
281 }
282
283 static int is_rmap_spte(u64 pte)
284 {
285         return is_shadow_present_pte(pte);
286 }
287
288 static int is_last_spte(u64 pte, int level)
289 {
290         if (level == PT_PAGE_TABLE_LEVEL)
291                 return 1;
292         if (is_large_pte(pte))
293                 return 1;
294         return 0;
295 }
296
297 static pfn_t spte_to_pfn(u64 pte)
298 {
299         return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
300 }
301
302 static gfn_t pse36_gfn_delta(u32 gpte)
303 {
304         int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
305
306         return (gpte & PT32_DIR_PSE36_MASK) << shift;
307 }
308
309 #ifdef CONFIG_X86_64
310 static void __set_spte(u64 *sptep, u64 spte)
311 {
312         *sptep = spte;
313 }
314
315 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
316 {
317         *sptep = spte;
318 }
319
320 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
321 {
322         return xchg(sptep, spte);
323 }
324
325 static u64 __get_spte_lockless(u64 *sptep)
326 {
327         return ACCESS_ONCE(*sptep);
328 }
329 #else
330 union split_spte {
331         struct {
332                 u32 spte_low;
333                 u32 spte_high;
334         };
335         u64 spte;
336 };
337
338 static void count_spte_clear(u64 *sptep, u64 spte)
339 {
340         struct kvm_mmu_page *sp =  page_header(__pa(sptep));
341
342         if (is_shadow_present_pte(spte))
343                 return;
344
345         /* Ensure the spte is completely set before we increase the count */
346         smp_wmb();
347         sp->clear_spte_count++;
348 }
349
350 static void __set_spte(u64 *sptep, u64 spte)
351 {
352         union split_spte *ssptep, sspte;
353
354         ssptep = (union split_spte *)sptep;
355         sspte = (union split_spte)spte;
356
357         ssptep->spte_high = sspte.spte_high;
358
359         /*
360          * If we map the spte from nonpresent to present, We should store
361          * the high bits firstly, then set present bit, so cpu can not
362          * fetch this spte while we are setting the spte.
363          */
364         smp_wmb();
365
366         ssptep->spte_low = sspte.spte_low;
367 }
368
369 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
370 {
371         union split_spte *ssptep, sspte;
372
373         ssptep = (union split_spte *)sptep;
374         sspte = (union split_spte)spte;
375
376         ssptep->spte_low = sspte.spte_low;
377
378         /*
379          * If we map the spte from present to nonpresent, we should clear
380          * present bit firstly to avoid vcpu fetch the old high bits.
381          */
382         smp_wmb();
383
384         ssptep->spte_high = sspte.spte_high;
385         count_spte_clear(sptep, spte);
386 }
387
388 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
389 {
390         union split_spte *ssptep, sspte, orig;
391
392         ssptep = (union split_spte *)sptep;
393         sspte = (union split_spte)spte;
394
395         /* xchg acts as a barrier before the setting of the high bits */
396         orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
397         orig.spte_high = ssptep->spte_high;
398         ssptep->spte_high = sspte.spte_high;
399         count_spte_clear(sptep, spte);
400
401         return orig.spte;
402 }
403
404 /*
405  * The idea using the light way get the spte on x86_32 guest is from
406  * gup_get_pte(arch/x86/mm/gup.c).
407  * The difference is we can not catch the spte tlb flush if we leave
408  * guest mode, so we emulate it by increase clear_spte_count when spte
409  * is cleared.
410  */
411 static u64 __get_spte_lockless(u64 *sptep)
412 {
413         struct kvm_mmu_page *sp =  page_header(__pa(sptep));
414         union split_spte spte, *orig = (union split_spte *)sptep;
415         int count;
416
417 retry:
418         count = sp->clear_spte_count;
419         smp_rmb();
420
421         spte.spte_low = orig->spte_low;
422         smp_rmb();
423
424         spte.spte_high = orig->spte_high;
425         smp_rmb();
426
427         if (unlikely(spte.spte_low != orig->spte_low ||
428               count != sp->clear_spte_count))
429                 goto retry;
430
431         return spte.spte;
432 }
433 #endif
434
435 static bool spte_has_volatile_bits(u64 spte)
436 {
437         if (!shadow_accessed_mask)
438                 return false;
439
440         if (!is_shadow_present_pte(spte))
441                 return false;
442
443         if ((spte & shadow_accessed_mask) &&
444               (!is_writable_pte(spte) || (spte & shadow_dirty_mask)))
445                 return false;
446
447         return true;
448 }
449
450 static bool spte_is_bit_cleared(u64 old_spte, u64 new_spte, u64 bit_mask)
451 {
452         return (old_spte & bit_mask) && !(new_spte & bit_mask);
453 }
454
455 /* Rules for using mmu_spte_set:
456  * Set the sptep from nonpresent to present.
457  * Note: the sptep being assigned *must* be either not present
458  * or in a state where the hardware will not attempt to update
459  * the spte.
460  */
461 static void mmu_spte_set(u64 *sptep, u64 new_spte)
462 {
463         WARN_ON(is_shadow_present_pte(*sptep));
464         __set_spte(sptep, new_spte);
465 }
466
467 /* Rules for using mmu_spte_update:
468  * Update the state bits, it means the mapped pfn is not changged.
469  */
470 static void mmu_spte_update(u64 *sptep, u64 new_spte)
471 {
472         u64 mask, old_spte = *sptep;
473
474         WARN_ON(!is_rmap_spte(new_spte));
475
476         if (!is_shadow_present_pte(old_spte))
477                 return mmu_spte_set(sptep, new_spte);
478
479         new_spte |= old_spte & shadow_dirty_mask;
480
481         mask = shadow_accessed_mask;
482         if (is_writable_pte(old_spte))
483                 mask |= shadow_dirty_mask;
484
485         if (!spte_has_volatile_bits(old_spte) || (new_spte & mask) == mask)
486                 __update_clear_spte_fast(sptep, new_spte);
487         else
488                 old_spte = __update_clear_spte_slow(sptep, new_spte);
489
490         if (!shadow_accessed_mask)
491                 return;
492
493         if (spte_is_bit_cleared(old_spte, new_spte, shadow_accessed_mask))
494                 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
495         if (spte_is_bit_cleared(old_spte, new_spte, shadow_dirty_mask))
496                 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
497 }
498
499 /*
500  * Rules for using mmu_spte_clear_track_bits:
501  * It sets the sptep from present to nonpresent, and track the
502  * state bits, it is used to clear the last level sptep.
503  */
504 static int mmu_spte_clear_track_bits(u64 *sptep)
505 {
506         pfn_t pfn;
507         u64 old_spte = *sptep;
508
509         if (!spte_has_volatile_bits(old_spte))
510                 __update_clear_spte_fast(sptep, 0ull);
511         else
512                 old_spte = __update_clear_spte_slow(sptep, 0ull);
513
514         if (!is_rmap_spte(old_spte))
515                 return 0;
516
517         pfn = spte_to_pfn(old_spte);
518         if (!shadow_accessed_mask || old_spte & shadow_accessed_mask)
519                 kvm_set_pfn_accessed(pfn);
520         if (!shadow_dirty_mask || (old_spte & shadow_dirty_mask))
521                 kvm_set_pfn_dirty(pfn);
522         return 1;
523 }
524
525 /*
526  * Rules for using mmu_spte_clear_no_track:
527  * Directly clear spte without caring the state bits of sptep,
528  * it is used to set the upper level spte.
529  */
530 static void mmu_spte_clear_no_track(u64 *sptep)
531 {
532         __update_clear_spte_fast(sptep, 0ull);
533 }
534
535 static u64 mmu_spte_get_lockless(u64 *sptep)
536 {
537         return __get_spte_lockless(sptep);
538 }
539
540 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
541 {
542         rcu_read_lock();
543         atomic_inc(&vcpu->kvm->arch.reader_counter);
544
545         /* Increase the counter before walking shadow page table */
546         smp_mb__after_atomic_inc();
547 }
548
549 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
550 {
551         /* Decrease the counter after walking shadow page table finished */
552         smp_mb__before_atomic_dec();
553         atomic_dec(&vcpu->kvm->arch.reader_counter);
554         rcu_read_unlock();
555 }
556
557 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
558                                   struct kmem_cache *base_cache, int min)
559 {
560         void *obj;
561
562         if (cache->nobjs >= min)
563                 return 0;
564         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
565                 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
566                 if (!obj)
567                         return -ENOMEM;
568                 cache->objects[cache->nobjs++] = obj;
569         }
570         return 0;
571 }
572
573 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
574                                   struct kmem_cache *cache)
575 {
576         while (mc->nobjs)
577                 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
578 }
579
580 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
581                                        int min)
582 {
583         void *page;
584
585         if (cache->nobjs >= min)
586                 return 0;
587         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
588                 page = (void *)__get_free_page(GFP_KERNEL);
589                 if (!page)
590                         return -ENOMEM;
591                 cache->objects[cache->nobjs++] = page;
592         }
593         return 0;
594 }
595
596 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
597 {
598         while (mc->nobjs)
599                 free_page((unsigned long)mc->objects[--mc->nobjs]);
600 }
601
602 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
603 {
604         int r;
605
606         r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
607                                    pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
608         if (r)
609                 goto out;
610         r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
611         if (r)
612                 goto out;
613         r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
614                                    mmu_page_header_cache, 4);
615 out:
616         return r;
617 }
618
619 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
620 {
621         mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
622                                 pte_list_desc_cache);
623         mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
624         mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
625                                 mmu_page_header_cache);
626 }
627
628 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc,
629                                     size_t size)
630 {
631         void *p;
632
633         BUG_ON(!mc->nobjs);
634         p = mc->objects[--mc->nobjs];
635         return p;
636 }
637
638 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
639 {
640         return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache,
641                                       sizeof(struct pte_list_desc));
642 }
643
644 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
645 {
646         kmem_cache_free(pte_list_desc_cache, pte_list_desc);
647 }
648
649 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
650 {
651         if (!sp->role.direct)
652                 return sp->gfns[index];
653
654         return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
655 }
656
657 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
658 {
659         if (sp->role.direct)
660                 BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
661         else
662                 sp->gfns[index] = gfn;
663 }
664
665 /*
666  * Return the pointer to the large page information for a given gfn,
667  * handling slots that are not large page aligned.
668  */
669 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
670                                               struct kvm_memory_slot *slot,
671                                               int level)
672 {
673         unsigned long idx;
674
675         idx = (gfn >> KVM_HPAGE_GFN_SHIFT(level)) -
676               (slot->base_gfn >> KVM_HPAGE_GFN_SHIFT(level));
677         return &slot->lpage_info[level - 2][idx];
678 }
679
680 static void account_shadowed(struct kvm *kvm, gfn_t gfn)
681 {
682         struct kvm_memory_slot *slot;
683         struct kvm_lpage_info *linfo;
684         int i;
685
686         slot = gfn_to_memslot(kvm, gfn);
687         for (i = PT_DIRECTORY_LEVEL;
688              i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) {
689                 linfo = lpage_info_slot(gfn, slot, i);
690                 linfo->write_count += 1;
691         }
692         kvm->arch.indirect_shadow_pages++;
693 }
694
695 static void unaccount_shadowed(struct kvm *kvm, gfn_t gfn)
696 {
697         struct kvm_memory_slot *slot;
698         struct kvm_lpage_info *linfo;
699         int i;
700
701         slot = gfn_to_memslot(kvm, gfn);
702         for (i = PT_DIRECTORY_LEVEL;
703              i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) {
704                 linfo = lpage_info_slot(gfn, slot, i);
705                 linfo->write_count -= 1;
706                 WARN_ON(linfo->write_count < 0);
707         }
708         kvm->arch.indirect_shadow_pages--;
709 }
710
711 static int has_wrprotected_page(struct kvm *kvm,
712                                 gfn_t gfn,
713                                 int level)
714 {
715         struct kvm_memory_slot *slot;
716         struct kvm_lpage_info *linfo;
717
718         slot = gfn_to_memslot(kvm, gfn);
719         if (slot) {
720                 linfo = lpage_info_slot(gfn, slot, level);
721                 return linfo->write_count;
722         }
723
724         return 1;
725 }
726
727 static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
728 {
729         unsigned long page_size;
730         int i, ret = 0;
731
732         page_size = kvm_host_page_size(kvm, gfn);
733
734         for (i = PT_PAGE_TABLE_LEVEL;
735              i < (PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES); ++i) {
736                 if (page_size >= KVM_HPAGE_SIZE(i))
737                         ret = i;
738                 else
739                         break;
740         }
741
742         return ret;
743 }
744
745 static struct kvm_memory_slot *
746 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
747                             bool no_dirty_log)
748 {
749         struct kvm_memory_slot *slot;
750
751         slot = gfn_to_memslot(vcpu->kvm, gfn);
752         if (!slot || slot->flags & KVM_MEMSLOT_INVALID ||
753               (no_dirty_log && slot->dirty_bitmap))
754                 slot = NULL;
755
756         return slot;
757 }
758
759 static bool mapping_level_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t large_gfn)
760 {
761         return !gfn_to_memslot_dirty_bitmap(vcpu, large_gfn, true);
762 }
763
764 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn)
765 {
766         int host_level, level, max_level;
767
768         host_level = host_mapping_level(vcpu->kvm, large_gfn);
769
770         if (host_level == PT_PAGE_TABLE_LEVEL)
771                 return host_level;
772
773         max_level = kvm_x86_ops->get_lpage_level() < host_level ?
774                 kvm_x86_ops->get_lpage_level() : host_level;
775
776         for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
777                 if (has_wrprotected_page(vcpu->kvm, large_gfn, level))
778                         break;
779
780         return level - 1;
781 }
782
783 /*
784  * Pte mapping structures:
785  *
786  * If pte_list bit zero is zero, then pte_list point to the spte.
787  *
788  * If pte_list bit zero is one, (then pte_list & ~1) points to a struct
789  * pte_list_desc containing more mappings.
790  *
791  * Returns the number of pte entries before the spte was added or zero if
792  * the spte was not added.
793  *
794  */
795 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
796                         unsigned long *pte_list)
797 {
798         struct pte_list_desc *desc;
799         int i, count = 0;
800
801         if (!*pte_list) {
802                 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
803                 *pte_list = (unsigned long)spte;
804         } else if (!(*pte_list & 1)) {
805                 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
806                 desc = mmu_alloc_pte_list_desc(vcpu);
807                 desc->sptes[0] = (u64 *)*pte_list;
808                 desc->sptes[1] = spte;
809                 *pte_list = (unsigned long)desc | 1;
810                 ++count;
811         } else {
812                 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
813                 desc = (struct pte_list_desc *)(*pte_list & ~1ul);
814                 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
815                         desc = desc->more;
816                         count += PTE_LIST_EXT;
817                 }
818                 if (desc->sptes[PTE_LIST_EXT-1]) {
819                         desc->more = mmu_alloc_pte_list_desc(vcpu);
820                         desc = desc->more;
821                 }
822                 for (i = 0; desc->sptes[i]; ++i)
823                         ++count;
824                 desc->sptes[i] = spte;
825         }
826         return count;
827 }
828
829 static u64 *pte_list_next(unsigned long *pte_list, u64 *spte)
830 {
831         struct pte_list_desc *desc;
832         u64 *prev_spte;
833         int i;
834
835         if (!*pte_list)
836                 return NULL;
837         else if (!(*pte_list & 1)) {
838                 if (!spte)
839                         return (u64 *)*pte_list;
840                 return NULL;
841         }
842         desc = (struct pte_list_desc *)(*pte_list & ~1ul);
843         prev_spte = NULL;
844         while (desc) {
845                 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
846                         if (prev_spte == spte)
847                                 return desc->sptes[i];
848                         prev_spte = desc->sptes[i];
849                 }
850                 desc = desc->more;
851         }
852         return NULL;
853 }
854
855 static void
856 pte_list_desc_remove_entry(unsigned long *pte_list, struct pte_list_desc *desc,
857                            int i, struct pte_list_desc *prev_desc)
858 {
859         int j;
860
861         for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
862                 ;
863         desc->sptes[i] = desc->sptes[j];
864         desc->sptes[j] = NULL;
865         if (j != 0)
866                 return;
867         if (!prev_desc && !desc->more)
868                 *pte_list = (unsigned long)desc->sptes[0];
869         else
870                 if (prev_desc)
871                         prev_desc->more = desc->more;
872                 else
873                         *pte_list = (unsigned long)desc->more | 1;
874         mmu_free_pte_list_desc(desc);
875 }
876
877 static void pte_list_remove(u64 *spte, unsigned long *pte_list)
878 {
879         struct pte_list_desc *desc;
880         struct pte_list_desc *prev_desc;
881         int i;
882
883         if (!*pte_list) {
884                 printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
885                 BUG();
886         } else if (!(*pte_list & 1)) {
887                 rmap_printk("pte_list_remove:  %p 1->0\n", spte);
888                 if ((u64 *)*pte_list != spte) {
889                         printk(KERN_ERR "pte_list_remove:  %p 1->BUG\n", spte);
890                         BUG();
891                 }
892                 *pte_list = 0;
893         } else {
894                 rmap_printk("pte_list_remove:  %p many->many\n", spte);
895                 desc = (struct pte_list_desc *)(*pte_list & ~1ul);
896                 prev_desc = NULL;
897                 while (desc) {
898                         for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i)
899                                 if (desc->sptes[i] == spte) {
900                                         pte_list_desc_remove_entry(pte_list,
901                                                                desc, i,
902                                                                prev_desc);
903                                         return;
904                                 }
905                         prev_desc = desc;
906                         desc = desc->more;
907                 }
908                 pr_err("pte_list_remove: %p many->many\n", spte);
909                 BUG();
910         }
911 }
912
913 typedef void (*pte_list_walk_fn) (u64 *spte);
914 static void pte_list_walk(unsigned long *pte_list, pte_list_walk_fn fn)
915 {
916         struct pte_list_desc *desc;
917         int i;
918
919         if (!*pte_list)
920                 return;
921
922         if (!(*pte_list & 1))
923                 return fn((u64 *)*pte_list);
924
925         desc = (struct pte_list_desc *)(*pte_list & ~1ul);
926         while (desc) {
927                 for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i)
928                         fn(desc->sptes[i]);
929                 desc = desc->more;
930         }
931 }
932
933 /*
934  * Take gfn and return the reverse mapping to it.
935  */
936 static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn, int level)
937 {
938         struct kvm_memory_slot *slot;
939         struct kvm_lpage_info *linfo;
940
941         slot = gfn_to_memslot(kvm, gfn);
942         if (likely(level == PT_PAGE_TABLE_LEVEL))
943                 return &slot->rmap[gfn - slot->base_gfn];
944
945         linfo = lpage_info_slot(gfn, slot, level);
946
947         return &linfo->rmap_pde;
948 }
949
950 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
951 {
952         struct kvm_mmu_page *sp;
953         unsigned long *rmapp;
954
955         sp = page_header(__pa(spte));
956         kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
957         rmapp = gfn_to_rmap(vcpu->kvm, gfn, sp->role.level);
958         return pte_list_add(vcpu, spte, rmapp);
959 }
960
961 static u64 *rmap_next(struct kvm *kvm, unsigned long *rmapp, u64 *spte)
962 {
963         return pte_list_next(rmapp, spte);
964 }
965
966 static void rmap_remove(struct kvm *kvm, u64 *spte)
967 {
968         struct kvm_mmu_page *sp;
969         gfn_t gfn;
970         unsigned long *rmapp;
971
972         sp = page_header(__pa(spte));
973         gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
974         rmapp = gfn_to_rmap(kvm, gfn, sp->role.level);
975         pte_list_remove(spte, rmapp);
976 }
977
978 static void drop_spte(struct kvm *kvm, u64 *sptep)
979 {
980         if (mmu_spte_clear_track_bits(sptep))
981                 rmap_remove(kvm, sptep);
982 }
983
984 static int rmap_write_protect(struct kvm *kvm, u64 gfn)
985 {
986         unsigned long *rmapp;
987         u64 *spte;
988         int i, write_protected = 0;
989
990         rmapp = gfn_to_rmap(kvm, gfn, PT_PAGE_TABLE_LEVEL);
991
992         spte = rmap_next(kvm, rmapp, NULL);
993         while (spte) {
994                 BUG_ON(!spte);
995                 BUG_ON(!(*spte & PT_PRESENT_MASK));
996                 rmap_printk("rmap_write_protect: spte %p %llx\n", spte, *spte);
997                 if (is_writable_pte(*spte)) {
998                         mmu_spte_update(spte, *spte & ~PT_WRITABLE_MASK);
999                         write_protected = 1;
1000                 }
1001                 spte = rmap_next(kvm, rmapp, spte);
1002         }
1003
1004         /* check for huge page mappings */
1005         for (i = PT_DIRECTORY_LEVEL;
1006              i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) {
1007                 rmapp = gfn_to_rmap(kvm, gfn, i);
1008                 spte = rmap_next(kvm, rmapp, NULL);
1009                 while (spte) {
1010                         BUG_ON(!spte);
1011                         BUG_ON(!(*spte & PT_PRESENT_MASK));
1012                         BUG_ON((*spte & (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK)) != (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK));
1013                         pgprintk("rmap_write_protect(large): spte %p %llx %lld\n", spte, *spte, gfn);
1014                         if (is_writable_pte(*spte)) {
1015                                 drop_spte(kvm, spte);
1016                                 --kvm->stat.lpages;
1017                                 spte = NULL;
1018                                 write_protected = 1;
1019                         }
1020                         spte = rmap_next(kvm, rmapp, spte);
1021                 }
1022         }
1023
1024         return write_protected;
1025 }
1026
1027 static int kvm_unmap_rmapp(struct kvm *kvm, unsigned long *rmapp,
1028                            unsigned long data)
1029 {
1030         u64 *spte;
1031         int need_tlb_flush = 0;
1032
1033         while ((spte = rmap_next(kvm, rmapp, NULL))) {
1034                 BUG_ON(!(*spte & PT_PRESENT_MASK));
1035                 rmap_printk("kvm_rmap_unmap_hva: spte %p %llx\n", spte, *spte);
1036                 drop_spte(kvm, spte);
1037                 need_tlb_flush = 1;
1038         }
1039         return need_tlb_flush;
1040 }
1041
1042 static int kvm_set_pte_rmapp(struct kvm *kvm, unsigned long *rmapp,
1043                              unsigned long data)
1044 {
1045         int need_flush = 0;
1046         u64 *spte, new_spte;
1047         pte_t *ptep = (pte_t *)data;
1048         pfn_t new_pfn;
1049
1050         WARN_ON(pte_huge(*ptep));
1051         new_pfn = pte_pfn(*ptep);
1052         spte = rmap_next(kvm, rmapp, NULL);
1053         while (spte) {
1054                 BUG_ON(!is_shadow_present_pte(*spte));
1055                 rmap_printk("kvm_set_pte_rmapp: spte %p %llx\n", spte, *spte);
1056                 need_flush = 1;
1057                 if (pte_write(*ptep)) {
1058                         drop_spte(kvm, spte);
1059                         spte = rmap_next(kvm, rmapp, NULL);
1060                 } else {
1061                         new_spte = *spte &~ (PT64_BASE_ADDR_MASK);
1062                         new_spte |= (u64)new_pfn << PAGE_SHIFT;
1063
1064                         new_spte &= ~PT_WRITABLE_MASK;
1065                         new_spte &= ~SPTE_HOST_WRITEABLE;
1066                         new_spte &= ~shadow_accessed_mask;
1067                         mmu_spte_clear_track_bits(spte);
1068                         mmu_spte_set(spte, new_spte);
1069                         spte = rmap_next(kvm, rmapp, spte);
1070                 }
1071         }
1072         if (need_flush)
1073                 kvm_flush_remote_tlbs(kvm);
1074
1075         return 0;
1076 }
1077
1078 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1079                           unsigned long data,
1080                           int (*handler)(struct kvm *kvm, unsigned long *rmapp,
1081                                          unsigned long data))
1082 {
1083         int i, j;
1084         int ret;
1085         int retval = 0;
1086         struct kvm_memslots *slots;
1087
1088         slots = kvm_memslots(kvm);
1089
1090         for (i = 0; i < slots->nmemslots; i++) {
1091                 struct kvm_memory_slot *memslot = &slots->memslots[i];
1092                 unsigned long start = memslot->userspace_addr;
1093                 unsigned long end;
1094
1095                 end = start + (memslot->npages << PAGE_SHIFT);
1096                 if (hva >= start && hva < end) {
1097                         gfn_t gfn_offset = (hva - start) >> PAGE_SHIFT;
1098                         gfn_t gfn = memslot->base_gfn + gfn_offset;
1099
1100                         ret = handler(kvm, &memslot->rmap[gfn_offset], data);
1101
1102                         for (j = 0; j < KVM_NR_PAGE_SIZES - 1; ++j) {
1103                                 struct kvm_lpage_info *linfo;
1104
1105                                 linfo = lpage_info_slot(gfn, memslot,
1106                                                         PT_DIRECTORY_LEVEL + j);
1107                                 ret |= handler(kvm, &linfo->rmap_pde, data);
1108                         }
1109                         trace_kvm_age_page(hva, memslot, ret);
1110                         retval |= ret;
1111                 }
1112         }
1113
1114         return retval;
1115 }
1116
1117 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
1118 {
1119         return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp);
1120 }
1121
1122 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1123 {
1124         kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1125 }
1126
1127 static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp,
1128                          unsigned long data)
1129 {
1130         u64 *spte;
1131         int young = 0;
1132
1133         /*
1134          * Emulate the accessed bit for EPT, by checking if this page has
1135          * an EPT mapping, and clearing it if it does. On the next access,
1136          * a new EPT mapping will be established.
1137          * This has some overhead, but not as much as the cost of swapping
1138          * out actively used pages or breaking up actively used hugepages.
1139          */
1140         if (!shadow_accessed_mask)
1141                 return kvm_unmap_rmapp(kvm, rmapp, data);
1142
1143         spte = rmap_next(kvm, rmapp, NULL);
1144         while (spte) {
1145                 int _young;
1146                 u64 _spte = *spte;
1147                 BUG_ON(!(_spte & PT_PRESENT_MASK));
1148                 _young = _spte & PT_ACCESSED_MASK;
1149                 if (_young) {
1150                         young = 1;
1151                         clear_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
1152                 }
1153                 spte = rmap_next(kvm, rmapp, spte);
1154         }
1155         return young;
1156 }
1157
1158 static int kvm_test_age_rmapp(struct kvm *kvm, unsigned long *rmapp,
1159                               unsigned long data)
1160 {
1161         u64 *spte;
1162         int young = 0;
1163
1164         /*
1165          * If there's no access bit in the secondary pte set by the
1166          * hardware it's up to gup-fast/gup to set the access bit in
1167          * the primary pte or in the page structure.
1168          */
1169         if (!shadow_accessed_mask)
1170                 goto out;
1171
1172         spte = rmap_next(kvm, rmapp, NULL);
1173         while (spte) {
1174                 u64 _spte = *spte;
1175                 BUG_ON(!(_spte & PT_PRESENT_MASK));
1176                 young = _spte & PT_ACCESSED_MASK;
1177                 if (young) {
1178                         young = 1;
1179                         break;
1180                 }
1181                 spte = rmap_next(kvm, rmapp, spte);
1182         }
1183 out:
1184         return young;
1185 }
1186
1187 #define RMAP_RECYCLE_THRESHOLD 1000
1188
1189 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1190 {
1191         unsigned long *rmapp;
1192         struct kvm_mmu_page *sp;
1193
1194         sp = page_header(__pa(spte));
1195
1196         rmapp = gfn_to_rmap(vcpu->kvm, gfn, sp->role.level);
1197
1198         kvm_unmap_rmapp(vcpu->kvm, rmapp, 0);
1199         kvm_flush_remote_tlbs(vcpu->kvm);
1200 }
1201
1202 int kvm_age_hva(struct kvm *kvm, unsigned long hva)
1203 {
1204         return kvm_handle_hva(kvm, hva, 0, kvm_age_rmapp);
1205 }
1206
1207 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1208 {
1209         return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1210 }
1211
1212 #ifdef MMU_DEBUG
1213 static int is_empty_shadow_page(u64 *spt)
1214 {
1215         u64 *pos;
1216         u64 *end;
1217
1218         for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1219                 if (is_shadow_present_pte(*pos)) {
1220                         printk(KERN_ERR "%s: %p %llx\n", __func__,
1221                                pos, *pos);
1222                         return 0;
1223                 }
1224         return 1;
1225 }
1226 #endif
1227
1228 /*
1229  * This value is the sum of all of the kvm instances's
1230  * kvm->arch.n_used_mmu_pages values.  We need a global,
1231  * aggregate version in order to make the slab shrinker
1232  * faster
1233  */
1234 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
1235 {
1236         kvm->arch.n_used_mmu_pages += nr;
1237         percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1238 }
1239
1240 /*
1241  * Remove the sp from shadow page cache, after call it,
1242  * we can not find this sp from the cache, and the shadow
1243  * page table is still valid.
1244  * It should be under the protection of mmu lock.
1245  */
1246 static void kvm_mmu_isolate_page(struct kvm_mmu_page *sp)
1247 {
1248         ASSERT(is_empty_shadow_page(sp->spt));
1249         hlist_del(&sp->hash_link);
1250         if (!sp->role.direct)
1251                 free_page((unsigned long)sp->gfns);
1252 }
1253
1254 /*
1255  * Free the shadow page table and the sp, we can do it
1256  * out of the protection of mmu lock.
1257  */
1258 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
1259 {
1260         list_del(&sp->link);
1261         free_page((unsigned long)sp->spt);
1262         kmem_cache_free(mmu_page_header_cache, sp);
1263 }
1264
1265 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1266 {
1267         return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
1268 }
1269
1270 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1271                                     struct kvm_mmu_page *sp, u64 *parent_pte)
1272 {
1273         if (!parent_pte)
1274                 return;
1275
1276         pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
1277 }
1278
1279 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1280                                        u64 *parent_pte)
1281 {
1282         pte_list_remove(parent_pte, &sp->parent_ptes);
1283 }
1284
1285 static void drop_parent_pte(struct kvm_mmu_page *sp,
1286                             u64 *parent_pte)
1287 {
1288         mmu_page_remove_parent_pte(sp, parent_pte);
1289         mmu_spte_clear_no_track(parent_pte);
1290 }
1291
1292 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
1293                                                u64 *parent_pte, int direct)
1294 {
1295         struct kvm_mmu_page *sp;
1296         sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache,
1297                                         sizeof *sp);
1298         sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
1299         if (!direct)
1300                 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache,
1301                                                   PAGE_SIZE);
1302         set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
1303         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
1304         bitmap_zero(sp->slot_bitmap, KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS);
1305         sp->parent_ptes = 0;
1306         mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1307         kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1308         return sp;
1309 }
1310
1311 static void mark_unsync(u64 *spte);
1312 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1313 {
1314         pte_list_walk(&sp->parent_ptes, mark_unsync);
1315 }
1316
1317 static void mark_unsync(u64 *spte)
1318 {
1319         struct kvm_mmu_page *sp;
1320         unsigned int index;
1321
1322         sp = page_header(__pa(spte));
1323         index = spte - sp->spt;
1324         if (__test_and_set_bit(index, sp->unsync_child_bitmap))
1325                 return;
1326         if (sp->unsync_children++)
1327                 return;
1328         kvm_mmu_mark_parents_unsync(sp);
1329 }
1330
1331 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1332                                struct kvm_mmu_page *sp)
1333 {
1334         return 1;
1335 }
1336
1337 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
1338 {
1339 }
1340
1341 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
1342                                  struct kvm_mmu_page *sp, u64 *spte,
1343                                  const void *pte)
1344 {
1345         WARN_ON(1);
1346 }
1347
1348 #define KVM_PAGE_ARRAY_NR 16
1349
1350 struct kvm_mmu_pages {
1351         struct mmu_page_and_offset {
1352                 struct kvm_mmu_page *sp;
1353                 unsigned int idx;
1354         } page[KVM_PAGE_ARRAY_NR];
1355         unsigned int nr;
1356 };
1357
1358 #define for_each_unsync_children(bitmap, idx)           \
1359         for (idx = find_first_bit(bitmap, 512);         \
1360              idx < 512;                                 \
1361              idx = find_next_bit(bitmap, 512, idx+1))
1362
1363 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1364                          int idx)
1365 {
1366         int i;
1367
1368         if (sp->unsync)
1369                 for (i=0; i < pvec->nr; i++)
1370                         if (pvec->page[i].sp == sp)
1371                                 return 0;
1372
1373         pvec->page[pvec->nr].sp = sp;
1374         pvec->page[pvec->nr].idx = idx;
1375         pvec->nr++;
1376         return (pvec->nr == KVM_PAGE_ARRAY_NR);
1377 }
1378
1379 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1380                            struct kvm_mmu_pages *pvec)
1381 {
1382         int i, ret, nr_unsync_leaf = 0;
1383
1384         for_each_unsync_children(sp->unsync_child_bitmap, i) {
1385                 struct kvm_mmu_page *child;
1386                 u64 ent = sp->spt[i];
1387
1388                 if (!is_shadow_present_pte(ent) || is_large_pte(ent))
1389                         goto clear_child_bitmap;
1390
1391                 child = page_header(ent & PT64_BASE_ADDR_MASK);
1392
1393                 if (child->unsync_children) {
1394                         if (mmu_pages_add(pvec, child, i))
1395                                 return -ENOSPC;
1396
1397                         ret = __mmu_unsync_walk(child, pvec);
1398                         if (!ret)
1399                                 goto clear_child_bitmap;
1400                         else if (ret > 0)
1401                                 nr_unsync_leaf += ret;
1402                         else
1403                                 return ret;
1404                 } else if (child->unsync) {
1405                         nr_unsync_leaf++;
1406                         if (mmu_pages_add(pvec, child, i))
1407                                 return -ENOSPC;
1408                 } else
1409                          goto clear_child_bitmap;
1410
1411                 continue;
1412
1413 clear_child_bitmap:
1414                 __clear_bit(i, sp->unsync_child_bitmap);
1415                 sp->unsync_children--;
1416                 WARN_ON((int)sp->unsync_children < 0);
1417         }
1418
1419
1420         return nr_unsync_leaf;
1421 }
1422
1423 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1424                            struct kvm_mmu_pages *pvec)
1425 {
1426         if (!sp->unsync_children)
1427                 return 0;
1428
1429         mmu_pages_add(pvec, sp, 0);
1430         return __mmu_unsync_walk(sp, pvec);
1431 }
1432
1433 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1434 {
1435         WARN_ON(!sp->unsync);
1436         trace_kvm_mmu_sync_page(sp);
1437         sp->unsync = 0;
1438         --kvm->stat.mmu_unsync;
1439 }
1440
1441 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1442                                     struct list_head *invalid_list);
1443 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1444                                     struct list_head *invalid_list);
1445
1446 #define for_each_gfn_sp(kvm, sp, gfn, pos)                              \
1447   hlist_for_each_entry(sp, pos,                                         \
1448    &(kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)], hash_link)   \
1449         if ((sp)->gfn != (gfn)) {} else
1450
1451 #define for_each_gfn_indirect_valid_sp(kvm, sp, gfn, pos)               \
1452   hlist_for_each_entry(sp, pos,                                         \
1453    &(kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)], hash_link)   \
1454                 if ((sp)->gfn != (gfn) || (sp)->role.direct ||          \
1455                         (sp)->role.invalid) {} else
1456
1457 /* @sp->gfn should be write-protected at the call site */
1458 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1459                            struct list_head *invalid_list, bool clear_unsync)
1460 {
1461         if (sp->role.cr4_pae != !!is_pae(vcpu)) {
1462                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1463                 return 1;
1464         }
1465
1466         if (clear_unsync)
1467                 kvm_unlink_unsync_page(vcpu->kvm, sp);
1468
1469         if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
1470                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1471                 return 1;
1472         }
1473
1474         kvm_mmu_flush_tlb(vcpu);
1475         return 0;
1476 }
1477
1478 static int kvm_sync_page_transient(struct kvm_vcpu *vcpu,
1479                                    struct kvm_mmu_page *sp)
1480 {
1481         LIST_HEAD(invalid_list);
1482         int ret;
1483
1484         ret = __kvm_sync_page(vcpu, sp, &invalid_list, false);
1485         if (ret)
1486                 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
1487
1488         return ret;
1489 }
1490
1491 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1492                          struct list_head *invalid_list)
1493 {
1494         return __kvm_sync_page(vcpu, sp, invalid_list, true);
1495 }
1496
1497 /* @gfn should be write-protected at the call site */
1498 static void kvm_sync_pages(struct kvm_vcpu *vcpu,  gfn_t gfn)
1499 {
1500         struct kvm_mmu_page *s;
1501         struct hlist_node *node;
1502         LIST_HEAD(invalid_list);
1503         bool flush = false;
1504
1505         for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn, node) {
1506                 if (!s->unsync)
1507                         continue;
1508
1509                 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
1510                 kvm_unlink_unsync_page(vcpu->kvm, s);
1511                 if ((s->role.cr4_pae != !!is_pae(vcpu)) ||
1512                         (vcpu->arch.mmu.sync_page(vcpu, s))) {
1513                         kvm_mmu_prepare_zap_page(vcpu->kvm, s, &invalid_list);
1514                         continue;
1515                 }
1516                 flush = true;
1517         }
1518
1519         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
1520         if (flush)
1521                 kvm_mmu_flush_tlb(vcpu);
1522 }
1523
1524 struct mmu_page_path {
1525         struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
1526         unsigned int idx[PT64_ROOT_LEVEL-1];
1527 };
1528
1529 #define for_each_sp(pvec, sp, parents, i)                       \
1530                 for (i = mmu_pages_next(&pvec, &parents, -1),   \
1531                         sp = pvec.page[i].sp;                   \
1532                         i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});   \
1533                         i = mmu_pages_next(&pvec, &parents, i))
1534
1535 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1536                           struct mmu_page_path *parents,
1537                           int i)
1538 {
1539         int n;
1540
1541         for (n = i+1; n < pvec->nr; n++) {
1542                 struct kvm_mmu_page *sp = pvec->page[n].sp;
1543
1544                 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1545                         parents->idx[0] = pvec->page[n].idx;
1546                         return n;
1547                 }
1548
1549                 parents->parent[sp->role.level-2] = sp;
1550                 parents->idx[sp->role.level-1] = pvec->page[n].idx;
1551         }
1552
1553         return n;
1554 }
1555
1556 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1557 {
1558         struct kvm_mmu_page *sp;
1559         unsigned int level = 0;
1560
1561         do {
1562                 unsigned int idx = parents->idx[level];
1563
1564                 sp = parents->parent[level];
1565                 if (!sp)
1566                         return;
1567
1568                 --sp->unsync_children;
1569                 WARN_ON((int)sp->unsync_children < 0);
1570                 __clear_bit(idx, sp->unsync_child_bitmap);
1571                 level++;
1572         } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
1573 }
1574
1575 static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
1576                                struct mmu_page_path *parents,
1577                                struct kvm_mmu_pages *pvec)
1578 {
1579         parents->parent[parent->role.level-1] = NULL;
1580         pvec->nr = 0;
1581 }
1582
1583 static void mmu_sync_children(struct kvm_vcpu *vcpu,
1584                               struct kvm_mmu_page *parent)
1585 {
1586         int i;
1587         struct kvm_mmu_page *sp;
1588         struct mmu_page_path parents;
1589         struct kvm_mmu_pages pages;
1590         LIST_HEAD(invalid_list);
1591
1592         kvm_mmu_pages_init(parent, &parents, &pages);
1593         while (mmu_unsync_walk(parent, &pages)) {
1594                 int protected = 0;
1595
1596                 for_each_sp(pages, sp, parents, i)
1597                         protected |= rmap_write_protect(vcpu->kvm, sp->gfn);
1598
1599                 if (protected)
1600                         kvm_flush_remote_tlbs(vcpu->kvm);
1601
1602                 for_each_sp(pages, sp, parents, i) {
1603                         kvm_sync_page(vcpu, sp, &invalid_list);
1604                         mmu_pages_clear_parents(&parents);
1605                 }
1606                 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
1607                 cond_resched_lock(&vcpu->kvm->mmu_lock);
1608                 kvm_mmu_pages_init(parent, &parents, &pages);
1609         }
1610 }
1611
1612 static void init_shadow_page_table(struct kvm_mmu_page *sp)
1613 {
1614         int i;
1615
1616         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
1617                 sp->spt[i] = 0ull;
1618 }
1619
1620 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
1621                                              gfn_t gfn,
1622                                              gva_t gaddr,
1623                                              unsigned level,
1624                                              int direct,
1625                                              unsigned access,
1626                                              u64 *parent_pte)
1627 {
1628         union kvm_mmu_page_role role;
1629         unsigned quadrant;
1630         struct kvm_mmu_page *sp;
1631         struct hlist_node *node;
1632         bool need_sync = false;
1633
1634         role = vcpu->arch.mmu.base_role;
1635         role.level = level;
1636         role.direct = direct;
1637         if (role.direct)
1638                 role.cr4_pae = 0;
1639         role.access = access;
1640         if (!vcpu->arch.mmu.direct_map
1641             && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
1642                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
1643                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
1644                 role.quadrant = quadrant;
1645         }
1646         for_each_gfn_sp(vcpu->kvm, sp, gfn, node) {
1647                 if (!need_sync && sp->unsync)
1648                         need_sync = true;
1649
1650                 if (sp->role.word != role.word)
1651                         continue;
1652
1653                 if (sp->unsync && kvm_sync_page_transient(vcpu, sp))
1654                         break;
1655
1656                 mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1657                 if (sp->unsync_children) {
1658                         kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
1659                         kvm_mmu_mark_parents_unsync(sp);
1660                 } else if (sp->unsync)
1661                         kvm_mmu_mark_parents_unsync(sp);
1662
1663                 trace_kvm_mmu_get_page(sp, false);
1664                 return sp;
1665         }
1666         ++vcpu->kvm->stat.mmu_cache_miss;
1667         sp = kvm_mmu_alloc_page(vcpu, parent_pte, direct);
1668         if (!sp)
1669                 return sp;
1670         sp->gfn = gfn;
1671         sp->role = role;
1672         hlist_add_head(&sp->hash_link,
1673                 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
1674         if (!direct) {
1675                 if (rmap_write_protect(vcpu->kvm, gfn))
1676                         kvm_flush_remote_tlbs(vcpu->kvm);
1677                 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
1678                         kvm_sync_pages(vcpu, gfn);
1679
1680                 account_shadowed(vcpu->kvm, gfn);
1681         }
1682         init_shadow_page_table(sp);
1683         trace_kvm_mmu_get_page(sp, true);
1684         return sp;
1685 }
1686
1687 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
1688                              struct kvm_vcpu *vcpu, u64 addr)
1689 {
1690         iterator->addr = addr;
1691         iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
1692         iterator->level = vcpu->arch.mmu.shadow_root_level;
1693
1694         if (iterator->level == PT64_ROOT_LEVEL &&
1695             vcpu->arch.mmu.root_level < PT64_ROOT_LEVEL &&
1696             !vcpu->arch.mmu.direct_map)
1697                 --iterator->level;
1698
1699         if (iterator->level == PT32E_ROOT_LEVEL) {
1700                 iterator->shadow_addr
1701                         = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
1702                 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
1703                 --iterator->level;
1704                 if (!iterator->shadow_addr)
1705                         iterator->level = 0;
1706         }
1707 }
1708
1709 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
1710 {
1711         if (iterator->level < PT_PAGE_TABLE_LEVEL)
1712                 return false;
1713
1714         iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
1715         iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
1716         return true;
1717 }
1718
1719 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
1720                                u64 spte)
1721 {
1722         if (is_last_spte(spte, iterator->level)) {
1723                 iterator->level = 0;
1724                 return;
1725         }
1726
1727         iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
1728         --iterator->level;
1729 }
1730
1731 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
1732 {
1733         return __shadow_walk_next(iterator, *iterator->sptep);
1734 }
1735
1736 static void link_shadow_page(u64 *sptep, struct kvm_mmu_page *sp)
1737 {
1738         u64 spte;
1739
1740         spte = __pa(sp->spt)
1741                 | PT_PRESENT_MASK | PT_ACCESSED_MASK
1742                 | PT_WRITABLE_MASK | PT_USER_MASK;
1743         mmu_spte_set(sptep, spte);
1744 }
1745
1746 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1747 {
1748         if (is_large_pte(*sptep)) {
1749                 drop_spte(vcpu->kvm, sptep);
1750                 kvm_flush_remote_tlbs(vcpu->kvm);
1751         }
1752 }
1753
1754 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
1755                                    unsigned direct_access)
1756 {
1757         if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
1758                 struct kvm_mmu_page *child;
1759
1760                 /*
1761                  * For the direct sp, if the guest pte's dirty bit
1762                  * changed form clean to dirty, it will corrupt the
1763                  * sp's access: allow writable in the read-only sp,
1764                  * so we should update the spte at this point to get
1765                  * a new sp with the correct access.
1766                  */
1767                 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
1768                 if (child->role.access == direct_access)
1769                         return;
1770
1771                 drop_parent_pte(child, sptep);
1772                 kvm_flush_remote_tlbs(vcpu->kvm);
1773         }
1774 }
1775
1776 static void mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1777                              u64 *spte)
1778 {
1779         u64 pte;
1780         struct kvm_mmu_page *child;
1781
1782         pte = *spte;
1783         if (is_shadow_present_pte(pte)) {
1784                 if (is_last_spte(pte, sp->role.level))
1785                         drop_spte(kvm, spte);
1786                 else {
1787                         child = page_header(pte & PT64_BASE_ADDR_MASK);
1788                         drop_parent_pte(child, spte);
1789                 }
1790         } else if (is_mmio_spte(pte))
1791                 mmu_spte_clear_no_track(spte);
1792
1793         if (is_large_pte(pte))
1794                 --kvm->stat.lpages;
1795 }
1796
1797 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
1798                                          struct kvm_mmu_page *sp)
1799 {
1800         unsigned i;
1801
1802         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
1803                 mmu_page_zap_pte(kvm, sp, sp->spt + i);
1804 }
1805
1806 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
1807 {
1808         mmu_page_remove_parent_pte(sp, parent_pte);
1809 }
1810
1811 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
1812 {
1813         int i;
1814         struct kvm_vcpu *vcpu;
1815
1816         kvm_for_each_vcpu(i, vcpu, kvm)
1817                 vcpu->arch.last_pte_updated = NULL;
1818 }
1819
1820 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
1821 {
1822         u64 *parent_pte;
1823
1824         while ((parent_pte = pte_list_next(&sp->parent_ptes, NULL)))
1825                 drop_parent_pte(sp, parent_pte);
1826 }
1827
1828 static int mmu_zap_unsync_children(struct kvm *kvm,
1829                                    struct kvm_mmu_page *parent,
1830                                    struct list_head *invalid_list)
1831 {
1832         int i, zapped = 0;
1833         struct mmu_page_path parents;
1834         struct kvm_mmu_pages pages;
1835
1836         if (parent->role.level == PT_PAGE_TABLE_LEVEL)
1837                 return 0;
1838
1839         kvm_mmu_pages_init(parent, &parents, &pages);
1840         while (mmu_unsync_walk(parent, &pages)) {
1841                 struct kvm_mmu_page *sp;
1842
1843                 for_each_sp(pages, sp, parents, i) {
1844                         kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
1845                         mmu_pages_clear_parents(&parents);
1846                         zapped++;
1847                 }
1848                 kvm_mmu_pages_init(parent, &parents, &pages);
1849         }
1850
1851         return zapped;
1852 }
1853
1854 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1855                                     struct list_head *invalid_list)
1856 {
1857         int ret;
1858
1859         trace_kvm_mmu_prepare_zap_page(sp);
1860         ++kvm->stat.mmu_shadow_zapped;
1861         ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
1862         kvm_mmu_page_unlink_children(kvm, sp);
1863         kvm_mmu_unlink_parents(kvm, sp);
1864         if (!sp->role.invalid && !sp->role.direct)
1865                 unaccount_shadowed(kvm, sp->gfn);
1866         if (sp->unsync)
1867                 kvm_unlink_unsync_page(kvm, sp);
1868         if (!sp->root_count) {
1869                 /* Count self */
1870                 ret++;
1871                 list_move(&sp->link, invalid_list);
1872                 kvm_mod_used_mmu_pages(kvm, -1);
1873         } else {
1874                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
1875                 kvm_reload_remote_mmus(kvm);
1876         }
1877
1878         sp->role.invalid = 1;
1879         kvm_mmu_reset_last_pte_updated(kvm);
1880         return ret;
1881 }
1882
1883 static void kvm_mmu_isolate_pages(struct list_head *invalid_list)
1884 {
1885         struct kvm_mmu_page *sp;
1886
1887         list_for_each_entry(sp, invalid_list, link)
1888                 kvm_mmu_isolate_page(sp);
1889 }
1890
1891 static void free_pages_rcu(struct rcu_head *head)
1892 {
1893         struct kvm_mmu_page *next, *sp;
1894
1895         sp = container_of(head, struct kvm_mmu_page, rcu);
1896         while (sp) {
1897                 if (!list_empty(&sp->link))
1898                         next = list_first_entry(&sp->link,
1899                                       struct kvm_mmu_page, link);
1900                 else
1901                         next = NULL;
1902                 kvm_mmu_free_page(sp);
1903                 sp = next;
1904         }
1905 }
1906
1907 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1908                                     struct list_head *invalid_list)
1909 {
1910         struct kvm_mmu_page *sp;
1911
1912         if (list_empty(invalid_list))
1913                 return;
1914
1915         kvm_flush_remote_tlbs(kvm);
1916
1917         if (atomic_read(&kvm->arch.reader_counter)) {
1918                 kvm_mmu_isolate_pages(invalid_list);
1919                 sp = list_first_entry(invalid_list, struct kvm_mmu_page, link);
1920                 list_del_init(invalid_list);
1921
1922                 trace_kvm_mmu_delay_free_pages(sp);
1923                 call_rcu(&sp->rcu, free_pages_rcu);
1924                 return;
1925         }
1926
1927         do {
1928                 sp = list_first_entry(invalid_list, struct kvm_mmu_page, link);
1929                 WARN_ON(!sp->role.invalid || sp->root_count);
1930                 kvm_mmu_isolate_page(sp);
1931                 kvm_mmu_free_page(sp);
1932         } while (!list_empty(invalid_list));
1933
1934 }
1935
1936 /*
1937  * Changing the number of mmu pages allocated to the vm
1938  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
1939  */
1940 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
1941 {
1942         LIST_HEAD(invalid_list);
1943         /*
1944          * If we set the number of mmu pages to be smaller be than the
1945          * number of actived pages , we must to free some mmu pages before we
1946          * change the value
1947          */
1948
1949         if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
1950                 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages &&
1951                         !list_empty(&kvm->arch.active_mmu_pages)) {
1952                         struct kvm_mmu_page *page;
1953
1954                         page = container_of(kvm->arch.active_mmu_pages.prev,
1955                                             struct kvm_mmu_page, link);
1956                         kvm_mmu_prepare_zap_page(kvm, page, &invalid_list);
1957                 }
1958                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
1959                 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
1960         }
1961
1962         kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
1963 }
1964
1965 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
1966 {
1967         struct kvm_mmu_page *sp;
1968         struct hlist_node *node;
1969         LIST_HEAD(invalid_list);
1970         int r;
1971
1972         pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
1973         r = 0;
1974
1975         for_each_gfn_indirect_valid_sp(kvm, sp, gfn, node) {
1976                 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
1977                          sp->role.word);
1978                 r = 1;
1979                 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
1980         }
1981         kvm_mmu_commit_zap_page(kvm, &invalid_list);
1982         return r;
1983 }
1984
1985 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
1986 {
1987         struct kvm_mmu_page *sp;
1988         struct hlist_node *node;
1989         LIST_HEAD(invalid_list);
1990
1991         for_each_gfn_indirect_valid_sp(kvm, sp, gfn, node) {
1992                 pgprintk("%s: zap %llx %x\n",
1993                          __func__, gfn, sp->role.word);
1994                 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
1995         }
1996         kvm_mmu_commit_zap_page(kvm, &invalid_list);
1997 }
1998
1999 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
2000 {
2001         int slot = memslot_id(kvm, gfn);
2002         struct kvm_mmu_page *sp = page_header(__pa(pte));
2003
2004         __set_bit(slot, sp->slot_bitmap);
2005 }
2006
2007 /*
2008  * The function is based on mtrr_type_lookup() in
2009  * arch/x86/kernel/cpu/mtrr/generic.c
2010  */
2011 static int get_mtrr_type(struct mtrr_state_type *mtrr_state,
2012                          u64 start, u64 end)
2013 {
2014         int i;
2015         u64 base, mask;
2016         u8 prev_match, curr_match;
2017         int num_var_ranges = KVM_NR_VAR_MTRR;
2018
2019         if (!mtrr_state->enabled)
2020                 return 0xFF;
2021
2022         /* Make end inclusive end, instead of exclusive */
2023         end--;
2024
2025         /* Look in fixed ranges. Just return the type as per start */
2026         if (mtrr_state->have_fixed && (start < 0x100000)) {
2027                 int idx;
2028
2029                 if (start < 0x80000) {
2030                         idx = 0;
2031                         idx += (start >> 16);
2032                         return mtrr_state->fixed_ranges[idx];
2033                 } else if (start < 0xC0000) {
2034                         idx = 1 * 8;
2035                         idx += ((start - 0x80000) >> 14);
2036                         return mtrr_state->fixed_ranges[idx];
2037                 } else if (start < 0x1000000) {
2038                         idx = 3 * 8;
2039                         idx += ((start - 0xC0000) >> 12);
2040                         return mtrr_state->fixed_ranges[idx];
2041                 }
2042         }
2043
2044         /*
2045          * Look in variable ranges
2046          * Look of multiple ranges matching this address and pick type
2047          * as per MTRR precedence
2048          */
2049         if (!(mtrr_state->enabled & 2))
2050                 return mtrr_state->def_type;
2051
2052         prev_match = 0xFF;
2053         for (i = 0; i < num_var_ranges; ++i) {
2054                 unsigned short start_state, end_state;
2055
2056                 if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11)))
2057                         continue;
2058
2059                 base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) +
2060                        (mtrr_state->var_ranges[i].base_lo & PAGE_MASK);
2061                 mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) +
2062                        (mtrr_state->var_ranges[i].mask_lo & PAGE_MASK);
2063
2064                 start_state = ((start & mask) == (base & mask));
2065                 end_state = ((end & mask) == (base & mask));
2066                 if (start_state != end_state)
2067                         return 0xFE;
2068
2069                 if ((start & mask) != (base & mask))
2070                         continue;
2071
2072                 curr_match = mtrr_state->var_ranges[i].base_lo & 0xff;
2073                 if (prev_match == 0xFF) {
2074                         prev_match = curr_match;
2075                         continue;
2076                 }
2077
2078                 if (prev_match == MTRR_TYPE_UNCACHABLE ||
2079                     curr_match == MTRR_TYPE_UNCACHABLE)
2080                         return MTRR_TYPE_UNCACHABLE;
2081
2082                 if ((prev_match == MTRR_TYPE_WRBACK &&
2083                      curr_match == MTRR_TYPE_WRTHROUGH) ||
2084                     (prev_match == MTRR_TYPE_WRTHROUGH &&
2085                      curr_match == MTRR_TYPE_WRBACK)) {
2086                         prev_match = MTRR_TYPE_WRTHROUGH;
2087                         curr_match = MTRR_TYPE_WRTHROUGH;
2088                 }
2089
2090                 if (prev_match != curr_match)
2091                         return MTRR_TYPE_UNCACHABLE;
2092         }
2093
2094         if (prev_match != 0xFF)
2095                 return prev_match;
2096
2097         return mtrr_state->def_type;
2098 }
2099
2100 u8 kvm_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn)
2101 {
2102         u8 mtrr;
2103
2104         mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT,
2105                              (gfn << PAGE_SHIFT) + PAGE_SIZE);
2106         if (mtrr == 0xfe || mtrr == 0xff)
2107                 mtrr = MTRR_TYPE_WRBACK;
2108         return mtrr;
2109 }
2110 EXPORT_SYMBOL_GPL(kvm_get_guest_memory_type);
2111
2112 static void __kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2113 {
2114         trace_kvm_mmu_unsync_page(sp);
2115         ++vcpu->kvm->stat.mmu_unsync;
2116         sp->unsync = 1;
2117
2118         kvm_mmu_mark_parents_unsync(sp);
2119 }
2120
2121 static void kvm_unsync_pages(struct kvm_vcpu *vcpu,  gfn_t gfn)
2122 {
2123         struct kvm_mmu_page *s;
2124         struct hlist_node *node;
2125
2126         for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn, node) {
2127                 if (s->unsync)
2128                         continue;
2129                 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2130                 __kvm_unsync_page(vcpu, s);
2131         }
2132 }
2133
2134 static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2135                                   bool can_unsync)
2136 {
2137         struct kvm_mmu_page *s;
2138         struct hlist_node *node;
2139         bool need_unsync = false;
2140
2141         for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn, node) {
2142                 if (!can_unsync)
2143                         return 1;
2144
2145                 if (s->role.level != PT_PAGE_TABLE_LEVEL)
2146                         return 1;
2147
2148                 if (!need_unsync && !s->unsync) {
2149                         if (!oos_shadow)
2150                                 return 1;
2151                         need_unsync = true;
2152                 }
2153         }
2154         if (need_unsync)
2155                 kvm_unsync_pages(vcpu, gfn);
2156         return 0;
2157 }
2158
2159 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2160                     unsigned pte_access, int user_fault,
2161                     int write_fault, int level,
2162                     gfn_t gfn, pfn_t pfn, bool speculative,
2163                     bool can_unsync, bool host_writable)
2164 {
2165         u64 spte, entry = *sptep;
2166         int ret = 0;
2167
2168         if (set_mmio_spte(sptep, gfn, pfn, pte_access))
2169                 return 0;
2170
2171         /*
2172          * We don't set the accessed bit, since we sometimes want to see
2173          * whether the guest actually used the pte (in order to detect
2174          * demand paging).
2175          */
2176         spte = PT_PRESENT_MASK;
2177         if (!speculative)
2178                 spte |= shadow_accessed_mask;
2179
2180         if (pte_access & ACC_EXEC_MASK)
2181                 spte |= shadow_x_mask;
2182         else
2183                 spte |= shadow_nx_mask;
2184         if (pte_access & ACC_USER_MASK)
2185                 spte |= shadow_user_mask;
2186         if (level > PT_PAGE_TABLE_LEVEL)
2187                 spte |= PT_PAGE_SIZE_MASK;
2188         if (tdp_enabled)
2189                 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2190                         kvm_is_mmio_pfn(pfn));
2191
2192         if (host_writable)
2193                 spte |= SPTE_HOST_WRITEABLE;
2194         else
2195                 pte_access &= ~ACC_WRITE_MASK;
2196
2197         spte |= (u64)pfn << PAGE_SHIFT;
2198
2199         if ((pte_access & ACC_WRITE_MASK)
2200             || (!vcpu->arch.mmu.direct_map && write_fault
2201                 && !is_write_protection(vcpu) && !user_fault)) {
2202
2203                 if (level > PT_PAGE_TABLE_LEVEL &&
2204                     has_wrprotected_page(vcpu->kvm, gfn, level)) {
2205                         ret = 1;
2206                         drop_spte(vcpu->kvm, sptep);
2207                         goto done;
2208                 }
2209
2210                 spte |= PT_WRITABLE_MASK;
2211
2212                 if (!vcpu->arch.mmu.direct_map
2213                     && !(pte_access & ACC_WRITE_MASK)) {
2214                         spte &= ~PT_USER_MASK;
2215                         /*
2216                          * If we converted a user page to a kernel page,
2217                          * so that the kernel can write to it when cr0.wp=0,
2218                          * then we should prevent the kernel from executing it
2219                          * if SMEP is enabled.
2220                          */
2221                         if (kvm_read_cr4_bits(vcpu, X86_CR4_SMEP))
2222                                 spte |= PT64_NX_MASK;
2223                 }
2224
2225                 /*
2226                  * Optimization: for pte sync, if spte was writable the hash
2227                  * lookup is unnecessary (and expensive). Write protection
2228                  * is responsibility of mmu_get_page / kvm_sync_page.
2229                  * Same reasoning can be applied to dirty page accounting.
2230                  */
2231                 if (!can_unsync && is_writable_pte(*sptep))
2232                         goto set_pte;
2233
2234                 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
2235                         pgprintk("%s: found shadow page for %llx, marking ro\n",
2236                                  __func__, gfn);
2237                         ret = 1;
2238                         pte_access &= ~ACC_WRITE_MASK;
2239                         if (is_writable_pte(spte))
2240                                 spte &= ~PT_WRITABLE_MASK;
2241                 }
2242         }
2243
2244         if (pte_access & ACC_WRITE_MASK)
2245                 mark_page_dirty(vcpu->kvm, gfn);
2246
2247 set_pte:
2248         mmu_spte_update(sptep, spte);
2249         /*
2250          * If we overwrite a writable spte with a read-only one we
2251          * should flush remote TLBs. Otherwise rmap_write_protect
2252          * will find a read-only spte, even though the writable spte
2253          * might be cached on a CPU's TLB.
2254          */
2255         if (is_writable_pte(entry) && !is_writable_pte(*sptep))
2256                 kvm_flush_remote_tlbs(vcpu->kvm);
2257 done:
2258         return ret;
2259 }
2260
2261 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2262                          unsigned pt_access, unsigned pte_access,
2263                          int user_fault, int write_fault,
2264                          int *emulate, int level, gfn_t gfn,
2265                          pfn_t pfn, bool speculative,
2266                          bool host_writable)
2267 {
2268         int was_rmapped = 0;
2269         int rmap_count;
2270
2271         pgprintk("%s: spte %llx access %x write_fault %d"
2272                  " user_fault %d gfn %llx\n",
2273                  __func__, *sptep, pt_access,
2274                  write_fault, user_fault, gfn);
2275
2276         if (is_rmap_spte(*sptep)) {
2277                 /*
2278                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2279                  * the parent of the now unreachable PTE.
2280                  */
2281                 if (level > PT_PAGE_TABLE_LEVEL &&
2282                     !is_large_pte(*sptep)) {
2283                         struct kvm_mmu_page *child;
2284                         u64 pte = *sptep;
2285
2286                         child = page_header(pte & PT64_BASE_ADDR_MASK);
2287                         drop_parent_pte(child, sptep);
2288                         kvm_flush_remote_tlbs(vcpu->kvm);
2289                 } else if (pfn != spte_to_pfn(*sptep)) {
2290                         pgprintk("hfn old %llx new %llx\n",
2291                                  spte_to_pfn(*sptep), pfn);
2292                         drop_spte(vcpu->kvm, sptep);
2293                         kvm_flush_remote_tlbs(vcpu->kvm);
2294                 } else
2295                         was_rmapped = 1;
2296         }
2297
2298         if (set_spte(vcpu, sptep, pte_access, user_fault, write_fault,
2299                       level, gfn, pfn, speculative, true,
2300                       host_writable)) {
2301                 if (write_fault)
2302                         *emulate = 1;
2303                 kvm_mmu_flush_tlb(vcpu);
2304         }
2305
2306         if (unlikely(is_mmio_spte(*sptep) && emulate))
2307                 *emulate = 1;
2308
2309         pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2310         pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
2311                  is_large_pte(*sptep)? "2MB" : "4kB",
2312                  *sptep & PT_PRESENT_MASK ?"RW":"R", gfn,
2313                  *sptep, sptep);
2314         if (!was_rmapped && is_large_pte(*sptep))
2315                 ++vcpu->kvm->stat.lpages;
2316
2317         if (is_shadow_present_pte(*sptep)) {
2318                 page_header_update_slot(vcpu->kvm, sptep, gfn);
2319                 if (!was_rmapped) {
2320                         rmap_count = rmap_add(vcpu, sptep, gfn);
2321                         if (rmap_count > RMAP_RECYCLE_THRESHOLD)
2322                                 rmap_recycle(vcpu, sptep, gfn);
2323                 }
2324         }
2325         kvm_release_pfn_clean(pfn);
2326         if (speculative) {
2327                 vcpu->arch.last_pte_updated = sptep;
2328                 vcpu->arch.last_pte_gfn = gfn;
2329         }
2330 }
2331
2332 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
2333 {
2334 }
2335
2336 static pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
2337                                      bool no_dirty_log)
2338 {
2339         struct kvm_memory_slot *slot;
2340         unsigned long hva;
2341
2342         slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
2343         if (!slot) {
2344                 get_page(fault_page);
2345                 return page_to_pfn(fault_page);
2346         }
2347
2348         hva = gfn_to_hva_memslot(slot, gfn);
2349
2350         return hva_to_pfn_atomic(vcpu->kvm, hva);
2351 }
2352
2353 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2354                                     struct kvm_mmu_page *sp,
2355                                     u64 *start, u64 *end)
2356 {
2357         struct page *pages[PTE_PREFETCH_NUM];
2358         unsigned access = sp->role.access;
2359         int i, ret;
2360         gfn_t gfn;
2361
2362         gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
2363         if (!gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK))
2364                 return -1;
2365
2366         ret = gfn_to_page_many_atomic(vcpu->kvm, gfn, pages, end - start);
2367         if (ret <= 0)
2368                 return -1;
2369
2370         for (i = 0; i < ret; i++, gfn++, start++)
2371                 mmu_set_spte(vcpu, start, ACC_ALL,
2372                              access, 0, 0, NULL,
2373                              sp->role.level, gfn,
2374                              page_to_pfn(pages[i]), true, true);
2375
2376         return 0;
2377 }
2378
2379 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2380                                   struct kvm_mmu_page *sp, u64 *sptep)
2381 {
2382         u64 *spte, *start = NULL;
2383         int i;
2384
2385         WARN_ON(!sp->role.direct);
2386
2387         i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2388         spte = sp->spt + i;
2389
2390         for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2391                 if (is_shadow_present_pte(*spte) || spte == sptep) {
2392                         if (!start)
2393                                 continue;
2394                         if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2395                                 break;
2396                         start = NULL;
2397                 } else if (!start)
2398                         start = spte;
2399         }
2400 }
2401
2402 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2403 {
2404         struct kvm_mmu_page *sp;
2405
2406         /*
2407          * Since it's no accessed bit on EPT, it's no way to
2408          * distinguish between actually accessed translations
2409          * and prefetched, so disable pte prefetch if EPT is
2410          * enabled.
2411          */
2412         if (!shadow_accessed_mask)
2413                 return;
2414
2415         sp = page_header(__pa(sptep));
2416         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
2417                 return;
2418
2419         __direct_pte_prefetch(vcpu, sp, sptep);
2420 }
2421
2422 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
2423                         int map_writable, int level, gfn_t gfn, pfn_t pfn,
2424                         bool prefault)
2425 {
2426         struct kvm_shadow_walk_iterator iterator;
2427         struct kvm_mmu_page *sp;
2428         int emulate = 0;
2429         gfn_t pseudo_gfn;
2430
2431         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2432                 return 0;
2433
2434         for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
2435                 if (iterator.level == level) {
2436                         unsigned pte_access = ACC_ALL;
2437
2438                         mmu_set_spte(vcpu, iterator.sptep, ACC_ALL, pte_access,
2439                                      0, write, &emulate,
2440                                      level, gfn, pfn, prefault, map_writable);
2441                         direct_pte_prefetch(vcpu, iterator.sptep);
2442                         ++vcpu->stat.pf_fixed;
2443                         break;
2444                 }
2445
2446                 if (!is_shadow_present_pte(*iterator.sptep)) {
2447                         u64 base_addr = iterator.addr;
2448
2449                         base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
2450                         pseudo_gfn = base_addr >> PAGE_SHIFT;
2451                         sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
2452                                               iterator.level - 1,
2453                                               1, ACC_ALL, iterator.sptep);
2454                         if (!sp) {
2455                                 pgprintk("nonpaging_map: ENOMEM\n");
2456                                 kvm_release_pfn_clean(pfn);
2457                                 return -ENOMEM;
2458                         }
2459
2460                         mmu_spte_set(iterator.sptep,
2461                                      __pa(sp->spt)
2462                                      | PT_PRESENT_MASK | PT_WRITABLE_MASK
2463                                      | shadow_user_mask | shadow_x_mask
2464                                      | shadow_accessed_mask);
2465                 }
2466         }
2467         return emulate;
2468 }
2469
2470 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
2471 {
2472         siginfo_t info;
2473
2474         info.si_signo   = SIGBUS;
2475         info.si_errno   = 0;
2476         info.si_code    = BUS_MCEERR_AR;
2477         info.si_addr    = (void __user *)address;
2478         info.si_addr_lsb = PAGE_SHIFT;
2479
2480         send_sig_info(SIGBUS, &info, tsk);
2481 }
2482
2483 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, pfn_t pfn)
2484 {
2485         kvm_release_pfn_clean(pfn);
2486         if (is_hwpoison_pfn(pfn)) {
2487                 kvm_send_hwpoison_signal(gfn_to_hva(vcpu->kvm, gfn), current);
2488                 return 0;
2489         }
2490
2491         return -EFAULT;
2492 }
2493
2494 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
2495                                         gfn_t *gfnp, pfn_t *pfnp, int *levelp)
2496 {
2497         pfn_t pfn = *pfnp;
2498         gfn_t gfn = *gfnp;
2499         int level = *levelp;
2500
2501         /*
2502          * Check if it's a transparent hugepage. If this would be an
2503          * hugetlbfs page, level wouldn't be set to
2504          * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
2505          * here.
2506          */
2507         if (!is_error_pfn(pfn) && !kvm_is_mmio_pfn(pfn) &&
2508             level == PT_PAGE_TABLE_LEVEL &&
2509             PageTransCompound(pfn_to_page(pfn)) &&
2510             !has_wrprotected_page(vcpu->kvm, gfn, PT_DIRECTORY_LEVEL)) {
2511                 unsigned long mask;
2512                 /*
2513                  * mmu_notifier_retry was successful and we hold the
2514                  * mmu_lock here, so the pmd can't become splitting
2515                  * from under us, and in turn
2516                  * __split_huge_page_refcount() can't run from under
2517                  * us and we can safely transfer the refcount from
2518                  * PG_tail to PG_head as we switch the pfn to tail to
2519                  * head.
2520                  */
2521                 *levelp = level = PT_DIRECTORY_LEVEL;
2522                 mask = KVM_PAGES_PER_HPAGE(level) - 1;
2523                 VM_BUG_ON((gfn & mask) != (pfn & mask));
2524                 if (pfn & mask) {
2525                         gfn &= ~mask;
2526                         *gfnp = gfn;
2527                         kvm_release_pfn_clean(pfn);
2528                         pfn &= ~mask;
2529                         if (!get_page_unless_zero(pfn_to_page(pfn)))
2530                                 BUG();
2531                         *pfnp = pfn;
2532                 }
2533         }
2534 }
2535
2536 static bool mmu_invalid_pfn(pfn_t pfn)
2537 {
2538         return unlikely(is_invalid_pfn(pfn));
2539 }
2540
2541 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
2542                                 pfn_t pfn, unsigned access, int *ret_val)
2543 {
2544         bool ret = true;
2545
2546         /* The pfn is invalid, report the error! */
2547         if (unlikely(is_invalid_pfn(pfn))) {
2548                 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
2549                 goto exit;
2550         }
2551
2552         if (unlikely(is_noslot_pfn(pfn)))
2553                 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
2554
2555         ret = false;
2556 exit:
2557         return ret;
2558 }
2559
2560 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
2561                          gva_t gva, pfn_t *pfn, bool write, bool *writable);
2562
2563 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn,
2564                          bool prefault)
2565 {
2566         int r;
2567         int level;
2568         int force_pt_level;
2569         pfn_t pfn;
2570         unsigned long mmu_seq;
2571         bool map_writable;
2572
2573         force_pt_level = mapping_level_dirty_bitmap(vcpu, gfn);
2574         if (likely(!force_pt_level)) {
2575                 level = mapping_level(vcpu, gfn);
2576                 /*
2577                  * This path builds a PAE pagetable - so we can map
2578                  * 2mb pages at maximum. Therefore check if the level
2579                  * is larger than that.
2580                  */
2581                 if (level > PT_DIRECTORY_LEVEL)
2582                         level = PT_DIRECTORY_LEVEL;
2583
2584                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
2585         } else
2586                 level = PT_PAGE_TABLE_LEVEL;
2587
2588         mmu_seq = vcpu->kvm->mmu_notifier_seq;
2589         smp_rmb();
2590
2591         if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
2592                 return 0;
2593
2594         if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
2595                 return r;
2596
2597         spin_lock(&vcpu->kvm->mmu_lock);
2598         if (mmu_notifier_retry(vcpu, mmu_seq))
2599                 goto out_unlock;
2600         kvm_mmu_free_some_pages(vcpu);
2601         if (likely(!force_pt_level))
2602                 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
2603         r = __direct_map(vcpu, v, write, map_writable, level, gfn, pfn,
2604                          prefault);
2605         spin_unlock(&vcpu->kvm->mmu_lock);
2606
2607
2608         return r;
2609
2610 out_unlock:
2611         spin_unlock(&vcpu->kvm->mmu_lock);
2612         kvm_release_pfn_clean(pfn);
2613         return 0;
2614 }
2615
2616
2617 static void mmu_free_roots(struct kvm_vcpu *vcpu)
2618 {
2619         int i;
2620         struct kvm_mmu_page *sp;
2621         LIST_HEAD(invalid_list);
2622
2623         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2624                 return;
2625         spin_lock(&vcpu->kvm->mmu_lock);
2626         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL &&
2627             (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL ||
2628              vcpu->arch.mmu.direct_map)) {
2629                 hpa_t root = vcpu->arch.mmu.root_hpa;
2630
2631                 sp = page_header(root);
2632                 --sp->root_count;
2633                 if (!sp->root_count && sp->role.invalid) {
2634                         kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
2635                         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2636                 }
2637                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
2638                 spin_unlock(&vcpu->kvm->mmu_lock);
2639                 return;
2640         }
2641         for (i = 0; i < 4; ++i) {
2642                 hpa_t root = vcpu->arch.mmu.pae_root[i];
2643
2644                 if (root) {
2645                         root &= PT64_BASE_ADDR_MASK;
2646                         sp = page_header(root);
2647                         --sp->root_count;
2648                         if (!sp->root_count && sp->role.invalid)
2649                                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
2650                                                          &invalid_list);
2651                 }
2652                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
2653         }
2654         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2655         spin_unlock(&vcpu->kvm->mmu_lock);
2656         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
2657 }
2658
2659 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
2660 {
2661         int ret = 0;
2662
2663         if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
2664                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2665                 ret = 1;
2666         }
2667
2668         return ret;
2669 }
2670
2671 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
2672 {
2673         struct kvm_mmu_page *sp;
2674         unsigned i;
2675
2676         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2677                 spin_lock(&vcpu->kvm->mmu_lock);
2678                 kvm_mmu_free_some_pages(vcpu);
2679                 sp = kvm_mmu_get_page(vcpu, 0, 0, PT64_ROOT_LEVEL,
2680                                       1, ACC_ALL, NULL);
2681                 ++sp->root_count;
2682                 spin_unlock(&vcpu->kvm->mmu_lock);
2683                 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
2684         } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
2685                 for (i = 0; i < 4; ++i) {
2686                         hpa_t root = vcpu->arch.mmu.pae_root[i];
2687
2688                         ASSERT(!VALID_PAGE(root));
2689                         spin_lock(&vcpu->kvm->mmu_lock);
2690                         kvm_mmu_free_some_pages(vcpu);
2691                         sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
2692                                               i << 30,
2693                                               PT32_ROOT_LEVEL, 1, ACC_ALL,
2694                                               NULL);
2695                         root = __pa(sp->spt);
2696                         ++sp->root_count;
2697                         spin_unlock(&vcpu->kvm->mmu_lock);
2698                         vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
2699                 }
2700                 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
2701         } else
2702                 BUG();
2703
2704         return 0;
2705 }
2706
2707 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
2708 {
2709         struct kvm_mmu_page *sp;
2710         u64 pdptr, pm_mask;
2711         gfn_t root_gfn;
2712         int i;
2713
2714         root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
2715
2716         if (mmu_check_root(vcpu, root_gfn))
2717                 return 1;
2718
2719         /*
2720          * Do we shadow a long mode page table? If so we need to
2721          * write-protect the guests page table root.
2722          */
2723         if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
2724                 hpa_t root = vcpu->arch.mmu.root_hpa;
2725
2726                 ASSERT(!VALID_PAGE(root));
2727
2728                 spin_lock(&vcpu->kvm->mmu_lock);
2729                 kvm_mmu_free_some_pages(vcpu);
2730                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0, PT64_ROOT_LEVEL,
2731                                       0, ACC_ALL, NULL);
2732                 root = __pa(sp->spt);
2733                 ++sp->root_count;
2734                 spin_unlock(&vcpu->kvm->mmu_lock);
2735                 vcpu->arch.mmu.root_hpa = root;
2736                 return 0;
2737         }
2738
2739         /*
2740          * We shadow a 32 bit page table. This may be a legacy 2-level
2741          * or a PAE 3-level page table. In either case we need to be aware that
2742          * the shadow page table may be a PAE or a long mode page table.
2743          */
2744         pm_mask = PT_PRESENT_MASK;
2745         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL)
2746                 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
2747
2748         for (i = 0; i < 4; ++i) {
2749                 hpa_t root = vcpu->arch.mmu.pae_root[i];
2750
2751                 ASSERT(!VALID_PAGE(root));
2752                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
2753                         pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
2754                         if (!is_present_gpte(pdptr)) {
2755                                 vcpu->arch.mmu.pae_root[i] = 0;
2756                                 continue;
2757                         }
2758                         root_gfn = pdptr >> PAGE_SHIFT;
2759                         if (mmu_check_root(vcpu, root_gfn))
2760                                 return 1;
2761                 }
2762                 spin_lock(&vcpu->kvm->mmu_lock);
2763                 kvm_mmu_free_some_pages(vcpu);
2764                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
2765                                       PT32_ROOT_LEVEL, 0,
2766                                       ACC_ALL, NULL);
2767                 root = __pa(sp->spt);
2768                 ++sp->root_count;
2769                 spin_unlock(&vcpu->kvm->mmu_lock);
2770
2771                 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
2772         }
2773         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
2774
2775         /*
2776          * If we shadow a 32 bit page table with a long mode page
2777          * table we enter this path.
2778          */
2779         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2780                 if (vcpu->arch.mmu.lm_root == NULL) {
2781                         /*
2782                          * The additional page necessary for this is only
2783                          * allocated on demand.
2784                          */
2785
2786                         u64 *lm_root;
2787
2788                         lm_root = (void*)get_zeroed_page(GFP_KERNEL);
2789                         if (lm_root == NULL)
2790                                 return 1;
2791
2792                         lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
2793
2794                         vcpu->arch.mmu.lm_root = lm_root;
2795                 }
2796
2797                 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
2798         }
2799
2800         return 0;
2801 }
2802
2803 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
2804 {
2805         if (vcpu->arch.mmu.direct_map)
2806                 return mmu_alloc_direct_roots(vcpu);
2807         else
2808                 return mmu_alloc_shadow_roots(vcpu);
2809 }
2810
2811 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
2812 {
2813         int i;
2814         struct kvm_mmu_page *sp;
2815
2816         if (vcpu->arch.mmu.direct_map)
2817                 return;
2818
2819         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2820                 return;
2821
2822         vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
2823         trace_kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
2824         if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
2825                 hpa_t root = vcpu->arch.mmu.root_hpa;
2826                 sp = page_header(root);
2827                 mmu_sync_children(vcpu, sp);
2828                 trace_kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
2829                 return;
2830         }
2831         for (i = 0; i < 4; ++i) {
2832                 hpa_t root = vcpu->arch.mmu.pae_root[i];
2833
2834                 if (root && VALID_PAGE(root)) {
2835                         root &= PT64_BASE_ADDR_MASK;
2836                         sp = page_header(root);
2837                         mmu_sync_children(vcpu, sp);
2838                 }
2839         }
2840         trace_kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
2841 }
2842
2843 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
2844 {
2845         spin_lock(&vcpu->kvm->mmu_lock);
2846         mmu_sync_roots(vcpu);
2847         spin_unlock(&vcpu->kvm->mmu_lock);
2848 }
2849
2850 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
2851                                   u32 access, struct x86_exception *exception)
2852 {
2853         if (exception)
2854                 exception->error_code = 0;
2855         return vaddr;
2856 }
2857
2858 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
2859                                          u32 access,
2860                                          struct x86_exception *exception)
2861 {
2862         if (exception)
2863                 exception->error_code = 0;
2864         return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access);
2865 }
2866
2867 static bool quickly_check_mmio_pf(struct kvm_vcpu *vcpu, u64 addr, bool direct)
2868 {
2869         if (direct)
2870                 return vcpu_match_mmio_gpa(vcpu, addr);
2871
2872         return vcpu_match_mmio_gva(vcpu, addr);
2873 }
2874
2875 static u64 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr)
2876 {
2877         struct kvm_shadow_walk_iterator iterator;
2878         u64 spte = 0ull;
2879
2880         walk_shadow_page_lockless_begin(vcpu);
2881         for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
2882                 if (!is_shadow_present_pte(spte))
2883                         break;
2884         walk_shadow_page_lockless_end(vcpu);
2885
2886         return spte;
2887 }
2888
2889 /*
2890  * If it is a real mmio page fault, return 1 and emulat the instruction
2891  * directly, return 0 to let CPU fault again on the address, -1 is
2892  * returned if bug is detected.
2893  */
2894 int handle_mmio_page_fault_common(struct kvm_vcpu *vcpu, u64 addr, bool direct)
2895 {
2896         u64 spte;
2897
2898         if (quickly_check_mmio_pf(vcpu, addr, direct))
2899                 return 1;
2900
2901         spte = walk_shadow_page_get_mmio_spte(vcpu, addr);
2902
2903         if (is_mmio_spte(spte)) {
2904                 gfn_t gfn = get_mmio_spte_gfn(spte);
2905                 unsigned access = get_mmio_spte_access(spte);
2906
2907                 if (direct)
2908                         addr = 0;
2909
2910                 trace_handle_mmio_page_fault(addr, gfn, access);
2911                 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
2912                 return 1;
2913         }
2914
2915         /*
2916          * If the page table is zapped by other cpus, let CPU fault again on
2917          * the address.
2918          */
2919         return 0;
2920 }
2921 EXPORT_SYMBOL_GPL(handle_mmio_page_fault_common);
2922
2923 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr,
2924                                   u32 error_code, bool direct)
2925 {
2926         int ret;
2927
2928         ret = handle_mmio_page_fault_common(vcpu, addr, direct);
2929         WARN_ON(ret < 0);
2930         return ret;
2931 }
2932
2933 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
2934                                 u32 error_code, bool prefault)
2935 {
2936         gfn_t gfn;
2937         int r;
2938
2939         pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
2940
2941         if (unlikely(error_code & PFERR_RSVD_MASK))
2942                 return handle_mmio_page_fault(vcpu, gva, error_code, true);
2943
2944         r = mmu_topup_memory_caches(vcpu);
2945         if (r)
2946                 return r;
2947
2948         ASSERT(vcpu);
2949         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2950
2951         gfn = gva >> PAGE_SHIFT;
2952
2953         return nonpaging_map(vcpu, gva & PAGE_MASK,
2954                              error_code & PFERR_WRITE_MASK, gfn, prefault);
2955 }
2956
2957 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
2958 {
2959         struct kvm_arch_async_pf arch;
2960
2961         arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
2962         arch.gfn = gfn;
2963         arch.direct_map = vcpu->arch.mmu.direct_map;
2964         arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
2965
2966         return kvm_setup_async_pf(vcpu, gva, gfn, &arch);
2967 }
2968
2969 static bool can_do_async_pf(struct kvm_vcpu *vcpu)
2970 {
2971         if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
2972                      kvm_event_needs_reinjection(vcpu)))
2973                 return false;
2974
2975         return kvm_x86_ops->interrupt_allowed(vcpu);
2976 }
2977
2978 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
2979                          gva_t gva, pfn_t *pfn, bool write, bool *writable)
2980 {
2981         bool async;
2982
2983         *pfn = gfn_to_pfn_async(vcpu->kvm, gfn, &async, write, writable);
2984
2985         if (!async)
2986                 return false; /* *pfn has correct page already */
2987
2988         put_page(pfn_to_page(*pfn));
2989
2990         if (!prefault && can_do_async_pf(vcpu)) {
2991                 trace_kvm_try_async_get_page(gva, gfn);
2992                 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
2993                         trace_kvm_async_pf_doublefault(gva, gfn);
2994                         kvm_make_request(KVM_REQ_APF_HALT, vcpu);
2995                         return true;
2996                 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
2997                         return true;
2998         }
2999
3000         *pfn = gfn_to_pfn_prot(vcpu->kvm, gfn, write, writable);
3001
3002         return false;
3003 }
3004
3005 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
3006                           bool prefault)
3007 {
3008         pfn_t pfn;
3009         int r;
3010         int level;
3011         int force_pt_level;
3012         gfn_t gfn = gpa >> PAGE_SHIFT;
3013         unsigned long mmu_seq;
3014         int write = error_code & PFERR_WRITE_MASK;
3015         bool map_writable;
3016
3017         ASSERT(vcpu);
3018         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
3019
3020         if (unlikely(error_code & PFERR_RSVD_MASK))
3021                 return handle_mmio_page_fault(vcpu, gpa, error_code, true);
3022
3023         r = mmu_topup_memory_caches(vcpu);
3024         if (r)
3025                 return r;
3026
3027         force_pt_level = mapping_level_dirty_bitmap(vcpu, gfn);
3028         if (likely(!force_pt_level)) {
3029                 level = mapping_level(vcpu, gfn);
3030                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3031         } else
3032                 level = PT_PAGE_TABLE_LEVEL;
3033
3034         mmu_seq = vcpu->kvm->mmu_notifier_seq;
3035         smp_rmb();
3036
3037         if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3038                 return 0;
3039
3040         if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
3041                 return r;
3042
3043         spin_lock(&vcpu->kvm->mmu_lock);
3044         if (mmu_notifier_retry(vcpu, mmu_seq))
3045                 goto out_unlock;
3046         kvm_mmu_free_some_pages(vcpu);
3047         if (likely(!force_pt_level))
3048                 transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
3049         r = __direct_map(vcpu, gpa, write, map_writable,
3050                          level, gfn, pfn, prefault);
3051         spin_unlock(&vcpu->kvm->mmu_lock);
3052
3053         return r;
3054
3055 out_unlock:
3056         spin_unlock(&vcpu->kvm->mmu_lock);
3057         kvm_release_pfn_clean(pfn);
3058         return 0;
3059 }
3060
3061 static void nonpaging_free(struct kvm_vcpu *vcpu)
3062 {
3063         mmu_free_roots(vcpu);
3064 }
3065
3066 static int nonpaging_init_context(struct kvm_vcpu *vcpu,
3067                                   struct kvm_mmu *context)
3068 {
3069         context->new_cr3 = nonpaging_new_cr3;
3070         context->page_fault = nonpaging_page_fault;
3071         context->gva_to_gpa = nonpaging_gva_to_gpa;
3072         context->free = nonpaging_free;
3073         context->sync_page = nonpaging_sync_page;
3074         context->invlpg = nonpaging_invlpg;
3075         context->update_pte = nonpaging_update_pte;
3076         context->root_level = 0;
3077         context->shadow_root_level = PT32E_ROOT_LEVEL;
3078         context->root_hpa = INVALID_PAGE;
3079         context->direct_map = true;
3080         context->nx = false;
3081         return 0;
3082 }
3083
3084 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
3085 {
3086         ++vcpu->stat.tlb_flush;
3087         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3088 }
3089
3090 static void paging_new_cr3(struct kvm_vcpu *vcpu)
3091 {
3092         pgprintk("%s: cr3 %lx\n", __func__, kvm_read_cr3(vcpu));
3093         mmu_free_roots(vcpu);
3094 }
3095
3096 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
3097 {
3098         return kvm_read_cr3(vcpu);
3099 }
3100
3101 static void inject_page_fault(struct kvm_vcpu *vcpu,
3102                               struct x86_exception *fault)
3103 {
3104         vcpu->arch.mmu.inject_page_fault(vcpu, fault);
3105 }
3106
3107 static void paging_free(struct kvm_vcpu *vcpu)
3108 {
3109         nonpaging_free(vcpu);
3110 }
3111
3112 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3113 {
3114         int bit7;
3115
3116         bit7 = (gpte >> 7) & 1;
3117         return (gpte & mmu->rsvd_bits_mask[bit7][level-1]) != 0;
3118 }
3119
3120 static bool sync_mmio_spte(u64 *sptep, gfn_t gfn, unsigned access,
3121                            int *nr_present)
3122 {
3123         if (unlikely(is_mmio_spte(*sptep))) {
3124                 if (gfn != get_mmio_spte_gfn(*sptep)) {
3125                         mmu_spte_clear_no_track(sptep);
3126                         return true;
3127                 }
3128
3129                 (*nr_present)++;
3130                 mark_mmio_spte(sptep, gfn, access);
3131                 return true;
3132         }
3133
3134         return false;
3135 }
3136
3137 #define PTTYPE 64
3138 #include "paging_tmpl.h"
3139 #undef PTTYPE
3140
3141 #define PTTYPE 32
3142 #include "paging_tmpl.h"
3143 #undef PTTYPE
3144
3145 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
3146                                   struct kvm_mmu *context,
3147                                   int level)
3148 {
3149         int maxphyaddr = cpuid_maxphyaddr(vcpu);
3150         u64 exb_bit_rsvd = 0;
3151
3152         if (!context->nx)
3153                 exb_bit_rsvd = rsvd_bits(63, 63);
3154         switch (level) {
3155         case PT32_ROOT_LEVEL:
3156                 /* no rsvd bits for 2 level 4K page table entries */
3157                 context->rsvd_bits_mask[0][1] = 0;
3158                 context->rsvd_bits_mask[0][0] = 0;
3159                 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0];
3160
3161                 if (!is_pse(vcpu)) {
3162                         context->rsvd_bits_mask[1][1] = 0;
3163                         break;
3164                 }
3165
3166                 if (is_cpuid_PSE36())
3167                         /* 36bits PSE 4MB page */
3168                         context->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
3169                 else
3170                         /* 32 bits PSE 4MB page */
3171                         context->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
3172                 break;
3173         case PT32E_ROOT_LEVEL:
3174                 context->rsvd_bits_mask[0][2] =
3175                         rsvd_bits(maxphyaddr, 63) |
3176                         rsvd_bits(7, 8) | rsvd_bits(1, 2);      /* PDPTE */
3177                 context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3178                         rsvd_bits(maxphyaddr, 62);      /* PDE */
3179                 context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3180                         rsvd_bits(maxphyaddr, 62);      /* PTE */
3181                 context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3182                         rsvd_bits(maxphyaddr, 62) |
3183                         rsvd_bits(13, 20);              /* large page */
3184                 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0];
3185                 break;
3186         case PT64_ROOT_LEVEL:
3187                 context->rsvd_bits_mask[0][3] = exb_bit_rsvd |
3188                         rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
3189                 context->rsvd_bits_mask[0][2] = exb_bit_rsvd |
3190                         rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
3191                 context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
3192                         rsvd_bits(maxphyaddr, 51);
3193                 context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
3194                         rsvd_bits(maxphyaddr, 51);
3195                 context->rsvd_bits_mask[1][3] = context->rsvd_bits_mask[0][3];
3196                 context->rsvd_bits_mask[1][2] = exb_bit_rsvd |
3197                         rsvd_bits(maxphyaddr, 51) |
3198                         rsvd_bits(13, 29);
3199                 context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
3200                         rsvd_bits(maxphyaddr, 51) |
3201                         rsvd_bits(13, 20);              /* large page */
3202                 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0];
3203                 break;
3204         }
3205 }
3206
3207 static int paging64_init_context_common(struct kvm_vcpu *vcpu,
3208                                         struct kvm_mmu *context,
3209                                         int level)
3210 {
3211         context->nx = is_nx(vcpu);
3212
3213         reset_rsvds_bits_mask(vcpu, context, level);
3214
3215         ASSERT(is_pae(vcpu));
3216         context->new_cr3 = paging_new_cr3;
3217         context->page_fault = paging64_page_fault;
3218         context->gva_to_gpa = paging64_gva_to_gpa;
3219         context->sync_page = paging64_sync_page;
3220         context->invlpg = paging64_invlpg;
3221         context->update_pte = paging64_update_pte;
3222         context->free = paging_free;
3223         context->root_level = level;
3224         context->shadow_root_level = level;
3225         context->root_hpa = INVALID_PAGE;
3226         context->direct_map = false;
3227         return 0;
3228 }
3229
3230 static int paging64_init_context(struct kvm_vcpu *vcpu,
3231                                  struct kvm_mmu *context)
3232 {
3233         return paging64_init_context_common(vcpu, context, PT64_ROOT_LEVEL);
3234 }
3235
3236 static int paging32_init_context(struct kvm_vcpu *vcpu,
3237                                  struct kvm_mmu *context)
3238 {
3239         context->nx = false;
3240
3241         reset_rsvds_bits_mask(vcpu, context, PT32_ROOT_LEVEL);
3242
3243         context->new_cr3 = paging_new_cr3;
3244         context->page_fault = paging32_page_fault;
3245         context->gva_to_gpa = paging32_gva_to_gpa;
3246         context->free = paging_free;
3247         context->sync_page = paging32_sync_page;
3248         context->invlpg = paging32_invlpg;
3249         context->update_pte = paging32_update_pte;
3250         context->root_level = PT32_ROOT_LEVEL;
3251         context->shadow_root_level = PT32E_ROOT_LEVEL;
3252         context->root_hpa = INVALID_PAGE;
3253         context->direct_map = false;
3254         return 0;
3255 }
3256
3257 static int paging32E_init_context(struct kvm_vcpu *vcpu,
3258                                   struct kvm_mmu *context)
3259 {
3260         return paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
3261 }
3262
3263 static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
3264 {
3265         struct kvm_mmu *context = vcpu->arch.walk_mmu;
3266
3267         context->base_role.word = 0;
3268         context->new_cr3 = nonpaging_new_cr3;
3269         context->page_fault = tdp_page_fault;
3270         context->free = nonpaging_free;
3271         context->sync_page = nonpaging_sync_page;
3272         context->invlpg = nonpaging_invlpg;
3273         context->update_pte = nonpaging_update_pte;
3274         context->shadow_root_level = kvm_x86_ops->get_tdp_level();
3275         context->root_hpa = INVALID_PAGE;
3276         context->direct_map = true;
3277         context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
3278         context->get_cr3 = get_cr3;
3279         context->get_pdptr = kvm_pdptr_read;
3280         context->inject_page_fault = kvm_inject_page_fault;
3281         context->nx = is_nx(vcpu);
3282
3283         if (!is_paging(vcpu)) {
3284                 context->nx = false;
3285                 context->gva_to_gpa = nonpaging_gva_to_gpa;
3286                 context->root_level = 0;
3287         } else if (is_long_mode(vcpu)) {
3288                 context->nx = is_nx(vcpu);
3289                 reset_rsvds_bits_mask(vcpu, context, PT64_ROOT_LEVEL);
3290                 context->gva_to_gpa = paging64_gva_to_gpa;
3291                 context->root_level = PT64_ROOT_LEVEL;
3292         } else if (is_pae(vcpu)) {
3293                 context->nx = is_nx(vcpu);
3294                 reset_rsvds_bits_mask(vcpu, context, PT32E_ROOT_LEVEL);
3295                 context->gva_to_gpa = paging64_gva_to_gpa;
3296                 context->root_level = PT32E_ROOT_LEVEL;
3297         } else {
3298                 context->nx = false;
3299                 reset_rsvds_bits_mask(vcpu, context, PT32_ROOT_LEVEL);
3300                 context->gva_to_gpa = paging32_gva_to_gpa;
3301                 context->root_level = PT32_ROOT_LEVEL;
3302         }
3303
3304         return 0;
3305 }
3306
3307 int kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
3308 {
3309         int r;
3310         bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
3311         ASSERT(vcpu);
3312         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3313
3314         if (!is_paging(vcpu))
3315                 r = nonpaging_init_context(vcpu, context);
3316         else if (is_long_mode(vcpu))
3317                 r = paging64_init_context(vcpu, context);
3318         else if (is_pae(vcpu))
3319                 r = paging32E_init_context(vcpu, context);
3320         else
3321                 r = paging32_init_context(vcpu, context);
3322
3323         vcpu->arch.mmu.base_role.cr4_pae = !!is_pae(vcpu);
3324         vcpu->arch.mmu.base_role.cr0_wp  = is_write_protection(vcpu);
3325         vcpu->arch.mmu.base_role.smep_andnot_wp
3326                 = smep && !is_write_protection(vcpu);
3327
3328         return r;
3329 }
3330 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
3331
3332 static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
3333 {
3334         int r = kvm_init_shadow_mmu(vcpu, vcpu->arch.walk_mmu);
3335
3336         vcpu->arch.walk_mmu->set_cr3           = kvm_x86_ops->set_cr3;
3337         vcpu->arch.walk_mmu->get_cr3           = get_cr3;
3338         vcpu->arch.walk_mmu->get_pdptr         = kvm_pdptr_read;
3339         vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
3340
3341         return r;
3342 }
3343
3344 static int init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
3345 {
3346         struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
3347
3348         g_context->get_cr3           = get_cr3;
3349         g_context->get_pdptr         = kvm_pdptr_read;
3350         g_context->inject_page_fault = kvm_inject_page_fault;
3351
3352         /*
3353          * Note that arch.mmu.gva_to_gpa translates l2_gva to l1_gpa. The
3354          * translation of l2_gpa to l1_gpa addresses is done using the
3355          * arch.nested_mmu.gva_to_gpa function. Basically the gva_to_gpa
3356          * functions between mmu and nested_mmu are swapped.
3357          */
3358         if (!is_paging(vcpu)) {
3359                 g_context->nx = false;
3360                 g_context->root_level = 0;
3361                 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
3362         } else if (is_long_mode(vcpu)) {
3363                 g_context->nx = is_nx(vcpu);
3364                 reset_rsvds_bits_mask(vcpu, g_context, PT64_ROOT_LEVEL);
3365                 g_context->root_level = PT64_ROOT_LEVEL;
3366                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
3367         } else if (is_pae(vcpu)) {
3368                 g_context->nx = is_nx(vcpu);
3369                 reset_rsvds_bits_mask(vcpu, g_context, PT32E_ROOT_LEVEL);
3370                 g_context->root_level = PT32E_ROOT_LEVEL;
3371                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
3372         } else {
3373                 g_context->nx = false;
3374                 reset_rsvds_bits_mask(vcpu, g_context, PT32_ROOT_LEVEL);
3375                 g_context->root_level = PT32_ROOT_LEVEL;
3376                 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
3377         }
3378
3379         return 0;
3380 }
3381
3382 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
3383 {
3384         if (mmu_is_nested(vcpu))
3385                 return init_kvm_nested_mmu(vcpu);
3386         else if (tdp_enabled)
3387                 return init_kvm_tdp_mmu(vcpu);
3388         else
3389                 return init_kvm_softmmu(vcpu);
3390 }
3391
3392 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
3393 {
3394         ASSERT(vcpu);
3395         if (VALID_PAGE(vcpu->arch.mmu.root_hpa))
3396                 /* mmu.free() should set root_hpa = INVALID_PAGE */
3397                 vcpu->arch.mmu.free(vcpu);
3398 }
3399
3400 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
3401 {
3402         destroy_kvm_mmu(vcpu);
3403         return init_kvm_mmu(vcpu);
3404 }
3405 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
3406
3407 int kvm_mmu_load(struct kvm_vcpu *vcpu)
3408 {
3409         int r;
3410
3411         r = mmu_topup_memory_caches(vcpu);
3412         if (r)
3413                 goto out;
3414         r = mmu_alloc_roots(vcpu);
3415         spin_lock(&vcpu->kvm->mmu_lock);
3416         mmu_sync_roots(vcpu);
3417         spin_unlock(&vcpu->kvm->mmu_lock);
3418         if (r)
3419                 goto out;
3420         /* set_cr3() should ensure TLB has been flushed */
3421         vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
3422 out:
3423         return r;
3424 }
3425 EXPORT_SYMBOL_GPL(kvm_mmu_load);
3426
3427 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
3428 {
3429         mmu_free_roots(vcpu);
3430 }
3431 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
3432
3433 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
3434                                   struct kvm_mmu_page *sp, u64 *spte,
3435                                   const void *new)
3436 {
3437         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
3438                 ++vcpu->kvm->stat.mmu_pde_zapped;
3439                 return;
3440         }
3441
3442         ++vcpu->kvm->stat.mmu_pte_updated;
3443         vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
3444 }
3445
3446 static bool need_remote_flush(u64 old, u64 new)
3447 {
3448         if (!is_shadow_present_pte(old))
3449                 return false;
3450         if (!is_shadow_present_pte(new))
3451                 return true;
3452         if ((old ^ new) & PT64_BASE_ADDR_MASK)
3453                 return true;
3454         old ^= PT64_NX_MASK;
3455         new ^= PT64_NX_MASK;
3456         return (old & ~new & PT64_PERM_MASK) != 0;
3457 }
3458
3459 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, bool zap_page,
3460                                     bool remote_flush, bool local_flush)
3461 {
3462         if (zap_page)
3463                 return;
3464
3465         if (remote_flush)
3466                 kvm_flush_remote_tlbs(vcpu->kvm);
3467         else if (local_flush)
3468                 kvm_mmu_flush_tlb(vcpu);
3469 }
3470
3471 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
3472 {
3473         u64 *spte = vcpu->arch.last_pte_updated;
3474
3475         return !!(spte && (*spte & shadow_accessed_mask));
3476 }
3477
3478 static void kvm_mmu_access_page(struct kvm_vcpu *vcpu, gfn_t gfn)
3479 {
3480         u64 *spte = vcpu->arch.last_pte_updated;
3481
3482         if (spte
3483             && vcpu->arch.last_pte_gfn == gfn
3484             && shadow_accessed_mask
3485             && !(*spte & shadow_accessed_mask)
3486             && is_shadow_present_pte(*spte))
3487                 set_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
3488 }
3489
3490 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
3491                        const u8 *new, int bytes,
3492                        bool guest_initiated)
3493 {
3494         gfn_t gfn = gpa >> PAGE_SHIFT;
3495         union kvm_mmu_page_role mask = { .word = 0 };
3496         struct kvm_mmu_page *sp;
3497         struct hlist_node *node;
3498         LIST_HEAD(invalid_list);
3499         u64 entry, gentry, *spte;
3500         unsigned pte_size, page_offset, misaligned, quadrant, offset;
3501         int level, npte, invlpg_counter, r, flooded = 0;
3502         bool remote_flush, local_flush, zap_page;
3503
3504         /*
3505          * If we don't have indirect shadow pages, it means no page is
3506          * write-protected, so we can exit simply.
3507          */
3508         if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
3509                 return;
3510
3511         zap_page = remote_flush = local_flush = false;
3512         offset = offset_in_page(gpa);
3513
3514         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
3515
3516         invlpg_counter = atomic_read(&vcpu->kvm->arch.invlpg_counter);
3517
3518         /*
3519          * Assume that the pte write on a page table of the same type
3520          * as the current vcpu paging mode since we update the sptes only
3521          * when they have the same mode.
3522          */
3523         if ((is_pae(vcpu) && bytes == 4) || !new) {
3524                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
3525                 if (is_pae(vcpu)) {
3526                         gpa &= ~(gpa_t)7;
3527                         bytes = 8;
3528                 }
3529                 r = kvm_read_guest(vcpu->kvm, gpa, &gentry, min(bytes, 8));
3530                 if (r)
3531                         gentry = 0;
3532                 new = (const u8 *)&gentry;
3533         }
3534
3535         switch (bytes) {
3536         case 4:
3537                 gentry = *(const u32 *)new;
3538                 break;
3539         case 8:
3540                 gentry = *(const u64 *)new;
3541                 break;
3542         default:
3543                 gentry = 0;
3544                 break;
3545         }
3546
3547         spin_lock(&vcpu->kvm->mmu_lock);
3548         if (atomic_read(&vcpu->kvm->arch.invlpg_counter) != invlpg_counter)
3549                 gentry = 0;
3550         kvm_mmu_free_some_pages(vcpu);
3551         ++vcpu->kvm->stat.mmu_pte_write;
3552         trace_kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
3553         if (guest_initiated) {
3554                 kvm_mmu_access_page(vcpu, gfn);
3555                 if (gfn == vcpu->arch.last_pt_write_gfn
3556                     && !last_updated_pte_accessed(vcpu)) {
3557                         ++vcpu->arch.last_pt_write_count;
3558                         if (vcpu->arch.last_pt_write_count >= 3)
3559                                 flooded = 1;
3560                 } else {
3561                         vcpu->arch.last_pt_write_gfn = gfn;
3562                         vcpu->arch.last_pt_write_count = 1;
3563                         vcpu->arch.last_pte_updated = NULL;
3564                 }
3565         }
3566
3567         mask.cr0_wp = mask.cr4_pae = mask.nxe = mask.smep_andnot_wp = 1;
3568         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn, node) {
3569                 pte_size = sp->role.cr4_pae ? 8 : 4;
3570                 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
3571                 misaligned |= bytes < 4;
3572                 if (misaligned || flooded) {
3573                         /*
3574                          * Misaligned accesses are too much trouble to fix
3575                          * up; also, they usually indicate a page is not used
3576                          * as a page table.
3577                          *
3578                          * If we're seeing too many writes to a page,
3579                          * it may no longer be a page table, or we may be
3580                          * forking, in which case it is better to unmap the
3581                          * page.
3582                          */
3583                         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
3584                                  gpa, bytes, sp->role.word);
3585                         zap_page |= !!kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
3586                                                      &invalid_list);
3587                         ++vcpu->kvm->stat.mmu_flooded;
3588                         continue;
3589                 }
3590                 page_offset = offset;
3591                 level = sp->role.level;
3592                 npte = 1;
3593                 if (!sp->role.cr4_pae) {
3594                         page_offset <<= 1;      /* 32->64 */
3595                         /*
3596                          * A 32-bit pde maps 4MB while the shadow pdes map
3597                          * only 2MB.  So we need to double the offset again
3598                          * and zap two pdes instead of one.
3599                          */
3600                         if (level == PT32_ROOT_LEVEL) {
3601                                 page_offset &= ~7; /* kill rounding error */
3602                                 page_offset <<= 1;
3603                                 npte = 2;
3604                         }
3605                         quadrant = page_offset >> PAGE_SHIFT;
3606                         page_offset &= ~PAGE_MASK;
3607                         if (quadrant != sp->role.quadrant)
3608                                 continue;
3609                 }
3610                 local_flush = true;
3611                 spte = &sp->spt[page_offset / sizeof(*spte)];
3612                 while (npte--) {
3613                         entry = *spte;
3614                         mmu_page_zap_pte(vcpu->kvm, sp, spte);
3615                         if (gentry &&
3616                               !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
3617                               & mask.word))
3618                                 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
3619                         if (!remote_flush && need_remote_flush(entry, *spte))
3620                                 remote_flush = true;
3621                         ++spte;
3622                 }
3623         }
3624         mmu_pte_write_flush_tlb(vcpu, zap_page, remote_flush, local_flush);
3625         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3626         trace_kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
3627         spin_unlock(&vcpu->kvm->mmu_lock);
3628 }
3629
3630 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
3631 {
3632         gpa_t gpa;
3633         int r;
3634
3635         if (vcpu->arch.mmu.direct_map)
3636                 return 0;
3637
3638         gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
3639
3640         spin_lock(&vcpu->kvm->mmu_lock);
3641         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
3642         spin_unlock(&vcpu->kvm->mmu_lock);
3643         return r;
3644 }
3645 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
3646
3647 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
3648 {
3649         LIST_HEAD(invalid_list);
3650
3651         while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES &&
3652                !list_empty(&vcpu->kvm->arch.active_mmu_pages)) {
3653                 struct kvm_mmu_page *sp;
3654
3655                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
3656                                   struct kvm_mmu_page, link);
3657                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
3658                 ++vcpu->kvm->stat.mmu_recycled;
3659         }
3660         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3661 }
3662
3663 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code,
3664                        void *insn, int insn_len)
3665 {
3666         int r;
3667         enum emulation_result er;
3668
3669         r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
3670         if (r < 0)
3671                 goto out;
3672
3673         if (!r) {
3674                 r = 1;
3675                 goto out;
3676         }
3677
3678         r = mmu_topup_memory_caches(vcpu);
3679         if (r)
3680                 goto out;
3681
3682         er = x86_emulate_instruction(vcpu, cr2, 0, insn, insn_len);
3683
3684         switch (er) {
3685         case EMULATE_DONE:
3686                 return 1;
3687         case EMULATE_DO_MMIO:
3688                 ++vcpu->stat.mmio_exits;
3689                 /* fall through */
3690         case EMULATE_FAIL:
3691                 return 0;
3692         default:
3693                 BUG();
3694         }
3695 out:
3696         return r;
3697 }
3698 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
3699
3700 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
3701 {
3702         vcpu->arch.mmu.invlpg(vcpu, gva);
3703         kvm_mmu_flush_tlb(vcpu);
3704         ++vcpu->stat.invlpg;
3705 }
3706 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
3707
3708 void kvm_enable_tdp(void)
3709 {
3710         tdp_enabled = true;
3711 }
3712 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
3713
3714 void kvm_disable_tdp(void)
3715 {
3716         tdp_enabled = false;
3717 }
3718 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
3719
3720 static void free_mmu_pages(struct kvm_vcpu *vcpu)
3721 {
3722         free_page((unsigned long)vcpu->arch.mmu.pae_root);
3723         if (vcpu->arch.mmu.lm_root != NULL)
3724                 free_page((unsigned long)vcpu->arch.mmu.lm_root);
3725 }
3726
3727 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
3728 {
3729         struct page *page;
3730         int i;
3731
3732         ASSERT(vcpu);
3733
3734         /*
3735          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
3736          * Therefore we need to allocate shadow page tables in the first
3737          * 4GB of memory, which happens to fit the DMA32 zone.
3738          */
3739         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
3740         if (!page)
3741                 return -ENOMEM;
3742
3743         vcpu->arch.mmu.pae_root = page_address(page);
3744         for (i = 0; i < 4; ++i)
3745                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
3746
3747         return 0;
3748 }
3749
3750 int kvm_mmu_create(struct kvm_vcpu *vcpu)
3751 {
3752         ASSERT(vcpu);
3753         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3754
3755         return alloc_mmu_pages(vcpu);
3756 }
3757
3758 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
3759 {
3760         ASSERT(vcpu);
3761         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3762
3763         return init_kvm_mmu(vcpu);
3764 }
3765
3766 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
3767 {
3768         struct kvm_mmu_page *sp;
3769
3770         list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
3771                 int i;
3772                 u64 *pt;
3773
3774                 if (!test_bit(slot, sp->slot_bitmap))
3775                         continue;
3776
3777                 pt = sp->spt;
3778                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3779                         if (!is_shadow_present_pte(pt[i]) ||
3780                               !is_last_spte(pt[i], sp->role.level))
3781                                 continue;
3782
3783                         if (is_large_pte(pt[i])) {
3784                                 drop_spte(kvm, &pt[i]);
3785                                 --kvm->stat.lpages;
3786                                 continue;
3787                         }
3788
3789                         /* avoid RMW */
3790                         if (is_writable_pte(pt[i]))
3791                                 mmu_spte_update(&pt[i],
3792                                                 pt[i] & ~PT_WRITABLE_MASK);
3793                 }
3794         }
3795         kvm_flush_remote_tlbs(kvm);
3796 }
3797
3798 void kvm_mmu_zap_all(struct kvm *kvm)
3799 {
3800         struct kvm_mmu_page *sp, *node;
3801         LIST_HEAD(invalid_list);
3802
3803         spin_lock(&kvm->mmu_lock);
3804 restart:
3805         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
3806                 if (kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list))
3807                         goto restart;
3808
3809         kvm_mmu_commit_zap_page(kvm, &invalid_list);
3810         spin_unlock(&kvm->mmu_lock);
3811 }
3812
3813 static int kvm_mmu_remove_some_alloc_mmu_pages(struct kvm *kvm,
3814                                                struct list_head *invalid_list)
3815 {
3816         struct kvm_mmu_page *page;
3817
3818         page = container_of(kvm->arch.active_mmu_pages.prev,
3819                             struct kvm_mmu_page, link);
3820         return kvm_mmu_prepare_zap_page(kvm, page, invalid_list);
3821 }
3822
3823 static int mmu_shrink(struct shrinker *shrink, struct shrink_control *sc)
3824 {
3825         struct kvm *kvm;
3826         struct kvm *kvm_freed = NULL;
3827         int nr_to_scan = sc->nr_to_scan;
3828
3829         if (nr_to_scan == 0)
3830                 goto out;
3831
3832         raw_spin_lock(&kvm_lock);
3833
3834         list_for_each_entry(kvm, &vm_list, vm_list) {
3835                 int idx, freed_pages;
3836                 LIST_HEAD(invalid_list);
3837
3838                 idx = srcu_read_lock(&kvm->srcu);
3839                 spin_lock(&kvm->mmu_lock);
3840                 if (!kvm_freed && nr_to_scan > 0 &&
3841                     kvm->arch.n_used_mmu_pages > 0) {
3842                         freed_pages = kvm_mmu_remove_some_alloc_mmu_pages(kvm,
3843                                                           &invalid_list);
3844                         kvm_freed = kvm;
3845                 }
3846                 nr_to_scan--;
3847
3848                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
3849                 spin_unlock(&kvm->mmu_lock);
3850                 srcu_read_unlock(&kvm->srcu, idx);
3851         }
3852         if (kvm_freed)
3853                 list_move_tail(&kvm_freed->vm_list, &vm_list);
3854
3855         raw_spin_unlock(&kvm_lock);
3856
3857 out:
3858         return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
3859 }
3860
3861 static struct shrinker mmu_shrinker = {
3862         .shrink = mmu_shrink,
3863         .seeks = DEFAULT_SEEKS * 10,
3864 };
3865
3866 static void mmu_destroy_caches(void)
3867 {
3868         if (pte_list_desc_cache)
3869                 kmem_cache_destroy(pte_list_desc_cache);
3870         if (mmu_page_header_cache)
3871                 kmem_cache_destroy(mmu_page_header_cache);
3872 }
3873
3874 int kvm_mmu_module_init(void)
3875 {
3876         pte_list_desc_cache = kmem_cache_create("pte_list_desc",
3877                                             sizeof(struct pte_list_desc),
3878                                             0, 0, NULL);
3879         if (!pte_list_desc_cache)
3880                 goto nomem;
3881
3882         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
3883                                                   sizeof(struct kvm_mmu_page),
3884                                                   0, 0, NULL);
3885         if (!mmu_page_header_cache)
3886                 goto nomem;
3887
3888         if (percpu_counter_init(&kvm_total_used_mmu_pages, 0))
3889                 goto nomem;
3890
3891         register_shrinker(&mmu_shrinker);
3892
3893         return 0;
3894
3895 nomem:
3896         mmu_destroy_caches();
3897         return -ENOMEM;
3898 }
3899
3900 /*
3901  * Caculate mmu pages needed for kvm.
3902  */
3903 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
3904 {
3905         int i;
3906         unsigned int nr_mmu_pages;
3907         unsigned int  nr_pages = 0;
3908         struct kvm_memslots *slots;
3909
3910         slots = kvm_memslots(kvm);
3911
3912         for (i = 0; i < slots->nmemslots; i++)
3913                 nr_pages += slots->memslots[i].npages;
3914
3915         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
3916         nr_mmu_pages = max(nr_mmu_pages,
3917                         (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
3918
3919         return nr_mmu_pages;
3920 }
3921
3922 static void *pv_mmu_peek_buffer(struct kvm_pv_mmu_op_buffer *buffer,
3923                                 unsigned len)
3924 {
3925         if (len > buffer->len)
3926                 return NULL;
3927         return buffer->ptr;
3928 }
3929
3930 static void *pv_mmu_read_buffer(struct kvm_pv_mmu_op_buffer *buffer,
3931                                 unsigned len)
3932 {
3933         void *ret;
3934
3935         ret = pv_mmu_peek_buffer(buffer, len);
3936         if (!ret)
3937                 return ret;
3938         buffer->ptr += len;
3939         buffer->len -= len;
3940         buffer->processed += len;
3941         return ret;
3942 }
3943
3944 static int kvm_pv_mmu_write(struct kvm_vcpu *vcpu,
3945                              gpa_t addr, gpa_t value)
3946 {
3947         int bytes = 8;
3948         int r;
3949
3950         if (!is_long_mode(vcpu) && !is_pae(vcpu))
3951                 bytes = 4;
3952
3953         r = mmu_topup_memory_caches(vcpu);
3954         if (r)
3955                 return r;
3956
3957         if (!emulator_write_phys(vcpu, addr, &value, bytes))
3958                 return -EFAULT;
3959
3960         return 1;
3961 }
3962
3963 static int kvm_pv_mmu_flush_tlb(struct kvm_vcpu *vcpu)
3964 {
3965         (void)kvm_set_cr3(vcpu, kvm_read_cr3(vcpu));
3966         return 1;
3967 }
3968
3969 static int kvm_pv_mmu_release_pt(struct kvm_vcpu *vcpu, gpa_t addr)
3970 {
3971         spin_lock(&vcpu->kvm->mmu_lock);
3972         mmu_unshadow(vcpu->kvm, addr >> PAGE_SHIFT);
3973         spin_unlock(&vcpu->kvm->mmu_lock);
3974         return 1;
3975 }
3976
3977 static int kvm_pv_mmu_op_one(struct kvm_vcpu *vcpu,
3978                              struct kvm_pv_mmu_op_buffer *buffer)
3979 {
3980         struct kvm_mmu_op_header *header;
3981
3982         header = pv_mmu_peek_buffer(buffer, sizeof *header);
3983         if (!header)
3984                 return 0;
3985         switch (header->op) {
3986         case KVM_MMU_OP_WRITE_PTE: {
3987                 struct kvm_mmu_op_write_pte *wpte;
3988
3989                 wpte = pv_mmu_read_buffer(buffer, sizeof *wpte);
3990                 if (!wpte)
3991                         return 0;
3992                 return kvm_pv_mmu_write(vcpu, wpte->pte_phys,
3993                                         wpte->pte_val);
3994         }
3995         case KVM_MMU_OP_FLUSH_TLB: {
3996                 struct kvm_mmu_op_flush_tlb *ftlb;
3997
3998                 ftlb = pv_mmu_read_buffer(buffer, sizeof *ftlb);
3999                 if (!ftlb)
4000                         return 0;
4001                 return kvm_pv_mmu_flush_tlb(vcpu);
4002         }
4003         case KVM_MMU_OP_RELEASE_PT: {
4004                 struct kvm_mmu_op_release_pt *rpt;
4005
4006                 rpt = pv_mmu_read_buffer(buffer, sizeof *rpt);
4007                 if (!rpt)
4008                         return 0;
4009                 return kvm_pv_mmu_release_pt(vcpu, rpt->pt_phys);
4010         }
4011         default: return 0;
4012         }
4013 }
4014
4015 int kvm_pv_mmu_op(struct kvm_vcpu *vcpu, unsigned long bytes,
4016                   gpa_t addr, unsigned long *ret)
4017 {
4018         int r;
4019         struct kvm_pv_mmu_op_buffer *buffer = &vcpu->arch.mmu_op_buffer;
4020
4021         buffer->ptr = buffer->buf;
4022         buffer->len = min_t(unsigned long, bytes, sizeof buffer->buf);
4023         buffer->processed = 0;
4024
4025         r = kvm_read_guest(vcpu->kvm, addr, buffer->buf, buffer->len);
4026         if (r)
4027                 goto out;
4028
4029         while (buffer->len) {
4030                 r = kvm_pv_mmu_op_one(vcpu, buffer);
4031                 if (r < 0)
4032                         goto out;
4033                 if (r == 0)
4034                         break;
4035         }
4036
4037         r = 1;
4038 out:
4039         *ret = buffer->processed;
4040         return r;
4041 }
4042
4043 int kvm_mmu_get_spte_hierarchy(struct kvm_vcpu *vcpu, u64 addr, u64 sptes[4])
4044 {
4045         struct kvm_shadow_walk_iterator iterator;
4046         u64 spte;
4047         int nr_sptes = 0;
4048
4049         walk_shadow_page_lockless_begin(vcpu);
4050         for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4051                 sptes[iterator.level-1] = spte;
4052                 nr_sptes++;
4053                 if (!is_shadow_present_pte(spte))
4054                         break;
4055         }
4056         walk_shadow_page_lockless_end(vcpu);
4057
4058         return nr_sptes;
4059 }
4060 EXPORT_SYMBOL_GPL(kvm_mmu_get_spte_hierarchy);
4061
4062 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
4063 {
4064         ASSERT(vcpu);
4065
4066         destroy_kvm_mmu(vcpu);
4067         free_mmu_pages(vcpu);
4068         mmu_free_memory_caches(vcpu);
4069 }
4070
4071 #ifdef CONFIG_KVM_MMU_AUDIT
4072 #include "mmu_audit.c"
4073 #else
4074 static void mmu_audit_disable(void) { }
4075 #endif
4076
4077 void kvm_mmu_module_exit(void)
4078 {
4079         mmu_destroy_caches();
4080         percpu_counter_destroy(&kvm_total_used_mmu_pages);
4081         unregister_shrinker(&mmu_shrinker);
4082         mmu_audit_disable();
4083 }