Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/penberg...
[linux-2.6] / arch / x86 / kvm / mmu.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * MMU support
8  *
9  * Copyright (C) 2006 Qumranet, Inc.
10  *
11  * Authors:
12  *   Yaniv Kamay  <yaniv@qumranet.com>
13  *   Avi Kivity   <avi@qumranet.com>
14  *
15  * This work is licensed under the terms of the GNU GPL, version 2.  See
16  * the COPYING file in the top-level directory.
17  *
18  */
19
20 #include "vmx.h"
21 #include "mmu.h"
22
23 #include <linux/kvm_host.h>
24 #include <linux/types.h>
25 #include <linux/string.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/module.h>
29 #include <linux/swap.h>
30 #include <linux/hugetlb.h>
31 #include <linux/compiler.h>
32
33 #include <asm/page.h>
34 #include <asm/cmpxchg.h>
35 #include <asm/io.h>
36
37 /*
38  * When setting this variable to true it enables Two-Dimensional-Paging
39  * where the hardware walks 2 page tables:
40  * 1. the guest-virtual to guest-physical
41  * 2. while doing 1. it walks guest-physical to host-physical
42  * If the hardware supports that we don't need to do shadow paging.
43  */
44 bool tdp_enabled = false;
45
46 #undef MMU_DEBUG
47
48 #undef AUDIT
49
50 #ifdef AUDIT
51 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg);
52 #else
53 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg) {}
54 #endif
55
56 #ifdef MMU_DEBUG
57
58 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
59 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
60
61 #else
62
63 #define pgprintk(x...) do { } while (0)
64 #define rmap_printk(x...) do { } while (0)
65
66 #endif
67
68 #if defined(MMU_DEBUG) || defined(AUDIT)
69 static int dbg = 1;
70 #endif
71
72 #ifndef MMU_DEBUG
73 #define ASSERT(x) do { } while (0)
74 #else
75 #define ASSERT(x)                                                       \
76         if (!(x)) {                                                     \
77                 printk(KERN_WARNING "assertion failed %s:%d: %s\n",     \
78                        __FILE__, __LINE__, #x);                         \
79         }
80 #endif
81
82 #define PT64_PT_BITS 9
83 #define PT64_ENT_PER_PAGE (1 << PT64_PT_BITS)
84 #define PT32_PT_BITS 10
85 #define PT32_ENT_PER_PAGE (1 << PT32_PT_BITS)
86
87 #define PT_WRITABLE_SHIFT 1
88
89 #define PT_PRESENT_MASK (1ULL << 0)
90 #define PT_WRITABLE_MASK (1ULL << PT_WRITABLE_SHIFT)
91 #define PT_USER_MASK (1ULL << 2)
92 #define PT_PWT_MASK (1ULL << 3)
93 #define PT_PCD_MASK (1ULL << 4)
94 #define PT_ACCESSED_MASK (1ULL << 5)
95 #define PT_DIRTY_MASK (1ULL << 6)
96 #define PT_PAGE_SIZE_MASK (1ULL << 7)
97 #define PT_PAT_MASK (1ULL << 7)
98 #define PT_GLOBAL_MASK (1ULL << 8)
99 #define PT64_NX_SHIFT 63
100 #define PT64_NX_MASK (1ULL << PT64_NX_SHIFT)
101
102 #define PT_PAT_SHIFT 7
103 #define PT_DIR_PAT_SHIFT 12
104 #define PT_DIR_PAT_MASK (1ULL << PT_DIR_PAT_SHIFT)
105
106 #define PT32_DIR_PSE36_SIZE 4
107 #define PT32_DIR_PSE36_SHIFT 13
108 #define PT32_DIR_PSE36_MASK \
109         (((1ULL << PT32_DIR_PSE36_SIZE) - 1) << PT32_DIR_PSE36_SHIFT)
110
111
112 #define PT_FIRST_AVAIL_BITS_SHIFT 9
113 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
114
115 #define VALID_PAGE(x) ((x) != INVALID_PAGE)
116
117 #define PT64_LEVEL_BITS 9
118
119 #define PT64_LEVEL_SHIFT(level) \
120                 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
121
122 #define PT64_LEVEL_MASK(level) \
123                 (((1ULL << PT64_LEVEL_BITS) - 1) << PT64_LEVEL_SHIFT(level))
124
125 #define PT64_INDEX(address, level)\
126         (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
127
128
129 #define PT32_LEVEL_BITS 10
130
131 #define PT32_LEVEL_SHIFT(level) \
132                 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
133
134 #define PT32_LEVEL_MASK(level) \
135                 (((1ULL << PT32_LEVEL_BITS) - 1) << PT32_LEVEL_SHIFT(level))
136
137 #define PT32_INDEX(address, level)\
138         (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
139
140
141 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
142 #define PT64_DIR_BASE_ADDR_MASK \
143         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
144
145 #define PT32_BASE_ADDR_MASK PAGE_MASK
146 #define PT32_DIR_BASE_ADDR_MASK \
147         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
148
149 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK \
150                         | PT64_NX_MASK)
151
152 #define PFERR_PRESENT_MASK (1U << 0)
153 #define PFERR_WRITE_MASK (1U << 1)
154 #define PFERR_USER_MASK (1U << 2)
155 #define PFERR_FETCH_MASK (1U << 4)
156
157 #define PT64_ROOT_LEVEL 4
158 #define PT32_ROOT_LEVEL 2
159 #define PT32E_ROOT_LEVEL 3
160
161 #define PT_DIRECTORY_LEVEL 2
162 #define PT_PAGE_TABLE_LEVEL 1
163
164 #define RMAP_EXT 4
165
166 #define ACC_EXEC_MASK    1
167 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
168 #define ACC_USER_MASK    PT_USER_MASK
169 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
170
171 struct kvm_pv_mmu_op_buffer {
172         void *ptr;
173         unsigned len;
174         unsigned processed;
175         char buf[512] __aligned(sizeof(long));
176 };
177
178 struct kvm_rmap_desc {
179         u64 *shadow_ptes[RMAP_EXT];
180         struct kvm_rmap_desc *more;
181 };
182
183 static struct kmem_cache *pte_chain_cache;
184 static struct kmem_cache *rmap_desc_cache;
185 static struct kmem_cache *mmu_page_header_cache;
186
187 static u64 __read_mostly shadow_trap_nonpresent_pte;
188 static u64 __read_mostly shadow_notrap_nonpresent_pte;
189
190 void kvm_mmu_set_nonpresent_ptes(u64 trap_pte, u64 notrap_pte)
191 {
192         shadow_trap_nonpresent_pte = trap_pte;
193         shadow_notrap_nonpresent_pte = notrap_pte;
194 }
195 EXPORT_SYMBOL_GPL(kvm_mmu_set_nonpresent_ptes);
196
197 static int is_write_protection(struct kvm_vcpu *vcpu)
198 {
199         return vcpu->arch.cr0 & X86_CR0_WP;
200 }
201
202 static int is_cpuid_PSE36(void)
203 {
204         return 1;
205 }
206
207 static int is_nx(struct kvm_vcpu *vcpu)
208 {
209         return vcpu->arch.shadow_efer & EFER_NX;
210 }
211
212 static int is_present_pte(unsigned long pte)
213 {
214         return pte & PT_PRESENT_MASK;
215 }
216
217 static int is_shadow_present_pte(u64 pte)
218 {
219         return pte != shadow_trap_nonpresent_pte
220                 && pte != shadow_notrap_nonpresent_pte;
221 }
222
223 static int is_large_pte(u64 pte)
224 {
225         return pte & PT_PAGE_SIZE_MASK;
226 }
227
228 static int is_writeble_pte(unsigned long pte)
229 {
230         return pte & PT_WRITABLE_MASK;
231 }
232
233 static int is_dirty_pte(unsigned long pte)
234 {
235         return pte & PT_DIRTY_MASK;
236 }
237
238 static int is_rmap_pte(u64 pte)
239 {
240         return is_shadow_present_pte(pte);
241 }
242
243 static pfn_t spte_to_pfn(u64 pte)
244 {
245         return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
246 }
247
248 static gfn_t pse36_gfn_delta(u32 gpte)
249 {
250         int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
251
252         return (gpte & PT32_DIR_PSE36_MASK) << shift;
253 }
254
255 static void set_shadow_pte(u64 *sptep, u64 spte)
256 {
257 #ifdef CONFIG_X86_64
258         set_64bit((unsigned long *)sptep, spte);
259 #else
260         set_64bit((unsigned long long *)sptep, spte);
261 #endif
262 }
263
264 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
265                                   struct kmem_cache *base_cache, int min)
266 {
267         void *obj;
268
269         if (cache->nobjs >= min)
270                 return 0;
271         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
272                 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
273                 if (!obj)
274                         return -ENOMEM;
275                 cache->objects[cache->nobjs++] = obj;
276         }
277         return 0;
278 }
279
280 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
281 {
282         while (mc->nobjs)
283                 kfree(mc->objects[--mc->nobjs]);
284 }
285
286 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
287                                        int min)
288 {
289         struct page *page;
290
291         if (cache->nobjs >= min)
292                 return 0;
293         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
294                 page = alloc_page(GFP_KERNEL);
295                 if (!page)
296                         return -ENOMEM;
297                 set_page_private(page, 0);
298                 cache->objects[cache->nobjs++] = page_address(page);
299         }
300         return 0;
301 }
302
303 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
304 {
305         while (mc->nobjs)
306                 free_page((unsigned long)mc->objects[--mc->nobjs]);
307 }
308
309 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
310 {
311         int r;
312
313         r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_chain_cache,
314                                    pte_chain_cache, 4);
315         if (r)
316                 goto out;
317         r = mmu_topup_memory_cache(&vcpu->arch.mmu_rmap_desc_cache,
318                                    rmap_desc_cache, 1);
319         if (r)
320                 goto out;
321         r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
322         if (r)
323                 goto out;
324         r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
325                                    mmu_page_header_cache, 4);
326 out:
327         return r;
328 }
329
330 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
331 {
332         mmu_free_memory_cache(&vcpu->arch.mmu_pte_chain_cache);
333         mmu_free_memory_cache(&vcpu->arch.mmu_rmap_desc_cache);
334         mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
335         mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
336 }
337
338 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc,
339                                     size_t size)
340 {
341         void *p;
342
343         BUG_ON(!mc->nobjs);
344         p = mc->objects[--mc->nobjs];
345         memset(p, 0, size);
346         return p;
347 }
348
349 static struct kvm_pte_chain *mmu_alloc_pte_chain(struct kvm_vcpu *vcpu)
350 {
351         return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_chain_cache,
352                                       sizeof(struct kvm_pte_chain));
353 }
354
355 static void mmu_free_pte_chain(struct kvm_pte_chain *pc)
356 {
357         kfree(pc);
358 }
359
360 static struct kvm_rmap_desc *mmu_alloc_rmap_desc(struct kvm_vcpu *vcpu)
361 {
362         return mmu_memory_cache_alloc(&vcpu->arch.mmu_rmap_desc_cache,
363                                       sizeof(struct kvm_rmap_desc));
364 }
365
366 static void mmu_free_rmap_desc(struct kvm_rmap_desc *rd)
367 {
368         kfree(rd);
369 }
370
371 /*
372  * Return the pointer to the largepage write count for a given
373  * gfn, handling slots that are not large page aligned.
374  */
375 static int *slot_largepage_idx(gfn_t gfn, struct kvm_memory_slot *slot)
376 {
377         unsigned long idx;
378
379         idx = (gfn / KVM_PAGES_PER_HPAGE) -
380               (slot->base_gfn / KVM_PAGES_PER_HPAGE);
381         return &slot->lpage_info[idx].write_count;
382 }
383
384 static void account_shadowed(struct kvm *kvm, gfn_t gfn)
385 {
386         int *write_count;
387
388         write_count = slot_largepage_idx(gfn, gfn_to_memslot(kvm, gfn));
389         *write_count += 1;
390         WARN_ON(*write_count > KVM_PAGES_PER_HPAGE);
391 }
392
393 static void unaccount_shadowed(struct kvm *kvm, gfn_t gfn)
394 {
395         int *write_count;
396
397         write_count = slot_largepage_idx(gfn, gfn_to_memslot(kvm, gfn));
398         *write_count -= 1;
399         WARN_ON(*write_count < 0);
400 }
401
402 static int has_wrprotected_page(struct kvm *kvm, gfn_t gfn)
403 {
404         struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
405         int *largepage_idx;
406
407         if (slot) {
408                 largepage_idx = slot_largepage_idx(gfn, slot);
409                 return *largepage_idx;
410         }
411
412         return 1;
413 }
414
415 static int host_largepage_backed(struct kvm *kvm, gfn_t gfn)
416 {
417         struct vm_area_struct *vma;
418         unsigned long addr;
419
420         addr = gfn_to_hva(kvm, gfn);
421         if (kvm_is_error_hva(addr))
422                 return 0;
423
424         vma = find_vma(current->mm, addr);
425         if (vma && is_vm_hugetlb_page(vma))
426                 return 1;
427
428         return 0;
429 }
430
431 static int is_largepage_backed(struct kvm_vcpu *vcpu, gfn_t large_gfn)
432 {
433         struct kvm_memory_slot *slot;
434
435         if (has_wrprotected_page(vcpu->kvm, large_gfn))
436                 return 0;
437
438         if (!host_largepage_backed(vcpu->kvm, large_gfn))
439                 return 0;
440
441         slot = gfn_to_memslot(vcpu->kvm, large_gfn);
442         if (slot && slot->dirty_bitmap)
443                 return 0;
444
445         return 1;
446 }
447
448 /*
449  * Take gfn and return the reverse mapping to it.
450  * Note: gfn must be unaliased before this function get called
451  */
452
453 static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn, int lpage)
454 {
455         struct kvm_memory_slot *slot;
456         unsigned long idx;
457
458         slot = gfn_to_memslot(kvm, gfn);
459         if (!lpage)
460                 return &slot->rmap[gfn - slot->base_gfn];
461
462         idx = (gfn / KVM_PAGES_PER_HPAGE) -
463               (slot->base_gfn / KVM_PAGES_PER_HPAGE);
464
465         return &slot->lpage_info[idx].rmap_pde;
466 }
467
468 /*
469  * Reverse mapping data structures:
470  *
471  * If rmapp bit zero is zero, then rmapp point to the shadw page table entry
472  * that points to page_address(page).
473  *
474  * If rmapp bit zero is one, (then rmap & ~1) points to a struct kvm_rmap_desc
475  * containing more mappings.
476  */
477 static void rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn, int lpage)
478 {
479         struct kvm_mmu_page *sp;
480         struct kvm_rmap_desc *desc;
481         unsigned long *rmapp;
482         int i;
483
484         if (!is_rmap_pte(*spte))
485                 return;
486         gfn = unalias_gfn(vcpu->kvm, gfn);
487         sp = page_header(__pa(spte));
488         sp->gfns[spte - sp->spt] = gfn;
489         rmapp = gfn_to_rmap(vcpu->kvm, gfn, lpage);
490         if (!*rmapp) {
491                 rmap_printk("rmap_add: %p %llx 0->1\n", spte, *spte);
492                 *rmapp = (unsigned long)spte;
493         } else if (!(*rmapp & 1)) {
494                 rmap_printk("rmap_add: %p %llx 1->many\n", spte, *spte);
495                 desc = mmu_alloc_rmap_desc(vcpu);
496                 desc->shadow_ptes[0] = (u64 *)*rmapp;
497                 desc->shadow_ptes[1] = spte;
498                 *rmapp = (unsigned long)desc | 1;
499         } else {
500                 rmap_printk("rmap_add: %p %llx many->many\n", spte, *spte);
501                 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
502                 while (desc->shadow_ptes[RMAP_EXT-1] && desc->more)
503                         desc = desc->more;
504                 if (desc->shadow_ptes[RMAP_EXT-1]) {
505                         desc->more = mmu_alloc_rmap_desc(vcpu);
506                         desc = desc->more;
507                 }
508                 for (i = 0; desc->shadow_ptes[i]; ++i)
509                         ;
510                 desc->shadow_ptes[i] = spte;
511         }
512 }
513
514 static void rmap_desc_remove_entry(unsigned long *rmapp,
515                                    struct kvm_rmap_desc *desc,
516                                    int i,
517                                    struct kvm_rmap_desc *prev_desc)
518 {
519         int j;
520
521         for (j = RMAP_EXT - 1; !desc->shadow_ptes[j] && j > i; --j)
522                 ;
523         desc->shadow_ptes[i] = desc->shadow_ptes[j];
524         desc->shadow_ptes[j] = NULL;
525         if (j != 0)
526                 return;
527         if (!prev_desc && !desc->more)
528                 *rmapp = (unsigned long)desc->shadow_ptes[0];
529         else
530                 if (prev_desc)
531                         prev_desc->more = desc->more;
532                 else
533                         *rmapp = (unsigned long)desc->more | 1;
534         mmu_free_rmap_desc(desc);
535 }
536
537 static void rmap_remove(struct kvm *kvm, u64 *spte)
538 {
539         struct kvm_rmap_desc *desc;
540         struct kvm_rmap_desc *prev_desc;
541         struct kvm_mmu_page *sp;
542         pfn_t pfn;
543         unsigned long *rmapp;
544         int i;
545
546         if (!is_rmap_pte(*spte))
547                 return;
548         sp = page_header(__pa(spte));
549         pfn = spte_to_pfn(*spte);
550         if (*spte & PT_ACCESSED_MASK)
551                 kvm_set_pfn_accessed(pfn);
552         if (is_writeble_pte(*spte))
553                 kvm_release_pfn_dirty(pfn);
554         else
555                 kvm_release_pfn_clean(pfn);
556         rmapp = gfn_to_rmap(kvm, sp->gfns[spte - sp->spt], is_large_pte(*spte));
557         if (!*rmapp) {
558                 printk(KERN_ERR "rmap_remove: %p %llx 0->BUG\n", spte, *spte);
559                 BUG();
560         } else if (!(*rmapp & 1)) {
561                 rmap_printk("rmap_remove:  %p %llx 1->0\n", spte, *spte);
562                 if ((u64 *)*rmapp != spte) {
563                         printk(KERN_ERR "rmap_remove:  %p %llx 1->BUG\n",
564                                spte, *spte);
565                         BUG();
566                 }
567                 *rmapp = 0;
568         } else {
569                 rmap_printk("rmap_remove:  %p %llx many->many\n", spte, *spte);
570                 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
571                 prev_desc = NULL;
572                 while (desc) {
573                         for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i)
574                                 if (desc->shadow_ptes[i] == spte) {
575                                         rmap_desc_remove_entry(rmapp,
576                                                                desc, i,
577                                                                prev_desc);
578                                         return;
579                                 }
580                         prev_desc = desc;
581                         desc = desc->more;
582                 }
583                 BUG();
584         }
585 }
586
587 static u64 *rmap_next(struct kvm *kvm, unsigned long *rmapp, u64 *spte)
588 {
589         struct kvm_rmap_desc *desc;
590         struct kvm_rmap_desc *prev_desc;
591         u64 *prev_spte;
592         int i;
593
594         if (!*rmapp)
595                 return NULL;
596         else if (!(*rmapp & 1)) {
597                 if (!spte)
598                         return (u64 *)*rmapp;
599                 return NULL;
600         }
601         desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
602         prev_desc = NULL;
603         prev_spte = NULL;
604         while (desc) {
605                 for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i) {
606                         if (prev_spte == spte)
607                                 return desc->shadow_ptes[i];
608                         prev_spte = desc->shadow_ptes[i];
609                 }
610                 desc = desc->more;
611         }
612         return NULL;
613 }
614
615 static void rmap_write_protect(struct kvm *kvm, u64 gfn)
616 {
617         unsigned long *rmapp;
618         u64 *spte;
619         int write_protected = 0;
620
621         gfn = unalias_gfn(kvm, gfn);
622         rmapp = gfn_to_rmap(kvm, gfn, 0);
623
624         spte = rmap_next(kvm, rmapp, NULL);
625         while (spte) {
626                 BUG_ON(!spte);
627                 BUG_ON(!(*spte & PT_PRESENT_MASK));
628                 rmap_printk("rmap_write_protect: spte %p %llx\n", spte, *spte);
629                 if (is_writeble_pte(*spte)) {
630                         set_shadow_pte(spte, *spte & ~PT_WRITABLE_MASK);
631                         write_protected = 1;
632                 }
633                 spte = rmap_next(kvm, rmapp, spte);
634         }
635         if (write_protected) {
636                 pfn_t pfn;
637
638                 spte = rmap_next(kvm, rmapp, NULL);
639                 pfn = spte_to_pfn(*spte);
640                 kvm_set_pfn_dirty(pfn);
641         }
642
643         /* check for huge page mappings */
644         rmapp = gfn_to_rmap(kvm, gfn, 1);
645         spte = rmap_next(kvm, rmapp, NULL);
646         while (spte) {
647                 BUG_ON(!spte);
648                 BUG_ON(!(*spte & PT_PRESENT_MASK));
649                 BUG_ON((*spte & (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK)) != (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK));
650                 pgprintk("rmap_write_protect(large): spte %p %llx %lld\n", spte, *spte, gfn);
651                 if (is_writeble_pte(*spte)) {
652                         rmap_remove(kvm, spte);
653                         --kvm->stat.lpages;
654                         set_shadow_pte(spte, shadow_trap_nonpresent_pte);
655                         write_protected = 1;
656                 }
657                 spte = rmap_next(kvm, rmapp, spte);
658         }
659
660         if (write_protected)
661                 kvm_flush_remote_tlbs(kvm);
662
663         account_shadowed(kvm, gfn);
664 }
665
666 #ifdef MMU_DEBUG
667 static int is_empty_shadow_page(u64 *spt)
668 {
669         u64 *pos;
670         u64 *end;
671
672         for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
673                 if (*pos != shadow_trap_nonpresent_pte) {
674                         printk(KERN_ERR "%s: %p %llx\n", __func__,
675                                pos, *pos);
676                         return 0;
677                 }
678         return 1;
679 }
680 #endif
681
682 static void kvm_mmu_free_page(struct kvm *kvm, struct kvm_mmu_page *sp)
683 {
684         ASSERT(is_empty_shadow_page(sp->spt));
685         list_del(&sp->link);
686         __free_page(virt_to_page(sp->spt));
687         __free_page(virt_to_page(sp->gfns));
688         kfree(sp);
689         ++kvm->arch.n_free_mmu_pages;
690 }
691
692 static unsigned kvm_page_table_hashfn(gfn_t gfn)
693 {
694         return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
695 }
696
697 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
698                                                u64 *parent_pte)
699 {
700         struct kvm_mmu_page *sp;
701
702         sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache, sizeof *sp);
703         sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
704         sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
705         set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
706         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
707         ASSERT(is_empty_shadow_page(sp->spt));
708         sp->slot_bitmap = 0;
709         sp->multimapped = 0;
710         sp->parent_pte = parent_pte;
711         --vcpu->kvm->arch.n_free_mmu_pages;
712         return sp;
713 }
714
715 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
716                                     struct kvm_mmu_page *sp, u64 *parent_pte)
717 {
718         struct kvm_pte_chain *pte_chain;
719         struct hlist_node *node;
720         int i;
721
722         if (!parent_pte)
723                 return;
724         if (!sp->multimapped) {
725                 u64 *old = sp->parent_pte;
726
727                 if (!old) {
728                         sp->parent_pte = parent_pte;
729                         return;
730                 }
731                 sp->multimapped = 1;
732                 pte_chain = mmu_alloc_pte_chain(vcpu);
733                 INIT_HLIST_HEAD(&sp->parent_ptes);
734                 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
735                 pte_chain->parent_ptes[0] = old;
736         }
737         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link) {
738                 if (pte_chain->parent_ptes[NR_PTE_CHAIN_ENTRIES-1])
739                         continue;
740                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i)
741                         if (!pte_chain->parent_ptes[i]) {
742                                 pte_chain->parent_ptes[i] = parent_pte;
743                                 return;
744                         }
745         }
746         pte_chain = mmu_alloc_pte_chain(vcpu);
747         BUG_ON(!pte_chain);
748         hlist_add_head(&pte_chain->link, &sp->parent_ptes);
749         pte_chain->parent_ptes[0] = parent_pte;
750 }
751
752 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
753                                        u64 *parent_pte)
754 {
755         struct kvm_pte_chain *pte_chain;
756         struct hlist_node *node;
757         int i;
758
759         if (!sp->multimapped) {
760                 BUG_ON(sp->parent_pte != parent_pte);
761                 sp->parent_pte = NULL;
762                 return;
763         }
764         hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
765                 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
766                         if (!pte_chain->parent_ptes[i])
767                                 break;
768                         if (pte_chain->parent_ptes[i] != parent_pte)
769                                 continue;
770                         while (i + 1 < NR_PTE_CHAIN_ENTRIES
771                                 && pte_chain->parent_ptes[i + 1]) {
772                                 pte_chain->parent_ptes[i]
773                                         = pte_chain->parent_ptes[i + 1];
774                                 ++i;
775                         }
776                         pte_chain->parent_ptes[i] = NULL;
777                         if (i == 0) {
778                                 hlist_del(&pte_chain->link);
779                                 mmu_free_pte_chain(pte_chain);
780                                 if (hlist_empty(&sp->parent_ptes)) {
781                                         sp->multimapped = 0;
782                                         sp->parent_pte = NULL;
783                                 }
784                         }
785                         return;
786                 }
787         BUG();
788 }
789
790 static struct kvm_mmu_page *kvm_mmu_lookup_page(struct kvm *kvm, gfn_t gfn)
791 {
792         unsigned index;
793         struct hlist_head *bucket;
794         struct kvm_mmu_page *sp;
795         struct hlist_node *node;
796
797         pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
798         index = kvm_page_table_hashfn(gfn);
799         bucket = &kvm->arch.mmu_page_hash[index];
800         hlist_for_each_entry(sp, node, bucket, hash_link)
801                 if (sp->gfn == gfn && !sp->role.metaphysical
802                     && !sp->role.invalid) {
803                         pgprintk("%s: found role %x\n",
804                                  __func__, sp->role.word);
805                         return sp;
806                 }
807         return NULL;
808 }
809
810 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
811                                              gfn_t gfn,
812                                              gva_t gaddr,
813                                              unsigned level,
814                                              int metaphysical,
815                                              unsigned access,
816                                              u64 *parent_pte)
817 {
818         union kvm_mmu_page_role role;
819         unsigned index;
820         unsigned quadrant;
821         struct hlist_head *bucket;
822         struct kvm_mmu_page *sp;
823         struct hlist_node *node;
824
825         role.word = 0;
826         role.glevels = vcpu->arch.mmu.root_level;
827         role.level = level;
828         role.metaphysical = metaphysical;
829         role.access = access;
830         if (vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
831                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
832                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
833                 role.quadrant = quadrant;
834         }
835         pgprintk("%s: looking gfn %lx role %x\n", __func__,
836                  gfn, role.word);
837         index = kvm_page_table_hashfn(gfn);
838         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
839         hlist_for_each_entry(sp, node, bucket, hash_link)
840                 if (sp->gfn == gfn && sp->role.word == role.word) {
841                         mmu_page_add_parent_pte(vcpu, sp, parent_pte);
842                         pgprintk("%s: found\n", __func__);
843                         return sp;
844                 }
845         ++vcpu->kvm->stat.mmu_cache_miss;
846         sp = kvm_mmu_alloc_page(vcpu, parent_pte);
847         if (!sp)
848                 return sp;
849         pgprintk("%s: adding gfn %lx role %x\n", __func__, gfn, role.word);
850         sp->gfn = gfn;
851         sp->role = role;
852         hlist_add_head(&sp->hash_link, bucket);
853         if (!metaphysical)
854                 rmap_write_protect(vcpu->kvm, gfn);
855         vcpu->arch.mmu.prefetch_page(vcpu, sp);
856         return sp;
857 }
858
859 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
860                                          struct kvm_mmu_page *sp)
861 {
862         unsigned i;
863         u64 *pt;
864         u64 ent;
865
866         pt = sp->spt;
867
868         if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
869                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
870                         if (is_shadow_present_pte(pt[i]))
871                                 rmap_remove(kvm, &pt[i]);
872                         pt[i] = shadow_trap_nonpresent_pte;
873                 }
874                 kvm_flush_remote_tlbs(kvm);
875                 return;
876         }
877
878         for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
879                 ent = pt[i];
880
881                 if (is_shadow_present_pte(ent)) {
882                         if (!is_large_pte(ent)) {
883                                 ent &= PT64_BASE_ADDR_MASK;
884                                 mmu_page_remove_parent_pte(page_header(ent),
885                                                            &pt[i]);
886                         } else {
887                                 --kvm->stat.lpages;
888                                 rmap_remove(kvm, &pt[i]);
889                         }
890                 }
891                 pt[i] = shadow_trap_nonpresent_pte;
892         }
893         kvm_flush_remote_tlbs(kvm);
894 }
895
896 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
897 {
898         mmu_page_remove_parent_pte(sp, parent_pte);
899 }
900
901 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
902 {
903         int i;
904
905         for (i = 0; i < KVM_MAX_VCPUS; ++i)
906                 if (kvm->vcpus[i])
907                         kvm->vcpus[i]->arch.last_pte_updated = NULL;
908 }
909
910 static void kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp)
911 {
912         u64 *parent_pte;
913
914         ++kvm->stat.mmu_shadow_zapped;
915         while (sp->multimapped || sp->parent_pte) {
916                 if (!sp->multimapped)
917                         parent_pte = sp->parent_pte;
918                 else {
919                         struct kvm_pte_chain *chain;
920
921                         chain = container_of(sp->parent_ptes.first,
922                                              struct kvm_pte_chain, link);
923                         parent_pte = chain->parent_ptes[0];
924                 }
925                 BUG_ON(!parent_pte);
926                 kvm_mmu_put_page(sp, parent_pte);
927                 set_shadow_pte(parent_pte, shadow_trap_nonpresent_pte);
928         }
929         kvm_mmu_page_unlink_children(kvm, sp);
930         if (!sp->root_count) {
931                 if (!sp->role.metaphysical)
932                         unaccount_shadowed(kvm, sp->gfn);
933                 hlist_del(&sp->hash_link);
934                 kvm_mmu_free_page(kvm, sp);
935         } else {
936                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
937                 sp->role.invalid = 1;
938                 kvm_reload_remote_mmus(kvm);
939         }
940         kvm_mmu_reset_last_pte_updated(kvm);
941 }
942
943 /*
944  * Changing the number of mmu pages allocated to the vm
945  * Note: if kvm_nr_mmu_pages is too small, you will get dead lock
946  */
947 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int kvm_nr_mmu_pages)
948 {
949         /*
950          * If we set the number of mmu pages to be smaller be than the
951          * number of actived pages , we must to free some mmu pages before we
952          * change the value
953          */
954
955         if ((kvm->arch.n_alloc_mmu_pages - kvm->arch.n_free_mmu_pages) >
956             kvm_nr_mmu_pages) {
957                 int n_used_mmu_pages = kvm->arch.n_alloc_mmu_pages
958                                        - kvm->arch.n_free_mmu_pages;
959
960                 while (n_used_mmu_pages > kvm_nr_mmu_pages) {
961                         struct kvm_mmu_page *page;
962
963                         page = container_of(kvm->arch.active_mmu_pages.prev,
964                                             struct kvm_mmu_page, link);
965                         kvm_mmu_zap_page(kvm, page);
966                         n_used_mmu_pages--;
967                 }
968                 kvm->arch.n_free_mmu_pages = 0;
969         }
970         else
971                 kvm->arch.n_free_mmu_pages += kvm_nr_mmu_pages
972                                          - kvm->arch.n_alloc_mmu_pages;
973
974         kvm->arch.n_alloc_mmu_pages = kvm_nr_mmu_pages;
975 }
976
977 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
978 {
979         unsigned index;
980         struct hlist_head *bucket;
981         struct kvm_mmu_page *sp;
982         struct hlist_node *node, *n;
983         int r;
984
985         pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
986         r = 0;
987         index = kvm_page_table_hashfn(gfn);
988         bucket = &kvm->arch.mmu_page_hash[index];
989         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link)
990                 if (sp->gfn == gfn && !sp->role.metaphysical) {
991                         pgprintk("%s: gfn %lx role %x\n", __func__, gfn,
992                                  sp->role.word);
993                         kvm_mmu_zap_page(kvm, sp);
994                         r = 1;
995                 }
996         return r;
997 }
998
999 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
1000 {
1001         struct kvm_mmu_page *sp;
1002
1003         while ((sp = kvm_mmu_lookup_page(kvm, gfn)) != NULL) {
1004                 pgprintk("%s: zap %lx %x\n", __func__, gfn, sp->role.word);
1005                 kvm_mmu_zap_page(kvm, sp);
1006         }
1007 }
1008
1009 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
1010 {
1011         int slot = memslot_id(kvm, gfn_to_memslot(kvm, gfn));
1012         struct kvm_mmu_page *sp = page_header(__pa(pte));
1013
1014         __set_bit(slot, &sp->slot_bitmap);
1015 }
1016
1017 struct page *gva_to_page(struct kvm_vcpu *vcpu, gva_t gva)
1018 {
1019         struct page *page;
1020
1021         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1022
1023         if (gpa == UNMAPPED_GVA)
1024                 return NULL;
1025
1026         down_read(&current->mm->mmap_sem);
1027         page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1028         up_read(&current->mm->mmap_sem);
1029
1030         return page;
1031 }
1032
1033 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
1034                          unsigned pt_access, unsigned pte_access,
1035                          int user_fault, int write_fault, int dirty,
1036                          int *ptwrite, int largepage, gfn_t gfn,
1037                          pfn_t pfn, bool speculative)
1038 {
1039         u64 spte;
1040         int was_rmapped = 0;
1041         int was_writeble = is_writeble_pte(*shadow_pte);
1042
1043         pgprintk("%s: spte %llx access %x write_fault %d"
1044                  " user_fault %d gfn %lx\n",
1045                  __func__, *shadow_pte, pt_access,
1046                  write_fault, user_fault, gfn);
1047
1048         if (is_rmap_pte(*shadow_pte)) {
1049                 /*
1050                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
1051                  * the parent of the now unreachable PTE.
1052                  */
1053                 if (largepage && !is_large_pte(*shadow_pte)) {
1054                         struct kvm_mmu_page *child;
1055                         u64 pte = *shadow_pte;
1056
1057                         child = page_header(pte & PT64_BASE_ADDR_MASK);
1058                         mmu_page_remove_parent_pte(child, shadow_pte);
1059                 } else if (pfn != spte_to_pfn(*shadow_pte)) {
1060                         pgprintk("hfn old %lx new %lx\n",
1061                                  spte_to_pfn(*shadow_pte), pfn);
1062                         rmap_remove(vcpu->kvm, shadow_pte);
1063                 } else {
1064                         if (largepage)
1065                                 was_rmapped = is_large_pte(*shadow_pte);
1066                         else
1067                                 was_rmapped = 1;
1068                 }
1069         }
1070
1071         /*
1072          * We don't set the accessed bit, since we sometimes want to see
1073          * whether the guest actually used the pte (in order to detect
1074          * demand paging).
1075          */
1076         spte = PT_PRESENT_MASK | PT_DIRTY_MASK;
1077         if (!speculative)
1078                 pte_access |= PT_ACCESSED_MASK;
1079         if (!dirty)
1080                 pte_access &= ~ACC_WRITE_MASK;
1081         if (!(pte_access & ACC_EXEC_MASK))
1082                 spte |= PT64_NX_MASK;
1083
1084         spte |= PT_PRESENT_MASK;
1085         if (pte_access & ACC_USER_MASK)
1086                 spte |= PT_USER_MASK;
1087         if (largepage)
1088                 spte |= PT_PAGE_SIZE_MASK;
1089
1090         spte |= (u64)pfn << PAGE_SHIFT;
1091
1092         if ((pte_access & ACC_WRITE_MASK)
1093             || (write_fault && !is_write_protection(vcpu) && !user_fault)) {
1094                 struct kvm_mmu_page *shadow;
1095
1096                 spte |= PT_WRITABLE_MASK;
1097                 if (user_fault) {
1098                         mmu_unshadow(vcpu->kvm, gfn);
1099                         goto unshadowed;
1100                 }
1101
1102                 shadow = kvm_mmu_lookup_page(vcpu->kvm, gfn);
1103                 if (shadow ||
1104                    (largepage && has_wrprotected_page(vcpu->kvm, gfn))) {
1105                         pgprintk("%s: found shadow page for %lx, marking ro\n",
1106                                  __func__, gfn);
1107                         pte_access &= ~ACC_WRITE_MASK;
1108                         if (is_writeble_pte(spte)) {
1109                                 spte &= ~PT_WRITABLE_MASK;
1110                                 kvm_x86_ops->tlb_flush(vcpu);
1111                         }
1112                         if (write_fault)
1113                                 *ptwrite = 1;
1114                 }
1115         }
1116
1117 unshadowed:
1118
1119         if (pte_access & ACC_WRITE_MASK)
1120                 mark_page_dirty(vcpu->kvm, gfn);
1121
1122         pgprintk("%s: setting spte %llx\n", __func__, spte);
1123         pgprintk("instantiating %s PTE (%s) at %d (%llx) addr %llx\n",
1124                  (spte&PT_PAGE_SIZE_MASK)? "2MB" : "4kB",
1125                  (spte&PT_WRITABLE_MASK)?"RW":"R", gfn, spte, shadow_pte);
1126         set_shadow_pte(shadow_pte, spte);
1127         if (!was_rmapped && (spte & PT_PAGE_SIZE_MASK)
1128             && (spte & PT_PRESENT_MASK))
1129                 ++vcpu->kvm->stat.lpages;
1130
1131         page_header_update_slot(vcpu->kvm, shadow_pte, gfn);
1132         if (!was_rmapped) {
1133                 rmap_add(vcpu, shadow_pte, gfn, largepage);
1134                 if (!is_rmap_pte(*shadow_pte))
1135                         kvm_release_pfn_clean(pfn);
1136         } else {
1137                 if (was_writeble)
1138                         kvm_release_pfn_dirty(pfn);
1139                 else
1140                         kvm_release_pfn_clean(pfn);
1141         }
1142         if (!ptwrite || !*ptwrite)
1143                 vcpu->arch.last_pte_updated = shadow_pte;
1144 }
1145
1146 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
1147 {
1148 }
1149
1150 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
1151                            int largepage, gfn_t gfn, pfn_t pfn,
1152                            int level)
1153 {
1154         hpa_t table_addr = vcpu->arch.mmu.root_hpa;
1155         int pt_write = 0;
1156
1157         for (; ; level--) {
1158                 u32 index = PT64_INDEX(v, level);
1159                 u64 *table;
1160
1161                 ASSERT(VALID_PAGE(table_addr));
1162                 table = __va(table_addr);
1163
1164                 if (level == 1) {
1165                         mmu_set_spte(vcpu, &table[index], ACC_ALL, ACC_ALL,
1166                                      0, write, 1, &pt_write, 0, gfn, pfn, false);
1167                         return pt_write;
1168                 }
1169
1170                 if (largepage && level == 2) {
1171                         mmu_set_spte(vcpu, &table[index], ACC_ALL, ACC_ALL,
1172                                      0, write, 1, &pt_write, 1, gfn, pfn, false);
1173                         return pt_write;
1174                 }
1175
1176                 if (table[index] == shadow_trap_nonpresent_pte) {
1177                         struct kvm_mmu_page *new_table;
1178                         gfn_t pseudo_gfn;
1179
1180                         pseudo_gfn = (v & PT64_DIR_BASE_ADDR_MASK)
1181                                 >> PAGE_SHIFT;
1182                         new_table = kvm_mmu_get_page(vcpu, pseudo_gfn,
1183                                                      v, level - 1,
1184                                                      1, ACC_ALL, &table[index]);
1185                         if (!new_table) {
1186                                 pgprintk("nonpaging_map: ENOMEM\n");
1187                                 kvm_release_pfn_clean(pfn);
1188                                 return -ENOMEM;
1189                         }
1190
1191                         table[index] = __pa(new_table->spt) | PT_PRESENT_MASK
1192                                 | PT_WRITABLE_MASK | PT_USER_MASK;
1193                 }
1194                 table_addr = table[index] & PT64_BASE_ADDR_MASK;
1195         }
1196 }
1197
1198 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn)
1199 {
1200         int r;
1201         int largepage = 0;
1202         pfn_t pfn;
1203
1204         down_read(&current->mm->mmap_sem);
1205         if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
1206                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
1207                 largepage = 1;
1208         }
1209
1210         pfn = gfn_to_pfn(vcpu->kvm, gfn);
1211         up_read(&current->mm->mmap_sem);
1212
1213         /* mmio */
1214         if (is_error_pfn(pfn)) {
1215                 kvm_release_pfn_clean(pfn);
1216                 return 1;
1217         }
1218
1219         spin_lock(&vcpu->kvm->mmu_lock);
1220         kvm_mmu_free_some_pages(vcpu);
1221         r = __direct_map(vcpu, v, write, largepage, gfn, pfn,
1222                          PT32E_ROOT_LEVEL);
1223         spin_unlock(&vcpu->kvm->mmu_lock);
1224
1225
1226         return r;
1227 }
1228
1229
1230 static void nonpaging_prefetch_page(struct kvm_vcpu *vcpu,
1231                                     struct kvm_mmu_page *sp)
1232 {
1233         int i;
1234
1235         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
1236                 sp->spt[i] = shadow_trap_nonpresent_pte;
1237 }
1238
1239 static void mmu_free_roots(struct kvm_vcpu *vcpu)
1240 {
1241         int i;
1242         struct kvm_mmu_page *sp;
1243
1244         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1245                 return;
1246         spin_lock(&vcpu->kvm->mmu_lock);
1247 #ifdef CONFIG_X86_64
1248         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1249                 hpa_t root = vcpu->arch.mmu.root_hpa;
1250
1251                 sp = page_header(root);
1252                 --sp->root_count;
1253                 if (!sp->root_count && sp->role.invalid)
1254                         kvm_mmu_zap_page(vcpu->kvm, sp);
1255                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1256                 spin_unlock(&vcpu->kvm->mmu_lock);
1257                 return;
1258         }
1259 #endif
1260         for (i = 0; i < 4; ++i) {
1261                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1262
1263                 if (root) {
1264                         root &= PT64_BASE_ADDR_MASK;
1265                         sp = page_header(root);
1266                         --sp->root_count;
1267                         if (!sp->root_count && sp->role.invalid)
1268                                 kvm_mmu_zap_page(vcpu->kvm, sp);
1269                 }
1270                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1271         }
1272         spin_unlock(&vcpu->kvm->mmu_lock);
1273         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1274 }
1275
1276 static void mmu_alloc_roots(struct kvm_vcpu *vcpu)
1277 {
1278         int i;
1279         gfn_t root_gfn;
1280         struct kvm_mmu_page *sp;
1281         int metaphysical = 0;
1282
1283         root_gfn = vcpu->arch.cr3 >> PAGE_SHIFT;
1284
1285 #ifdef CONFIG_X86_64
1286         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1287                 hpa_t root = vcpu->arch.mmu.root_hpa;
1288
1289                 ASSERT(!VALID_PAGE(root));
1290                 if (tdp_enabled)
1291                         metaphysical = 1;
1292                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
1293                                       PT64_ROOT_LEVEL, metaphysical,
1294                                       ACC_ALL, NULL);
1295                 root = __pa(sp->spt);
1296                 ++sp->root_count;
1297                 vcpu->arch.mmu.root_hpa = root;
1298                 return;
1299         }
1300 #endif
1301         metaphysical = !is_paging(vcpu);
1302         if (tdp_enabled)
1303                 metaphysical = 1;
1304         for (i = 0; i < 4; ++i) {
1305                 hpa_t root = vcpu->arch.mmu.pae_root[i];
1306
1307                 ASSERT(!VALID_PAGE(root));
1308                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
1309                         if (!is_present_pte(vcpu->arch.pdptrs[i])) {
1310                                 vcpu->arch.mmu.pae_root[i] = 0;
1311                                 continue;
1312                         }
1313                         root_gfn = vcpu->arch.pdptrs[i] >> PAGE_SHIFT;
1314                 } else if (vcpu->arch.mmu.root_level == 0)
1315                         root_gfn = 0;
1316                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
1317                                       PT32_ROOT_LEVEL, metaphysical,
1318                                       ACC_ALL, NULL);
1319                 root = __pa(sp->spt);
1320                 ++sp->root_count;
1321                 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
1322         }
1323         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
1324 }
1325
1326 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr)
1327 {
1328         return vaddr;
1329 }
1330
1331 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
1332                                 u32 error_code)
1333 {
1334         gfn_t gfn;
1335         int r;
1336
1337         pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
1338         r = mmu_topup_memory_caches(vcpu);
1339         if (r)
1340                 return r;
1341
1342         ASSERT(vcpu);
1343         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
1344
1345         gfn = gva >> PAGE_SHIFT;
1346
1347         return nonpaging_map(vcpu, gva & PAGE_MASK,
1348                              error_code & PFERR_WRITE_MASK, gfn);
1349 }
1350
1351 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
1352                                 u32 error_code)
1353 {
1354         pfn_t pfn;
1355         int r;
1356         int largepage = 0;
1357         gfn_t gfn = gpa >> PAGE_SHIFT;
1358
1359         ASSERT(vcpu);
1360         ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
1361
1362         r = mmu_topup_memory_caches(vcpu);
1363         if (r)
1364                 return r;
1365
1366         down_read(&current->mm->mmap_sem);
1367         if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
1368                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
1369                 largepage = 1;
1370         }
1371         pfn = gfn_to_pfn(vcpu->kvm, gfn);
1372         up_read(&current->mm->mmap_sem);
1373         if (is_error_pfn(pfn)) {
1374                 kvm_release_pfn_clean(pfn);
1375                 return 1;
1376         }
1377         spin_lock(&vcpu->kvm->mmu_lock);
1378         kvm_mmu_free_some_pages(vcpu);
1379         r = __direct_map(vcpu, gpa, error_code & PFERR_WRITE_MASK,
1380                          largepage, gfn, pfn, TDP_ROOT_LEVEL);
1381         spin_unlock(&vcpu->kvm->mmu_lock);
1382
1383         return r;
1384 }
1385
1386 static void nonpaging_free(struct kvm_vcpu *vcpu)
1387 {
1388         mmu_free_roots(vcpu);
1389 }
1390
1391 static int nonpaging_init_context(struct kvm_vcpu *vcpu)
1392 {
1393         struct kvm_mmu *context = &vcpu->arch.mmu;
1394
1395         context->new_cr3 = nonpaging_new_cr3;
1396         context->page_fault = nonpaging_page_fault;
1397         context->gva_to_gpa = nonpaging_gva_to_gpa;
1398         context->free = nonpaging_free;
1399         context->prefetch_page = nonpaging_prefetch_page;
1400         context->root_level = 0;
1401         context->shadow_root_level = PT32E_ROOT_LEVEL;
1402         context->root_hpa = INVALID_PAGE;
1403         return 0;
1404 }
1405
1406 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
1407 {
1408         ++vcpu->stat.tlb_flush;
1409         kvm_x86_ops->tlb_flush(vcpu);
1410 }
1411
1412 static void paging_new_cr3(struct kvm_vcpu *vcpu)
1413 {
1414         pgprintk("%s: cr3 %lx\n", __func__, vcpu->arch.cr3);
1415         mmu_free_roots(vcpu);
1416 }
1417
1418 static void inject_page_fault(struct kvm_vcpu *vcpu,
1419                               u64 addr,
1420                               u32 err_code)
1421 {
1422         kvm_inject_page_fault(vcpu, addr, err_code);
1423 }
1424
1425 static void paging_free(struct kvm_vcpu *vcpu)
1426 {
1427         nonpaging_free(vcpu);
1428 }
1429
1430 #define PTTYPE 64
1431 #include "paging_tmpl.h"
1432 #undef PTTYPE
1433
1434 #define PTTYPE 32
1435 #include "paging_tmpl.h"
1436 #undef PTTYPE
1437
1438 static int paging64_init_context_common(struct kvm_vcpu *vcpu, int level)
1439 {
1440         struct kvm_mmu *context = &vcpu->arch.mmu;
1441
1442         ASSERT(is_pae(vcpu));
1443         context->new_cr3 = paging_new_cr3;
1444         context->page_fault = paging64_page_fault;
1445         context->gva_to_gpa = paging64_gva_to_gpa;
1446         context->prefetch_page = paging64_prefetch_page;
1447         context->free = paging_free;
1448         context->root_level = level;
1449         context->shadow_root_level = level;
1450         context->root_hpa = INVALID_PAGE;
1451         return 0;
1452 }
1453
1454 static int paging64_init_context(struct kvm_vcpu *vcpu)
1455 {
1456         return paging64_init_context_common(vcpu, PT64_ROOT_LEVEL);
1457 }
1458
1459 static int paging32_init_context(struct kvm_vcpu *vcpu)
1460 {
1461         struct kvm_mmu *context = &vcpu->arch.mmu;
1462
1463         context->new_cr3 = paging_new_cr3;
1464         context->page_fault = paging32_page_fault;
1465         context->gva_to_gpa = paging32_gva_to_gpa;
1466         context->free = paging_free;
1467         context->prefetch_page = paging32_prefetch_page;
1468         context->root_level = PT32_ROOT_LEVEL;
1469         context->shadow_root_level = PT32E_ROOT_LEVEL;
1470         context->root_hpa = INVALID_PAGE;
1471         return 0;
1472 }
1473
1474 static int paging32E_init_context(struct kvm_vcpu *vcpu)
1475 {
1476         return paging64_init_context_common(vcpu, PT32E_ROOT_LEVEL);
1477 }
1478
1479 static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
1480 {
1481         struct kvm_mmu *context = &vcpu->arch.mmu;
1482
1483         context->new_cr3 = nonpaging_new_cr3;
1484         context->page_fault = tdp_page_fault;
1485         context->free = nonpaging_free;
1486         context->prefetch_page = nonpaging_prefetch_page;
1487         context->shadow_root_level = TDP_ROOT_LEVEL;
1488         context->root_hpa = INVALID_PAGE;
1489
1490         if (!is_paging(vcpu)) {
1491                 context->gva_to_gpa = nonpaging_gva_to_gpa;
1492                 context->root_level = 0;
1493         } else if (is_long_mode(vcpu)) {
1494                 context->gva_to_gpa = paging64_gva_to_gpa;
1495                 context->root_level = PT64_ROOT_LEVEL;
1496         } else if (is_pae(vcpu)) {
1497                 context->gva_to_gpa = paging64_gva_to_gpa;
1498                 context->root_level = PT32E_ROOT_LEVEL;
1499         } else {
1500                 context->gva_to_gpa = paging32_gva_to_gpa;
1501                 context->root_level = PT32_ROOT_LEVEL;
1502         }
1503
1504         return 0;
1505 }
1506
1507 static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
1508 {
1509         ASSERT(vcpu);
1510         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
1511
1512         if (!is_paging(vcpu))
1513                 return nonpaging_init_context(vcpu);
1514         else if (is_long_mode(vcpu))
1515                 return paging64_init_context(vcpu);
1516         else if (is_pae(vcpu))
1517                 return paging32E_init_context(vcpu);
1518         else
1519                 return paging32_init_context(vcpu);
1520 }
1521
1522 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
1523 {
1524         vcpu->arch.update_pte.pfn = bad_pfn;
1525
1526         if (tdp_enabled)
1527                 return init_kvm_tdp_mmu(vcpu);
1528         else
1529                 return init_kvm_softmmu(vcpu);
1530 }
1531
1532 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
1533 {
1534         ASSERT(vcpu);
1535         if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) {
1536                 vcpu->arch.mmu.free(vcpu);
1537                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1538         }
1539 }
1540
1541 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
1542 {
1543         destroy_kvm_mmu(vcpu);
1544         return init_kvm_mmu(vcpu);
1545 }
1546 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
1547
1548 int kvm_mmu_load(struct kvm_vcpu *vcpu)
1549 {
1550         int r;
1551
1552         r = mmu_topup_memory_caches(vcpu);
1553         if (r)
1554                 goto out;
1555         spin_lock(&vcpu->kvm->mmu_lock);
1556         kvm_mmu_free_some_pages(vcpu);
1557         mmu_alloc_roots(vcpu);
1558         spin_unlock(&vcpu->kvm->mmu_lock);
1559         kvm_x86_ops->set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
1560         kvm_mmu_flush_tlb(vcpu);
1561 out:
1562         return r;
1563 }
1564 EXPORT_SYMBOL_GPL(kvm_mmu_load);
1565
1566 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
1567 {
1568         mmu_free_roots(vcpu);
1569 }
1570
1571 static void mmu_pte_write_zap_pte(struct kvm_vcpu *vcpu,
1572                                   struct kvm_mmu_page *sp,
1573                                   u64 *spte)
1574 {
1575         u64 pte;
1576         struct kvm_mmu_page *child;
1577
1578         pte = *spte;
1579         if (is_shadow_present_pte(pte)) {
1580                 if (sp->role.level == PT_PAGE_TABLE_LEVEL ||
1581                     is_large_pte(pte))
1582                         rmap_remove(vcpu->kvm, spte);
1583                 else {
1584                         child = page_header(pte & PT64_BASE_ADDR_MASK);
1585                         mmu_page_remove_parent_pte(child, spte);
1586                 }
1587         }
1588         set_shadow_pte(spte, shadow_trap_nonpresent_pte);
1589         if (is_large_pte(pte))
1590                 --vcpu->kvm->stat.lpages;
1591 }
1592
1593 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
1594                                   struct kvm_mmu_page *sp,
1595                                   u64 *spte,
1596                                   const void *new)
1597 {
1598         if ((sp->role.level != PT_PAGE_TABLE_LEVEL)
1599             && !vcpu->arch.update_pte.largepage) {
1600                 ++vcpu->kvm->stat.mmu_pde_zapped;
1601                 return;
1602         }
1603
1604         ++vcpu->kvm->stat.mmu_pte_updated;
1605         if (sp->role.glevels == PT32_ROOT_LEVEL)
1606                 paging32_update_pte(vcpu, sp, spte, new);
1607         else
1608                 paging64_update_pte(vcpu, sp, spte, new);
1609 }
1610
1611 static bool need_remote_flush(u64 old, u64 new)
1612 {
1613         if (!is_shadow_present_pte(old))
1614                 return false;
1615         if (!is_shadow_present_pte(new))
1616                 return true;
1617         if ((old ^ new) & PT64_BASE_ADDR_MASK)
1618                 return true;
1619         old ^= PT64_NX_MASK;
1620         new ^= PT64_NX_MASK;
1621         return (old & ~new & PT64_PERM_MASK) != 0;
1622 }
1623
1624 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, u64 old, u64 new)
1625 {
1626         if (need_remote_flush(old, new))
1627                 kvm_flush_remote_tlbs(vcpu->kvm);
1628         else
1629                 kvm_mmu_flush_tlb(vcpu);
1630 }
1631
1632 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
1633 {
1634         u64 *spte = vcpu->arch.last_pte_updated;
1635
1636         return !!(spte && (*spte & PT_ACCESSED_MASK));
1637 }
1638
1639 static void mmu_guess_page_from_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
1640                                           const u8 *new, int bytes)
1641 {
1642         gfn_t gfn;
1643         int r;
1644         u64 gpte = 0;
1645         pfn_t pfn;
1646
1647         vcpu->arch.update_pte.largepage = 0;
1648
1649         if (bytes != 4 && bytes != 8)
1650                 return;
1651
1652         /*
1653          * Assume that the pte write on a page table of the same type
1654          * as the current vcpu paging mode.  This is nearly always true
1655          * (might be false while changing modes).  Note it is verified later
1656          * by update_pte().
1657          */
1658         if (is_pae(vcpu)) {
1659                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
1660                 if ((bytes == 4) && (gpa % 4 == 0)) {
1661                         r = kvm_read_guest(vcpu->kvm, gpa & ~(u64)7, &gpte, 8);
1662                         if (r)
1663                                 return;
1664                         memcpy((void *)&gpte + (gpa % 8), new, 4);
1665                 } else if ((bytes == 8) && (gpa % 8 == 0)) {
1666                         memcpy((void *)&gpte, new, 8);
1667                 }
1668         } else {
1669                 if ((bytes == 4) && (gpa % 4 == 0))
1670                         memcpy((void *)&gpte, new, 4);
1671         }
1672         if (!is_present_pte(gpte))
1673                 return;
1674         gfn = (gpte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
1675
1676         down_read(&current->mm->mmap_sem);
1677         if (is_large_pte(gpte) && is_largepage_backed(vcpu, gfn)) {
1678                 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
1679                 vcpu->arch.update_pte.largepage = 1;
1680         }
1681         pfn = gfn_to_pfn(vcpu->kvm, gfn);
1682         up_read(&current->mm->mmap_sem);
1683
1684         if (is_error_pfn(pfn)) {
1685                 kvm_release_pfn_clean(pfn);
1686                 return;
1687         }
1688         vcpu->arch.update_pte.gfn = gfn;
1689         vcpu->arch.update_pte.pfn = pfn;
1690 }
1691
1692 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
1693                        const u8 *new, int bytes)
1694 {
1695         gfn_t gfn = gpa >> PAGE_SHIFT;
1696         struct kvm_mmu_page *sp;
1697         struct hlist_node *node, *n;
1698         struct hlist_head *bucket;
1699         unsigned index;
1700         u64 entry, gentry;
1701         u64 *spte;
1702         unsigned offset = offset_in_page(gpa);
1703         unsigned pte_size;
1704         unsigned page_offset;
1705         unsigned misaligned;
1706         unsigned quadrant;
1707         int level;
1708         int flooded = 0;
1709         int npte;
1710         int r;
1711
1712         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
1713         mmu_guess_page_from_pte_write(vcpu, gpa, new, bytes);
1714         spin_lock(&vcpu->kvm->mmu_lock);
1715         kvm_mmu_free_some_pages(vcpu);
1716         ++vcpu->kvm->stat.mmu_pte_write;
1717         kvm_mmu_audit(vcpu, "pre pte write");
1718         if (gfn == vcpu->arch.last_pt_write_gfn
1719             && !last_updated_pte_accessed(vcpu)) {
1720                 ++vcpu->arch.last_pt_write_count;
1721                 if (vcpu->arch.last_pt_write_count >= 3)
1722                         flooded = 1;
1723         } else {
1724                 vcpu->arch.last_pt_write_gfn = gfn;
1725                 vcpu->arch.last_pt_write_count = 1;
1726                 vcpu->arch.last_pte_updated = NULL;
1727         }
1728         index = kvm_page_table_hashfn(gfn);
1729         bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1730         hlist_for_each_entry_safe(sp, node, n, bucket, hash_link) {
1731                 if (sp->gfn != gfn || sp->role.metaphysical)
1732                         continue;
1733                 pte_size = sp->role.glevels == PT32_ROOT_LEVEL ? 4 : 8;
1734                 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
1735                 misaligned |= bytes < 4;
1736                 if (misaligned || flooded) {
1737                         /*
1738                          * Misaligned accesses are too much trouble to fix
1739                          * up; also, they usually indicate a page is not used
1740                          * as a page table.
1741                          *
1742                          * If we're seeing too many writes to a page,
1743                          * it may no longer be a page table, or we may be
1744                          * forking, in which case it is better to unmap the
1745                          * page.
1746                          */
1747                         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
1748                                  gpa, bytes, sp->role.word);
1749                         kvm_mmu_zap_page(vcpu->kvm, sp);
1750                         ++vcpu->kvm->stat.mmu_flooded;
1751                         continue;
1752                 }
1753                 page_offset = offset;
1754                 level = sp->role.level;
1755                 npte = 1;
1756                 if (sp->role.glevels == PT32_ROOT_LEVEL) {
1757                         page_offset <<= 1;      /* 32->64 */
1758                         /*
1759                          * A 32-bit pde maps 4MB while the shadow pdes map
1760                          * only 2MB.  So we need to double the offset again
1761                          * and zap two pdes instead of one.
1762                          */
1763                         if (level == PT32_ROOT_LEVEL) {
1764                                 page_offset &= ~7; /* kill rounding error */
1765                                 page_offset <<= 1;
1766                                 npte = 2;
1767                         }
1768                         quadrant = page_offset >> PAGE_SHIFT;
1769                         page_offset &= ~PAGE_MASK;
1770                         if (quadrant != sp->role.quadrant)
1771                                 continue;
1772                 }
1773                 spte = &sp->spt[page_offset / sizeof(*spte)];
1774                 if ((gpa & (pte_size - 1)) || (bytes < pte_size)) {
1775                         gentry = 0;
1776                         r = kvm_read_guest_atomic(vcpu->kvm,
1777                                                   gpa & ~(u64)(pte_size - 1),
1778                                                   &gentry, pte_size);
1779                         new = (const void *)&gentry;
1780                         if (r < 0)
1781                                 new = NULL;
1782                 }
1783                 while (npte--) {
1784                         entry = *spte;
1785                         mmu_pte_write_zap_pte(vcpu, sp, spte);
1786                         if (new)
1787                                 mmu_pte_write_new_pte(vcpu, sp, spte, new);
1788                         mmu_pte_write_flush_tlb(vcpu, entry, *spte);
1789                         ++spte;
1790                 }
1791         }
1792         kvm_mmu_audit(vcpu, "post pte write");
1793         spin_unlock(&vcpu->kvm->mmu_lock);
1794         if (!is_error_pfn(vcpu->arch.update_pte.pfn)) {
1795                 kvm_release_pfn_clean(vcpu->arch.update_pte.pfn);
1796                 vcpu->arch.update_pte.pfn = bad_pfn;
1797         }
1798 }
1799
1800 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
1801 {
1802         gpa_t gpa;
1803         int r;
1804
1805         gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1806
1807         spin_lock(&vcpu->kvm->mmu_lock);
1808         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1809         spin_unlock(&vcpu->kvm->mmu_lock);
1810         return r;
1811 }
1812
1813 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
1814 {
1815         while (vcpu->kvm->arch.n_free_mmu_pages < KVM_REFILL_PAGES) {
1816                 struct kvm_mmu_page *sp;
1817
1818                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
1819                                   struct kvm_mmu_page, link);
1820                 kvm_mmu_zap_page(vcpu->kvm, sp);
1821                 ++vcpu->kvm->stat.mmu_recycled;
1822         }
1823 }
1824
1825 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
1826 {
1827         int r;
1828         enum emulation_result er;
1829
1830         r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
1831         if (r < 0)
1832                 goto out;
1833
1834         if (!r) {
1835                 r = 1;
1836                 goto out;
1837         }
1838
1839         r = mmu_topup_memory_caches(vcpu);
1840         if (r)
1841                 goto out;
1842
1843         er = emulate_instruction(vcpu, vcpu->run, cr2, error_code, 0);
1844
1845         switch (er) {
1846         case EMULATE_DONE:
1847                 return 1;
1848         case EMULATE_DO_MMIO:
1849                 ++vcpu->stat.mmio_exits;
1850                 return 0;
1851         case EMULATE_FAIL:
1852                 kvm_report_emulation_failure(vcpu, "pagetable");
1853                 return 1;
1854         default:
1855                 BUG();
1856         }
1857 out:
1858         return r;
1859 }
1860 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
1861
1862 void kvm_enable_tdp(void)
1863 {
1864         tdp_enabled = true;
1865 }
1866 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
1867
1868 static void free_mmu_pages(struct kvm_vcpu *vcpu)
1869 {
1870         struct kvm_mmu_page *sp;
1871
1872         while (!list_empty(&vcpu->kvm->arch.active_mmu_pages)) {
1873                 sp = container_of(vcpu->kvm->arch.active_mmu_pages.next,
1874                                   struct kvm_mmu_page, link);
1875                 kvm_mmu_zap_page(vcpu->kvm, sp);
1876         }
1877         free_page((unsigned long)vcpu->arch.mmu.pae_root);
1878 }
1879
1880 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
1881 {
1882         struct page *page;
1883         int i;
1884
1885         ASSERT(vcpu);
1886
1887         if (vcpu->kvm->arch.n_requested_mmu_pages)
1888                 vcpu->kvm->arch.n_free_mmu_pages =
1889                                         vcpu->kvm->arch.n_requested_mmu_pages;
1890         else
1891                 vcpu->kvm->arch.n_free_mmu_pages =
1892                                         vcpu->kvm->arch.n_alloc_mmu_pages;
1893         /*
1894          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
1895          * Therefore we need to allocate shadow page tables in the first
1896          * 4GB of memory, which happens to fit the DMA32 zone.
1897          */
1898         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
1899         if (!page)
1900                 goto error_1;
1901         vcpu->arch.mmu.pae_root = page_address(page);
1902         for (i = 0; i < 4; ++i)
1903                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1904
1905         return 0;
1906
1907 error_1:
1908         free_mmu_pages(vcpu);
1909         return -ENOMEM;
1910 }
1911
1912 int kvm_mmu_create(struct kvm_vcpu *vcpu)
1913 {
1914         ASSERT(vcpu);
1915         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
1916
1917         return alloc_mmu_pages(vcpu);
1918 }
1919
1920 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
1921 {
1922         ASSERT(vcpu);
1923         ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
1924
1925         return init_kvm_mmu(vcpu);
1926 }
1927
1928 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
1929 {
1930         ASSERT(vcpu);
1931
1932         destroy_kvm_mmu(vcpu);
1933         free_mmu_pages(vcpu);
1934         mmu_free_memory_caches(vcpu);
1935 }
1936
1937 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
1938 {
1939         struct kvm_mmu_page *sp;
1940
1941         list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
1942                 int i;
1943                 u64 *pt;
1944
1945                 if (!test_bit(slot, &sp->slot_bitmap))
1946                         continue;
1947
1948                 pt = sp->spt;
1949                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
1950                         /* avoid RMW */
1951                         if (pt[i] & PT_WRITABLE_MASK)
1952                                 pt[i] &= ~PT_WRITABLE_MASK;
1953         }
1954 }
1955
1956 void kvm_mmu_zap_all(struct kvm *kvm)
1957 {
1958         struct kvm_mmu_page *sp, *node;
1959
1960         spin_lock(&kvm->mmu_lock);
1961         list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
1962                 kvm_mmu_zap_page(kvm, sp);
1963         spin_unlock(&kvm->mmu_lock);
1964
1965         kvm_flush_remote_tlbs(kvm);
1966 }
1967
1968 void kvm_mmu_remove_one_alloc_mmu_page(struct kvm *kvm)
1969 {
1970         struct kvm_mmu_page *page;
1971
1972         page = container_of(kvm->arch.active_mmu_pages.prev,
1973                             struct kvm_mmu_page, link);
1974         kvm_mmu_zap_page(kvm, page);
1975 }
1976
1977 static int mmu_shrink(int nr_to_scan, gfp_t gfp_mask)
1978 {
1979         struct kvm *kvm;
1980         struct kvm *kvm_freed = NULL;
1981         int cache_count = 0;
1982
1983         spin_lock(&kvm_lock);
1984
1985         list_for_each_entry(kvm, &vm_list, vm_list) {
1986                 int npages;
1987
1988                 spin_lock(&kvm->mmu_lock);
1989                 npages = kvm->arch.n_alloc_mmu_pages -
1990                          kvm->arch.n_free_mmu_pages;
1991                 cache_count += npages;
1992                 if (!kvm_freed && nr_to_scan > 0 && npages > 0) {
1993                         kvm_mmu_remove_one_alloc_mmu_page(kvm);
1994                         cache_count--;
1995                         kvm_freed = kvm;
1996                 }
1997                 nr_to_scan--;
1998
1999                 spin_unlock(&kvm->mmu_lock);
2000         }
2001         if (kvm_freed)
2002                 list_move_tail(&kvm_freed->vm_list, &vm_list);
2003
2004         spin_unlock(&kvm_lock);
2005
2006         return cache_count;
2007 }
2008
2009 static struct shrinker mmu_shrinker = {
2010         .shrink = mmu_shrink,
2011         .seeks = DEFAULT_SEEKS * 10,
2012 };
2013
2014 void mmu_destroy_caches(void)
2015 {
2016         if (pte_chain_cache)
2017                 kmem_cache_destroy(pte_chain_cache);
2018         if (rmap_desc_cache)
2019                 kmem_cache_destroy(rmap_desc_cache);
2020         if (mmu_page_header_cache)
2021                 kmem_cache_destroy(mmu_page_header_cache);
2022 }
2023
2024 void kvm_mmu_module_exit(void)
2025 {
2026         mmu_destroy_caches();
2027         unregister_shrinker(&mmu_shrinker);
2028 }
2029
2030 int kvm_mmu_module_init(void)
2031 {
2032         pte_chain_cache = kmem_cache_create("kvm_pte_chain",
2033                                             sizeof(struct kvm_pte_chain),
2034                                             0, 0, NULL);
2035         if (!pte_chain_cache)
2036                 goto nomem;
2037         rmap_desc_cache = kmem_cache_create("kvm_rmap_desc",
2038                                             sizeof(struct kvm_rmap_desc),
2039                                             0, 0, NULL);
2040         if (!rmap_desc_cache)
2041                 goto nomem;
2042
2043         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
2044                                                   sizeof(struct kvm_mmu_page),
2045                                                   0, 0, NULL);
2046         if (!mmu_page_header_cache)
2047                 goto nomem;
2048
2049         register_shrinker(&mmu_shrinker);
2050
2051         return 0;
2052
2053 nomem:
2054         mmu_destroy_caches();
2055         return -ENOMEM;
2056 }
2057
2058 /*
2059  * Caculate mmu pages needed for kvm.
2060  */
2061 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
2062 {
2063         int i;
2064         unsigned int nr_mmu_pages;
2065         unsigned int  nr_pages = 0;
2066
2067         for (i = 0; i < kvm->nmemslots; i++)
2068                 nr_pages += kvm->memslots[i].npages;
2069
2070         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
2071         nr_mmu_pages = max(nr_mmu_pages,
2072                         (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
2073
2074         return nr_mmu_pages;
2075 }
2076
2077 static void *pv_mmu_peek_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2078                                 unsigned len)
2079 {
2080         if (len > buffer->len)
2081                 return NULL;
2082         return buffer->ptr;
2083 }
2084
2085 static void *pv_mmu_read_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2086                                 unsigned len)
2087 {
2088         void *ret;
2089
2090         ret = pv_mmu_peek_buffer(buffer, len);
2091         if (!ret)
2092                 return ret;
2093         buffer->ptr += len;
2094         buffer->len -= len;
2095         buffer->processed += len;
2096         return ret;
2097 }
2098
2099 static int kvm_pv_mmu_write(struct kvm_vcpu *vcpu,
2100                              gpa_t addr, gpa_t value)
2101 {
2102         int bytes = 8;
2103         int r;
2104
2105         if (!is_long_mode(vcpu) && !is_pae(vcpu))
2106                 bytes = 4;
2107
2108         r = mmu_topup_memory_caches(vcpu);
2109         if (r)
2110                 return r;
2111
2112         if (!emulator_write_phys(vcpu, addr, &value, bytes))
2113                 return -EFAULT;
2114
2115         return 1;
2116 }
2117
2118 static int kvm_pv_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2119 {
2120         kvm_x86_ops->tlb_flush(vcpu);
2121         return 1;
2122 }
2123
2124 static int kvm_pv_mmu_release_pt(struct kvm_vcpu *vcpu, gpa_t addr)
2125 {
2126         spin_lock(&vcpu->kvm->mmu_lock);
2127         mmu_unshadow(vcpu->kvm, addr >> PAGE_SHIFT);
2128         spin_unlock(&vcpu->kvm->mmu_lock);
2129         return 1;
2130 }
2131
2132 static int kvm_pv_mmu_op_one(struct kvm_vcpu *vcpu,
2133                              struct kvm_pv_mmu_op_buffer *buffer)
2134 {
2135         struct kvm_mmu_op_header *header;
2136
2137         header = pv_mmu_peek_buffer(buffer, sizeof *header);
2138         if (!header)
2139                 return 0;
2140         switch (header->op) {
2141         case KVM_MMU_OP_WRITE_PTE: {
2142                 struct kvm_mmu_op_write_pte *wpte;
2143
2144                 wpte = pv_mmu_read_buffer(buffer, sizeof *wpte);
2145                 if (!wpte)
2146                         return 0;
2147                 return kvm_pv_mmu_write(vcpu, wpte->pte_phys,
2148                                         wpte->pte_val);
2149         }
2150         case KVM_MMU_OP_FLUSH_TLB: {
2151                 struct kvm_mmu_op_flush_tlb *ftlb;
2152
2153                 ftlb = pv_mmu_read_buffer(buffer, sizeof *ftlb);
2154                 if (!ftlb)
2155                         return 0;
2156                 return kvm_pv_mmu_flush_tlb(vcpu);
2157         }
2158         case KVM_MMU_OP_RELEASE_PT: {
2159                 struct kvm_mmu_op_release_pt *rpt;
2160
2161                 rpt = pv_mmu_read_buffer(buffer, sizeof *rpt);
2162                 if (!rpt)
2163                         return 0;
2164                 return kvm_pv_mmu_release_pt(vcpu, rpt->pt_phys);
2165         }
2166         default: return 0;
2167         }
2168 }
2169
2170 int kvm_pv_mmu_op(struct kvm_vcpu *vcpu, unsigned long bytes,
2171                   gpa_t addr, unsigned long *ret)
2172 {
2173         int r;
2174         struct kvm_pv_mmu_op_buffer buffer;
2175
2176         buffer.ptr = buffer.buf;
2177         buffer.len = min_t(unsigned long, bytes, sizeof buffer.buf);
2178         buffer.processed = 0;
2179
2180         r = kvm_read_guest(vcpu->kvm, addr, buffer.buf, buffer.len);
2181         if (r)
2182                 goto out;
2183
2184         while (buffer.len) {
2185                 r = kvm_pv_mmu_op_one(vcpu, &buffer);
2186                 if (r < 0)
2187                         goto out;
2188                 if (r == 0)
2189                         break;
2190         }
2191
2192         r = 1;
2193 out:
2194         *ret = buffer.processed;
2195         return r;
2196 }
2197
2198 #ifdef AUDIT
2199
2200 static const char *audit_msg;
2201
2202 static gva_t canonicalize(gva_t gva)
2203 {
2204 #ifdef CONFIG_X86_64
2205         gva = (long long)(gva << 16) >> 16;
2206 #endif
2207         return gva;
2208 }
2209
2210 static void audit_mappings_page(struct kvm_vcpu *vcpu, u64 page_pte,
2211                                 gva_t va, int level)
2212 {
2213         u64 *pt = __va(page_pte & PT64_BASE_ADDR_MASK);
2214         int i;
2215         gva_t va_delta = 1ul << (PAGE_SHIFT + 9 * (level - 1));
2216
2217         for (i = 0; i < PT64_ENT_PER_PAGE; ++i, va += va_delta) {
2218                 u64 ent = pt[i];
2219
2220                 if (ent == shadow_trap_nonpresent_pte)
2221                         continue;
2222
2223                 va = canonicalize(va);
2224                 if (level > 1) {
2225                         if (ent == shadow_notrap_nonpresent_pte)
2226                                 printk(KERN_ERR "audit: (%s) nontrapping pte"
2227                                        " in nonleaf level: levels %d gva %lx"
2228                                        " level %d pte %llx\n", audit_msg,
2229                                        vcpu->arch.mmu.root_level, va, level, ent);
2230
2231                         audit_mappings_page(vcpu, ent, va, level - 1);
2232                 } else {
2233                         gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, va);
2234                         hpa_t hpa = (hpa_t)gpa_to_pfn(vcpu, gpa) << PAGE_SHIFT;
2235
2236                         if (is_shadow_present_pte(ent)
2237                             && (ent & PT64_BASE_ADDR_MASK) != hpa)
2238                                 printk(KERN_ERR "xx audit error: (%s) levels %d"
2239                                        " gva %lx gpa %llx hpa %llx ent %llx %d\n",
2240                                        audit_msg, vcpu->arch.mmu.root_level,
2241                                        va, gpa, hpa, ent,
2242                                        is_shadow_present_pte(ent));
2243                         else if (ent == shadow_notrap_nonpresent_pte
2244                                  && !is_error_hpa(hpa))
2245                                 printk(KERN_ERR "audit: (%s) notrap shadow,"
2246                                        " valid guest gva %lx\n", audit_msg, va);
2247                         kvm_release_pfn_clean(pfn);
2248
2249                 }
2250         }
2251 }
2252
2253 static void audit_mappings(struct kvm_vcpu *vcpu)
2254 {
2255         unsigned i;
2256
2257         if (vcpu->arch.mmu.root_level == 4)
2258                 audit_mappings_page(vcpu, vcpu->arch.mmu.root_hpa, 0, 4);
2259         else
2260                 for (i = 0; i < 4; ++i)
2261                         if (vcpu->arch.mmu.pae_root[i] & PT_PRESENT_MASK)
2262                                 audit_mappings_page(vcpu,
2263                                                     vcpu->arch.mmu.pae_root[i],
2264                                                     i << 30,
2265                                                     2);
2266 }
2267
2268 static int count_rmaps(struct kvm_vcpu *vcpu)
2269 {
2270         int nmaps = 0;
2271         int i, j, k;
2272
2273         for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
2274                 struct kvm_memory_slot *m = &vcpu->kvm->memslots[i];
2275                 struct kvm_rmap_desc *d;
2276
2277                 for (j = 0; j < m->npages; ++j) {
2278                         unsigned long *rmapp = &m->rmap[j];
2279
2280                         if (!*rmapp)
2281                                 continue;
2282                         if (!(*rmapp & 1)) {
2283                                 ++nmaps;
2284                                 continue;
2285                         }
2286                         d = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
2287                         while (d) {
2288                                 for (k = 0; k < RMAP_EXT; ++k)
2289                                         if (d->shadow_ptes[k])
2290                                                 ++nmaps;
2291                                         else
2292                                                 break;
2293                                 d = d->more;
2294                         }
2295                 }
2296         }
2297         return nmaps;
2298 }
2299
2300 static int count_writable_mappings(struct kvm_vcpu *vcpu)
2301 {
2302         int nmaps = 0;
2303         struct kvm_mmu_page *sp;
2304         int i;
2305
2306         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
2307                 u64 *pt = sp->spt;
2308
2309                 if (sp->role.level != PT_PAGE_TABLE_LEVEL)
2310                         continue;
2311
2312                 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
2313                         u64 ent = pt[i];
2314
2315                         if (!(ent & PT_PRESENT_MASK))
2316                                 continue;
2317                         if (!(ent & PT_WRITABLE_MASK))
2318                                 continue;
2319                         ++nmaps;
2320                 }
2321         }
2322         return nmaps;
2323 }
2324
2325 static void audit_rmap(struct kvm_vcpu *vcpu)
2326 {
2327         int n_rmap = count_rmaps(vcpu);
2328         int n_actual = count_writable_mappings(vcpu);
2329
2330         if (n_rmap != n_actual)
2331                 printk(KERN_ERR "%s: (%s) rmap %d actual %d\n",
2332                        __func__, audit_msg, n_rmap, n_actual);
2333 }
2334
2335 static void audit_write_protection(struct kvm_vcpu *vcpu)
2336 {
2337         struct kvm_mmu_page *sp;
2338         struct kvm_memory_slot *slot;
2339         unsigned long *rmapp;
2340         gfn_t gfn;
2341
2342         list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
2343                 if (sp->role.metaphysical)
2344                         continue;
2345
2346                 slot = gfn_to_memslot(vcpu->kvm, sp->gfn);
2347                 gfn = unalias_gfn(vcpu->kvm, sp->gfn);
2348                 rmapp = &slot->rmap[gfn - slot->base_gfn];
2349                 if (*rmapp)
2350                         printk(KERN_ERR "%s: (%s) shadow page has writable"
2351                                " mappings: gfn %lx role %x\n",
2352                                __func__, audit_msg, sp->gfn,
2353                                sp->role.word);
2354         }
2355 }
2356
2357 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg)
2358 {
2359         int olddbg = dbg;
2360
2361         dbg = 0;
2362         audit_msg = msg;
2363         audit_rmap(vcpu);
2364         audit_write_protection(vcpu);
2365         audit_mappings(vcpu);
2366         dbg = olddbg;
2367 }
2368
2369 #endif