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