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