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