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