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