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