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