KVM: Trace shadow page lifecycle
[linux/fpc-iii.git] / arch / x86 / kvm / mmu.c
blobac121b39a5bce1a406c4f9f01c59f55f4c0a5866
1 /*
2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
7 * MMU support
9 * Copyright (C) 2006 Qumranet, Inc.
11 * Authors:
12 * Yaniv Kamay <yaniv@qumranet.com>
13 * Avi Kivity <avi@qumranet.com>
15 * This work is licensed under the terms of the GNU GPL, version 2. See
16 * the COPYING file in the top-level directory.
20 #include "mmu.h"
21 #include "kvm_cache_regs.h"
23 #include <linux/kvm_host.h>
24 #include <linux/types.h>
25 #include <linux/string.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/module.h>
29 #include <linux/swap.h>
30 #include <linux/hugetlb.h>
31 #include <linux/compiler.h>
33 #include <asm/page.h>
34 #include <asm/cmpxchg.h>
35 #include <asm/io.h>
36 #include <asm/vmx.h>
39 * When setting this variable to true it enables Two-Dimensional-Paging
40 * where the hardware walks 2 page tables:
41 * 1. the guest-virtual to guest-physical
42 * 2. while doing 1. it walks guest-physical to host-physical
43 * If the hardware supports that we don't need to do shadow paging.
45 bool tdp_enabled = false;
47 #undef MMU_DEBUG
49 #undef AUDIT
51 #ifdef AUDIT
52 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg);
53 #else
54 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg) {}
55 #endif
57 #ifdef MMU_DEBUG
59 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
60 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
62 #else
64 #define pgprintk(x...) do { } while (0)
65 #define rmap_printk(x...) do { } while (0)
67 #endif
69 #if defined(MMU_DEBUG) || defined(AUDIT)
70 static int dbg = 0;
71 module_param(dbg, bool, 0644);
72 #endif
74 static int oos_shadow = 1;
75 module_param(oos_shadow, bool, 0644);
77 #ifndef MMU_DEBUG
78 #define ASSERT(x) do { } while (0)
79 #else
80 #define ASSERT(x) \
81 if (!(x)) { \
82 printk(KERN_WARNING "assertion failed %s:%d: %s\n", \
83 __FILE__, __LINE__, #x); \
85 #endif
87 #define PT_FIRST_AVAIL_BITS_SHIFT 9
88 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
90 #define VALID_PAGE(x) ((x) != INVALID_PAGE)
92 #define PT64_LEVEL_BITS 9
94 #define PT64_LEVEL_SHIFT(level) \
95 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
97 #define PT64_LEVEL_MASK(level) \
98 (((1ULL << PT64_LEVEL_BITS) - 1) << PT64_LEVEL_SHIFT(level))
100 #define PT64_INDEX(address, level)\
101 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
104 #define PT32_LEVEL_BITS 10
106 #define PT32_LEVEL_SHIFT(level) \
107 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
109 #define PT32_LEVEL_MASK(level) \
110 (((1ULL << PT32_LEVEL_BITS) - 1) << PT32_LEVEL_SHIFT(level))
112 #define PT32_INDEX(address, level)\
113 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
116 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
117 #define PT64_DIR_BASE_ADDR_MASK \
118 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
120 #define PT32_BASE_ADDR_MASK PAGE_MASK
121 #define PT32_DIR_BASE_ADDR_MASK \
122 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
124 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK \
125 | PT64_NX_MASK)
127 #define PFERR_PRESENT_MASK (1U << 0)
128 #define PFERR_WRITE_MASK (1U << 1)
129 #define PFERR_USER_MASK (1U << 2)
130 #define PFERR_RSVD_MASK (1U << 3)
131 #define PFERR_FETCH_MASK (1U << 4)
133 #define PT_DIRECTORY_LEVEL 2
134 #define PT_PAGE_TABLE_LEVEL 1
136 #define RMAP_EXT 4
138 #define ACC_EXEC_MASK 1
139 #define ACC_WRITE_MASK PT_WRITABLE_MASK
140 #define ACC_USER_MASK PT_USER_MASK
141 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
143 #define CREATE_TRACE_POINTS
144 #include "mmutrace.h"
146 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
148 struct kvm_rmap_desc {
149 u64 *sptes[RMAP_EXT];
150 struct kvm_rmap_desc *more;
153 struct kvm_shadow_walk_iterator {
154 u64 addr;
155 hpa_t shadow_addr;
156 int level;
157 u64 *sptep;
158 unsigned index;
161 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
162 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
163 shadow_walk_okay(&(_walker)); \
164 shadow_walk_next(&(_walker)))
167 struct kvm_unsync_walk {
168 int (*entry) (struct kvm_mmu_page *sp, struct kvm_unsync_walk *walk);
171 typedef int (*mmu_parent_walk_fn) (struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp);
173 static struct kmem_cache *pte_chain_cache;
174 static struct kmem_cache *rmap_desc_cache;
175 static struct kmem_cache *mmu_page_header_cache;
177 static u64 __read_mostly shadow_trap_nonpresent_pte;
178 static u64 __read_mostly shadow_notrap_nonpresent_pte;
179 static u64 __read_mostly shadow_base_present_pte;
180 static u64 __read_mostly shadow_nx_mask;
181 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
182 static u64 __read_mostly shadow_user_mask;
183 static u64 __read_mostly shadow_accessed_mask;
184 static u64 __read_mostly shadow_dirty_mask;
186 static inline u64 rsvd_bits(int s, int e)
188 return ((1ULL << (e - s + 1)) - 1) << s;
191 void kvm_mmu_set_nonpresent_ptes(u64 trap_pte, u64 notrap_pte)
193 shadow_trap_nonpresent_pte = trap_pte;
194 shadow_notrap_nonpresent_pte = notrap_pte;
196 EXPORT_SYMBOL_GPL(kvm_mmu_set_nonpresent_ptes);
198 void kvm_mmu_set_base_ptes(u64 base_pte)
200 shadow_base_present_pte = base_pte;
202 EXPORT_SYMBOL_GPL(kvm_mmu_set_base_ptes);
204 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
205 u64 dirty_mask, u64 nx_mask, u64 x_mask)
207 shadow_user_mask = user_mask;
208 shadow_accessed_mask = accessed_mask;
209 shadow_dirty_mask = dirty_mask;
210 shadow_nx_mask = nx_mask;
211 shadow_x_mask = x_mask;
213 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
215 static int is_write_protection(struct kvm_vcpu *vcpu)
217 return vcpu->arch.cr0 & X86_CR0_WP;
220 static int is_cpuid_PSE36(void)
222 return 1;
225 static int is_nx(struct kvm_vcpu *vcpu)
227 return vcpu->arch.shadow_efer & EFER_NX;
230 static int is_shadow_present_pte(u64 pte)
232 return pte != shadow_trap_nonpresent_pte
233 && pte != shadow_notrap_nonpresent_pte;
236 static int is_large_pte(u64 pte)
238 return pte & PT_PAGE_SIZE_MASK;
241 static int is_writeble_pte(unsigned long pte)
243 return pte & PT_WRITABLE_MASK;
246 static int is_dirty_gpte(unsigned long pte)
248 return pte & PT_DIRTY_MASK;
251 static int is_rmap_spte(u64 pte)
253 return is_shadow_present_pte(pte);
256 static int is_last_spte(u64 pte, int level)
258 if (level == PT_PAGE_TABLE_LEVEL)
259 return 1;
260 if (level == PT_DIRECTORY_LEVEL && is_large_pte(pte))
261 return 1;
262 return 0;
265 static pfn_t spte_to_pfn(u64 pte)
267 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
270 static gfn_t pse36_gfn_delta(u32 gpte)
272 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
274 return (gpte & PT32_DIR_PSE36_MASK) << shift;
277 static void __set_spte(u64 *sptep, u64 spte)
279 #ifdef CONFIG_X86_64
280 set_64bit((unsigned long *)sptep, spte);
281 #else
282 set_64bit((unsigned long long *)sptep, spte);
283 #endif
286 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
287 struct kmem_cache *base_cache, int min)
289 void *obj;
291 if (cache->nobjs >= min)
292 return 0;
293 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
294 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
295 if (!obj)
296 return -ENOMEM;
297 cache->objects[cache->nobjs++] = obj;
299 return 0;
302 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
304 while (mc->nobjs)
305 kfree(mc->objects[--mc->nobjs]);
308 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
309 int min)
311 struct page *page;
313 if (cache->nobjs >= min)
314 return 0;
315 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
316 page = alloc_page(GFP_KERNEL);
317 if (!page)
318 return -ENOMEM;
319 set_page_private(page, 0);
320 cache->objects[cache->nobjs++] = page_address(page);
322 return 0;
325 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
327 while (mc->nobjs)
328 free_page((unsigned long)mc->objects[--mc->nobjs]);
331 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
333 int r;
335 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_chain_cache,
336 pte_chain_cache, 4);
337 if (r)
338 goto out;
339 r = mmu_topup_memory_cache(&vcpu->arch.mmu_rmap_desc_cache,
340 rmap_desc_cache, 4);
341 if (r)
342 goto out;
343 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
344 if (r)
345 goto out;
346 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
347 mmu_page_header_cache, 4);
348 out:
349 return r;
352 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
354 mmu_free_memory_cache(&vcpu->arch.mmu_pte_chain_cache);
355 mmu_free_memory_cache(&vcpu->arch.mmu_rmap_desc_cache);
356 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
357 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
360 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc,
361 size_t size)
363 void *p;
365 BUG_ON(!mc->nobjs);
366 p = mc->objects[--mc->nobjs];
367 return p;
370 static struct kvm_pte_chain *mmu_alloc_pte_chain(struct kvm_vcpu *vcpu)
372 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_chain_cache,
373 sizeof(struct kvm_pte_chain));
376 static void mmu_free_pte_chain(struct kvm_pte_chain *pc)
378 kfree(pc);
381 static struct kvm_rmap_desc *mmu_alloc_rmap_desc(struct kvm_vcpu *vcpu)
383 return mmu_memory_cache_alloc(&vcpu->arch.mmu_rmap_desc_cache,
384 sizeof(struct kvm_rmap_desc));
387 static void mmu_free_rmap_desc(struct kvm_rmap_desc *rd)
389 kfree(rd);
393 * Return the pointer to the largepage write count for a given
394 * gfn, handling slots that are not large page aligned.
396 static int *slot_largepage_idx(gfn_t gfn, struct kvm_memory_slot *slot)
398 unsigned long idx;
400 idx = (gfn / KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL)) -
401 (slot->base_gfn / KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL));
402 return &slot->lpage_info[0][idx].write_count;
405 static void account_shadowed(struct kvm *kvm, gfn_t gfn)
407 int *write_count;
409 gfn = unalias_gfn(kvm, gfn);
410 write_count = slot_largepage_idx(gfn,
411 gfn_to_memslot_unaliased(kvm, gfn));
412 *write_count += 1;
415 static void unaccount_shadowed(struct kvm *kvm, gfn_t gfn)
417 int *write_count;
419 gfn = unalias_gfn(kvm, gfn);
420 write_count = slot_largepage_idx(gfn,
421 gfn_to_memslot_unaliased(kvm, gfn));
422 *write_count -= 1;
423 WARN_ON(*write_count < 0);
426 static int has_wrprotected_page(struct kvm *kvm, gfn_t gfn)
428 struct kvm_memory_slot *slot;
429 int *largepage_idx;
431 gfn = unalias_gfn(kvm, gfn);
432 slot = gfn_to_memslot_unaliased(kvm, gfn);
433 if (slot) {
434 largepage_idx = slot_largepage_idx(gfn, slot);
435 return *largepage_idx;
438 return 1;
441 static int host_largepage_backed(struct kvm *kvm, gfn_t gfn)
443 struct vm_area_struct *vma;
444 unsigned long addr;
445 int ret = 0;
447 addr = gfn_to_hva(kvm, gfn);
448 if (kvm_is_error_hva(addr))
449 return ret;
451 down_read(&current->mm->mmap_sem);
452 vma = find_vma(current->mm, addr);
453 if (vma && is_vm_hugetlb_page(vma))
454 ret = 1;
455 up_read(&current->mm->mmap_sem);
457 return ret;
460 static int is_largepage_backed(struct kvm_vcpu *vcpu, gfn_t large_gfn)
462 struct kvm_memory_slot *slot;
464 if (has_wrprotected_page(vcpu->kvm, large_gfn))
465 return 0;
467 if (!host_largepage_backed(vcpu->kvm, large_gfn))
468 return 0;
470 slot = gfn_to_memslot(vcpu->kvm, large_gfn);
471 if (slot && slot->dirty_bitmap)
472 return 0;
474 return 1;
478 * Take gfn and return the reverse mapping to it.
479 * Note: gfn must be unaliased before this function get called
482 static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn, int lpage)
484 struct kvm_memory_slot *slot;
485 unsigned long idx;
487 slot = gfn_to_memslot(kvm, gfn);
488 if (!lpage)
489 return &slot->rmap[gfn - slot->base_gfn];
491 idx = (gfn / KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL)) -
492 (slot->base_gfn / KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL));
494 return &slot->lpage_info[0][idx].rmap_pde;
498 * Reverse mapping data structures:
500 * If rmapp bit zero is zero, then rmapp point to the shadw page table entry
501 * that points to page_address(page).
503 * If rmapp bit zero is one, (then rmap & ~1) points to a struct kvm_rmap_desc
504 * containing more mappings.
506 * Returns the number of rmap entries before the spte was added or zero if
507 * the spte was not added.
510 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn, int lpage)
512 struct kvm_mmu_page *sp;
513 struct kvm_rmap_desc *desc;
514 unsigned long *rmapp;
515 int i, count = 0;
517 if (!is_rmap_spte(*spte))
518 return count;
519 gfn = unalias_gfn(vcpu->kvm, gfn);
520 sp = page_header(__pa(spte));
521 sp->gfns[spte - sp->spt] = gfn;
522 rmapp = gfn_to_rmap(vcpu->kvm, gfn, lpage);
523 if (!*rmapp) {
524 rmap_printk("rmap_add: %p %llx 0->1\n", spte, *spte);
525 *rmapp = (unsigned long)spte;
526 } else if (!(*rmapp & 1)) {
527 rmap_printk("rmap_add: %p %llx 1->many\n", spte, *spte);
528 desc = mmu_alloc_rmap_desc(vcpu);
529 desc->sptes[0] = (u64 *)*rmapp;
530 desc->sptes[1] = spte;
531 *rmapp = (unsigned long)desc | 1;
532 } else {
533 rmap_printk("rmap_add: %p %llx many->many\n", spte, *spte);
534 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
535 while (desc->sptes[RMAP_EXT-1] && desc->more) {
536 desc = desc->more;
537 count += RMAP_EXT;
539 if (desc->sptes[RMAP_EXT-1]) {
540 desc->more = mmu_alloc_rmap_desc(vcpu);
541 desc = desc->more;
543 for (i = 0; desc->sptes[i]; ++i)
545 desc->sptes[i] = spte;
547 return count;
550 static void rmap_desc_remove_entry(unsigned long *rmapp,
551 struct kvm_rmap_desc *desc,
552 int i,
553 struct kvm_rmap_desc *prev_desc)
555 int j;
557 for (j = RMAP_EXT - 1; !desc->sptes[j] && j > i; --j)
559 desc->sptes[i] = desc->sptes[j];
560 desc->sptes[j] = NULL;
561 if (j != 0)
562 return;
563 if (!prev_desc && !desc->more)
564 *rmapp = (unsigned long)desc->sptes[0];
565 else
566 if (prev_desc)
567 prev_desc->more = desc->more;
568 else
569 *rmapp = (unsigned long)desc->more | 1;
570 mmu_free_rmap_desc(desc);
573 static void rmap_remove(struct kvm *kvm, u64 *spte)
575 struct kvm_rmap_desc *desc;
576 struct kvm_rmap_desc *prev_desc;
577 struct kvm_mmu_page *sp;
578 pfn_t pfn;
579 unsigned long *rmapp;
580 int i;
582 if (!is_rmap_spte(*spte))
583 return;
584 sp = page_header(__pa(spte));
585 pfn = spte_to_pfn(*spte);
586 if (*spte & shadow_accessed_mask)
587 kvm_set_pfn_accessed(pfn);
588 if (is_writeble_pte(*spte))
589 kvm_release_pfn_dirty(pfn);
590 else
591 kvm_release_pfn_clean(pfn);
592 rmapp = gfn_to_rmap(kvm, sp->gfns[spte - sp->spt], is_large_pte(*spte));
593 if (!*rmapp) {
594 printk(KERN_ERR "rmap_remove: %p %llx 0->BUG\n", spte, *spte);
595 BUG();
596 } else if (!(*rmapp & 1)) {
597 rmap_printk("rmap_remove: %p %llx 1->0\n", spte, *spte);
598 if ((u64 *)*rmapp != spte) {
599 printk(KERN_ERR "rmap_remove: %p %llx 1->BUG\n",
600 spte, *spte);
601 BUG();
603 *rmapp = 0;
604 } else {
605 rmap_printk("rmap_remove: %p %llx many->many\n", spte, *spte);
606 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
607 prev_desc = NULL;
608 while (desc) {
609 for (i = 0; i < RMAP_EXT && desc->sptes[i]; ++i)
610 if (desc->sptes[i] == spte) {
611 rmap_desc_remove_entry(rmapp,
612 desc, i,
613 prev_desc);
614 return;
616 prev_desc = desc;
617 desc = desc->more;
619 BUG();
623 static u64 *rmap_next(struct kvm *kvm, unsigned long *rmapp, u64 *spte)
625 struct kvm_rmap_desc *desc;
626 struct kvm_rmap_desc *prev_desc;
627 u64 *prev_spte;
628 int i;
630 if (!*rmapp)
631 return NULL;
632 else if (!(*rmapp & 1)) {
633 if (!spte)
634 return (u64 *)*rmapp;
635 return NULL;
637 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
638 prev_desc = NULL;
639 prev_spte = NULL;
640 while (desc) {
641 for (i = 0; i < RMAP_EXT && desc->sptes[i]; ++i) {
642 if (prev_spte == spte)
643 return desc->sptes[i];
644 prev_spte = desc->sptes[i];
646 desc = desc->more;
648 return NULL;
651 static int rmap_write_protect(struct kvm *kvm, u64 gfn)
653 unsigned long *rmapp;
654 u64 *spte;
655 int write_protected = 0;
657 gfn = unalias_gfn(kvm, gfn);
658 rmapp = gfn_to_rmap(kvm, gfn, 0);
660 spte = rmap_next(kvm, rmapp, NULL);
661 while (spte) {
662 BUG_ON(!spte);
663 BUG_ON(!(*spte & PT_PRESENT_MASK));
664 rmap_printk("rmap_write_protect: spte %p %llx\n", spte, *spte);
665 if (is_writeble_pte(*spte)) {
666 __set_spte(spte, *spte & ~PT_WRITABLE_MASK);
667 write_protected = 1;
669 spte = rmap_next(kvm, rmapp, spte);
671 if (write_protected) {
672 pfn_t pfn;
674 spte = rmap_next(kvm, rmapp, NULL);
675 pfn = spte_to_pfn(*spte);
676 kvm_set_pfn_dirty(pfn);
679 /* check for huge page mappings */
680 rmapp = gfn_to_rmap(kvm, gfn, 1);
681 spte = rmap_next(kvm, rmapp, NULL);
682 while (spte) {
683 BUG_ON(!spte);
684 BUG_ON(!(*spte & PT_PRESENT_MASK));
685 BUG_ON((*spte & (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK)) != (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK));
686 pgprintk("rmap_write_protect(large): spte %p %llx %lld\n", spte, *spte, gfn);
687 if (is_writeble_pte(*spte)) {
688 rmap_remove(kvm, spte);
689 --kvm->stat.lpages;
690 __set_spte(spte, shadow_trap_nonpresent_pte);
691 spte = NULL;
692 write_protected = 1;
694 spte = rmap_next(kvm, rmapp, spte);
697 return write_protected;
700 static int kvm_unmap_rmapp(struct kvm *kvm, unsigned long *rmapp)
702 u64 *spte;
703 int need_tlb_flush = 0;
705 while ((spte = rmap_next(kvm, rmapp, NULL))) {
706 BUG_ON(!(*spte & PT_PRESENT_MASK));
707 rmap_printk("kvm_rmap_unmap_hva: spte %p %llx\n", spte, *spte);
708 rmap_remove(kvm, spte);
709 __set_spte(spte, shadow_trap_nonpresent_pte);
710 need_tlb_flush = 1;
712 return need_tlb_flush;
715 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
716 int (*handler)(struct kvm *kvm, unsigned long *rmapp))
718 int i;
719 int retval = 0;
722 * If mmap_sem isn't taken, we can look the memslots with only
723 * the mmu_lock by skipping over the slots with userspace_addr == 0.
725 for (i = 0; i < kvm->nmemslots; i++) {
726 struct kvm_memory_slot *memslot = &kvm->memslots[i];
727 unsigned long start = memslot->userspace_addr;
728 unsigned long end;
730 /* mmu_lock protects userspace_addr */
731 if (!start)
732 continue;
734 end = start + (memslot->npages << PAGE_SHIFT);
735 if (hva >= start && hva < end) {
736 gfn_t gfn_offset = (hva - start) >> PAGE_SHIFT;
737 int idx = gfn_offset /
738 KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL);
739 retval |= handler(kvm, &memslot->rmap[gfn_offset]);
740 retval |= handler(kvm,
741 &memslot->lpage_info[0][idx].rmap_pde);
745 return retval;
748 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
750 return kvm_handle_hva(kvm, hva, kvm_unmap_rmapp);
753 static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp)
755 u64 *spte;
756 int young = 0;
758 /* always return old for EPT */
759 if (!shadow_accessed_mask)
760 return 0;
762 spte = rmap_next(kvm, rmapp, NULL);
763 while (spte) {
764 int _young;
765 u64 _spte = *spte;
766 BUG_ON(!(_spte & PT_PRESENT_MASK));
767 _young = _spte & PT_ACCESSED_MASK;
768 if (_young) {
769 young = 1;
770 clear_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
772 spte = rmap_next(kvm, rmapp, spte);
774 return young;
777 #define RMAP_RECYCLE_THRESHOLD 1000
779 static void rmap_recycle(struct kvm_vcpu *vcpu, gfn_t gfn, int lpage)
781 unsigned long *rmapp;
783 gfn = unalias_gfn(vcpu->kvm, gfn);
784 rmapp = gfn_to_rmap(vcpu->kvm, gfn, lpage);
786 kvm_unmap_rmapp(vcpu->kvm, rmapp);
787 kvm_flush_remote_tlbs(vcpu->kvm);
790 int kvm_age_hva(struct kvm *kvm, unsigned long hva)
792 return kvm_handle_hva(kvm, hva, kvm_age_rmapp);
795 #ifdef MMU_DEBUG
796 static int is_empty_shadow_page(u64 *spt)
798 u64 *pos;
799 u64 *end;
801 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
802 if (is_shadow_present_pte(*pos)) {
803 printk(KERN_ERR "%s: %p %llx\n", __func__,
804 pos, *pos);
805 return 0;
807 return 1;
809 #endif
811 static void kvm_mmu_free_page(struct kvm *kvm, struct kvm_mmu_page *sp)
813 ASSERT(is_empty_shadow_page(sp->spt));
814 list_del(&sp->link);
815 __free_page(virt_to_page(sp->spt));
816 __free_page(virt_to_page(sp->gfns));
817 kfree(sp);
818 ++kvm->arch.n_free_mmu_pages;
821 static unsigned kvm_page_table_hashfn(gfn_t gfn)
823 return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
826 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
827 u64 *parent_pte)
829 struct kvm_mmu_page *sp;
831 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache, sizeof *sp);
832 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
833 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
834 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
835 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
836 INIT_LIST_HEAD(&sp->oos_link);
837 bitmap_zero(sp->slot_bitmap, KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS);
838 sp->multimapped = 0;
839 sp->parent_pte = parent_pte;
840 --vcpu->kvm->arch.n_free_mmu_pages;
841 return sp;
844 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
845 struct kvm_mmu_page *sp, u64 *parent_pte)
847 struct kvm_pte_chain *pte_chain;
848 struct hlist_node *node;
849 int i;
851 if (!parent_pte)
852 return;
853 if (!sp->multimapped) {
854 u64 *old = sp->parent_pte;
856 if (!old) {
857 sp->parent_pte = parent_pte;
858 return;
860 sp->multimapped = 1;
861 pte_chain = mmu_alloc_pte_chain(vcpu);
862 INIT_HLIST_HEAD(&sp->parent_ptes);
863 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
864 pte_chain->parent_ptes[0] = old;
866 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link) {
867 if (pte_chain->parent_ptes[NR_PTE_CHAIN_ENTRIES-1])
868 continue;
869 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i)
870 if (!pte_chain->parent_ptes[i]) {
871 pte_chain->parent_ptes[i] = parent_pte;
872 return;
875 pte_chain = mmu_alloc_pte_chain(vcpu);
876 BUG_ON(!pte_chain);
877 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
878 pte_chain->parent_ptes[0] = parent_pte;
881 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
882 u64 *parent_pte)
884 struct kvm_pte_chain *pte_chain;
885 struct hlist_node *node;
886 int i;
888 if (!sp->multimapped) {
889 BUG_ON(sp->parent_pte != parent_pte);
890 sp->parent_pte = NULL;
891 return;
893 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
894 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
895 if (!pte_chain->parent_ptes[i])
896 break;
897 if (pte_chain->parent_ptes[i] != parent_pte)
898 continue;
899 while (i + 1 < NR_PTE_CHAIN_ENTRIES
900 && pte_chain->parent_ptes[i + 1]) {
901 pte_chain->parent_ptes[i]
902 = pte_chain->parent_ptes[i + 1];
903 ++i;
905 pte_chain->parent_ptes[i] = NULL;
906 if (i == 0) {
907 hlist_del(&pte_chain->link);
908 mmu_free_pte_chain(pte_chain);
909 if (hlist_empty(&sp->parent_ptes)) {
910 sp->multimapped = 0;
911 sp->parent_pte = NULL;
914 return;
916 BUG();
920 static void mmu_parent_walk(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
921 mmu_parent_walk_fn fn)
923 struct kvm_pte_chain *pte_chain;
924 struct hlist_node *node;
925 struct kvm_mmu_page *parent_sp;
926 int i;
928 if (!sp->multimapped && sp->parent_pte) {
929 parent_sp = page_header(__pa(sp->parent_pte));
930 fn(vcpu, parent_sp);
931 mmu_parent_walk(vcpu, parent_sp, fn);
932 return;
934 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
935 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
936 if (!pte_chain->parent_ptes[i])
937 break;
938 parent_sp = page_header(__pa(pte_chain->parent_ptes[i]));
939 fn(vcpu, parent_sp);
940 mmu_parent_walk(vcpu, parent_sp, fn);
944 static void kvm_mmu_update_unsync_bitmap(u64 *spte)
946 unsigned int index;
947 struct kvm_mmu_page *sp = page_header(__pa(spte));
949 index = spte - sp->spt;
950 if (!__test_and_set_bit(index, sp->unsync_child_bitmap))
951 sp->unsync_children++;
952 WARN_ON(!sp->unsync_children);
955 static void kvm_mmu_update_parents_unsync(struct kvm_mmu_page *sp)
957 struct kvm_pte_chain *pte_chain;
958 struct hlist_node *node;
959 int i;
961 if (!sp->parent_pte)
962 return;
964 if (!sp->multimapped) {
965 kvm_mmu_update_unsync_bitmap(sp->parent_pte);
966 return;
969 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
970 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
971 if (!pte_chain->parent_ptes[i])
972 break;
973 kvm_mmu_update_unsync_bitmap(pte_chain->parent_ptes[i]);
977 static int unsync_walk_fn(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
979 kvm_mmu_update_parents_unsync(sp);
980 return 1;
983 static void kvm_mmu_mark_parents_unsync(struct kvm_vcpu *vcpu,
984 struct kvm_mmu_page *sp)
986 mmu_parent_walk(vcpu, sp, unsync_walk_fn);
987 kvm_mmu_update_parents_unsync(sp);
990 static void nonpaging_prefetch_page(struct kvm_vcpu *vcpu,
991 struct kvm_mmu_page *sp)
993 int i;
995 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
996 sp->spt[i] = shadow_trap_nonpresent_pte;
999 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1000 struct kvm_mmu_page *sp)
1002 return 1;
1005 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
1009 #define KVM_PAGE_ARRAY_NR 16
1011 struct kvm_mmu_pages {
1012 struct mmu_page_and_offset {
1013 struct kvm_mmu_page *sp;
1014 unsigned int idx;
1015 } page[KVM_PAGE_ARRAY_NR];
1016 unsigned int nr;
1019 #define for_each_unsync_children(bitmap, idx) \
1020 for (idx = find_first_bit(bitmap, 512); \
1021 idx < 512; \
1022 idx = find_next_bit(bitmap, 512, idx+1))
1024 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1025 int idx)
1027 int i;
1029 if (sp->unsync)
1030 for (i=0; i < pvec->nr; i++)
1031 if (pvec->page[i].sp == sp)
1032 return 0;
1034 pvec->page[pvec->nr].sp = sp;
1035 pvec->page[pvec->nr].idx = idx;
1036 pvec->nr++;
1037 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1040 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1041 struct kvm_mmu_pages *pvec)
1043 int i, ret, nr_unsync_leaf = 0;
1045 for_each_unsync_children(sp->unsync_child_bitmap, i) {
1046 u64 ent = sp->spt[i];
1048 if (is_shadow_present_pte(ent) && !is_large_pte(ent)) {
1049 struct kvm_mmu_page *child;
1050 child = page_header(ent & PT64_BASE_ADDR_MASK);
1052 if (child->unsync_children) {
1053 if (mmu_pages_add(pvec, child, i))
1054 return -ENOSPC;
1056 ret = __mmu_unsync_walk(child, pvec);
1057 if (!ret)
1058 __clear_bit(i, sp->unsync_child_bitmap);
1059 else if (ret > 0)
1060 nr_unsync_leaf += ret;
1061 else
1062 return ret;
1065 if (child->unsync) {
1066 nr_unsync_leaf++;
1067 if (mmu_pages_add(pvec, child, i))
1068 return -ENOSPC;
1073 if (find_first_bit(sp->unsync_child_bitmap, 512) == 512)
1074 sp->unsync_children = 0;
1076 return nr_unsync_leaf;
1079 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1080 struct kvm_mmu_pages *pvec)
1082 if (!sp->unsync_children)
1083 return 0;
1085 mmu_pages_add(pvec, sp, 0);
1086 return __mmu_unsync_walk(sp, pvec);
1089 static struct kvm_mmu_page *kvm_mmu_lookup_page(struct kvm *kvm, gfn_t gfn)
1091 unsigned index;
1092 struct hlist_head *bucket;
1093 struct kvm_mmu_page *sp;
1094 struct hlist_node *node;
1096 pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1097 index = kvm_page_table_hashfn(gfn);
1098 bucket = &kvm->arch.mmu_page_hash[index];
1099 hlist_for_each_entry(sp, node, bucket, hash_link)
1100 if (sp->gfn == gfn && !sp->role.direct
1101 && !sp->role.invalid) {
1102 pgprintk("%s: found role %x\n",
1103 __func__, sp->role.word);
1104 return sp;
1106 return NULL;
1109 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1111 WARN_ON(!sp->unsync);
1112 sp->unsync = 0;
1113 --kvm->stat.mmu_unsync;
1116 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp);
1118 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1120 if (sp->role.glevels != vcpu->arch.mmu.root_level) {
1121 kvm_mmu_zap_page(vcpu->kvm, sp);
1122 return 1;
1125 trace_kvm_mmu_sync_page(sp);
1126 if (rmap_write_protect(vcpu->kvm, sp->gfn))
1127 kvm_flush_remote_tlbs(vcpu->kvm);
1128 kvm_unlink_unsync_page(vcpu->kvm, sp);
1129 if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
1130 kvm_mmu_zap_page(vcpu->kvm, sp);
1131 return 1;
1134 kvm_mmu_flush_tlb(vcpu);
1135 return 0;
1138 struct mmu_page_path {
1139 struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
1140 unsigned int idx[PT64_ROOT_LEVEL-1];
1143 #define for_each_sp(pvec, sp, parents, i) \
1144 for (i = mmu_pages_next(&pvec, &parents, -1), \
1145 sp = pvec.page[i].sp; \
1146 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
1147 i = mmu_pages_next(&pvec, &parents, i))
1149 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1150 struct mmu_page_path *parents,
1151 int i)
1153 int n;
1155 for (n = i+1; n < pvec->nr; n++) {
1156 struct kvm_mmu_page *sp = pvec->page[n].sp;
1158 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1159 parents->idx[0] = pvec->page[n].idx;
1160 return n;
1163 parents->parent[sp->role.level-2] = sp;
1164 parents->idx[sp->role.level-1] = pvec->page[n].idx;
1167 return n;
1170 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1172 struct kvm_mmu_page *sp;
1173 unsigned int level = 0;
1175 do {
1176 unsigned int idx = parents->idx[level];
1178 sp = parents->parent[level];
1179 if (!sp)
1180 return;
1182 --sp->unsync_children;
1183 WARN_ON((int)sp->unsync_children < 0);
1184 __clear_bit(idx, sp->unsync_child_bitmap);
1185 level++;
1186 } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
1189 static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
1190 struct mmu_page_path *parents,
1191 struct kvm_mmu_pages *pvec)
1193 parents->parent[parent->role.level-1] = NULL;
1194 pvec->nr = 0;
1197 static void mmu_sync_children(struct kvm_vcpu *vcpu,
1198 struct kvm_mmu_page *parent)
1200 int i;
1201 struct kvm_mmu_page *sp;
1202 struct mmu_page_path parents;
1203 struct kvm_mmu_pages pages;
1205 kvm_mmu_pages_init(parent, &parents, &pages);
1206 while (mmu_unsync_walk(parent, &pages)) {
1207 int protected = 0;
1209 for_each_sp(pages, sp, parents, i)
1210 protected |= rmap_write_protect(vcpu->kvm, sp->gfn);
1212 if (protected)
1213 kvm_flush_remote_tlbs(vcpu->kvm);
1215 for_each_sp(pages, sp, parents, i) {
1216 kvm_sync_page(vcpu, sp);
1217 mmu_pages_clear_parents(&parents);
1219 cond_resched_lock(&vcpu->kvm->mmu_lock);
1220 kvm_mmu_pages_init(parent, &parents, &pages);
1224 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
1225 gfn_t gfn,
1226 gva_t gaddr,
1227 unsigned level,
1228 int direct,
1229 unsigned access,
1230 u64 *parent_pte)
1232 union kvm_mmu_page_role role;
1233 unsigned index;
1234 unsigned quadrant;
1235 struct hlist_head *bucket;
1236 struct kvm_mmu_page *sp;
1237 struct hlist_node *node, *tmp;
1239 role = vcpu->arch.mmu.base_role;
1240 role.level = level;
1241 role.direct = direct;
1242 role.access = access;
1243 if (vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
1244 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
1245 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
1246 role.quadrant = quadrant;
1248 index = kvm_page_table_hashfn(gfn);
1249 bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1250 hlist_for_each_entry_safe(sp, node, tmp, bucket, hash_link)
1251 if (sp->gfn == gfn) {
1252 if (sp->unsync)
1253 if (kvm_sync_page(vcpu, sp))
1254 continue;
1256 if (sp->role.word != role.word)
1257 continue;
1259 mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1260 if (sp->unsync_children) {
1261 set_bit(KVM_REQ_MMU_SYNC, &vcpu->requests);
1262 kvm_mmu_mark_parents_unsync(vcpu, sp);
1264 trace_kvm_mmu_get_page(sp, false);
1265 return sp;
1267 ++vcpu->kvm->stat.mmu_cache_miss;
1268 sp = kvm_mmu_alloc_page(vcpu, parent_pte);
1269 if (!sp)
1270 return sp;
1271 sp->gfn = gfn;
1272 sp->role = role;
1273 hlist_add_head(&sp->hash_link, bucket);
1274 if (!direct) {
1275 if (rmap_write_protect(vcpu->kvm, gfn))
1276 kvm_flush_remote_tlbs(vcpu->kvm);
1277 account_shadowed(vcpu->kvm, gfn);
1279 if (shadow_trap_nonpresent_pte != shadow_notrap_nonpresent_pte)
1280 vcpu->arch.mmu.prefetch_page(vcpu, sp);
1281 else
1282 nonpaging_prefetch_page(vcpu, sp);
1283 trace_kvm_mmu_get_page(sp, true);
1284 return sp;
1287 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
1288 struct kvm_vcpu *vcpu, u64 addr)
1290 iterator->addr = addr;
1291 iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
1292 iterator->level = vcpu->arch.mmu.shadow_root_level;
1293 if (iterator->level == PT32E_ROOT_LEVEL) {
1294 iterator->shadow_addr
1295 = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
1296 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
1297 --iterator->level;
1298 if (!iterator->shadow_addr)
1299 iterator->level = 0;
1303 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
1305 if (iterator->level < PT_PAGE_TABLE_LEVEL)
1306 return false;
1308 if (iterator->level == PT_PAGE_TABLE_LEVEL)
1309 if (is_large_pte(*iterator->sptep))
1310 return false;
1312 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
1313 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
1314 return true;
1317 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
1319 iterator->shadow_addr = *iterator->sptep & PT64_BASE_ADDR_MASK;
1320 --iterator->level;
1323 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
1324 struct kvm_mmu_page *sp)
1326 unsigned i;
1327 u64 *pt;
1328 u64 ent;
1330 pt = sp->spt;
1332 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1333 ent = pt[i];
1335 if (is_shadow_present_pte(ent)) {
1336 if (!is_last_spte(ent, sp->role.level)) {
1337 ent &= PT64_BASE_ADDR_MASK;
1338 mmu_page_remove_parent_pte(page_header(ent),
1339 &pt[i]);
1340 } else {
1341 if (is_large_pte(ent))
1342 --kvm->stat.lpages;
1343 rmap_remove(kvm, &pt[i]);
1346 pt[i] = shadow_trap_nonpresent_pte;
1350 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
1352 mmu_page_remove_parent_pte(sp, parent_pte);
1355 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
1357 int i;
1358 struct kvm_vcpu *vcpu;
1360 kvm_for_each_vcpu(i, vcpu, kvm)
1361 vcpu->arch.last_pte_updated = NULL;
1364 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
1366 u64 *parent_pte;
1368 while (sp->multimapped || sp->parent_pte) {
1369 if (!sp->multimapped)
1370 parent_pte = sp->parent_pte;
1371 else {
1372 struct kvm_pte_chain *chain;
1374 chain = container_of(sp->parent_ptes.first,
1375 struct kvm_pte_chain, link);
1376 parent_pte = chain->parent_ptes[0];
1378 BUG_ON(!parent_pte);
1379 kvm_mmu_put_page(sp, parent_pte);
1380 __set_spte(parent_pte, shadow_trap_nonpresent_pte);
1384 static int mmu_zap_unsync_children(struct kvm *kvm,
1385 struct kvm_mmu_page *parent)
1387 int i, zapped = 0;
1388 struct mmu_page_path parents;
1389 struct kvm_mmu_pages pages;
1391 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
1392 return 0;
1394 kvm_mmu_pages_init(parent, &parents, &pages);
1395 while (mmu_unsync_walk(parent, &pages)) {
1396 struct kvm_mmu_page *sp;
1398 for_each_sp(pages, sp, parents, i) {
1399 kvm_mmu_zap_page(kvm, sp);
1400 mmu_pages_clear_parents(&parents);
1402 zapped += pages.nr;
1403 kvm_mmu_pages_init(parent, &parents, &pages);
1406 return zapped;
1409 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1411 int ret;
1413 trace_kvm_mmu_zap_page(sp);
1414 ++kvm->stat.mmu_shadow_zapped;
1415 ret = mmu_zap_unsync_children(kvm, sp);
1416 kvm_mmu_page_unlink_children(kvm, sp);
1417 kvm_mmu_unlink_parents(kvm, sp);
1418 kvm_flush_remote_tlbs(kvm);
1419 if (!sp->role.invalid && !sp->role.direct)
1420 unaccount_shadowed(kvm, sp->gfn);
1421 if (sp->unsync)
1422 kvm_unlink_unsync_page(kvm, sp);
1423 if (!sp->root_count) {
1424 hlist_del(&sp->hash_link);
1425 kvm_mmu_free_page(kvm, sp);
1426 } else {
1427 sp->role.invalid = 1;
1428 list_move(&sp->link, &kvm->arch.active_mmu_pages);
1429 kvm_reload_remote_mmus(kvm);
1431 kvm_mmu_reset_last_pte_updated(kvm);
1432 return ret;
1436 * Changing the number of mmu pages allocated to the vm
1437 * Note: if kvm_nr_mmu_pages is too small, you will get dead lock
1439 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int kvm_nr_mmu_pages)
1441 int used_pages;
1443 used_pages = kvm->arch.n_alloc_mmu_pages - kvm->arch.n_free_mmu_pages;
1444 used_pages = max(0, used_pages);
1447 * If we set the number of mmu pages to be smaller be than the
1448 * number of actived pages , we must to free some mmu pages before we
1449 * change the value
1452 if (used_pages > kvm_nr_mmu_pages) {
1453 while (used_pages > kvm_nr_mmu_pages) {
1454 struct kvm_mmu_page *page;
1456 page = container_of(kvm->arch.active_mmu_pages.prev,
1457 struct kvm_mmu_page, link);
1458 kvm_mmu_zap_page(kvm, page);
1459 used_pages--;
1461 kvm->arch.n_free_mmu_pages = 0;
1463 else
1464 kvm->arch.n_free_mmu_pages += kvm_nr_mmu_pages
1465 - kvm->arch.n_alloc_mmu_pages;
1467 kvm->arch.n_alloc_mmu_pages = kvm_nr_mmu_pages;
1470 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
1472 unsigned index;
1473 struct hlist_head *bucket;
1474 struct kvm_mmu_page *sp;
1475 struct hlist_node *node, *n;
1476 int r;
1478 pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1479 r = 0;
1480 index = kvm_page_table_hashfn(gfn);
1481 bucket = &kvm->arch.mmu_page_hash[index];
1482 hlist_for_each_entry_safe(sp, node, n, bucket, hash_link)
1483 if (sp->gfn == gfn && !sp->role.direct) {
1484 pgprintk("%s: gfn %lx role %x\n", __func__, gfn,
1485 sp->role.word);
1486 r = 1;
1487 if (kvm_mmu_zap_page(kvm, sp))
1488 n = bucket->first;
1490 return r;
1493 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
1495 unsigned index;
1496 struct hlist_head *bucket;
1497 struct kvm_mmu_page *sp;
1498 struct hlist_node *node, *nn;
1500 index = kvm_page_table_hashfn(gfn);
1501 bucket = &kvm->arch.mmu_page_hash[index];
1502 hlist_for_each_entry_safe(sp, node, nn, bucket, hash_link) {
1503 if (sp->gfn == gfn && !sp->role.direct
1504 && !sp->role.invalid) {
1505 pgprintk("%s: zap %lx %x\n",
1506 __func__, gfn, sp->role.word);
1507 kvm_mmu_zap_page(kvm, sp);
1512 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
1514 int slot = memslot_id(kvm, gfn_to_memslot(kvm, gfn));
1515 struct kvm_mmu_page *sp = page_header(__pa(pte));
1517 __set_bit(slot, sp->slot_bitmap);
1520 static void mmu_convert_notrap(struct kvm_mmu_page *sp)
1522 int i;
1523 u64 *pt = sp->spt;
1525 if (shadow_trap_nonpresent_pte == shadow_notrap_nonpresent_pte)
1526 return;
1528 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1529 if (pt[i] == shadow_notrap_nonpresent_pte)
1530 __set_spte(&pt[i], shadow_trap_nonpresent_pte);
1534 struct page *gva_to_page(struct kvm_vcpu *vcpu, gva_t gva)
1536 struct page *page;
1538 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1540 if (gpa == UNMAPPED_GVA)
1541 return NULL;
1543 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1545 return page;
1549 * The function is based on mtrr_type_lookup() in
1550 * arch/x86/kernel/cpu/mtrr/generic.c
1552 static int get_mtrr_type(struct mtrr_state_type *mtrr_state,
1553 u64 start, u64 end)
1555 int i;
1556 u64 base, mask;
1557 u8 prev_match, curr_match;
1558 int num_var_ranges = KVM_NR_VAR_MTRR;
1560 if (!mtrr_state->enabled)
1561 return 0xFF;
1563 /* Make end inclusive end, instead of exclusive */
1564 end--;
1566 /* Look in fixed ranges. Just return the type as per start */
1567 if (mtrr_state->have_fixed && (start < 0x100000)) {
1568 int idx;
1570 if (start < 0x80000) {
1571 idx = 0;
1572 idx += (start >> 16);
1573 return mtrr_state->fixed_ranges[idx];
1574 } else if (start < 0xC0000) {
1575 idx = 1 * 8;
1576 idx += ((start - 0x80000) >> 14);
1577 return mtrr_state->fixed_ranges[idx];
1578 } else if (start < 0x1000000) {
1579 idx = 3 * 8;
1580 idx += ((start - 0xC0000) >> 12);
1581 return mtrr_state->fixed_ranges[idx];
1586 * Look in variable ranges
1587 * Look of multiple ranges matching this address and pick type
1588 * as per MTRR precedence
1590 if (!(mtrr_state->enabled & 2))
1591 return mtrr_state->def_type;
1593 prev_match = 0xFF;
1594 for (i = 0; i < num_var_ranges; ++i) {
1595 unsigned short start_state, end_state;
1597 if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11)))
1598 continue;
1600 base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) +
1601 (mtrr_state->var_ranges[i].base_lo & PAGE_MASK);
1602 mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) +
1603 (mtrr_state->var_ranges[i].mask_lo & PAGE_MASK);
1605 start_state = ((start & mask) == (base & mask));
1606 end_state = ((end & mask) == (base & mask));
1607 if (start_state != end_state)
1608 return 0xFE;
1610 if ((start & mask) != (base & mask))
1611 continue;
1613 curr_match = mtrr_state->var_ranges[i].base_lo & 0xff;
1614 if (prev_match == 0xFF) {
1615 prev_match = curr_match;
1616 continue;
1619 if (prev_match == MTRR_TYPE_UNCACHABLE ||
1620 curr_match == MTRR_TYPE_UNCACHABLE)
1621 return MTRR_TYPE_UNCACHABLE;
1623 if ((prev_match == MTRR_TYPE_WRBACK &&
1624 curr_match == MTRR_TYPE_WRTHROUGH) ||
1625 (prev_match == MTRR_TYPE_WRTHROUGH &&
1626 curr_match == MTRR_TYPE_WRBACK)) {
1627 prev_match = MTRR_TYPE_WRTHROUGH;
1628 curr_match = MTRR_TYPE_WRTHROUGH;
1631 if (prev_match != curr_match)
1632 return MTRR_TYPE_UNCACHABLE;
1635 if (prev_match != 0xFF)
1636 return prev_match;
1638 return mtrr_state->def_type;
1641 u8 kvm_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn)
1643 u8 mtrr;
1645 mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT,
1646 (gfn << PAGE_SHIFT) + PAGE_SIZE);
1647 if (mtrr == 0xfe || mtrr == 0xff)
1648 mtrr = MTRR_TYPE_WRBACK;
1649 return mtrr;
1651 EXPORT_SYMBOL_GPL(kvm_get_guest_memory_type);
1653 static int kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1655 unsigned index;
1656 struct hlist_head *bucket;
1657 struct kvm_mmu_page *s;
1658 struct hlist_node *node, *n;
1660 trace_kvm_mmu_unsync_page(sp);
1661 index = kvm_page_table_hashfn(sp->gfn);
1662 bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1663 /* don't unsync if pagetable is shadowed with multiple roles */
1664 hlist_for_each_entry_safe(s, node, n, bucket, hash_link) {
1665 if (s->gfn != sp->gfn || s->role.direct)
1666 continue;
1667 if (s->role.word != sp->role.word)
1668 return 1;
1670 ++vcpu->kvm->stat.mmu_unsync;
1671 sp->unsync = 1;
1673 kvm_mmu_mark_parents_unsync(vcpu, sp);
1675 mmu_convert_notrap(sp);
1676 return 0;
1679 static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
1680 bool can_unsync)
1682 struct kvm_mmu_page *shadow;
1684 shadow = kvm_mmu_lookup_page(vcpu->kvm, gfn);
1685 if (shadow) {
1686 if (shadow->role.level != PT_PAGE_TABLE_LEVEL)
1687 return 1;
1688 if (shadow->unsync)
1689 return 0;
1690 if (can_unsync && oos_shadow)
1691 return kvm_unsync_page(vcpu, shadow);
1692 return 1;
1694 return 0;
1697 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
1698 unsigned pte_access, int user_fault,
1699 int write_fault, int dirty, int largepage,
1700 gfn_t gfn, pfn_t pfn, bool speculative,
1701 bool can_unsync)
1703 u64 spte;
1704 int ret = 0;
1707 * We don't set the accessed bit, since we sometimes want to see
1708 * whether the guest actually used the pte (in order to detect
1709 * demand paging).
1711 spte = shadow_base_present_pte | shadow_dirty_mask;
1712 if (!speculative)
1713 spte |= shadow_accessed_mask;
1714 if (!dirty)
1715 pte_access &= ~ACC_WRITE_MASK;
1716 if (pte_access & ACC_EXEC_MASK)
1717 spte |= shadow_x_mask;
1718 else
1719 spte |= shadow_nx_mask;
1720 if (pte_access & ACC_USER_MASK)
1721 spte |= shadow_user_mask;
1722 if (largepage)
1723 spte |= PT_PAGE_SIZE_MASK;
1724 if (tdp_enabled)
1725 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
1726 kvm_is_mmio_pfn(pfn));
1728 spte |= (u64)pfn << PAGE_SHIFT;
1730 if ((pte_access & ACC_WRITE_MASK)
1731 || (write_fault && !is_write_protection(vcpu) && !user_fault)) {
1733 if (largepage && has_wrprotected_page(vcpu->kvm, gfn)) {
1734 ret = 1;
1735 spte = shadow_trap_nonpresent_pte;
1736 goto set_pte;
1739 spte |= PT_WRITABLE_MASK;
1742 * Optimization: for pte sync, if spte was writable the hash
1743 * lookup is unnecessary (and expensive). Write protection
1744 * is responsibility of mmu_get_page / kvm_sync_page.
1745 * Same reasoning can be applied to dirty page accounting.
1747 if (!can_unsync && is_writeble_pte(*sptep))
1748 goto set_pte;
1750 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
1751 pgprintk("%s: found shadow page for %lx, marking ro\n",
1752 __func__, gfn);
1753 ret = 1;
1754 pte_access &= ~ACC_WRITE_MASK;
1755 if (is_writeble_pte(spte))
1756 spte &= ~PT_WRITABLE_MASK;
1760 if (pte_access & ACC_WRITE_MASK)
1761 mark_page_dirty(vcpu->kvm, gfn);
1763 set_pte:
1764 __set_spte(sptep, spte);
1765 return ret;
1768 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
1769 unsigned pt_access, unsigned pte_access,
1770 int user_fault, int write_fault, int dirty,
1771 int *ptwrite, int largepage, gfn_t gfn,
1772 pfn_t pfn, bool speculative)
1774 int was_rmapped = 0;
1775 int was_writeble = is_writeble_pte(*sptep);
1776 int rmap_count;
1778 pgprintk("%s: spte %llx access %x write_fault %d"
1779 " user_fault %d gfn %lx\n",
1780 __func__, *sptep, pt_access,
1781 write_fault, user_fault, gfn);
1783 if (is_rmap_spte(*sptep)) {
1785 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
1786 * the parent of the now unreachable PTE.
1788 if (largepage && !is_large_pte(*sptep)) {
1789 struct kvm_mmu_page *child;
1790 u64 pte = *sptep;
1792 child = page_header(pte & PT64_BASE_ADDR_MASK);
1793 mmu_page_remove_parent_pte(child, sptep);
1794 } else if (pfn != spte_to_pfn(*sptep)) {
1795 pgprintk("hfn old %lx new %lx\n",
1796 spte_to_pfn(*sptep), pfn);
1797 rmap_remove(vcpu->kvm, sptep);
1798 } else
1799 was_rmapped = 1;
1801 if (set_spte(vcpu, sptep, pte_access, user_fault, write_fault,
1802 dirty, largepage, gfn, pfn, speculative, true)) {
1803 if (write_fault)
1804 *ptwrite = 1;
1805 kvm_x86_ops->tlb_flush(vcpu);
1808 pgprintk("%s: setting spte %llx\n", __func__, *sptep);
1809 pgprintk("instantiating %s PTE (%s) at %ld (%llx) addr %p\n",
1810 is_large_pte(*sptep)? "2MB" : "4kB",
1811 is_present_pte(*sptep)?"RW":"R", gfn,
1812 *shadow_pte, sptep);
1813 if (!was_rmapped && is_large_pte(*sptep))
1814 ++vcpu->kvm->stat.lpages;
1816 page_header_update_slot(vcpu->kvm, sptep, gfn);
1817 if (!was_rmapped) {
1818 rmap_count = rmap_add(vcpu, sptep, gfn, largepage);
1819 if (!is_rmap_spte(*sptep))
1820 kvm_release_pfn_clean(pfn);
1821 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
1822 rmap_recycle(vcpu, gfn, largepage);
1823 } else {
1824 if (was_writeble)
1825 kvm_release_pfn_dirty(pfn);
1826 else
1827 kvm_release_pfn_clean(pfn);
1829 if (speculative) {
1830 vcpu->arch.last_pte_updated = sptep;
1831 vcpu->arch.last_pte_gfn = gfn;
1835 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
1839 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
1840 int largepage, gfn_t gfn, pfn_t pfn)
1842 struct kvm_shadow_walk_iterator iterator;
1843 struct kvm_mmu_page *sp;
1844 int pt_write = 0;
1845 gfn_t pseudo_gfn;
1847 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
1848 if (iterator.level == PT_PAGE_TABLE_LEVEL
1849 || (largepage && iterator.level == PT_DIRECTORY_LEVEL)) {
1850 mmu_set_spte(vcpu, iterator.sptep, ACC_ALL, ACC_ALL,
1851 0, write, 1, &pt_write,
1852 largepage, gfn, pfn, false);
1853 ++vcpu->stat.pf_fixed;
1854 break;
1857 if (*iterator.sptep == shadow_trap_nonpresent_pte) {
1858 pseudo_gfn = (iterator.addr & PT64_DIR_BASE_ADDR_MASK) >> PAGE_SHIFT;
1859 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
1860 iterator.level - 1,
1861 1, ACC_ALL, iterator.sptep);
1862 if (!sp) {
1863 pgprintk("nonpaging_map: ENOMEM\n");
1864 kvm_release_pfn_clean(pfn);
1865 return -ENOMEM;
1868 __set_spte(iterator.sptep,
1869 __pa(sp->spt)
1870 | PT_PRESENT_MASK | PT_WRITABLE_MASK
1871 | shadow_user_mask | shadow_x_mask);
1874 return pt_write;
1877 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn)
1879 int r;
1880 int largepage = 0;
1881 pfn_t pfn;
1882 unsigned long mmu_seq;
1884 if (is_largepage_backed(vcpu, gfn &
1885 ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1))) {
1886 gfn &= ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1);
1887 largepage = 1;
1890 mmu_seq = vcpu->kvm->mmu_notifier_seq;
1891 smp_rmb();
1892 pfn = gfn_to_pfn(vcpu->kvm, gfn);
1894 /* mmio */
1895 if (is_error_pfn(pfn)) {
1896 kvm_release_pfn_clean(pfn);
1897 return 1;
1900 spin_lock(&vcpu->kvm->mmu_lock);
1901 if (mmu_notifier_retry(vcpu, mmu_seq))
1902 goto out_unlock;
1903 kvm_mmu_free_some_pages(vcpu);
1904 r = __direct_map(vcpu, v, write, largepage, gfn, pfn);
1905 spin_unlock(&vcpu->kvm->mmu_lock);
1908 return r;
1910 out_unlock:
1911 spin_unlock(&vcpu->kvm->mmu_lock);
1912 kvm_release_pfn_clean(pfn);
1913 return 0;
1917 static void mmu_free_roots(struct kvm_vcpu *vcpu)
1919 int i;
1920 struct kvm_mmu_page *sp;
1922 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1923 return;
1924 spin_lock(&vcpu->kvm->mmu_lock);
1925 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1926 hpa_t root = vcpu->arch.mmu.root_hpa;
1928 sp = page_header(root);
1929 --sp->root_count;
1930 if (!sp->root_count && sp->role.invalid)
1931 kvm_mmu_zap_page(vcpu->kvm, sp);
1932 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1933 spin_unlock(&vcpu->kvm->mmu_lock);
1934 return;
1936 for (i = 0; i < 4; ++i) {
1937 hpa_t root = vcpu->arch.mmu.pae_root[i];
1939 if (root) {
1940 root &= PT64_BASE_ADDR_MASK;
1941 sp = page_header(root);
1942 --sp->root_count;
1943 if (!sp->root_count && sp->role.invalid)
1944 kvm_mmu_zap_page(vcpu->kvm, sp);
1946 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1948 spin_unlock(&vcpu->kvm->mmu_lock);
1949 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1952 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
1954 int ret = 0;
1956 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
1957 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
1958 ret = 1;
1961 return ret;
1964 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
1966 int i;
1967 gfn_t root_gfn;
1968 struct kvm_mmu_page *sp;
1969 int direct = 0;
1970 u64 pdptr;
1972 root_gfn = vcpu->arch.cr3 >> PAGE_SHIFT;
1974 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1975 hpa_t root = vcpu->arch.mmu.root_hpa;
1977 ASSERT(!VALID_PAGE(root));
1978 if (tdp_enabled)
1979 direct = 1;
1980 if (mmu_check_root(vcpu, root_gfn))
1981 return 1;
1982 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
1983 PT64_ROOT_LEVEL, direct,
1984 ACC_ALL, NULL);
1985 root = __pa(sp->spt);
1986 ++sp->root_count;
1987 vcpu->arch.mmu.root_hpa = root;
1988 return 0;
1990 direct = !is_paging(vcpu);
1991 if (tdp_enabled)
1992 direct = 1;
1993 for (i = 0; i < 4; ++i) {
1994 hpa_t root = vcpu->arch.mmu.pae_root[i];
1996 ASSERT(!VALID_PAGE(root));
1997 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
1998 pdptr = kvm_pdptr_read(vcpu, i);
1999 if (!is_present_gpte(pdptr)) {
2000 vcpu->arch.mmu.pae_root[i] = 0;
2001 continue;
2003 root_gfn = pdptr >> PAGE_SHIFT;
2004 } else if (vcpu->arch.mmu.root_level == 0)
2005 root_gfn = 0;
2006 if (mmu_check_root(vcpu, root_gfn))
2007 return 1;
2008 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
2009 PT32_ROOT_LEVEL, direct,
2010 ACC_ALL, NULL);
2011 root = __pa(sp->spt);
2012 ++sp->root_count;
2013 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
2015 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
2016 return 0;
2019 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
2021 int i;
2022 struct kvm_mmu_page *sp;
2024 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2025 return;
2026 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2027 hpa_t root = vcpu->arch.mmu.root_hpa;
2028 sp = page_header(root);
2029 mmu_sync_children(vcpu, sp);
2030 return;
2032 for (i = 0; i < 4; ++i) {
2033 hpa_t root = vcpu->arch.mmu.pae_root[i];
2035 if (root && VALID_PAGE(root)) {
2036 root &= PT64_BASE_ADDR_MASK;
2037 sp = page_header(root);
2038 mmu_sync_children(vcpu, sp);
2043 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
2045 spin_lock(&vcpu->kvm->mmu_lock);
2046 mmu_sync_roots(vcpu);
2047 spin_unlock(&vcpu->kvm->mmu_lock);
2050 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr)
2052 return vaddr;
2055 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
2056 u32 error_code)
2058 gfn_t gfn;
2059 int r;
2061 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
2062 r = mmu_topup_memory_caches(vcpu);
2063 if (r)
2064 return r;
2066 ASSERT(vcpu);
2067 ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2069 gfn = gva >> PAGE_SHIFT;
2071 return nonpaging_map(vcpu, gva & PAGE_MASK,
2072 error_code & PFERR_WRITE_MASK, gfn);
2075 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
2076 u32 error_code)
2078 pfn_t pfn;
2079 int r;
2080 int largepage = 0;
2081 gfn_t gfn = gpa >> PAGE_SHIFT;
2082 unsigned long mmu_seq;
2084 ASSERT(vcpu);
2085 ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2087 r = mmu_topup_memory_caches(vcpu);
2088 if (r)
2089 return r;
2091 if (is_largepage_backed(vcpu, gfn &
2092 ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1))) {
2093 gfn &= ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1);
2094 largepage = 1;
2096 mmu_seq = vcpu->kvm->mmu_notifier_seq;
2097 smp_rmb();
2098 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2099 if (is_error_pfn(pfn)) {
2100 kvm_release_pfn_clean(pfn);
2101 return 1;
2103 spin_lock(&vcpu->kvm->mmu_lock);
2104 if (mmu_notifier_retry(vcpu, mmu_seq))
2105 goto out_unlock;
2106 kvm_mmu_free_some_pages(vcpu);
2107 r = __direct_map(vcpu, gpa, error_code & PFERR_WRITE_MASK,
2108 largepage, gfn, pfn);
2109 spin_unlock(&vcpu->kvm->mmu_lock);
2111 return r;
2113 out_unlock:
2114 spin_unlock(&vcpu->kvm->mmu_lock);
2115 kvm_release_pfn_clean(pfn);
2116 return 0;
2119 static void nonpaging_free(struct kvm_vcpu *vcpu)
2121 mmu_free_roots(vcpu);
2124 static int nonpaging_init_context(struct kvm_vcpu *vcpu)
2126 struct kvm_mmu *context = &vcpu->arch.mmu;
2128 context->new_cr3 = nonpaging_new_cr3;
2129 context->page_fault = nonpaging_page_fault;
2130 context->gva_to_gpa = nonpaging_gva_to_gpa;
2131 context->free = nonpaging_free;
2132 context->prefetch_page = nonpaging_prefetch_page;
2133 context->sync_page = nonpaging_sync_page;
2134 context->invlpg = nonpaging_invlpg;
2135 context->root_level = 0;
2136 context->shadow_root_level = PT32E_ROOT_LEVEL;
2137 context->root_hpa = INVALID_PAGE;
2138 return 0;
2141 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2143 ++vcpu->stat.tlb_flush;
2144 kvm_x86_ops->tlb_flush(vcpu);
2147 static void paging_new_cr3(struct kvm_vcpu *vcpu)
2149 pgprintk("%s: cr3 %lx\n", __func__, vcpu->arch.cr3);
2150 mmu_free_roots(vcpu);
2153 static void inject_page_fault(struct kvm_vcpu *vcpu,
2154 u64 addr,
2155 u32 err_code)
2157 kvm_inject_page_fault(vcpu, addr, err_code);
2160 static void paging_free(struct kvm_vcpu *vcpu)
2162 nonpaging_free(vcpu);
2165 static bool is_rsvd_bits_set(struct kvm_vcpu *vcpu, u64 gpte, int level)
2167 int bit7;
2169 bit7 = (gpte >> 7) & 1;
2170 return (gpte & vcpu->arch.mmu.rsvd_bits_mask[bit7][level-1]) != 0;
2173 #define PTTYPE 64
2174 #include "paging_tmpl.h"
2175 #undef PTTYPE
2177 #define PTTYPE 32
2178 #include "paging_tmpl.h"
2179 #undef PTTYPE
2181 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu, int level)
2183 struct kvm_mmu *context = &vcpu->arch.mmu;
2184 int maxphyaddr = cpuid_maxphyaddr(vcpu);
2185 u64 exb_bit_rsvd = 0;
2187 if (!is_nx(vcpu))
2188 exb_bit_rsvd = rsvd_bits(63, 63);
2189 switch (level) {
2190 case PT32_ROOT_LEVEL:
2191 /* no rsvd bits for 2 level 4K page table entries */
2192 context->rsvd_bits_mask[0][1] = 0;
2193 context->rsvd_bits_mask[0][0] = 0;
2194 if (is_cpuid_PSE36())
2195 /* 36bits PSE 4MB page */
2196 context->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
2197 else
2198 /* 32 bits PSE 4MB page */
2199 context->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
2200 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[1][0];
2201 break;
2202 case PT32E_ROOT_LEVEL:
2203 context->rsvd_bits_mask[0][2] =
2204 rsvd_bits(maxphyaddr, 63) |
2205 rsvd_bits(7, 8) | rsvd_bits(1, 2); /* PDPTE */
2206 context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
2207 rsvd_bits(maxphyaddr, 62); /* PDE */
2208 context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
2209 rsvd_bits(maxphyaddr, 62); /* PTE */
2210 context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
2211 rsvd_bits(maxphyaddr, 62) |
2212 rsvd_bits(13, 20); /* large page */
2213 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[1][0];
2214 break;
2215 case PT64_ROOT_LEVEL:
2216 context->rsvd_bits_mask[0][3] = exb_bit_rsvd |
2217 rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
2218 context->rsvd_bits_mask[0][2] = exb_bit_rsvd |
2219 rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
2220 context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
2221 rsvd_bits(maxphyaddr, 51);
2222 context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
2223 rsvd_bits(maxphyaddr, 51);
2224 context->rsvd_bits_mask[1][3] = context->rsvd_bits_mask[0][3];
2225 context->rsvd_bits_mask[1][2] = context->rsvd_bits_mask[0][2];
2226 context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
2227 rsvd_bits(maxphyaddr, 51) |
2228 rsvd_bits(13, 20); /* large page */
2229 context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[1][0];
2230 break;
2234 static int paging64_init_context_common(struct kvm_vcpu *vcpu, int level)
2236 struct kvm_mmu *context = &vcpu->arch.mmu;
2238 ASSERT(is_pae(vcpu));
2239 context->new_cr3 = paging_new_cr3;
2240 context->page_fault = paging64_page_fault;
2241 context->gva_to_gpa = paging64_gva_to_gpa;
2242 context->prefetch_page = paging64_prefetch_page;
2243 context->sync_page = paging64_sync_page;
2244 context->invlpg = paging64_invlpg;
2245 context->free = paging_free;
2246 context->root_level = level;
2247 context->shadow_root_level = level;
2248 context->root_hpa = INVALID_PAGE;
2249 return 0;
2252 static int paging64_init_context(struct kvm_vcpu *vcpu)
2254 reset_rsvds_bits_mask(vcpu, PT64_ROOT_LEVEL);
2255 return paging64_init_context_common(vcpu, PT64_ROOT_LEVEL);
2258 static int paging32_init_context(struct kvm_vcpu *vcpu)
2260 struct kvm_mmu *context = &vcpu->arch.mmu;
2262 reset_rsvds_bits_mask(vcpu, PT32_ROOT_LEVEL);
2263 context->new_cr3 = paging_new_cr3;
2264 context->page_fault = paging32_page_fault;
2265 context->gva_to_gpa = paging32_gva_to_gpa;
2266 context->free = paging_free;
2267 context->prefetch_page = paging32_prefetch_page;
2268 context->sync_page = paging32_sync_page;
2269 context->invlpg = paging32_invlpg;
2270 context->root_level = PT32_ROOT_LEVEL;
2271 context->shadow_root_level = PT32E_ROOT_LEVEL;
2272 context->root_hpa = INVALID_PAGE;
2273 return 0;
2276 static int paging32E_init_context(struct kvm_vcpu *vcpu)
2278 reset_rsvds_bits_mask(vcpu, PT32E_ROOT_LEVEL);
2279 return paging64_init_context_common(vcpu, PT32E_ROOT_LEVEL);
2282 static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
2284 struct kvm_mmu *context = &vcpu->arch.mmu;
2286 context->new_cr3 = nonpaging_new_cr3;
2287 context->page_fault = tdp_page_fault;
2288 context->free = nonpaging_free;
2289 context->prefetch_page = nonpaging_prefetch_page;
2290 context->sync_page = nonpaging_sync_page;
2291 context->invlpg = nonpaging_invlpg;
2292 context->shadow_root_level = kvm_x86_ops->get_tdp_level();
2293 context->root_hpa = INVALID_PAGE;
2295 if (!is_paging(vcpu)) {
2296 context->gva_to_gpa = nonpaging_gva_to_gpa;
2297 context->root_level = 0;
2298 } else if (is_long_mode(vcpu)) {
2299 reset_rsvds_bits_mask(vcpu, PT64_ROOT_LEVEL);
2300 context->gva_to_gpa = paging64_gva_to_gpa;
2301 context->root_level = PT64_ROOT_LEVEL;
2302 } else if (is_pae(vcpu)) {
2303 reset_rsvds_bits_mask(vcpu, PT32E_ROOT_LEVEL);
2304 context->gva_to_gpa = paging64_gva_to_gpa;
2305 context->root_level = PT32E_ROOT_LEVEL;
2306 } else {
2307 reset_rsvds_bits_mask(vcpu, PT32_ROOT_LEVEL);
2308 context->gva_to_gpa = paging32_gva_to_gpa;
2309 context->root_level = PT32_ROOT_LEVEL;
2312 return 0;
2315 static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
2317 int r;
2319 ASSERT(vcpu);
2320 ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2322 if (!is_paging(vcpu))
2323 r = nonpaging_init_context(vcpu);
2324 else if (is_long_mode(vcpu))
2325 r = paging64_init_context(vcpu);
2326 else if (is_pae(vcpu))
2327 r = paging32E_init_context(vcpu);
2328 else
2329 r = paging32_init_context(vcpu);
2331 vcpu->arch.mmu.base_role.glevels = vcpu->arch.mmu.root_level;
2333 return r;
2336 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
2338 vcpu->arch.update_pte.pfn = bad_pfn;
2340 if (tdp_enabled)
2341 return init_kvm_tdp_mmu(vcpu);
2342 else
2343 return init_kvm_softmmu(vcpu);
2346 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
2348 ASSERT(vcpu);
2349 if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) {
2350 vcpu->arch.mmu.free(vcpu);
2351 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
2355 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
2357 destroy_kvm_mmu(vcpu);
2358 return init_kvm_mmu(vcpu);
2360 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
2362 int kvm_mmu_load(struct kvm_vcpu *vcpu)
2364 int r;
2366 r = mmu_topup_memory_caches(vcpu);
2367 if (r)
2368 goto out;
2369 spin_lock(&vcpu->kvm->mmu_lock);
2370 kvm_mmu_free_some_pages(vcpu);
2371 r = mmu_alloc_roots(vcpu);
2372 mmu_sync_roots(vcpu);
2373 spin_unlock(&vcpu->kvm->mmu_lock);
2374 if (r)
2375 goto out;
2376 kvm_x86_ops->set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
2377 kvm_mmu_flush_tlb(vcpu);
2378 out:
2379 return r;
2381 EXPORT_SYMBOL_GPL(kvm_mmu_load);
2383 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
2385 mmu_free_roots(vcpu);
2388 static void mmu_pte_write_zap_pte(struct kvm_vcpu *vcpu,
2389 struct kvm_mmu_page *sp,
2390 u64 *spte)
2392 u64 pte;
2393 struct kvm_mmu_page *child;
2395 pte = *spte;
2396 if (is_shadow_present_pte(pte)) {
2397 if (is_last_spte(pte, sp->role.level))
2398 rmap_remove(vcpu->kvm, spte);
2399 else {
2400 child = page_header(pte & PT64_BASE_ADDR_MASK);
2401 mmu_page_remove_parent_pte(child, spte);
2404 __set_spte(spte, shadow_trap_nonpresent_pte);
2405 if (is_large_pte(pte))
2406 --vcpu->kvm->stat.lpages;
2409 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
2410 struct kvm_mmu_page *sp,
2411 u64 *spte,
2412 const void *new)
2414 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
2415 if (!vcpu->arch.update_pte.largepage ||
2416 sp->role.glevels == PT32_ROOT_LEVEL) {
2417 ++vcpu->kvm->stat.mmu_pde_zapped;
2418 return;
2422 ++vcpu->kvm->stat.mmu_pte_updated;
2423 if (sp->role.glevels == PT32_ROOT_LEVEL)
2424 paging32_update_pte(vcpu, sp, spte, new);
2425 else
2426 paging64_update_pte(vcpu, sp, spte, new);
2429 static bool need_remote_flush(u64 old, u64 new)
2431 if (!is_shadow_present_pte(old))
2432 return false;
2433 if (!is_shadow_present_pte(new))
2434 return true;
2435 if ((old ^ new) & PT64_BASE_ADDR_MASK)
2436 return true;
2437 old ^= PT64_NX_MASK;
2438 new ^= PT64_NX_MASK;
2439 return (old & ~new & PT64_PERM_MASK) != 0;
2442 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, u64 old, u64 new)
2444 if (need_remote_flush(old, new))
2445 kvm_flush_remote_tlbs(vcpu->kvm);
2446 else
2447 kvm_mmu_flush_tlb(vcpu);
2450 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
2452 u64 *spte = vcpu->arch.last_pte_updated;
2454 return !!(spte && (*spte & shadow_accessed_mask));
2457 static void mmu_guess_page_from_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2458 const u8 *new, int bytes)
2460 gfn_t gfn;
2461 int r;
2462 u64 gpte = 0;
2463 pfn_t pfn;
2465 vcpu->arch.update_pte.largepage = 0;
2467 if (bytes != 4 && bytes != 8)
2468 return;
2471 * Assume that the pte write on a page table of the same type
2472 * as the current vcpu paging mode. This is nearly always true
2473 * (might be false while changing modes). Note it is verified later
2474 * by update_pte().
2476 if (is_pae(vcpu)) {
2477 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
2478 if ((bytes == 4) && (gpa % 4 == 0)) {
2479 r = kvm_read_guest(vcpu->kvm, gpa & ~(u64)7, &gpte, 8);
2480 if (r)
2481 return;
2482 memcpy((void *)&gpte + (gpa % 8), new, 4);
2483 } else if ((bytes == 8) && (gpa % 8 == 0)) {
2484 memcpy((void *)&gpte, new, 8);
2486 } else {
2487 if ((bytes == 4) && (gpa % 4 == 0))
2488 memcpy((void *)&gpte, new, 4);
2490 if (!is_present_gpte(gpte))
2491 return;
2492 gfn = (gpte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
2494 if (is_large_pte(gpte) && is_largepage_backed(vcpu, gfn)) {
2495 gfn &= ~(KVM_PAGES_PER_HPAGE(PT_DIRECTORY_LEVEL) - 1);
2496 vcpu->arch.update_pte.largepage = 1;
2498 vcpu->arch.update_pte.mmu_seq = vcpu->kvm->mmu_notifier_seq;
2499 smp_rmb();
2500 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2502 if (is_error_pfn(pfn)) {
2503 kvm_release_pfn_clean(pfn);
2504 return;
2506 vcpu->arch.update_pte.gfn = gfn;
2507 vcpu->arch.update_pte.pfn = pfn;
2510 static void kvm_mmu_access_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2512 u64 *spte = vcpu->arch.last_pte_updated;
2514 if (spte
2515 && vcpu->arch.last_pte_gfn == gfn
2516 && shadow_accessed_mask
2517 && !(*spte & shadow_accessed_mask)
2518 && is_shadow_present_pte(*spte))
2519 set_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
2522 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2523 const u8 *new, int bytes,
2524 bool guest_initiated)
2526 gfn_t gfn = gpa >> PAGE_SHIFT;
2527 struct kvm_mmu_page *sp;
2528 struct hlist_node *node, *n;
2529 struct hlist_head *bucket;
2530 unsigned index;
2531 u64 entry, gentry;
2532 u64 *spte;
2533 unsigned offset = offset_in_page(gpa);
2534 unsigned pte_size;
2535 unsigned page_offset;
2536 unsigned misaligned;
2537 unsigned quadrant;
2538 int level;
2539 int flooded = 0;
2540 int npte;
2541 int r;
2543 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
2544 mmu_guess_page_from_pte_write(vcpu, gpa, new, bytes);
2545 spin_lock(&vcpu->kvm->mmu_lock);
2546 kvm_mmu_access_page(vcpu, gfn);
2547 kvm_mmu_free_some_pages(vcpu);
2548 ++vcpu->kvm->stat.mmu_pte_write;
2549 kvm_mmu_audit(vcpu, "pre pte write");
2550 if (guest_initiated) {
2551 if (gfn == vcpu->arch.last_pt_write_gfn
2552 && !last_updated_pte_accessed(vcpu)) {
2553 ++vcpu->arch.last_pt_write_count;
2554 if (vcpu->arch.last_pt_write_count >= 3)
2555 flooded = 1;
2556 } else {
2557 vcpu->arch.last_pt_write_gfn = gfn;
2558 vcpu->arch.last_pt_write_count = 1;
2559 vcpu->arch.last_pte_updated = NULL;
2562 index = kvm_page_table_hashfn(gfn);
2563 bucket = &vcpu->kvm->arch.mmu_page_hash[index];
2564 hlist_for_each_entry_safe(sp, node, n, bucket, hash_link) {
2565 if (sp->gfn != gfn || sp->role.direct || sp->role.invalid)
2566 continue;
2567 pte_size = sp->role.glevels == PT32_ROOT_LEVEL ? 4 : 8;
2568 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
2569 misaligned |= bytes < 4;
2570 if (misaligned || flooded) {
2572 * Misaligned accesses are too much trouble to fix
2573 * up; also, they usually indicate a page is not used
2574 * as a page table.
2576 * If we're seeing too many writes to a page,
2577 * it may no longer be a page table, or we may be
2578 * forking, in which case it is better to unmap the
2579 * page.
2581 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
2582 gpa, bytes, sp->role.word);
2583 if (kvm_mmu_zap_page(vcpu->kvm, sp))
2584 n = bucket->first;
2585 ++vcpu->kvm->stat.mmu_flooded;
2586 continue;
2588 page_offset = offset;
2589 level = sp->role.level;
2590 npte = 1;
2591 if (sp->role.glevels == PT32_ROOT_LEVEL) {
2592 page_offset <<= 1; /* 32->64 */
2594 * A 32-bit pde maps 4MB while the shadow pdes map
2595 * only 2MB. So we need to double the offset again
2596 * and zap two pdes instead of one.
2598 if (level == PT32_ROOT_LEVEL) {
2599 page_offset &= ~7; /* kill rounding error */
2600 page_offset <<= 1;
2601 npte = 2;
2603 quadrant = page_offset >> PAGE_SHIFT;
2604 page_offset &= ~PAGE_MASK;
2605 if (quadrant != sp->role.quadrant)
2606 continue;
2608 spte = &sp->spt[page_offset / sizeof(*spte)];
2609 if ((gpa & (pte_size - 1)) || (bytes < pte_size)) {
2610 gentry = 0;
2611 r = kvm_read_guest_atomic(vcpu->kvm,
2612 gpa & ~(u64)(pte_size - 1),
2613 &gentry, pte_size);
2614 new = (const void *)&gentry;
2615 if (r < 0)
2616 new = NULL;
2618 while (npte--) {
2619 entry = *spte;
2620 mmu_pte_write_zap_pte(vcpu, sp, spte);
2621 if (new)
2622 mmu_pte_write_new_pte(vcpu, sp, spte, new);
2623 mmu_pte_write_flush_tlb(vcpu, entry, *spte);
2624 ++spte;
2627 kvm_mmu_audit(vcpu, "post pte write");
2628 spin_unlock(&vcpu->kvm->mmu_lock);
2629 if (!is_error_pfn(vcpu->arch.update_pte.pfn)) {
2630 kvm_release_pfn_clean(vcpu->arch.update_pte.pfn);
2631 vcpu->arch.update_pte.pfn = bad_pfn;
2635 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2637 gpa_t gpa;
2638 int r;
2640 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
2642 spin_lock(&vcpu->kvm->mmu_lock);
2643 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2644 spin_unlock(&vcpu->kvm->mmu_lock);
2645 return r;
2647 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
2649 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
2651 while (vcpu->kvm->arch.n_free_mmu_pages < KVM_REFILL_PAGES) {
2652 struct kvm_mmu_page *sp;
2654 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
2655 struct kvm_mmu_page, link);
2656 kvm_mmu_zap_page(vcpu->kvm, sp);
2657 ++vcpu->kvm->stat.mmu_recycled;
2661 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
2663 int r;
2664 enum emulation_result er;
2666 r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
2667 if (r < 0)
2668 goto out;
2670 if (!r) {
2671 r = 1;
2672 goto out;
2675 r = mmu_topup_memory_caches(vcpu);
2676 if (r)
2677 goto out;
2679 er = emulate_instruction(vcpu, vcpu->run, cr2, error_code, 0);
2681 switch (er) {
2682 case EMULATE_DONE:
2683 return 1;
2684 case EMULATE_DO_MMIO:
2685 ++vcpu->stat.mmio_exits;
2686 return 0;
2687 case EMULATE_FAIL:
2688 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2689 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
2690 return 0;
2691 default:
2692 BUG();
2694 out:
2695 return r;
2697 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
2699 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
2701 vcpu->arch.mmu.invlpg(vcpu, gva);
2702 kvm_mmu_flush_tlb(vcpu);
2703 ++vcpu->stat.invlpg;
2705 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
2707 void kvm_enable_tdp(void)
2709 tdp_enabled = true;
2711 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
2713 void kvm_disable_tdp(void)
2715 tdp_enabled = false;
2717 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
2719 static void free_mmu_pages(struct kvm_vcpu *vcpu)
2721 free_page((unsigned long)vcpu->arch.mmu.pae_root);
2724 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
2726 struct page *page;
2727 int i;
2729 ASSERT(vcpu);
2731 if (vcpu->kvm->arch.n_requested_mmu_pages)
2732 vcpu->kvm->arch.n_free_mmu_pages =
2733 vcpu->kvm->arch.n_requested_mmu_pages;
2734 else
2735 vcpu->kvm->arch.n_free_mmu_pages =
2736 vcpu->kvm->arch.n_alloc_mmu_pages;
2738 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
2739 * Therefore we need to allocate shadow page tables in the first
2740 * 4GB of memory, which happens to fit the DMA32 zone.
2742 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
2743 if (!page)
2744 goto error_1;
2745 vcpu->arch.mmu.pae_root = page_address(page);
2746 for (i = 0; i < 4; ++i)
2747 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
2749 return 0;
2751 error_1:
2752 free_mmu_pages(vcpu);
2753 return -ENOMEM;
2756 int kvm_mmu_create(struct kvm_vcpu *vcpu)
2758 ASSERT(vcpu);
2759 ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2761 return alloc_mmu_pages(vcpu);
2764 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
2766 ASSERT(vcpu);
2767 ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2769 return init_kvm_mmu(vcpu);
2772 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
2774 ASSERT(vcpu);
2776 destroy_kvm_mmu(vcpu);
2777 free_mmu_pages(vcpu);
2778 mmu_free_memory_caches(vcpu);
2781 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
2783 struct kvm_mmu_page *sp;
2785 list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
2786 int i;
2787 u64 *pt;
2789 if (!test_bit(slot, sp->slot_bitmap))
2790 continue;
2792 pt = sp->spt;
2793 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2794 /* avoid RMW */
2795 if (pt[i] & PT_WRITABLE_MASK)
2796 pt[i] &= ~PT_WRITABLE_MASK;
2798 kvm_flush_remote_tlbs(kvm);
2801 void kvm_mmu_zap_all(struct kvm *kvm)
2803 struct kvm_mmu_page *sp, *node;
2805 spin_lock(&kvm->mmu_lock);
2806 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
2807 if (kvm_mmu_zap_page(kvm, sp))
2808 node = container_of(kvm->arch.active_mmu_pages.next,
2809 struct kvm_mmu_page, link);
2810 spin_unlock(&kvm->mmu_lock);
2812 kvm_flush_remote_tlbs(kvm);
2815 static void kvm_mmu_remove_one_alloc_mmu_page(struct kvm *kvm)
2817 struct kvm_mmu_page *page;
2819 page = container_of(kvm->arch.active_mmu_pages.prev,
2820 struct kvm_mmu_page, link);
2821 kvm_mmu_zap_page(kvm, page);
2824 static int mmu_shrink(int nr_to_scan, gfp_t gfp_mask)
2826 struct kvm *kvm;
2827 struct kvm *kvm_freed = NULL;
2828 int cache_count = 0;
2830 spin_lock(&kvm_lock);
2832 list_for_each_entry(kvm, &vm_list, vm_list) {
2833 int npages;
2835 if (!down_read_trylock(&kvm->slots_lock))
2836 continue;
2837 spin_lock(&kvm->mmu_lock);
2838 npages = kvm->arch.n_alloc_mmu_pages -
2839 kvm->arch.n_free_mmu_pages;
2840 cache_count += npages;
2841 if (!kvm_freed && nr_to_scan > 0 && npages > 0) {
2842 kvm_mmu_remove_one_alloc_mmu_page(kvm);
2843 cache_count--;
2844 kvm_freed = kvm;
2846 nr_to_scan--;
2848 spin_unlock(&kvm->mmu_lock);
2849 up_read(&kvm->slots_lock);
2851 if (kvm_freed)
2852 list_move_tail(&kvm_freed->vm_list, &vm_list);
2854 spin_unlock(&kvm_lock);
2856 return cache_count;
2859 static struct shrinker mmu_shrinker = {
2860 .shrink = mmu_shrink,
2861 .seeks = DEFAULT_SEEKS * 10,
2864 static void mmu_destroy_caches(void)
2866 if (pte_chain_cache)
2867 kmem_cache_destroy(pte_chain_cache);
2868 if (rmap_desc_cache)
2869 kmem_cache_destroy(rmap_desc_cache);
2870 if (mmu_page_header_cache)
2871 kmem_cache_destroy(mmu_page_header_cache);
2874 void kvm_mmu_module_exit(void)
2876 mmu_destroy_caches();
2877 unregister_shrinker(&mmu_shrinker);
2880 int kvm_mmu_module_init(void)
2882 pte_chain_cache = kmem_cache_create("kvm_pte_chain",
2883 sizeof(struct kvm_pte_chain),
2884 0, 0, NULL);
2885 if (!pte_chain_cache)
2886 goto nomem;
2887 rmap_desc_cache = kmem_cache_create("kvm_rmap_desc",
2888 sizeof(struct kvm_rmap_desc),
2889 0, 0, NULL);
2890 if (!rmap_desc_cache)
2891 goto nomem;
2893 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
2894 sizeof(struct kvm_mmu_page),
2895 0, 0, NULL);
2896 if (!mmu_page_header_cache)
2897 goto nomem;
2899 register_shrinker(&mmu_shrinker);
2901 return 0;
2903 nomem:
2904 mmu_destroy_caches();
2905 return -ENOMEM;
2909 * Caculate mmu pages needed for kvm.
2911 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
2913 int i;
2914 unsigned int nr_mmu_pages;
2915 unsigned int nr_pages = 0;
2917 for (i = 0; i < kvm->nmemslots; i++)
2918 nr_pages += kvm->memslots[i].npages;
2920 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
2921 nr_mmu_pages = max(nr_mmu_pages,
2922 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
2924 return nr_mmu_pages;
2927 static void *pv_mmu_peek_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2928 unsigned len)
2930 if (len > buffer->len)
2931 return NULL;
2932 return buffer->ptr;
2935 static void *pv_mmu_read_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2936 unsigned len)
2938 void *ret;
2940 ret = pv_mmu_peek_buffer(buffer, len);
2941 if (!ret)
2942 return ret;
2943 buffer->ptr += len;
2944 buffer->len -= len;
2945 buffer->processed += len;
2946 return ret;
2949 static int kvm_pv_mmu_write(struct kvm_vcpu *vcpu,
2950 gpa_t addr, gpa_t value)
2952 int bytes = 8;
2953 int r;
2955 if (!is_long_mode(vcpu) && !is_pae(vcpu))
2956 bytes = 4;
2958 r = mmu_topup_memory_caches(vcpu);
2959 if (r)
2960 return r;
2962 if (!emulator_write_phys(vcpu, addr, &value, bytes))
2963 return -EFAULT;
2965 return 1;
2968 static int kvm_pv_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2970 kvm_set_cr3(vcpu, vcpu->arch.cr3);
2971 return 1;
2974 static int kvm_pv_mmu_release_pt(struct kvm_vcpu *vcpu, gpa_t addr)
2976 spin_lock(&vcpu->kvm->mmu_lock);
2977 mmu_unshadow(vcpu->kvm, addr >> PAGE_SHIFT);
2978 spin_unlock(&vcpu->kvm->mmu_lock);
2979 return 1;
2982 static int kvm_pv_mmu_op_one(struct kvm_vcpu *vcpu,
2983 struct kvm_pv_mmu_op_buffer *buffer)
2985 struct kvm_mmu_op_header *header;
2987 header = pv_mmu_peek_buffer(buffer, sizeof *header);
2988 if (!header)
2989 return 0;
2990 switch (header->op) {
2991 case KVM_MMU_OP_WRITE_PTE: {
2992 struct kvm_mmu_op_write_pte *wpte;
2994 wpte = pv_mmu_read_buffer(buffer, sizeof *wpte);
2995 if (!wpte)
2996 return 0;
2997 return kvm_pv_mmu_write(vcpu, wpte->pte_phys,
2998 wpte->pte_val);
3000 case KVM_MMU_OP_FLUSH_TLB: {
3001 struct kvm_mmu_op_flush_tlb *ftlb;
3003 ftlb = pv_mmu_read_buffer(buffer, sizeof *ftlb);
3004 if (!ftlb)
3005 return 0;
3006 return kvm_pv_mmu_flush_tlb(vcpu);
3008 case KVM_MMU_OP_RELEASE_PT: {
3009 struct kvm_mmu_op_release_pt *rpt;
3011 rpt = pv_mmu_read_buffer(buffer, sizeof *rpt);
3012 if (!rpt)
3013 return 0;
3014 return kvm_pv_mmu_release_pt(vcpu, rpt->pt_phys);
3016 default: return 0;
3020 int kvm_pv_mmu_op(struct kvm_vcpu *vcpu, unsigned long bytes,
3021 gpa_t addr, unsigned long *ret)
3023 int r;
3024 struct kvm_pv_mmu_op_buffer *buffer = &vcpu->arch.mmu_op_buffer;
3026 buffer->ptr = buffer->buf;
3027 buffer->len = min_t(unsigned long, bytes, sizeof buffer->buf);
3028 buffer->processed = 0;
3030 r = kvm_read_guest(vcpu->kvm, addr, buffer->buf, buffer->len);
3031 if (r)
3032 goto out;
3034 while (buffer->len) {
3035 r = kvm_pv_mmu_op_one(vcpu, buffer);
3036 if (r < 0)
3037 goto out;
3038 if (r == 0)
3039 break;
3042 r = 1;
3043 out:
3044 *ret = buffer->processed;
3045 return r;
3048 int kvm_mmu_get_spte_hierarchy(struct kvm_vcpu *vcpu, u64 addr, u64 sptes[4])
3050 struct kvm_shadow_walk_iterator iterator;
3051 int nr_sptes = 0;
3053 spin_lock(&vcpu->kvm->mmu_lock);
3054 for_each_shadow_entry(vcpu, addr, iterator) {
3055 sptes[iterator.level-1] = *iterator.sptep;
3056 nr_sptes++;
3057 if (!is_shadow_present_pte(*iterator.sptep))
3058 break;
3060 spin_unlock(&vcpu->kvm->mmu_lock);
3062 return nr_sptes;
3064 EXPORT_SYMBOL_GPL(kvm_mmu_get_spte_hierarchy);
3066 #ifdef AUDIT
3068 static const char *audit_msg;
3070 static gva_t canonicalize(gva_t gva)
3072 #ifdef CONFIG_X86_64
3073 gva = (long long)(gva << 16) >> 16;
3074 #endif
3075 return gva;
3079 typedef void (*inspect_spte_fn) (struct kvm *kvm, struct kvm_mmu_page *sp,
3080 u64 *sptep);
3082 static void __mmu_spte_walk(struct kvm *kvm, struct kvm_mmu_page *sp,
3083 inspect_spte_fn fn)
3085 int i;
3087 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3088 u64 ent = sp->spt[i];
3090 if (is_shadow_present_pte(ent)) {
3091 if (!is_last_spte(ent, sp->role.level)) {
3092 struct kvm_mmu_page *child;
3093 child = page_header(ent & PT64_BASE_ADDR_MASK);
3094 __mmu_spte_walk(kvm, child, fn);
3095 } else
3096 fn(kvm, sp, &sp->spt[i]);
3101 static void mmu_spte_walk(struct kvm_vcpu *vcpu, inspect_spte_fn fn)
3103 int i;
3104 struct kvm_mmu_page *sp;
3106 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3107 return;
3108 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
3109 hpa_t root = vcpu->arch.mmu.root_hpa;
3110 sp = page_header(root);
3111 __mmu_spte_walk(vcpu->kvm, sp, fn);
3112 return;
3114 for (i = 0; i < 4; ++i) {
3115 hpa_t root = vcpu->arch.mmu.pae_root[i];
3117 if (root && VALID_PAGE(root)) {
3118 root &= PT64_BASE_ADDR_MASK;
3119 sp = page_header(root);
3120 __mmu_spte_walk(vcpu->kvm, sp, fn);
3123 return;
3126 static void audit_mappings_page(struct kvm_vcpu *vcpu, u64 page_pte,
3127 gva_t va, int level)
3129 u64 *pt = __va(page_pte & PT64_BASE_ADDR_MASK);
3130 int i;
3131 gva_t va_delta = 1ul << (PAGE_SHIFT + 9 * (level - 1));
3133 for (i = 0; i < PT64_ENT_PER_PAGE; ++i, va += va_delta) {
3134 u64 ent = pt[i];
3136 if (ent == shadow_trap_nonpresent_pte)
3137 continue;
3139 va = canonicalize(va);
3140 if (is_shadow_present_pte(ent) && !is_last_spte(ent, level))
3141 audit_mappings_page(vcpu, ent, va, level - 1);
3142 else {
3143 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, va);
3144 gfn_t gfn = gpa >> PAGE_SHIFT;
3145 pfn_t pfn = gfn_to_pfn(vcpu->kvm, gfn);
3146 hpa_t hpa = (hpa_t)pfn << PAGE_SHIFT;
3148 if (is_error_pfn(pfn)) {
3149 kvm_release_pfn_clean(pfn);
3150 continue;
3153 if (is_shadow_present_pte(ent)
3154 && (ent & PT64_BASE_ADDR_MASK) != hpa)
3155 printk(KERN_ERR "xx audit error: (%s) levels %d"
3156 " gva %lx gpa %llx hpa %llx ent %llx %d\n",
3157 audit_msg, vcpu->arch.mmu.root_level,
3158 va, gpa, hpa, ent,
3159 is_shadow_present_pte(ent));
3160 else if (ent == shadow_notrap_nonpresent_pte
3161 && !is_error_hpa(hpa))
3162 printk(KERN_ERR "audit: (%s) notrap shadow,"
3163 " valid guest gva %lx\n", audit_msg, va);
3164 kvm_release_pfn_clean(pfn);
3170 static void audit_mappings(struct kvm_vcpu *vcpu)
3172 unsigned i;
3174 if (vcpu->arch.mmu.root_level == 4)
3175 audit_mappings_page(vcpu, vcpu->arch.mmu.root_hpa, 0, 4);
3176 else
3177 for (i = 0; i < 4; ++i)
3178 if (vcpu->arch.mmu.pae_root[i] & PT_PRESENT_MASK)
3179 audit_mappings_page(vcpu,
3180 vcpu->arch.mmu.pae_root[i],
3181 i << 30,
3185 static int count_rmaps(struct kvm_vcpu *vcpu)
3187 int nmaps = 0;
3188 int i, j, k;
3190 for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
3191 struct kvm_memory_slot *m = &vcpu->kvm->memslots[i];
3192 struct kvm_rmap_desc *d;
3194 for (j = 0; j < m->npages; ++j) {
3195 unsigned long *rmapp = &m->rmap[j];
3197 if (!*rmapp)
3198 continue;
3199 if (!(*rmapp & 1)) {
3200 ++nmaps;
3201 continue;
3203 d = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
3204 while (d) {
3205 for (k = 0; k < RMAP_EXT; ++k)
3206 if (d->sptes[k])
3207 ++nmaps;
3208 else
3209 break;
3210 d = d->more;
3214 return nmaps;
3217 void inspect_spte_has_rmap(struct kvm *kvm, struct kvm_mmu_page *sp, u64 *sptep)
3219 unsigned long *rmapp;
3220 struct kvm_mmu_page *rev_sp;
3221 gfn_t gfn;
3223 if (*sptep & PT_WRITABLE_MASK) {
3224 rev_sp = page_header(__pa(sptep));
3225 gfn = rev_sp->gfns[sptep - rev_sp->spt];
3227 if (!gfn_to_memslot(kvm, gfn)) {
3228 if (!printk_ratelimit())
3229 return;
3230 printk(KERN_ERR "%s: no memslot for gfn %ld\n",
3231 audit_msg, gfn);
3232 printk(KERN_ERR "%s: index %ld of sp (gfn=%lx)\n",
3233 audit_msg, sptep - rev_sp->spt,
3234 rev_sp->gfn);
3235 dump_stack();
3236 return;
3239 rmapp = gfn_to_rmap(kvm, rev_sp->gfns[sptep - rev_sp->spt],
3240 is_large_pte(*sptep));
3241 if (!*rmapp) {
3242 if (!printk_ratelimit())
3243 return;
3244 printk(KERN_ERR "%s: no rmap for writable spte %llx\n",
3245 audit_msg, *sptep);
3246 dump_stack();
3252 void audit_writable_sptes_have_rmaps(struct kvm_vcpu *vcpu)
3254 mmu_spte_walk(vcpu, inspect_spte_has_rmap);
3257 static void check_writable_mappings_rmap(struct kvm_vcpu *vcpu)
3259 struct kvm_mmu_page *sp;
3260 int i;
3262 list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3263 u64 *pt = sp->spt;
3265 if (sp->role.level != PT_PAGE_TABLE_LEVEL)
3266 continue;
3268 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3269 u64 ent = pt[i];
3271 if (!(ent & PT_PRESENT_MASK))
3272 continue;
3273 if (!(ent & PT_WRITABLE_MASK))
3274 continue;
3275 inspect_spte_has_rmap(vcpu->kvm, sp, &pt[i]);
3278 return;
3281 static void audit_rmap(struct kvm_vcpu *vcpu)
3283 check_writable_mappings_rmap(vcpu);
3284 count_rmaps(vcpu);
3287 static void audit_write_protection(struct kvm_vcpu *vcpu)
3289 struct kvm_mmu_page *sp;
3290 struct kvm_memory_slot *slot;
3291 unsigned long *rmapp;
3292 u64 *spte;
3293 gfn_t gfn;
3295 list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3296 if (sp->role.direct)
3297 continue;
3298 if (sp->unsync)
3299 continue;
3301 gfn = unalias_gfn(vcpu->kvm, sp->gfn);
3302 slot = gfn_to_memslot_unaliased(vcpu->kvm, sp->gfn);
3303 rmapp = &slot->rmap[gfn - slot->base_gfn];
3305 spte = rmap_next(vcpu->kvm, rmapp, NULL);
3306 while (spte) {
3307 if (*spte & PT_WRITABLE_MASK)
3308 printk(KERN_ERR "%s: (%s) shadow page has "
3309 "writable mappings: gfn %lx role %x\n",
3310 __func__, audit_msg, sp->gfn,
3311 sp->role.word);
3312 spte = rmap_next(vcpu->kvm, rmapp, spte);
3317 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg)
3319 int olddbg = dbg;
3321 dbg = 0;
3322 audit_msg = msg;
3323 audit_rmap(vcpu);
3324 audit_write_protection(vcpu);
3325 if (strcmp("pre pte write", audit_msg) != 0)
3326 audit_mappings(vcpu);
3327 audit_writable_sptes_have_rmaps(vcpu);
3328 dbg = olddbg;
3331 #endif