Merge branch 'next' of git://git.kernel.org/pub/scm/linux/kernel/git/davej/cpufreq
[linux-2.6] / 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  *
11  * Authors:
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *   Avi Kivity   <avi@qumranet.com>
14  *
15  * This work is licensed under the terms of the GNU GPL, version 2.  See
16  * the COPYING file in the top-level directory.
17  *
18  */
19
20 #include "mmu.h"
21
22 #include <linux/kvm_host.h>
23 #include <linux/types.h>
24 #include <linux/string.h>
25 #include <linux/mm.h>
26 #include <linux/highmem.h>
27 #include <linux/module.h>
28 #include <linux/swap.h>
29 #include <linux/hugetlb.h>
30 #include <linux/compiler.h>
31
32 #include <asm/page.h>
33 #include <asm/cmpxchg.h>
34 #include <asm/io.h>
35 #include <asm/vmx.h>
36
37 /*
38  * When setting this variable to true it enables Two-Dimensional-Paging
39  * where the hardware walks 2 page tables:
40  * 1. the guest-virtual to guest-physical
41  * 2. while doing 1. it walks guest-physical to host-physical
42  * If the hardware supports that we don't need to do shadow paging.
43  */
44 bool tdp_enabled = false;
45
46 #undef MMU_DEBUG
47
48 #undef AUDIT
49
50 #ifdef AUDIT
51 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg);
52 #else
53 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg) {}
54 #endif
55
56 #ifdef MMU_DEBUG
57
58 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
59 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
60
61 #else
62
63 #define pgprintk(x...) do { } while (0)
64 #define rmap_printk(x...) do { } while (0)
65
66 #endif
67
68 #if defined(MMU_DEBUG) || defined(AUDIT)
69 static int dbg = 0;
70 module_param(dbg, bool, 0644);
71 #endif
72
73 static int oos_shadow = 1;
74 module_param(oos_shadow, bool, 0644);
75
76 #ifndef MMU_DEBUG
77 #define ASSERT(x) do { } while (0)
78 #else
79 #define ASSERT(x)                                                       \
80         if (!(x)) {                                                     \
81                 printk(KERN_WARNING "assertion failed %s:%d: %s\n",     \
82                        __FILE__, __LINE__, #x);                         \
83         }
84 #endif
85
86 #define PT_FIRST_AVAIL_BITS_SHIFT 9
87 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
88
89 #define VALID_PAGE(x) ((x) != INVALID_PAGE)
90
91 #define PT64_LEVEL_BITS 9
92
93 #define PT64_LEVEL_SHIFT(level) \
94                 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
95
96 #define PT64_LEVEL_MASK(level) \
97                 (((1ULL << PT64_LEVEL_BITS) - 1) << PT64_LEVEL_SHIFT(level))
98
99 #define PT64_INDEX(address, level)\
100         (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
101
102
103 #define PT32_LEVEL_BITS 10
104
105 #define PT32_LEVEL_SHIFT(level) \
106                 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
107
108 #define PT32_LEVEL_MASK(level) \
109                 (((1ULL << PT32_LEVEL_BITS) - 1) << PT32_LEVEL_SHIFT(level))
110
111 #define PT32_INDEX(address, level)\
112         (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
113
114
115 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
116 #define PT64_DIR_BASE_ADDR_MASK \
117         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
118
119 #define PT32_BASE_ADDR_MASK PAGE_MASK
120 #define PT32_DIR_BASE_ADDR_MASK \
121         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
122
123 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK \
124                         | PT64_NX_MASK)
125
126 #define PFERR_PRESENT_MASK (1U << 0)
127 #define PFERR_WRITE_MASK (1U << 1)
128 #define PFERR_USER_MASK (1U << 2)
129 #define PFERR_FETCH_MASK (1U << 4)
130
131 #define PT_DIRECTORY_LEVEL 2
132 #define PT_PAGE_TABLE_LEVEL 1
133
134 #define RMAP_EXT 4
135
136 #define ACC_EXEC_MASK    1
137 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
138 #define ACC_USER_MASK    PT_USER_MASK
139 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
140
141 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
142
143 struct kvm_rmap_desc {
144         u64 *shadow_ptes[RMAP_EXT];
145         struct kvm_rmap_desc *more;
146 };
147
148 struct kvm_shadow_walk {
149         int (*entry)(struct kvm_shadow_walk *walk, struct kvm_vcpu *vcpu,
150                      u64 addr, u64 *spte, int level);
151 };
152
153 struct kvm_unsync_walk {
154         int (*entry) (struct kvm_mmu_page *sp, struct kvm_unsync_walk *walk);
155 };
156
157 typedef int (*mmu_parent_walk_fn) (struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp);
158
159 static struct kmem_cache *pte_chain_cache;
160 static struct kmem_cache *rmap_desc_cache;
161 static struct kmem_cache *mmu_page_header_cache;
162
163 static u64 __read_mostly shadow_trap_nonpresent_pte;
164 static u64 __read_mostly shadow_notrap_nonpresent_pte;
165 static u64 __read_mostly shadow_base_present_pte;
166 static u64 __read_mostly shadow_nx_mask;
167 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
168 static u64 __read_mostly shadow_user_mask;
169 static u64 __read_mostly shadow_accessed_mask;
170 static u64 __read_mostly shadow_dirty_mask;
171 static u64 __read_mostly shadow_mt_mask;
172
173 void kvm_mmu_set_nonpresent_ptes(u64 trap_pte, u64 notrap_pte)
174 {
175         shadow_trap_nonpresent_pte = trap_pte;
176         shadow_notrap_nonpresent_pte = notrap_pte;
177 }
178 EXPORT_SYMBOL_GPL(kvm_mmu_set_nonpresent_ptes);
179
180 void kvm_mmu_set_base_ptes(u64 base_pte)
181 {
182         shadow_base_present_pte = base_pte;
183 }
184 EXPORT_SYMBOL_GPL(kvm_mmu_set_base_ptes);
185
186 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
187                 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 mt_mask)
188 {
189         shadow_user_mask = user_mask;
190         shadow_accessed_mask = accessed_mask;
191         shadow_dirty_mask = dirty_mask;
192         shadow_nx_mask = nx_mask;
193         shadow_x_mask = x_mask;
194         shadow_mt_mask = mt_mask;
195 }
196 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
197
198 static int is_write_protection(struct kvm_vcpu *vcpu)
199 {
200         return vcpu->arch.cr0 & X86_CR0_WP;
201 }
202
203 static int is_cpuid_PSE36(void)
204 {
205         return 1;
206 }
207
208 static int is_nx(struct kvm_vcpu *vcpu)
209 {
210         return vcpu->arch.shadow_efer & EFER_NX;
211 }
212
213 static int is_present_pte(unsigned long pte)
214 {
215         return pte & PT_PRESENT_MASK;
216 }
217
218 static int is_shadow_present_pte(u64 pte)
219 {
220         return pte != shadow_trap_nonpresent_pte
221                 && pte != shadow_notrap_nonpresent_pte;
222 }
223
224 static int is_large_pte(u64 pte)
225 {
226         return pte & PT_PAGE_SIZE_MASK;
227 }
228
229 static int is_writeble_pte(unsigned long pte)
230 {
231         return pte & PT_WRITABLE_MASK;
232 }
233
234 static int is_dirty_pte(unsigned long pte)
235 {
236         return pte & shadow_dirty_mask;
237 }
238
239 static int is_rmap_pte(u64 pte)
240 {
241         return is_shadow_present_pte(pte);
242 }
243
244 static pfn_t spte_to_pfn(u64 pte)
245 {
246         return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
247 }
248
249 static gfn_t pse36_gfn_delta(u32 gpte)
250 {
251         int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
252
253         return (gpte & PT32_DIR_PSE36_MASK) << shift;
254 }
255
256 static void set_shadow_pte(u64 *sptep, u64 spte)
257 {
258 #ifdef CONFIG_X86_64
259         set_64bit((unsigned long *)sptep, spte);
260 #else
261         set_64bit((unsigned long long *)sptep, spte);
262 #endif
263 }
264
265 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
266                                   struct kmem_cache *base_cache, int min)
267 {
268         void *obj;
269
270         if (cache->nobjs >= min)
271                 return 0;
272         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
273                 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
274                 if (!obj)
275                         return -ENOMEM;
276                 cache->objects[cache->nobjs++] = obj;
277         }
278         return 0;
279 }
280
281 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
282 {
283         while (mc->nobjs)
284                 kfree(mc->objects[--mc->nobjs]);
285 }
286
287 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
288                                        int min)
289 {
290         struct page *page;
291
292         if (cache->nobjs >= min)
293                 return 0;
294         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
295                 page = alloc_page(GFP_KERNEL);
296                 if (!page)
297                         return -ENOMEM;
298                 set_page_private(page, 0);
299                 cache->objects[cache->nobjs++] = page_address(page);
300         }
301         return 0;
302 }
303
304 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
305 {
306         while (mc->nobjs)
307                 free_page((unsigned long)mc->objects[--mc->nobjs]);
308 }
309
310 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
311 {
312         int r;
313
314         r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_chain_cache,
315                                    pte_chain_cache, 4);
316         if (r)
317                 goto out;
318         r = mmu_topup_memory_cache(&vcpu->arch.mmu_rmap_desc_cache,
319                                    rmap_desc_cache, 4);
320         if (r)
321                 goto out;
322         r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
323         if (r)
324                 goto out;
325         r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
326                                    mmu_page_header_cache, 4);
327 out:
328         return r;
329 }
330
331 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
332 {
333         mmu_free_memory_cache(&vcpu->arch.mmu_pte_chain_cache);
334         mmu_free_memory_cache(&vcpu->arch.mmu_rmap_desc_cache);
335         mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
336         mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
337 }
338
339 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc,
340                                     size_t size)
341 {
342         void *p;
343
344         BUG_ON(!mc->nobjs);
345         p = mc->objects[--mc->nobjs];
346         memset(p, 0, size);
347         return p;
348 }
349
350 static struct kvm_pte_chain *mmu_alloc_pte_chain(struct kvm_vcpu *vcpu)
351 {
352         return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_chain_cache,
353                                       sizeof(struct kvm_pte_chain));
354 }
355
356 static void mmu_free_pte_chain(struct kvm_pte_chain *pc)
357 {
358         kfree(pc);
359 }
360
361 static struct kvm_rmap_desc *mmu_alloc_rmap_desc(struct kvm_vcpu *vcpu)
362 {
363         return mmu_memory_cache_alloc(&vcpu->arch.mmu_rmap_desc_cache,
364                                       sizeof(struct kvm_rmap_desc));
365 }
366
367 static void mmu_free_rmap_desc(struct kvm_rmap_desc *rd)
368 {
369         kfree(rd);
370 }
371
372 /*
373  * Return the pointer to the largepage write count for a given
374  * gfn, handling slots that are not large page aligned.
375  */
376 static int *slot_largepage_idx(gfn_t gfn, struct kvm_memory_slot *slot)
377 {
378         unsigned long idx;
379
380         idx = (gfn / KVM_PAGES_PER_HPAGE) -
381               (slot->base_gfn / KVM_PAGES_PER_HPAGE);
382         return &slot->lpage_info[idx].write_count;
383 }
384
385 static void account_shadowed(struct kvm *kvm, gfn_t gfn)
386 {
387         int *write_count;
388
389         gfn = unalias_gfn(kvm, gfn);
390         write_count = slot_largepage_idx(gfn,
391                                          gfn_to_memslot_unaliased(kvm, gfn));
392         *write_count += 1;
393 }
394
395 static void unaccount_shadowed(struct kvm *kvm, gfn_t gfn)
396 {
397         int *write_count;
398
399         gfn = unalias_gfn(kvm, gfn);
400         write_count = slot_largepage_idx(gfn,
401                                          gfn_to_memslot_unaliased(kvm, gfn));
402         *write_count -= 1;
403         WARN_ON(*write_count < 0);
404 }
405
406 static int has_wrprotected_page(struct kvm *kvm, gfn_t gfn)
407 {
408         struct kvm_memory_slot *slot;
409         int *largepage_idx;
410
411         gfn = unalias_gfn(kvm, gfn);
412         slot = gfn_to_memslot_unaliased(kvm, gfn);
413         if (slot) {
414                 largepage_idx = slot_largepage_idx(gfn, slot);
415                 return *largepage_idx;
416         }
417
418         return 1;
419 }
420
421 static int host_largepage_backed(struct kvm *kvm, gfn_t gfn)
422 {
423         struct vm_area_struct *vma;
424         unsigned long addr;
425         int ret = 0;
426
427         addr = gfn_to_hva(kvm, gfn);
428         if (kvm_is_error_hva(addr))
429                 return ret;
430
431         down_read(&current->mm->mmap_sem);
432         vma = find_vma(current->mm, addr);
433         if (vma && is_vm_hugetlb_page(vma))
434                 ret = 1;
435         up_read(&current->mm->mmap_sem);
436
437         return ret;
438 }
439
440 static int is_largepage_backed(struct kvm_vcpu *vcpu, gfn_t large_gfn)
441 {
442         struct kvm_memory_slot *slot;
443
444         if (has_wrprotected_page(vcpu->kvm, large_gfn))
445                 return 0;
446
447         if (!host_largepage_backed(vcpu->kvm, large_gfn))
448                 return 0;
449
450         slot = gfn_to_memslot(vcpu->kvm, large_gfn);
451         if (slot && slot->dirty_bitmap)
452                 return 0;
453
454         return 1;
455 }
456
457 /*
458  * Take gfn and return the reverse mapping to it.
459  * Note: gfn must be unaliased before this function get called
460  */
461
462 static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn, int lpage)
463 {
464         struct kvm_memory_slot *slot;
465         unsigned long idx;
466
467         slot = gfn_to_memslot(kvm, gfn);
468         if (!lpage)
469                 return &slot->rmap[gfn - slot->base_gfn];
470
471         idx = (gfn / KVM_PAGES_PER_HPAGE) -
472               (slot->base_gfn / KVM_PAGES_PER_HPAGE);
473
474         return &slot->lpage_info[idx].rmap_pde;
475 }
476
477 /*
478  * Reverse mapping data structures:
479  *
480  * If rmapp bit zero is zero, then rmapp point to the shadw page table entry
481  * that points to page_address(page).
482  *
483  * If rmapp bit zero is one, (then rmap & ~1) points to a struct kvm_rmap_desc
484  * containing more mappings.
485  */
486 static void rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn, int lpage)
487 {
488         struct kvm_mmu_page *sp;
489         struct kvm_rmap_desc *desc;
490         unsigned long *rmapp;
491         int i;
492
493         if (!is_rmap_pte(*spte))
494                 return;
495         gfn = unalias_gfn(vcpu->kvm, gfn);
496         sp = page_header(__pa(spte));
497         sp->gfns[spte - sp->spt] = gfn;
498         rmapp = gfn_to_rmap(vcpu->kvm, gfn, lpage);
499         if (!*rmapp) {
500                 rmap_printk("rmap_add: %p %llx 0->1\n", spte, *spte);
501                 *rmapp = (unsigned long)spte;
502         } else if (!(*rmapp & 1)) {
503                 rmap_printk("rmap_add: %p %llx 1->many\n", spte, *spte);
504                 desc = mmu_alloc_rmap_desc(vcpu);
505                 desc->shadow_ptes[0] = (u64 *)*rmapp;
506                 desc->shadow_ptes[1] = spte;
507                 *rmapp = (unsigned long)desc | 1;
508         } else {
509                 rmap_printk("rmap_add: %p %llx many->many\n", spte, *spte);
510                 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
511                 while (desc->shadow_ptes[RMAP_EXT-1] && desc->more)
512                         desc = desc->more;
513                 if (desc->shadow_ptes[RMAP_EXT-1]) {
514                         desc->more = mmu_alloc_rmap_desc(vcpu);
515                         desc = desc->more;
516                 }
517                 for (i = 0; desc->shadow_ptes[i]; ++i)
518                         ;
519                 desc->shadow_ptes[i] = spte;
520         }
521 }
522
523 static void rmap_desc_remove_entry(unsigned long *rmapp,
524                                    struct kvm_rmap_desc *desc,
525                                    int i,
526                                    struct kvm_rmap_desc *prev_desc)
527 {
528         int j;
529
530         for (j = RMAP_EXT - 1; !desc->shadow_ptes[j] && j > i; --j)
531                 ;
532         desc->shadow_ptes[i] = desc->shadow_ptes[j];
533         desc->shadow_ptes[j] = NULL;
534         if (j != 0)
535                 return;
536         if (!prev_desc && !desc->more)
537                 *rmapp = (unsigned long)desc->shadow_ptes[0];
538         else
539                 if (prev_desc)
540                         prev_desc->more = desc->more;
541                 else
542                         *rmapp = (unsigned long)desc->more | 1;
543         mmu_free_rmap_desc(desc);
544 }
545
546 static void rmap_remove(struct kvm *kvm, u64 *spte)
547 {
548         struct kvm_rmap_desc *desc;
549         struct kvm_rmap_desc *prev_desc;
550         struct kvm_mmu_page *sp;
551         pfn_t pfn;
552         unsigned long *rmapp;
553         int i;
554
555         if (!is_rmap_pte(*spte))
556                 return;
557         sp = page_header(__pa(spte));
558         pfn = spte_to_pfn(*spte);
559         if (*spte & shadow_accessed_mask)
560                 kvm_set_pfn_accessed(pfn);
561         if (is_writeble_pte(*spte))
562                 kvm_release_pfn_dirty(pfn);
563         else
564                 kvm_release_pfn_clean(pfn);
565         rmapp = gfn_to_rmap(kvm, sp->gfns[spte - sp->spt], is_large_pte(*spte));
566         if (!*rmapp) {
567                 printk(KERN_ERR "rmap_remove: %p %llx 0->BUG\n", spte, *spte);
568                 BUG();
569         } else if (!(*rmapp & 1)) {
570                 rmap_printk("rmap_remove:  %p %llx 1->0\n", spte, *spte);
571                 if ((u64 *)*rmapp != spte) {
572                         printk(KERN_ERR "rmap_remove:  %p %llx 1->BUG\n",
573                                spte, *spte);
574                         BUG();
575                 }
576                 *rmapp = 0;
577         } else {
578                 rmap_printk("rmap_remove:  %p %llx many->many\n", spte, *spte);
579                 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
580                 prev_desc = NULL;
581                 while (desc) {
582                         for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i)
583                                 if (desc->shadow_ptes[i] == spte) {
584                                         rmap_desc_remove_entry(rmapp,
585                                                                desc, i,
586                                                                prev_desc);
587                                         return;
588                                 }
589                         prev_desc = desc;
590                         desc = desc->more;
591                 }
592                 BUG();
593         }
594 }
595
596 static u64 *rmap_next(struct kvm *kvm, unsigned long *rmapp, u64 *spte)
597 {
598         struct kvm_rmap_desc *desc;
599         struct kvm_rmap_desc *prev_desc;
600         u64 *prev_spte;
601         int i;
602
603         if (!*rmapp)
604                 return NULL;
605         else if (!(*rmapp & 1)) {
606                 if (!spte)
607                         return (u64 *)*rmapp;
608                 return NULL;
609         }
610         desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
611         prev_desc = NULL;
612         prev_spte = NULL;
613         while (desc) {
614                 for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i) {
615                         if (prev_spte == spte)
616                                 return desc->shadow_ptes[i];
617                         prev_spte = desc->shadow_ptes[i];
618                 }
619                 desc = desc->more;
620         }
621         return NULL;
622 }
623
624 static int rmap_write_protect(struct kvm *kvm, u64 gfn)
625 {
626         unsigned long *rmapp;
627         u64 *spte;
628         int write_protected = 0;
629
630         gfn = unalias_gfn(kvm, gfn);
631         rmapp = gfn_to_rmap(kvm, gfn, 0);
632
633         spte = rmap_next(kvm, rmapp, NULL);
634         while (spte) {
635                 BUG_ON(!spte);
636                 BUG_ON(!(*spte & PT_PRESENT_MASK));
637                 rmap_printk("rmap_write_protect: spte %p %llx\n", spte, *spte);
638                 if (is_writeble_pte(*spte)) {
639                         set_shadow_pte(spte, *spte & ~PT_WRITABLE_MASK);
640                         write_protected = 1;
641                 }
642                 spte = rmap_next(kvm, rmapp, spte);
643         }
644         if (write_protected) {
645                 pfn_t pfn;
646
647                 spte = rmap_next(kvm, rmapp, NULL);
648                 pfn = spte_to_pfn(*spte);
649                 kvm_set_pfn_dirty(pfn);
650         }
651
652         /* check for huge page mappings */
653         rmapp = gfn_to_rmap(kvm, gfn, 1);
654         spte = rmap_next(kvm, rmapp, NULL);
655         while (spte) {
656                 BUG_ON(!spte);
657                 BUG_ON(!(*spte & PT_PRESENT_MASK));
658                 BUG_ON((*spte & (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK)) != (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK));
659                 pgprintk("rmap_write_protect(large): spte %p %llx %lld\n", spte, *spte, gfn);
660                 if (is_writeble_pte(*spte)) {
661                         rmap_remove(kvm, spte);
662                         --kvm->stat.lpages;
663                         set_shadow_pte(spte, shadow_trap_nonpresent_pte);
664                         spte = NULL;
665                         write_protected = 1;
666                 }
667                 spte = rmap_next(kvm, rmapp, spte);
668         }
669
670         return write_protected;
671 }
672
673 static int kvm_unmap_rmapp(struct kvm *kvm, unsigned long *rmapp)
674 {
675         u64 *spte;
676         int need_tlb_flush = 0;
677
678         while ((spte = rmap_next(kvm, rmapp, NULL))) {
679                 BUG_ON(!(*spte & PT_PRESENT_MASK));
680                 rmap_printk("kvm_rmap_unmap_hva: spte %p %llx\n", spte, *spte);
681                 rmap_remove(kvm, spte);
682                 set_shadow_pte(spte, shadow_trap_nonpresent_pte);
683                 need_tlb_flush = 1;
684         }
685         return need_tlb_flush;
686 }
687
688 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
689                           int (*handler)(struct kvm *kvm, unsigned long *rmapp))
690 {
691         int i;
692         int retval = 0;
693
694         /*
695          * If mmap_sem isn't taken, we can look the memslots with only
696          * the mmu_lock by skipping over the slots with userspace_addr == 0.
697          */
698         for (i = 0; i < kvm->nmemslots; i++) {
699                 struct kvm_memory_slot *memslot = &kvm->memslots[i];
700                 unsigned long start = memslot->userspace_addr;
701                 unsigned long end;
702
703                 /* mmu_lock protects userspace_addr */
704                 if (!start)
705                         continue;
706
707                 end = start + (memslot->npages << PAGE_SHIFT);
708                 if (hva >= start && hva < end) {
709                         gfn_t gfn_offset = (hva - start) >> PAGE_SHIFT;
710                         retval |= handler(kvm, &memslot->rmap[gfn_offset]);
711                         retval |= handler(kvm,
712                                           &memslot->lpage_info[
713                                                   gfn_offset /
714                                                   KVM_PAGES_PER_HPAGE].rmap_pde);
715                 }
716         }
717
718         return retval;
719 }
720
721 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
722 {
723         return kvm_handle_hva(kvm, hva, kvm_unmap_rmapp);
724 }
725
726 static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp)
727 {
728         u64 *spte;
729         int young = 0;
730
731         /* always return old for EPT */
732         if (!shadow_accessed_mask)
733                 return 0;
734
735         spte = rmap_next(kvm, rmapp, NULL);
736         while (spte) {
737                 int _young;
738                 u64 _spte = *spte;
739                 BUG_ON(!(_spte & PT_PRESENT_MASK));
740                 _young = _spte & PT_ACCESSED_MASK;
741                 if (_young) {
742                         young = 1;
743                         clear_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
744                 }
745                 spte = rmap_next(kvm, rmapp, spte);
746         }
747         return young;
748 }
749
750 int kvm_age_hva(struct kvm *kvm, unsigned long hva)
751 {
752         return kvm_handle_hva(kvm, hva, kvm_age_rmapp);
753 }
754
755 #ifdef MMU_DEBUG
756 static int is_empty_shadow_page(u64 *spt)
757 {
758         u64 *pos;
759         u64 *end;
760
761         for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
762                 if (is_shadow_present_pte(*pos)) {
763                         printk(KERN_ERR "%s: %p %llx\n", __func__,
764                                pos, *pos);
765                         return 0;
766                 }
767         return 1;
768 }
769 #endif
770
771 static void kvm_mmu_free_page(struct kvm *kvm, struct kvm_mmu_page *sp)
772 {
773         ASSERT(is_empty_shadow_page(sp->spt));
774         list_del(&sp->link);
775         __free_page(virt_to_page(sp->spt));
776         __free_page(virt_to_page(sp->gfns));
777         kfree(sp);
778         ++kvm->arch.n_free_mmu_pages;
779 }
780
781 static unsigned kvm_page_table_hashfn(gfn_t gfn)
782 {
783         return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
784 }
785
786 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
787                                                u64 *parent_pte)
788 {
789         struct kvm_mmu_page *sp;
790
791         sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache, sizeof *sp);
792         sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
793         sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
794         set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
795         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
796         INIT_LIST_HEAD(&sp->oos_link);
797         ASSERT(is_empty_shadow_page(sp->spt));
798         bitmap_zero(sp->slot_bitmap, KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS);
799         sp->multimapped = 0;
800         sp->global = 1;
801         sp->parent_pte = parent_pte;
802         --vcpu->kvm->arch.n_free_mmu_pages;
803         return sp;
804 }
805
806 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
807                                     struct kvm_mmu_page *sp, u64 *parent_pte)
808 {
809         struct kvm_pte_chain *pte_chain;
810         struct hlist_node *node;
811         int i;
812
813         if (!parent_pte)
814                 return;
815         if (!sp->multimapped) {
816                 u64 *old = sp->parent_pte;
817
818                 if (!old) {
819                         sp->parent_pte = parent_pte;
820                         return;
821                 }
822                 sp->multimapped = 1;
823                 pte_chain = mmu_alloc_pte_chain(vcpu);
824                 INIT_HLIST_HEAD(&sp->parent_ptes);
825                 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
826                 pte_chain->parent_ptes[0] = old;
827         }
828         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link) {
829                 if (pte_chain->parent_ptes[NR_PTE_CHAIN_ENTRIES-1])
830                         continue;
831                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i)
832                         if (!pte_chain->parent_ptes[i]) {
833                                 pte_chain->parent_ptes[i] = parent_pte;
834                                 return;
835                         }
836         }
837         pte_chain = mmu_alloc_pte_chain(vcpu);
838         BUG_ON(!pte_chain);
839         hlist_add_head(&pte_chain->link, &sp->parent_ptes);
840         pte_chain->parent_ptes[0] = parent_pte;
841 }
842
843 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
844                                        u64 *parent_pte)
845 {
846         struct kvm_pte_chain *pte_chain;
847         struct hlist_node *node;
848         int i;
849
850         if (!sp->multimapped) {
851                 BUG_ON(sp->parent_pte != parent_pte);
852                 sp->parent_pte = NULL;
853                 return;
854         }
855         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
856                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
857                         if (!pte_chain->parent_ptes[i])
858                                 break;
859                         if (pte_chain->parent_ptes[i] != parent_pte)
860                                 continue;
861                         while (i + 1 < NR_PTE_CHAIN_ENTRIES
862                                 && pte_chain->parent_ptes[i + 1]) {
863                                 pte_chain->parent_ptes[i]
864                                         = pte_chain->parent_ptes[i + 1];
865                                 ++i;
866                         }
867                         pte_chain->parent_ptes[i] = NULL;
868                         if (i == 0) {
869                                 hlist_del(&pte_chain->link);
870                                 mmu_free_pte_chain(pte_chain);
871                                 if (hlist_empty(&sp->parent_ptes)) {
872                                         sp->multimapped = 0;
873                                         sp->parent_pte = NULL;
874                                 }
875                         }
876                         return;
877                 }
878         BUG();
879 }
880
881
882 static void mmu_parent_walk(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
883                             mmu_parent_walk_fn fn)
884 {
885         struct kvm_pte_chain *pte_chain;
886         struct hlist_node *node;
887         struct kvm_mmu_page *parent_sp;
888         int i;
889
890         if (!sp->multimapped && sp->parent_pte) {
891                 parent_sp = page_header(__pa(sp->parent_pte));
892                 fn(vcpu, parent_sp);
893                 mmu_parent_walk(vcpu, parent_sp, fn);
894                 return;
895         }
896         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
897                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
898                         if (!pte_chain->parent_ptes[i])
899                                 break;
900                         parent_sp = page_header(__pa(pte_chain->parent_ptes[i]));
901                         fn(vcpu, parent_sp);
902                         mmu_parent_walk(vcpu, parent_sp, fn);
903                 }
904 }
905
906 static void kvm_mmu_update_unsync_bitmap(u64 *spte)
907 {
908         unsigned int index;
909         struct kvm_mmu_page *sp = page_header(__pa(spte));
910
911         index = spte - sp->spt;
912         if (!__test_and_set_bit(index, sp->unsync_child_bitmap))
913                 sp->unsync_children++;
914         WARN_ON(!sp->unsync_children);
915 }
916
917 static void kvm_mmu_update_parents_unsync(struct kvm_mmu_page *sp)
918 {
919         struct kvm_pte_chain *pte_chain;
920         struct hlist_node *node;
921         int i;
922
923         if (!sp->parent_pte)
924                 return;
925
926         if (!sp->multimapped) {
927                 kvm_mmu_update_unsync_bitmap(sp->parent_pte);
928                 return;
929         }
930
931         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
932                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
933                         if (!pte_chain->parent_ptes[i])
934                                 break;
935                         kvm_mmu_update_unsync_bitmap(pte_chain->parent_ptes[i]);
936                 }
937 }
938
939 static int unsync_walk_fn(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
940 {
941         kvm_mmu_update_parents_unsync(sp);
942         return 1;
943 }
944
945 static void kvm_mmu_mark_parents_unsync(struct kvm_vcpu *vcpu,
946                                         struct kvm_mmu_page *sp)
947 {
948         mmu_parent_walk(vcpu, sp, unsync_walk_fn);
949         kvm_mmu_update_parents_unsync(sp);
950 }
951
952 static void nonpaging_prefetch_page(struct kvm_vcpu *vcpu,
953                                     struct kvm_mmu_page *sp)
954 {
955         int i;
956
957         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
958                 sp->spt[i] = shadow_trap_nonpresent_pte;
959 }
960
961 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
962                                struct kvm_mmu_page *sp)
963 {
964         return 1;
965 }
966
967 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
968 {
969 }
970
971 #define KVM_PAGE_ARRAY_NR 16
972
973 struct kvm_mmu_pages {
974         struct mmu_page_and_offset {
975                 struct kvm_mmu_page *sp;
976                 unsigned int idx;
977         } page[KVM_PAGE_ARRAY_NR];
978         unsigned int nr;
979 };
980
981 #define for_each_unsync_children(bitmap, idx)           \
982         for (idx = find_first_bit(bitmap, 512);         \
983              idx < 512;                                 \
984              idx = find_next_bit(bitmap, 512, idx+1))
985
986 int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
987                    int idx)
988 {
989         int i;
990
991         if (sp->unsync)
992                 for (i=0; i < pvec->nr; i++)
993                         if (pvec->page[i].sp == sp)
994                                 return 0;
995
996         pvec->page[pvec->nr].sp = sp;
997         pvec->page[pvec->nr].idx = idx;
998         pvec->nr++;
999         return (pvec->nr == KVM_PAGE_ARRAY_NR);
1000 }
1001
1002 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1003                            struct kvm_mmu_pages *pvec)
1004 {
1005         int i, ret, nr_unsync_leaf = 0;
1006
1007         for_each_unsync_children(sp->unsync_child_bitmap, i) {
1008                 u64 ent = sp->spt[i];
1009
1010                 if (is_shadow_present_pte(ent) && !is_large_pte(ent)) {
1011                         struct kvm_mmu_page *child;
1012                         child = page_header(ent & PT64_BASE_ADDR_MASK);
1013
1014                         if (child->unsync_children) {
1015                                 if (mmu_pages_add(pvec, child, i))
1016                                         return -ENOSPC;
1017
1018                                 ret = __mmu_unsync_walk(child, pvec);
1019                                 if (!ret)
1020                                         __clear_bit(i, sp->unsync_child_bitmap);
1021                                 else if (ret > 0)
1022                                         nr_unsync_leaf += ret;
1023                                 else
1024                                         return ret;
1025                         }
1026
1027                         if (child->unsync) {
1028                                 nr_unsync_leaf++;
1029                                 if (mmu_pages_add(pvec, child, i))
1030                                         return -ENOSPC;
1031                         }
1032                 }
1033         }
1034
1035         if (find_first_bit(sp->unsync_child_bitmap, 512) == 512)
1036                 sp->unsync_children = 0;
1037
1038         return nr_unsync_leaf;
1039 }
1040
1041 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1042                            struct kvm_mmu_pages *pvec)
1043 {
1044         if (!sp->unsync_children)
1045                 return 0;
1046
1047         mmu_pages_add(pvec, sp, 0);
1048         return __mmu_unsync_walk(sp, pvec);
1049 }
1050
1051 static struct kvm_mmu_page *kvm_mmu_lookup_page(struct kvm *kvm, gfn_t gfn)
1052 {
1053         unsigned index;
1054         struct hlist_head *bucket;
1055         struct kvm_mmu_page *sp;
1056         struct hlist_node *node;
1057
1058         pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1059         index = kvm_page_table_hashfn(gfn);
1060         bucket = &kvm->arch.mmu_page_hash[index];
1061         hlist_for_each_entry(sp, node, bucket, hash_link)
1062                 if (sp->gfn == gfn && !sp->role.metaphysical
1063                     && !sp->role.invalid) {
1064                         pgprintk("%s: found role %x\n",
1065                                  __func__, sp->role.word);
1066                         return sp;
1067                 }
1068         return NULL;
1069 }
1070
1071 static void kvm_unlink_unsync_global(struct kvm *kvm, struct kvm_mmu_page *sp)
1072 {
1073         list_del(&sp->oos_link);
1074         --kvm->stat.mmu_unsync_global;
1075 }
1076
1077 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1078 {
1079         WARN_ON(!sp->unsync);
1080         sp->unsync = 0;
1081         if (sp->global)
1082                 kvm_unlink_unsync_global(kvm, sp);
1083         --kvm->stat.mmu_unsync;
1084 }
1085
1086 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp);
1087
1088 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1089 {
1090         if (sp->role.glevels != vcpu->arch.mmu.root_level) {
1091                 kvm_mmu_zap_page(vcpu->kvm, sp);
1092                 return 1;
1093         }
1094
1095         if (rmap_write_protect(vcpu->kvm, sp->gfn))
1096                 kvm_flush_remote_tlbs(vcpu->kvm);
1097         kvm_unlink_unsync_page(vcpu->kvm, sp);
1098         if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
1099                 kvm_mmu_zap_page(vcpu->kvm, sp);
1100                 return 1;
1101         }
1102
1103         kvm_mmu_flush_tlb(vcpu);
1104         return 0;
1105 }
1106
1107 struct mmu_page_path {
1108         struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
1109         unsigned int idx[PT64_ROOT_LEVEL-1];
1110 };
1111
1112 #define for_each_sp(pvec, sp, parents, i)                       \
1113                 for (i = mmu_pages_next(&pvec, &parents, -1),   \
1114                         sp = pvec.page[i].sp;                   \
1115                         i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});   \
1116                         i = mmu_pages_next(&pvec, &parents, i))
1117
1118 int mmu_pages_next(struct kvm_mmu_pages *pvec, struct mmu_page_path *parents,
1119                    int i)
1120 {
1121         int n;
1122
1123         for (n = i+1; n < pvec->nr; n++) {
1124                 struct kvm_mmu_page *sp = pvec->page[n].sp;
1125
1126                 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1127                         parents->idx[0] = pvec->page[n].idx;
1128                         return n;
1129                 }
1130
1131                 parents->parent[sp->role.level-2] = sp;
1132                 parents->idx[sp->role.level-1] = pvec->page[n].idx;
1133         }
1134
1135         return n;
1136 }
1137
1138 void mmu_pages_clear_parents(struct mmu_page_path *parents)
1139 {
1140         struct kvm_mmu_page *sp;
1141         unsigned int level = 0;
1142
1143         do {
1144                 unsigned int idx = parents->idx[level];
1145
1146                 sp = parents->parent[level];
1147                 if (!sp)
1148                         return;
1149
1150                 --sp->unsync_children;
1151                 WARN_ON((int)sp->unsync_children < 0);
1152                 __clear_bit(idx, sp->unsync_child_bitmap);
1153                 level++;
1154         } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
1155 }
1156
1157 static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
1158                                struct mmu_page_path *parents,
1159                                struct kvm_mmu_pages *pvec)
1160 {
1161         parents->parent[parent->role.level-1] = NULL;
1162         pvec->nr = 0;
1163 }
1164
1165 static void mmu_sync_children(struct kvm_vcpu *vcpu,
1166                               struct kvm_mmu_page *parent)
1167 {
1168         int i;
1169         struct kvm_mmu_page *sp;
1170         struct mmu_page_path parents;
1171         struct kvm_mmu_pages pages;
1172
1173         kvm_mmu_pages_init(parent, &parents, &pages);
1174         while (mmu_unsync_walk(parent, &pages)) {
1175                 int protected = 0;
1176
1177                 for_each_sp(pages, sp, parents, i)
1178                         protected |= rmap_write_protect(vcpu->kvm, sp->gfn);
1179
1180                 if (protected)
1181                         kvm_flush_remote_tlbs(vcpu->kvm);
1182
1183                 for_each_sp(pages, sp, parents, i) {
1184                         kvm_sync_page(vcpu, sp);
1185                         mmu_pages_clear_parents(&parents);
1186                 }
1187                 cond_resched_lock(&vcpu->kvm->mmu_lock);
1188                 kvm_mmu_pages_init(parent, &parents, &pages);
1189         }
1190 }
1191
1192 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
1193                                              gfn_t gfn,
1194                                              gva_t gaddr,
1195                                              unsigned level,
1196                                              int metaphysical,
1197                                              unsigned access,
1198                                              u64 *parent_pte)
1199 {
1200         union kvm_mmu_page_role role;
1201         unsigned index;
1202         unsigned quadrant;
1203         struct hlist_head *bucket;
1204         struct kvm_mmu_page *sp;
1205         struct hlist_node *node, *tmp;
1206
1207         role.word = 0;
1208         role.glevels = vcpu->arch.mmu.root_level;
1209         role.level = level;
1210         role.metaphysical = metaphysical;
1211         role.access = access;
1212         if (vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
1213                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
1214                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
1215                 role.quadrant = quadrant;
1216         }
1217         pgprintk("%s: looking gfn %lx role %x\n", __func__,
1218                  gfn, role.word);
1219         index = kvm_page_table_hashfn(gfn);
1220         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1221         hlist_for_each_entry_safe(sp, node, tmp, bucket, hash_link)
1222                 if (sp->gfn == gfn) {
1223                         if (sp->unsync)
1224                                 if (kvm_sync_page(vcpu, sp))
1225                                         continue;
1226
1227                         if (sp->role.word != role.word)
1228                                 continue;
1229
1230                         mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1231                         if (sp->unsync_children) {
1232                                 set_bit(KVM_REQ_MMU_SYNC, &vcpu->requests);
1233                                 kvm_mmu_mark_parents_unsync(vcpu, sp);
1234                         }
1235                         pgprintk("%s: found\n", __func__);
1236                         return sp;
1237                 }
1238         ++vcpu->kvm->stat.mmu_cache_miss;
1239         sp = kvm_mmu_alloc_page(vcpu, parent_pte);
1240         if (!sp)
1241                 return sp;
1242         pgprintk("%s: adding gfn %lx role %x\n", __func__, gfn, role.word);
1243         sp->gfn = gfn;
1244         sp->role = role;
1245         hlist_add_head(&sp->hash_link, bucket);
1246         if (!metaphysical) {
1247                 if (rmap_write_protect(vcpu->kvm, gfn))
1248                         kvm_flush_remote_tlbs(vcpu->kvm);
1249                 account_shadowed(vcpu->kvm, gfn);
1250         }
1251         if (shadow_trap_nonpresent_pte != shadow_notrap_nonpresent_pte)
1252                 vcpu->arch.mmu.prefetch_page(vcpu, sp);
1253         else
1254                 nonpaging_prefetch_page(vcpu, sp);
1255         return sp;
1256 }
1257
1258 static int walk_shadow(struct kvm_shadow_walk *walker,
1259                        struct kvm_vcpu *vcpu, u64 addr)
1260 {
1261         hpa_t shadow_addr;
1262         int level;
1263         int r;
1264         u64 *sptep;
1265         unsigned index;
1266
1267         shadow_addr = vcpu->arch.mmu.root_hpa;
1268         level = vcpu->arch.mmu.shadow_root_level;
1269         if (level == PT32E_ROOT_LEVEL) {
1270                 shadow_addr = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
1271                 shadow_addr &= PT64_BASE_ADDR_MASK;
1272                 if (!shadow_addr)
1273                         return 1;
1274                 --level;
1275         }
1276
1277         while (level >= PT_PAGE_TABLE_LEVEL) {
1278                 index = SHADOW_PT_INDEX(addr, level);
1279                 sptep = ((u64 *)__va(shadow_addr)) + index;
1280                 r = walker->entry(walker, vcpu, addr, sptep, level);
1281                 if (r)
1282                         return r;
1283                 shadow_addr = *sptep & PT64_BASE_ADDR_MASK;
1284                 --level;
1285         }
1286         return 0;
1287 }
1288
1289 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
1290                                          struct kvm_mmu_page *sp)
1291 {
1292         unsigned i;
1293         u64 *pt;
1294         u64 ent;
1295
1296         pt = sp->spt;
1297
1298         if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1299                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1300                         if (is_shadow_present_pte(pt[i]))
1301                                 rmap_remove(kvm, &pt[i]);
1302                         pt[i] = shadow_trap_nonpresent_pte;
1303                 }
1304                 return;
1305         }
1306
1307         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1308                 ent = pt[i];
1309
1310                 if (is_shadow_present_pte(ent)) {
1311                         if (!is_large_pte(ent)) {
1312                                 ent &= PT64_BASE_ADDR_MASK;
1313                                 mmu_page_remove_parent_pte(page_header(ent),
1314                                                            &pt[i]);
1315                         } else {
1316                                 --kvm->stat.lpages;
1317                                 rmap_remove(kvm, &pt[i]);
1318                         }
1319                 }
1320                 pt[i] = shadow_trap_nonpresent_pte;
1321         }
1322 }
1323
1324 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
1325 {
1326         mmu_page_remove_parent_pte(sp, parent_pte);
1327 }
1328
1329 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
1330 {
1331         int i;
1332
1333         for (i = 0; i < KVM_MAX_VCPUS; ++i)
1334                 if (kvm->vcpus[i])
1335                         kvm->vcpus[i]->arch.last_pte_updated = NULL;
1336 }
1337
1338 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
1339 {
1340         u64 *parent_pte;
1341
1342         while (sp->multimapped || sp->parent_pte) {
1343                 if (!sp->multimapped)
1344                         parent_pte = sp->parent_pte;
1345                 else {
1346                         struct kvm_pte_chain *chain;
1347
1348                         chain = container_of(sp->parent_ptes.first,
1349                                              struct kvm_pte_chain, link);
1350                         parent_pte = chain->parent_ptes[0];
1351                 }
1352                 BUG_ON(!parent_pte);
1353                 kvm_mmu_put_page(sp, parent_pte);
1354                 set_shadow_pte(parent_pte, shadow_trap_nonpresent_pte);
1355         }
1356 }
1357
1358 static int mmu_zap_unsync_children(struct kvm *kvm,
1359                                    struct kvm_mmu_page *parent)
1360 {
1361         int i, zapped = 0;
1362         struct mmu_page_path parents;
1363         struct kvm_mmu_pages pages;
1364
1365         if (parent->role.level == PT_PAGE_TABLE_LEVEL)
1366                 return 0;
1367
1368         kvm_mmu_pages_init(parent, &parents, &pages);
1369         while (mmu_unsync_walk(parent, &pages)) {
1370                 struct kvm_mmu_page *sp;
1371
1372                 for_each_sp(pages, sp, parents, i) {
1373                         kvm_mmu_zap_page(kvm, sp);
1374                         mmu_pages_clear_parents(&parents);
1375                 }
1376                 zapped += pages.nr;
1377                 kvm_mmu_pages_init(parent, &parents, &pages);
1378         }
1379
1380         return zapped;
1381 }
1382
1383 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1384 {
1385         int ret;
1386         ++kvm->stat.mmu_shadow_zapped;
1387         ret = mmu_zap_unsync_children(kvm, sp);
1388         kvm_mmu_page_unlink_children(kvm, sp);
1389         kvm_mmu_unlink_parents(kvm, sp);
1390         kvm_flush_remote_tlbs(kvm);
1391         if (!sp->role.invalid && !sp->role.metaphysical)
1392                 unaccount_shadowed(kvm, sp->gfn);
1393         if (sp->unsync)
1394                 kvm_unlink_unsync_page(kvm, sp);
1395         if (!sp->root_count) {
1396                 hlist_del(&sp->hash_link);
1397                 kvm_mmu_free_page(kvm, sp);
1398         } else {
1399                 sp->role.invalid = 1;
1400                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
1401                 kvm_reload_remote_mmus(kvm);
1402         }
1403         kvm_mmu_reset_last_pte_updated(kvm);
1404         return ret;
1405 }
1406
1407 /*
1408  * Changing the number of mmu pages allocated to the vm
1409  * Note: if kvm_nr_mmu_pages is too small, you will get dead lock
1410  */
1411 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int kvm_nr_mmu_pages)
1412 {
1413         /*
1414          * If we set the number of mmu pages to be smaller be than the
1415          * number of actived pages , we must to free some mmu pages before we
1416          * change the value
1417          */
1418
1419         if ((kvm->arch.n_alloc_mmu_pages - kvm->arch.n_free_mmu_pages) >
1420             kvm_nr_mmu_pages) {
1421                 int n_used_mmu_pages = kvm->arch.n_alloc_mmu_pages
1422                                        - kvm->arch.n_free_mmu_pages;
1423
1424                 while (n_used_mmu_pages > kvm_nr_mmu_pages) {
1425                         struct kvm_mmu_page *page;
1426
1427                         page = container_of(kvm->arch.active_mmu_pages.prev,
1428                                             struct kvm_mmu_page, link);
1429                         kvm_mmu_zap_page(kvm, page);
1430                         n_used_mmu_pages--;
1431                 }
1432                 kvm->arch.n_free_mmu_pages = 0;
1433         }
1434         else
1435                 kvm->arch.n_free_mmu_pages += kvm_nr_mmu_pages
1436                                          - kvm->arch.n_alloc_mmu_pages;
1437
1438         kvm->arch.n_alloc_mmu_pages = kvm_nr_mmu_pages;
1439 }
1440
1441 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
1442 {
1443         unsigned index;
1444         struct hlist_head *bucket;
1445         struct kvm_mmu_page *sp;
1446         struct hlist_node *node, *n;
1447         int r;
1448
1449         pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1450         r = 0;
1451         index = kvm_page_table_hashfn(gfn);
1452         bucket = &kvm->arch.mmu_page_hash[index];
1453         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link)
1454                 if (sp->gfn == gfn && !sp->role.metaphysical) {
1455                         pgprintk("%s: gfn %lx role %x\n", __func__, gfn,
1456                                  sp->role.word);
1457                         r = 1;
1458                         if (kvm_mmu_zap_page(kvm, sp))
1459                                 n = bucket->first;
1460                 }
1461         return r;
1462 }
1463
1464 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
1465 {
1466         struct kvm_mmu_page *sp;
1467
1468         while ((sp = kvm_mmu_lookup_page(kvm, gfn)) != NULL) {
1469                 pgprintk("%s: zap %lx %x\n", __func__, gfn, sp->role.word);
1470                 kvm_mmu_zap_page(kvm, sp);
1471         }
1472 }
1473
1474 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
1475 {
1476         int slot = memslot_id(kvm, gfn_to_memslot(kvm, gfn));
1477         struct kvm_mmu_page *sp = page_header(__pa(pte));
1478
1479         __set_bit(slot, sp->slot_bitmap);
1480 }
1481
1482 static void mmu_convert_notrap(struct kvm_mmu_page *sp)
1483 {
1484         int i;
1485         u64 *pt = sp->spt;
1486
1487         if (shadow_trap_nonpresent_pte == shadow_notrap_nonpresent_pte)
1488                 return;
1489
1490         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1491                 if (pt[i] == shadow_notrap_nonpresent_pte)
1492                         set_shadow_pte(&pt[i], shadow_trap_nonpresent_pte);
1493         }
1494 }
1495
1496 struct page *gva_to_page(struct kvm_vcpu *vcpu, gva_t gva)
1497 {
1498         struct page *page;
1499
1500         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1501
1502         if (gpa == UNMAPPED_GVA)
1503                 return NULL;
1504
1505         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1506
1507         return page;
1508 }
1509
1510 /*
1511  * The function is based on mtrr_type_lookup() in
1512  * arch/x86/kernel/cpu/mtrr/generic.c
1513  */
1514 static int get_mtrr_type(struct mtrr_state_type *mtrr_state,
1515                          u64 start, u64 end)
1516 {
1517         int i;
1518         u64 base, mask;
1519         u8 prev_match, curr_match;
1520         int num_var_ranges = KVM_NR_VAR_MTRR;
1521
1522         if (!mtrr_state->enabled)
1523                 return 0xFF;
1524
1525         /* Make end inclusive end, instead of exclusive */
1526         end--;
1527
1528         /* Look in fixed ranges. Just return the type as per start */
1529         if (mtrr_state->have_fixed && (start < 0x100000)) {
1530                 int idx;
1531
1532                 if (start < 0x80000) {
1533                         idx = 0;
1534                         idx += (start >> 16);
1535                         return mtrr_state->fixed_ranges[idx];
1536                 } else if (start < 0xC0000) {
1537                         idx = 1 * 8;
1538                         idx += ((start - 0x80000) >> 14);
1539                         return mtrr_state->fixed_ranges[idx];
1540                 } else if (start < 0x1000000) {
1541                         idx = 3 * 8;
1542                         idx += ((start - 0xC0000) >> 12);
1543                         return mtrr_state->fixed_ranges[idx];
1544                 }
1545         }
1546
1547         /*
1548          * Look in variable ranges
1549          * Look of multiple ranges matching this address and pick type
1550          * as per MTRR precedence
1551          */
1552         if (!(mtrr_state->enabled & 2))
1553                 return mtrr_state->def_type;
1554
1555         prev_match = 0xFF;
1556         for (i = 0; i < num_var_ranges; ++i) {
1557                 unsigned short start_state, end_state;
1558
1559                 if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11)))
1560                         continue;
1561
1562                 base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) +
1563                        (mtrr_state->var_ranges[i].base_lo & PAGE_MASK);
1564                 mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) +
1565                        (mtrr_state->var_ranges[i].mask_lo & PAGE_MASK);
1566
1567                 start_state = ((start & mask) == (base & mask));
1568                 end_state = ((end & mask) == (base & mask));
1569                 if (start_state != end_state)
1570                         return 0xFE;
1571
1572                 if ((start & mask) != (base & mask))
1573                         continue;
1574
1575                 curr_match = mtrr_state->var_ranges[i].base_lo & 0xff;
1576                 if (prev_match == 0xFF) {
1577                         prev_match = curr_match;
1578                         continue;
1579                 }
1580
1581                 if (prev_match == MTRR_TYPE_UNCACHABLE ||
1582                     curr_match == MTRR_TYPE_UNCACHABLE)
1583                         return MTRR_TYPE_UNCACHABLE;
1584
1585                 if ((prev_match == MTRR_TYPE_WRBACK &&
1586                      curr_match == MTRR_TYPE_WRTHROUGH) ||
1587                     (prev_match == MTRR_TYPE_WRTHROUGH &&
1588                      curr_match == MTRR_TYPE_WRBACK)) {
1589                         prev_match = MTRR_TYPE_WRTHROUGH;
1590                         curr_match = MTRR_TYPE_WRTHROUGH;
1591                 }
1592
1593                 if (prev_match != curr_match)
1594                         return MTRR_TYPE_UNCACHABLE;
1595         }
1596
1597         if (prev_match != 0xFF)
1598                 return prev_match;
1599
1600         return mtrr_state->def_type;
1601 }
1602
1603 static u8 get_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn)
1604 {
1605         u8 mtrr;
1606
1607         mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT,
1608                              (gfn << PAGE_SHIFT) + PAGE_SIZE);
1609         if (mtrr == 0xfe || mtrr == 0xff)
1610                 mtrr = MTRR_TYPE_WRBACK;
1611         return mtrr;
1612 }
1613
1614 static int kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1615 {
1616         unsigned index;
1617         struct hlist_head *bucket;
1618         struct kvm_mmu_page *s;
1619         struct hlist_node *node, *n;
1620
1621         index = kvm_page_table_hashfn(sp->gfn);
1622         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1623         /* don't unsync if pagetable is shadowed with multiple roles */
1624         hlist_for_each_entry_safe(s, node, n, bucket, hash_link) {
1625                 if (s->gfn != sp->gfn || s->role.metaphysical)
1626                         continue;
1627                 if (s->role.word != sp->role.word)
1628                         return 1;
1629         }
1630         ++vcpu->kvm->stat.mmu_unsync;
1631         sp->unsync = 1;
1632
1633         if (sp->global) {
1634                 list_add(&sp->oos_link, &vcpu->kvm->arch.oos_global_pages);
1635                 ++vcpu->kvm->stat.mmu_unsync_global;
1636         } else
1637                 kvm_mmu_mark_parents_unsync(vcpu, sp);
1638
1639         mmu_convert_notrap(sp);
1640         return 0;
1641 }
1642
1643 static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
1644                                   bool can_unsync)
1645 {
1646         struct kvm_mmu_page *shadow;
1647
1648         shadow = kvm_mmu_lookup_page(vcpu->kvm, gfn);
1649         if (shadow) {
1650                 if (shadow->role.level != PT_PAGE_TABLE_LEVEL)
1651                         return 1;
1652                 if (shadow->unsync)
1653                         return 0;
1654                 if (can_unsync && oos_shadow)
1655                         return kvm_unsync_page(vcpu, shadow);
1656                 return 1;
1657         }
1658         return 0;
1659 }
1660
1661 static int set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
1662                     unsigned pte_access, int user_fault,
1663                     int write_fault, int dirty, int largepage,
1664                     int global, gfn_t gfn, pfn_t pfn, bool speculative,
1665                     bool can_unsync)
1666 {
1667         u64 spte;
1668         int ret = 0;
1669         u64 mt_mask = shadow_mt_mask;
1670         struct kvm_mmu_page *sp = page_header(__pa(shadow_pte));
1671
1672         if (!(vcpu->arch.cr4 & X86_CR4_PGE))
1673                 global = 0;
1674         if (!global && sp->global) {
1675                 sp->global = 0;
1676                 if (sp->unsync) {
1677                         kvm_unlink_unsync_global(vcpu->kvm, sp);
1678                         kvm_mmu_mark_parents_unsync(vcpu, sp);
1679                 }
1680         }
1681
1682         /*
1683          * We don't set the accessed bit, since we sometimes want to see
1684          * whether the guest actually used the pte (in order to detect
1685          * demand paging).
1686          */
1687         spte = shadow_base_present_pte | shadow_dirty_mask;
1688         if (!speculative)
1689                 spte |= shadow_accessed_mask;
1690         if (!dirty)
1691                 pte_access &= ~ACC_WRITE_MASK;
1692         if (pte_access & ACC_EXEC_MASK)
1693                 spte |= shadow_x_mask;
1694         else
1695                 spte |= shadow_nx_mask;
1696         if (pte_access & ACC_USER_MASK)
1697                 spte |= shadow_user_mask;
1698         if (largepage)
1699                 spte |= PT_PAGE_SIZE_MASK;
1700         if (mt_mask) {
1701                 mt_mask = get_memory_type(vcpu, gfn) <<
1702                           kvm_x86_ops->get_mt_mask_shift();
1703                 spte |= mt_mask;
1704         }
1705
1706         spte |= (u64)pfn << PAGE_SHIFT;
1707
1708         if ((pte_access & ACC_WRITE_MASK)
1709             || (write_fault && !is_write_protection(vcpu) && !user_fault)) {
1710
1711                 if (largepage && has_wrprotected_page(vcpu->kvm, gfn)) {
1712                         ret = 1;
1713                         spte = shadow_trap_nonpresent_pte;
1714                         goto set_pte;
1715                 }
1716
1717                 spte |= PT_WRITABLE_MASK;
1718
1719                 /*
1720                  * Optimization: for pte sync, if spte was writable the hash
1721                  * lookup is unnecessary (and expensive). Write protection
1722                  * is responsibility of mmu_get_page / kvm_sync_page.
1723                  * Same reasoning can be applied to dirty page accounting.
1724                  */
1725                 if (!can_unsync && is_writeble_pte(*shadow_pte))
1726                         goto set_pte;
1727
1728                 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
1729                         pgprintk("%s: found shadow page for %lx, marking ro\n",
1730                                  __func__, gfn);
1731                         ret = 1;
1732                         pte_access &= ~ACC_WRITE_MASK;
1733                         if (is_writeble_pte(spte))
1734                                 spte &= ~PT_WRITABLE_MASK;
1735                 }
1736         }
1737
1738         if (pte_access & ACC_WRITE_MASK)
1739                 mark_page_dirty(vcpu->kvm, gfn);
1740
1741 set_pte:
1742         set_shadow_pte(shadow_pte, spte);
1743         return ret;
1744 }
1745
1746 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
1747                          unsigned pt_access, unsigned pte_access,
1748                          int user_fault, int write_fault, int dirty,
1749                          int *ptwrite, int largepage, int global,
1750                          gfn_t gfn, pfn_t pfn, bool speculative)
1751 {
1752         int was_rmapped = 0;
1753         int was_writeble = is_writeble_pte(*shadow_pte);
1754
1755         pgprintk("%s: spte %llx access %x write_fault %d"
1756                  " user_fault %d gfn %lx\n",
1757                  __func__, *shadow_pte, pt_access,
1758                  write_fault, user_fault, gfn);
1759
1760         if (is_rmap_pte(*shadow_pte)) {
1761                 /*
1762                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
1763                  * the parent of the now unreachable PTE.
1764                  */
1765                 if (largepage && !is_large_pte(*shadow_pte)) {
1766                         struct kvm_mmu_page *child;
1767                         u64 pte = *shadow_pte;
1768
1769                         child = page_header(pte & PT64_BASE_ADDR_MASK);
1770                         mmu_page_remove_parent_pte(child, shadow_pte);
1771                 } else if (pfn != spte_to_pfn(*shadow_pte)) {
1772                         pgprintk("hfn old %lx new %lx\n",
1773                                  spte_to_pfn(*shadow_pte), pfn);
1774                         rmap_remove(vcpu->kvm, shadow_pte);
1775                 } else {
1776                         if (largepage)
1777                                 was_rmapped = is_large_pte(*shadow_pte);
1778                         else
1779                                 was_rmapped = 1;
1780                 }
1781         }
1782         if (set_spte(vcpu, shadow_pte, pte_access, user_fault, write_fault,
1783                       dirty, largepage, global, gfn, pfn, speculative, true)) {
1784                 if (write_fault)
1785                         *ptwrite = 1;
1786                 kvm_x86_ops->tlb_flush(vcpu);
1787         }
1788
1789         pgprintk("%s: setting spte %llx\n", __func__, *shadow_pte);
1790         pgprintk("instantiating %s PTE (%s) at %ld (%llx) addr %p\n",
1791                  is_large_pte(*shadow_pte)? "2MB" : "4kB",
1792                  is_present_pte(*shadow_pte)?"RW":"R", gfn,
1793                  *shadow_pte, shadow_pte);
1794         if (!was_rmapped && is_large_pte(*shadow_pte))
1795                 ++vcpu->kvm->stat.lpages;
1796
1797         page_header_update_slot(vcpu->kvm, shadow_pte, gfn);
1798         if (!was_rmapped) {
1799                 rmap_add(vcpu, shadow_pte, gfn, largepage);
1800                 if (!is_rmap_pte(*shadow_pte))
1801                         kvm_release_pfn_clean(pfn);
1802         } else {
1803                 if (was_writeble)
1804                         kvm_release_pfn_dirty(pfn);
1805                 else
1806                         kvm_release_pfn_clean(pfn);
1807         }
1808         if (speculative) {
1809                 vcpu->arch.last_pte_updated = shadow_pte;
1810                 vcpu->arch.last_pte_gfn = gfn;
1811         }
1812 }
1813
1814 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
1815 {
1816 }
1817
1818 struct direct_shadow_walk {
1819         struct kvm_shadow_walk walker;
1820         pfn_t pfn;
1821         int write;
1822         int largepage;
1823         int pt_write;
1824 };
1825
1826 static int direct_map_entry(struct kvm_shadow_walk *_walk,
1827                             struct kvm_vcpu *vcpu,
1828                             u64 addr, u64 *sptep, int level)
1829 {
1830         struct direct_shadow_walk *walk =
1831                 container_of(_walk, struct direct_shadow_walk, walker);
1832         struct kvm_mmu_page *sp;
1833         gfn_t pseudo_gfn;
1834         gfn_t gfn = addr >> PAGE_SHIFT;
1835
1836         if (level == PT_PAGE_TABLE_LEVEL
1837             || (walk->largepage && level == PT_DIRECTORY_LEVEL)) {
1838                 mmu_set_spte(vcpu, sptep, ACC_ALL, ACC_ALL,
1839                              0, walk->write, 1, &walk->pt_write,
1840                              walk->largepage, 0, gfn, walk->pfn, false);
1841                 ++vcpu->stat.pf_fixed;
1842                 return 1;
1843         }
1844
1845         if (*sptep == shadow_trap_nonpresent_pte) {
1846                 pseudo_gfn = (addr & PT64_DIR_BASE_ADDR_MASK) >> PAGE_SHIFT;
1847                 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, (gva_t)addr, level - 1,
1848                                       1, ACC_ALL, sptep);
1849                 if (!sp) {
1850                         pgprintk("nonpaging_map: ENOMEM\n");
1851                         kvm_release_pfn_clean(walk->pfn);
1852                         return -ENOMEM;
1853                 }
1854
1855                 set_shadow_pte(sptep,
1856                                __pa(sp->spt)
1857                                | PT_PRESENT_MASK | PT_WRITABLE_MASK
1858                                | shadow_user_mask | shadow_x_mask);
1859         }
1860         return 0;
1861 }
1862
1863 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
1864                         int largepage, gfn_t gfn, pfn_t pfn)
1865 {
1866         int r;
1867         struct direct_shadow_walk walker = {
1868                 .walker = { .entry = direct_map_entry, },
1869                 .pfn = pfn,
1870                 .largepage = largepage,
1871                 .write = write,
1872                 .pt_write = 0,
1873         };
1874
1875         r = walk_shadow(&walker.walker, vcpu, gfn << PAGE_SHIFT);
1876         if (r < 0)
1877                 return r;
1878         return walker.pt_write;
1879 }
1880
1881 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn)
1882 {
1883         int r;
1884         int largepage = 0;
1885         pfn_t pfn;
1886         unsigned long mmu_seq;
1887
1888         if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
1889                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
1890                 largepage = 1;
1891         }
1892
1893         mmu_seq = vcpu->kvm->mmu_notifier_seq;
1894         smp_rmb();
1895         pfn = gfn_to_pfn(vcpu->kvm, gfn);
1896
1897         /* mmio */
1898         if (is_error_pfn(pfn)) {
1899                 kvm_release_pfn_clean(pfn);
1900                 return 1;
1901         }
1902
1903         spin_lock(&vcpu->kvm->mmu_lock);
1904         if (mmu_notifier_retry(vcpu, mmu_seq))
1905                 goto out_unlock;
1906         kvm_mmu_free_some_pages(vcpu);
1907         r = __direct_map(vcpu, v, write, largepage, gfn, pfn);
1908         spin_unlock(&vcpu->kvm->mmu_lock);
1909
1910
1911         return r;
1912
1913 out_unlock:
1914         spin_unlock(&vcpu->kvm->mmu_lock);
1915         kvm_release_pfn_clean(pfn);
1916         return 0;
1917 }
1918
1919
1920 static void mmu_free_roots(struct kvm_vcpu *vcpu)
1921 {
1922         int i;
1923         struct kvm_mmu_page *sp;
1924
1925         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1926                 return;
1927         spin_lock(&vcpu->kvm->mmu_lock);
1928         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1929                 hpa_t root = vcpu->arch.mmu.root_hpa;
1930
1931                 sp = page_header(root);
1932                 --sp->root_count;
1933                 if (!sp->root_count && sp->role.invalid)
1934                         kvm_mmu_zap_page(vcpu->kvm, sp);
1935                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1936                 spin_unlock(&vcpu->kvm->mmu_lock);
1937                 return;
1938         }
1939         for (i = 0; i < 4; ++i) {
1940                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1941
1942                 if (root) {
1943                         root &= PT64_BASE_ADDR_MASK;
1944                         sp = page_header(root);
1945                         --sp->root_count;
1946                         if (!sp->root_count && sp->role.invalid)
1947                                 kvm_mmu_zap_page(vcpu->kvm, sp);
1948                 }
1949                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1950         }
1951         spin_unlock(&vcpu->kvm->mmu_lock);
1952         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1953 }
1954
1955 static void mmu_alloc_roots(struct kvm_vcpu *vcpu)
1956 {
1957         int i;
1958         gfn_t root_gfn;
1959         struct kvm_mmu_page *sp;
1960         int metaphysical = 0;
1961
1962         root_gfn = vcpu->arch.cr3 >> PAGE_SHIFT;
1963
1964         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1965                 hpa_t root = vcpu->arch.mmu.root_hpa;
1966
1967                 ASSERT(!VALID_PAGE(root));
1968                 if (tdp_enabled)
1969                         metaphysical = 1;
1970                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
1971                                       PT64_ROOT_LEVEL, metaphysical,
1972                                       ACC_ALL, NULL);
1973                 root = __pa(sp->spt);
1974                 ++sp->root_count;
1975                 vcpu->arch.mmu.root_hpa = root;
1976                 return;
1977         }
1978         metaphysical = !is_paging(vcpu);
1979         if (tdp_enabled)
1980                 metaphysical = 1;
1981         for (i = 0; i < 4; ++i) {
1982                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1983
1984                 ASSERT(!VALID_PAGE(root));
1985                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
1986                         if (!is_present_pte(vcpu->arch.pdptrs[i])) {
1987                                 vcpu->arch.mmu.pae_root[i] = 0;
1988                                 continue;
1989                         }
1990                         root_gfn = vcpu->arch.pdptrs[i] >> PAGE_SHIFT;
1991                 } else if (vcpu->arch.mmu.root_level == 0)
1992                         root_gfn = 0;
1993                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
1994                                       PT32_ROOT_LEVEL, metaphysical,
1995                                       ACC_ALL, NULL);
1996                 root = __pa(sp->spt);
1997                 ++sp->root_count;
1998                 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
1999         }
2000         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
2001 }
2002
2003 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
2004 {
2005         int i;
2006         struct kvm_mmu_page *sp;
2007
2008         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2009                 return;
2010         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2011                 hpa_t root = vcpu->arch.mmu.root_hpa;
2012                 sp = page_header(root);
2013                 mmu_sync_children(vcpu, sp);
2014                 return;
2015         }
2016         for (i = 0; i < 4; ++i) {
2017                 hpa_t root = vcpu->arch.mmu.pae_root[i];
2018
2019                 if (root) {
2020                         root &= PT64_BASE_ADDR_MASK;
2021                         sp = page_header(root);
2022                         mmu_sync_children(vcpu, sp);
2023                 }
2024         }
2025 }
2026
2027 static void mmu_sync_global(struct kvm_vcpu *vcpu)
2028 {
2029         struct kvm *kvm = vcpu->kvm;
2030         struct kvm_mmu_page *sp, *n;
2031
2032         list_for_each_entry_safe(sp, n, &kvm->arch.oos_global_pages, oos_link)
2033                 kvm_sync_page(vcpu, sp);
2034 }
2035
2036 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
2037 {
2038         spin_lock(&vcpu->kvm->mmu_lock);
2039         mmu_sync_roots(vcpu);
2040         spin_unlock(&vcpu->kvm->mmu_lock);
2041 }
2042
2043 void kvm_mmu_sync_global(struct kvm_vcpu *vcpu)
2044 {
2045         spin_lock(&vcpu->kvm->mmu_lock);
2046         mmu_sync_global(vcpu);
2047         spin_unlock(&vcpu->kvm->mmu_lock);
2048 }
2049
2050 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr)
2051 {
2052         return vaddr;
2053 }
2054
2055 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
2056                                 u32 error_code)
2057 {
2058         gfn_t gfn;
2059         int r;
2060
2061         pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
2062         r = mmu_topup_memory_caches(vcpu);
2063         if (r)
2064                 return r;
2065
2066         ASSERT(vcpu);
2067         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2068
2069         gfn = gva >> PAGE_SHIFT;
2070
2071         return nonpaging_map(vcpu, gva & PAGE_MASK,
2072                              error_code & PFERR_WRITE_MASK, gfn);
2073 }
2074
2075 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
2076                                 u32 error_code)
2077 {
2078         pfn_t pfn;
2079         int r;
2080         int largepage = 0;
2081         gfn_t gfn = gpa >> PAGE_SHIFT;
2082         unsigned long mmu_seq;
2083
2084         ASSERT(vcpu);
2085         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2086
2087         r = mmu_topup_memory_caches(vcpu);
2088         if (r)
2089                 return r;
2090
2091         if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
2092                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
2093                 largepage = 1;
2094         }
2095         mmu_seq = vcpu->kvm->mmu_notifier_seq;
2096         smp_rmb();
2097         pfn = gfn_to_pfn(vcpu->kvm, gfn);
2098         if (is_error_pfn(pfn)) {
2099                 kvm_release_pfn_clean(pfn);
2100                 return 1;
2101         }
2102         spin_lock(&vcpu->kvm->mmu_lock);
2103         if (mmu_notifier_retry(vcpu, mmu_seq))
2104                 goto out_unlock;
2105         kvm_mmu_free_some_pages(vcpu);
2106         r = __direct_map(vcpu, gpa, error_code & PFERR_WRITE_MASK,
2107                          largepage, gfn, pfn);
2108         spin_unlock(&vcpu->kvm->mmu_lock);
2109
2110         return r;
2111
2112 out_unlock:
2113         spin_unlock(&vcpu->kvm->mmu_lock);
2114         kvm_release_pfn_clean(pfn);
2115         return 0;
2116 }
2117
2118 static void nonpaging_free(struct kvm_vcpu *vcpu)
2119 {
2120         mmu_free_roots(vcpu);
2121 }
2122
2123 static int nonpaging_init_context(struct kvm_vcpu *vcpu)
2124 {
2125         struct kvm_mmu *context = &vcpu->arch.mmu;
2126
2127         context->new_cr3 = nonpaging_new_cr3;
2128         context->page_fault = nonpaging_page_fault;
2129         context->gva_to_gpa = nonpaging_gva_to_gpa;
2130         context->free = nonpaging_free;
2131         context->prefetch_page = nonpaging_prefetch_page;
2132         context->sync_page = nonpaging_sync_page;
2133         context->invlpg = nonpaging_invlpg;
2134         context->root_level = 0;
2135         context->shadow_root_level = PT32E_ROOT_LEVEL;
2136         context->root_hpa = INVALID_PAGE;
2137         return 0;
2138 }
2139
2140 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2141 {
2142         ++vcpu->stat.tlb_flush;
2143         kvm_x86_ops->tlb_flush(vcpu);
2144 }
2145
2146 static void paging_new_cr3(struct kvm_vcpu *vcpu)
2147 {
2148         pgprintk("%s: cr3 %lx\n", __func__, vcpu->arch.cr3);
2149         mmu_free_roots(vcpu);
2150 }
2151
2152 static void inject_page_fault(struct kvm_vcpu *vcpu,
2153                               u64 addr,
2154                               u32 err_code)
2155 {
2156         kvm_inject_page_fault(vcpu, addr, err_code);
2157 }
2158
2159 static void paging_free(struct kvm_vcpu *vcpu)
2160 {
2161         nonpaging_free(vcpu);
2162 }
2163
2164 #define PTTYPE 64
2165 #include "paging_tmpl.h"
2166 #undef PTTYPE
2167
2168 #define PTTYPE 32
2169 #include "paging_tmpl.h"
2170 #undef PTTYPE
2171
2172 static int paging64_init_context_common(struct kvm_vcpu *vcpu, int level)
2173 {
2174         struct kvm_mmu *context = &vcpu->arch.mmu;
2175
2176         ASSERT(is_pae(vcpu));
2177         context->new_cr3 = paging_new_cr3;
2178         context->page_fault = paging64_page_fault;
2179         context->gva_to_gpa = paging64_gva_to_gpa;
2180         context->prefetch_page = paging64_prefetch_page;
2181         context->sync_page = paging64_sync_page;
2182         context->invlpg = paging64_invlpg;
2183         context->free = paging_free;
2184         context->root_level = level;
2185         context->shadow_root_level = level;
2186         context->root_hpa = INVALID_PAGE;
2187         return 0;
2188 }
2189
2190 static int paging64_init_context(struct kvm_vcpu *vcpu)
2191 {
2192         return paging64_init_context_common(vcpu, PT64_ROOT_LEVEL);
2193 }
2194
2195 static int paging32_init_context(struct kvm_vcpu *vcpu)
2196 {
2197         struct kvm_mmu *context = &vcpu->arch.mmu;
2198
2199         context->new_cr3 = paging_new_cr3;
2200         context->page_fault = paging32_page_fault;
2201         context->gva_to_gpa = paging32_gva_to_gpa;
2202         context->free = paging_free;
2203         context->prefetch_page = paging32_prefetch_page;
2204         context->sync_page = paging32_sync_page;
2205         context->invlpg = paging32_invlpg;
2206         context->root_level = PT32_ROOT_LEVEL;
2207         context->shadow_root_level = PT32E_ROOT_LEVEL;
2208         context->root_hpa = INVALID_PAGE;
2209         return 0;
2210 }
2211
2212 static int paging32E_init_context(struct kvm_vcpu *vcpu)
2213 {
2214         return paging64_init_context_common(vcpu, PT32E_ROOT_LEVEL);
2215 }
2216
2217 static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
2218 {
2219         struct kvm_mmu *context = &vcpu->arch.mmu;
2220
2221         context->new_cr3 = nonpaging_new_cr3;
2222         context->page_fault = tdp_page_fault;
2223         context->free = nonpaging_free;
2224         context->prefetch_page = nonpaging_prefetch_page;
2225         context->sync_page = nonpaging_sync_page;
2226         context->invlpg = nonpaging_invlpg;
2227         context->shadow_root_level = kvm_x86_ops->get_tdp_level();
2228         context->root_hpa = INVALID_PAGE;
2229
2230         if (!is_paging(vcpu)) {
2231                 context->gva_to_gpa = nonpaging_gva_to_gpa;
2232                 context->root_level = 0;
2233         } else if (is_long_mode(vcpu)) {
2234                 context->gva_to_gpa = paging64_gva_to_gpa;
2235                 context->root_level = PT64_ROOT_LEVEL;
2236         } else if (is_pae(vcpu)) {
2237                 context->gva_to_gpa = paging64_gva_to_gpa;
2238                 context->root_level = PT32E_ROOT_LEVEL;
2239         } else {
2240                 context->gva_to_gpa = paging32_gva_to_gpa;
2241                 context->root_level = PT32_ROOT_LEVEL;
2242         }
2243
2244         return 0;
2245 }
2246
2247 static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
2248 {
2249         ASSERT(vcpu);
2250         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2251
2252         if (!is_paging(vcpu))
2253                 return nonpaging_init_context(vcpu);
2254         else if (is_long_mode(vcpu))
2255                 return paging64_init_context(vcpu);
2256         else if (is_pae(vcpu))
2257                 return paging32E_init_context(vcpu);
2258         else
2259                 return paging32_init_context(vcpu);
2260 }
2261
2262 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
2263 {
2264         vcpu->arch.update_pte.pfn = bad_pfn;
2265
2266         if (tdp_enabled)
2267                 return init_kvm_tdp_mmu(vcpu);
2268         else
2269                 return init_kvm_softmmu(vcpu);
2270 }
2271
2272 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
2273 {
2274         ASSERT(vcpu);
2275         if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) {
2276                 vcpu->arch.mmu.free(vcpu);
2277                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
2278         }
2279 }
2280
2281 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
2282 {
2283         destroy_kvm_mmu(vcpu);
2284         return init_kvm_mmu(vcpu);
2285 }
2286 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
2287
2288 int kvm_mmu_load(struct kvm_vcpu *vcpu)
2289 {
2290         int r;
2291
2292         r = mmu_topup_memory_caches(vcpu);
2293         if (r)
2294                 goto out;
2295         spin_lock(&vcpu->kvm->mmu_lock);
2296         kvm_mmu_free_some_pages(vcpu);
2297         mmu_alloc_roots(vcpu);
2298         mmu_sync_roots(vcpu);
2299         spin_unlock(&vcpu->kvm->mmu_lock);
2300         kvm_x86_ops->set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
2301         kvm_mmu_flush_tlb(vcpu);
2302 out:
2303         return r;
2304 }
2305 EXPORT_SYMBOL_GPL(kvm_mmu_load);
2306
2307 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
2308 {
2309         mmu_free_roots(vcpu);
2310 }
2311
2312 static void mmu_pte_write_zap_pte(struct kvm_vcpu *vcpu,
2313                                   struct kvm_mmu_page *sp,
2314                                   u64 *spte)
2315 {
2316         u64 pte;
2317         struct kvm_mmu_page *child;
2318
2319         pte = *spte;
2320         if (is_shadow_present_pte(pte)) {
2321                 if (sp->role.level == PT_PAGE_TABLE_LEVEL ||
2322                     is_large_pte(pte))
2323                         rmap_remove(vcpu->kvm, spte);
2324                 else {
2325                         child = page_header(pte & PT64_BASE_ADDR_MASK);
2326                         mmu_page_remove_parent_pte(child, spte);
2327                 }
2328         }
2329         set_shadow_pte(spte, shadow_trap_nonpresent_pte);
2330         if (is_large_pte(pte))
2331                 --vcpu->kvm->stat.lpages;
2332 }
2333
2334 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
2335                                   struct kvm_mmu_page *sp,
2336                                   u64 *spte,
2337                                   const void *new)
2338 {
2339         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
2340                 if (!vcpu->arch.update_pte.largepage ||
2341                     sp->role.glevels == PT32_ROOT_LEVEL) {
2342                         ++vcpu->kvm->stat.mmu_pde_zapped;
2343                         return;
2344                 }
2345         }
2346
2347         ++vcpu->kvm->stat.mmu_pte_updated;
2348         if (sp->role.glevels == PT32_ROOT_LEVEL)
2349                 paging32_update_pte(vcpu, sp, spte, new);
2350         else
2351                 paging64_update_pte(vcpu, sp, spte, new);
2352 }
2353
2354 static bool need_remote_flush(u64 old, u64 new)
2355 {
2356         if (!is_shadow_present_pte(old))
2357                 return false;
2358         if (!is_shadow_present_pte(new))
2359                 return true;
2360         if ((old ^ new) & PT64_BASE_ADDR_MASK)
2361                 return true;
2362         old ^= PT64_NX_MASK;
2363         new ^= PT64_NX_MASK;
2364         return (old & ~new & PT64_PERM_MASK) != 0;
2365 }
2366
2367 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, u64 old, u64 new)
2368 {
2369         if (need_remote_flush(old, new))
2370                 kvm_flush_remote_tlbs(vcpu->kvm);
2371         else
2372                 kvm_mmu_flush_tlb(vcpu);
2373 }
2374
2375 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
2376 {
2377         u64 *spte = vcpu->arch.last_pte_updated;
2378
2379         return !!(spte && (*spte & shadow_accessed_mask));
2380 }
2381
2382 static void mmu_guess_page_from_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2383                                           const u8 *new, int bytes)
2384 {
2385         gfn_t gfn;
2386         int r;
2387         u64 gpte = 0;
2388         pfn_t pfn;
2389
2390         vcpu->arch.update_pte.largepage = 0;
2391
2392         if (bytes != 4 && bytes != 8)
2393                 return;
2394
2395         /*
2396          * Assume that the pte write on a page table of the same type
2397          * as the current vcpu paging mode.  This is nearly always true
2398          * (might be false while changing modes).  Note it is verified later
2399          * by update_pte().
2400          */
2401         if (is_pae(vcpu)) {
2402                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
2403                 if ((bytes == 4) && (gpa % 4 == 0)) {
2404                         r = kvm_read_guest(vcpu->kvm, gpa & ~(u64)7, &gpte, 8);
2405                         if (r)
2406                                 return;
2407                         memcpy((void *)&gpte + (gpa % 8), new, 4);
2408                 } else if ((bytes == 8) && (gpa % 8 == 0)) {
2409                         memcpy((void *)&gpte, new, 8);
2410                 }
2411         } else {
2412                 if ((bytes == 4) && (gpa % 4 == 0))
2413                         memcpy((void *)&gpte, new, 4);
2414         }
2415         if (!is_present_pte(gpte))
2416                 return;
2417         gfn = (gpte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
2418
2419         if (is_large_pte(gpte) && is_largepage_backed(vcpu, gfn)) {
2420                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
2421                 vcpu->arch.update_pte.largepage = 1;
2422         }
2423         vcpu->arch.update_pte.mmu_seq = vcpu->kvm->mmu_notifier_seq;
2424         smp_rmb();
2425         pfn = gfn_to_pfn(vcpu->kvm, gfn);
2426
2427         if (is_error_pfn(pfn)) {
2428                 kvm_release_pfn_clean(pfn);
2429                 return;
2430         }
2431         vcpu->arch.update_pte.gfn = gfn;
2432         vcpu->arch.update_pte.pfn = pfn;
2433 }
2434
2435 static void kvm_mmu_access_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2436 {
2437         u64 *spte = vcpu->arch.last_pte_updated;
2438
2439         if (spte
2440             && vcpu->arch.last_pte_gfn == gfn
2441             && shadow_accessed_mask
2442             && !(*spte & shadow_accessed_mask)
2443             && is_shadow_present_pte(*spte))
2444                 set_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
2445 }
2446
2447 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2448                        const u8 *new, int bytes,
2449                        bool guest_initiated)
2450 {
2451         gfn_t gfn = gpa >> PAGE_SHIFT;
2452         struct kvm_mmu_page *sp;
2453         struct hlist_node *node, *n;
2454         struct hlist_head *bucket;
2455         unsigned index;
2456         u64 entry, gentry;
2457         u64 *spte;
2458         unsigned offset = offset_in_page(gpa);
2459         unsigned pte_size;
2460         unsigned page_offset;
2461         unsigned misaligned;
2462         unsigned quadrant;
2463         int level;
2464         int flooded = 0;
2465         int npte;
2466         int r;
2467
2468         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
2469         mmu_guess_page_from_pte_write(vcpu, gpa, new, bytes);
2470         spin_lock(&vcpu->kvm->mmu_lock);
2471         kvm_mmu_access_page(vcpu, gfn);
2472         kvm_mmu_free_some_pages(vcpu);
2473         ++vcpu->kvm->stat.mmu_pte_write;
2474         kvm_mmu_audit(vcpu, "pre pte write");
2475         if (guest_initiated) {
2476                 if (gfn == vcpu->arch.last_pt_write_gfn
2477                     && !last_updated_pte_accessed(vcpu)) {
2478                         ++vcpu->arch.last_pt_write_count;
2479                         if (vcpu->arch.last_pt_write_count >= 3)
2480                                 flooded = 1;
2481                 } else {
2482                         vcpu->arch.last_pt_write_gfn = gfn;
2483                         vcpu->arch.last_pt_write_count = 1;
2484                         vcpu->arch.last_pte_updated = NULL;
2485                 }
2486         }
2487         index = kvm_page_table_hashfn(gfn);
2488         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
2489         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link) {
2490                 if (sp->gfn != gfn || sp->role.metaphysical || sp->role.invalid)
2491                         continue;
2492                 pte_size = sp->role.glevels == PT32_ROOT_LEVEL ? 4 : 8;
2493                 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
2494                 misaligned |= bytes < 4;
2495                 if (misaligned || flooded) {
2496                         /*
2497                          * Misaligned accesses are too much trouble to fix
2498                          * up; also, they usually indicate a page is not used
2499                          * as a page table.
2500                          *
2501                          * If we're seeing too many writes to a page,
2502                          * it may no longer be a page table, or we may be
2503                          * forking, in which case it is better to unmap the
2504                          * page.
2505                          */
2506                         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
2507                                  gpa, bytes, sp->role.word);
2508                         if (kvm_mmu_zap_page(vcpu->kvm, sp))
2509                                 n = bucket->first;
2510                         ++vcpu->kvm->stat.mmu_flooded;
2511                         continue;
2512                 }
2513                 page_offset = offset;
2514                 level = sp->role.level;
2515                 npte = 1;
2516                 if (sp->role.glevels == PT32_ROOT_LEVEL) {
2517                         page_offset <<= 1;      /* 32->64 */
2518                         /*
2519                          * A 32-bit pde maps 4MB while the shadow pdes map
2520                          * only 2MB.  So we need to double the offset again
2521                          * and zap two pdes instead of one.
2522                          */
2523                         if (level == PT32_ROOT_LEVEL) {
2524                                 page_offset &= ~7; /* kill rounding error */
2525                                 page_offset <<= 1;
2526                                 npte = 2;
2527                         }
2528                         quadrant = page_offset >> PAGE_SHIFT;
2529                         page_offset &= ~PAGE_MASK;
2530                         if (quadrant != sp->role.quadrant)
2531                                 continue;
2532                 }
2533                 spte = &sp->spt[page_offset / sizeof(*spte)];
2534                 if ((gpa & (pte_size - 1)) || (bytes < pte_size)) {
2535                         gentry = 0;
2536                         r = kvm_read_guest_atomic(vcpu->kvm,
2537                                                   gpa & ~(u64)(pte_size - 1),
2538                                                   &gentry, pte_size);
2539                         new = (const void *)&gentry;
2540                         if (r < 0)
2541                                 new = NULL;
2542                 }
2543                 while (npte--) {
2544                         entry = *spte;
2545                         mmu_pte_write_zap_pte(vcpu, sp, spte);
2546                         if (new)
2547                                 mmu_pte_write_new_pte(vcpu, sp, spte, new);
2548                         mmu_pte_write_flush_tlb(vcpu, entry, *spte);
2549                         ++spte;
2550                 }
2551         }
2552         kvm_mmu_audit(vcpu, "post pte write");
2553         spin_unlock(&vcpu->kvm->mmu_lock);
2554         if (!is_error_pfn(vcpu->arch.update_pte.pfn)) {
2555                 kvm_release_pfn_clean(vcpu->arch.update_pte.pfn);
2556                 vcpu->arch.update_pte.pfn = bad_pfn;
2557         }
2558 }
2559
2560 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2561 {
2562         gpa_t gpa;
2563         int r;
2564
2565         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
2566
2567         spin_lock(&vcpu->kvm->mmu_lock);
2568         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2569         spin_unlock(&vcpu->kvm->mmu_lock);
2570         return r;
2571 }
2572 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
2573
2574 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
2575 {
2576         while (vcpu->kvm->arch.n_free_mmu_pages < KVM_REFILL_PAGES) {
2577                 struct kvm_mmu_page *sp;
2578
2579                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
2580                                   struct kvm_mmu_page, link);
2581                 kvm_mmu_zap_page(vcpu->kvm, sp);
2582                 ++vcpu->kvm->stat.mmu_recycled;
2583         }
2584 }
2585
2586 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
2587 {
2588         int r;
2589         enum emulation_result er;
2590
2591         r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
2592         if (r < 0)
2593                 goto out;
2594
2595         if (!r) {
2596                 r = 1;
2597                 goto out;
2598         }
2599
2600         r = mmu_topup_memory_caches(vcpu);
2601         if (r)
2602                 goto out;
2603
2604         er = emulate_instruction(vcpu, vcpu->run, cr2, error_code, 0);
2605
2606         switch (er) {
2607         case EMULATE_DONE:
2608                 return 1;
2609         case EMULATE_DO_MMIO:
2610                 ++vcpu->stat.mmio_exits;
2611                 return 0;
2612         case EMULATE_FAIL:
2613                 kvm_report_emulation_failure(vcpu, "pagetable");
2614                 return 1;
2615         default:
2616                 BUG();
2617         }
2618 out:
2619         return r;
2620 }
2621 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
2622
2623 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
2624 {
2625         vcpu->arch.mmu.invlpg(vcpu, gva);
2626         kvm_mmu_flush_tlb(vcpu);
2627         ++vcpu->stat.invlpg;
2628 }
2629 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
2630
2631 void kvm_enable_tdp(void)
2632 {
2633         tdp_enabled = true;
2634 }
2635 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
2636
2637 void kvm_disable_tdp(void)
2638 {
2639         tdp_enabled = false;
2640 }
2641 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
2642
2643 static void free_mmu_pages(struct kvm_vcpu *vcpu)
2644 {
2645         struct kvm_mmu_page *sp;
2646
2647         while (!list_empty(&vcpu->kvm->arch.active_mmu_pages)) {
2648                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.next,
2649                                   struct kvm_mmu_page, link);
2650                 kvm_mmu_zap_page(vcpu->kvm, sp);
2651                 cond_resched();
2652         }
2653         free_page((unsigned long)vcpu->arch.mmu.pae_root);
2654 }
2655
2656 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
2657 {
2658         struct page *page;
2659         int i;
2660
2661         ASSERT(vcpu);
2662
2663         if (vcpu->kvm->arch.n_requested_mmu_pages)
2664                 vcpu->kvm->arch.n_free_mmu_pages =
2665                                         vcpu->kvm->arch.n_requested_mmu_pages;
2666         else
2667                 vcpu->kvm->arch.n_free_mmu_pages =
2668                                         vcpu->kvm->arch.n_alloc_mmu_pages;
2669         /*
2670          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
2671          * Therefore we need to allocate shadow page tables in the first
2672          * 4GB of memory, which happens to fit the DMA32 zone.
2673          */
2674         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
2675         if (!page)
2676                 goto error_1;
2677         vcpu->arch.mmu.pae_root = page_address(page);
2678         for (i = 0; i < 4; ++i)
2679                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
2680
2681         return 0;
2682
2683 error_1:
2684         free_mmu_pages(vcpu);
2685         return -ENOMEM;
2686 }
2687
2688 int kvm_mmu_create(struct kvm_vcpu *vcpu)
2689 {
2690         ASSERT(vcpu);
2691         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2692
2693         return alloc_mmu_pages(vcpu);
2694 }
2695
2696 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
2697 {
2698         ASSERT(vcpu);
2699         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2700
2701         return init_kvm_mmu(vcpu);
2702 }
2703
2704 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
2705 {
2706         ASSERT(vcpu);
2707
2708         destroy_kvm_mmu(vcpu);
2709         free_mmu_pages(vcpu);
2710         mmu_free_memory_caches(vcpu);
2711 }
2712
2713 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
2714 {
2715         struct kvm_mmu_page *sp;
2716
2717         spin_lock(&kvm->mmu_lock);
2718         list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
2719                 int i;
2720                 u64 *pt;
2721
2722                 if (!test_bit(slot, sp->slot_bitmap))
2723                         continue;
2724
2725                 pt = sp->spt;
2726                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2727                         /* avoid RMW */
2728                         if (pt[i] & PT_WRITABLE_MASK)
2729                                 pt[i] &= ~PT_WRITABLE_MASK;
2730         }
2731         kvm_flush_remote_tlbs(kvm);
2732         spin_unlock(&kvm->mmu_lock);
2733 }
2734
2735 void kvm_mmu_zap_all(struct kvm *kvm)
2736 {
2737         struct kvm_mmu_page *sp, *node;
2738
2739         spin_lock(&kvm->mmu_lock);
2740         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
2741                 if (kvm_mmu_zap_page(kvm, sp))
2742                         node = container_of(kvm->arch.active_mmu_pages.next,
2743                                             struct kvm_mmu_page, link);
2744         spin_unlock(&kvm->mmu_lock);
2745
2746         kvm_flush_remote_tlbs(kvm);
2747 }
2748
2749 static void kvm_mmu_remove_one_alloc_mmu_page(struct kvm *kvm)
2750 {
2751         struct kvm_mmu_page *page;
2752
2753         page = container_of(kvm->arch.active_mmu_pages.prev,
2754                             struct kvm_mmu_page, link);
2755         kvm_mmu_zap_page(kvm, page);
2756 }
2757
2758 static int mmu_shrink(int nr_to_scan, gfp_t gfp_mask)
2759 {
2760         struct kvm *kvm;
2761         struct kvm *kvm_freed = NULL;
2762         int cache_count = 0;
2763
2764         spin_lock(&kvm_lock);
2765
2766         list_for_each_entry(kvm, &vm_list, vm_list) {
2767                 int npages;
2768
2769                 if (!down_read_trylock(&kvm->slots_lock))
2770                         continue;
2771                 spin_lock(&kvm->mmu_lock);
2772                 npages = kvm->arch.n_alloc_mmu_pages -
2773                          kvm->arch.n_free_mmu_pages;
2774                 cache_count += npages;
2775                 if (!kvm_freed && nr_to_scan > 0 && npages > 0) {
2776                         kvm_mmu_remove_one_alloc_mmu_page(kvm);
2777                         cache_count--;
2778                         kvm_freed = kvm;
2779                 }
2780                 nr_to_scan--;
2781
2782                 spin_unlock(&kvm->mmu_lock);
2783                 up_read(&kvm->slots_lock);
2784         }
2785         if (kvm_freed)
2786                 list_move_tail(&kvm_freed->vm_list, &vm_list);
2787
2788         spin_unlock(&kvm_lock);
2789
2790         return cache_count;
2791 }
2792
2793 static struct shrinker mmu_shrinker = {
2794         .shrink = mmu_shrink,
2795         .seeks = DEFAULT_SEEKS * 10,
2796 };
2797
2798 static void mmu_destroy_caches(void)
2799 {
2800         if (pte_chain_cache)
2801                 kmem_cache_destroy(pte_chain_cache);
2802         if (rmap_desc_cache)
2803                 kmem_cache_destroy(rmap_desc_cache);
2804         if (mmu_page_header_cache)
2805                 kmem_cache_destroy(mmu_page_header_cache);
2806 }
2807
2808 void kvm_mmu_module_exit(void)
2809 {
2810         mmu_destroy_caches();
2811         unregister_shrinker(&mmu_shrinker);
2812 }
2813
2814 int kvm_mmu_module_init(void)
2815 {
2816         pte_chain_cache = kmem_cache_create("kvm_pte_chain",
2817                                             sizeof(struct kvm_pte_chain),
2818                                             0, 0, NULL);
2819         if (!pte_chain_cache)
2820                 goto nomem;
2821         rmap_desc_cache = kmem_cache_create("kvm_rmap_desc",
2822                                             sizeof(struct kvm_rmap_desc),
2823                                             0, 0, NULL);
2824         if (!rmap_desc_cache)
2825                 goto nomem;
2826
2827         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
2828                                                   sizeof(struct kvm_mmu_page),
2829                                                   0, 0, NULL);
2830         if (!mmu_page_header_cache)
2831                 goto nomem;
2832
2833         register_shrinker(&mmu_shrinker);
2834
2835         return 0;
2836
2837 nomem:
2838         mmu_destroy_caches();
2839         return -ENOMEM;
2840 }
2841
2842 /*
2843  * Caculate mmu pages needed for kvm.
2844  */
2845 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
2846 {
2847         int i;
2848         unsigned int nr_mmu_pages;
2849         unsigned int  nr_pages = 0;
2850
2851         for (i = 0; i < kvm->nmemslots; i++)
2852                 nr_pages += kvm->memslots[i].npages;
2853
2854         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
2855         nr_mmu_pages = max(nr_mmu_pages,
2856                         (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
2857
2858         return nr_mmu_pages;
2859 }
2860
2861 static void *pv_mmu_peek_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2862                                 unsigned len)
2863 {
2864         if (len > buffer->len)
2865                 return NULL;
2866         return buffer->ptr;
2867 }
2868
2869 static void *pv_mmu_read_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2870                                 unsigned len)
2871 {
2872         void *ret;
2873
2874         ret = pv_mmu_peek_buffer(buffer, len);
2875         if (!ret)
2876                 return ret;
2877         buffer->ptr += len;
2878         buffer->len -= len;
2879         buffer->processed += len;
2880         return ret;
2881 }
2882
2883 static int kvm_pv_mmu_write(struct kvm_vcpu *vcpu,
2884                              gpa_t addr, gpa_t value)
2885 {
2886         int bytes = 8;
2887         int r;
2888
2889         if (!is_long_mode(vcpu) && !is_pae(vcpu))
2890                 bytes = 4;
2891
2892         r = mmu_topup_memory_caches(vcpu);
2893         if (r)
2894                 return r;
2895
2896         if (!emulator_write_phys(vcpu, addr, &value, bytes))
2897                 return -EFAULT;
2898
2899         return 1;
2900 }
2901
2902 static int kvm_pv_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2903 {
2904         kvm_x86_ops->tlb_flush(vcpu);
2905         set_bit(KVM_REQ_MMU_SYNC, &vcpu->requests);
2906         return 1;
2907 }
2908
2909 static int kvm_pv_mmu_release_pt(struct kvm_vcpu *vcpu, gpa_t addr)
2910 {
2911         spin_lock(&vcpu->kvm->mmu_lock);
2912         mmu_unshadow(vcpu->kvm, addr >> PAGE_SHIFT);
2913         spin_unlock(&vcpu->kvm->mmu_lock);
2914         return 1;
2915 }
2916
2917 static int kvm_pv_mmu_op_one(struct kvm_vcpu *vcpu,
2918                              struct kvm_pv_mmu_op_buffer *buffer)
2919 {
2920         struct kvm_mmu_op_header *header;
2921
2922         header = pv_mmu_peek_buffer(buffer, sizeof *header);
2923         if (!header)
2924                 return 0;
2925         switch (header->op) {
2926         case KVM_MMU_OP_WRITE_PTE: {
2927                 struct kvm_mmu_op_write_pte *wpte;
2928
2929                 wpte = pv_mmu_read_buffer(buffer, sizeof *wpte);
2930                 if (!wpte)
2931                         return 0;
2932                 return kvm_pv_mmu_write(vcpu, wpte->pte_phys,
2933                                         wpte->pte_val);
2934         }
2935         case KVM_MMU_OP_FLUSH_TLB: {
2936                 struct kvm_mmu_op_flush_tlb *ftlb;
2937
2938                 ftlb = pv_mmu_read_buffer(buffer, sizeof *ftlb);
2939                 if (!ftlb)
2940                         return 0;
2941                 return kvm_pv_mmu_flush_tlb(vcpu);
2942         }
2943         case KVM_MMU_OP_RELEASE_PT: {
2944                 struct kvm_mmu_op_release_pt *rpt;
2945
2946                 rpt = pv_mmu_read_buffer(buffer, sizeof *rpt);
2947                 if (!rpt)
2948                         return 0;
2949                 return kvm_pv_mmu_release_pt(vcpu, rpt->pt_phys);
2950         }
2951         default: return 0;
2952         }
2953 }
2954
2955 int kvm_pv_mmu_op(struct kvm_vcpu *vcpu, unsigned long bytes,
2956                   gpa_t addr, unsigned long *ret)
2957 {
2958         int r;
2959         struct kvm_pv_mmu_op_buffer *buffer = &vcpu->arch.mmu_op_buffer;
2960
2961         buffer->ptr = buffer->buf;
2962         buffer->len = min_t(unsigned long, bytes, sizeof buffer->buf);
2963         buffer->processed = 0;
2964
2965         r = kvm_read_guest(vcpu->kvm, addr, buffer->buf, buffer->len);
2966         if (r)
2967                 goto out;
2968
2969         while (buffer->len) {
2970                 r = kvm_pv_mmu_op_one(vcpu, buffer);
2971                 if (r < 0)
2972                         goto out;
2973                 if (r == 0)
2974                         break;
2975         }
2976
2977         r = 1;
2978 out:
2979         *ret = buffer->processed;
2980         return r;
2981 }
2982
2983 #ifdef AUDIT
2984
2985 static const char *audit_msg;
2986
2987 static gva_t canonicalize(gva_t gva)
2988 {
2989 #ifdef CONFIG_X86_64
2990         gva = (long long)(gva << 16) >> 16;
2991 #endif
2992         return gva;
2993 }
2994
2995 static void audit_mappings_page(struct kvm_vcpu *vcpu, u64 page_pte,
2996                                 gva_t va, int level)
2997 {
2998         u64 *pt = __va(page_pte & PT64_BASE_ADDR_MASK);
2999         int i;
3000         gva_t va_delta = 1ul << (PAGE_SHIFT + 9 * (level - 1));
3001
3002         for (i = 0; i < PT64_ENT_PER_PAGE; ++i, va += va_delta) {
3003                 u64 ent = pt[i];
3004
3005                 if (ent == shadow_trap_nonpresent_pte)
3006                         continue;
3007
3008                 va = canonicalize(va);
3009                 if (level > 1) {
3010                         if (ent == shadow_notrap_nonpresent_pte)
3011                                 printk(KERN_ERR "audit: (%s) nontrapping pte"
3012                                        " in nonleaf level: levels %d gva %lx"
3013                                        " level %d pte %llx\n", audit_msg,
3014                                        vcpu->arch.mmu.root_level, va, level, ent);
3015
3016                         audit_mappings_page(vcpu, ent, va, level - 1);
3017                 } else {
3018                         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, va);
3019                         hpa_t hpa = (hpa_t)gpa_to_pfn(vcpu, gpa) << PAGE_SHIFT;
3020
3021                         if (is_shadow_present_pte(ent)
3022                             && (ent & PT64_BASE_ADDR_MASK) != hpa)
3023                                 printk(KERN_ERR "xx audit error: (%s) levels %d"
3024                                        " gva %lx gpa %llx hpa %llx ent %llx %d\n",
3025                                        audit_msg, vcpu->arch.mmu.root_level,
3026                                        va, gpa, hpa, ent,
3027                                        is_shadow_present_pte(ent));
3028                         else if (ent == shadow_notrap_nonpresent_pte
3029                                  && !is_error_hpa(hpa))
3030                                 printk(KERN_ERR "audit: (%s) notrap shadow,"
3031                                        " valid guest gva %lx\n", audit_msg, va);
3032                         kvm_release_pfn_clean(pfn);
3033
3034                 }
3035         }
3036 }
3037
3038 static void audit_mappings(struct kvm_vcpu *vcpu)
3039 {
3040         unsigned i;
3041
3042         if (vcpu->arch.mmu.root_level == 4)
3043                 audit_mappings_page(vcpu, vcpu->arch.mmu.root_hpa, 0, 4);
3044         else
3045                 for (i = 0; i < 4; ++i)
3046                         if (vcpu->arch.mmu.pae_root[i] & PT_PRESENT_MASK)
3047                                 audit_mappings_page(vcpu,
3048                                                     vcpu->arch.mmu.pae_root[i],
3049                                                     i << 30,
3050                                                     2);
3051 }
3052
3053 static int count_rmaps(struct kvm_vcpu *vcpu)
3054 {
3055         int nmaps = 0;
3056         int i, j, k;
3057
3058         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
3059                 struct kvm_memory_slot *m = &vcpu->kvm->memslots[i];
3060                 struct kvm_rmap_desc *d;
3061
3062                 for (j = 0; j < m->npages; ++j) {
3063                         unsigned long *rmapp = &m->rmap[j];
3064
3065                         if (!*rmapp)
3066                                 continue;
3067                         if (!(*rmapp & 1)) {
3068                                 ++nmaps;
3069                                 continue;
3070                         }
3071                         d = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
3072                         while (d) {
3073                                 for (k = 0; k < RMAP_EXT; ++k)
3074                                         if (d->shadow_ptes[k])
3075                                                 ++nmaps;
3076                                         else
3077                                                 break;
3078                                 d = d->more;
3079                         }
3080                 }
3081         }
3082         return nmaps;
3083 }
3084
3085 static int count_writable_mappings(struct kvm_vcpu *vcpu)
3086 {
3087         int nmaps = 0;
3088         struct kvm_mmu_page *sp;
3089         int i;
3090
3091         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3092                 u64 *pt = sp->spt;
3093
3094                 if (sp->role.level != PT_PAGE_TABLE_LEVEL)
3095                         continue;
3096
3097                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3098                         u64 ent = pt[i];
3099
3100                         if (!(ent & PT_PRESENT_MASK))
3101                                 continue;
3102                         if (!(ent & PT_WRITABLE_MASK))
3103                                 continue;
3104                         ++nmaps;
3105                 }
3106         }
3107         return nmaps;
3108 }
3109
3110 static void audit_rmap(struct kvm_vcpu *vcpu)
3111 {
3112         int n_rmap = count_rmaps(vcpu);
3113         int n_actual = count_writable_mappings(vcpu);
3114
3115         if (n_rmap != n_actual)
3116                 printk(KERN_ERR "%s: (%s) rmap %d actual %d\n",
3117                        __func__, audit_msg, n_rmap, n_actual);
3118 }
3119
3120 static void audit_write_protection(struct kvm_vcpu *vcpu)
3121 {
3122         struct kvm_mmu_page *sp;
3123         struct kvm_memory_slot *slot;
3124         unsigned long *rmapp;
3125         gfn_t gfn;
3126
3127         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3128                 if (sp->role.metaphysical)
3129                         continue;
3130
3131                 gfn = unalias_gfn(vcpu->kvm, sp->gfn);
3132                 slot = gfn_to_memslot_unaliased(vcpu->kvm, sp->gfn);
3133                 rmapp = &slot->rmap[gfn - slot->base_gfn];
3134                 if (*rmapp)
3135                         printk(KERN_ERR "%s: (%s) shadow page has writable"
3136                                " mappings: gfn %lx role %x\n",
3137                                __func__, audit_msg, sp->gfn,
3138                                sp->role.word);
3139         }
3140 }
3141
3142 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg)
3143 {
3144         int olddbg = dbg;
3145
3146         dbg = 0;
3147         audit_msg = msg;
3148         audit_rmap(vcpu);
3149         audit_write_protection(vcpu);
3150         audit_mappings(vcpu);
3151         dbg = olddbg;
3152 }
3153
3154 #endif