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