KVM: MMU: make __kvm_mmu_free_some_pages handle empty list
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / arch / x86 / kvm / mmu.c
bloba1c5e34e15fda2377190de8fcc9225c8892bd84a
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"
22 #include <linux/kvm_host.h>
23 #include <linux/types.h>
24 #include <linux/string.h>
25 #include <linux/mm.h>
26 #include <linux/highmem.h>
27 #include <linux/module.h>
28 #include <linux/swap.h>
29 #include <linux/hugetlb.h>
30 #include <linux/compiler.h>
32 #include <asm/page.h>
33 #include <asm/cmpxchg.h>
34 #include <asm/io.h>
35 #include <asm/vmx.h>
38 * When setting this variable to true it enables Two-Dimensional-Paging
39 * where the hardware walks 2 page tables:
40 * 1. the guest-virtual to guest-physical
41 * 2. while doing 1. it walks guest-physical to host-physical
42 * If the hardware supports that we don't need to do shadow paging.
44 bool tdp_enabled = false;
46 #undef MMU_DEBUG
48 #undef AUDIT
50 #ifdef AUDIT
51 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg);
52 #else
53 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg) {}
54 #endif
56 #ifdef MMU_DEBUG
58 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
59 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
61 #else
63 #define pgprintk(x...) do { } while (0)
64 #define rmap_printk(x...) do { } while (0)
66 #endif
68 #if defined(MMU_DEBUG) || defined(AUDIT)
69 static int dbg = 0;
70 module_param(dbg, bool, 0644);
71 #endif
73 static int oos_shadow = 1;
74 module_param(oos_shadow, bool, 0644);
76 #ifndef MMU_DEBUG
77 #define ASSERT(x) do { } while (0)
78 #else
79 #define ASSERT(x) \
80 if (!(x)) { \
81 printk(KERN_WARNING "assertion failed %s:%d: %s\n", \
82 __FILE__, __LINE__, #x); \
84 #endif
86 #define PT_FIRST_AVAIL_BITS_SHIFT 9
87 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
89 #define VALID_PAGE(x) ((x) != INVALID_PAGE)
91 #define PT64_LEVEL_BITS 9
93 #define PT64_LEVEL_SHIFT(level) \
94 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
96 #define PT64_LEVEL_MASK(level) \
97 (((1ULL << PT64_LEVEL_BITS) - 1) << PT64_LEVEL_SHIFT(level))
99 #define PT64_INDEX(address, level)\
100 (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
103 #define PT32_LEVEL_BITS 10
105 #define PT32_LEVEL_SHIFT(level) \
106 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
108 #define PT32_LEVEL_MASK(level) \
109 (((1ULL << PT32_LEVEL_BITS) - 1) << PT32_LEVEL_SHIFT(level))
111 #define PT32_INDEX(address, level)\
112 (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
115 #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
116 #define PT64_DIR_BASE_ADDR_MASK \
117 (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
119 #define PT32_BASE_ADDR_MASK PAGE_MASK
120 #define PT32_DIR_BASE_ADDR_MASK \
121 (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
123 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK \
124 | PT64_NX_MASK)
126 #define PFERR_PRESENT_MASK (1U << 0)
127 #define PFERR_WRITE_MASK (1U << 1)
128 #define PFERR_USER_MASK (1U << 2)
129 #define PFERR_FETCH_MASK (1U << 4)
131 #define PT_DIRECTORY_LEVEL 2
132 #define PT_PAGE_TABLE_LEVEL 1
134 #define RMAP_EXT 4
136 #define ACC_EXEC_MASK 1
137 #define ACC_WRITE_MASK PT_WRITABLE_MASK
138 #define ACC_USER_MASK PT_USER_MASK
139 #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
141 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
143 struct kvm_rmap_desc {
144 u64 *shadow_ptes[RMAP_EXT];
145 struct kvm_rmap_desc *more;
148 struct kvm_shadow_walk_iterator {
149 u64 addr;
150 hpa_t shadow_addr;
151 int level;
152 u64 *sptep;
153 unsigned index;
156 #define for_each_shadow_entry(_vcpu, _addr, _walker) \
157 for (shadow_walk_init(&(_walker), _vcpu, _addr); \
158 shadow_walk_okay(&(_walker)); \
159 shadow_walk_next(&(_walker)))
162 struct kvm_unsync_walk {
163 int (*entry) (struct kvm_mmu_page *sp, struct kvm_unsync_walk *walk);
166 typedef int (*mmu_parent_walk_fn) (struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp);
168 static struct kmem_cache *pte_chain_cache;
169 static struct kmem_cache *rmap_desc_cache;
170 static struct kmem_cache *mmu_page_header_cache;
172 static u64 __read_mostly shadow_trap_nonpresent_pte;
173 static u64 __read_mostly shadow_notrap_nonpresent_pte;
174 static u64 __read_mostly shadow_base_present_pte;
175 static u64 __read_mostly shadow_nx_mask;
176 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
177 static u64 __read_mostly shadow_user_mask;
178 static u64 __read_mostly shadow_accessed_mask;
179 static u64 __read_mostly shadow_dirty_mask;
180 static u64 __read_mostly shadow_mt_mask;
182 void kvm_mmu_set_nonpresent_ptes(u64 trap_pte, u64 notrap_pte)
184 shadow_trap_nonpresent_pte = trap_pte;
185 shadow_notrap_nonpresent_pte = notrap_pte;
187 EXPORT_SYMBOL_GPL(kvm_mmu_set_nonpresent_ptes);
189 void kvm_mmu_set_base_ptes(u64 base_pte)
191 shadow_base_present_pte = base_pte;
193 EXPORT_SYMBOL_GPL(kvm_mmu_set_base_ptes);
195 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
196 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 mt_mask)
198 shadow_user_mask = user_mask;
199 shadow_accessed_mask = accessed_mask;
200 shadow_dirty_mask = dirty_mask;
201 shadow_nx_mask = nx_mask;
202 shadow_x_mask = x_mask;
203 shadow_mt_mask = mt_mask;
205 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
207 static int is_write_protection(struct kvm_vcpu *vcpu)
209 return vcpu->arch.cr0 & X86_CR0_WP;
212 static int is_cpuid_PSE36(void)
214 return 1;
217 static int is_nx(struct kvm_vcpu *vcpu)
219 return vcpu->arch.shadow_efer & EFER_NX;
222 static int is_present_pte(unsigned long pte)
224 return pte & PT_PRESENT_MASK;
227 static int is_shadow_present_pte(u64 pte)
229 return pte != shadow_trap_nonpresent_pte
230 && pte != shadow_notrap_nonpresent_pte;
233 static int is_large_pte(u64 pte)
235 return pte & PT_PAGE_SIZE_MASK;
238 static int is_writeble_pte(unsigned long pte)
240 return pte & PT_WRITABLE_MASK;
243 static int is_dirty_pte(unsigned long pte)
245 return pte & shadow_dirty_mask;
248 static int is_rmap_pte(u64 pte)
250 return is_shadow_present_pte(pte);
253 static pfn_t spte_to_pfn(u64 pte)
255 return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
258 static gfn_t pse36_gfn_delta(u32 gpte)
260 int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
262 return (gpte & PT32_DIR_PSE36_MASK) << shift;
265 static void set_shadow_pte(u64 *sptep, u64 spte)
267 #ifdef CONFIG_X86_64
268 set_64bit((unsigned long *)sptep, spte);
269 #else
270 set_64bit((unsigned long long *)sptep, spte);
271 #endif
274 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
275 struct kmem_cache *base_cache, int min)
277 void *obj;
279 if (cache->nobjs >= min)
280 return 0;
281 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
282 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
283 if (!obj)
284 return -ENOMEM;
285 cache->objects[cache->nobjs++] = obj;
287 return 0;
290 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
292 while (mc->nobjs)
293 kfree(mc->objects[--mc->nobjs]);
296 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
297 int min)
299 struct page *page;
301 if (cache->nobjs >= min)
302 return 0;
303 while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
304 page = alloc_page(GFP_KERNEL);
305 if (!page)
306 return -ENOMEM;
307 set_page_private(page, 0);
308 cache->objects[cache->nobjs++] = page_address(page);
310 return 0;
313 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
315 while (mc->nobjs)
316 free_page((unsigned long)mc->objects[--mc->nobjs]);
319 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
321 int r;
323 r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_chain_cache,
324 pte_chain_cache, 4);
325 if (r)
326 goto out;
327 r = mmu_topup_memory_cache(&vcpu->arch.mmu_rmap_desc_cache,
328 rmap_desc_cache, 4);
329 if (r)
330 goto out;
331 r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
332 if (r)
333 goto out;
334 r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
335 mmu_page_header_cache, 4);
336 out:
337 return r;
340 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
342 mmu_free_memory_cache(&vcpu->arch.mmu_pte_chain_cache);
343 mmu_free_memory_cache(&vcpu->arch.mmu_rmap_desc_cache);
344 mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
345 mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
348 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc,
349 size_t size)
351 void *p;
353 BUG_ON(!mc->nobjs);
354 p = mc->objects[--mc->nobjs];
355 return p;
358 static struct kvm_pte_chain *mmu_alloc_pte_chain(struct kvm_vcpu *vcpu)
360 return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_chain_cache,
361 sizeof(struct kvm_pte_chain));
364 static void mmu_free_pte_chain(struct kvm_pte_chain *pc)
366 kfree(pc);
369 static struct kvm_rmap_desc *mmu_alloc_rmap_desc(struct kvm_vcpu *vcpu)
371 return mmu_memory_cache_alloc(&vcpu->arch.mmu_rmap_desc_cache,
372 sizeof(struct kvm_rmap_desc));
375 static void mmu_free_rmap_desc(struct kvm_rmap_desc *rd)
377 kfree(rd);
381 * Return the pointer to the largepage write count for a given
382 * gfn, handling slots that are not large page aligned.
384 static int *slot_largepage_idx(gfn_t gfn, struct kvm_memory_slot *slot)
386 unsigned long idx;
388 idx = (gfn / KVM_PAGES_PER_HPAGE) -
389 (slot->base_gfn / KVM_PAGES_PER_HPAGE);
390 return &slot->lpage_info[idx].write_count;
393 static void account_shadowed(struct kvm *kvm, gfn_t gfn)
395 int *write_count;
397 gfn = unalias_gfn(kvm, gfn);
398 write_count = slot_largepage_idx(gfn,
399 gfn_to_memslot_unaliased(kvm, gfn));
400 *write_count += 1;
403 static void unaccount_shadowed(struct kvm *kvm, gfn_t gfn)
405 int *write_count;
407 gfn = unalias_gfn(kvm, gfn);
408 write_count = slot_largepage_idx(gfn,
409 gfn_to_memslot_unaliased(kvm, gfn));
410 *write_count -= 1;
411 WARN_ON(*write_count < 0);
414 static int has_wrprotected_page(struct kvm *kvm, gfn_t gfn)
416 struct kvm_memory_slot *slot;
417 int *largepage_idx;
419 gfn = unalias_gfn(kvm, gfn);
420 slot = gfn_to_memslot_unaliased(kvm, gfn);
421 if (slot) {
422 largepage_idx = slot_largepage_idx(gfn, slot);
423 return *largepage_idx;
426 return 1;
429 static int host_largepage_backed(struct kvm *kvm, gfn_t gfn)
431 struct vm_area_struct *vma;
432 unsigned long addr;
433 int ret = 0;
435 addr = gfn_to_hva(kvm, gfn);
436 if (kvm_is_error_hva(addr))
437 return ret;
439 down_read(&current->mm->mmap_sem);
440 vma = find_vma(current->mm, addr);
441 if (vma && is_vm_hugetlb_page(vma))
442 ret = 1;
443 up_read(&current->mm->mmap_sem);
445 return ret;
448 static int is_largepage_backed(struct kvm_vcpu *vcpu, gfn_t large_gfn)
450 struct kvm_memory_slot *slot;
452 if (has_wrprotected_page(vcpu->kvm, large_gfn))
453 return 0;
455 if (!host_largepage_backed(vcpu->kvm, large_gfn))
456 return 0;
458 slot = gfn_to_memslot(vcpu->kvm, large_gfn);
459 if (slot && slot->dirty_bitmap)
460 return 0;
462 return 1;
466 * Take gfn and return the reverse mapping to it.
467 * Note: gfn must be unaliased before this function get called
470 static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn, int lpage)
472 struct kvm_memory_slot *slot;
473 unsigned long idx;
475 slot = gfn_to_memslot(kvm, gfn);
476 if (!lpage)
477 return &slot->rmap[gfn - slot->base_gfn];
479 idx = (gfn / KVM_PAGES_PER_HPAGE) -
480 (slot->base_gfn / KVM_PAGES_PER_HPAGE);
482 return &slot->lpage_info[idx].rmap_pde;
486 * Reverse mapping data structures:
488 * If rmapp bit zero is zero, then rmapp point to the shadw page table entry
489 * that points to page_address(page).
491 * If rmapp bit zero is one, (then rmap & ~1) points to a struct kvm_rmap_desc
492 * containing more mappings.
494 * Returns the number of rmap entries before the spte was added or zero if
495 * the spte was not added.
498 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn, int lpage)
500 struct kvm_mmu_page *sp;
501 struct kvm_rmap_desc *desc;
502 unsigned long *rmapp;
503 int i, count = 0;
505 if (!is_rmap_pte(*spte))
506 return count;
507 gfn = unalias_gfn(vcpu->kvm, gfn);
508 sp = page_header(__pa(spte));
509 sp->gfns[spte - sp->spt] = gfn;
510 rmapp = gfn_to_rmap(vcpu->kvm, gfn, lpage);
511 if (!*rmapp) {
512 rmap_printk("rmap_add: %p %llx 0->1\n", spte, *spte);
513 *rmapp = (unsigned long)spte;
514 } else if (!(*rmapp & 1)) {
515 rmap_printk("rmap_add: %p %llx 1->many\n", spte, *spte);
516 desc = mmu_alloc_rmap_desc(vcpu);
517 desc->shadow_ptes[0] = (u64 *)*rmapp;
518 desc->shadow_ptes[1] = spte;
519 *rmapp = (unsigned long)desc | 1;
520 } else {
521 rmap_printk("rmap_add: %p %llx many->many\n", spte, *spte);
522 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
523 while (desc->shadow_ptes[RMAP_EXT-1] && desc->more) {
524 desc = desc->more;
525 count += RMAP_EXT;
527 if (desc->shadow_ptes[RMAP_EXT-1]) {
528 desc->more = mmu_alloc_rmap_desc(vcpu);
529 desc = desc->more;
531 for (i = 0; desc->shadow_ptes[i]; ++i)
533 desc->shadow_ptes[i] = spte;
535 return count;
538 static void rmap_desc_remove_entry(unsigned long *rmapp,
539 struct kvm_rmap_desc *desc,
540 int i,
541 struct kvm_rmap_desc *prev_desc)
543 int j;
545 for (j = RMAP_EXT - 1; !desc->shadow_ptes[j] && j > i; --j)
547 desc->shadow_ptes[i] = desc->shadow_ptes[j];
548 desc->shadow_ptes[j] = NULL;
549 if (j != 0)
550 return;
551 if (!prev_desc && !desc->more)
552 *rmapp = (unsigned long)desc->shadow_ptes[0];
553 else
554 if (prev_desc)
555 prev_desc->more = desc->more;
556 else
557 *rmapp = (unsigned long)desc->more | 1;
558 mmu_free_rmap_desc(desc);
561 static void rmap_remove(struct kvm *kvm, u64 *spte)
563 struct kvm_rmap_desc *desc;
564 struct kvm_rmap_desc *prev_desc;
565 struct kvm_mmu_page *sp;
566 pfn_t pfn;
567 unsigned long *rmapp;
568 int i;
570 if (!is_rmap_pte(*spte))
571 return;
572 sp = page_header(__pa(spte));
573 pfn = spte_to_pfn(*spte);
574 if (*spte & shadow_accessed_mask)
575 kvm_set_pfn_accessed(pfn);
576 if (is_writeble_pte(*spte))
577 kvm_release_pfn_dirty(pfn);
578 else
579 kvm_release_pfn_clean(pfn);
580 rmapp = gfn_to_rmap(kvm, sp->gfns[spte - sp->spt], is_large_pte(*spte));
581 if (!*rmapp) {
582 printk(KERN_ERR "rmap_remove: %p %llx 0->BUG\n", spte, *spte);
583 BUG();
584 } else if (!(*rmapp & 1)) {
585 rmap_printk("rmap_remove: %p %llx 1->0\n", spte, *spte);
586 if ((u64 *)*rmapp != spte) {
587 printk(KERN_ERR "rmap_remove: %p %llx 1->BUG\n",
588 spte, *spte);
589 BUG();
591 *rmapp = 0;
592 } else {
593 rmap_printk("rmap_remove: %p %llx many->many\n", spte, *spte);
594 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
595 prev_desc = NULL;
596 while (desc) {
597 for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i)
598 if (desc->shadow_ptes[i] == spte) {
599 rmap_desc_remove_entry(rmapp,
600 desc, i,
601 prev_desc);
602 return;
604 prev_desc = desc;
605 desc = desc->more;
607 BUG();
611 static u64 *rmap_next(struct kvm *kvm, unsigned long *rmapp, u64 *spte)
613 struct kvm_rmap_desc *desc;
614 struct kvm_rmap_desc *prev_desc;
615 u64 *prev_spte;
616 int i;
618 if (!*rmapp)
619 return NULL;
620 else if (!(*rmapp & 1)) {
621 if (!spte)
622 return (u64 *)*rmapp;
623 return NULL;
625 desc = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
626 prev_desc = NULL;
627 prev_spte = NULL;
628 while (desc) {
629 for (i = 0; i < RMAP_EXT && desc->shadow_ptes[i]; ++i) {
630 if (prev_spte == spte)
631 return desc->shadow_ptes[i];
632 prev_spte = desc->shadow_ptes[i];
634 desc = desc->more;
636 return NULL;
639 static int rmap_write_protect(struct kvm *kvm, u64 gfn)
641 unsigned long *rmapp;
642 u64 *spte;
643 int write_protected = 0;
645 gfn = unalias_gfn(kvm, gfn);
646 rmapp = gfn_to_rmap(kvm, gfn, 0);
648 spte = rmap_next(kvm, rmapp, NULL);
649 while (spte) {
650 BUG_ON(!spte);
651 BUG_ON(!(*spte & PT_PRESENT_MASK));
652 rmap_printk("rmap_write_protect: spte %p %llx\n", spte, *spte);
653 if (is_writeble_pte(*spte)) {
654 set_shadow_pte(spte, *spte & ~PT_WRITABLE_MASK);
655 write_protected = 1;
657 spte = rmap_next(kvm, rmapp, spte);
659 if (write_protected) {
660 pfn_t pfn;
662 spte = rmap_next(kvm, rmapp, NULL);
663 pfn = spte_to_pfn(*spte);
664 kvm_set_pfn_dirty(pfn);
667 /* check for huge page mappings */
668 rmapp = gfn_to_rmap(kvm, gfn, 1);
669 spte = rmap_next(kvm, rmapp, NULL);
670 while (spte) {
671 BUG_ON(!spte);
672 BUG_ON(!(*spte & PT_PRESENT_MASK));
673 BUG_ON((*spte & (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK)) != (PT_PAGE_SIZE_MASK|PT_PRESENT_MASK));
674 pgprintk("rmap_write_protect(large): spte %p %llx %lld\n", spte, *spte, gfn);
675 if (is_writeble_pte(*spte)) {
676 rmap_remove(kvm, spte);
677 --kvm->stat.lpages;
678 set_shadow_pte(spte, shadow_trap_nonpresent_pte);
679 spte = NULL;
680 write_protected = 1;
682 spte = rmap_next(kvm, rmapp, spte);
685 return write_protected;
688 static int kvm_unmap_rmapp(struct kvm *kvm, unsigned long *rmapp)
690 u64 *spte;
691 int need_tlb_flush = 0;
693 while ((spte = rmap_next(kvm, rmapp, NULL))) {
694 BUG_ON(!(*spte & PT_PRESENT_MASK));
695 rmap_printk("kvm_rmap_unmap_hva: spte %p %llx\n", spte, *spte);
696 rmap_remove(kvm, spte);
697 set_shadow_pte(spte, shadow_trap_nonpresent_pte);
698 need_tlb_flush = 1;
700 return need_tlb_flush;
703 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
704 int (*handler)(struct kvm *kvm, unsigned long *rmapp))
706 int i;
707 int retval = 0;
710 * If mmap_sem isn't taken, we can look the memslots with only
711 * the mmu_lock by skipping over the slots with userspace_addr == 0.
713 for (i = 0; i < kvm->nmemslots; i++) {
714 struct kvm_memory_slot *memslot = &kvm->memslots[i];
715 unsigned long start = memslot->userspace_addr;
716 unsigned long end;
718 /* mmu_lock protects userspace_addr */
719 if (!start)
720 continue;
722 end = start + (memslot->npages << PAGE_SHIFT);
723 if (hva >= start && hva < end) {
724 gfn_t gfn_offset = (hva - start) >> PAGE_SHIFT;
725 retval |= handler(kvm, &memslot->rmap[gfn_offset]);
726 retval |= handler(kvm,
727 &memslot->lpage_info[
728 gfn_offset /
729 KVM_PAGES_PER_HPAGE].rmap_pde);
733 return retval;
736 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
738 return kvm_handle_hva(kvm, hva, kvm_unmap_rmapp);
741 static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp)
743 u64 *spte;
744 int young = 0;
746 /* always return old for EPT */
747 if (!shadow_accessed_mask)
748 return 0;
750 spte = rmap_next(kvm, rmapp, NULL);
751 while (spte) {
752 int _young;
753 u64 _spte = *spte;
754 BUG_ON(!(_spte & PT_PRESENT_MASK));
755 _young = _spte & PT_ACCESSED_MASK;
756 if (_young) {
757 young = 1;
758 clear_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
760 spte = rmap_next(kvm, rmapp, spte);
762 return young;
765 #define RMAP_RECYCLE_THRESHOLD 1000
767 static void rmap_recycle(struct kvm_vcpu *vcpu, gfn_t gfn, int lpage)
769 unsigned long *rmapp;
771 gfn = unalias_gfn(vcpu->kvm, gfn);
772 rmapp = gfn_to_rmap(vcpu->kvm, gfn, lpage);
774 kvm_unmap_rmapp(vcpu->kvm, rmapp);
775 kvm_flush_remote_tlbs(vcpu->kvm);
778 int kvm_age_hva(struct kvm *kvm, unsigned long hva)
780 return kvm_handle_hva(kvm, hva, kvm_age_rmapp);
783 #ifdef MMU_DEBUG
784 static int is_empty_shadow_page(u64 *spt)
786 u64 *pos;
787 u64 *end;
789 for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
790 if (is_shadow_present_pte(*pos)) {
791 printk(KERN_ERR "%s: %p %llx\n", __func__,
792 pos, *pos);
793 return 0;
795 return 1;
797 #endif
799 static void kvm_mmu_free_page(struct kvm *kvm, struct kvm_mmu_page *sp)
801 ASSERT(is_empty_shadow_page(sp->spt));
802 list_del(&sp->link);
803 __free_page(virt_to_page(sp->spt));
804 __free_page(virt_to_page(sp->gfns));
805 kfree(sp);
806 ++kvm->arch.n_free_mmu_pages;
809 static unsigned kvm_page_table_hashfn(gfn_t gfn)
811 return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
814 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
815 u64 *parent_pte)
817 struct kvm_mmu_page *sp;
819 sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache, sizeof *sp);
820 sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
821 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache, PAGE_SIZE);
822 set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
823 list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
824 INIT_LIST_HEAD(&sp->oos_link);
825 bitmap_zero(sp->slot_bitmap, KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS);
826 sp->multimapped = 0;
827 sp->parent_pte = parent_pte;
828 --vcpu->kvm->arch.n_free_mmu_pages;
829 return sp;
832 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
833 struct kvm_mmu_page *sp, u64 *parent_pte)
835 struct kvm_pte_chain *pte_chain;
836 struct hlist_node *node;
837 int i;
839 if (!parent_pte)
840 return;
841 if (!sp->multimapped) {
842 u64 *old = sp->parent_pte;
844 if (!old) {
845 sp->parent_pte = parent_pte;
846 return;
848 sp->multimapped = 1;
849 pte_chain = mmu_alloc_pte_chain(vcpu);
850 INIT_HLIST_HEAD(&sp->parent_ptes);
851 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
852 pte_chain->parent_ptes[0] = old;
854 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link) {
855 if (pte_chain->parent_ptes[NR_PTE_CHAIN_ENTRIES-1])
856 continue;
857 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i)
858 if (!pte_chain->parent_ptes[i]) {
859 pte_chain->parent_ptes[i] = parent_pte;
860 return;
863 pte_chain = mmu_alloc_pte_chain(vcpu);
864 BUG_ON(!pte_chain);
865 hlist_add_head(&pte_chain->link, &sp->parent_ptes);
866 pte_chain->parent_ptes[0] = parent_pte;
869 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
870 u64 *parent_pte)
872 struct kvm_pte_chain *pte_chain;
873 struct hlist_node *node;
874 int i;
876 if (!sp->multimapped) {
877 BUG_ON(sp->parent_pte != parent_pte);
878 sp->parent_pte = NULL;
879 return;
881 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
882 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
883 if (!pte_chain->parent_ptes[i])
884 break;
885 if (pte_chain->parent_ptes[i] != parent_pte)
886 continue;
887 while (i + 1 < NR_PTE_CHAIN_ENTRIES
888 && pte_chain->parent_ptes[i + 1]) {
889 pte_chain->parent_ptes[i]
890 = pte_chain->parent_ptes[i + 1];
891 ++i;
893 pte_chain->parent_ptes[i] = NULL;
894 if (i == 0) {
895 hlist_del(&pte_chain->link);
896 mmu_free_pte_chain(pte_chain);
897 if (hlist_empty(&sp->parent_ptes)) {
898 sp->multimapped = 0;
899 sp->parent_pte = NULL;
902 return;
904 BUG();
908 static void mmu_parent_walk(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
909 mmu_parent_walk_fn fn)
911 struct kvm_pte_chain *pte_chain;
912 struct hlist_node *node;
913 struct kvm_mmu_page *parent_sp;
914 int i;
916 if (!sp->multimapped && sp->parent_pte) {
917 parent_sp = page_header(__pa(sp->parent_pte));
918 fn(vcpu, parent_sp);
919 mmu_parent_walk(vcpu, parent_sp, fn);
920 return;
922 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
923 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
924 if (!pte_chain->parent_ptes[i])
925 break;
926 parent_sp = page_header(__pa(pte_chain->parent_ptes[i]));
927 fn(vcpu, parent_sp);
928 mmu_parent_walk(vcpu, parent_sp, fn);
932 static void kvm_mmu_update_unsync_bitmap(u64 *spte)
934 unsigned int index;
935 struct kvm_mmu_page *sp = page_header(__pa(spte));
937 index = spte - sp->spt;
938 if (!__test_and_set_bit(index, sp->unsync_child_bitmap))
939 sp->unsync_children++;
940 WARN_ON(!sp->unsync_children);
943 static void kvm_mmu_update_parents_unsync(struct kvm_mmu_page *sp)
945 struct kvm_pte_chain *pte_chain;
946 struct hlist_node *node;
947 int i;
949 if (!sp->parent_pte)
950 return;
952 if (!sp->multimapped) {
953 kvm_mmu_update_unsync_bitmap(sp->parent_pte);
954 return;
957 hlist_for_each_entry(pte_chain, node, &sp->parent_ptes, link)
958 for (i = 0; i < NR_PTE_CHAIN_ENTRIES; ++i) {
959 if (!pte_chain->parent_ptes[i])
960 break;
961 kvm_mmu_update_unsync_bitmap(pte_chain->parent_ptes[i]);
965 static int unsync_walk_fn(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
967 kvm_mmu_update_parents_unsync(sp);
968 return 1;
971 static void kvm_mmu_mark_parents_unsync(struct kvm_vcpu *vcpu,
972 struct kvm_mmu_page *sp)
974 mmu_parent_walk(vcpu, sp, unsync_walk_fn);
975 kvm_mmu_update_parents_unsync(sp);
978 static void nonpaging_prefetch_page(struct kvm_vcpu *vcpu,
979 struct kvm_mmu_page *sp)
981 int i;
983 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
984 sp->spt[i] = shadow_trap_nonpresent_pte;
987 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
988 struct kvm_mmu_page *sp)
990 return 1;
993 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
997 #define KVM_PAGE_ARRAY_NR 16
999 struct kvm_mmu_pages {
1000 struct mmu_page_and_offset {
1001 struct kvm_mmu_page *sp;
1002 unsigned int idx;
1003 } page[KVM_PAGE_ARRAY_NR];
1004 unsigned int nr;
1007 #define for_each_unsync_children(bitmap, idx) \
1008 for (idx = find_first_bit(bitmap, 512); \
1009 idx < 512; \
1010 idx = find_next_bit(bitmap, 512, idx+1))
1012 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1013 int idx)
1015 int i;
1017 if (sp->unsync)
1018 for (i=0; i < pvec->nr; i++)
1019 if (pvec->page[i].sp == sp)
1020 return 0;
1022 pvec->page[pvec->nr].sp = sp;
1023 pvec->page[pvec->nr].idx = idx;
1024 pvec->nr++;
1025 return (pvec->nr == KVM_PAGE_ARRAY_NR);
1028 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1029 struct kvm_mmu_pages *pvec)
1031 int i, ret, nr_unsync_leaf = 0;
1033 for_each_unsync_children(sp->unsync_child_bitmap, i) {
1034 u64 ent = sp->spt[i];
1036 if (is_shadow_present_pte(ent) && !is_large_pte(ent)) {
1037 struct kvm_mmu_page *child;
1038 child = page_header(ent & PT64_BASE_ADDR_MASK);
1040 if (child->unsync_children) {
1041 if (mmu_pages_add(pvec, child, i))
1042 return -ENOSPC;
1044 ret = __mmu_unsync_walk(child, pvec);
1045 if (!ret)
1046 __clear_bit(i, sp->unsync_child_bitmap);
1047 else if (ret > 0)
1048 nr_unsync_leaf += ret;
1049 else
1050 return ret;
1053 if (child->unsync) {
1054 nr_unsync_leaf++;
1055 if (mmu_pages_add(pvec, child, i))
1056 return -ENOSPC;
1061 if (find_first_bit(sp->unsync_child_bitmap, 512) == 512)
1062 sp->unsync_children = 0;
1064 return nr_unsync_leaf;
1067 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1068 struct kvm_mmu_pages *pvec)
1070 if (!sp->unsync_children)
1071 return 0;
1073 mmu_pages_add(pvec, sp, 0);
1074 return __mmu_unsync_walk(sp, pvec);
1077 static struct kvm_mmu_page *kvm_mmu_lookup_page(struct kvm *kvm, gfn_t gfn)
1079 unsigned index;
1080 struct hlist_head *bucket;
1081 struct kvm_mmu_page *sp;
1082 struct hlist_node *node;
1084 pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1085 index = kvm_page_table_hashfn(gfn);
1086 bucket = &kvm->arch.mmu_page_hash[index];
1087 hlist_for_each_entry(sp, node, bucket, hash_link)
1088 if (sp->gfn == gfn && !sp->role.direct
1089 && !sp->role.invalid) {
1090 pgprintk("%s: found role %x\n",
1091 __func__, sp->role.word);
1092 return sp;
1094 return NULL;
1097 static void kvm_unlink_unsync_global(struct kvm *kvm, struct kvm_mmu_page *sp)
1099 list_del(&sp->oos_link);
1100 --kvm->stat.mmu_unsync_global;
1103 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1105 WARN_ON(!sp->unsync);
1106 sp->unsync = 0;
1107 if (sp->global)
1108 kvm_unlink_unsync_global(kvm, sp);
1109 --kvm->stat.mmu_unsync;
1112 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp);
1114 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1116 if (sp->role.glevels != vcpu->arch.mmu.root_level) {
1117 kvm_mmu_zap_page(vcpu->kvm, sp);
1118 return 1;
1121 if (rmap_write_protect(vcpu->kvm, sp->gfn))
1122 kvm_flush_remote_tlbs(vcpu->kvm);
1123 kvm_unlink_unsync_page(vcpu->kvm, sp);
1124 if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
1125 kvm_mmu_zap_page(vcpu->kvm, sp);
1126 return 1;
1129 kvm_mmu_flush_tlb(vcpu);
1130 return 0;
1133 struct mmu_page_path {
1134 struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
1135 unsigned int idx[PT64_ROOT_LEVEL-1];
1138 #define for_each_sp(pvec, sp, parents, i) \
1139 for (i = mmu_pages_next(&pvec, &parents, -1), \
1140 sp = pvec.page[i].sp; \
1141 i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
1142 i = mmu_pages_next(&pvec, &parents, i))
1144 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1145 struct mmu_page_path *parents,
1146 int i)
1148 int n;
1150 for (n = i+1; n < pvec->nr; n++) {
1151 struct kvm_mmu_page *sp = pvec->page[n].sp;
1153 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1154 parents->idx[0] = pvec->page[n].idx;
1155 return n;
1158 parents->parent[sp->role.level-2] = sp;
1159 parents->idx[sp->role.level-1] = pvec->page[n].idx;
1162 return n;
1165 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1167 struct kvm_mmu_page *sp;
1168 unsigned int level = 0;
1170 do {
1171 unsigned int idx = parents->idx[level];
1173 sp = parents->parent[level];
1174 if (!sp)
1175 return;
1177 --sp->unsync_children;
1178 WARN_ON((int)sp->unsync_children < 0);
1179 __clear_bit(idx, sp->unsync_child_bitmap);
1180 level++;
1181 } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
1184 static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
1185 struct mmu_page_path *parents,
1186 struct kvm_mmu_pages *pvec)
1188 parents->parent[parent->role.level-1] = NULL;
1189 pvec->nr = 0;
1192 static void mmu_sync_children(struct kvm_vcpu *vcpu,
1193 struct kvm_mmu_page *parent)
1195 int i;
1196 struct kvm_mmu_page *sp;
1197 struct mmu_page_path parents;
1198 struct kvm_mmu_pages pages;
1200 kvm_mmu_pages_init(parent, &parents, &pages);
1201 while (mmu_unsync_walk(parent, &pages)) {
1202 int protected = 0;
1204 for_each_sp(pages, sp, parents, i)
1205 protected |= rmap_write_protect(vcpu->kvm, sp->gfn);
1207 if (protected)
1208 kvm_flush_remote_tlbs(vcpu->kvm);
1210 for_each_sp(pages, sp, parents, i) {
1211 kvm_sync_page(vcpu, sp);
1212 mmu_pages_clear_parents(&parents);
1214 cond_resched_lock(&vcpu->kvm->mmu_lock);
1215 kvm_mmu_pages_init(parent, &parents, &pages);
1219 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
1220 gfn_t gfn,
1221 gva_t gaddr,
1222 unsigned level,
1223 int direct,
1224 unsigned access,
1225 u64 *parent_pte)
1227 union kvm_mmu_page_role role;
1228 unsigned index;
1229 unsigned quadrant;
1230 struct hlist_head *bucket;
1231 struct kvm_mmu_page *sp;
1232 struct hlist_node *node, *tmp;
1234 role = vcpu->arch.mmu.base_role;
1235 role.level = level;
1236 role.direct = direct;
1237 role.access = access;
1238 if (vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
1239 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
1240 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
1241 role.quadrant = quadrant;
1243 pgprintk("%s: looking gfn %lx role %x\n", __func__,
1244 gfn, role.word);
1245 index = kvm_page_table_hashfn(gfn);
1246 bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1247 hlist_for_each_entry_safe(sp, node, tmp, bucket, hash_link)
1248 if (sp->gfn == gfn) {
1249 if (sp->unsync)
1250 if (kvm_sync_page(vcpu, sp))
1251 continue;
1253 if (sp->role.word != role.word)
1254 continue;
1256 mmu_page_add_parent_pte(vcpu, sp, parent_pte);
1257 if (sp->unsync_children) {
1258 set_bit(KVM_REQ_MMU_SYNC, &vcpu->requests);
1259 kvm_mmu_mark_parents_unsync(vcpu, sp);
1261 pgprintk("%s: found\n", __func__);
1262 return sp;
1264 ++vcpu->kvm->stat.mmu_cache_miss;
1265 sp = kvm_mmu_alloc_page(vcpu, parent_pte);
1266 if (!sp)
1267 return sp;
1268 pgprintk("%s: adding gfn %lx role %x\n", __func__, gfn, role.word);
1269 sp->gfn = gfn;
1270 sp->role = role;
1271 sp->global = 0;
1272 hlist_add_head(&sp->hash_link, bucket);
1273 if (!direct) {
1274 if (rmap_write_protect(vcpu->kvm, gfn))
1275 kvm_flush_remote_tlbs(vcpu->kvm);
1276 account_shadowed(vcpu->kvm, gfn);
1278 if (shadow_trap_nonpresent_pte != shadow_notrap_nonpresent_pte)
1279 vcpu->arch.mmu.prefetch_page(vcpu, sp);
1280 else
1281 nonpaging_prefetch_page(vcpu, sp);
1282 return sp;
1285 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
1286 struct kvm_vcpu *vcpu, u64 addr)
1288 iterator->addr = addr;
1289 iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
1290 iterator->level = vcpu->arch.mmu.shadow_root_level;
1291 if (iterator->level == PT32E_ROOT_LEVEL) {
1292 iterator->shadow_addr
1293 = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
1294 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
1295 --iterator->level;
1296 if (!iterator->shadow_addr)
1297 iterator->level = 0;
1301 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
1303 if (iterator->level < PT_PAGE_TABLE_LEVEL)
1304 return false;
1305 iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
1306 iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
1307 return true;
1310 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
1312 iterator->shadow_addr = *iterator->sptep & PT64_BASE_ADDR_MASK;
1313 --iterator->level;
1316 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
1317 struct kvm_mmu_page *sp)
1319 unsigned i;
1320 u64 *pt;
1321 u64 ent;
1323 pt = sp->spt;
1325 if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
1326 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1327 if (is_shadow_present_pte(pt[i]))
1328 rmap_remove(kvm, &pt[i]);
1329 pt[i] = shadow_trap_nonpresent_pte;
1331 return;
1334 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1335 ent = pt[i];
1337 if (is_shadow_present_pte(ent)) {
1338 if (!is_large_pte(ent)) {
1339 ent &= PT64_BASE_ADDR_MASK;
1340 mmu_page_remove_parent_pte(page_header(ent),
1341 &pt[i]);
1342 } else {
1343 --kvm->stat.lpages;
1344 rmap_remove(kvm, &pt[i]);
1347 pt[i] = shadow_trap_nonpresent_pte;
1351 static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
1353 mmu_page_remove_parent_pte(sp, parent_pte);
1356 static void kvm_mmu_reset_last_pte_updated(struct kvm *kvm)
1358 int i;
1360 for (i = 0; i < KVM_MAX_VCPUS; ++i)
1361 if (kvm->vcpus[i])
1362 kvm->vcpus[i]->arch.last_pte_updated = NULL;
1365 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
1367 u64 *parent_pte;
1369 while (sp->multimapped || sp->parent_pte) {
1370 if (!sp->multimapped)
1371 parent_pte = sp->parent_pte;
1372 else {
1373 struct kvm_pte_chain *chain;
1375 chain = container_of(sp->parent_ptes.first,
1376 struct kvm_pte_chain, link);
1377 parent_pte = chain->parent_ptes[0];
1379 BUG_ON(!parent_pte);
1380 kvm_mmu_put_page(sp, parent_pte);
1381 set_shadow_pte(parent_pte, shadow_trap_nonpresent_pte);
1385 static int mmu_zap_unsync_children(struct kvm *kvm,
1386 struct kvm_mmu_page *parent)
1388 int i, zapped = 0;
1389 struct mmu_page_path parents;
1390 struct kvm_mmu_pages pages;
1392 if (parent->role.level == PT_PAGE_TABLE_LEVEL)
1393 return 0;
1395 kvm_mmu_pages_init(parent, &parents, &pages);
1396 while (mmu_unsync_walk(parent, &pages)) {
1397 struct kvm_mmu_page *sp;
1399 for_each_sp(pages, sp, parents, i) {
1400 kvm_mmu_zap_page(kvm, sp);
1401 mmu_pages_clear_parents(&parents);
1403 zapped += pages.nr;
1404 kvm_mmu_pages_init(parent, &parents, &pages);
1407 return zapped;
1410 static int kvm_mmu_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1412 int ret;
1413 ++kvm->stat.mmu_shadow_zapped;
1414 ret = mmu_zap_unsync_children(kvm, sp);
1415 kvm_mmu_page_unlink_children(kvm, sp);
1416 kvm_mmu_unlink_parents(kvm, sp);
1417 kvm_flush_remote_tlbs(kvm);
1418 if (!sp->role.invalid && !sp->role.direct)
1419 unaccount_shadowed(kvm, sp->gfn);
1420 if (sp->unsync)
1421 kvm_unlink_unsync_page(kvm, sp);
1422 if (!sp->root_count) {
1423 hlist_del(&sp->hash_link);
1424 kvm_mmu_free_page(kvm, sp);
1425 } else {
1426 sp->role.invalid = 1;
1427 list_move(&sp->link, &kvm->arch.active_mmu_pages);
1428 kvm_reload_remote_mmus(kvm);
1430 kvm_mmu_reset_last_pte_updated(kvm);
1431 return ret;
1435 * Changing the number of mmu pages allocated to the vm
1436 * Note: if kvm_nr_mmu_pages is too small, you will get dead lock
1438 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int kvm_nr_mmu_pages)
1440 int used_pages;
1442 used_pages = kvm->arch.n_alloc_mmu_pages - kvm->arch.n_free_mmu_pages;
1443 used_pages = max(0, used_pages);
1446 * If we set the number of mmu pages to be smaller be than the
1447 * number of actived pages , we must to free some mmu pages before we
1448 * change the value
1451 if (used_pages > kvm_nr_mmu_pages) {
1452 while (used_pages > kvm_nr_mmu_pages) {
1453 struct kvm_mmu_page *page;
1455 page = container_of(kvm->arch.active_mmu_pages.prev,
1456 struct kvm_mmu_page, link);
1457 kvm_mmu_zap_page(kvm, page);
1458 used_pages--;
1460 kvm->arch.n_free_mmu_pages = 0;
1462 else
1463 kvm->arch.n_free_mmu_pages += kvm_nr_mmu_pages
1464 - kvm->arch.n_alloc_mmu_pages;
1466 kvm->arch.n_alloc_mmu_pages = kvm_nr_mmu_pages;
1469 static int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
1471 unsigned index;
1472 struct hlist_head *bucket;
1473 struct kvm_mmu_page *sp;
1474 struct hlist_node *node, *n;
1475 int r;
1477 pgprintk("%s: looking for gfn %lx\n", __func__, gfn);
1478 r = 0;
1479 index = kvm_page_table_hashfn(gfn);
1480 bucket = &kvm->arch.mmu_page_hash[index];
1481 hlist_for_each_entry_safe(sp, node, n, bucket, hash_link)
1482 if (sp->gfn == gfn && !sp->role.direct) {
1483 pgprintk("%s: gfn %lx role %x\n", __func__, gfn,
1484 sp->role.word);
1485 r = 1;
1486 if (kvm_mmu_zap_page(kvm, sp))
1487 n = bucket->first;
1489 return r;
1492 static void mmu_unshadow(struct kvm *kvm, gfn_t gfn)
1494 unsigned index;
1495 struct hlist_head *bucket;
1496 struct kvm_mmu_page *sp;
1497 struct hlist_node *node, *nn;
1499 index = kvm_page_table_hashfn(gfn);
1500 bucket = &kvm->arch.mmu_page_hash[index];
1501 hlist_for_each_entry_safe(sp, node, nn, bucket, hash_link) {
1502 if (sp->gfn == gfn && !sp->role.direct
1503 && !sp->role.invalid) {
1504 pgprintk("%s: zap %lx %x\n",
1505 __func__, gfn, sp->role.word);
1506 kvm_mmu_zap_page(kvm, sp);
1511 static void page_header_update_slot(struct kvm *kvm, void *pte, gfn_t gfn)
1513 int slot = memslot_id(kvm, gfn_to_memslot(kvm, gfn));
1514 struct kvm_mmu_page *sp = page_header(__pa(pte));
1516 __set_bit(slot, sp->slot_bitmap);
1519 static void mmu_convert_notrap(struct kvm_mmu_page *sp)
1521 int i;
1522 u64 *pt = sp->spt;
1524 if (shadow_trap_nonpresent_pte == shadow_notrap_nonpresent_pte)
1525 return;
1527 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
1528 if (pt[i] == shadow_notrap_nonpresent_pte)
1529 set_shadow_pte(&pt[i], shadow_trap_nonpresent_pte);
1533 struct page *gva_to_page(struct kvm_vcpu *vcpu, gva_t gva)
1535 struct page *page;
1537 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
1539 if (gpa == UNMAPPED_GVA)
1540 return NULL;
1542 page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
1544 return page;
1548 * The function is based on mtrr_type_lookup() in
1549 * arch/x86/kernel/cpu/mtrr/generic.c
1551 static int get_mtrr_type(struct mtrr_state_type *mtrr_state,
1552 u64 start, u64 end)
1554 int i;
1555 u64 base, mask;
1556 u8 prev_match, curr_match;
1557 int num_var_ranges = KVM_NR_VAR_MTRR;
1559 if (!mtrr_state->enabled)
1560 return 0xFF;
1562 /* Make end inclusive end, instead of exclusive */
1563 end--;
1565 /* Look in fixed ranges. Just return the type as per start */
1566 if (mtrr_state->have_fixed && (start < 0x100000)) {
1567 int idx;
1569 if (start < 0x80000) {
1570 idx = 0;
1571 idx += (start >> 16);
1572 return mtrr_state->fixed_ranges[idx];
1573 } else if (start < 0xC0000) {
1574 idx = 1 * 8;
1575 idx += ((start - 0x80000) >> 14);
1576 return mtrr_state->fixed_ranges[idx];
1577 } else if (start < 0x1000000) {
1578 idx = 3 * 8;
1579 idx += ((start - 0xC0000) >> 12);
1580 return mtrr_state->fixed_ranges[idx];
1585 * Look in variable ranges
1586 * Look of multiple ranges matching this address and pick type
1587 * as per MTRR precedence
1589 if (!(mtrr_state->enabled & 2))
1590 return mtrr_state->def_type;
1592 prev_match = 0xFF;
1593 for (i = 0; i < num_var_ranges; ++i) {
1594 unsigned short start_state, end_state;
1596 if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11)))
1597 continue;
1599 base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) +
1600 (mtrr_state->var_ranges[i].base_lo & PAGE_MASK);
1601 mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) +
1602 (mtrr_state->var_ranges[i].mask_lo & PAGE_MASK);
1604 start_state = ((start & mask) == (base & mask));
1605 end_state = ((end & mask) == (base & mask));
1606 if (start_state != end_state)
1607 return 0xFE;
1609 if ((start & mask) != (base & mask))
1610 continue;
1612 curr_match = mtrr_state->var_ranges[i].base_lo & 0xff;
1613 if (prev_match == 0xFF) {
1614 prev_match = curr_match;
1615 continue;
1618 if (prev_match == MTRR_TYPE_UNCACHABLE ||
1619 curr_match == MTRR_TYPE_UNCACHABLE)
1620 return MTRR_TYPE_UNCACHABLE;
1622 if ((prev_match == MTRR_TYPE_WRBACK &&
1623 curr_match == MTRR_TYPE_WRTHROUGH) ||
1624 (prev_match == MTRR_TYPE_WRTHROUGH &&
1625 curr_match == MTRR_TYPE_WRBACK)) {
1626 prev_match = MTRR_TYPE_WRTHROUGH;
1627 curr_match = MTRR_TYPE_WRTHROUGH;
1630 if (prev_match != curr_match)
1631 return MTRR_TYPE_UNCACHABLE;
1634 if (prev_match != 0xFF)
1635 return prev_match;
1637 return mtrr_state->def_type;
1640 static u8 get_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn)
1642 u8 mtrr;
1644 mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT,
1645 (gfn << PAGE_SHIFT) + PAGE_SIZE);
1646 if (mtrr == 0xfe || mtrr == 0xff)
1647 mtrr = MTRR_TYPE_WRBACK;
1648 return mtrr;
1651 static int kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1653 unsigned index;
1654 struct hlist_head *bucket;
1655 struct kvm_mmu_page *s;
1656 struct hlist_node *node, *n;
1658 index = kvm_page_table_hashfn(sp->gfn);
1659 bucket = &vcpu->kvm->arch.mmu_page_hash[index];
1660 /* don't unsync if pagetable is shadowed with multiple roles */
1661 hlist_for_each_entry_safe(s, node, n, bucket, hash_link) {
1662 if (s->gfn != sp->gfn || s->role.direct)
1663 continue;
1664 if (s->role.word != sp->role.word)
1665 return 1;
1667 ++vcpu->kvm->stat.mmu_unsync;
1668 sp->unsync = 1;
1670 if (sp->global) {
1671 list_add(&sp->oos_link, &vcpu->kvm->arch.oos_global_pages);
1672 ++vcpu->kvm->stat.mmu_unsync_global;
1673 } else
1674 kvm_mmu_mark_parents_unsync(vcpu, sp);
1676 mmu_convert_notrap(sp);
1677 return 0;
1680 static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
1681 bool can_unsync)
1683 struct kvm_mmu_page *shadow;
1685 shadow = kvm_mmu_lookup_page(vcpu->kvm, gfn);
1686 if (shadow) {
1687 if (shadow->role.level != PT_PAGE_TABLE_LEVEL)
1688 return 1;
1689 if (shadow->unsync)
1690 return 0;
1691 if (can_unsync && oos_shadow)
1692 return kvm_unsync_page(vcpu, shadow);
1693 return 1;
1695 return 0;
1698 static int set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
1699 unsigned pte_access, int user_fault,
1700 int write_fault, int dirty, int largepage,
1701 int global, gfn_t gfn, pfn_t pfn, bool speculative,
1702 bool can_unsync)
1704 u64 spte;
1705 int ret = 0;
1706 u64 mt_mask = shadow_mt_mask;
1707 struct kvm_mmu_page *sp = page_header(__pa(shadow_pte));
1709 if (!global && sp->global) {
1710 sp->global = 0;
1711 if (sp->unsync) {
1712 kvm_unlink_unsync_global(vcpu->kvm, sp);
1713 kvm_mmu_mark_parents_unsync(vcpu, sp);
1718 * We don't set the accessed bit, since we sometimes want to see
1719 * whether the guest actually used the pte (in order to detect
1720 * demand paging).
1722 spte = shadow_base_present_pte | shadow_dirty_mask;
1723 if (!speculative)
1724 spte |= shadow_accessed_mask;
1725 if (!dirty)
1726 pte_access &= ~ACC_WRITE_MASK;
1727 if (pte_access & ACC_EXEC_MASK)
1728 spte |= shadow_x_mask;
1729 else
1730 spte |= shadow_nx_mask;
1731 if (pte_access & ACC_USER_MASK)
1732 spte |= shadow_user_mask;
1733 if (largepage)
1734 spte |= PT_PAGE_SIZE_MASK;
1735 if (mt_mask) {
1736 if (!kvm_is_mmio_pfn(pfn)) {
1737 mt_mask = get_memory_type(vcpu, gfn) <<
1738 kvm_x86_ops->get_mt_mask_shift();
1739 mt_mask |= VMX_EPT_IGMT_BIT;
1740 } else
1741 mt_mask = MTRR_TYPE_UNCACHABLE <<
1742 kvm_x86_ops->get_mt_mask_shift();
1743 spte |= mt_mask;
1746 spte |= (u64)pfn << PAGE_SHIFT;
1748 if ((pte_access & ACC_WRITE_MASK)
1749 || (write_fault && !is_write_protection(vcpu) && !user_fault)) {
1751 if (largepage && has_wrprotected_page(vcpu->kvm, gfn)) {
1752 ret = 1;
1753 spte = shadow_trap_nonpresent_pte;
1754 goto set_pte;
1757 spte |= PT_WRITABLE_MASK;
1760 * Optimization: for pte sync, if spte was writable the hash
1761 * lookup is unnecessary (and expensive). Write protection
1762 * is responsibility of mmu_get_page / kvm_sync_page.
1763 * Same reasoning can be applied to dirty page accounting.
1765 if (!can_unsync && is_writeble_pte(*shadow_pte))
1766 goto set_pte;
1768 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
1769 pgprintk("%s: found shadow page for %lx, marking ro\n",
1770 __func__, gfn);
1771 ret = 1;
1772 pte_access &= ~ACC_WRITE_MASK;
1773 if (is_writeble_pte(spte))
1774 spte &= ~PT_WRITABLE_MASK;
1778 if (pte_access & ACC_WRITE_MASK)
1779 mark_page_dirty(vcpu->kvm, gfn);
1781 set_pte:
1782 set_shadow_pte(shadow_pte, spte);
1783 return ret;
1786 static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *shadow_pte,
1787 unsigned pt_access, unsigned pte_access,
1788 int user_fault, int write_fault, int dirty,
1789 int *ptwrite, int largepage, int global,
1790 gfn_t gfn, pfn_t pfn, bool speculative)
1792 int was_rmapped = 0;
1793 int was_writeble = is_writeble_pte(*shadow_pte);
1794 int rmap_count;
1796 pgprintk("%s: spte %llx access %x write_fault %d"
1797 " user_fault %d gfn %lx\n",
1798 __func__, *shadow_pte, pt_access,
1799 write_fault, user_fault, gfn);
1801 if (is_rmap_pte(*shadow_pte)) {
1803 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
1804 * the parent of the now unreachable PTE.
1806 if (largepage && !is_large_pte(*shadow_pte)) {
1807 struct kvm_mmu_page *child;
1808 u64 pte = *shadow_pte;
1810 child = page_header(pte & PT64_BASE_ADDR_MASK);
1811 mmu_page_remove_parent_pte(child, shadow_pte);
1812 } else if (pfn != spte_to_pfn(*shadow_pte)) {
1813 pgprintk("hfn old %lx new %lx\n",
1814 spte_to_pfn(*shadow_pte), pfn);
1815 rmap_remove(vcpu->kvm, shadow_pte);
1816 } else
1817 was_rmapped = 1;
1819 if (set_spte(vcpu, shadow_pte, pte_access, user_fault, write_fault,
1820 dirty, largepage, global, gfn, pfn, speculative, true)) {
1821 if (write_fault)
1822 *ptwrite = 1;
1823 kvm_x86_ops->tlb_flush(vcpu);
1826 pgprintk("%s: setting spte %llx\n", __func__, *shadow_pte);
1827 pgprintk("instantiating %s PTE (%s) at %ld (%llx) addr %p\n",
1828 is_large_pte(*shadow_pte)? "2MB" : "4kB",
1829 is_present_pte(*shadow_pte)?"RW":"R", gfn,
1830 *shadow_pte, shadow_pte);
1831 if (!was_rmapped && is_large_pte(*shadow_pte))
1832 ++vcpu->kvm->stat.lpages;
1834 page_header_update_slot(vcpu->kvm, shadow_pte, gfn);
1835 if (!was_rmapped) {
1836 rmap_count = rmap_add(vcpu, shadow_pte, gfn, largepage);
1837 if (!is_rmap_pte(*shadow_pte))
1838 kvm_release_pfn_clean(pfn);
1839 if (rmap_count > RMAP_RECYCLE_THRESHOLD)
1840 rmap_recycle(vcpu, gfn, largepage);
1841 } else {
1842 if (was_writeble)
1843 kvm_release_pfn_dirty(pfn);
1844 else
1845 kvm_release_pfn_clean(pfn);
1847 if (speculative) {
1848 vcpu->arch.last_pte_updated = shadow_pte;
1849 vcpu->arch.last_pte_gfn = gfn;
1853 static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
1857 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
1858 int largepage, gfn_t gfn, pfn_t pfn)
1860 struct kvm_shadow_walk_iterator iterator;
1861 struct kvm_mmu_page *sp;
1862 int pt_write = 0;
1863 gfn_t pseudo_gfn;
1865 for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
1866 if (iterator.level == PT_PAGE_TABLE_LEVEL
1867 || (largepage && iterator.level == PT_DIRECTORY_LEVEL)) {
1868 mmu_set_spte(vcpu, iterator.sptep, ACC_ALL, ACC_ALL,
1869 0, write, 1, &pt_write,
1870 largepage, 0, gfn, pfn, false);
1871 ++vcpu->stat.pf_fixed;
1872 break;
1875 if (*iterator.sptep == shadow_trap_nonpresent_pte) {
1876 pseudo_gfn = (iterator.addr & PT64_DIR_BASE_ADDR_MASK) >> PAGE_SHIFT;
1877 sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
1878 iterator.level - 1,
1879 1, ACC_ALL, iterator.sptep);
1880 if (!sp) {
1881 pgprintk("nonpaging_map: ENOMEM\n");
1882 kvm_release_pfn_clean(pfn);
1883 return -ENOMEM;
1886 set_shadow_pte(iterator.sptep,
1887 __pa(sp->spt)
1888 | PT_PRESENT_MASK | PT_WRITABLE_MASK
1889 | shadow_user_mask | shadow_x_mask);
1892 return pt_write;
1895 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, int write, gfn_t gfn)
1897 int r;
1898 int largepage = 0;
1899 pfn_t pfn;
1900 unsigned long mmu_seq;
1902 if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
1903 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
1904 largepage = 1;
1907 mmu_seq = vcpu->kvm->mmu_notifier_seq;
1908 smp_rmb();
1909 pfn = gfn_to_pfn(vcpu->kvm, gfn);
1911 /* mmio */
1912 if (is_error_pfn(pfn)) {
1913 kvm_release_pfn_clean(pfn);
1914 return 1;
1917 spin_lock(&vcpu->kvm->mmu_lock);
1918 if (mmu_notifier_retry(vcpu, mmu_seq))
1919 goto out_unlock;
1920 kvm_mmu_free_some_pages(vcpu);
1921 r = __direct_map(vcpu, v, write, largepage, gfn, pfn);
1922 spin_unlock(&vcpu->kvm->mmu_lock);
1925 return r;
1927 out_unlock:
1928 spin_unlock(&vcpu->kvm->mmu_lock);
1929 kvm_release_pfn_clean(pfn);
1930 return 0;
1934 static void mmu_free_roots(struct kvm_vcpu *vcpu)
1936 int i;
1937 struct kvm_mmu_page *sp;
1939 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
1940 return;
1941 spin_lock(&vcpu->kvm->mmu_lock);
1942 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1943 hpa_t root = vcpu->arch.mmu.root_hpa;
1945 sp = page_header(root);
1946 --sp->root_count;
1947 if (!sp->root_count && sp->role.invalid)
1948 kvm_mmu_zap_page(vcpu->kvm, sp);
1949 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1950 spin_unlock(&vcpu->kvm->mmu_lock);
1951 return;
1953 for (i = 0; i < 4; ++i) {
1954 hpa_t root = vcpu->arch.mmu.pae_root[i];
1956 if (root) {
1957 root &= PT64_BASE_ADDR_MASK;
1958 sp = page_header(root);
1959 --sp->root_count;
1960 if (!sp->root_count && sp->role.invalid)
1961 kvm_mmu_zap_page(vcpu->kvm, sp);
1963 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
1965 spin_unlock(&vcpu->kvm->mmu_lock);
1966 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
1969 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
1971 int ret = 0;
1973 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
1974 set_bit(KVM_REQ_TRIPLE_FAULT, &vcpu->requests);
1975 ret = 1;
1978 return ret;
1981 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
1983 int i;
1984 gfn_t root_gfn;
1985 struct kvm_mmu_page *sp;
1986 int direct = 0;
1988 root_gfn = vcpu->arch.cr3 >> PAGE_SHIFT;
1990 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
1991 hpa_t root = vcpu->arch.mmu.root_hpa;
1993 ASSERT(!VALID_PAGE(root));
1994 if (tdp_enabled)
1995 direct = 1;
1996 if (mmu_check_root(vcpu, root_gfn))
1997 return 1;
1998 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
1999 PT64_ROOT_LEVEL, direct,
2000 ACC_ALL, NULL);
2001 root = __pa(sp->spt);
2002 ++sp->root_count;
2003 vcpu->arch.mmu.root_hpa = root;
2004 return 0;
2006 direct = !is_paging(vcpu);
2007 if (tdp_enabled)
2008 direct = 1;
2009 for (i = 0; i < 4; ++i) {
2010 hpa_t root = vcpu->arch.mmu.pae_root[i];
2012 ASSERT(!VALID_PAGE(root));
2013 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
2014 if (!is_present_pte(vcpu->arch.pdptrs[i])) {
2015 vcpu->arch.mmu.pae_root[i] = 0;
2016 continue;
2018 root_gfn = vcpu->arch.pdptrs[i] >> PAGE_SHIFT;
2019 } else if (vcpu->arch.mmu.root_level == 0)
2020 root_gfn = 0;
2021 if (mmu_check_root(vcpu, root_gfn))
2022 return 1;
2023 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
2024 PT32_ROOT_LEVEL, direct,
2025 ACC_ALL, NULL);
2026 root = __pa(sp->spt);
2027 ++sp->root_count;
2028 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
2030 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
2031 return 0;
2034 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
2036 int i;
2037 struct kvm_mmu_page *sp;
2039 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
2040 return;
2041 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
2042 hpa_t root = vcpu->arch.mmu.root_hpa;
2043 sp = page_header(root);
2044 mmu_sync_children(vcpu, sp);
2045 return;
2047 for (i = 0; i < 4; ++i) {
2048 hpa_t root = vcpu->arch.mmu.pae_root[i];
2050 if (root && VALID_PAGE(root)) {
2051 root &= PT64_BASE_ADDR_MASK;
2052 sp = page_header(root);
2053 mmu_sync_children(vcpu, sp);
2058 static void mmu_sync_global(struct kvm_vcpu *vcpu)
2060 struct kvm *kvm = vcpu->kvm;
2061 struct kvm_mmu_page *sp, *n;
2063 list_for_each_entry_safe(sp, n, &kvm->arch.oos_global_pages, oos_link)
2064 kvm_sync_page(vcpu, sp);
2067 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
2069 spin_lock(&vcpu->kvm->mmu_lock);
2070 mmu_sync_roots(vcpu);
2071 spin_unlock(&vcpu->kvm->mmu_lock);
2074 void kvm_mmu_sync_global(struct kvm_vcpu *vcpu)
2076 spin_lock(&vcpu->kvm->mmu_lock);
2077 mmu_sync_global(vcpu);
2078 spin_unlock(&vcpu->kvm->mmu_lock);
2081 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr)
2083 return vaddr;
2086 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
2087 u32 error_code)
2089 gfn_t gfn;
2090 int r;
2092 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
2093 r = mmu_topup_memory_caches(vcpu);
2094 if (r)
2095 return r;
2097 ASSERT(vcpu);
2098 ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2100 gfn = gva >> PAGE_SHIFT;
2102 return nonpaging_map(vcpu, gva & PAGE_MASK,
2103 error_code & PFERR_WRITE_MASK, gfn);
2106 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa,
2107 u32 error_code)
2109 pfn_t pfn;
2110 int r;
2111 int largepage = 0;
2112 gfn_t gfn = gpa >> PAGE_SHIFT;
2113 unsigned long mmu_seq;
2115 ASSERT(vcpu);
2116 ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
2118 r = mmu_topup_memory_caches(vcpu);
2119 if (r)
2120 return r;
2122 if (is_largepage_backed(vcpu, gfn & ~(KVM_PAGES_PER_HPAGE-1))) {
2123 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
2124 largepage = 1;
2126 mmu_seq = vcpu->kvm->mmu_notifier_seq;
2127 smp_rmb();
2128 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2129 if (is_error_pfn(pfn)) {
2130 kvm_release_pfn_clean(pfn);
2131 return 1;
2133 spin_lock(&vcpu->kvm->mmu_lock);
2134 if (mmu_notifier_retry(vcpu, mmu_seq))
2135 goto out_unlock;
2136 kvm_mmu_free_some_pages(vcpu);
2137 r = __direct_map(vcpu, gpa, error_code & PFERR_WRITE_MASK,
2138 largepage, gfn, pfn);
2139 spin_unlock(&vcpu->kvm->mmu_lock);
2141 return r;
2143 out_unlock:
2144 spin_unlock(&vcpu->kvm->mmu_lock);
2145 kvm_release_pfn_clean(pfn);
2146 return 0;
2149 static void nonpaging_free(struct kvm_vcpu *vcpu)
2151 mmu_free_roots(vcpu);
2154 static int nonpaging_init_context(struct kvm_vcpu *vcpu)
2156 struct kvm_mmu *context = &vcpu->arch.mmu;
2158 context->new_cr3 = nonpaging_new_cr3;
2159 context->page_fault = nonpaging_page_fault;
2160 context->gva_to_gpa = nonpaging_gva_to_gpa;
2161 context->free = nonpaging_free;
2162 context->prefetch_page = nonpaging_prefetch_page;
2163 context->sync_page = nonpaging_sync_page;
2164 context->invlpg = nonpaging_invlpg;
2165 context->root_level = 0;
2166 context->shadow_root_level = PT32E_ROOT_LEVEL;
2167 context->root_hpa = INVALID_PAGE;
2168 return 0;
2171 void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2173 ++vcpu->stat.tlb_flush;
2174 kvm_x86_ops->tlb_flush(vcpu);
2177 static void paging_new_cr3(struct kvm_vcpu *vcpu)
2179 pgprintk("%s: cr3 %lx\n", __func__, vcpu->arch.cr3);
2180 mmu_free_roots(vcpu);
2183 static void inject_page_fault(struct kvm_vcpu *vcpu,
2184 u64 addr,
2185 u32 err_code)
2187 kvm_inject_page_fault(vcpu, addr, err_code);
2190 static void paging_free(struct kvm_vcpu *vcpu)
2192 nonpaging_free(vcpu);
2195 #define PTTYPE 64
2196 #include "paging_tmpl.h"
2197 #undef PTTYPE
2199 #define PTTYPE 32
2200 #include "paging_tmpl.h"
2201 #undef PTTYPE
2203 static int paging64_init_context_common(struct kvm_vcpu *vcpu, int level)
2205 struct kvm_mmu *context = &vcpu->arch.mmu;
2207 ASSERT(is_pae(vcpu));
2208 context->new_cr3 = paging_new_cr3;
2209 context->page_fault = paging64_page_fault;
2210 context->gva_to_gpa = paging64_gva_to_gpa;
2211 context->prefetch_page = paging64_prefetch_page;
2212 context->sync_page = paging64_sync_page;
2213 context->invlpg = paging64_invlpg;
2214 context->free = paging_free;
2215 context->root_level = level;
2216 context->shadow_root_level = level;
2217 context->root_hpa = INVALID_PAGE;
2218 return 0;
2221 static int paging64_init_context(struct kvm_vcpu *vcpu)
2223 return paging64_init_context_common(vcpu, PT64_ROOT_LEVEL);
2226 static int paging32_init_context(struct kvm_vcpu *vcpu)
2228 struct kvm_mmu *context = &vcpu->arch.mmu;
2230 context->new_cr3 = paging_new_cr3;
2231 context->page_fault = paging32_page_fault;
2232 context->gva_to_gpa = paging32_gva_to_gpa;
2233 context->free = paging_free;
2234 context->prefetch_page = paging32_prefetch_page;
2235 context->sync_page = paging32_sync_page;
2236 context->invlpg = paging32_invlpg;
2237 context->root_level = PT32_ROOT_LEVEL;
2238 context->shadow_root_level = PT32E_ROOT_LEVEL;
2239 context->root_hpa = INVALID_PAGE;
2240 return 0;
2243 static int paging32E_init_context(struct kvm_vcpu *vcpu)
2245 return paging64_init_context_common(vcpu, PT32E_ROOT_LEVEL);
2248 static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
2250 struct kvm_mmu *context = &vcpu->arch.mmu;
2252 context->new_cr3 = nonpaging_new_cr3;
2253 context->page_fault = tdp_page_fault;
2254 context->free = nonpaging_free;
2255 context->prefetch_page = nonpaging_prefetch_page;
2256 context->sync_page = nonpaging_sync_page;
2257 context->invlpg = nonpaging_invlpg;
2258 context->shadow_root_level = kvm_x86_ops->get_tdp_level();
2259 context->root_hpa = INVALID_PAGE;
2261 if (!is_paging(vcpu)) {
2262 context->gva_to_gpa = nonpaging_gva_to_gpa;
2263 context->root_level = 0;
2264 } else if (is_long_mode(vcpu)) {
2265 context->gva_to_gpa = paging64_gva_to_gpa;
2266 context->root_level = PT64_ROOT_LEVEL;
2267 } else if (is_pae(vcpu)) {
2268 context->gva_to_gpa = paging64_gva_to_gpa;
2269 context->root_level = PT32E_ROOT_LEVEL;
2270 } else {
2271 context->gva_to_gpa = paging32_gva_to_gpa;
2272 context->root_level = PT32_ROOT_LEVEL;
2275 return 0;
2278 static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
2280 int r;
2282 ASSERT(vcpu);
2283 ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2285 if (!is_paging(vcpu))
2286 r = nonpaging_init_context(vcpu);
2287 else if (is_long_mode(vcpu))
2288 r = paging64_init_context(vcpu);
2289 else if (is_pae(vcpu))
2290 r = paging32E_init_context(vcpu);
2291 else
2292 r = paging32_init_context(vcpu);
2294 vcpu->arch.mmu.base_role.glevels = vcpu->arch.mmu.root_level;
2296 return r;
2299 static int init_kvm_mmu(struct kvm_vcpu *vcpu)
2301 vcpu->arch.update_pte.pfn = bad_pfn;
2303 if (tdp_enabled)
2304 return init_kvm_tdp_mmu(vcpu);
2305 else
2306 return init_kvm_softmmu(vcpu);
2309 static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
2311 ASSERT(vcpu);
2312 if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) {
2313 vcpu->arch.mmu.free(vcpu);
2314 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
2318 int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
2320 destroy_kvm_mmu(vcpu);
2321 return init_kvm_mmu(vcpu);
2323 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
2325 int kvm_mmu_load(struct kvm_vcpu *vcpu)
2327 int r;
2329 r = mmu_topup_memory_caches(vcpu);
2330 if (r)
2331 goto out;
2332 spin_lock(&vcpu->kvm->mmu_lock);
2333 kvm_mmu_free_some_pages(vcpu);
2334 r = mmu_alloc_roots(vcpu);
2335 mmu_sync_roots(vcpu);
2336 spin_unlock(&vcpu->kvm->mmu_lock);
2337 if (r)
2338 goto out;
2339 kvm_x86_ops->set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
2340 kvm_mmu_flush_tlb(vcpu);
2341 out:
2342 return r;
2344 EXPORT_SYMBOL_GPL(kvm_mmu_load);
2346 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
2348 mmu_free_roots(vcpu);
2351 static void mmu_pte_write_zap_pte(struct kvm_vcpu *vcpu,
2352 struct kvm_mmu_page *sp,
2353 u64 *spte)
2355 u64 pte;
2356 struct kvm_mmu_page *child;
2358 pte = *spte;
2359 if (is_shadow_present_pte(pte)) {
2360 if (sp->role.level == PT_PAGE_TABLE_LEVEL ||
2361 is_large_pte(pte))
2362 rmap_remove(vcpu->kvm, spte);
2363 else {
2364 child = page_header(pte & PT64_BASE_ADDR_MASK);
2365 mmu_page_remove_parent_pte(child, spte);
2368 set_shadow_pte(spte, shadow_trap_nonpresent_pte);
2369 if (is_large_pte(pte))
2370 --vcpu->kvm->stat.lpages;
2373 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
2374 struct kvm_mmu_page *sp,
2375 u64 *spte,
2376 const void *new)
2378 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
2379 if (!vcpu->arch.update_pte.largepage ||
2380 sp->role.glevels == PT32_ROOT_LEVEL) {
2381 ++vcpu->kvm->stat.mmu_pde_zapped;
2382 return;
2386 ++vcpu->kvm->stat.mmu_pte_updated;
2387 if (sp->role.glevels == PT32_ROOT_LEVEL)
2388 paging32_update_pte(vcpu, sp, spte, new);
2389 else
2390 paging64_update_pte(vcpu, sp, spte, new);
2393 static bool need_remote_flush(u64 old, u64 new)
2395 if (!is_shadow_present_pte(old))
2396 return false;
2397 if (!is_shadow_present_pte(new))
2398 return true;
2399 if ((old ^ new) & PT64_BASE_ADDR_MASK)
2400 return true;
2401 old ^= PT64_NX_MASK;
2402 new ^= PT64_NX_MASK;
2403 return (old & ~new & PT64_PERM_MASK) != 0;
2406 static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, u64 old, u64 new)
2408 if (need_remote_flush(old, new))
2409 kvm_flush_remote_tlbs(vcpu->kvm);
2410 else
2411 kvm_mmu_flush_tlb(vcpu);
2414 static bool last_updated_pte_accessed(struct kvm_vcpu *vcpu)
2416 u64 *spte = vcpu->arch.last_pte_updated;
2418 return !!(spte && (*spte & shadow_accessed_mask));
2421 static void mmu_guess_page_from_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2422 const u8 *new, int bytes)
2424 gfn_t gfn;
2425 int r;
2426 u64 gpte = 0;
2427 pfn_t pfn;
2429 vcpu->arch.update_pte.largepage = 0;
2431 if (bytes != 4 && bytes != 8)
2432 return;
2435 * Assume that the pte write on a page table of the same type
2436 * as the current vcpu paging mode. This is nearly always true
2437 * (might be false while changing modes). Note it is verified later
2438 * by update_pte().
2440 if (is_pae(vcpu)) {
2441 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
2442 if ((bytes == 4) && (gpa % 4 == 0)) {
2443 r = kvm_read_guest(vcpu->kvm, gpa & ~(u64)7, &gpte, 8);
2444 if (r)
2445 return;
2446 memcpy((void *)&gpte + (gpa % 8), new, 4);
2447 } else if ((bytes == 8) && (gpa % 8 == 0)) {
2448 memcpy((void *)&gpte, new, 8);
2450 } else {
2451 if ((bytes == 4) && (gpa % 4 == 0))
2452 memcpy((void *)&gpte, new, 4);
2454 if (!is_present_pte(gpte))
2455 return;
2456 gfn = (gpte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
2458 if (is_large_pte(gpte) && is_largepage_backed(vcpu, gfn)) {
2459 gfn &= ~(KVM_PAGES_PER_HPAGE-1);
2460 vcpu->arch.update_pte.largepage = 1;
2462 vcpu->arch.update_pte.mmu_seq = vcpu->kvm->mmu_notifier_seq;
2463 smp_rmb();
2464 pfn = gfn_to_pfn(vcpu->kvm, gfn);
2466 if (is_error_pfn(pfn)) {
2467 kvm_release_pfn_clean(pfn);
2468 return;
2470 vcpu->arch.update_pte.gfn = gfn;
2471 vcpu->arch.update_pte.pfn = pfn;
2474 static void kvm_mmu_access_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2476 u64 *spte = vcpu->arch.last_pte_updated;
2478 if (spte
2479 && vcpu->arch.last_pte_gfn == gfn
2480 && shadow_accessed_mask
2481 && !(*spte & shadow_accessed_mask)
2482 && is_shadow_present_pte(*spte))
2483 set_bit(PT_ACCESSED_SHIFT, (unsigned long *)spte);
2486 void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
2487 const u8 *new, int bytes,
2488 bool guest_initiated)
2490 gfn_t gfn = gpa >> PAGE_SHIFT;
2491 struct kvm_mmu_page *sp;
2492 struct hlist_node *node, *n;
2493 struct hlist_head *bucket;
2494 unsigned index;
2495 u64 entry, gentry;
2496 u64 *spte;
2497 unsigned offset = offset_in_page(gpa);
2498 unsigned pte_size;
2499 unsigned page_offset;
2500 unsigned misaligned;
2501 unsigned quadrant;
2502 int level;
2503 int flooded = 0;
2504 int npte;
2505 int r;
2507 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
2508 mmu_guess_page_from_pte_write(vcpu, gpa, new, bytes);
2509 spin_lock(&vcpu->kvm->mmu_lock);
2510 kvm_mmu_access_page(vcpu, gfn);
2511 kvm_mmu_free_some_pages(vcpu);
2512 ++vcpu->kvm->stat.mmu_pte_write;
2513 kvm_mmu_audit(vcpu, "pre pte write");
2514 if (guest_initiated) {
2515 if (gfn == vcpu->arch.last_pt_write_gfn
2516 && !last_updated_pte_accessed(vcpu)) {
2517 ++vcpu->arch.last_pt_write_count;
2518 if (vcpu->arch.last_pt_write_count >= 3)
2519 flooded = 1;
2520 } else {
2521 vcpu->arch.last_pt_write_gfn = gfn;
2522 vcpu->arch.last_pt_write_count = 1;
2523 vcpu->arch.last_pte_updated = NULL;
2526 index = kvm_page_table_hashfn(gfn);
2527 bucket = &vcpu->kvm->arch.mmu_page_hash[index];
2528 hlist_for_each_entry_safe(sp, node, n, bucket, hash_link) {
2529 if (sp->gfn != gfn || sp->role.direct || sp->role.invalid)
2530 continue;
2531 pte_size = sp->role.glevels == PT32_ROOT_LEVEL ? 4 : 8;
2532 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
2533 misaligned |= bytes < 4;
2534 if (misaligned || flooded) {
2536 * Misaligned accesses are too much trouble to fix
2537 * up; also, they usually indicate a page is not used
2538 * as a page table.
2540 * If we're seeing too many writes to a page,
2541 * it may no longer be a page table, or we may be
2542 * forking, in which case it is better to unmap the
2543 * page.
2545 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
2546 gpa, bytes, sp->role.word);
2547 if (kvm_mmu_zap_page(vcpu->kvm, sp))
2548 n = bucket->first;
2549 ++vcpu->kvm->stat.mmu_flooded;
2550 continue;
2552 page_offset = offset;
2553 level = sp->role.level;
2554 npte = 1;
2555 if (sp->role.glevels == PT32_ROOT_LEVEL) {
2556 page_offset <<= 1; /* 32->64 */
2558 * A 32-bit pde maps 4MB while the shadow pdes map
2559 * only 2MB. So we need to double the offset again
2560 * and zap two pdes instead of one.
2562 if (level == PT32_ROOT_LEVEL) {
2563 page_offset &= ~7; /* kill rounding error */
2564 page_offset <<= 1;
2565 npte = 2;
2567 quadrant = page_offset >> PAGE_SHIFT;
2568 page_offset &= ~PAGE_MASK;
2569 if (quadrant != sp->role.quadrant)
2570 continue;
2572 spte = &sp->spt[page_offset / sizeof(*spte)];
2573 if ((gpa & (pte_size - 1)) || (bytes < pte_size)) {
2574 gentry = 0;
2575 r = kvm_read_guest_atomic(vcpu->kvm,
2576 gpa & ~(u64)(pte_size - 1),
2577 &gentry, pte_size);
2578 new = (const void *)&gentry;
2579 if (r < 0)
2580 new = NULL;
2582 while (npte--) {
2583 entry = *spte;
2584 mmu_pte_write_zap_pte(vcpu, sp, spte);
2585 if (new)
2586 mmu_pte_write_new_pte(vcpu, sp, spte, new);
2587 mmu_pte_write_flush_tlb(vcpu, entry, *spte);
2588 ++spte;
2591 kvm_mmu_audit(vcpu, "post pte write");
2592 spin_unlock(&vcpu->kvm->mmu_lock);
2593 if (!is_error_pfn(vcpu->arch.update_pte.pfn)) {
2594 kvm_release_pfn_clean(vcpu->arch.update_pte.pfn);
2595 vcpu->arch.update_pte.pfn = bad_pfn;
2599 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2601 gpa_t gpa;
2602 int r;
2604 gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gva);
2606 spin_lock(&vcpu->kvm->mmu_lock);
2607 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2608 spin_unlock(&vcpu->kvm->mmu_lock);
2609 return r;
2611 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
2613 void __kvm_mmu_free_some_pages(struct kvm_vcpu *vcpu)
2615 while (vcpu->kvm->arch.n_free_mmu_pages < KVM_REFILL_PAGES &&
2616 !list_empty(&vcpu->kvm->arch.active_mmu_pages)) {
2617 struct kvm_mmu_page *sp;
2619 sp = container_of(vcpu->kvm->arch.active_mmu_pages.prev,
2620 struct kvm_mmu_page, link);
2621 kvm_mmu_zap_page(vcpu->kvm, sp);
2622 ++vcpu->kvm->stat.mmu_recycled;
2626 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code)
2628 int r;
2629 enum emulation_result er;
2631 r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code);
2632 if (r < 0)
2633 goto out;
2635 if (!r) {
2636 r = 1;
2637 goto out;
2640 r = mmu_topup_memory_caches(vcpu);
2641 if (r)
2642 goto out;
2644 er = emulate_instruction(vcpu, vcpu->run, cr2, error_code, 0);
2646 switch (er) {
2647 case EMULATE_DONE:
2648 return 1;
2649 case EMULATE_DO_MMIO:
2650 ++vcpu->stat.mmio_exits;
2651 return 0;
2652 case EMULATE_FAIL:
2653 kvm_report_emulation_failure(vcpu, "pagetable");
2654 return 1;
2655 default:
2656 BUG();
2658 out:
2659 return r;
2661 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
2663 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
2665 vcpu->arch.mmu.invlpg(vcpu, gva);
2666 kvm_mmu_flush_tlb(vcpu);
2667 ++vcpu->stat.invlpg;
2669 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
2671 void kvm_enable_tdp(void)
2673 tdp_enabled = true;
2675 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
2677 void kvm_disable_tdp(void)
2679 tdp_enabled = false;
2681 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
2683 static void free_mmu_pages(struct kvm_vcpu *vcpu)
2685 free_page((unsigned long)vcpu->arch.mmu.pae_root);
2688 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
2690 struct page *page;
2691 int i;
2693 ASSERT(vcpu);
2695 if (vcpu->kvm->arch.n_requested_mmu_pages)
2696 vcpu->kvm->arch.n_free_mmu_pages =
2697 vcpu->kvm->arch.n_requested_mmu_pages;
2698 else
2699 vcpu->kvm->arch.n_free_mmu_pages =
2700 vcpu->kvm->arch.n_alloc_mmu_pages;
2702 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
2703 * Therefore we need to allocate shadow page tables in the first
2704 * 4GB of memory, which happens to fit the DMA32 zone.
2706 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
2707 if (!page)
2708 goto error_1;
2709 vcpu->arch.mmu.pae_root = page_address(page);
2710 for (i = 0; i < 4; ++i)
2711 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
2713 return 0;
2715 error_1:
2716 free_mmu_pages(vcpu);
2717 return -ENOMEM;
2720 int kvm_mmu_create(struct kvm_vcpu *vcpu)
2722 ASSERT(vcpu);
2723 ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2725 return alloc_mmu_pages(vcpu);
2728 int kvm_mmu_setup(struct kvm_vcpu *vcpu)
2730 ASSERT(vcpu);
2731 ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
2733 return init_kvm_mmu(vcpu);
2736 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
2738 ASSERT(vcpu);
2740 destroy_kvm_mmu(vcpu);
2741 free_mmu_pages(vcpu);
2742 mmu_free_memory_caches(vcpu);
2745 void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
2747 struct kvm_mmu_page *sp;
2749 list_for_each_entry(sp, &kvm->arch.active_mmu_pages, link) {
2750 int i;
2751 u64 *pt;
2753 if (!test_bit(slot, sp->slot_bitmap))
2754 continue;
2756 pt = sp->spt;
2757 for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2758 /* avoid RMW */
2759 if (pt[i] & PT_WRITABLE_MASK)
2760 pt[i] &= ~PT_WRITABLE_MASK;
2762 kvm_flush_remote_tlbs(kvm);
2765 void kvm_mmu_zap_all(struct kvm *kvm)
2767 struct kvm_mmu_page *sp, *node;
2769 spin_lock(&kvm->mmu_lock);
2770 list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link)
2771 if (kvm_mmu_zap_page(kvm, sp))
2772 node = container_of(kvm->arch.active_mmu_pages.next,
2773 struct kvm_mmu_page, link);
2774 spin_unlock(&kvm->mmu_lock);
2776 kvm_flush_remote_tlbs(kvm);
2779 static void kvm_mmu_remove_one_alloc_mmu_page(struct kvm *kvm)
2781 struct kvm_mmu_page *page;
2783 page = container_of(kvm->arch.active_mmu_pages.prev,
2784 struct kvm_mmu_page, link);
2785 kvm_mmu_zap_page(kvm, page);
2788 static int mmu_shrink(int nr_to_scan, gfp_t gfp_mask)
2790 struct kvm *kvm;
2791 struct kvm *kvm_freed = NULL;
2792 int cache_count = 0;
2794 spin_lock(&kvm_lock);
2796 list_for_each_entry(kvm, &vm_list, vm_list) {
2797 int npages;
2799 if (!down_read_trylock(&kvm->slots_lock))
2800 continue;
2801 spin_lock(&kvm->mmu_lock);
2802 npages = kvm->arch.n_alloc_mmu_pages -
2803 kvm->arch.n_free_mmu_pages;
2804 cache_count += npages;
2805 if (!kvm_freed && nr_to_scan > 0 && npages > 0) {
2806 kvm_mmu_remove_one_alloc_mmu_page(kvm);
2807 cache_count--;
2808 kvm_freed = kvm;
2810 nr_to_scan--;
2812 spin_unlock(&kvm->mmu_lock);
2813 up_read(&kvm->slots_lock);
2815 if (kvm_freed)
2816 list_move_tail(&kvm_freed->vm_list, &vm_list);
2818 spin_unlock(&kvm_lock);
2820 return cache_count;
2823 static struct shrinker mmu_shrinker = {
2824 .shrink = mmu_shrink,
2825 .seeks = DEFAULT_SEEKS * 10,
2828 static void mmu_destroy_caches(void)
2830 if (pte_chain_cache)
2831 kmem_cache_destroy(pte_chain_cache);
2832 if (rmap_desc_cache)
2833 kmem_cache_destroy(rmap_desc_cache);
2834 if (mmu_page_header_cache)
2835 kmem_cache_destroy(mmu_page_header_cache);
2838 void kvm_mmu_module_exit(void)
2840 mmu_destroy_caches();
2841 unregister_shrinker(&mmu_shrinker);
2844 int kvm_mmu_module_init(void)
2846 pte_chain_cache = kmem_cache_create("kvm_pte_chain",
2847 sizeof(struct kvm_pte_chain),
2848 0, 0, NULL);
2849 if (!pte_chain_cache)
2850 goto nomem;
2851 rmap_desc_cache = kmem_cache_create("kvm_rmap_desc",
2852 sizeof(struct kvm_rmap_desc),
2853 0, 0, NULL);
2854 if (!rmap_desc_cache)
2855 goto nomem;
2857 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
2858 sizeof(struct kvm_mmu_page),
2859 0, 0, NULL);
2860 if (!mmu_page_header_cache)
2861 goto nomem;
2863 register_shrinker(&mmu_shrinker);
2865 return 0;
2867 nomem:
2868 mmu_destroy_caches();
2869 return -ENOMEM;
2873 * Caculate mmu pages needed for kvm.
2875 unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
2877 int i;
2878 unsigned int nr_mmu_pages;
2879 unsigned int nr_pages = 0;
2881 for (i = 0; i < kvm->nmemslots; i++)
2882 nr_pages += kvm->memslots[i].npages;
2884 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
2885 nr_mmu_pages = max(nr_mmu_pages,
2886 (unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
2888 return nr_mmu_pages;
2891 static void *pv_mmu_peek_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2892 unsigned len)
2894 if (len > buffer->len)
2895 return NULL;
2896 return buffer->ptr;
2899 static void *pv_mmu_read_buffer(struct kvm_pv_mmu_op_buffer *buffer,
2900 unsigned len)
2902 void *ret;
2904 ret = pv_mmu_peek_buffer(buffer, len);
2905 if (!ret)
2906 return ret;
2907 buffer->ptr += len;
2908 buffer->len -= len;
2909 buffer->processed += len;
2910 return ret;
2913 static int kvm_pv_mmu_write(struct kvm_vcpu *vcpu,
2914 gpa_t addr, gpa_t value)
2916 int bytes = 8;
2917 int r;
2919 if (!is_long_mode(vcpu) && !is_pae(vcpu))
2920 bytes = 4;
2922 r = mmu_topup_memory_caches(vcpu);
2923 if (r)
2924 return r;
2926 if (!emulator_write_phys(vcpu, addr, &value, bytes))
2927 return -EFAULT;
2929 return 1;
2932 static int kvm_pv_mmu_flush_tlb(struct kvm_vcpu *vcpu)
2934 kvm_set_cr3(vcpu, vcpu->arch.cr3);
2935 return 1;
2938 static int kvm_pv_mmu_release_pt(struct kvm_vcpu *vcpu, gpa_t addr)
2940 spin_lock(&vcpu->kvm->mmu_lock);
2941 mmu_unshadow(vcpu->kvm, addr >> PAGE_SHIFT);
2942 spin_unlock(&vcpu->kvm->mmu_lock);
2943 return 1;
2946 static int kvm_pv_mmu_op_one(struct kvm_vcpu *vcpu,
2947 struct kvm_pv_mmu_op_buffer *buffer)
2949 struct kvm_mmu_op_header *header;
2951 header = pv_mmu_peek_buffer(buffer, sizeof *header);
2952 if (!header)
2953 return 0;
2954 switch (header->op) {
2955 case KVM_MMU_OP_WRITE_PTE: {
2956 struct kvm_mmu_op_write_pte *wpte;
2958 wpte = pv_mmu_read_buffer(buffer, sizeof *wpte);
2959 if (!wpte)
2960 return 0;
2961 return kvm_pv_mmu_write(vcpu, wpte->pte_phys,
2962 wpte->pte_val);
2964 case KVM_MMU_OP_FLUSH_TLB: {
2965 struct kvm_mmu_op_flush_tlb *ftlb;
2967 ftlb = pv_mmu_read_buffer(buffer, sizeof *ftlb);
2968 if (!ftlb)
2969 return 0;
2970 return kvm_pv_mmu_flush_tlb(vcpu);
2972 case KVM_MMU_OP_RELEASE_PT: {
2973 struct kvm_mmu_op_release_pt *rpt;
2975 rpt = pv_mmu_read_buffer(buffer, sizeof *rpt);
2976 if (!rpt)
2977 return 0;
2978 return kvm_pv_mmu_release_pt(vcpu, rpt->pt_phys);
2980 default: return 0;
2984 int kvm_pv_mmu_op(struct kvm_vcpu *vcpu, unsigned long bytes,
2985 gpa_t addr, unsigned long *ret)
2987 int r;
2988 struct kvm_pv_mmu_op_buffer *buffer = &vcpu->arch.mmu_op_buffer;
2990 buffer->ptr = buffer->buf;
2991 buffer->len = min_t(unsigned long, bytes, sizeof buffer->buf);
2992 buffer->processed = 0;
2994 r = kvm_read_guest(vcpu->kvm, addr, buffer->buf, buffer->len);
2995 if (r)
2996 goto out;
2998 while (buffer->len) {
2999 r = kvm_pv_mmu_op_one(vcpu, buffer);
3000 if (r < 0)
3001 goto out;
3002 if (r == 0)
3003 break;
3006 r = 1;
3007 out:
3008 *ret = buffer->processed;
3009 return r;
3012 #ifdef AUDIT
3014 static const char *audit_msg;
3016 static gva_t canonicalize(gva_t gva)
3018 #ifdef CONFIG_X86_64
3019 gva = (long long)(gva << 16) >> 16;
3020 #endif
3021 return gva;
3024 static void audit_mappings_page(struct kvm_vcpu *vcpu, u64 page_pte,
3025 gva_t va, int level)
3027 u64 *pt = __va(page_pte & PT64_BASE_ADDR_MASK);
3028 int i;
3029 gva_t va_delta = 1ul << (PAGE_SHIFT + 9 * (level - 1));
3031 for (i = 0; i < PT64_ENT_PER_PAGE; ++i, va += va_delta) {
3032 u64 ent = pt[i];
3034 if (ent == shadow_trap_nonpresent_pte)
3035 continue;
3037 va = canonicalize(va);
3038 if (level > 1) {
3039 if (ent == shadow_notrap_nonpresent_pte)
3040 printk(KERN_ERR "audit: (%s) nontrapping pte"
3041 " in nonleaf level: levels %d gva %lx"
3042 " level %d pte %llx\n", audit_msg,
3043 vcpu->arch.mmu.root_level, va, level, ent);
3045 audit_mappings_page(vcpu, ent, va, level - 1);
3046 } else {
3047 gpa_t gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, va);
3048 hpa_t hpa = (hpa_t)gpa_to_pfn(vcpu, gpa) << PAGE_SHIFT;
3050 if (is_shadow_present_pte(ent)
3051 && (ent & PT64_BASE_ADDR_MASK) != hpa)
3052 printk(KERN_ERR "xx audit error: (%s) levels %d"
3053 " gva %lx gpa %llx hpa %llx ent %llx %d\n",
3054 audit_msg, vcpu->arch.mmu.root_level,
3055 va, gpa, hpa, ent,
3056 is_shadow_present_pte(ent));
3057 else if (ent == shadow_notrap_nonpresent_pte
3058 && !is_error_hpa(hpa))
3059 printk(KERN_ERR "audit: (%s) notrap shadow,"
3060 " valid guest gva %lx\n", audit_msg, va);
3061 kvm_release_pfn_clean(pfn);
3067 static void audit_mappings(struct kvm_vcpu *vcpu)
3069 unsigned i;
3071 if (vcpu->arch.mmu.root_level == 4)
3072 audit_mappings_page(vcpu, vcpu->arch.mmu.root_hpa, 0, 4);
3073 else
3074 for (i = 0; i < 4; ++i)
3075 if (vcpu->arch.mmu.pae_root[i] & PT_PRESENT_MASK)
3076 audit_mappings_page(vcpu,
3077 vcpu->arch.mmu.pae_root[i],
3078 i << 30,
3082 static int count_rmaps(struct kvm_vcpu *vcpu)
3084 int nmaps = 0;
3085 int i, j, k;
3087 for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
3088 struct kvm_memory_slot *m = &vcpu->kvm->memslots[i];
3089 struct kvm_rmap_desc *d;
3091 for (j = 0; j < m->npages; ++j) {
3092 unsigned long *rmapp = &m->rmap[j];
3094 if (!*rmapp)
3095 continue;
3096 if (!(*rmapp & 1)) {
3097 ++nmaps;
3098 continue;
3100 d = (struct kvm_rmap_desc *)(*rmapp & ~1ul);
3101 while (d) {
3102 for (k = 0; k < RMAP_EXT; ++k)
3103 if (d->shadow_ptes[k])
3104 ++nmaps;
3105 else
3106 break;
3107 d = d->more;
3111 return nmaps;
3114 static int count_writable_mappings(struct kvm_vcpu *vcpu)
3116 int nmaps = 0;
3117 struct kvm_mmu_page *sp;
3118 int i;
3120 list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3121 u64 *pt = sp->spt;
3123 if (sp->role.level != PT_PAGE_TABLE_LEVEL)
3124 continue;
3126 for (i = 0; i < PT64_ENT_PER_PAGE; ++i) {
3127 u64 ent = pt[i];
3129 if (!(ent & PT_PRESENT_MASK))
3130 continue;
3131 if (!(ent & PT_WRITABLE_MASK))
3132 continue;
3133 ++nmaps;
3136 return nmaps;
3139 static void audit_rmap(struct kvm_vcpu *vcpu)
3141 int n_rmap = count_rmaps(vcpu);
3142 int n_actual = count_writable_mappings(vcpu);
3144 if (n_rmap != n_actual)
3145 printk(KERN_ERR "%s: (%s) rmap %d actual %d\n",
3146 __func__, audit_msg, n_rmap, n_actual);
3149 static void audit_write_protection(struct kvm_vcpu *vcpu)
3151 struct kvm_mmu_page *sp;
3152 struct kvm_memory_slot *slot;
3153 unsigned long *rmapp;
3154 gfn_t gfn;
3156 list_for_each_entry(sp, &vcpu->kvm->arch.active_mmu_pages, link) {
3157 if (sp->role.direct)
3158 continue;
3160 gfn = unalias_gfn(vcpu->kvm, sp->gfn);
3161 slot = gfn_to_memslot_unaliased(vcpu->kvm, sp->gfn);
3162 rmapp = &slot->rmap[gfn - slot->base_gfn];
3163 if (*rmapp)
3164 printk(KERN_ERR "%s: (%s) shadow page has writable"
3165 " mappings: gfn %lx role %x\n",
3166 __func__, audit_msg, sp->gfn,
3167 sp->role.word);
3171 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, const char *msg)
3173 int olddbg = dbg;
3175 dbg = 0;
3176 audit_msg = msg;
3177 audit_rmap(vcpu);
3178 audit_write_protection(vcpu);
3179 audit_mappings(vcpu);
3180 dbg = olddbg;
3183 #endif