KVM: MMU: rename is_largepage_backed to mapping_level
[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 (level == PT_DIRECTORY_LEVEL && 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;
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                         int idx = gfn_offset /
776                                   KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL);
777                         retval |= handler(kvm, &memslot->rmap[gfn_offset]);
778                         retval |= handler(kvm,
779                                         &memslot->lpage_info[0][idx].rmap_pde);
780                 }
781         }
782
783         return retval;
784 }
785
786 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
787 {
788         return kvm_handle_hva(kvm, hva, kvm_unmap_rmapp);
789 }
790
791 static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp)
792 {
793         u64 *spte;
794         int young = 0;
795
796         /* always return old for EPT */
797         if (!shadow_accessed_mask)
798                 return 0;
799
800         spte = rmap_next(kvm, rmapp, NULL);
801         while (spte) {
802                 int _young;
803                 u64 _spte = *spte;
804                 BUG_ON(!(_spte & PT_PRESENT_MASK));
805                 _young = _spte & PT_ACCESSED_MASK;
806                 if (_young) {
807                         young = 1;
808                         clear_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
809                 }
810                 spte = rmap_next(kvm, rmapp, spte);
811         }
812         return young;
813 }
814
815 #define RMAP_RECYCLE_THRESHOLD 1000
816
817 static void rmap_recycle(struct kvm_vcpu *vcpu, gfn_t gfn, int lpage)
818 {
819         unsigned long *rmapp;
820
821         gfn = unalias_gfn(vcpu->kvm, gfn);
822         rmapp = gfn_to_rmap(vcpu->kvm, gfn, lpage);
823
824         kvm_unmap_rmapp(vcpu->kvm, rmapp);
825         kvm_flush_remote_tlbs(vcpu->kvm);
826 }
827
828 int kvm_age_hva(struct kvm *kvm, unsigned long hva)
829 {
830         return kvm_handle_hva(kvm, hva, kvm_age_rmapp);
831 }
832
833 #ifdef MMU_DEBUG
834 static int is_empty_shadow_page(u64 *spt)
835 {
836         u64 *pos;
837         u64 *end;
838
839         for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
840                 if (is_shadow_present_pte(*pos)) {
841                         printk(KERN_ERR "%s: %p %llx\n", __func__,
842                                pos, *pos);
843                         return 0;
844                 }
845         return 1;
846 }
847 #endif
848
849 static void kvm_mmu_free_page(struct kvm *kvm, struct kvm_mmu_page *sp)
850 {
851         ASSERT(is_empty_shadow_page(sp->spt));
852         list_del(&sp->link);
853         __free_page(virt_to_page(sp->spt));
854         __free_page(virt_to_page(sp->gfns));
855         kfree(sp);
856         ++kvm->arch.n_free_mmu_pages;
857 }
858
859 static unsigned kvm_page_table_hashfn(gfn_t gfn)
860 {
861         return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
862 }
863
864 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
865                                                u64 *parent_pte)
866 {
867         struct kvm_mmu_page *sp;
868
869         sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache, sizeof *sp);
870         sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
871         sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
872         set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
873         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
874         INIT_LIST_HEAD(&sp->oos_link);
875         bitmap_zero(sp->slot_bitmap, KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS);
876         sp->multimapped = 0;
877         sp->parent_pte = parent_pte;
878         --vcpu->kvm->arch.n_free_mmu_pages;
879         return sp;
880 }
881
882 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
883                                     struct kvm_mmu_page *sp, u64 *parent_pte)
884 {
885         struct kvm_pte_chain *pte_chain;
886         struct hlist_node *node;
887         int i;
888
889         if (!parent_pte)
890                 return;
891         if (!sp->multimapped) {
892                 u64 *old = sp->parent_pte;
893
894                 if (!old) {
895                         sp->parent_pte = parent_pte;
896                         return;
897                 }
898                 sp->multimapped = 1;
899                 pte_chain = mmu_alloc_pte_chain(vcpu);
900                 INIT_HLIST_HEAD(&sp->parent_ptes);
901                 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
902                 pte_chain->parent_ptes[0] = old;
903         }
904         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link) {
905                 if (pte_chain->parent_ptes[NR_PTE_CHAIN_ENTRIES-1])
906                         continue;
907                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i)
908                         if (!pte_chain->parent_ptes[i]) {
909                                 pte_chain->parent_ptes[i] = parent_pte;
910                                 return;
911                         }
912         }
913         pte_chain = mmu_alloc_pte_chain(vcpu);
914         BUG_ON(!pte_chain);
915         hlist_add_head(&pte_chain->link, &sp->parent_ptes);
916         pte_chain->parent_ptes[0] = parent_pte;
917 }
918
919 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
920                                        u64 *parent_pte)
921 {
922         struct kvm_pte_chain *pte_chain;
923         struct hlist_node *node;
924         int i;
925
926         if (!sp->multimapped) {
927                 BUG_ON(sp->parent_pte != parent_pte);
928                 sp->parent_pte = NULL;
929                 return;
930         }
931         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
932                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
933                         if (!pte_chain->parent_ptes[i])
934                                 break;
935                         if (pte_chain->parent_ptes[i] != parent_pte)
936                                 continue;
937                         while (i + 1 < NR_PTE_CHAIN_ENTRIES
938                                 && pte_chain->parent_ptes[i + 1]) {
939                                 pte_chain->parent_ptes[i]
940                                         = pte_chain->parent_ptes[i + 1];
941                                 ++i;
942                         }
943                         pte_chain->parent_ptes[i] = NULL;
944                         if (i == 0) {
945                                 hlist_del(&pte_chain->link);
946                                 mmu_free_pte_chain(pte_chain);
947                                 if (hlist_empty(&sp->parent_ptes)) {
948                                         sp->multimapped = 0;
949                                         sp->parent_pte = NULL;
950                                 }
951                         }
952                         return;
953                 }
954         BUG();
955 }
956
957
958 static void mmu_parent_walk(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
959                             mmu_parent_walk_fn fn)
960 {
961         struct kvm_pte_chain *pte_chain;
962         struct hlist_node *node;
963         struct kvm_mmu_page *parent_sp;
964         int i;
965
966         if (!sp->multimapped && sp->parent_pte) {
967                 parent_sp = page_header(__pa(sp->parent_pte));
968                 fn(vcpu, parent_sp);
969                 mmu_parent_walk(vcpu, parent_sp, fn);
970                 return;
971         }
972         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
973                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
974                         if (!pte_chain->parent_ptes[i])
975                                 break;
976                         parent_sp = page_header(__pa(pte_chain->parent_ptes[i]));
977                         fn(vcpu, parent_sp);
978                         mmu_parent_walk(vcpu, parent_sp, fn);
979                 }
980 }
981
982 static void kvm_mmu_update_unsync_bitmap(u64 *spte)
983 {
984         unsigned int index;
985         struct kvm_mmu_page *sp = page_header(__pa(spte));
986
987         index = spte - sp->spt;
988         if (!__test_and_set_bit(index, sp->unsync_child_bitmap))
989                 sp->unsync_children++;
990         WARN_ON(!sp->unsync_children);
991 }
992
993 static void kvm_mmu_update_parents_unsync(struct kvm_mmu_page *sp)
994 {
995         struct kvm_pte_chain *pte_chain;
996         struct hlist_node *node;
997         int i;
998
999         if (!sp->parent_pte)
1000                 return;
1001
1002         if (!sp->multimapped) {
1003                 kvm_mmu_update_unsync_bitmap(sp->parent_pte);
1004                 return;
1005         }
1006
1007         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
1008                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
1009                         if (!pte_chain->parent_ptes[i])
1010                                 break;
1011                         kvm_mmu_update_unsync_bitmap(pte_chain->parent_ptes[i]);
1012                 }
1013 }
1014
1015 static int unsync_walk_fn(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1016 {
1017         kvm_mmu_update_parents_unsync(sp);
1018         return 1;
1019 }
1020
1021 static void kvm_mmu_mark_parents_unsync(struct kvm_vcpu *vcpu,
1022                                         struct kvm_mmu_page *sp)
1023 {
1024         mmu_parent_walk(vcpu, sp, unsync_walk_fn);
1025         kvm_mmu_update_parents_unsync(sp);
1026 }
1027
1028 static void nonpaging_prefetch_page(struct kvm_vcpu *vcpu,
1029                                     struct kvm_mmu_page *sp)
1030 {
1031         int i;
1032
1033         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
1034                 sp->spt[i] = shadow_trap_nonpresent_pte;
1035 }
1036
1037 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1038                                struct kvm_mmu_page *sp)
1039 {
1040         return 1;
1041 }
1042
1043 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
1044 {
1045 }
1046
1047 #define KVM_PAGE_ARRAY_NR 16
1048
1049 struct kvm_mmu_pages {
1050         struct mmu_page_and_offset {
1051                 struct kvm_mmu_page *sp;
1052                 unsigned int idx;
1053         } page[KVM_PAGE_ARRAY_NR];
1054         unsigned int nr;
1055 };
1056
1057 #define for_each_unsync_children(bitmap, idx)           \
1058         for (idx = find_first_bit(bitmap, 512);         \
1059              idx < 512;                                 \
1060              idx = find_next_bit(bitmap, 512, idx+1))
1061
1062 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1063                          int idx)
1064 {
1065         int i;
1066
1067         if (sp->unsync)
1068                 for (i=0; i < pvec->nr; i++)
1069                         if (pvec->page[i].sp == sp)
1070                                 return 0;
1071
1072         pvec->page[pvec->nr].sp = sp;
1073         pvec->page[pvec->nr].idx = idx;
1074         pvec->nr++;
1075         return (pvec->nr == KVM_PAGE_ARRAY_NR);
1076 }
1077
1078 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1079                            struct kvm_mmu_pages *pvec)
1080 {
1081         int i, ret, nr_unsync_leaf = 0;
1082
1083         for_each_unsync_children(sp->unsync_child_bitmap, i) {
1084                 u64 ent = sp->spt[i];
1085
1086                 if (is_shadow_present_pte(ent) && !is_large_pte(ent)) {
1087                         struct kvm_mmu_page *child;
1088                         child = page_header(ent & PT64_BASE_ADDR_MASK);
1089
1090                         if (child->unsync_children) {
1091                                 if (mmu_pages_add(pvec, child, i))
1092                                         return -ENOSPC;
1093
1094                                 ret = __mmu_unsync_walk(child, pvec);
1095                                 if (!ret)
1096                                         __clear_bit(i, sp->unsync_child_bitmap);
1097                                 else if (ret > 0)
1098                                         nr_unsync_leaf += ret;
1099                                 else
1100                                         return ret;
1101                         }
1102
1103                         if (child->unsync) {
1104                                 nr_unsync_leaf++;
1105                                 if (mmu_pages_add(pvec, child, i))
1106                                         return -ENOSPC;
1107                         }
1108                 }
1109         }
1110
1111         if (find_first_bit(sp->unsync_child_bitmap, 512) == 512)
1112                 sp->unsync_children = 0;
1113
1114         return nr_unsync_leaf;
1115 }
1116
1117 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1118                            struct kvm_mmu_pages *pvec)
1119 {
1120         if (!sp->unsync_children)
1121                 return 0;
1122
1123         mmu_pages_add(pvec, sp, 0);
1124         return __mmu_unsync_walk(sp, pvec);
1125 }
1126
1127 static struct kvm_mmu_page *kvm_mmu_lookup_page(struct kvm *kvm, gfn_t gfn)
1128 {
1129         unsigned index;
1130         struct hlist_head *bucket;
1131         struct kvm_mmu_page *sp;
1132         struct hlist_node *node;
1133
1134         pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1135         index = kvm_page_table_hashfn(gfn);
1136         bucket = &kvm->arch.mmu_page_hash[index];
1137         hlist_for_each_entry(sp, node, bucket, hash_link)
1138                 if (sp->gfn == gfn && !sp->role.direct
1139                     && !sp->role.invalid) {
1140                         pgprintk("%s: found role %x\n",
1141                                  __func__, sp->role.word);
1142                         return sp;
1143                 }
1144         return NULL;
1145 }
1146
1147 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1148 {
1149         WARN_ON(!sp->unsync);
1150         sp->unsync = 0;
1151         --kvm->stat.mmu_unsync;
1152 }
1153
1154 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp);
1155
1156 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1157 {
1158         if (sp->role.glevels != vcpu->arch.mmu.root_level) {
1159                 kvm_mmu_zap_page(vcpu->kvm, sp);
1160                 return 1;
1161         }
1162
1163         trace_kvm_mmu_sync_page(sp);
1164         if (rmap_write_protect(vcpu->kvm, sp->gfn))
1165                 kvm_flush_remote_tlbs(vcpu->kvm);
1166         kvm_unlink_unsync_page(vcpu->kvm, sp);
1167         if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
1168                 kvm_mmu_zap_page(vcpu->kvm, sp);
1169                 return 1;
1170         }
1171
1172         kvm_mmu_flush_tlb(vcpu);
1173         return 0;
1174 }
1175
1176 struct mmu_page_path {
1177         struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
1178         unsigned int idx[PT64_ROOT_LEVEL-1];
1179 };
1180
1181 #define for_each_sp(pvec, sp, parents, i)                       \
1182                 for (i = mmu_pages_next(&pvec, &parents, -1),   \
1183                         sp = pvec.page[i].sp;                   \
1184                         i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});   \
1185                         i = mmu_pages_next(&pvec, &parents, i))
1186
1187 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1188                           struct mmu_page_path *parents,
1189                           int i)
1190 {
1191         int n;
1192
1193         for (n = i+1; n < pvec->nr; n++) {
1194                 struct kvm_mmu_page *sp = pvec->page[n].sp;
1195
1196                 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1197                         parents->idx[0] = pvec->page[n].idx;
1198                         return n;
1199                 }
1200
1201                 parents->parent[sp->role.level-2] = sp;
1202                 parents->idx[sp->role.level-1] = pvec->page[n].idx;
1203         }
1204
1205         return n;
1206 }
1207
1208 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1209 {
1210         struct kvm_mmu_page *sp;
1211         unsigned int level = 0;
1212
1213         do {
1214                 unsigned int idx = parents->idx[level];
1215
1216                 sp = parents->parent[level];
1217                 if (!sp)
1218                         return;
1219
1220                 --sp->unsync_children;
1221                 WARN_ON((int)sp->unsync_children < 0);
1222                 __clear_bit(idx, sp->unsync_child_bitmap);
1223                 level++;
1224         } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
1225 }
1226
1227 static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
1228                                struct mmu_page_path *parents,
1229                                struct kvm_mmu_pages *pvec)
1230 {
1231         parents->parent[parent->role.level-1] = NULL;
1232         pvec->nr = 0;
1233 }
1234
1235 static void mmu_sync_children(struct kvm_vcpu *vcpu,
1236                               struct kvm_mmu_page *parent)
1237 {
1238         int i;
1239         struct kvm_mmu_page *sp;
1240         struct mmu_page_path parents;
1241         struct kvm_mmu_pages pages;
1242
1243         kvm_mmu_pages_init(parent, &parents, &pages);
1244         while (mmu_unsync_walk(parent, &pages)) {
1245                 int protected = 0;
1246
1247                 for_each_sp(pages, sp, parents, i)
1248                         protected |= rmap_write_protect(vcpu->kvm, sp->gfn);
1249
1250                 if (protected)
1251                         kvm_flush_remote_tlbs(vcpu->kvm);
1252
1253                 for_each_sp(pages, sp, parents, i) {
1254                         kvm_sync_page(vcpu, sp);
1255                         mmu_pages_clear_parents(&parents);
1256                 }
1257                 cond_resched_lock(&vcpu->kvm->mmu_lock);
1258                 kvm_mmu_pages_init(parent, &parents, &pages);
1259         }
1260 }
1261
1262 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
1263                                              gfn_t gfn,
1264                                              gva_t gaddr,
1265                                              unsigned level,
1266                                              int direct,
1267                                              unsigned access,
1268                                              u64 *parent_pte)
1269 {
1270         union kvm_mmu_page_role role;
1271         unsigned index;
1272         unsigned quadrant;
1273         struct hlist_head *bucket;
1274         struct kvm_mmu_page *sp;
1275         struct hlist_node *node, *tmp;
1276
1277         role = vcpu->arch.mmu.base_role;
1278         role.level = level;
1279         role.direct = direct;
1280         role.access = access;
1281         if (vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
1282                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
1283                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
1284                 role.quadrant = quadrant;
1285         }
1286         index = kvm_page_table_hashfn(gfn);
1287         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1288         hlist_for_each_entry_safe(sp, node, tmp, bucket, hash_link)
1289                 if (sp->gfn == gfn) {
1290                         if (sp->unsync)
1291                                 if (kvm_sync_page(vcpu, sp))
1292                                         continue;
1293
1294                         if (sp->role.word != role.word)
1295                                 continue;
1296
1297                         mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1298                         if (sp->unsync_children) {
1299                                 set_bit(KVM_REQ_MMU_SYNC, &vcpu->requests);
1300                                 kvm_mmu_mark_parents_unsync(vcpu, sp);
1301                         }
1302                         trace_kvm_mmu_get_page(sp, false);
1303                         return sp;
1304                 }
1305         ++vcpu->kvm->stat.mmu_cache_miss;
1306         sp = kvm_mmu_alloc_page(vcpu, parent_pte);
1307         if (!sp)
1308                 return sp;
1309         sp->gfn = gfn;
1310         sp->role = role;
1311         hlist_add_head(&sp->hash_link, bucket);
1312         if (!direct) {
1313                 if (rmap_write_protect(vcpu->kvm, gfn))
1314                         kvm_flush_remote_tlbs(vcpu->kvm);
1315                 account_shadowed(vcpu->kvm, gfn);
1316         }
1317         if (shadow_trap_nonpresent_pte != shadow_notrap_nonpresent_pte)
1318                 vcpu->arch.mmu.prefetch_page(vcpu, sp);
1319         else
1320                 nonpaging_prefetch_page(vcpu, sp);
1321         trace_kvm_mmu_get_page(sp, true);
1322         return sp;
1323 }
1324
1325 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
1326                              struct kvm_vcpu *vcpu, u64 addr)
1327 {
1328         iterator->addr = addr;
1329         iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
1330         iterator->level = vcpu->arch.mmu.shadow_root_level;
1331         if (iterator->level == PT32E_ROOT_LEVEL) {
1332                 iterator->shadow_addr
1333                         = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
1334                 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
1335                 --iterator->level;
1336                 if (!iterator->shadow_addr)
1337                         iterator->level = 0;
1338         }
1339 }
1340
1341 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
1342 {
1343         if (iterator->level < PT_PAGE_TABLE_LEVEL)
1344                 return false;
1345
1346         if (iterator->level == PT_PAGE_TABLE_LEVEL)
1347                 if (is_large_pte(*iterator->sptep))
1348                         return false;
1349
1350         iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
1351         iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
1352         return true;
1353 }
1354
1355 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
1356 {
1357         iterator->shadow_addr = *iterator->sptep & PT64_BASE_ADDR_MASK;
1358         --iterator->level;
1359 }
1360
1361 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
1362                                          struct kvm_mmu_page *sp)
1363 {
1364         unsigned i;
1365         u64 *pt;
1366         u64 ent;
1367
1368         pt = sp->spt;
1369
1370         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1371                 ent = pt[i];
1372
1373                 if (is_shadow_present_pte(ent)) {
1374                         if (!is_last_spte(ent, sp->role.level)) {
1375                                 ent &= PT64_BASE_ADDR_MASK;
1376                                 mmu_page_remove_parent_pte(page_header(ent),
1377                                                            &pt[i]);
1378                         } else {
1379                                 if (is_large_pte(ent))
1380                                         --kvm->stat.lpages;
1381                                 rmap_remove(kvm, &pt[i]);
1382                         }
1383                 }
1384                 pt[i] = shadow_trap_nonpresent_pte;
1385         }
1386 }
1387
1388 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
1389 {
1390         mmu_page_remove_parent_pte(sp, parent_pte);
1391 }
1392
1393 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
1394 {
1395         int i;
1396         struct kvm_vcpu *vcpu;
1397
1398         kvm_for_each_vcpu(i, vcpu, kvm)
1399                 vcpu->arch.last_pte_updated = NULL;
1400 }
1401
1402 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
1403 {
1404         u64 *parent_pte;
1405
1406         while (sp->multimapped || sp->parent_pte) {
1407                 if (!sp->multimapped)
1408                         parent_pte = sp->parent_pte;
1409                 else {
1410                         struct kvm_pte_chain *chain;
1411
1412                         chain = container_of(sp->parent_ptes.first,
1413                                              struct kvm_pte_chain, link);
1414                         parent_pte = chain->parent_ptes[0];
1415                 }
1416                 BUG_ON(!parent_pte);
1417                 kvm_mmu_put_page(sp, parent_pte);
1418                 __set_spte(parent_pte, shadow_trap_nonpresent_pte);
1419         }
1420 }
1421
1422 static int mmu_zap_unsync_children(struct kvm *kvm,
1423                                    struct kvm_mmu_page *parent)
1424 {
1425         int i, zapped = 0;
1426         struct mmu_page_path parents;
1427         struct kvm_mmu_pages pages;
1428
1429         if (parent->role.level == PT_PAGE_TABLE_LEVEL)
1430                 return 0;
1431
1432         kvm_mmu_pages_init(parent, &parents, &pages);
1433         while (mmu_unsync_walk(parent, &pages)) {
1434                 struct kvm_mmu_page *sp;
1435
1436                 for_each_sp(pages, sp, parents, i) {
1437                         kvm_mmu_zap_page(kvm, sp);
1438                         mmu_pages_clear_parents(&parents);
1439                 }
1440                 zapped += pages.nr;
1441                 kvm_mmu_pages_init(parent, &parents, &pages);
1442         }
1443
1444         return zapped;
1445 }
1446
1447 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1448 {
1449         int ret;
1450
1451         trace_kvm_mmu_zap_page(sp);
1452         ++kvm->stat.mmu_shadow_zapped;
1453         ret = mmu_zap_unsync_children(kvm, sp);
1454         kvm_mmu_page_unlink_children(kvm, sp);
1455         kvm_mmu_unlink_parents(kvm, sp);
1456         kvm_flush_remote_tlbs(kvm);
1457         if (!sp->role.invalid && !sp->role.direct)
1458                 unaccount_shadowed(kvm, sp->gfn);
1459         if (sp->unsync)
1460                 kvm_unlink_unsync_page(kvm, sp);
1461         if (!sp->root_count) {
1462                 hlist_del(&sp->hash_link);
1463                 kvm_mmu_free_page(kvm, sp);
1464         } else {
1465                 sp->role.invalid = 1;
1466                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
1467                 kvm_reload_remote_mmus(kvm);
1468         }
1469         kvm_mmu_reset_last_pte_updated(kvm);
1470         return ret;
1471 }
1472
1473 /*
1474  * Changing the number of mmu pages allocated to the vm
1475  * Note: if kvm_nr_mmu_pages is too small, you will get dead lock
1476  */
1477 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int kvm_nr_mmu_pages)
1478 {
1479         int used_pages;
1480
1481         used_pages = kvm->arch.n_alloc_mmu_pages - kvm->arch.n_free_mmu_pages;
1482         used_pages = max(0, used_pages);
1483
1484         /*
1485          * If we set the number of mmu pages to be smaller be than the
1486          * number of actived pages , we must to free some mmu pages before we
1487          * change the value
1488          */
1489
1490         if (used_pages > kvm_nr_mmu_pages) {
1491                 while (used_pages > kvm_nr_mmu_pages) {
1492                         struct kvm_mmu_page *page;
1493
1494                         page = container_of(kvm->arch.active_mmu_pages.prev,
1495                                             struct kvm_mmu_page, link);
1496                         kvm_mmu_zap_page(kvm, page);
1497                         used_pages--;
1498                 }
1499                 kvm->arch.n_free_mmu_pages = 0;
1500         }
1501         else
1502                 kvm->arch.n_free_mmu_pages += kvm_nr_mmu_pages
1503                                          - kvm->arch.n_alloc_mmu_pages;
1504
1505         kvm->arch.n_alloc_mmu_pages = kvm_nr_mmu_pages;
1506 }
1507
1508 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
1509 {
1510         unsigned index;
1511         struct hlist_head *bucket;
1512         struct kvm_mmu_page *sp;
1513         struct hlist_node *node, *n;
1514         int r;
1515
1516         pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1517         r = 0;
1518         index = kvm_page_table_hashfn(gfn);
1519         bucket = &kvm->arch.mmu_page_hash[index];
1520         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link)
1521                 if (sp->gfn == gfn && !sp->role.direct) {
1522                         pgprintk("%s: gfn %lx role %x\n", __func__, gfn,
1523                                  sp->role.word);
1524                         r = 1;
1525                         if (kvm_mmu_zap_page(kvm, sp))
1526                                 n = bucket->first;
1527                 }
1528         return r;
1529 }
1530
1531 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
1532 {
1533         unsigned index;
1534         struct hlist_head *bucket;
1535         struct kvm_mmu_page *sp;
1536         struct hlist_node *node, *nn;
1537
1538         index = kvm_page_table_hashfn(gfn);
1539         bucket = &kvm->arch.mmu_page_hash[index];
1540         hlist_for_each_entry_safe(sp, node, nn, bucket, hash_link) {
1541                 if (sp->gfn == gfn && !sp->role.direct
1542                     && !sp->role.invalid) {
1543                         pgprintk("%s: zap %lx %x\n",
1544                                  __func__, gfn, sp->role.word);
1545                         kvm_mmu_zap_page(kvm, sp);
1546                 }
1547         }
1548 }
1549
1550 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
1551 {
1552         int slot = memslot_id(kvm, gfn_to_memslot(kvm, gfn));
1553         struct kvm_mmu_page *sp = page_header(__pa(pte));
1554
1555         __set_bit(slot, sp->slot_bitmap);
1556 }
1557
1558 static void mmu_convert_notrap(struct kvm_mmu_page *sp)
1559 {
1560         int i;
1561         u64 *pt = sp->spt;
1562
1563         if (shadow_trap_nonpresent_pte == shadow_notrap_nonpresent_pte)
1564                 return;
1565
1566         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1567                 if (pt[i] == shadow_notrap_nonpresent_pte)
1568                         __set_spte(&pt[i], shadow_trap_nonpresent_pte);
1569         }
1570 }
1571
1572 struct page *gva_to_page(struct kvm_vcpu *vcpu, gva_t gva)
1573 {
1574         struct page *page;
1575
1576         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1577
1578         if (gpa == UNMAPPED_GVA)
1579                 return NULL;
1580
1581         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1582
1583         return page;
1584 }
1585
1586 /*
1587  * The function is based on mtrr_type_lookup() in
1588  * arch/x86/kernel/cpu/mtrr/generic.c
1589  */
1590 static int get_mtrr_type(struct mtrr_state_type *mtrr_state,
1591                          u64 start, u64 end)
1592 {
1593         int i;
1594         u64 base, mask;
1595         u8 prev_match, curr_match;
1596         int num_var_ranges = KVM_NR_VAR_MTRR;
1597
1598         if (!mtrr_state->enabled)
1599                 return 0xFF;
1600
1601         /* Make end inclusive end, instead of exclusive */
1602         end--;
1603
1604         /* Look in fixed ranges. Just return the type as per start */
1605         if (mtrr_state->have_fixed && (start < 0x100000)) {
1606                 int idx;
1607
1608                 if (start < 0x80000) {
1609                         idx = 0;
1610                         idx += (start >> 16);
1611                         return mtrr_state->fixed_ranges[idx];
1612                 } else if (start < 0xC0000) {
1613                         idx = 1 * 8;
1614                         idx += ((start - 0x80000) >> 14);
1615                         return mtrr_state->fixed_ranges[idx];
1616                 } else if (start < 0x1000000) {
1617                         idx = 3 * 8;
1618                         idx += ((start - 0xC0000) >> 12);
1619                         return mtrr_state->fixed_ranges[idx];
1620                 }
1621         }
1622
1623         /*
1624          * Look in variable ranges
1625          * Look of multiple ranges matching this address and pick type
1626          * as per MTRR precedence
1627          */
1628         if (!(mtrr_state->enabled & 2))
1629                 return mtrr_state->def_type;
1630
1631         prev_match = 0xFF;
1632         for (i = 0; i < num_var_ranges; ++i) {
1633                 unsigned short start_state, end_state;
1634
1635                 if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11)))
1636                         continue;
1637
1638                 base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) +
1639                        (mtrr_state->var_ranges[i].base_lo & PAGE_MASK);
1640                 mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) +
1641                        (mtrr_state->var_ranges[i].mask_lo & PAGE_MASK);
1642
1643                 start_state = ((start & mask) == (base & mask));
1644                 end_state = ((end & mask) == (base & mask));
1645                 if (start_state != end_state)
1646                         return 0xFE;
1647
1648                 if ((start & mask) != (base & mask))
1649                         continue;
1650
1651                 curr_match = mtrr_state->var_ranges[i].base_lo & 0xff;
1652                 if (prev_match == 0xFF) {
1653                         prev_match = curr_match;
1654                         continue;
1655                 }
1656
1657                 if (prev_match == MTRR_TYPE_UNCACHABLE ||
1658                     curr_match == MTRR_TYPE_UNCACHABLE)
1659                         return MTRR_TYPE_UNCACHABLE;
1660
1661                 if ((prev_match == MTRR_TYPE_WRBACK &&
1662                      curr_match == MTRR_TYPE_WRTHROUGH) ||
1663                     (prev_match == MTRR_TYPE_WRTHROUGH &&
1664                      curr_match == MTRR_TYPE_WRBACK)) {
1665                         prev_match = MTRR_TYPE_WRTHROUGH;
1666                         curr_match = MTRR_TYPE_WRTHROUGH;
1667                 }
1668
1669                 if (prev_match != curr_match)
1670                         return MTRR_TYPE_UNCACHABLE;
1671         }
1672
1673         if (prev_match != 0xFF)
1674                 return prev_match;
1675
1676         return mtrr_state->def_type;
1677 }
1678
1679 u8 kvm_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn)
1680 {
1681         u8 mtrr;
1682
1683         mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT,
1684                              (gfn << PAGE_SHIFT) + PAGE_SIZE);
1685         if (mtrr == 0xfe || mtrr == 0xff)
1686                 mtrr = MTRR_TYPE_WRBACK;
1687         return mtrr;
1688 }
1689 EXPORT_SYMBOL_GPL(kvm_get_guest_memory_type);
1690
1691 static int kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1692 {
1693         unsigned index;
1694         struct hlist_head *bucket;
1695         struct kvm_mmu_page *s;
1696         struct hlist_node *node, *n;
1697
1698         trace_kvm_mmu_unsync_page(sp);
1699         index = kvm_page_table_hashfn(sp->gfn);
1700         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1701         /* don't unsync if pagetable is shadowed with multiple roles */
1702         hlist_for_each_entry_safe(s, node, n, bucket, hash_link) {
1703                 if (s->gfn != sp->gfn || s->role.direct)
1704                         continue;
1705                 if (s->role.word != sp->role.word)
1706                         return 1;
1707         }
1708         ++vcpu->kvm->stat.mmu_unsync;
1709         sp->unsync = 1;
1710
1711         kvm_mmu_mark_parents_unsync(vcpu, sp);
1712
1713         mmu_convert_notrap(sp);
1714         return 0;
1715 }
1716
1717 static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
1718                                   bool can_unsync)
1719 {
1720         struct kvm_mmu_page *shadow;
1721
1722         shadow = kvm_mmu_lookup_page(vcpu->kvm, gfn);
1723         if (shadow) {
1724                 if (shadow->role.level != PT_PAGE_TABLE_LEVEL)
1725                         return 1;
1726                 if (shadow->unsync)
1727                         return 0;
1728                 if (can_unsync && oos_shadow)
1729                         return kvm_unsync_page(vcpu, shadow);
1730                 return 1;
1731         }
1732         return 0;
1733 }
1734
1735 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
1736                     unsigned pte_access, int user_fault,
1737                     int write_fault, int dirty, int largepage,
1738                     gfn_t gfn, pfn_t pfn, bool speculative,
1739                     bool can_unsync)
1740 {
1741         u64 spte;
1742         int ret = 0;
1743
1744         /*
1745          * We don't set the accessed bit, since we sometimes want to see
1746          * whether the guest actually used the pte (in order to detect
1747          * demand paging).
1748          */
1749         spte = shadow_base_present_pte | shadow_dirty_mask;
1750         if (!speculative)
1751                 spte |= shadow_accessed_mask;
1752         if (!dirty)
1753                 pte_access &= ~ACC_WRITE_MASK;
1754         if (pte_access & ACC_EXEC_MASK)
1755                 spte |= shadow_x_mask;
1756         else
1757                 spte |= shadow_nx_mask;
1758         if (pte_access & ACC_USER_MASK)
1759                 spte |= shadow_user_mask;
1760         if (largepage)
1761                 spte |= PT_PAGE_SIZE_MASK;
1762         if (tdp_enabled)
1763                 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
1764                         kvm_is_mmio_pfn(pfn));
1765
1766         spte |= (u64)pfn << PAGE_SHIFT;
1767
1768         if ((pte_access & ACC_WRITE_MASK)
1769             || (write_fault && !is_write_protection(vcpu) && !user_fault)) {
1770
1771                 if (largepage && has_wrprotected_page(vcpu->kvm, gfn, 1)) {
1772                         ret = 1;
1773                         spte = shadow_trap_nonpresent_pte;
1774                         goto set_pte;
1775                 }
1776
1777                 spte |= PT_WRITABLE_MASK;
1778
1779                 /*
1780                  * Optimization: for pte sync, if spte was writable the hash
1781                  * lookup is unnecessary (and expensive). Write protection
1782                  * is responsibility of mmu_get_page / kvm_sync_page.
1783                  * Same reasoning can be applied to dirty page accounting.
1784                  */
1785                 if (!can_unsync && is_writeble_pte(*sptep))
1786                         goto set_pte;
1787
1788                 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
1789                         pgprintk("%s: found shadow page for %lx, marking ro\n",
1790                                  __func__, gfn);
1791                         ret = 1;
1792                         pte_access &= ~ACC_WRITE_MASK;
1793                         if (is_writeble_pte(spte))
1794                                 spte &= ~PT_WRITABLE_MASK;
1795                 }
1796         }
1797
1798         if (pte_access & ACC_WRITE_MASK)
1799                 mark_page_dirty(vcpu->kvm, gfn);
1800
1801 set_pte:
1802         __set_spte(sptep, spte);
1803         return ret;
1804 }
1805
1806 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
1807                          unsigned pt_access, unsigned pte_access,
1808                          int user_fault, int write_fault, int dirty,
1809                          int *ptwrite, int largepage, gfn_t gfn,
1810                          pfn_t pfn, bool speculative)
1811 {
1812         int was_rmapped = 0;
1813         int was_writeble = is_writeble_pte(*sptep);
1814         int rmap_count;
1815
1816         pgprintk("%s: spte %llx access %x write_fault %d"
1817                  " user_fault %d gfn %lx\n",
1818                  __func__, *sptep, pt_access,
1819                  write_fault, user_fault, gfn);
1820
1821         if (is_rmap_spte(*sptep)) {
1822                 /*
1823                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
1824                  * the parent of the now unreachable PTE.
1825                  */
1826                 if (largepage && !is_large_pte(*sptep)) {
1827                         struct kvm_mmu_page *child;
1828                         u64 pte = *sptep;
1829
1830                         child = page_header(pte & PT64_BASE_ADDR_MASK);
1831                         mmu_page_remove_parent_pte(child, sptep);
1832                 } else if (pfn != spte_to_pfn(*sptep)) {
1833                         pgprintk("hfn old %lx new %lx\n",
1834                                  spte_to_pfn(*sptep), pfn);
1835                         rmap_remove(vcpu->kvm, sptep);
1836                 } else
1837                         was_rmapped = 1;
1838         }
1839         if (set_spte(vcpu, sptep, pte_access, user_fault, write_fault,
1840                       dirty, largepage, gfn, pfn, speculative, true)) {
1841                 if (write_fault)
1842                         *ptwrite = 1;
1843                 kvm_x86_ops->tlb_flush(vcpu);
1844         }
1845
1846         pgprintk("%s: setting spte %llx\n", __func__, *sptep);
1847         pgprintk("instantiating %s PTE (%s) at %ld (%llx) addr %p\n",
1848                  is_large_pte(*sptep)? "2MB" : "4kB",
1849                  *sptep & PT_PRESENT_MASK ?"RW":"R", gfn,
1850                  *sptep, sptep);
1851         if (!was_rmapped && is_large_pte(*sptep))
1852                 ++vcpu->kvm->stat.lpages;
1853
1854         page_header_update_slot(vcpu->kvm, sptep, gfn);
1855         if (!was_rmapped) {
1856                 rmap_count = rmap_add(vcpu, sptep, gfn);
1857                 if (!is_rmap_spte(*sptep))
1858                         kvm_release_pfn_clean(pfn);
1859                 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
1860                         rmap_recycle(vcpu, gfn, largepage);
1861         } else {
1862                 if (was_writeble)
1863                         kvm_release_pfn_dirty(pfn);
1864                 else
1865                         kvm_release_pfn_clean(pfn);
1866         }
1867         if (speculative) {
1868                 vcpu->arch.last_pte_updated = sptep;
1869                 vcpu->arch.last_pte_gfn = gfn;
1870         }
1871 }
1872
1873 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
1874 {
1875 }
1876
1877 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
1878                         int largepage, gfn_t gfn, pfn_t pfn)
1879 {
1880         struct kvm_shadow_walk_iterator iterator;
1881         struct kvm_mmu_page *sp;
1882         int pt_write = 0;
1883         gfn_t pseudo_gfn;
1884
1885         for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
1886                 if (iterator.level == PT_PAGE_TABLE_LEVEL
1887                     || (largepage && iterator.level == PT_DIRECTORY_LEVEL)) {
1888                         mmu_set_spte(vcpu, iterator.sptep, ACC_ALL, ACC_ALL,
1889                                      0, write, 1, &pt_write,
1890                                      largepage, gfn, pfn, false);
1891                         ++vcpu->stat.pf_fixed;
1892                         break;
1893                 }
1894
1895                 if (*iterator.sptep == shadow_trap_nonpresent_pte) {
1896                         pseudo_gfn = (iterator.addr & PT64_DIR_BASE_ADDR_MASK) >> PAGE_SHIFT;
1897                         sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
1898                                               iterator.level - 1,
1899                                               1, ACC_ALL, iterator.sptep);
1900                         if (!sp) {
1901                                 pgprintk("nonpaging_map: ENOMEM\n");
1902                                 kvm_release_pfn_clean(pfn);
1903                                 return -ENOMEM;
1904                         }
1905
1906                         __set_spte(iterator.sptep,
1907                                    __pa(sp->spt)
1908                                    | PT_PRESENT_MASK | PT_WRITABLE_MASK
1909                                    | shadow_user_mask | shadow_x_mask);
1910                 }
1911         }
1912         return pt_write;
1913 }
1914
1915 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn)
1916 {
1917         int r;
1918         int largepage = 0;
1919         pfn_t pfn;
1920         unsigned long mmu_seq;
1921
1922         if (mapping_level(vcpu, gfn) == PT_DIRECTORY_LEVEL) {
1923                 gfn &= ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1);
1924                 largepage = 1;
1925         }
1926
1927         mmu_seq = vcpu->kvm->mmu_notifier_seq;
1928         smp_rmb();
1929         pfn = gfn_to_pfn(vcpu->kvm, gfn);
1930
1931         /* mmio */
1932         if (is_error_pfn(pfn)) {
1933                 kvm_release_pfn_clean(pfn);
1934                 return 1;
1935         }
1936
1937         spin_lock(&vcpu->kvm->mmu_lock);
1938         if (mmu_notifier_retry(vcpu, mmu_seq))
1939                 goto out_unlock;
1940         kvm_mmu_free_some_pages(vcpu);
1941         r = __direct_map(vcpu, v, write, largepage, gfn, pfn);
1942         spin_unlock(&vcpu->kvm->mmu_lock);
1943
1944
1945         return r;
1946
1947 out_unlock:
1948         spin_unlock(&vcpu->kvm->mmu_lock);
1949         kvm_release_pfn_clean(pfn);
1950         return 0;
1951 }
1952
1953
1954 static void mmu_free_roots(struct kvm_vcpu *vcpu)
1955 {
1956         int i;
1957         struct kvm_mmu_page *sp;
1958
1959         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1960                 return;
1961         spin_lock(&vcpu->kvm->mmu_lock);
1962         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1963                 hpa_t root = vcpu->arch.mmu.root_hpa;
1964
1965                 sp = page_header(root);
1966                 --sp->root_count;
1967                 if (!sp->root_count && sp->role.invalid)
1968                         kvm_mmu_zap_page(vcpu->kvm, sp);
1969                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1970                 spin_unlock(&vcpu->kvm->mmu_lock);
1971                 return;
1972         }
1973         for (i = 0; i < 4; ++i) {
1974                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1975
1976                 if (root) {
1977                         root &= PT64_BASE_ADDR_MASK;
1978                         sp = page_header(root);
1979                         --sp->root_count;
1980                         if (!sp->root_count && sp->role.invalid)
1981                                 kvm_mmu_zap_page(vcpu->kvm, sp);
1982                 }
1983                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1984         }
1985         spin_unlock(&vcpu->kvm->mmu_lock);
1986         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1987 }
1988
1989 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
1990 {
1991         int ret = 0;
1992
1993         if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
1994                 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
1995                 ret = 1;
1996         }
1997
1998         return ret;
1999 }
2000
2001 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
2002 {
2003         int i;
2004         gfn_t root_gfn;
2005         struct kvm_mmu_page *sp;
2006         int direct = 0;
2007         u64 pdptr;
2008
2009         root_gfn = vcpu->arch.cr3 >> PAGE_SHIFT;
2010
2011         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2012                 hpa_t root = vcpu->arch.mmu.root_hpa;
2013
2014                 ASSERT(!VALID_PAGE(root));
2015                 if (tdp_enabled)
2016                         direct = 1;
2017                 if (mmu_check_root(vcpu, root_gfn))
2018                         return 1;
2019                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
2020                                       PT64_ROOT_LEVEL, direct,
2021                                       ACC_ALL, NULL);
2022                 root = __pa(sp->spt);
2023                 ++sp->root_count;
2024                 vcpu->arch.mmu.root_hpa = root;
2025                 return 0;
2026         }
2027         direct = !is_paging(vcpu);
2028         if (tdp_enabled)
2029                 direct = 1;
2030         for (i = 0; i < 4; ++i) {
2031                 hpa_t root = vcpu->arch.mmu.pae_root[i];
2032
2033                 ASSERT(!VALID_PAGE(root));
2034                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
2035                         pdptr = kvm_pdptr_read(vcpu, i);
2036                         if (!is_present_gpte(pdptr)) {
2037                                 vcpu->arch.mmu.pae_root[i] = 0;
2038                                 continue;
2039                         }
2040                         root_gfn = pdptr >> PAGE_SHIFT;
2041                 } else if (vcpu->arch.mmu.root_level == 0)
2042                         root_gfn = 0;
2043                 if (mmu_check_root(vcpu, root_gfn))
2044                         return 1;
2045                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
2046                                       PT32_ROOT_LEVEL, direct,
2047                                       ACC_ALL, NULL);
2048                 root = __pa(sp->spt);
2049                 ++sp->root_count;
2050                 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
2051         }
2052         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
2053         return 0;
2054 }
2055
2056 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
2057 {
2058         int i;
2059         struct kvm_mmu_page *sp;
2060
2061         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2062                 return;
2063         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2064                 hpa_t root = vcpu->arch.mmu.root_hpa;
2065                 sp = page_header(root);
2066                 mmu_sync_children(vcpu, sp);
2067                 return;
2068         }
2069         for (i = 0; i < 4; ++i) {
2070                 hpa_t root = vcpu->arch.mmu.pae_root[i];
2071
2072                 if (root && VALID_PAGE(root)) {
2073                         root &= PT64_BASE_ADDR_MASK;
2074                         sp = page_header(root);
2075                         mmu_sync_children(vcpu, sp);
2076                 }
2077         }
2078 }
2079
2080 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
2081 {
2082         spin_lock(&vcpu->kvm->mmu_lock);
2083         mmu_sync_roots(vcpu);
2084         spin_unlock(&vcpu->kvm->mmu_lock);
2085 }
2086
2087 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr)
2088 {
2089         return vaddr;
2090 }
2091
2092 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
2093                                 u32 error_code)
2094 {
2095         gfn_t gfn;
2096         int r;
2097
2098         pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
2099         r = mmu_topup_memory_caches(vcpu);
2100         if (r)
2101                 return r;
2102
2103         ASSERT(vcpu);
2104         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2105
2106         gfn = gva >> PAGE_SHIFT;
2107
2108         return nonpaging_map(vcpu, gva & PAGE_MASK,
2109                              error_code & PFERR_WRITE_MASK, gfn);
2110 }
2111
2112 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
2113                                 u32 error_code)
2114 {
2115         pfn_t pfn;
2116         int r;
2117         int largepage = 0;
2118         gfn_t gfn = gpa >> PAGE_SHIFT;
2119         unsigned long mmu_seq;
2120
2121         ASSERT(vcpu);
2122         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2123
2124         r = mmu_topup_memory_caches(vcpu);
2125         if (r)
2126                 return r;
2127
2128         if (mapping_level(vcpu, gfn) == PT_DIRECTORY_LEVEL) {
2129                 gfn &= ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1);
2130                 largepage = 1;
2131         }
2132         mmu_seq = vcpu->kvm->mmu_notifier_seq;
2133         smp_rmb();
2134         pfn = gfn_to_pfn(vcpu->kvm, gfn);
2135         if (is_error_pfn(pfn)) {
2136                 kvm_release_pfn_clean(pfn);
2137                 return 1;
2138         }
2139         spin_lock(&vcpu->kvm->mmu_lock);
2140         if (mmu_notifier_retry(vcpu, mmu_seq))
2141                 goto out_unlock;
2142         kvm_mmu_free_some_pages(vcpu);
2143         r = __direct_map(vcpu, gpa, error_code & PFERR_WRITE_MASK,
2144                          largepage, gfn, pfn);
2145         spin_unlock(&vcpu->kvm->mmu_lock);
2146
2147         return r;
2148
2149 out_unlock:
2150         spin_unlock(&vcpu->kvm->mmu_lock);
2151         kvm_release_pfn_clean(pfn);
2152         return 0;
2153 }
2154
2155 static void nonpaging_free(struct kvm_vcpu *vcpu)
2156 {
2157         mmu_free_roots(vcpu);
2158 }
2159
2160 static int nonpaging_init_context(struct kvm_vcpu *vcpu)
2161 {
2162         struct kvm_mmu *context = &vcpu->arch.mmu;
2163
2164         context->new_cr3 = nonpaging_new_cr3;
2165         context->page_fault = nonpaging_page_fault;
2166         context->gva_to_gpa = nonpaging_gva_to_gpa;
2167         context->free = nonpaging_free;
2168         context->prefetch_page = nonpaging_prefetch_page;
2169         context->sync_page = nonpaging_sync_page;
2170         context->invlpg = nonpaging_invlpg;
2171         context->root_level = 0;
2172         context->shadow_root_level = PT32E_ROOT_LEVEL;
2173         context->root_hpa = INVALID_PAGE;
2174         return 0;
2175 }
2176
2177 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2178 {
2179         ++vcpu->stat.tlb_flush;
2180         kvm_x86_ops->tlb_flush(vcpu);
2181 }
2182
2183 static void paging_new_cr3(struct kvm_vcpu *vcpu)
2184 {
2185         pgprintk("%s: cr3 %lx\n", __func__, vcpu->arch.cr3);
2186         mmu_free_roots(vcpu);
2187 }
2188
2189 static void inject_page_fault(struct kvm_vcpu *vcpu,
2190                               u64 addr,
2191                               u32 err_code)
2192 {
2193         kvm_inject_page_fault(vcpu, addr, err_code);
2194 }
2195
2196 static void paging_free(struct kvm_vcpu *vcpu)
2197 {
2198         nonpaging_free(vcpu);
2199 }
2200
2201 static bool is_rsvd_bits_set(struct kvm_vcpu *vcpu, u64 gpte, int level)
2202 {
2203         int bit7;
2204
2205         bit7 = (gpte >> 7) & 1;
2206         return (gpte & vcpu->arch.mmu.rsvd_bits_mask[bit7][level-1]) != 0;
2207 }
2208
2209 #define PTTYPE 64
2210 #include "paging_tmpl.h"
2211 #undef PTTYPE
2212
2213 #define PTTYPE 32
2214 #include "paging_tmpl.h"
2215 #undef PTTYPE
2216
2217 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu, int level)
2218 {
2219         struct kvm_mmu *context = &vcpu->arch.mmu;
2220         int maxphyaddr = cpuid_maxphyaddr(vcpu);
2221         u64 exb_bit_rsvd = 0;
2222
2223         if (!is_nx(vcpu))
2224                 exb_bit_rsvd = rsvd_bits(63, 63);
2225         switch (level) {
2226         case PT32_ROOT_LEVEL:
2227                 /* no rsvd bits for 2 level 4K page table entries */
2228                 context->rsvd_bits_mask[0][1] = 0;
2229                 context->rsvd_bits_mask[0][0] = 0;
2230                 if (is_cpuid_PSE36())
2231                         /* 36bits PSE 4MB page */
2232                         context->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
2233                 else
2234                         /* 32 bits PSE 4MB page */
2235                         context->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
2236                 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[1][0];
2237                 break;
2238         case PT32E_ROOT_LEVEL:
2239                 context->rsvd_bits_mask[0][2] =
2240                         rsvd_bits(maxphyaddr, 63) |
2241                         rsvd_bits(7, 8) | rsvd_bits(1, 2);      /* PDPTE */
2242                 context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
2243                         rsvd_bits(maxphyaddr, 62);      /* PDE */
2244                 context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
2245                         rsvd_bits(maxphyaddr, 62);      /* PTE */
2246                 context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
2247                         rsvd_bits(maxphyaddr, 62) |
2248                         rsvd_bits(13, 20);              /* large page */
2249                 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[1][0];
2250                 break;
2251         case PT64_ROOT_LEVEL:
2252                 context->rsvd_bits_mask[0][3] = exb_bit_rsvd |
2253                         rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
2254                 context->rsvd_bits_mask[0][2] = exb_bit_rsvd |
2255                         rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
2256                 context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
2257                         rsvd_bits(maxphyaddr, 51);
2258                 context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
2259                         rsvd_bits(maxphyaddr, 51);
2260                 context->rsvd_bits_mask[1][3] = context->rsvd_bits_mask[0][3];
2261                 context->rsvd_bits_mask[1][2] = context->rsvd_bits_mask[0][2];
2262                 context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
2263                         rsvd_bits(maxphyaddr, 51) |
2264                         rsvd_bits(13, 20);              /* large page */
2265                 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[1][0];
2266                 break;
2267         }
2268 }
2269
2270 static int paging64_init_context_common(struct kvm_vcpu *vcpu, int level)
2271 {
2272         struct kvm_mmu *context = &vcpu->arch.mmu;
2273
2274         ASSERT(is_pae(vcpu));
2275         context->new_cr3 = paging_new_cr3;
2276         context->page_fault = paging64_page_fault;
2277         context->gva_to_gpa = paging64_gva_to_gpa;
2278         context->prefetch_page = paging64_prefetch_page;
2279         context->sync_page = paging64_sync_page;
2280         context->invlpg = paging64_invlpg;
2281         context->free = paging_free;
2282         context->root_level = level;
2283         context->shadow_root_level = level;
2284         context->root_hpa = INVALID_PAGE;
2285         return 0;
2286 }
2287
2288 static int paging64_init_context(struct kvm_vcpu *vcpu)
2289 {
2290         reset_rsvds_bits_mask(vcpu, PT64_ROOT_LEVEL);
2291         return paging64_init_context_common(vcpu, PT64_ROOT_LEVEL);
2292 }
2293
2294 static int paging32_init_context(struct kvm_vcpu *vcpu)
2295 {
2296         struct kvm_mmu *context = &vcpu->arch.mmu;
2297
2298         reset_rsvds_bits_mask(vcpu, PT32_ROOT_LEVEL);
2299         context->new_cr3 = paging_new_cr3;
2300         context->page_fault = paging32_page_fault;
2301         context->gva_to_gpa = paging32_gva_to_gpa;
2302         context->free = paging_free;
2303         context->prefetch_page = paging32_prefetch_page;
2304         context->sync_page = paging32_sync_page;
2305         context->invlpg = paging32_invlpg;
2306         context->root_level = PT32_ROOT_LEVEL;
2307         context->shadow_root_level = PT32E_ROOT_LEVEL;
2308         context->root_hpa = INVALID_PAGE;
2309         return 0;
2310 }
2311
2312 static int paging32E_init_context(struct kvm_vcpu *vcpu)
2313 {
2314         reset_rsvds_bits_mask(vcpu, PT32E_ROOT_LEVEL);
2315         return paging64_init_context_common(vcpu, PT32E_ROOT_LEVEL);
2316 }
2317
2318 static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
2319 {
2320         struct kvm_mmu *context = &vcpu->arch.mmu;
2321
2322         context->new_cr3 = nonpaging_new_cr3;
2323         context->page_fault = tdp_page_fault;
2324         context->free = nonpaging_free;
2325         context->prefetch_page = nonpaging_prefetch_page;
2326         context->sync_page = nonpaging_sync_page;
2327         context->invlpg = nonpaging_invlpg;
2328         context->shadow_root_level = kvm_x86_ops->get_tdp_level();
2329         context->root_hpa = INVALID_PAGE;
2330
2331         if (!is_paging(vcpu)) {
2332                 context->gva_to_gpa = nonpaging_gva_to_gpa;
2333                 context->root_level = 0;
2334         } else if (is_long_mode(vcpu)) {
2335                 reset_rsvds_bits_mask(vcpu, PT64_ROOT_LEVEL);
2336                 context->gva_to_gpa = paging64_gva_to_gpa;
2337                 context->root_level = PT64_ROOT_LEVEL;
2338         } else if (is_pae(vcpu)) {
2339                 reset_rsvds_bits_mask(vcpu, PT32E_ROOT_LEVEL);
2340                 context->gva_to_gpa = paging64_gva_to_gpa;
2341                 context->root_level = PT32E_ROOT_LEVEL;
2342         } else {
2343                 reset_rsvds_bits_mask(vcpu, PT32_ROOT_LEVEL);
2344                 context->gva_to_gpa = paging32_gva_to_gpa;
2345                 context->root_level = PT32_ROOT_LEVEL;
2346         }
2347
2348         return 0;
2349 }
2350
2351 static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
2352 {
2353         int r;
2354
2355         ASSERT(vcpu);
2356         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2357
2358         if (!is_paging(vcpu))
2359                 r = nonpaging_init_context(vcpu);
2360         else if (is_long_mode(vcpu))
2361                 r = paging64_init_context(vcpu);
2362         else if (is_pae(vcpu))
2363                 r = paging32E_init_context(vcpu);
2364         else
2365                 r = paging32_init_context(vcpu);
2366
2367         vcpu->arch.mmu.base_role.glevels = vcpu->arch.mmu.root_level;
2368
2369         return r;
2370 }
2371
2372 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
2373 {
2374         vcpu->arch.update_pte.pfn = bad_pfn;
2375
2376         if (tdp_enabled)
2377                 return init_kvm_tdp_mmu(vcpu);
2378         else
2379                 return init_kvm_softmmu(vcpu);
2380 }
2381
2382 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
2383 {
2384         ASSERT(vcpu);
2385         if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) {
2386                 vcpu->arch.mmu.free(vcpu);
2387                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
2388         }
2389 }
2390
2391 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
2392 {
2393         destroy_kvm_mmu(vcpu);
2394         return init_kvm_mmu(vcpu);
2395 }
2396 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
2397
2398 int kvm_mmu_load(struct kvm_vcpu *vcpu)
2399 {
2400         int r;
2401
2402         r = mmu_topup_memory_caches(vcpu);
2403         if (r)
2404                 goto out;
2405         spin_lock(&vcpu->kvm->mmu_lock);
2406         kvm_mmu_free_some_pages(vcpu);
2407         r = mmu_alloc_roots(vcpu);
2408         mmu_sync_roots(vcpu);
2409         spin_unlock(&vcpu->kvm->mmu_lock);
2410         if (r)
2411                 goto out;
2412         /* set_cr3() should ensure TLB has been flushed */
2413         kvm_x86_ops->set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
2414 out:
2415         return r;
2416 }
2417 EXPORT_SYMBOL_GPL(kvm_mmu_load);
2418
2419 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
2420 {
2421         mmu_free_roots(vcpu);
2422 }
2423
2424 static void mmu_pte_write_zap_pte(struct kvm_vcpu *vcpu,
2425                                   struct kvm_mmu_page *sp,
2426                                   u64 *spte)
2427 {
2428         u64 pte;
2429         struct kvm_mmu_page *child;
2430
2431         pte = *spte;
2432         if (is_shadow_present_pte(pte)) {
2433                 if (is_last_spte(pte, sp->role.level))
2434                         rmap_remove(vcpu->kvm, spte);
2435                 else {
2436                         child = page_header(pte & PT64_BASE_ADDR_MASK);
2437                         mmu_page_remove_parent_pte(child, spte);
2438                 }
2439         }
2440         __set_spte(spte, shadow_trap_nonpresent_pte);
2441         if (is_large_pte(pte))
2442                 --vcpu->kvm->stat.lpages;
2443 }
2444
2445 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
2446                                   struct kvm_mmu_page *sp,
2447                                   u64 *spte,
2448                                   const void *new)
2449 {
2450         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
2451                 if (!vcpu->arch.update_pte.largepage ||
2452                     sp->role.glevels == PT32_ROOT_LEVEL) {
2453                         ++vcpu->kvm->stat.mmu_pde_zapped;
2454                         return;
2455                 }
2456         }
2457
2458         ++vcpu->kvm->stat.mmu_pte_updated;
2459         if (sp->role.glevels == PT32_ROOT_LEVEL)
2460                 paging32_update_pte(vcpu, sp, spte, new);
2461         else
2462                 paging64_update_pte(vcpu, sp, spte, new);
2463 }
2464
2465 static bool need_remote_flush(u64 old, u64 new)
2466 {
2467         if (!is_shadow_present_pte(old))
2468                 return false;
2469         if (!is_shadow_present_pte(new))
2470                 return true;
2471         if ((old ^ new) & PT64_BASE_ADDR_MASK)
2472                 return true;
2473         old ^= PT64_NX_MASK;
2474         new ^= PT64_NX_MASK;
2475         return (old & ~new & PT64_PERM_MASK) != 0;
2476 }
2477
2478 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, u64 old, u64 new)
2479 {
2480         if (need_remote_flush(old, new))
2481                 kvm_flush_remote_tlbs(vcpu->kvm);
2482         else
2483                 kvm_mmu_flush_tlb(vcpu);
2484 }
2485
2486 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
2487 {
2488         u64 *spte = vcpu->arch.last_pte_updated;
2489
2490         return !!(spte && (*spte & shadow_accessed_mask));
2491 }
2492
2493 static void mmu_guess_page_from_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2494                                           const u8 *new, int bytes)
2495 {
2496         gfn_t gfn;
2497         int r;
2498         u64 gpte = 0;
2499         pfn_t pfn;
2500
2501         vcpu->arch.update_pte.largepage = 0;
2502
2503         if (bytes != 4 && bytes != 8)
2504                 return;
2505
2506         /*
2507          * Assume that the pte write on a page table of the same type
2508          * as the current vcpu paging mode.  This is nearly always true
2509          * (might be false while changing modes).  Note it is verified later
2510          * by update_pte().
2511          */
2512         if (is_pae(vcpu)) {
2513                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
2514                 if ((bytes == 4) && (gpa % 4 == 0)) {
2515                         r = kvm_read_guest(vcpu->kvm, gpa & ~(u64)7, &gpte, 8);
2516                         if (r)
2517                                 return;
2518                         memcpy((void *)&gpte + (gpa % 8), new, 4);
2519                 } else if ((bytes == 8) && (gpa % 8 == 0)) {
2520                         memcpy((void *)&gpte, new, 8);
2521                 }
2522         } else {
2523                 if ((bytes == 4) && (gpa % 4 == 0))
2524                         memcpy((void *)&gpte, new, 4);
2525         }
2526         if (!is_present_gpte(gpte))
2527                 return;
2528         gfn = (gpte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
2529
2530         if (is_large_pte(gpte) &&
2531             (mapping_level(vcpu, gfn) == PT_DIRECTORY_LEVEL)) {
2532                 gfn &= ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1);
2533                 vcpu->arch.update_pte.largepage = 1;
2534         }
2535         vcpu->arch.update_pte.mmu_seq = vcpu->kvm->mmu_notifier_seq;
2536         smp_rmb();
2537         pfn = gfn_to_pfn(vcpu->kvm, gfn);
2538
2539         if (is_error_pfn(pfn)) {
2540                 kvm_release_pfn_clean(pfn);
2541                 return;
2542         }
2543         vcpu->arch.update_pte.gfn = gfn;
2544         vcpu->arch.update_pte.pfn = pfn;
2545 }
2546
2547 static void kvm_mmu_access_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2548 {
2549         u64 *spte = vcpu->arch.last_pte_updated;
2550
2551         if (spte
2552             && vcpu->arch.last_pte_gfn == gfn
2553             && shadow_accessed_mask
2554             && !(*spte & shadow_accessed_mask)
2555             && is_shadow_present_pte(*spte))
2556                 set_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
2557 }
2558
2559 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2560                        const u8 *new, int bytes,
2561                        bool guest_initiated)
2562 {
2563         gfn_t gfn = gpa >> PAGE_SHIFT;
2564         struct kvm_mmu_page *sp;
2565         struct hlist_node *node, *n;
2566         struct hlist_head *bucket;
2567         unsigned index;
2568         u64 entry, gentry;
2569         u64 *spte;
2570         unsigned offset = offset_in_page(gpa);
2571         unsigned pte_size;
2572         unsigned page_offset;
2573         unsigned misaligned;
2574         unsigned quadrant;
2575         int level;
2576         int flooded = 0;
2577         int npte;
2578         int r;
2579
2580         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
2581         mmu_guess_page_from_pte_write(vcpu, gpa, new, bytes);
2582         spin_lock(&vcpu->kvm->mmu_lock);
2583         kvm_mmu_access_page(vcpu, gfn);
2584         kvm_mmu_free_some_pages(vcpu);
2585         ++vcpu->kvm->stat.mmu_pte_write;
2586         kvm_mmu_audit(vcpu, "pre pte write");
2587         if (guest_initiated) {
2588                 if (gfn == vcpu->arch.last_pt_write_gfn
2589                     && !last_updated_pte_accessed(vcpu)) {
2590                         ++vcpu->arch.last_pt_write_count;
2591                         if (vcpu->arch.last_pt_write_count >= 3)
2592                                 flooded = 1;
2593                 } else {
2594                         vcpu->arch.last_pt_write_gfn = gfn;
2595                         vcpu->arch.last_pt_write_count = 1;
2596                         vcpu->arch.last_pte_updated = NULL;
2597                 }
2598         }
2599         index = kvm_page_table_hashfn(gfn);
2600         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
2601         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link) {
2602                 if (sp->gfn != gfn || sp->role.direct || sp->role.invalid)
2603                         continue;
2604                 pte_size = sp->role.glevels == PT32_ROOT_LEVEL ? 4 : 8;
2605                 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
2606                 misaligned |= bytes < 4;
2607                 if (misaligned || flooded) {
2608                         /*
2609                          * Misaligned accesses are too much trouble to fix
2610                          * up; also, they usually indicate a page is not used
2611                          * as a page table.
2612                          *
2613                          * If we're seeing too many writes to a page,
2614                          * it may no longer be a page table, or we may be
2615                          * forking, in which case it is better to unmap the
2616                          * page.
2617                          */
2618                         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
2619                                  gpa, bytes, sp->role.word);
2620                         if (kvm_mmu_zap_page(vcpu->kvm, sp))
2621                                 n = bucket->first;
2622                         ++vcpu->kvm->stat.mmu_flooded;
2623                         continue;
2624                 }
2625                 page_offset = offset;
2626                 level = sp->role.level;
2627                 npte = 1;
2628                 if (sp->role.glevels == PT32_ROOT_LEVEL) {
2629                         page_offset <<= 1;      /* 32->64 */
2630                         /*
2631                          * A 32-bit pde maps 4MB while the shadow pdes map
2632                          * only 2MB.  So we need to double the offset again
2633                          * and zap two pdes instead of one.
2634                          */
2635                         if (level == PT32_ROOT_LEVEL) {
2636                                 page_offset &= ~7; /* kill rounding error */
2637                                 page_offset <<= 1;
2638                                 npte = 2;
2639                         }
2640                         quadrant = page_offset >> PAGE_SHIFT;
2641                         page_offset &= ~PAGE_MASK;
2642                         if (quadrant != sp->role.quadrant)
2643                                 continue;
2644                 }
2645                 spte = &sp->spt[page_offset / sizeof(*spte)];
2646                 if ((gpa & (pte_size - 1)) || (bytes < pte_size)) {
2647                         gentry = 0;
2648                         r = kvm_read_guest_atomic(vcpu->kvm,
2649                                                   gpa & ~(u64)(pte_size - 1),
2650                                                   &gentry, pte_size);
2651                         new = (const void *)&gentry;
2652                         if (r < 0)
2653                                 new = NULL;
2654                 }
2655                 while (npte--) {
2656                         entry = *spte;
2657                         mmu_pte_write_zap_pte(vcpu, sp, spte);
2658                         if (new)
2659                                 mmu_pte_write_new_pte(vcpu, sp, spte, new);
2660                         mmu_pte_write_flush_tlb(vcpu, entry, *spte);
2661                         ++spte;
2662                 }
2663         }
2664         kvm_mmu_audit(vcpu, "post pte write");
2665         spin_unlock(&vcpu->kvm->mmu_lock);
2666         if (!is_error_pfn(vcpu->arch.update_pte.pfn)) {
2667                 kvm_release_pfn_clean(vcpu->arch.update_pte.pfn);
2668                 vcpu->arch.update_pte.pfn = bad_pfn;
2669         }
2670 }
2671
2672 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2673 {
2674         gpa_t gpa;
2675         int r;
2676
2677         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
2678
2679         spin_lock(&vcpu->kvm->mmu_lock);
2680         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2681         spin_unlock(&vcpu->kvm->mmu_lock);
2682         return r;
2683 }
2684 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
2685
2686 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
2687 {
2688         while (vcpu->kvm->arch.n_free_mmu_pages < KVM_REFILL_PAGES) {
2689                 struct kvm_mmu_page *sp;
2690
2691                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
2692                                   struct kvm_mmu_page, link);
2693                 kvm_mmu_zap_page(vcpu->kvm, sp);
2694                 ++vcpu->kvm->stat.mmu_recycled;
2695         }
2696 }
2697
2698 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
2699 {
2700         int r;
2701         enum emulation_result er;
2702
2703         r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
2704         if (r < 0)
2705                 goto out;
2706
2707         if (!r) {
2708                 r = 1;
2709                 goto out;
2710         }
2711
2712         r = mmu_topup_memory_caches(vcpu);
2713         if (r)
2714                 goto out;
2715
2716         er = emulate_instruction(vcpu, vcpu->run, cr2, error_code, 0);
2717
2718         switch (er) {
2719         case EMULATE_DONE:
2720                 return 1;
2721         case EMULATE_DO_MMIO:
2722                 ++vcpu->stat.mmio_exits;
2723                 return 0;
2724         case EMULATE_FAIL:
2725                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2726                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
2727                 return 0;
2728         default:
2729                 BUG();
2730         }
2731 out:
2732         return r;
2733 }
2734 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
2735
2736 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
2737 {
2738         vcpu->arch.mmu.invlpg(vcpu, gva);
2739         kvm_mmu_flush_tlb(vcpu);
2740         ++vcpu->stat.invlpg;
2741 }
2742 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
2743
2744 void kvm_enable_tdp(void)
2745 {
2746         tdp_enabled = true;
2747 }
2748 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
2749
2750 void kvm_disable_tdp(void)
2751 {
2752         tdp_enabled = false;
2753 }
2754 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
2755
2756 static void free_mmu_pages(struct kvm_vcpu *vcpu)
2757 {
2758         free_page((unsigned long)vcpu->arch.mmu.pae_root);
2759 }
2760
2761 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
2762 {
2763         struct page *page;
2764         int i;
2765
2766         ASSERT(vcpu);
2767
2768         spin_lock(&vcpu->kvm->mmu_lock);
2769         if (vcpu->kvm->arch.n_requested_mmu_pages)
2770                 vcpu->kvm->arch.n_free_mmu_pages =
2771                                         vcpu->kvm->arch.n_requested_mmu_pages;
2772         else
2773                 vcpu->kvm->arch.n_free_mmu_pages =
2774                                         vcpu->kvm->arch.n_alloc_mmu_pages;
2775         spin_unlock(&vcpu->kvm->mmu_lock);
2776         /*
2777          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
2778          * Therefore we need to allocate shadow page tables in the first
2779          * 4GB of memory, which happens to fit the DMA32 zone.
2780          */
2781         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
2782         if (!page)
2783                 goto error_1;
2784         vcpu->arch.mmu.pae_root = page_address(page);
2785         for (i = 0; i < 4; ++i)
2786                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
2787
2788         return 0;
2789
2790 error_1:
2791         free_mmu_pages(vcpu);
2792         return -ENOMEM;
2793 }
2794
2795 int kvm_mmu_create(struct kvm_vcpu *vcpu)
2796 {
2797         ASSERT(vcpu);
2798         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2799
2800         return alloc_mmu_pages(vcpu);
2801 }
2802
2803 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
2804 {
2805         ASSERT(vcpu);
2806         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2807
2808         return init_kvm_mmu(vcpu);
2809 }
2810
2811 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
2812 {
2813         ASSERT(vcpu);
2814
2815         destroy_kvm_mmu(vcpu);
2816         free_mmu_pages(vcpu);
2817         mmu_free_memory_caches(vcpu);
2818 }
2819
2820 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
2821 {
2822         struct kvm_mmu_page *sp;
2823
2824         list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
2825                 int i;
2826                 u64 *pt;
2827
2828                 if (!test_bit(slot, sp->slot_bitmap))
2829                         continue;
2830
2831                 pt = sp->spt;
2832                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2833                         /* avoid RMW */
2834                         if (pt[i] & PT_WRITABLE_MASK)
2835                                 pt[i] &= ~PT_WRITABLE_MASK;
2836         }
2837         kvm_flush_remote_tlbs(kvm);
2838 }
2839
2840 void kvm_mmu_zap_all(struct kvm *kvm)
2841 {
2842         struct kvm_mmu_page *sp, *node;
2843
2844         spin_lock(&kvm->mmu_lock);
2845         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
2846                 if (kvm_mmu_zap_page(kvm, sp))
2847                         node = container_of(kvm->arch.active_mmu_pages.next,
2848                                             struct kvm_mmu_page, link);
2849         spin_unlock(&kvm->mmu_lock);
2850
2851         kvm_flush_remote_tlbs(kvm);
2852 }
2853
2854 static void kvm_mmu_remove_one_alloc_mmu_page(struct kvm *kvm)
2855 {
2856         struct kvm_mmu_page *page;
2857
2858         page = container_of(kvm->arch.active_mmu_pages.prev,
2859                             struct kvm_mmu_page, link);
2860         kvm_mmu_zap_page(kvm, page);
2861 }
2862
2863 static int mmu_shrink(int nr_to_scan, gfp_t gfp_mask)
2864 {
2865         struct kvm *kvm;
2866         struct kvm *kvm_freed = NULL;
2867         int cache_count = 0;
2868
2869         spin_lock(&kvm_lock);
2870
2871         list_for_each_entry(kvm, &vm_list, vm_list) {
2872                 int npages;
2873
2874                 if (!down_read_trylock(&kvm->slots_lock))
2875                         continue;
2876                 spin_lock(&kvm->mmu_lock);
2877                 npages = kvm->arch.n_alloc_mmu_pages -
2878                          kvm->arch.n_free_mmu_pages;
2879                 cache_count += npages;
2880                 if (!kvm_freed && nr_to_scan > 0 && npages > 0) {
2881                         kvm_mmu_remove_one_alloc_mmu_page(kvm);
2882                         cache_count--;
2883                         kvm_freed = kvm;
2884                 }
2885                 nr_to_scan--;
2886
2887                 spin_unlock(&kvm->mmu_lock);
2888                 up_read(&kvm->slots_lock);
2889         }
2890         if (kvm_freed)
2891                 list_move_tail(&kvm_freed->vm_list, &vm_list);
2892
2893         spin_unlock(&kvm_lock);
2894
2895         return cache_count;
2896 }
2897
2898 static struct shrinker mmu_shrinker = {
2899         .shrink = mmu_shrink,
2900         .seeks = DEFAULT_SEEKS * 10,
2901 };
2902
2903 static void mmu_destroy_caches(void)
2904 {
2905         if (pte_chain_cache)
2906                 kmem_cache_destroy(pte_chain_cache);
2907         if (rmap_desc_cache)
2908                 kmem_cache_destroy(rmap_desc_cache);
2909         if (mmu_page_header_cache)
2910                 kmem_cache_destroy(mmu_page_header_cache);
2911 }
2912
2913 void kvm_mmu_module_exit(void)
2914 {
2915         mmu_destroy_caches();
2916         unregister_shrinker(&mmu_shrinker);
2917 }
2918
2919 int kvm_mmu_module_init(void)
2920 {
2921         pte_chain_cache = kmem_cache_create("kvm_pte_chain",
2922                                             sizeof(struct kvm_pte_chain),
2923                                             0, 0, NULL);
2924         if (!pte_chain_cache)
2925                 goto nomem;
2926         rmap_desc_cache = kmem_cache_create("kvm_rmap_desc",
2927                                             sizeof(struct kvm_rmap_desc),
2928                                             0, 0, NULL);
2929         if (!rmap_desc_cache)
2930                 goto nomem;
2931
2932         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
2933                                                   sizeof(struct kvm_mmu_page),
2934                                                   0, 0, NULL);
2935         if (!mmu_page_header_cache)
2936                 goto nomem;
2937
2938         register_shrinker(&mmu_shrinker);
2939
2940         return 0;
2941
2942 nomem:
2943         mmu_destroy_caches();
2944         return -ENOMEM;
2945 }
2946
2947 /*
2948  * Caculate mmu pages needed for kvm.
2949  */
2950 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
2951 {
2952         int i;
2953         unsigned int nr_mmu_pages;
2954         unsigned int  nr_pages = 0;
2955
2956         for (i = 0; i < kvm->nmemslots; i++)
2957                 nr_pages += kvm->memslots[i].npages;
2958
2959         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
2960         nr_mmu_pages = max(nr_mmu_pages,
2961                         (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
2962
2963         return nr_mmu_pages;
2964 }
2965
2966 static void *pv_mmu_peek_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2967                                 unsigned len)
2968 {
2969         if (len > buffer->len)
2970                 return NULL;
2971         return buffer->ptr;
2972 }
2973
2974 static void *pv_mmu_read_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2975                                 unsigned len)
2976 {
2977         void *ret;
2978
2979         ret = pv_mmu_peek_buffer(buffer, len);
2980         if (!ret)
2981                 return ret;
2982         buffer->ptr += len;
2983         buffer->len -= len;
2984         buffer->processed += len;
2985         return ret;
2986 }
2987
2988 static int kvm_pv_mmu_write(struct kvm_vcpu *vcpu,
2989                              gpa_t addr, gpa_t value)
2990 {
2991         int bytes = 8;
2992         int r;
2993
2994         if (!is_long_mode(vcpu) && !is_pae(vcpu))
2995                 bytes = 4;
2996
2997         r = mmu_topup_memory_caches(vcpu);
2998         if (r)
2999                 return r;
3000
3001         if (!emulator_write_phys(vcpu, addr, &value, bytes))
3002                 return -EFAULT;
3003
3004         return 1;
3005 }
3006
3007 static int kvm_pv_mmu_flush_tlb(struct kvm_vcpu *vcpu)
3008 {
3009         kvm_set_cr3(vcpu, vcpu->arch.cr3);
3010         return 1;
3011 }
3012
3013 static int kvm_pv_mmu_release_pt(struct kvm_vcpu *vcpu, gpa_t addr)
3014 {
3015         spin_lock(&vcpu->kvm->mmu_lock);
3016         mmu_unshadow(vcpu->kvm, addr >> PAGE_SHIFT);
3017         spin_unlock(&vcpu->kvm->mmu_lock);
3018         return 1;
3019 }
3020
3021 static int kvm_pv_mmu_op_one(struct kvm_vcpu *vcpu,
3022                              struct kvm_pv_mmu_op_buffer *buffer)
3023 {
3024         struct kvm_mmu_op_header *header;
3025
3026         header = pv_mmu_peek_buffer(buffer, sizeof *header);
3027         if (!header)
3028                 return 0;
3029         switch (header->op) {
3030         case KVM_MMU_OP_WRITE_PTE: {
3031                 struct kvm_mmu_op_write_pte *wpte;
3032
3033                 wpte = pv_mmu_read_buffer(buffer, sizeof *wpte);
3034                 if (!wpte)
3035                         return 0;
3036                 return kvm_pv_mmu_write(vcpu, wpte->pte_phys,
3037                                         wpte->pte_val);
3038         }
3039         case KVM_MMU_OP_FLUSH_TLB: {
3040                 struct kvm_mmu_op_flush_tlb *ftlb;
3041
3042                 ftlb = pv_mmu_read_buffer(buffer, sizeof *ftlb);
3043                 if (!ftlb)
3044                         return 0;
3045                 return kvm_pv_mmu_flush_tlb(vcpu);
3046         }
3047         case KVM_MMU_OP_RELEASE_PT: {
3048                 struct kvm_mmu_op_release_pt *rpt;
3049
3050                 rpt = pv_mmu_read_buffer(buffer, sizeof *rpt);
3051                 if (!rpt)
3052                         return 0;
3053                 return kvm_pv_mmu_release_pt(vcpu, rpt->pt_phys);
3054         }
3055         default: return 0;
3056         }
3057 }
3058
3059 int kvm_pv_mmu_op(struct kvm_vcpu *vcpu, unsigned long bytes,
3060                   gpa_t addr, unsigned long *ret)
3061 {
3062         int r;
3063         struct kvm_pv_mmu_op_buffer *buffer = &vcpu->arch.mmu_op_buffer;
3064
3065         buffer->ptr = buffer->buf;
3066         buffer->len = min_t(unsigned long, bytes, sizeof buffer->buf);
3067         buffer->processed = 0;
3068
3069         r = kvm_read_guest(vcpu->kvm, addr, buffer->buf, buffer->len);
3070         if (r)
3071                 goto out;
3072
3073         while (buffer->len) {
3074                 r = kvm_pv_mmu_op_one(vcpu, buffer);
3075                 if (r < 0)
3076                         goto out;
3077                 if (r == 0)
3078                         break;
3079         }
3080
3081         r = 1;
3082 out:
3083         *ret = buffer->processed;
3084         return r;
3085 }
3086
3087 int kvm_mmu_get_spte_hierarchy(struct kvm_vcpu *vcpu, u64 addr, u64 sptes[4])
3088 {
3089         struct kvm_shadow_walk_iterator iterator;
3090         int nr_sptes = 0;
3091
3092         spin_lock(&vcpu->kvm->mmu_lock);
3093         for_each_shadow_entry(vcpu, addr, iterator) {
3094                 sptes[iterator.level-1] = *iterator.sptep;
3095                 nr_sptes++;
3096                 if (!is_shadow_present_pte(*iterator.sptep))
3097                         break;
3098         }
3099         spin_unlock(&vcpu->kvm->mmu_lock);
3100
3101         return nr_sptes;
3102 }
3103 EXPORT_SYMBOL_GPL(kvm_mmu_get_spte_hierarchy);
3104
3105 #ifdef AUDIT
3106
3107 static const char *audit_msg;
3108
3109 static gva_t canonicalize(gva_t gva)
3110 {
3111 #ifdef CONFIG_X86_64
3112         gva = (long long)(gva << 16) >> 16;
3113 #endif
3114         return gva;
3115 }
3116
3117
3118 typedef void (*inspect_spte_fn) (struct kvm *kvm, struct kvm_mmu_page *sp,
3119                                  u64 *sptep);
3120
3121 static void __mmu_spte_walk(struct kvm *kvm, struct kvm_mmu_page *sp,
3122                             inspect_spte_fn fn)
3123 {
3124         int i;
3125
3126         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3127                 u64 ent = sp->spt[i];
3128
3129                 if (is_shadow_present_pte(ent)) {
3130                         if (!is_last_spte(ent, sp->role.level)) {
3131                                 struct kvm_mmu_page *child;
3132                                 child = page_header(ent & PT64_BASE_ADDR_MASK);
3133                                 __mmu_spte_walk(kvm, child, fn);
3134                         } else
3135                                 fn(kvm, sp, &sp->spt[i]);
3136                 }
3137         }
3138 }
3139
3140 static void mmu_spte_walk(struct kvm_vcpu *vcpu, inspect_spte_fn fn)
3141 {
3142         int i;
3143         struct kvm_mmu_page *sp;
3144
3145         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3146                 return;
3147         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3148                 hpa_t root = vcpu->arch.mmu.root_hpa;
3149                 sp = page_header(root);
3150                 __mmu_spte_walk(vcpu->kvm, sp, fn);
3151                 return;
3152         }
3153         for (i = 0; i < 4; ++i) {
3154                 hpa_t root = vcpu->arch.mmu.pae_root[i];
3155
3156                 if (root && VALID_PAGE(root)) {
3157                         root &= PT64_BASE_ADDR_MASK;
3158                         sp = page_header(root);
3159                         __mmu_spte_walk(vcpu->kvm, sp, fn);
3160                 }
3161         }
3162         return;
3163 }
3164
3165 static void audit_mappings_page(struct kvm_vcpu *vcpu, u64 page_pte,
3166                                 gva_t va, int level)
3167 {
3168         u64 *pt = __va(page_pte & PT64_BASE_ADDR_MASK);
3169         int i;
3170         gva_t va_delta = 1ul << (PAGE_SHIFT + 9 * (level - 1));
3171
3172         for (i = 0; i < PT64_ENT_PER_PAGE; ++i, va += va_delta) {
3173                 u64 ent = pt[i];
3174
3175                 if (ent == shadow_trap_nonpresent_pte)
3176                         continue;
3177
3178                 va = canonicalize(va);
3179                 if (is_shadow_present_pte(ent) && !is_last_spte(ent, level))
3180                         audit_mappings_page(vcpu, ent, va, level - 1);
3181                 else {
3182                         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, va);
3183                         gfn_t gfn = gpa >> PAGE_SHIFT;
3184                         pfn_t pfn = gfn_to_pfn(vcpu->kvm, gfn);
3185                         hpa_t hpa = (hpa_t)pfn << PAGE_SHIFT;
3186
3187                         if (is_error_pfn(pfn)) {
3188                                 kvm_release_pfn_clean(pfn);
3189                                 continue;
3190                         }
3191
3192                         if (is_shadow_present_pte(ent)
3193                             && (ent & PT64_BASE_ADDR_MASK) != hpa)
3194                                 printk(KERN_ERR "xx audit error: (%s) levels %d"
3195                                        " gva %lx gpa %llx hpa %llx ent %llx %d\n",
3196                                        audit_msg, vcpu->arch.mmu.root_level,
3197                                        va, gpa, hpa, ent,
3198                                        is_shadow_present_pte(ent));
3199                         else if (ent == shadow_notrap_nonpresent_pte
3200                                  && !is_error_hpa(hpa))
3201                                 printk(KERN_ERR "audit: (%s) notrap shadow,"
3202                                        " valid guest gva %lx\n", audit_msg, va);
3203                         kvm_release_pfn_clean(pfn);
3204
3205                 }
3206         }
3207 }
3208
3209 static void audit_mappings(struct kvm_vcpu *vcpu)
3210 {
3211         unsigned i;
3212
3213         if (vcpu->arch.mmu.root_level == 4)
3214                 audit_mappings_page(vcpu, vcpu->arch.mmu.root_hpa, 0, 4);
3215         else
3216                 for (i = 0; i < 4; ++i)
3217                         if (vcpu->arch.mmu.pae_root[i] & PT_PRESENT_MASK)
3218                                 audit_mappings_page(vcpu,
3219                                                     vcpu->arch.mmu.pae_root[i],
3220                                                     i << 30,
3221                                                     2);
3222 }
3223
3224 static int count_rmaps(struct kvm_vcpu *vcpu)
3225 {
3226         int nmaps = 0;
3227         int i, j, k;
3228
3229         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
3230                 struct kvm_memory_slot *m = &vcpu->kvm->memslots[i];
3231                 struct kvm_rmap_desc *d;
3232
3233                 for (j = 0; j < m->npages; ++j) {
3234                         unsigned long *rmapp = &m->rmap[j];
3235
3236                         if (!*rmapp)
3237                                 continue;
3238                         if (!(*rmapp & 1)) {
3239                                 ++nmaps;
3240                                 continue;
3241                         }
3242                         d = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
3243                         while (d) {
3244                                 for (k = 0; k < RMAP_EXT; ++k)
3245                                         if (d->sptes[k])
3246                                                 ++nmaps;
3247                                         else
3248                                                 break;
3249                                 d = d->more;
3250                         }
3251                 }
3252         }
3253         return nmaps;
3254 }
3255
3256 void inspect_spte_has_rmap(struct kvm *kvm, struct kvm_mmu_page *sp, u64 *sptep)
3257 {
3258         unsigned long *rmapp;
3259         struct kvm_mmu_page *rev_sp;
3260         gfn_t gfn;
3261
3262         if (*sptep & PT_WRITABLE_MASK) {
3263                 rev_sp = page_header(__pa(sptep));
3264                 gfn = rev_sp->gfns[sptep - rev_sp->spt];
3265
3266                 if (!gfn_to_memslot(kvm, gfn)) {
3267                         if (!printk_ratelimit())
3268                                 return;
3269                         printk(KERN_ERR "%s: no memslot for gfn %ld\n",
3270                                          audit_msg, gfn);
3271                         printk(KERN_ERR "%s: index %ld of sp (gfn=%lx)\n",
3272                                         audit_msg, sptep - rev_sp->spt,
3273                                         rev_sp->gfn);
3274                         dump_stack();
3275                         return;
3276                 }
3277
3278                 rmapp = gfn_to_rmap(kvm, rev_sp->gfns[sptep - rev_sp->spt],
3279                                     is_large_pte(*sptep));
3280                 if (!*rmapp) {
3281                         if (!printk_ratelimit())
3282                                 return;
3283                         printk(KERN_ERR "%s: no rmap for writable spte %llx\n",
3284                                          audit_msg, *sptep);
3285                         dump_stack();
3286                 }
3287         }
3288
3289 }
3290
3291 void audit_writable_sptes_have_rmaps(struct kvm_vcpu *vcpu)
3292 {
3293         mmu_spte_walk(vcpu, inspect_spte_has_rmap);
3294 }
3295
3296 static void check_writable_mappings_rmap(struct kvm_vcpu *vcpu)
3297 {
3298         struct kvm_mmu_page *sp;
3299         int i;
3300
3301         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3302                 u64 *pt = sp->spt;
3303
3304                 if (sp->role.level != PT_PAGE_TABLE_LEVEL)
3305                         continue;
3306
3307                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3308                         u64 ent = pt[i];
3309
3310                         if (!(ent & PT_PRESENT_MASK))
3311                                 continue;
3312                         if (!(ent & PT_WRITABLE_MASK))
3313                                 continue;
3314                         inspect_spte_has_rmap(vcpu->kvm, sp, &pt[i]);
3315                 }
3316         }
3317         return;
3318 }
3319
3320 static void audit_rmap(struct kvm_vcpu *vcpu)
3321 {
3322         check_writable_mappings_rmap(vcpu);
3323         count_rmaps(vcpu);
3324 }
3325
3326 static void audit_write_protection(struct kvm_vcpu *vcpu)
3327 {
3328         struct kvm_mmu_page *sp;
3329         struct kvm_memory_slot *slot;
3330         unsigned long *rmapp;
3331         u64 *spte;
3332         gfn_t gfn;
3333
3334         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3335                 if (sp->role.direct)
3336                         continue;
3337                 if (sp->unsync)
3338                         continue;
3339
3340                 gfn = unalias_gfn(vcpu->kvm, sp->gfn);
3341                 slot = gfn_to_memslot_unaliased(vcpu->kvm, sp->gfn);
3342                 rmapp = &slot->rmap[gfn - slot->base_gfn];
3343
3344                 spte = rmap_next(vcpu->kvm, rmapp, NULL);
3345                 while (spte) {
3346                         if (*spte & PT_WRITABLE_MASK)
3347                                 printk(KERN_ERR "%s: (%s) shadow page has "
3348                                 "writable mappings: gfn %lx role %x\n",
3349                                __func__, audit_msg, sp->gfn,
3350                                sp->role.word);
3351                         spte = rmap_next(vcpu->kvm, rmapp, spte);
3352                 }
3353         }
3354 }
3355
3356 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg)
3357 {
3358         int olddbg = dbg;
3359
3360         dbg = 0;
3361         audit_msg = msg;
3362         audit_rmap(vcpu);
3363         audit_write_protection(vcpu);
3364         if (strcmp("pre pte write", audit_msg) != 0)
3365                 audit_mappings(vcpu);
3366         audit_writable_sptes_have_rmaps(vcpu);
3367         dbg = olddbg;
3368 }
3369
3370 #endif