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