OSDN Git Service

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