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