KVM: MMU: Inherit a shadow page's guest level count from vcpu setup
[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 = vcpu->arch.mmu.base_role;
1208         role.level = level;
1209         role.metaphysical = metaphysical;
1210         role.access = access;
1211         if (vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
1212                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
1213                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
1214                 role.quadrant = quadrant;
1215         }
1216         pgprintk("%s: looking gfn %lx role %x\n", __func__,
1217                  gfn, role.word);
1218         index = kvm_page_table_hashfn(gfn);
1219         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1220         hlist_for_each_entry_safe(sp, node, tmp, bucket, hash_link)
1221                 if (sp->gfn == gfn) {
1222                         if (sp->unsync)
1223                                 if (kvm_sync_page(vcpu, sp))
1224                                         continue;
1225
1226                         if (sp->role.word != role.word)
1227                                 continue;
1228
1229                         mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1230                         if (sp->unsync_children) {
1231                                 set_bit(KVM_REQ_MMU_SYNC, &vcpu->requests);
1232                                 kvm_mmu_mark_parents_unsync(vcpu, sp);
1233                         }
1234                         pgprintk("%s: found\n", __func__);
1235                         return sp;
1236                 }
1237         ++vcpu->kvm->stat.mmu_cache_miss;
1238         sp = kvm_mmu_alloc_page(vcpu, parent_pte);
1239         if (!sp)
1240                 return sp;
1241         pgprintk("%s: adding gfn %lx role %x\n", __func__, gfn, role.word);
1242         sp->gfn = gfn;
1243         sp->role = role;
1244         hlist_add_head(&sp->hash_link, bucket);
1245         if (!metaphysical) {
1246                 if (rmap_write_protect(vcpu->kvm, gfn))
1247                         kvm_flush_remote_tlbs(vcpu->kvm);
1248                 account_shadowed(vcpu->kvm, gfn);
1249         }
1250         if (shadow_trap_nonpresent_pte != shadow_notrap_nonpresent_pte)
1251                 vcpu->arch.mmu.prefetch_page(vcpu, sp);
1252         else
1253                 nonpaging_prefetch_page(vcpu, sp);
1254         return sp;
1255 }
1256
1257 static int walk_shadow(struct kvm_shadow_walk *walker,
1258                        struct kvm_vcpu *vcpu, u64 addr)
1259 {
1260         hpa_t shadow_addr;
1261         int level;
1262         int r;
1263         u64 *sptep;
1264         unsigned index;
1265
1266         shadow_addr = vcpu->arch.mmu.root_hpa;
1267         level = vcpu->arch.mmu.shadow_root_level;
1268         if (level == PT32E_ROOT_LEVEL) {
1269                 shadow_addr = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
1270                 shadow_addr &= PT64_BASE_ADDR_MASK;
1271                 if (!shadow_addr)
1272                         return 1;
1273                 --level;
1274         }
1275
1276         while (level >= PT_PAGE_TABLE_LEVEL) {
1277                 index = SHADOW_PT_INDEX(addr, level);
1278                 sptep = ((u64 *)__va(shadow_addr)) + index;
1279                 r = walker->entry(walker, vcpu, addr, sptep, level);
1280                 if (r)
1281                         return r;
1282                 shadow_addr = *sptep & PT64_BASE_ADDR_MASK;
1283                 --level;
1284         }
1285         return 0;
1286 }
1287
1288 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
1289                                          struct kvm_mmu_page *sp)
1290 {
1291         unsigned i;
1292         u64 *pt;
1293         u64 ent;
1294
1295         pt = sp->spt;
1296
1297         if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1298                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1299                         if (is_shadow_present_pte(pt[i]))
1300                                 rmap_remove(kvm, &pt[i]);
1301                         pt[i] = shadow_trap_nonpresent_pte;
1302                 }
1303                 return;
1304         }
1305
1306         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1307                 ent = pt[i];
1308
1309                 if (is_shadow_present_pte(ent)) {
1310                         if (!is_large_pte(ent)) {
1311                                 ent &= PT64_BASE_ADDR_MASK;
1312                                 mmu_page_remove_parent_pte(page_header(ent),
1313                                                            &pt[i]);
1314                         } else {
1315                                 --kvm->stat.lpages;
1316                                 rmap_remove(kvm, &pt[i]);
1317                         }
1318                 }
1319                 pt[i] = shadow_trap_nonpresent_pte;
1320         }
1321 }
1322
1323 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
1324 {
1325         mmu_page_remove_parent_pte(sp, parent_pte);
1326 }
1327
1328 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
1329 {
1330         int i;
1331
1332         for (i = 0; i < KVM_MAX_VCPUS; ++i)
1333                 if (kvm->vcpus[i])
1334                         kvm->vcpus[i]->arch.last_pte_updated = NULL;
1335 }
1336
1337 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
1338 {
1339         u64 *parent_pte;
1340
1341         while (sp->multimapped || sp->parent_pte) {
1342                 if (!sp->multimapped)
1343                         parent_pte = sp->parent_pte;
1344                 else {
1345                         struct kvm_pte_chain *chain;
1346
1347                         chain = container_of(sp->parent_ptes.first,
1348                                              struct kvm_pte_chain, link);
1349                         parent_pte = chain->parent_ptes[0];
1350                 }
1351                 BUG_ON(!parent_pte);
1352                 kvm_mmu_put_page(sp, parent_pte);
1353                 set_shadow_pte(parent_pte, shadow_trap_nonpresent_pte);
1354         }
1355 }
1356
1357 static int mmu_zap_unsync_children(struct kvm *kvm,
1358                                    struct kvm_mmu_page *parent)
1359 {
1360         int i, zapped = 0;
1361         struct mmu_page_path parents;
1362         struct kvm_mmu_pages pages;
1363
1364         if (parent->role.level == PT_PAGE_TABLE_LEVEL)
1365                 return 0;
1366
1367         kvm_mmu_pages_init(parent, &parents, &pages);
1368         while (mmu_unsync_walk(parent, &pages)) {
1369                 struct kvm_mmu_page *sp;
1370
1371                 for_each_sp(pages, sp, parents, i) {
1372                         kvm_mmu_zap_page(kvm, sp);
1373                         mmu_pages_clear_parents(&parents);
1374                 }
1375                 zapped += pages.nr;
1376                 kvm_mmu_pages_init(parent, &parents, &pages);
1377         }
1378
1379         return zapped;
1380 }
1381
1382 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1383 {
1384         int ret;
1385         ++kvm->stat.mmu_shadow_zapped;
1386         ret = mmu_zap_unsync_children(kvm, sp);
1387         kvm_mmu_page_unlink_children(kvm, sp);
1388         kvm_mmu_unlink_parents(kvm, sp);
1389         kvm_flush_remote_tlbs(kvm);
1390         if (!sp->role.invalid && !sp->role.metaphysical)
1391                 unaccount_shadowed(kvm, sp->gfn);
1392         if (sp->unsync)
1393                 kvm_unlink_unsync_page(kvm, sp);
1394         if (!sp->root_count) {
1395                 hlist_del(&sp->hash_link);
1396                 kvm_mmu_free_page(kvm, sp);
1397         } else {
1398                 sp->role.invalid = 1;
1399                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
1400                 kvm_reload_remote_mmus(kvm);
1401         }
1402         kvm_mmu_reset_last_pte_updated(kvm);
1403         return ret;
1404 }
1405
1406 /*
1407  * Changing the number of mmu pages allocated to the vm
1408  * Note: if kvm_nr_mmu_pages is too small, you will get dead lock
1409  */
1410 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int kvm_nr_mmu_pages)
1411 {
1412         /*
1413          * If we set the number of mmu pages to be smaller be than the
1414          * number of actived pages , we must to free some mmu pages before we
1415          * change the value
1416          */
1417
1418         if ((kvm->arch.n_alloc_mmu_pages - kvm->arch.n_free_mmu_pages) >
1419             kvm_nr_mmu_pages) {
1420                 int n_used_mmu_pages = kvm->arch.n_alloc_mmu_pages
1421                                        - kvm->arch.n_free_mmu_pages;
1422
1423                 while (n_used_mmu_pages > kvm_nr_mmu_pages) {
1424                         struct kvm_mmu_page *page;
1425
1426                         page = container_of(kvm->arch.active_mmu_pages.prev,
1427                                             struct kvm_mmu_page, link);
1428                         kvm_mmu_zap_page(kvm, page);
1429                         n_used_mmu_pages--;
1430                 }
1431                 kvm->arch.n_free_mmu_pages = 0;
1432         }
1433         else
1434                 kvm->arch.n_free_mmu_pages += kvm_nr_mmu_pages
1435                                          - kvm->arch.n_alloc_mmu_pages;
1436
1437         kvm->arch.n_alloc_mmu_pages = kvm_nr_mmu_pages;
1438 }
1439
1440 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
1441 {
1442         unsigned index;
1443         struct hlist_head *bucket;
1444         struct kvm_mmu_page *sp;
1445         struct hlist_node *node, *n;
1446         int r;
1447
1448         pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1449         r = 0;
1450         index = kvm_page_table_hashfn(gfn);
1451         bucket = &kvm->arch.mmu_page_hash[index];
1452         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link)
1453                 if (sp->gfn == gfn && !sp->role.metaphysical) {
1454                         pgprintk("%s: gfn %lx role %x\n", __func__, gfn,
1455                                  sp->role.word);
1456                         r = 1;
1457                         if (kvm_mmu_zap_page(kvm, sp))
1458                                 n = bucket->first;
1459                 }
1460         return r;
1461 }
1462
1463 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
1464 {
1465         struct kvm_mmu_page *sp;
1466
1467         while ((sp = kvm_mmu_lookup_page(kvm, gfn)) != NULL) {
1468                 pgprintk("%s: zap %lx %x\n", __func__, gfn, sp->role.word);
1469                 kvm_mmu_zap_page(kvm, sp);
1470         }
1471 }
1472
1473 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
1474 {
1475         int slot = memslot_id(kvm, gfn_to_memslot(kvm, gfn));
1476         struct kvm_mmu_page *sp = page_header(__pa(pte));
1477
1478         __set_bit(slot, sp->slot_bitmap);
1479 }
1480
1481 static void mmu_convert_notrap(struct kvm_mmu_page *sp)
1482 {
1483         int i;
1484         u64 *pt = sp->spt;
1485
1486         if (shadow_trap_nonpresent_pte == shadow_notrap_nonpresent_pte)
1487                 return;
1488
1489         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1490                 if (pt[i] == shadow_notrap_nonpresent_pte)
1491                         set_shadow_pte(&pt[i], shadow_trap_nonpresent_pte);
1492         }
1493 }
1494
1495 struct page *gva_to_page(struct kvm_vcpu *vcpu, gva_t gva)
1496 {
1497         struct page *page;
1498
1499         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1500
1501         if (gpa == UNMAPPED_GVA)
1502                 return NULL;
1503
1504         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1505
1506         return page;
1507 }
1508
1509 /*
1510  * The function is based on mtrr_type_lookup() in
1511  * arch/x86/kernel/cpu/mtrr/generic.c
1512  */
1513 static int get_mtrr_type(struct mtrr_state_type *mtrr_state,
1514                          u64 start, u64 end)
1515 {
1516         int i;
1517         u64 base, mask;
1518         u8 prev_match, curr_match;
1519         int num_var_ranges = KVM_NR_VAR_MTRR;
1520
1521         if (!mtrr_state->enabled)
1522                 return 0xFF;
1523
1524         /* Make end inclusive end, instead of exclusive */
1525         end--;
1526
1527         /* Look in fixed ranges. Just return the type as per start */
1528         if (mtrr_state->have_fixed && (start < 0x100000)) {
1529                 int idx;
1530
1531                 if (start < 0x80000) {
1532                         idx = 0;
1533                         idx += (start >> 16);
1534                         return mtrr_state->fixed_ranges[idx];
1535                 } else if (start < 0xC0000) {
1536                         idx = 1 * 8;
1537                         idx += ((start - 0x80000) >> 14);
1538                         return mtrr_state->fixed_ranges[idx];
1539                 } else if (start < 0x1000000) {
1540                         idx = 3 * 8;
1541                         idx += ((start - 0xC0000) >> 12);
1542                         return mtrr_state->fixed_ranges[idx];
1543                 }
1544         }
1545
1546         /*
1547          * Look in variable ranges
1548          * Look of multiple ranges matching this address and pick type
1549          * as per MTRR precedence
1550          */
1551         if (!(mtrr_state->enabled & 2))
1552                 return mtrr_state->def_type;
1553
1554         prev_match = 0xFF;
1555         for (i = 0; i < num_var_ranges; ++i) {
1556                 unsigned short start_state, end_state;
1557
1558                 if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11)))
1559                         continue;
1560
1561                 base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) +
1562                        (mtrr_state->var_ranges[i].base_lo & PAGE_MASK);
1563                 mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) +
1564                        (mtrr_state->var_ranges[i].mask_lo & PAGE_MASK);
1565
1566                 start_state = ((start & mask) == (base & mask));
1567                 end_state = ((end & mask) == (base & mask));
1568                 if (start_state != end_state)
1569                         return 0xFE;
1570
1571                 if ((start & mask) != (base & mask))
1572                         continue;
1573
1574                 curr_match = mtrr_state->var_ranges[i].base_lo & 0xff;
1575                 if (prev_match == 0xFF) {
1576                         prev_match = curr_match;
1577                         continue;
1578                 }
1579
1580                 if (prev_match == MTRR_TYPE_UNCACHABLE ||
1581                     curr_match == MTRR_TYPE_UNCACHABLE)
1582                         return MTRR_TYPE_UNCACHABLE;
1583
1584                 if ((prev_match == MTRR_TYPE_WRBACK &&
1585                      curr_match == MTRR_TYPE_WRTHROUGH) ||
1586                     (prev_match == MTRR_TYPE_WRTHROUGH &&
1587                      curr_match == MTRR_TYPE_WRBACK)) {
1588                         prev_match = MTRR_TYPE_WRTHROUGH;
1589                         curr_match = MTRR_TYPE_WRTHROUGH;
1590                 }
1591
1592                 if (prev_match != curr_match)
1593                         return MTRR_TYPE_UNCACHABLE;
1594         }
1595
1596         if (prev_match != 0xFF)
1597                 return prev_match;
1598
1599         return mtrr_state->def_type;
1600 }
1601
1602 static u8 get_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn)
1603 {
1604         u8 mtrr;
1605
1606         mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT,
1607                              (gfn << PAGE_SHIFT) + PAGE_SIZE);
1608         if (mtrr == 0xfe || mtrr == 0xff)
1609                 mtrr = MTRR_TYPE_WRBACK;
1610         return mtrr;
1611 }
1612
1613 static int kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1614 {
1615         unsigned index;
1616         struct hlist_head *bucket;
1617         struct kvm_mmu_page *s;
1618         struct hlist_node *node, *n;
1619
1620         index = kvm_page_table_hashfn(sp->gfn);
1621         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1622         /* don't unsync if pagetable is shadowed with multiple roles */
1623         hlist_for_each_entry_safe(s, node, n, bucket, hash_link) {
1624                 if (s->gfn != sp->gfn || s->role.metaphysical)
1625                         continue;
1626                 if (s->role.word != sp->role.word)
1627                         return 1;
1628         }
1629         ++vcpu->kvm->stat.mmu_unsync;
1630         sp->unsync = 1;
1631
1632         if (sp->global) {
1633                 list_add(&sp->oos_link, &vcpu->kvm->arch.oos_global_pages);
1634                 ++vcpu->kvm->stat.mmu_unsync_global;
1635         } else
1636                 kvm_mmu_mark_parents_unsync(vcpu, sp);
1637
1638         mmu_convert_notrap(sp);
1639         return 0;
1640 }
1641
1642 static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
1643                                   bool can_unsync)
1644 {
1645         struct kvm_mmu_page *shadow;
1646
1647         shadow = kvm_mmu_lookup_page(vcpu->kvm, gfn);
1648         if (shadow) {
1649                 if (shadow->role.level != PT_PAGE_TABLE_LEVEL)
1650                         return 1;
1651                 if (shadow->unsync)
1652                         return 0;
1653                 if (can_unsync && oos_shadow)
1654                         return kvm_unsync_page(vcpu, shadow);
1655                 return 1;
1656         }
1657         return 0;
1658 }
1659
1660 static int set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
1661                     unsigned pte_access, int user_fault,
1662                     int write_fault, int dirty, int largepage,
1663                     int global, gfn_t gfn, pfn_t pfn, bool speculative,
1664                     bool can_unsync)
1665 {
1666         u64 spte;
1667         int ret = 0;
1668         u64 mt_mask = shadow_mt_mask;
1669         struct kvm_mmu_page *sp = page_header(__pa(shadow_pte));
1670
1671         if (!(vcpu->arch.cr4 & X86_CR4_PGE))
1672                 global = 0;
1673         if (!global && sp->global) {
1674                 sp->global = 0;
1675                 if (sp->unsync) {
1676                         kvm_unlink_unsync_global(vcpu->kvm, sp);
1677                         kvm_mmu_mark_parents_unsync(vcpu, sp);
1678                 }
1679         }
1680
1681         /*
1682          * We don't set the accessed bit, since we sometimes want to see
1683          * whether the guest actually used the pte (in order to detect
1684          * demand paging).
1685          */
1686         spte = shadow_base_present_pte | shadow_dirty_mask;
1687         if (!speculative)
1688                 spte |= shadow_accessed_mask;
1689         if (!dirty)
1690                 pte_access &= ~ACC_WRITE_MASK;
1691         if (pte_access & ACC_EXEC_MASK)
1692                 spte |= shadow_x_mask;
1693         else
1694                 spte |= shadow_nx_mask;
1695         if (pte_access & ACC_USER_MASK)
1696                 spte |= shadow_user_mask;
1697         if (largepage)
1698                 spte |= PT_PAGE_SIZE_MASK;
1699         if (mt_mask) {
1700                 if (!kvm_is_mmio_pfn(pfn)) {
1701                         mt_mask = get_memory_type(vcpu, gfn) <<
1702                                 kvm_x86_ops->get_mt_mask_shift();
1703                         mt_mask |= VMX_EPT_IGMT_BIT;
1704                 } else
1705                         mt_mask = MTRR_TYPE_UNCACHABLE <<
1706                                 kvm_x86_ops->get_mt_mask_shift();
1707                 spte |= mt_mask;
1708         }
1709
1710         spte |= (u64)pfn << PAGE_SHIFT;
1711
1712         if ((pte_access & ACC_WRITE_MASK)
1713             || (write_fault && !is_write_protection(vcpu) && !user_fault)) {
1714
1715                 if (largepage && has_wrprotected_page(vcpu->kvm, gfn)) {
1716                         ret = 1;
1717                         spte = shadow_trap_nonpresent_pte;
1718                         goto set_pte;
1719                 }
1720
1721                 spte |= PT_WRITABLE_MASK;
1722
1723                 /*
1724                  * Optimization: for pte sync, if spte was writable the hash
1725                  * lookup is unnecessary (and expensive). Write protection
1726                  * is responsibility of mmu_get_page / kvm_sync_page.
1727                  * Same reasoning can be applied to dirty page accounting.
1728                  */
1729                 if (!can_unsync && is_writeble_pte(*shadow_pte))
1730                         goto set_pte;
1731
1732                 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
1733                         pgprintk("%s: found shadow page for %lx, marking ro\n",
1734                                  __func__, gfn);
1735                         ret = 1;
1736                         pte_access &= ~ACC_WRITE_MASK;
1737                         if (is_writeble_pte(spte))
1738                                 spte &= ~PT_WRITABLE_MASK;
1739                 }
1740         }
1741
1742         if (pte_access & ACC_WRITE_MASK)
1743                 mark_page_dirty(vcpu->kvm, gfn);
1744
1745 set_pte:
1746         set_shadow_pte(shadow_pte, spte);
1747         return ret;
1748 }
1749
1750 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
1751                          unsigned pt_access, unsigned pte_access,
1752                          int user_fault, int write_fault, int dirty,
1753                          int *ptwrite, int largepage, int global,
1754                          gfn_t gfn, pfn_t pfn, bool speculative)
1755 {
1756         int was_rmapped = 0;
1757         int was_writeble = is_writeble_pte(*shadow_pte);
1758
1759         pgprintk("%s: spte %llx access %x write_fault %d"
1760                  " user_fault %d gfn %lx\n",
1761                  __func__, *shadow_pte, pt_access,
1762                  write_fault, user_fault, gfn);
1763
1764         if (is_rmap_pte(*shadow_pte)) {
1765                 /*
1766                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
1767                  * the parent of the now unreachable PTE.
1768                  */
1769                 if (largepage && !is_large_pte(*shadow_pte)) {
1770                         struct kvm_mmu_page *child;
1771                         u64 pte = *shadow_pte;
1772
1773                         child = page_header(pte & PT64_BASE_ADDR_MASK);
1774                         mmu_page_remove_parent_pte(child, shadow_pte);
1775                 } else if (pfn != spte_to_pfn(*shadow_pte)) {
1776                         pgprintk("hfn old %lx new %lx\n",
1777                                  spte_to_pfn(*shadow_pte), pfn);
1778                         rmap_remove(vcpu->kvm, shadow_pte);
1779                 } else {
1780                         if (largepage)
1781                                 was_rmapped = is_large_pte(*shadow_pte);
1782                         else
1783                                 was_rmapped = 1;
1784                 }
1785         }
1786         if (set_spte(vcpu, shadow_pte, pte_access, user_fault, write_fault,
1787                       dirty, largepage, global, gfn, pfn, speculative, true)) {
1788                 if (write_fault)
1789                         *ptwrite = 1;
1790                 kvm_x86_ops->tlb_flush(vcpu);
1791         }
1792
1793         pgprintk("%s: setting spte %llx\n", __func__, *shadow_pte);
1794         pgprintk("instantiating %s PTE (%s) at %ld (%llx) addr %p\n",
1795                  is_large_pte(*shadow_pte)? "2MB" : "4kB",
1796                  is_present_pte(*shadow_pte)?"RW":"R", gfn,
1797                  *shadow_pte, shadow_pte);
1798         if (!was_rmapped && is_large_pte(*shadow_pte))
1799                 ++vcpu->kvm->stat.lpages;
1800
1801         page_header_update_slot(vcpu->kvm, shadow_pte, gfn);
1802         if (!was_rmapped) {
1803                 rmap_add(vcpu, shadow_pte, gfn, largepage);
1804                 if (!is_rmap_pte(*shadow_pte))
1805                         kvm_release_pfn_clean(pfn);
1806         } else {
1807                 if (was_writeble)
1808                         kvm_release_pfn_dirty(pfn);
1809                 else
1810                         kvm_release_pfn_clean(pfn);
1811         }
1812         if (speculative) {
1813                 vcpu->arch.last_pte_updated = shadow_pte;
1814                 vcpu->arch.last_pte_gfn = gfn;
1815         }
1816 }
1817
1818 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
1819 {
1820 }
1821
1822 struct direct_shadow_walk {
1823         struct kvm_shadow_walk walker;
1824         pfn_t pfn;
1825         int write;
1826         int largepage;
1827         int pt_write;
1828 };
1829
1830 static int direct_map_entry(struct kvm_shadow_walk *_walk,
1831                             struct kvm_vcpu *vcpu,
1832                             u64 addr, u64 *sptep, int level)
1833 {
1834         struct direct_shadow_walk *walk =
1835                 container_of(_walk, struct direct_shadow_walk, walker);
1836         struct kvm_mmu_page *sp;
1837         gfn_t pseudo_gfn;
1838         gfn_t gfn = addr >> PAGE_SHIFT;
1839
1840         if (level == PT_PAGE_TABLE_LEVEL
1841             || (walk->largepage && level == PT_DIRECTORY_LEVEL)) {
1842                 mmu_set_spte(vcpu, sptep, ACC_ALL, ACC_ALL,
1843                              0, walk->write, 1, &walk->pt_write,
1844                              walk->largepage, 0, gfn, walk->pfn, false);
1845                 ++vcpu->stat.pf_fixed;
1846                 return 1;
1847         }
1848
1849         if (*sptep == shadow_trap_nonpresent_pte) {
1850                 pseudo_gfn = (addr & PT64_DIR_BASE_ADDR_MASK) >> PAGE_SHIFT;
1851                 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, (gva_t)addr, level - 1,
1852                                       1, ACC_ALL, sptep);
1853                 if (!sp) {
1854                         pgprintk("nonpaging_map: ENOMEM\n");
1855                         kvm_release_pfn_clean(walk->pfn);
1856                         return -ENOMEM;
1857                 }
1858
1859                 set_shadow_pte(sptep,
1860                                __pa(sp->spt)
1861                                | PT_PRESENT_MASK | PT_WRITABLE_MASK
1862                                | shadow_user_mask | shadow_x_mask);
1863         }
1864         return 0;
1865 }
1866
1867 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
1868                         int largepage, gfn_t gfn, pfn_t pfn)
1869 {
1870         int r;
1871         struct direct_shadow_walk walker = {
1872                 .walker = { .entry = direct_map_entry, },
1873                 .pfn = pfn,
1874                 .largepage = largepage,
1875                 .write = write,
1876                 .pt_write = 0,
1877         };
1878
1879         r = walk_shadow(&walker.walker, vcpu, gfn << PAGE_SHIFT);
1880         if (r < 0)
1881                 return r;
1882         return walker.pt_write;
1883 }
1884
1885 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn)
1886 {
1887         int r;
1888         int largepage = 0;
1889         pfn_t pfn;
1890         unsigned long mmu_seq;
1891
1892         if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
1893                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
1894                 largepage = 1;
1895         }
1896
1897         mmu_seq = vcpu->kvm->mmu_notifier_seq;
1898         smp_rmb();
1899         pfn = gfn_to_pfn(vcpu->kvm, gfn);
1900
1901         /* mmio */
1902         if (is_error_pfn(pfn)) {
1903                 kvm_release_pfn_clean(pfn);
1904                 return 1;
1905         }
1906
1907         spin_lock(&vcpu->kvm->mmu_lock);
1908         if (mmu_notifier_retry(vcpu, mmu_seq))
1909                 goto out_unlock;
1910         kvm_mmu_free_some_pages(vcpu);
1911         r = __direct_map(vcpu, v, write, largepage, gfn, pfn);
1912         spin_unlock(&vcpu->kvm->mmu_lock);
1913
1914
1915         return r;
1916
1917 out_unlock:
1918         spin_unlock(&vcpu->kvm->mmu_lock);
1919         kvm_release_pfn_clean(pfn);
1920         return 0;
1921 }
1922
1923
1924 static void mmu_free_roots(struct kvm_vcpu *vcpu)
1925 {
1926         int i;
1927         struct kvm_mmu_page *sp;
1928
1929         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1930                 return;
1931         spin_lock(&vcpu->kvm->mmu_lock);
1932         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1933                 hpa_t root = vcpu->arch.mmu.root_hpa;
1934
1935                 sp = page_header(root);
1936                 --sp->root_count;
1937                 if (!sp->root_count && sp->role.invalid)
1938                         kvm_mmu_zap_page(vcpu->kvm, sp);
1939                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1940                 spin_unlock(&vcpu->kvm->mmu_lock);
1941                 return;
1942         }
1943         for (i = 0; i < 4; ++i) {
1944                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1945
1946                 if (root) {
1947                         root &= PT64_BASE_ADDR_MASK;
1948                         sp = page_header(root);
1949                         --sp->root_count;
1950                         if (!sp->root_count && sp->role.invalid)
1951                                 kvm_mmu_zap_page(vcpu->kvm, sp);
1952                 }
1953                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1954         }
1955         spin_unlock(&vcpu->kvm->mmu_lock);
1956         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1957 }
1958
1959 static void mmu_alloc_roots(struct kvm_vcpu *vcpu)
1960 {
1961         int i;
1962         gfn_t root_gfn;
1963         struct kvm_mmu_page *sp;
1964         int metaphysical = 0;
1965
1966         root_gfn = vcpu->arch.cr3 >> PAGE_SHIFT;
1967
1968         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1969                 hpa_t root = vcpu->arch.mmu.root_hpa;
1970
1971                 ASSERT(!VALID_PAGE(root));
1972                 if (tdp_enabled)
1973                         metaphysical = 1;
1974                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
1975                                       PT64_ROOT_LEVEL, metaphysical,
1976                                       ACC_ALL, NULL);
1977                 root = __pa(sp->spt);
1978                 ++sp->root_count;
1979                 vcpu->arch.mmu.root_hpa = root;
1980                 return;
1981         }
1982         metaphysical = !is_paging(vcpu);
1983         if (tdp_enabled)
1984                 metaphysical = 1;
1985         for (i = 0; i < 4; ++i) {
1986                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1987
1988                 ASSERT(!VALID_PAGE(root));
1989                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
1990                         if (!is_present_pte(vcpu->arch.pdptrs[i])) {
1991                                 vcpu->arch.mmu.pae_root[i] = 0;
1992                                 continue;
1993                         }
1994                         root_gfn = vcpu->arch.pdptrs[i] >> PAGE_SHIFT;
1995                 } else if (vcpu->arch.mmu.root_level == 0)
1996                         root_gfn = 0;
1997                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
1998                                       PT32_ROOT_LEVEL, metaphysical,
1999                                       ACC_ALL, NULL);
2000                 root = __pa(sp->spt);
2001                 ++sp->root_count;
2002                 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
2003         }
2004         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
2005 }
2006
2007 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
2008 {
2009         int i;
2010         struct kvm_mmu_page *sp;
2011
2012         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2013                 return;
2014         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2015                 hpa_t root = vcpu->arch.mmu.root_hpa;
2016                 sp = page_header(root);
2017                 mmu_sync_children(vcpu, sp);
2018                 return;
2019         }
2020         for (i = 0; i < 4; ++i) {
2021                 hpa_t root = vcpu->arch.mmu.pae_root[i];
2022
2023                 if (root) {
2024                         root &= PT64_BASE_ADDR_MASK;
2025                         sp = page_header(root);
2026                         mmu_sync_children(vcpu, sp);
2027                 }
2028         }
2029 }
2030
2031 static void mmu_sync_global(struct kvm_vcpu *vcpu)
2032 {
2033         struct kvm *kvm = vcpu->kvm;
2034         struct kvm_mmu_page *sp, *n;
2035
2036         list_for_each_entry_safe(sp, n, &kvm->arch.oos_global_pages, oos_link)
2037                 kvm_sync_page(vcpu, sp);
2038 }
2039
2040 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
2041 {
2042         spin_lock(&vcpu->kvm->mmu_lock);
2043         mmu_sync_roots(vcpu);
2044         spin_unlock(&vcpu->kvm->mmu_lock);
2045 }
2046
2047 void kvm_mmu_sync_global(struct kvm_vcpu *vcpu)
2048 {
2049         spin_lock(&vcpu->kvm->mmu_lock);
2050         mmu_sync_global(vcpu);
2051         spin_unlock(&vcpu->kvm->mmu_lock);
2052 }
2053
2054 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr)
2055 {
2056         return vaddr;
2057 }
2058
2059 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
2060                                 u32 error_code)
2061 {
2062         gfn_t gfn;
2063         int r;
2064
2065         pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
2066         r = mmu_topup_memory_caches(vcpu);
2067         if (r)
2068                 return r;
2069
2070         ASSERT(vcpu);
2071         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2072
2073         gfn = gva >> PAGE_SHIFT;
2074
2075         return nonpaging_map(vcpu, gva & PAGE_MASK,
2076                              error_code & PFERR_WRITE_MASK, gfn);
2077 }
2078
2079 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
2080                                 u32 error_code)
2081 {
2082         pfn_t pfn;
2083         int r;
2084         int largepage = 0;
2085         gfn_t gfn = gpa >> PAGE_SHIFT;
2086         unsigned long mmu_seq;
2087
2088         ASSERT(vcpu);
2089         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2090
2091         r = mmu_topup_memory_caches(vcpu);
2092         if (r)
2093                 return r;
2094
2095         if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
2096                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
2097                 largepage = 1;
2098         }
2099         mmu_seq = vcpu->kvm->mmu_notifier_seq;
2100         smp_rmb();
2101         pfn = gfn_to_pfn(vcpu->kvm, gfn);
2102         if (is_error_pfn(pfn)) {
2103                 kvm_release_pfn_clean(pfn);
2104                 return 1;
2105         }
2106         spin_lock(&vcpu->kvm->mmu_lock);
2107         if (mmu_notifier_retry(vcpu, mmu_seq))
2108                 goto out_unlock;
2109         kvm_mmu_free_some_pages(vcpu);
2110         r = __direct_map(vcpu, gpa, error_code & PFERR_WRITE_MASK,
2111                          largepage, gfn, pfn);
2112         spin_unlock(&vcpu->kvm->mmu_lock);
2113
2114         return r;
2115
2116 out_unlock:
2117         spin_unlock(&vcpu->kvm->mmu_lock);
2118         kvm_release_pfn_clean(pfn);
2119         return 0;
2120 }
2121
2122 static void nonpaging_free(struct kvm_vcpu *vcpu)
2123 {
2124         mmu_free_roots(vcpu);
2125 }
2126
2127 static int nonpaging_init_context(struct kvm_vcpu *vcpu)
2128 {
2129         struct kvm_mmu *context = &vcpu->arch.mmu;
2130
2131         context->new_cr3 = nonpaging_new_cr3;
2132         context->page_fault = nonpaging_page_fault;
2133         context->gva_to_gpa = nonpaging_gva_to_gpa;
2134         context->free = nonpaging_free;
2135         context->prefetch_page = nonpaging_prefetch_page;
2136         context->sync_page = nonpaging_sync_page;
2137         context->invlpg = nonpaging_invlpg;
2138         context->root_level = 0;
2139         context->shadow_root_level = PT32E_ROOT_LEVEL;
2140         context->root_hpa = INVALID_PAGE;
2141         return 0;
2142 }
2143
2144 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2145 {
2146         ++vcpu->stat.tlb_flush;
2147         kvm_x86_ops->tlb_flush(vcpu);
2148 }
2149
2150 static void paging_new_cr3(struct kvm_vcpu *vcpu)
2151 {
2152         pgprintk("%s: cr3 %lx\n", __func__, vcpu->arch.cr3);
2153         mmu_free_roots(vcpu);
2154 }
2155
2156 static void inject_page_fault(struct kvm_vcpu *vcpu,
2157                               u64 addr,
2158                               u32 err_code)
2159 {
2160         kvm_inject_page_fault(vcpu, addr, err_code);
2161 }
2162
2163 static void paging_free(struct kvm_vcpu *vcpu)
2164 {
2165         nonpaging_free(vcpu);
2166 }
2167
2168 #define PTTYPE 64
2169 #include "paging_tmpl.h"
2170 #undef PTTYPE
2171
2172 #define PTTYPE 32
2173 #include "paging_tmpl.h"
2174 #undef PTTYPE
2175
2176 static int paging64_init_context_common(struct kvm_vcpu *vcpu, int level)
2177 {
2178         struct kvm_mmu *context = &vcpu->arch.mmu;
2179
2180         ASSERT(is_pae(vcpu));
2181         context->new_cr3 = paging_new_cr3;
2182         context->page_fault = paging64_page_fault;
2183         context->gva_to_gpa = paging64_gva_to_gpa;
2184         context->prefetch_page = paging64_prefetch_page;
2185         context->sync_page = paging64_sync_page;
2186         context->invlpg = paging64_invlpg;
2187         context->free = paging_free;
2188         context->root_level = level;
2189         context->shadow_root_level = level;
2190         context->root_hpa = INVALID_PAGE;
2191         return 0;
2192 }
2193
2194 static int paging64_init_context(struct kvm_vcpu *vcpu)
2195 {
2196         return paging64_init_context_common(vcpu, PT64_ROOT_LEVEL);
2197 }
2198
2199 static int paging32_init_context(struct kvm_vcpu *vcpu)
2200 {
2201         struct kvm_mmu *context = &vcpu->arch.mmu;
2202
2203         context->new_cr3 = paging_new_cr3;
2204         context->page_fault = paging32_page_fault;
2205         context->gva_to_gpa = paging32_gva_to_gpa;
2206         context->free = paging_free;
2207         context->prefetch_page = paging32_prefetch_page;
2208         context->sync_page = paging32_sync_page;
2209         context->invlpg = paging32_invlpg;
2210         context->root_level = PT32_ROOT_LEVEL;
2211         context->shadow_root_level = PT32E_ROOT_LEVEL;
2212         context->root_hpa = INVALID_PAGE;
2213         return 0;
2214 }
2215
2216 static int paging32E_init_context(struct kvm_vcpu *vcpu)
2217 {
2218         return paging64_init_context_common(vcpu, PT32E_ROOT_LEVEL);
2219 }
2220
2221 static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
2222 {
2223         struct kvm_mmu *context = &vcpu->arch.mmu;
2224
2225         context->new_cr3 = nonpaging_new_cr3;
2226         context->page_fault = tdp_page_fault;
2227         context->free = nonpaging_free;
2228         context->prefetch_page = nonpaging_prefetch_page;
2229         context->sync_page = nonpaging_sync_page;
2230         context->invlpg = nonpaging_invlpg;
2231         context->shadow_root_level = kvm_x86_ops->get_tdp_level();
2232         context->root_hpa = INVALID_PAGE;
2233
2234         if (!is_paging(vcpu)) {
2235                 context->gva_to_gpa = nonpaging_gva_to_gpa;
2236                 context->root_level = 0;
2237         } else if (is_long_mode(vcpu)) {
2238                 context->gva_to_gpa = paging64_gva_to_gpa;
2239                 context->root_level = PT64_ROOT_LEVEL;
2240         } else if (is_pae(vcpu)) {
2241                 context->gva_to_gpa = paging64_gva_to_gpa;
2242                 context->root_level = PT32E_ROOT_LEVEL;
2243         } else {
2244                 context->gva_to_gpa = paging32_gva_to_gpa;
2245                 context->root_level = PT32_ROOT_LEVEL;
2246         }
2247
2248         return 0;
2249 }
2250
2251 static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
2252 {
2253         int r;
2254
2255         ASSERT(vcpu);
2256         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2257
2258         if (!is_paging(vcpu))
2259                 r = nonpaging_init_context(vcpu);
2260         else if (is_long_mode(vcpu))
2261                 r = paging64_init_context(vcpu);
2262         else if (is_pae(vcpu))
2263                 r = paging32E_init_context(vcpu);
2264         else
2265                 r = paging32_init_context(vcpu);
2266
2267         vcpu->arch.mmu.base_role.glevels = vcpu->arch.mmu.root_level;
2268
2269         return r;
2270 }
2271
2272 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
2273 {
2274         vcpu->arch.update_pte.pfn = bad_pfn;
2275
2276         if (tdp_enabled)
2277                 return init_kvm_tdp_mmu(vcpu);
2278         else
2279                 return init_kvm_softmmu(vcpu);
2280 }
2281
2282 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
2283 {
2284         ASSERT(vcpu);
2285         if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) {
2286                 vcpu->arch.mmu.free(vcpu);
2287                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
2288         }
2289 }
2290
2291 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
2292 {
2293         destroy_kvm_mmu(vcpu);
2294         return init_kvm_mmu(vcpu);
2295 }
2296 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
2297
2298 int kvm_mmu_load(struct kvm_vcpu *vcpu)
2299 {
2300         int r;
2301
2302         r = mmu_topup_memory_caches(vcpu);
2303         if (r)
2304                 goto out;
2305         spin_lock(&vcpu->kvm->mmu_lock);
2306         kvm_mmu_free_some_pages(vcpu);
2307         mmu_alloc_roots(vcpu);
2308         mmu_sync_roots(vcpu);
2309         spin_unlock(&vcpu->kvm->mmu_lock);
2310         kvm_x86_ops->set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
2311         kvm_mmu_flush_tlb(vcpu);
2312 out:
2313         return r;
2314 }
2315 EXPORT_SYMBOL_GPL(kvm_mmu_load);
2316
2317 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
2318 {
2319         mmu_free_roots(vcpu);
2320 }
2321
2322 static void mmu_pte_write_zap_pte(struct kvm_vcpu *vcpu,
2323                                   struct kvm_mmu_page *sp,
2324                                   u64 *spte)
2325 {
2326         u64 pte;
2327         struct kvm_mmu_page *child;
2328
2329         pte = *spte;
2330         if (is_shadow_present_pte(pte)) {
2331                 if (sp->role.level == PT_PAGE_TABLE_LEVEL ||
2332                     is_large_pte(pte))
2333                         rmap_remove(vcpu->kvm, spte);
2334                 else {
2335                         child = page_header(pte & PT64_BASE_ADDR_MASK);
2336                         mmu_page_remove_parent_pte(child, spte);
2337                 }
2338         }
2339         set_shadow_pte(spte, shadow_trap_nonpresent_pte);
2340         if (is_large_pte(pte))
2341                 --vcpu->kvm->stat.lpages;
2342 }
2343
2344 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
2345                                   struct kvm_mmu_page *sp,
2346                                   u64 *spte,
2347                                   const void *new)
2348 {
2349         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
2350                 if (!vcpu->arch.update_pte.largepage ||
2351                     sp->role.glevels == PT32_ROOT_LEVEL) {
2352                         ++vcpu->kvm->stat.mmu_pde_zapped;
2353                         return;
2354                 }
2355         }
2356
2357         ++vcpu->kvm->stat.mmu_pte_updated;
2358         if (sp->role.glevels == PT32_ROOT_LEVEL)
2359                 paging32_update_pte(vcpu, sp, spte, new);
2360         else
2361                 paging64_update_pte(vcpu, sp, spte, new);
2362 }
2363
2364 static bool need_remote_flush(u64 old, u64 new)
2365 {
2366         if (!is_shadow_present_pte(old))
2367                 return false;
2368         if (!is_shadow_present_pte(new))
2369                 return true;
2370         if ((old ^ new) & PT64_BASE_ADDR_MASK)
2371                 return true;
2372         old ^= PT64_NX_MASK;
2373         new ^= PT64_NX_MASK;
2374         return (old & ~new & PT64_PERM_MASK) != 0;
2375 }
2376
2377 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, u64 old, u64 new)
2378 {
2379         if (need_remote_flush(old, new))
2380                 kvm_flush_remote_tlbs(vcpu->kvm);
2381         else
2382                 kvm_mmu_flush_tlb(vcpu);
2383 }
2384
2385 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
2386 {
2387         u64 *spte = vcpu->arch.last_pte_updated;
2388
2389         return !!(spte && (*spte & shadow_accessed_mask));
2390 }
2391
2392 static void mmu_guess_page_from_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2393                                           const u8 *new, int bytes)
2394 {
2395         gfn_t gfn;
2396         int r;
2397         u64 gpte = 0;
2398         pfn_t pfn;
2399
2400         vcpu->arch.update_pte.largepage = 0;
2401
2402         if (bytes != 4 && bytes != 8)
2403                 return;
2404
2405         /*
2406          * Assume that the pte write on a page table of the same type
2407          * as the current vcpu paging mode.  This is nearly always true
2408          * (might be false while changing modes).  Note it is verified later
2409          * by update_pte().
2410          */
2411         if (is_pae(vcpu)) {
2412                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
2413                 if ((bytes == 4) && (gpa % 4 == 0)) {
2414                         r = kvm_read_guest(vcpu->kvm, gpa & ~(u64)7, &gpte, 8);
2415                         if (r)
2416                                 return;
2417                         memcpy((void *)&gpte + (gpa % 8), new, 4);
2418                 } else if ((bytes == 8) && (gpa % 8 == 0)) {
2419                         memcpy((void *)&gpte, new, 8);
2420                 }
2421         } else {
2422                 if ((bytes == 4) && (gpa % 4 == 0))
2423                         memcpy((void *)&gpte, new, 4);
2424         }
2425         if (!is_present_pte(gpte))
2426                 return;
2427         gfn = (gpte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
2428
2429         if (is_large_pte(gpte) && is_largepage_backed(vcpu, gfn)) {
2430                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
2431                 vcpu->arch.update_pte.largepage = 1;
2432         }
2433         vcpu->arch.update_pte.mmu_seq = vcpu->kvm->mmu_notifier_seq;
2434         smp_rmb();
2435         pfn = gfn_to_pfn(vcpu->kvm, gfn);
2436
2437         if (is_error_pfn(pfn)) {
2438                 kvm_release_pfn_clean(pfn);
2439                 return;
2440         }
2441         vcpu->arch.update_pte.gfn = gfn;
2442         vcpu->arch.update_pte.pfn = pfn;
2443 }
2444
2445 static void kvm_mmu_access_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2446 {
2447         u64 *spte = vcpu->arch.last_pte_updated;
2448
2449         if (spte
2450             && vcpu->arch.last_pte_gfn == gfn
2451             && shadow_accessed_mask
2452             && !(*spte & shadow_accessed_mask)
2453             && is_shadow_present_pte(*spte))
2454                 set_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
2455 }
2456
2457 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2458                        const u8 *new, int bytes,
2459                        bool guest_initiated)
2460 {
2461         gfn_t gfn = gpa >> PAGE_SHIFT;
2462         struct kvm_mmu_page *sp;
2463         struct hlist_node *node, *n;
2464         struct hlist_head *bucket;
2465         unsigned index;
2466         u64 entry, gentry;
2467         u64 *spte;
2468         unsigned offset = offset_in_page(gpa);
2469         unsigned pte_size;
2470         unsigned page_offset;
2471         unsigned misaligned;
2472         unsigned quadrant;
2473         int level;
2474         int flooded = 0;
2475         int npte;
2476         int r;
2477
2478         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
2479         mmu_guess_page_from_pte_write(vcpu, gpa, new, bytes);
2480         spin_lock(&vcpu->kvm->mmu_lock);
2481         kvm_mmu_access_page(vcpu, gfn);
2482         kvm_mmu_free_some_pages(vcpu);
2483         ++vcpu->kvm->stat.mmu_pte_write;
2484         kvm_mmu_audit(vcpu, "pre pte write");
2485         if (guest_initiated) {
2486                 if (gfn == vcpu->arch.last_pt_write_gfn
2487                     && !last_updated_pte_accessed(vcpu)) {
2488                         ++vcpu->arch.last_pt_write_count;
2489                         if (vcpu->arch.last_pt_write_count >= 3)
2490                                 flooded = 1;
2491                 } else {
2492                         vcpu->arch.last_pt_write_gfn = gfn;
2493                         vcpu->arch.last_pt_write_count = 1;
2494                         vcpu->arch.last_pte_updated = NULL;
2495                 }
2496         }
2497         index = kvm_page_table_hashfn(gfn);
2498         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
2499         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link) {
2500                 if (sp->gfn != gfn || sp->role.metaphysical || sp->role.invalid)
2501                         continue;
2502                 pte_size = sp->role.glevels == PT32_ROOT_LEVEL ? 4 : 8;
2503                 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
2504                 misaligned |= bytes < 4;
2505                 if (misaligned || flooded) {
2506                         /*
2507                          * Misaligned accesses are too much trouble to fix
2508                          * up; also, they usually indicate a page is not used
2509                          * as a page table.
2510                          *
2511                          * If we're seeing too many writes to a page,
2512                          * it may no longer be a page table, or we may be
2513                          * forking, in which case it is better to unmap the
2514                          * page.
2515                          */
2516                         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
2517                                  gpa, bytes, sp->role.word);
2518                         if (kvm_mmu_zap_page(vcpu->kvm, sp))
2519                                 n = bucket->first;
2520                         ++vcpu->kvm->stat.mmu_flooded;
2521                         continue;
2522                 }
2523                 page_offset = offset;
2524                 level = sp->role.level;
2525                 npte = 1;
2526                 if (sp->role.glevels == PT32_ROOT_LEVEL) {
2527                         page_offset <<= 1;      /* 32->64 */
2528                         /*
2529                          * A 32-bit pde maps 4MB while the shadow pdes map
2530                          * only 2MB.  So we need to double the offset again
2531                          * and zap two pdes instead of one.
2532                          */
2533                         if (level == PT32_ROOT_LEVEL) {
2534                                 page_offset &= ~7; /* kill rounding error */
2535                                 page_offset <<= 1;
2536                                 npte = 2;
2537                         }
2538                         quadrant = page_offset >> PAGE_SHIFT;
2539                         page_offset &= ~PAGE_MASK;
2540                         if (quadrant != sp->role.quadrant)
2541                                 continue;
2542                 }
2543                 spte = &sp->spt[page_offset / sizeof(*spte)];
2544                 if ((gpa & (pte_size - 1)) || (bytes < pte_size)) {
2545                         gentry = 0;
2546                         r = kvm_read_guest_atomic(vcpu->kvm,
2547                                                   gpa & ~(u64)(pte_size - 1),
2548                                                   &gentry, pte_size);
2549                         new = (const void *)&gentry;
2550                         if (r < 0)
2551                                 new = NULL;
2552                 }
2553                 while (npte--) {
2554                         entry = *spte;
2555                         mmu_pte_write_zap_pte(vcpu, sp, spte);
2556                         if (new)
2557                                 mmu_pte_write_new_pte(vcpu, sp, spte, new);
2558                         mmu_pte_write_flush_tlb(vcpu, entry, *spte);
2559                         ++spte;
2560                 }
2561         }
2562         kvm_mmu_audit(vcpu, "post pte write");
2563         spin_unlock(&vcpu->kvm->mmu_lock);
2564         if (!is_error_pfn(vcpu->arch.update_pte.pfn)) {
2565                 kvm_release_pfn_clean(vcpu->arch.update_pte.pfn);
2566                 vcpu->arch.update_pte.pfn = bad_pfn;
2567         }
2568 }
2569
2570 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2571 {
2572         gpa_t gpa;
2573         int r;
2574
2575         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
2576
2577         spin_lock(&vcpu->kvm->mmu_lock);
2578         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2579         spin_unlock(&vcpu->kvm->mmu_lock);
2580         return r;
2581 }
2582 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
2583
2584 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
2585 {
2586         while (vcpu->kvm->arch.n_free_mmu_pages < KVM_REFILL_PAGES) {
2587                 struct kvm_mmu_page *sp;
2588
2589                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
2590                                   struct kvm_mmu_page, link);
2591                 kvm_mmu_zap_page(vcpu->kvm, sp);
2592                 ++vcpu->kvm->stat.mmu_recycled;
2593         }
2594 }
2595
2596 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
2597 {
2598         int r;
2599         enum emulation_result er;
2600
2601         r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
2602         if (r < 0)
2603                 goto out;
2604
2605         if (!r) {
2606                 r = 1;
2607                 goto out;
2608         }
2609
2610         r = mmu_topup_memory_caches(vcpu);
2611         if (r)
2612                 goto out;
2613
2614         er = emulate_instruction(vcpu, vcpu->run, cr2, error_code, 0);
2615
2616         switch (er) {
2617         case EMULATE_DONE:
2618                 return 1;
2619         case EMULATE_DO_MMIO:
2620                 ++vcpu->stat.mmio_exits;
2621                 return 0;
2622         case EMULATE_FAIL:
2623                 kvm_report_emulation_failure(vcpu, "pagetable");
2624                 return 1;
2625         default:
2626                 BUG();
2627         }
2628 out:
2629         return r;
2630 }
2631 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
2632
2633 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
2634 {
2635         vcpu->arch.mmu.invlpg(vcpu, gva);
2636         kvm_mmu_flush_tlb(vcpu);
2637         ++vcpu->stat.invlpg;
2638 }
2639 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
2640
2641 void kvm_enable_tdp(void)
2642 {
2643         tdp_enabled = true;
2644 }
2645 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
2646
2647 void kvm_disable_tdp(void)
2648 {
2649         tdp_enabled = false;
2650 }
2651 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
2652
2653 static void free_mmu_pages(struct kvm_vcpu *vcpu)
2654 {
2655         struct kvm_mmu_page *sp;
2656
2657         while (!list_empty(&vcpu->kvm->arch.active_mmu_pages)) {
2658                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.next,
2659                                   struct kvm_mmu_page, link);
2660                 kvm_mmu_zap_page(vcpu->kvm, sp);
2661                 cond_resched();
2662         }
2663         free_page((unsigned long)vcpu->arch.mmu.pae_root);
2664 }
2665
2666 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
2667 {
2668         struct page *page;
2669         int i;
2670
2671         ASSERT(vcpu);
2672
2673         if (vcpu->kvm->arch.n_requested_mmu_pages)
2674                 vcpu->kvm->arch.n_free_mmu_pages =
2675                                         vcpu->kvm->arch.n_requested_mmu_pages;
2676         else
2677                 vcpu->kvm->arch.n_free_mmu_pages =
2678                                         vcpu->kvm->arch.n_alloc_mmu_pages;
2679         /*
2680          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
2681          * Therefore we need to allocate shadow page tables in the first
2682          * 4GB of memory, which happens to fit the DMA32 zone.
2683          */
2684         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
2685         if (!page)
2686                 goto error_1;
2687         vcpu->arch.mmu.pae_root = page_address(page);
2688         for (i = 0; i < 4; ++i)
2689                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
2690
2691         return 0;
2692
2693 error_1:
2694         free_mmu_pages(vcpu);
2695         return -ENOMEM;
2696 }
2697
2698 int kvm_mmu_create(struct kvm_vcpu *vcpu)
2699 {
2700         ASSERT(vcpu);
2701         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2702
2703         return alloc_mmu_pages(vcpu);
2704 }
2705
2706 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
2707 {
2708         ASSERT(vcpu);
2709         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2710
2711         return init_kvm_mmu(vcpu);
2712 }
2713
2714 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
2715 {
2716         ASSERT(vcpu);
2717
2718         destroy_kvm_mmu(vcpu);
2719         free_mmu_pages(vcpu);
2720         mmu_free_memory_caches(vcpu);
2721 }
2722
2723 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
2724 {
2725         struct kvm_mmu_page *sp;
2726
2727         spin_lock(&kvm->mmu_lock);
2728         list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
2729                 int i;
2730                 u64 *pt;
2731
2732                 if (!test_bit(slot, sp->slot_bitmap))
2733                         continue;
2734
2735                 pt = sp->spt;
2736                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2737                         /* avoid RMW */
2738                         if (pt[i] & PT_WRITABLE_MASK)
2739                                 pt[i] &= ~PT_WRITABLE_MASK;
2740         }
2741         kvm_flush_remote_tlbs(kvm);
2742         spin_unlock(&kvm->mmu_lock);
2743 }
2744
2745 void kvm_mmu_zap_all(struct kvm *kvm)
2746 {
2747         struct kvm_mmu_page *sp, *node;
2748
2749         spin_lock(&kvm->mmu_lock);
2750         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
2751                 if (kvm_mmu_zap_page(kvm, sp))
2752                         node = container_of(kvm->arch.active_mmu_pages.next,
2753                                             struct kvm_mmu_page, link);
2754         spin_unlock(&kvm->mmu_lock);
2755
2756         kvm_flush_remote_tlbs(kvm);
2757 }
2758
2759 static void kvm_mmu_remove_one_alloc_mmu_page(struct kvm *kvm)
2760 {
2761         struct kvm_mmu_page *page;
2762
2763         page = container_of(kvm->arch.active_mmu_pages.prev,
2764                             struct kvm_mmu_page, link);
2765         kvm_mmu_zap_page(kvm, page);
2766 }
2767
2768 static int mmu_shrink(int nr_to_scan, gfp_t gfp_mask)
2769 {
2770         struct kvm *kvm;
2771         struct kvm *kvm_freed = NULL;
2772         int cache_count = 0;
2773
2774         spin_lock(&kvm_lock);
2775
2776         list_for_each_entry(kvm, &vm_list, vm_list) {
2777                 int npages;
2778
2779                 if (!down_read_trylock(&kvm->slots_lock))
2780                         continue;
2781                 spin_lock(&kvm->mmu_lock);
2782                 npages = kvm->arch.n_alloc_mmu_pages -
2783                          kvm->arch.n_free_mmu_pages;
2784                 cache_count += npages;
2785                 if (!kvm_freed && nr_to_scan > 0 && npages > 0) {
2786                         kvm_mmu_remove_one_alloc_mmu_page(kvm);
2787                         cache_count--;
2788                         kvm_freed = kvm;
2789                 }
2790                 nr_to_scan--;
2791
2792                 spin_unlock(&kvm->mmu_lock);
2793                 up_read(&kvm->slots_lock);
2794         }
2795         if (kvm_freed)
2796                 list_move_tail(&kvm_freed->vm_list, &vm_list);
2797
2798         spin_unlock(&kvm_lock);
2799
2800         return cache_count;
2801 }
2802
2803 static struct shrinker mmu_shrinker = {
2804         .shrink = mmu_shrink,
2805         .seeks = DEFAULT_SEEKS * 10,
2806 };
2807
2808 static void mmu_destroy_caches(void)
2809 {
2810         if (pte_chain_cache)
2811                 kmem_cache_destroy(pte_chain_cache);
2812         if (rmap_desc_cache)
2813                 kmem_cache_destroy(rmap_desc_cache);
2814         if (mmu_page_header_cache)
2815                 kmem_cache_destroy(mmu_page_header_cache);
2816 }
2817
2818 void kvm_mmu_module_exit(void)
2819 {
2820         mmu_destroy_caches();
2821         unregister_shrinker(&mmu_shrinker);
2822 }
2823
2824 int kvm_mmu_module_init(void)
2825 {
2826         pte_chain_cache = kmem_cache_create("kvm_pte_chain",
2827                                             sizeof(struct kvm_pte_chain),
2828                                             0, 0, NULL);
2829         if (!pte_chain_cache)
2830                 goto nomem;
2831         rmap_desc_cache = kmem_cache_create("kvm_rmap_desc",
2832                                             sizeof(struct kvm_rmap_desc),
2833                                             0, 0, NULL);
2834         if (!rmap_desc_cache)
2835                 goto nomem;
2836
2837         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
2838                                                   sizeof(struct kvm_mmu_page),
2839                                                   0, 0, NULL);
2840         if (!mmu_page_header_cache)
2841                 goto nomem;
2842
2843         register_shrinker(&mmu_shrinker);
2844
2845         return 0;
2846
2847 nomem:
2848         mmu_destroy_caches();
2849         return -ENOMEM;
2850 }
2851
2852 /*
2853  * Caculate mmu pages needed for kvm.
2854  */
2855 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
2856 {
2857         int i;
2858         unsigned int nr_mmu_pages;
2859         unsigned int  nr_pages = 0;
2860
2861         for (i = 0; i < kvm->nmemslots; i++)
2862                 nr_pages += kvm->memslots[i].npages;
2863
2864         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
2865         nr_mmu_pages = max(nr_mmu_pages,
2866                         (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
2867
2868         return nr_mmu_pages;
2869 }
2870
2871 static void *pv_mmu_peek_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2872                                 unsigned len)
2873 {
2874         if (len > buffer->len)
2875                 return NULL;
2876         return buffer->ptr;
2877 }
2878
2879 static void *pv_mmu_read_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2880                                 unsigned len)
2881 {
2882         void *ret;
2883
2884         ret = pv_mmu_peek_buffer(buffer, len);
2885         if (!ret)
2886                 return ret;
2887         buffer->ptr += len;
2888         buffer->len -= len;
2889         buffer->processed += len;
2890         return ret;
2891 }
2892
2893 static int kvm_pv_mmu_write(struct kvm_vcpu *vcpu,
2894                              gpa_t addr, gpa_t value)
2895 {
2896         int bytes = 8;
2897         int r;
2898
2899         if (!is_long_mode(vcpu) && !is_pae(vcpu))
2900                 bytes = 4;
2901
2902         r = mmu_topup_memory_caches(vcpu);
2903         if (r)
2904                 return r;
2905
2906         if (!emulator_write_phys(vcpu, addr, &value, bytes))
2907                 return -EFAULT;
2908
2909         return 1;
2910 }
2911
2912 static int kvm_pv_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2913 {
2914         kvm_x86_ops->tlb_flush(vcpu);
2915         set_bit(KVM_REQ_MMU_SYNC, &vcpu->requests);
2916         return 1;
2917 }
2918
2919 static int kvm_pv_mmu_release_pt(struct kvm_vcpu *vcpu, gpa_t addr)
2920 {
2921         spin_lock(&vcpu->kvm->mmu_lock);
2922         mmu_unshadow(vcpu->kvm, addr >> PAGE_SHIFT);
2923         spin_unlock(&vcpu->kvm->mmu_lock);
2924         return 1;
2925 }
2926
2927 static int kvm_pv_mmu_op_one(struct kvm_vcpu *vcpu,
2928                              struct kvm_pv_mmu_op_buffer *buffer)
2929 {
2930         struct kvm_mmu_op_header *header;
2931
2932         header = pv_mmu_peek_buffer(buffer, sizeof *header);
2933         if (!header)
2934                 return 0;
2935         switch (header->op) {
2936         case KVM_MMU_OP_WRITE_PTE: {
2937                 struct kvm_mmu_op_write_pte *wpte;
2938
2939                 wpte = pv_mmu_read_buffer(buffer, sizeof *wpte);
2940                 if (!wpte)
2941                         return 0;
2942                 return kvm_pv_mmu_write(vcpu, wpte->pte_phys,
2943                                         wpte->pte_val);
2944         }
2945         case KVM_MMU_OP_FLUSH_TLB: {
2946                 struct kvm_mmu_op_flush_tlb *ftlb;
2947
2948                 ftlb = pv_mmu_read_buffer(buffer, sizeof *ftlb);
2949                 if (!ftlb)
2950                         return 0;
2951                 return kvm_pv_mmu_flush_tlb(vcpu);
2952         }
2953         case KVM_MMU_OP_RELEASE_PT: {
2954                 struct kvm_mmu_op_release_pt *rpt;
2955
2956                 rpt = pv_mmu_read_buffer(buffer, sizeof *rpt);
2957                 if (!rpt)
2958                         return 0;
2959                 return kvm_pv_mmu_release_pt(vcpu, rpt->pt_phys);
2960         }
2961         default: return 0;
2962         }
2963 }
2964
2965 int kvm_pv_mmu_op(struct kvm_vcpu *vcpu, unsigned long bytes,
2966                   gpa_t addr, unsigned long *ret)
2967 {
2968         int r;
2969         struct kvm_pv_mmu_op_buffer *buffer = &vcpu->arch.mmu_op_buffer;
2970
2971         buffer->ptr = buffer->buf;
2972         buffer->len = min_t(unsigned long, bytes, sizeof buffer->buf);
2973         buffer->processed = 0;
2974
2975         r = kvm_read_guest(vcpu->kvm, addr, buffer->buf, buffer->len);
2976         if (r)
2977                 goto out;
2978
2979         while (buffer->len) {
2980                 r = kvm_pv_mmu_op_one(vcpu, buffer);
2981                 if (r < 0)
2982                         goto out;
2983                 if (r == 0)
2984                         break;
2985         }
2986
2987         r = 1;
2988 out:
2989         *ret = buffer->processed;
2990         return r;
2991 }
2992
2993 #ifdef AUDIT
2994
2995 static const char *audit_msg;
2996
2997 static gva_t canonicalize(gva_t gva)
2998 {
2999 #ifdef CONFIG_X86_64
3000         gva = (long long)(gva << 16) >> 16;
3001 #endif
3002         return gva;
3003 }
3004
3005 static void audit_mappings_page(struct kvm_vcpu *vcpu, u64 page_pte,
3006                                 gva_t va, int level)
3007 {
3008         u64 *pt = __va(page_pte & PT64_BASE_ADDR_MASK);
3009         int i;
3010         gva_t va_delta = 1ul << (PAGE_SHIFT + 9 * (level - 1));
3011
3012         for (i = 0; i < PT64_ENT_PER_PAGE; ++i, va += va_delta) {
3013                 u64 ent = pt[i];
3014
3015                 if (ent == shadow_trap_nonpresent_pte)
3016                         continue;
3017
3018                 va = canonicalize(va);
3019                 if (level > 1) {
3020                         if (ent == shadow_notrap_nonpresent_pte)
3021                                 printk(KERN_ERR "audit: (%s) nontrapping pte"
3022                                        " in nonleaf level: levels %d gva %lx"
3023                                        " level %d pte %llx\n", audit_msg,
3024                                        vcpu->arch.mmu.root_level, va, level, ent);
3025
3026                         audit_mappings_page(vcpu, ent, va, level - 1);
3027                 } else {
3028                         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, va);
3029                         hpa_t hpa = (hpa_t)gpa_to_pfn(vcpu, gpa) << PAGE_SHIFT;
3030
3031                         if (is_shadow_present_pte(ent)
3032                             && (ent & PT64_BASE_ADDR_MASK) != hpa)
3033                                 printk(KERN_ERR "xx audit error: (%s) levels %d"
3034                                        " gva %lx gpa %llx hpa %llx ent %llx %d\n",
3035                                        audit_msg, vcpu->arch.mmu.root_level,
3036                                        va, gpa, hpa, ent,
3037                                        is_shadow_present_pte(ent));
3038                         else if (ent == shadow_notrap_nonpresent_pte
3039                                  && !is_error_hpa(hpa))
3040                                 printk(KERN_ERR "audit: (%s) notrap shadow,"
3041                                        " valid guest gva %lx\n", audit_msg, va);
3042                         kvm_release_pfn_clean(pfn);
3043
3044                 }
3045         }
3046 }
3047
3048 static void audit_mappings(struct kvm_vcpu *vcpu)
3049 {
3050         unsigned i;
3051
3052         if (vcpu->arch.mmu.root_level == 4)
3053                 audit_mappings_page(vcpu, vcpu->arch.mmu.root_hpa, 0, 4);
3054         else
3055                 for (i = 0; i < 4; ++i)
3056                         if (vcpu->arch.mmu.pae_root[i] & PT_PRESENT_MASK)
3057                                 audit_mappings_page(vcpu,
3058                                                     vcpu->arch.mmu.pae_root[i],
3059                                                     i << 30,
3060                                                     2);
3061 }
3062
3063 static int count_rmaps(struct kvm_vcpu *vcpu)
3064 {
3065         int nmaps = 0;
3066         int i, j, k;
3067
3068         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
3069                 struct kvm_memory_slot *m = &vcpu->kvm->memslots[i];
3070                 struct kvm_rmap_desc *d;
3071
3072                 for (j = 0; j < m->npages; ++j) {
3073                         unsigned long *rmapp = &m->rmap[j];
3074
3075                         if (!*rmapp)
3076                                 continue;
3077                         if (!(*rmapp & 1)) {
3078                                 ++nmaps;
3079                                 continue;
3080                         }
3081                         d = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
3082                         while (d) {
3083                                 for (k = 0; k < RMAP_EXT; ++k)
3084                                         if (d->shadow_ptes[k])
3085                                                 ++nmaps;
3086                                         else
3087                                                 break;
3088                                 d = d->more;
3089                         }
3090                 }
3091         }
3092         return nmaps;
3093 }
3094
3095 static int count_writable_mappings(struct kvm_vcpu *vcpu)
3096 {
3097         int nmaps = 0;
3098         struct kvm_mmu_page *sp;
3099         int i;
3100
3101         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3102                 u64 *pt = sp->spt;
3103
3104                 if (sp->role.level != PT_PAGE_TABLE_LEVEL)
3105                         continue;
3106
3107                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3108                         u64 ent = pt[i];
3109
3110                         if (!(ent & PT_PRESENT_MASK))
3111                                 continue;
3112                         if (!(ent & PT_WRITABLE_MASK))
3113                                 continue;
3114                         ++nmaps;
3115                 }
3116         }
3117         return nmaps;
3118 }
3119
3120 static void audit_rmap(struct kvm_vcpu *vcpu)
3121 {
3122         int n_rmap = count_rmaps(vcpu);
3123         int n_actual = count_writable_mappings(vcpu);
3124
3125         if (n_rmap != n_actual)
3126                 printk(KERN_ERR "%s: (%s) rmap %d actual %d\n",
3127                        __func__, audit_msg, n_rmap, n_actual);
3128 }
3129
3130 static void audit_write_protection(struct kvm_vcpu *vcpu)
3131 {
3132         struct kvm_mmu_page *sp;
3133         struct kvm_memory_slot *slot;
3134         unsigned long *rmapp;
3135         gfn_t gfn;
3136
3137         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3138                 if (sp->role.metaphysical)
3139                         continue;
3140
3141                 gfn = unalias_gfn(vcpu->kvm, sp->gfn);
3142                 slot = gfn_to_memslot_unaliased(vcpu->kvm, sp->gfn);
3143                 rmapp = &slot->rmap[gfn - slot->base_gfn];
3144                 if (*rmapp)
3145                         printk(KERN_ERR "%s: (%s) shadow page has writable"
3146                                " mappings: gfn %lx role %x\n",
3147                                __func__, audit_msg, sp->gfn,
3148                                sp->role.word);
3149         }
3150 }
3151
3152 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg)
3153 {
3154         int olddbg = dbg;
3155
3156         dbg = 0;
3157         audit_msg = msg;
3158         audit_rmap(vcpu);
3159         audit_write_protection(vcpu);
3160         audit_mappings(vcpu);
3161         dbg = olddbg;
3162 }
3163
3164 #endif