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