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