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