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