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