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