1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2012 - Virtual Open Systems and Columbia University
4 * Author: Christoffer Dall <c.dall@virtualopensystems.com>
7 #include <linux/mman.h>
8 #include <linux/kvm_host.h>
10 #include <linux/hugetlb.h>
11 #include <linux/sched/signal.h>
12 #include <trace/events/kvm.h>
13 #include <asm/pgalloc.h>
14 #include <asm/cacheflush.h>
15 #include <asm/kvm_arm.h>
16 #include <asm/kvm_mmu.h>
17 #include <asm/kvm_pgtable.h>
18 #include <asm/kvm_ras.h>
19 #include <asm/kvm_asm.h>
20 #include <asm/kvm_emulate.h>
25 static struct kvm_pgtable *hyp_pgtable;
26 static DEFINE_MUTEX(kvm_hyp_pgd_mutex);
28 static unsigned long __ro_after_init hyp_idmap_start;
29 static unsigned long __ro_after_init hyp_idmap_end;
30 static phys_addr_t __ro_after_init hyp_idmap_vector;
32 static unsigned long __ro_after_init io_map_base;
34 static phys_addr_t stage2_range_addr_end(phys_addr_t addr, phys_addr_t end)
36 phys_addr_t size = kvm_granule_size(KVM_PGTABLE_MIN_BLOCK_LEVEL);
37 phys_addr_t boundary = ALIGN_DOWN(addr + size, size);
39 return (boundary - 1 < end - 1) ? boundary : end;
43 * Release kvm_mmu_lock periodically if the memory region is large. Otherwise,
44 * we may see kernel panics with CONFIG_DETECT_HUNG_TASK,
45 * CONFIG_LOCKUP_DETECTOR, CONFIG_LOCKDEP. Additionally, holding the lock too
46 * long will also starve other vCPUs. We have to also make sure that the page
47 * tables are not freed while we released the lock.
49 static int stage2_apply_range(struct kvm_s2_mmu *mmu, phys_addr_t addr,
51 int (*fn)(struct kvm_pgtable *, u64, u64),
54 struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
59 struct kvm_pgtable *pgt = mmu->pgt;
63 next = stage2_range_addr_end(addr, end);
64 ret = fn(pgt, addr, next - addr);
68 if (resched && next != end)
69 cond_resched_rwlock_write(&kvm->mmu_lock);
70 } while (addr = next, addr != end);
75 #define stage2_apply_range_resched(mmu, addr, end, fn) \
76 stage2_apply_range(mmu, addr, end, fn, true)
78 static bool memslot_is_logging(struct kvm_memory_slot *memslot)
80 return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY);
84 * kvm_flush_remote_tlbs() - flush all VM TLB entries for v7/8
85 * @kvm: pointer to kvm structure.
87 * Interface to HYP function to flush all VM TLB entries
89 void kvm_flush_remote_tlbs(struct kvm *kvm)
91 ++kvm->stat.generic.remote_tlb_flush_requests;
92 kvm_call_hyp(__kvm_tlb_flush_vmid, &kvm->arch.mmu);
95 static bool kvm_is_device_pfn(unsigned long pfn)
97 return !pfn_is_map_memory(pfn);
100 static void *stage2_memcache_zalloc_page(void *arg)
102 struct kvm_mmu_memory_cache *mc = arg;
105 /* Allocated with __GFP_ZERO, so no need to zero */
106 virt = kvm_mmu_memory_cache_alloc(mc);
108 kvm_account_pgtable_pages(virt, 1);
112 static void *kvm_host_zalloc_pages_exact(size_t size)
114 return alloc_pages_exact(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
117 static void *kvm_s2_zalloc_pages_exact(size_t size)
119 void *virt = kvm_host_zalloc_pages_exact(size);
122 kvm_account_pgtable_pages(virt, (size >> PAGE_SHIFT));
126 static void kvm_s2_free_pages_exact(void *virt, size_t size)
128 kvm_account_pgtable_pages(virt, -(size >> PAGE_SHIFT));
129 free_pages_exact(virt, size);
132 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops;
134 static void stage2_free_removed_table_rcu_cb(struct rcu_head *head)
136 struct page *page = container_of(head, struct page, rcu_head);
137 void *pgtable = page_to_virt(page);
138 u32 level = page_private(page);
140 kvm_pgtable_stage2_free_removed(&kvm_s2_mm_ops, pgtable, level);
143 static void stage2_free_removed_table(void *addr, u32 level)
145 struct page *page = virt_to_page(addr);
147 set_page_private(page, (unsigned long)level);
148 call_rcu(&page->rcu_head, stage2_free_removed_table_rcu_cb);
151 static void kvm_host_get_page(void *addr)
153 get_page(virt_to_page(addr));
156 static void kvm_host_put_page(void *addr)
158 put_page(virt_to_page(addr));
161 static void kvm_s2_put_page(void *addr)
163 struct page *p = virt_to_page(addr);
164 /* Dropping last refcount, the page will be freed */
165 if (page_count(p) == 1)
166 kvm_account_pgtable_pages(addr, -1);
170 static int kvm_host_page_count(void *addr)
172 return page_count(virt_to_page(addr));
175 static phys_addr_t kvm_host_pa(void *addr)
180 static void *kvm_host_va(phys_addr_t phys)
185 static void clean_dcache_guest_page(void *va, size_t size)
187 __clean_dcache_guest_page(va, size);
190 static void invalidate_icache_guest_page(void *va, size_t size)
192 __invalidate_icache_guest_page(va, size);
196 * Unmapping vs dcache management:
198 * If a guest maps certain memory pages as uncached, all writes will
199 * bypass the data cache and go directly to RAM. However, the CPUs
200 * can still speculate reads (not writes) and fill cache lines with
203 * Those cache lines will be *clean* cache lines though, so a
204 * clean+invalidate operation is equivalent to an invalidate
205 * operation, because no cache lines are marked dirty.
207 * Those clean cache lines could be filled prior to an uncached write
208 * by the guest, and the cache coherent IO subsystem would therefore
209 * end up writing old data to disk.
211 * This is why right after unmapping a page/section and invalidating
212 * the corresponding TLBs, we flush to make sure the IO subsystem will
213 * never hit in the cache.
215 * This is all avoided on systems that have ARM64_HAS_STAGE2_FWB, as
216 * we then fully enforce cacheability of RAM, no matter what the guest
220 * unmap_stage2_range -- Clear stage2 page table entries to unmap a range
221 * @mmu: The KVM stage-2 MMU pointer
222 * @start: The intermediate physical base address of the range to unmap
223 * @size: The size of the area to unmap
224 * @may_block: Whether or not we are permitted to block
226 * Clear a range of stage-2 mappings, lowering the various ref-counts. Must
227 * be called while holding mmu_lock (unless for freeing the stage2 pgd before
228 * destroying the VM), otherwise another faulting VCPU may come in and mess
229 * with things behind our backs.
231 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
234 struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
235 phys_addr_t end = start + size;
237 lockdep_assert_held_write(&kvm->mmu_lock);
238 WARN_ON(size & ~PAGE_MASK);
239 WARN_ON(stage2_apply_range(mmu, start, end, kvm_pgtable_stage2_unmap,
243 static void unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size)
245 __unmap_stage2_range(mmu, start, size, true);
248 static void stage2_flush_memslot(struct kvm *kvm,
249 struct kvm_memory_slot *memslot)
251 phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
252 phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
254 stage2_apply_range_resched(&kvm->arch.mmu, addr, end, kvm_pgtable_stage2_flush);
258 * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
259 * @kvm: The struct kvm pointer
261 * Go through the stage 2 page tables and invalidate any cache lines
262 * backing memory already mapped to the VM.
264 static void stage2_flush_vm(struct kvm *kvm)
266 struct kvm_memslots *slots;
267 struct kvm_memory_slot *memslot;
270 idx = srcu_read_lock(&kvm->srcu);
271 write_lock(&kvm->mmu_lock);
273 slots = kvm_memslots(kvm);
274 kvm_for_each_memslot(memslot, bkt, slots)
275 stage2_flush_memslot(kvm, memslot);
277 write_unlock(&kvm->mmu_lock);
278 srcu_read_unlock(&kvm->srcu, idx);
282 * free_hyp_pgds - free Hyp-mode page tables
284 void __init free_hyp_pgds(void)
286 mutex_lock(&kvm_hyp_pgd_mutex);
288 kvm_pgtable_hyp_destroy(hyp_pgtable);
292 mutex_unlock(&kvm_hyp_pgd_mutex);
295 static bool kvm_host_owns_hyp_mappings(void)
297 if (is_kernel_in_hyp_mode())
300 if (static_branch_likely(&kvm_protected_mode_initialized))
304 * This can happen at boot time when __create_hyp_mappings() is called
305 * after the hyp protection has been enabled, but the static key has
306 * not been flipped yet.
308 if (!hyp_pgtable && is_protected_kvm_enabled())
311 WARN_ON(!hyp_pgtable);
316 int __create_hyp_mappings(unsigned long start, unsigned long size,
317 unsigned long phys, enum kvm_pgtable_prot prot)
321 if (WARN_ON(!kvm_host_owns_hyp_mappings()))
324 mutex_lock(&kvm_hyp_pgd_mutex);
325 err = kvm_pgtable_hyp_map(hyp_pgtable, start, size, phys, prot);
326 mutex_unlock(&kvm_hyp_pgd_mutex);
331 static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
333 if (!is_vmalloc_addr(kaddr)) {
334 BUG_ON(!virt_addr_valid(kaddr));
337 return page_to_phys(vmalloc_to_page(kaddr)) +
338 offset_in_page(kaddr);
342 struct hyp_shared_pfn {
348 static DEFINE_MUTEX(hyp_shared_pfns_lock);
349 static struct rb_root hyp_shared_pfns = RB_ROOT;
351 static struct hyp_shared_pfn *find_shared_pfn(u64 pfn, struct rb_node ***node,
352 struct rb_node **parent)
354 struct hyp_shared_pfn *this;
356 *node = &hyp_shared_pfns.rb_node;
359 this = container_of(**node, struct hyp_shared_pfn, node);
362 *node = &((**node)->rb_left);
363 else if (this->pfn > pfn)
364 *node = &((**node)->rb_right);
372 static int share_pfn_hyp(u64 pfn)
374 struct rb_node **node, *parent;
375 struct hyp_shared_pfn *this;
378 mutex_lock(&hyp_shared_pfns_lock);
379 this = find_shared_pfn(pfn, &node, &parent);
385 this = kzalloc(sizeof(*this), GFP_KERNEL);
393 rb_link_node(&this->node, parent, node);
394 rb_insert_color(&this->node, &hyp_shared_pfns);
395 ret = kvm_call_hyp_nvhe(__pkvm_host_share_hyp, pfn, 1);
397 mutex_unlock(&hyp_shared_pfns_lock);
402 static int unshare_pfn_hyp(u64 pfn)
404 struct rb_node **node, *parent;
405 struct hyp_shared_pfn *this;
408 mutex_lock(&hyp_shared_pfns_lock);
409 this = find_shared_pfn(pfn, &node, &parent);
410 if (WARN_ON(!this)) {
419 rb_erase(&this->node, &hyp_shared_pfns);
421 ret = kvm_call_hyp_nvhe(__pkvm_host_unshare_hyp, pfn, 1);
423 mutex_unlock(&hyp_shared_pfns_lock);
428 int kvm_share_hyp(void *from, void *to)
430 phys_addr_t start, end, cur;
434 if (is_kernel_in_hyp_mode())
438 * The share hcall maps things in the 'fixed-offset' region of the hyp
439 * VA space, so we can only share physically contiguous data-structures
442 if (is_vmalloc_or_module_addr(from) || is_vmalloc_or_module_addr(to))
445 if (kvm_host_owns_hyp_mappings())
446 return create_hyp_mappings(from, to, PAGE_HYP);
448 start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
449 end = PAGE_ALIGN(__pa(to));
450 for (cur = start; cur < end; cur += PAGE_SIZE) {
451 pfn = __phys_to_pfn(cur);
452 ret = share_pfn_hyp(pfn);
460 void kvm_unshare_hyp(void *from, void *to)
462 phys_addr_t start, end, cur;
465 if (is_kernel_in_hyp_mode() || kvm_host_owns_hyp_mappings() || !from)
468 start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
469 end = PAGE_ALIGN(__pa(to));
470 for (cur = start; cur < end; cur += PAGE_SIZE) {
471 pfn = __phys_to_pfn(cur);
472 WARN_ON(unshare_pfn_hyp(pfn));
477 * create_hyp_mappings - duplicate a kernel virtual address range in Hyp mode
478 * @from: The virtual kernel start address of the range
479 * @to: The virtual kernel end address of the range (exclusive)
480 * @prot: The protection to be applied to this range
482 * The same virtual address as the kernel virtual address is also used
483 * in Hyp-mode mapping (modulo HYP_PAGE_OFFSET) to the same underlying
486 int create_hyp_mappings(void *from, void *to, enum kvm_pgtable_prot prot)
488 phys_addr_t phys_addr;
489 unsigned long virt_addr;
490 unsigned long start = kern_hyp_va((unsigned long)from);
491 unsigned long end = kern_hyp_va((unsigned long)to);
493 if (is_kernel_in_hyp_mode())
496 if (!kvm_host_owns_hyp_mappings())
499 start = start & PAGE_MASK;
500 end = PAGE_ALIGN(end);
502 for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
505 phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
506 err = __create_hyp_mappings(virt_addr, PAGE_SIZE, phys_addr,
517 * hyp_alloc_private_va_range - Allocates a private VA range.
518 * @size: The size of the VA range to reserve.
519 * @haddr: The hypervisor virtual start address of the allocation.
521 * The private virtual address (VA) range is allocated below io_map_base
522 * and aligned based on the order of @size.
524 * Return: 0 on success or negative error code on failure.
526 int hyp_alloc_private_va_range(size_t size, unsigned long *haddr)
531 mutex_lock(&kvm_hyp_pgd_mutex);
534 * This assumes that we have enough space below the idmap
535 * page to allocate our VAs. If not, the check below will
536 * kick. A potential alternative would be to detect that
537 * overflow and switch to an allocation above the idmap.
539 * The allocated size is always a multiple of PAGE_SIZE.
541 base = io_map_base - PAGE_ALIGN(size);
543 /* Align the allocation based on the order of its size */
544 base = ALIGN_DOWN(base, PAGE_SIZE << get_order(size));
547 * Verify that BIT(VA_BITS - 1) hasn't been flipped by
548 * allocating the new area, as it would indicate we've
549 * overflowed the idmap/IO address range.
551 if ((base ^ io_map_base) & BIT(VA_BITS - 1))
554 *haddr = io_map_base = base;
556 mutex_unlock(&kvm_hyp_pgd_mutex);
561 static int __create_hyp_private_mapping(phys_addr_t phys_addr, size_t size,
562 unsigned long *haddr,
563 enum kvm_pgtable_prot prot)
568 if (!kvm_host_owns_hyp_mappings()) {
569 addr = kvm_call_hyp_nvhe(__pkvm_create_private_mapping,
570 phys_addr, size, prot);
571 if (IS_ERR_VALUE(addr))
578 size = PAGE_ALIGN(size + offset_in_page(phys_addr));
579 ret = hyp_alloc_private_va_range(size, &addr);
583 ret = __create_hyp_mappings(addr, size, phys_addr, prot);
587 *haddr = addr + offset_in_page(phys_addr);
592 * create_hyp_io_mappings - Map IO into both kernel and HYP
593 * @phys_addr: The physical start address which gets mapped
594 * @size: Size of the region being mapped
595 * @kaddr: Kernel VA for this mapping
596 * @haddr: HYP VA for this mapping
598 int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size,
599 void __iomem **kaddr,
600 void __iomem **haddr)
605 if (is_protected_kvm_enabled())
608 *kaddr = ioremap(phys_addr, size);
612 if (is_kernel_in_hyp_mode()) {
617 ret = __create_hyp_private_mapping(phys_addr, size,
618 &addr, PAGE_HYP_DEVICE);
626 *haddr = (void __iomem *)addr;
631 * create_hyp_exec_mappings - Map an executable range into HYP
632 * @phys_addr: The physical start address which gets mapped
633 * @size: Size of the region being mapped
634 * @haddr: HYP VA for this mapping
636 int create_hyp_exec_mappings(phys_addr_t phys_addr, size_t size,
642 BUG_ON(is_kernel_in_hyp_mode());
644 ret = __create_hyp_private_mapping(phys_addr, size,
645 &addr, PAGE_HYP_EXEC);
651 *haddr = (void *)addr;
655 static struct kvm_pgtable_mm_ops kvm_user_mm_ops = {
656 /* We shouldn't need any other callback to walk the PT */
657 .phys_to_virt = kvm_host_va,
660 static int get_user_mapping_size(struct kvm *kvm, u64 addr)
662 struct kvm_pgtable pgt = {
663 .pgd = (kvm_pteref_t)kvm->mm->pgd,
664 .ia_bits = vabits_actual,
665 .start_level = (KVM_PGTABLE_MAX_LEVELS -
666 CONFIG_PGTABLE_LEVELS),
667 .mm_ops = &kvm_user_mm_ops,
669 kvm_pte_t pte = 0; /* Keep GCC quiet... */
673 ret = kvm_pgtable_get_leaf(&pgt, addr, &pte, &level);
675 VM_BUG_ON(level >= KVM_PGTABLE_MAX_LEVELS);
676 VM_BUG_ON(!(pte & PTE_VALID));
678 return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(level));
681 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
682 .zalloc_page = stage2_memcache_zalloc_page,
683 .zalloc_pages_exact = kvm_s2_zalloc_pages_exact,
684 .free_pages_exact = kvm_s2_free_pages_exact,
685 .free_removed_table = stage2_free_removed_table,
686 .get_page = kvm_host_get_page,
687 .put_page = kvm_s2_put_page,
688 .page_count = kvm_host_page_count,
689 .phys_to_virt = kvm_host_va,
690 .virt_to_phys = kvm_host_pa,
691 .dcache_clean_inval_poc = clean_dcache_guest_page,
692 .icache_inval_pou = invalidate_icache_guest_page,
696 * kvm_init_stage2_mmu - Initialise a S2 MMU structure
697 * @kvm: The pointer to the KVM structure
698 * @mmu: The pointer to the s2 MMU structure
699 * @type: The machine type of the virtual machine
701 * Allocates only the stage-2 HW PGD level table(s).
702 * Note we don't need locking here as this is only called when the VM is
703 * created, which can only be done once.
705 int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long type)
707 u32 kvm_ipa_limit = get_kvm_ipa_limit();
709 struct kvm_pgtable *pgt;
713 if (type & ~KVM_VM_TYPE_ARM_IPA_SIZE_MASK)
716 phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
717 if (is_protected_kvm_enabled()) {
718 phys_shift = kvm_ipa_limit;
719 } else if (phys_shift) {
720 if (phys_shift > kvm_ipa_limit ||
721 phys_shift < ARM64_MIN_PARANGE_BITS)
724 phys_shift = KVM_PHYS_SHIFT;
725 if (phys_shift > kvm_ipa_limit) {
726 pr_warn_once("%s using unsupported default IPA limit, upgrade your VMM\n",
732 mmfr0 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
733 mmfr1 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
734 kvm->arch.vtcr = kvm_get_vtcr(mmfr0, mmfr1, phys_shift);
736 if (mmu->pgt != NULL) {
737 kvm_err("kvm_arch already initialized?\n");
741 pgt = kzalloc(sizeof(*pgt), GFP_KERNEL_ACCOUNT);
745 mmu->arch = &kvm->arch;
746 err = kvm_pgtable_stage2_init(pgt, mmu, &kvm_s2_mm_ops);
748 goto out_free_pgtable;
750 mmu->last_vcpu_ran = alloc_percpu(typeof(*mmu->last_vcpu_ran));
751 if (!mmu->last_vcpu_ran) {
753 goto out_destroy_pgtable;
756 for_each_possible_cpu(cpu)
757 *per_cpu_ptr(mmu->last_vcpu_ran, cpu) = -1;
760 mmu->pgd_phys = __pa(pgt->pgd);
764 kvm_pgtable_stage2_destroy(pgt);
770 static void stage2_unmap_memslot(struct kvm *kvm,
771 struct kvm_memory_slot *memslot)
773 hva_t hva = memslot->userspace_addr;
774 phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
775 phys_addr_t size = PAGE_SIZE * memslot->npages;
776 hva_t reg_end = hva + size;
779 * A memory region could potentially cover multiple VMAs, and any holes
780 * between them, so iterate over all of them to find out if we should
783 * +--------------------------------------------+
784 * +---------------+----------------+ +----------------+
785 * | : VMA 1 | VMA 2 | | VMA 3 : |
786 * +---------------+----------------+ +----------------+
788 * +--------------------------------------------+
791 struct vm_area_struct *vma;
792 hva_t vm_start, vm_end;
794 vma = find_vma_intersection(current->mm, hva, reg_end);
799 * Take the intersection of this VMA with the memory region
801 vm_start = max(hva, vma->vm_start);
802 vm_end = min(reg_end, vma->vm_end);
804 if (!(vma->vm_flags & VM_PFNMAP)) {
805 gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
806 unmap_stage2_range(&kvm->arch.mmu, gpa, vm_end - vm_start);
809 } while (hva < reg_end);
813 * stage2_unmap_vm - Unmap Stage-2 RAM mappings
814 * @kvm: The struct kvm pointer
816 * Go through the memregions and unmap any regular RAM
817 * backing memory already mapped to the VM.
819 void stage2_unmap_vm(struct kvm *kvm)
821 struct kvm_memslots *slots;
822 struct kvm_memory_slot *memslot;
825 idx = srcu_read_lock(&kvm->srcu);
826 mmap_read_lock(current->mm);
827 write_lock(&kvm->mmu_lock);
829 slots = kvm_memslots(kvm);
830 kvm_for_each_memslot(memslot, bkt, slots)
831 stage2_unmap_memslot(kvm, memslot);
833 write_unlock(&kvm->mmu_lock);
834 mmap_read_unlock(current->mm);
835 srcu_read_unlock(&kvm->srcu, idx);
838 void kvm_free_stage2_pgd(struct kvm_s2_mmu *mmu)
840 struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
841 struct kvm_pgtable *pgt = NULL;
843 write_lock(&kvm->mmu_lock);
848 free_percpu(mmu->last_vcpu_ran);
850 write_unlock(&kvm->mmu_lock);
853 kvm_pgtable_stage2_destroy(pgt);
858 static void hyp_mc_free_fn(void *addr, void *unused)
860 free_page((unsigned long)addr);
863 static void *hyp_mc_alloc_fn(void *unused)
865 return (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
868 void free_hyp_memcache(struct kvm_hyp_memcache *mc)
870 if (is_protected_kvm_enabled())
871 __free_hyp_memcache(mc, hyp_mc_free_fn,
875 int topup_hyp_memcache(struct kvm_hyp_memcache *mc, unsigned long min_pages)
877 if (!is_protected_kvm_enabled())
880 return __topup_hyp_memcache(mc, min_pages, hyp_mc_alloc_fn,
885 * kvm_phys_addr_ioremap - map a device range to guest IPA
887 * @kvm: The KVM pointer
888 * @guest_ipa: The IPA at which to insert the mapping
889 * @pa: The physical address of the device
890 * @size: The size of the mapping
891 * @writable: Whether or not to create a writable mapping
893 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
894 phys_addr_t pa, unsigned long size, bool writable)
898 struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };
899 struct kvm_pgtable *pgt = kvm->arch.mmu.pgt;
900 enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_DEVICE |
902 (writable ? KVM_PGTABLE_PROT_W : 0);
904 if (is_protected_kvm_enabled())
907 size += offset_in_page(guest_ipa);
908 guest_ipa &= PAGE_MASK;
910 for (addr = guest_ipa; addr < guest_ipa + size; addr += PAGE_SIZE) {
911 ret = kvm_mmu_topup_memory_cache(&cache,
912 kvm_mmu_cache_min_pages(kvm));
916 write_lock(&kvm->mmu_lock);
917 ret = kvm_pgtable_stage2_map(pgt, addr, PAGE_SIZE, pa, prot,
919 write_unlock(&kvm->mmu_lock);
926 kvm_mmu_free_memory_cache(&cache);
931 * stage2_wp_range() - write protect stage2 memory region range
932 * @mmu: The KVM stage-2 MMU pointer
933 * @addr: Start address of range
934 * @end: End address of range
936 static void stage2_wp_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
938 stage2_apply_range_resched(mmu, addr, end, kvm_pgtable_stage2_wrprotect);
942 * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
943 * @kvm: The KVM pointer
944 * @slot: The memory slot to write protect
946 * Called to start logging dirty pages after memory region
947 * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
948 * all present PUD, PMD and PTEs are write protected in the memory region.
949 * Afterwards read of dirty page log can be called.
951 * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
952 * serializing operations for VM memory regions.
954 static void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
956 struct kvm_memslots *slots = kvm_memslots(kvm);
957 struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
958 phys_addr_t start, end;
960 if (WARN_ON_ONCE(!memslot))
963 start = memslot->base_gfn << PAGE_SHIFT;
964 end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
966 write_lock(&kvm->mmu_lock);
967 stage2_wp_range(&kvm->arch.mmu, start, end);
968 write_unlock(&kvm->mmu_lock);
969 kvm_flush_remote_tlbs(kvm);
973 * kvm_mmu_write_protect_pt_masked() - write protect dirty pages
974 * @kvm: The KVM pointer
975 * @slot: The memory slot associated with mask
976 * @gfn_offset: The gfn offset in memory slot
977 * @mask: The mask of dirty pages at offset 'gfn_offset' in this memory
978 * slot to be write protected
980 * Walks bits set in mask write protects the associated pte's. Caller must
981 * acquire kvm_mmu_lock.
983 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
984 struct kvm_memory_slot *slot,
985 gfn_t gfn_offset, unsigned long mask)
987 phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
988 phys_addr_t start = (base_gfn + __ffs(mask)) << PAGE_SHIFT;
989 phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
991 stage2_wp_range(&kvm->arch.mmu, start, end);
995 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
998 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
999 * enable dirty logging for them.
1001 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1002 struct kvm_memory_slot *slot,
1003 gfn_t gfn_offset, unsigned long mask)
1005 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1008 static void kvm_send_hwpoison_signal(unsigned long address, short lsb)
1010 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, current);
1013 static bool fault_supports_stage2_huge_mapping(struct kvm_memory_slot *memslot,
1015 unsigned long map_size)
1018 hva_t uaddr_start, uaddr_end;
1021 /* The memslot and the VMA are guaranteed to be aligned to PAGE_SIZE */
1022 if (map_size == PAGE_SIZE)
1025 size = memslot->npages * PAGE_SIZE;
1027 gpa_start = memslot->base_gfn << PAGE_SHIFT;
1029 uaddr_start = memslot->userspace_addr;
1030 uaddr_end = uaddr_start + size;
1033 * Pages belonging to memslots that don't have the same alignment
1034 * within a PMD/PUD for userspace and IPA cannot be mapped with stage-2
1035 * PMD/PUD entries, because we'll end up mapping the wrong pages.
1037 * Consider a layout like the following:
1039 * memslot->userspace_addr:
1040 * +-----+--------------------+--------------------+---+
1041 * |abcde|fgh Stage-1 block | Stage-1 block tv|xyz|
1042 * +-----+--------------------+--------------------+---+
1044 * memslot->base_gfn << PAGE_SHIFT:
1045 * +---+--------------------+--------------------+-----+
1046 * |abc|def Stage-2 block | Stage-2 block |tvxyz|
1047 * +---+--------------------+--------------------+-----+
1049 * If we create those stage-2 blocks, we'll end up with this incorrect
1055 if ((gpa_start & (map_size - 1)) != (uaddr_start & (map_size - 1)))
1059 * Next, let's make sure we're not trying to map anything not covered
1060 * by the memslot. This means we have to prohibit block size mappings
1061 * for the beginning and end of a non-block aligned and non-block sized
1062 * memory slot (illustrated by the head and tail parts of the
1063 * userspace view above containing pages 'abcde' and 'xyz',
1066 * Note that it doesn't matter if we do the check using the
1067 * userspace_addr or the base_gfn, as both are equally aligned (per
1068 * the check above) and equally sized.
1070 return (hva & ~(map_size - 1)) >= uaddr_start &&
1071 (hva & ~(map_size - 1)) + map_size <= uaddr_end;
1075 * Check if the given hva is backed by a transparent huge page (THP) and
1076 * whether it can be mapped using block mapping in stage2. If so, adjust
1077 * the stage2 PFN and IPA accordingly. Only PMD_SIZE THPs are currently
1078 * supported. This will need to be updated to support other THP sizes.
1080 * Returns the size of the mapping.
1082 static unsigned long
1083 transparent_hugepage_adjust(struct kvm *kvm, struct kvm_memory_slot *memslot,
1084 unsigned long hva, kvm_pfn_t *pfnp,
1087 kvm_pfn_t pfn = *pfnp;
1090 * Make sure the adjustment is done only for THP pages. Also make
1091 * sure that the HVA and IPA are sufficiently aligned and that the
1092 * block map is contained within the memslot.
1094 if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE) &&
1095 get_user_mapping_size(kvm, hva) >= PMD_SIZE) {
1097 * The address we faulted on is backed by a transparent huge
1098 * page. However, because we map the compound huge page and
1099 * not the individual tail page, we need to transfer the
1100 * refcount to the head page. We have to be careful that the
1101 * THP doesn't start to split while we are adjusting the
1104 * We are sure this doesn't happen, because mmu_invalidate_retry
1105 * was successful and we are holding the mmu_lock, so if this
1106 * THP is trying to split, it will be blocked in the mmu
1107 * notifier before touching any of the pages, specifically
1108 * before being able to call __split_huge_page_refcount().
1110 * We can therefore safely transfer the refcount from PG_tail
1111 * to PG_head and switch the pfn from a tail page to the head
1115 kvm_release_pfn_clean(pfn);
1116 pfn &= ~(PTRS_PER_PMD - 1);
1117 get_page(pfn_to_page(pfn));
1123 /* Use page mapping if we cannot use block mapping. */
1127 static int get_vma_page_shift(struct vm_area_struct *vma, unsigned long hva)
1131 if (is_vm_hugetlb_page(vma) && !(vma->vm_flags & VM_PFNMAP))
1132 return huge_page_shift(hstate_vma(vma));
1134 if (!(vma->vm_flags & VM_PFNMAP))
1137 VM_BUG_ON(is_vm_hugetlb_page(vma));
1139 pa = (vma->vm_pgoff << PAGE_SHIFT) + (hva - vma->vm_start);
1141 #ifndef __PAGETABLE_PMD_FOLDED
1142 if ((hva & (PUD_SIZE - 1)) == (pa & (PUD_SIZE - 1)) &&
1143 ALIGN_DOWN(hva, PUD_SIZE) >= vma->vm_start &&
1144 ALIGN(hva, PUD_SIZE) <= vma->vm_end)
1148 if ((hva & (PMD_SIZE - 1)) == (pa & (PMD_SIZE - 1)) &&
1149 ALIGN_DOWN(hva, PMD_SIZE) >= vma->vm_start &&
1150 ALIGN(hva, PMD_SIZE) <= vma->vm_end)
1157 * The page will be mapped in stage 2 as Normal Cacheable, so the VM will be
1158 * able to see the page's tags and therefore they must be initialised first. If
1159 * PG_mte_tagged is set, tags have already been initialised.
1161 * The race in the test/set of the PG_mte_tagged flag is handled by:
1162 * - preventing VM_SHARED mappings in a memslot with MTE preventing two VMs
1163 * racing to santise the same page
1164 * - mmap_lock protects between a VM faulting a page in and the VMM performing
1165 * an mprotect() to add VM_MTE
1167 static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn,
1170 unsigned long i, nr_pages = size >> PAGE_SHIFT;
1171 struct page *page = pfn_to_page(pfn);
1173 if (!kvm_has_mte(kvm))
1176 for (i = 0; i < nr_pages; i++, page++) {
1177 if (try_page_mte_tagging(page)) {
1178 mte_clear_page_tags(page_address(page));
1179 set_page_mte_tagged(page);
1184 static bool kvm_vma_mte_allowed(struct vm_area_struct *vma)
1186 return vma->vm_flags & VM_MTE_ALLOWED;
1189 static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1190 struct kvm_memory_slot *memslot, unsigned long hva,
1191 unsigned long fault_status)
1194 bool write_fault, writable, force_pte = false;
1196 bool device = false;
1197 unsigned long mmu_seq;
1198 struct kvm *kvm = vcpu->kvm;
1199 struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
1200 struct vm_area_struct *vma;
1204 bool logging_active = memslot_is_logging(memslot);
1205 unsigned long fault_level = kvm_vcpu_trap_get_fault_level(vcpu);
1206 unsigned long vma_pagesize, fault_granule;
1207 enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
1208 struct kvm_pgtable *pgt;
1210 fault_granule = 1UL << ARM64_HW_PGTABLE_LEVEL_SHIFT(fault_level);
1211 write_fault = kvm_is_write_fault(vcpu);
1212 exec_fault = kvm_vcpu_trap_is_exec_fault(vcpu);
1213 VM_BUG_ON(write_fault && exec_fault);
1215 if (fault_status == ESR_ELx_FSC_PERM && !write_fault && !exec_fault) {
1216 kvm_err("Unexpected L2 read permission error\n");
1221 * Permission faults just need to update the existing leaf entry,
1222 * and so normally don't require allocations from the memcache. The
1223 * only exception to this is when dirty logging is enabled at runtime
1224 * and a write fault needs to collapse a block entry into a table.
1226 if (fault_status != ESR_ELx_FSC_PERM ||
1227 (logging_active && write_fault)) {
1228 ret = kvm_mmu_topup_memory_cache(memcache,
1229 kvm_mmu_cache_min_pages(kvm));
1235 * Let's check if we will get back a huge page backed by hugetlbfs, or
1236 * get block mapping for device MMIO region.
1238 mmap_read_lock(current->mm);
1239 vma = vma_lookup(current->mm, hva);
1240 if (unlikely(!vma)) {
1241 kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
1242 mmap_read_unlock(current->mm);
1247 * logging_active is guaranteed to never be true for VM_PFNMAP
1250 if (logging_active) {
1252 vma_shift = PAGE_SHIFT;
1254 vma_shift = get_vma_page_shift(vma, hva);
1257 switch (vma_shift) {
1258 #ifndef __PAGETABLE_PMD_FOLDED
1260 if (fault_supports_stage2_huge_mapping(memslot, hva, PUD_SIZE))
1264 case CONT_PMD_SHIFT:
1265 vma_shift = PMD_SHIFT;
1268 if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE))
1271 case CONT_PTE_SHIFT:
1272 vma_shift = PAGE_SHIFT;
1278 WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
1281 vma_pagesize = 1UL << vma_shift;
1282 if (vma_pagesize == PMD_SIZE || vma_pagesize == PUD_SIZE)
1283 fault_ipa &= ~(vma_pagesize - 1);
1285 gfn = fault_ipa >> PAGE_SHIFT;
1288 * Read mmu_invalidate_seq so that KVM can detect if the results of
1289 * vma_lookup() or __gfn_to_pfn_memslot() become stale prior to
1290 * acquiring kvm->mmu_lock.
1292 * Rely on mmap_read_unlock() for an implicit smp_rmb(), which pairs
1293 * with the smp_wmb() in kvm_mmu_invalidate_end().
1295 mmu_seq = vcpu->kvm->mmu_invalidate_seq;
1296 mmap_read_unlock(current->mm);
1298 pfn = __gfn_to_pfn_memslot(memslot, gfn, false, false, NULL,
1299 write_fault, &writable, NULL);
1300 if (pfn == KVM_PFN_ERR_HWPOISON) {
1301 kvm_send_hwpoison_signal(hva, vma_shift);
1304 if (is_error_noslot_pfn(pfn))
1307 if (kvm_is_device_pfn(pfn)) {
1309 * If the page was identified as device early by looking at
1310 * the VMA flags, vma_pagesize is already representing the
1311 * largest quantity we can map. If instead it was mapped
1312 * via gfn_to_pfn_prot(), vma_pagesize is set to PAGE_SIZE
1313 * and must not be upgraded.
1315 * In both cases, we don't let transparent_hugepage_adjust()
1316 * change things at the last minute.
1319 } else if (logging_active && !write_fault) {
1321 * Only actually map the page as writable if this was a write
1327 if (exec_fault && device)
1330 read_lock(&kvm->mmu_lock);
1331 pgt = vcpu->arch.hw_mmu->pgt;
1332 if (mmu_invalidate_retry(kvm, mmu_seq))
1336 * If we are not forced to use page mapping, check if we are
1337 * backed by a THP and thus use block mapping if possible.
1339 if (vma_pagesize == PAGE_SIZE && !(force_pte || device)) {
1340 if (fault_status == ESR_ELx_FSC_PERM &&
1341 fault_granule > PAGE_SIZE)
1342 vma_pagesize = fault_granule;
1344 vma_pagesize = transparent_hugepage_adjust(kvm, memslot,
1349 if (fault_status != ESR_ELx_FSC_PERM && !device && kvm_has_mte(kvm)) {
1350 /* Check the VMM hasn't introduced a new disallowed VMA */
1351 if (kvm_vma_mte_allowed(vma)) {
1352 sanitise_mte_tags(kvm, pfn, vma_pagesize);
1360 prot |= KVM_PGTABLE_PROT_W;
1363 prot |= KVM_PGTABLE_PROT_X;
1366 prot |= KVM_PGTABLE_PROT_DEVICE;
1367 else if (cpus_have_const_cap(ARM64_HAS_CACHE_DIC))
1368 prot |= KVM_PGTABLE_PROT_X;
1371 * Under the premise of getting a FSC_PERM fault, we just need to relax
1372 * permissions only if vma_pagesize equals fault_granule. Otherwise,
1373 * kvm_pgtable_stage2_map() should be called to change block size.
1375 if (fault_status == ESR_ELx_FSC_PERM && vma_pagesize == fault_granule)
1376 ret = kvm_pgtable_stage2_relax_perms(pgt, fault_ipa, prot);
1378 ret = kvm_pgtable_stage2_map(pgt, fault_ipa, vma_pagesize,
1379 __pfn_to_phys(pfn), prot,
1381 KVM_PGTABLE_WALK_HANDLE_FAULT |
1382 KVM_PGTABLE_WALK_SHARED);
1384 /* Mark the page dirty only if the fault is handled successfully */
1385 if (writable && !ret) {
1386 kvm_set_pfn_dirty(pfn);
1387 mark_page_dirty_in_slot(kvm, memslot, gfn);
1391 read_unlock(&kvm->mmu_lock);
1392 kvm_set_pfn_accessed(pfn);
1393 kvm_release_pfn_clean(pfn);
1394 return ret != -EAGAIN ? ret : 0;
1397 /* Resolve the access fault by making the page young again. */
1398 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
1401 struct kvm_s2_mmu *mmu;
1403 trace_kvm_access_fault(fault_ipa);
1405 read_lock(&vcpu->kvm->mmu_lock);
1406 mmu = vcpu->arch.hw_mmu;
1407 pte = kvm_pgtable_stage2_mkyoung(mmu->pgt, fault_ipa);
1408 read_unlock(&vcpu->kvm->mmu_lock);
1410 if (kvm_pte_valid(pte))
1411 kvm_set_pfn_accessed(kvm_pte_to_pfn(pte));
1415 * kvm_handle_guest_abort - handles all 2nd stage aborts
1416 * @vcpu: the VCPU pointer
1418 * Any abort that gets to the host is almost guaranteed to be caused by a
1419 * missing second stage translation table entry, which can mean that either the
1420 * guest simply needs more memory and we must allocate an appropriate page or it
1421 * can mean that the guest tried to access I/O memory, which is emulated by user
1422 * space. The distinction is based on the IPA causing the fault and whether this
1423 * memory region has been registered as standard RAM by user space.
1425 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
1427 unsigned long fault_status;
1428 phys_addr_t fault_ipa;
1429 struct kvm_memory_slot *memslot;
1431 bool is_iabt, write_fault, writable;
1435 fault_status = kvm_vcpu_trap_get_fault_type(vcpu);
1437 fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
1438 is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
1440 if (fault_status == ESR_ELx_FSC_FAULT) {
1441 /* Beyond sanitised PARange (which is the IPA limit) */
1442 if (fault_ipa >= BIT_ULL(get_kvm_ipa_limit())) {
1443 kvm_inject_size_fault(vcpu);
1447 /* Falls between the IPA range and the PARange? */
1448 if (fault_ipa >= BIT_ULL(vcpu->arch.hw_mmu->pgt->ia_bits)) {
1449 fault_ipa |= kvm_vcpu_get_hfar(vcpu) & GENMASK(11, 0);
1452 kvm_inject_pabt(vcpu, fault_ipa);
1454 kvm_inject_dabt(vcpu, fault_ipa);
1459 /* Synchronous External Abort? */
1460 if (kvm_vcpu_abt_issea(vcpu)) {
1462 * For RAS the host kernel may handle this abort.
1463 * There is no need to pass the error into the guest.
1465 if (kvm_handle_guest_sea(fault_ipa, kvm_vcpu_get_esr(vcpu)))
1466 kvm_inject_vabt(vcpu);
1471 trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_esr(vcpu),
1472 kvm_vcpu_get_hfar(vcpu), fault_ipa);
1474 /* Check the stage-2 fault is trans. fault or write fault */
1475 if (fault_status != ESR_ELx_FSC_FAULT &&
1476 fault_status != ESR_ELx_FSC_PERM &&
1477 fault_status != ESR_ELx_FSC_ACCESS) {
1478 kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
1479 kvm_vcpu_trap_get_class(vcpu),
1480 (unsigned long)kvm_vcpu_trap_get_fault(vcpu),
1481 (unsigned long)kvm_vcpu_get_esr(vcpu));
1485 idx = srcu_read_lock(&vcpu->kvm->srcu);
1487 gfn = fault_ipa >> PAGE_SHIFT;
1488 memslot = gfn_to_memslot(vcpu->kvm, gfn);
1489 hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
1490 write_fault = kvm_is_write_fault(vcpu);
1491 if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
1493 * The guest has put either its instructions or its page-tables
1494 * somewhere it shouldn't have. Userspace won't be able to do
1495 * anything about this (there's no syndrome for a start), so
1496 * re-inject the abort back into the guest.
1503 if (kvm_vcpu_abt_iss1tw(vcpu)) {
1504 kvm_inject_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1510 * Check for a cache maintenance operation. Since we
1511 * ended-up here, we know it is outside of any memory
1512 * slot. But we can't find out if that is for a device,
1513 * or if the guest is just being stupid. The only thing
1514 * we know for sure is that this range cannot be cached.
1516 * So let's assume that the guest is just being
1517 * cautious, and skip the instruction.
1519 if (kvm_is_error_hva(hva) && kvm_vcpu_dabt_is_cm(vcpu)) {
1526 * The IPA is reported as [MAX:12], so we need to
1527 * complement it with the bottom 12 bits from the
1528 * faulting VA. This is always 12 bits, irrespective
1531 fault_ipa |= kvm_vcpu_get_hfar(vcpu) & ((1 << 12) - 1);
1532 ret = io_mem_abort(vcpu, fault_ipa);
1536 /* Userspace should not be able to register out-of-bounds IPAs */
1537 VM_BUG_ON(fault_ipa >= kvm_phys_size(vcpu->kvm));
1539 if (fault_status == ESR_ELx_FSC_ACCESS) {
1540 handle_access_fault(vcpu, fault_ipa);
1545 ret = user_mem_abort(vcpu, fault_ipa, memslot, hva, fault_status);
1549 if (ret == -ENOEXEC) {
1550 kvm_inject_pabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1554 srcu_read_unlock(&vcpu->kvm->srcu, idx);
1558 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1560 if (!kvm->arch.mmu.pgt)
1563 __unmap_stage2_range(&kvm->arch.mmu, range->start << PAGE_SHIFT,
1564 (range->end - range->start) << PAGE_SHIFT,
1570 bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1572 kvm_pfn_t pfn = pte_pfn(range->pte);
1574 if (!kvm->arch.mmu.pgt)
1577 WARN_ON(range->end - range->start != 1);
1580 * If the page isn't tagged, defer to user_mem_abort() for sanitising
1581 * the MTE tags. The S2 pte should have been unmapped by
1582 * mmu_notifier_invalidate_range_end().
1584 if (kvm_has_mte(kvm) && !page_mte_tagged(pfn_to_page(pfn)))
1588 * We've moved a page around, probably through CoW, so let's treat
1589 * it just like a translation fault and the map handler will clean
1590 * the cache to the PoC.
1592 * The MMU notifiers will have unmapped a huge PMD before calling
1593 * ->change_pte() (which in turn calls kvm_set_spte_gfn()) and
1594 * therefore we never need to clear out a huge PMD through this
1595 * calling path and a memcache is not required.
1597 kvm_pgtable_stage2_map(kvm->arch.mmu.pgt, range->start << PAGE_SHIFT,
1598 PAGE_SIZE, __pfn_to_phys(pfn),
1599 KVM_PGTABLE_PROT_R, NULL, 0);
1604 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1606 u64 size = (range->end - range->start) << PAGE_SHIFT;
1610 if (!kvm->arch.mmu.pgt)
1613 WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
1615 kpte = kvm_pgtable_stage2_mkold(kvm->arch.mmu.pgt,
1616 range->start << PAGE_SHIFT);
1618 return pte_valid(pte) && pte_young(pte);
1621 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1623 if (!kvm->arch.mmu.pgt)
1626 return kvm_pgtable_stage2_is_young(kvm->arch.mmu.pgt,
1627 range->start << PAGE_SHIFT);
1630 phys_addr_t kvm_mmu_get_httbr(void)
1632 return __pa(hyp_pgtable->pgd);
1635 phys_addr_t kvm_get_idmap_vector(void)
1637 return hyp_idmap_vector;
1640 static int kvm_map_idmap_text(void)
1642 unsigned long size = hyp_idmap_end - hyp_idmap_start;
1643 int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
1646 kvm_err("Failed to idmap %lx-%lx\n",
1647 hyp_idmap_start, hyp_idmap_end);
1652 static void *kvm_hyp_zalloc_page(void *arg)
1654 return (void *)get_zeroed_page(GFP_KERNEL);
1657 static struct kvm_pgtable_mm_ops kvm_hyp_mm_ops = {
1658 .zalloc_page = kvm_hyp_zalloc_page,
1659 .get_page = kvm_host_get_page,
1660 .put_page = kvm_host_put_page,
1661 .phys_to_virt = kvm_host_va,
1662 .virt_to_phys = kvm_host_pa,
1665 int __init kvm_mmu_init(u32 *hyp_va_bits)
1671 hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
1672 hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
1673 hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
1674 hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
1675 hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
1678 * We rely on the linker script to ensure at build time that the HYP
1679 * init code does not cross a page boundary.
1681 BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
1684 * The ID map may be configured to use an extended virtual address
1685 * range. This is only the case if system RAM is out of range for the
1686 * currently configured page size and VA_BITS_MIN, in which case we will
1687 * also need the extended virtual range for the HYP ID map, or we won't
1688 * be able to enable the EL2 MMU.
1690 * However, in some cases the ID map may be configured for fewer than
1691 * the number of VA bits used by the regular kernel stage 1. This
1692 * happens when VA_BITS=52 and the kernel image is placed in PA space
1695 * At EL2, there is only one TTBR register, and we can't switch between
1696 * translation tables *and* update TCR_EL2.T0SZ at the same time. Bottom
1697 * line: we need to use the extended range with *both* our translation
1700 * So use the maximum of the idmap VA bits and the regular kernel stage
1701 * 1 VA bits to assure that the hypervisor can both ID map its code page
1702 * and map any kernel memory.
1704 idmap_bits = 64 - ((idmap_t0sz & TCR_T0SZ_MASK) >> TCR_T0SZ_OFFSET);
1705 kernel_bits = vabits_actual;
1706 *hyp_va_bits = max(idmap_bits, kernel_bits);
1708 kvm_debug("Using %u-bit virtual addresses at EL2\n", *hyp_va_bits);
1709 kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
1710 kvm_debug("HYP VA range: %lx:%lx\n",
1711 kern_hyp_va(PAGE_OFFSET),
1712 kern_hyp_va((unsigned long)high_memory - 1));
1714 if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
1715 hyp_idmap_start < kern_hyp_va((unsigned long)high_memory - 1) &&
1716 hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
1718 * The idmap page is intersecting with the VA space,
1719 * it is not safe to continue further.
1721 kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
1726 hyp_pgtable = kzalloc(sizeof(*hyp_pgtable), GFP_KERNEL);
1728 kvm_err("Hyp mode page-table not allocated\n");
1733 err = kvm_pgtable_hyp_init(hyp_pgtable, *hyp_va_bits, &kvm_hyp_mm_ops);
1735 goto out_free_pgtable;
1737 err = kvm_map_idmap_text();
1739 goto out_destroy_pgtable;
1741 io_map_base = hyp_idmap_start;
1744 out_destroy_pgtable:
1745 kvm_pgtable_hyp_destroy(hyp_pgtable);
1753 void kvm_arch_commit_memory_region(struct kvm *kvm,
1754 struct kvm_memory_slot *old,
1755 const struct kvm_memory_slot *new,
1756 enum kvm_mr_change change)
1759 * At this point memslot has been committed and there is an
1760 * allocated dirty_bitmap[], dirty pages will be tracked while the
1761 * memory slot is write protected.
1763 if (change != KVM_MR_DELETE && new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1765 * If we're with initial-all-set, we don't need to write
1766 * protect any pages because they're all reported as dirty.
1767 * Huge pages and normal pages will be write protect gradually.
1769 if (!kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1770 kvm_mmu_wp_memory_region(kvm, new->id);
1775 int kvm_arch_prepare_memory_region(struct kvm *kvm,
1776 const struct kvm_memory_slot *old,
1777 struct kvm_memory_slot *new,
1778 enum kvm_mr_change change)
1783 if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
1784 change != KVM_MR_FLAGS_ONLY)
1788 * Prevent userspace from creating a memory region outside of the IPA
1789 * space addressable by the KVM guest IPA space.
1791 if ((new->base_gfn + new->npages) > (kvm_phys_size(kvm) >> PAGE_SHIFT))
1794 hva = new->userspace_addr;
1795 reg_end = hva + (new->npages << PAGE_SHIFT);
1797 mmap_read_lock(current->mm);
1799 * A memory region could potentially cover multiple VMAs, and any holes
1800 * between them, so iterate over all of them.
1802 * +--------------------------------------------+
1803 * +---------------+----------------+ +----------------+
1804 * | : VMA 1 | VMA 2 | | VMA 3 : |
1805 * +---------------+----------------+ +----------------+
1807 * +--------------------------------------------+
1810 struct vm_area_struct *vma;
1812 vma = find_vma_intersection(current->mm, hva, reg_end);
1816 if (kvm_has_mte(kvm) && !kvm_vma_mte_allowed(vma)) {
1821 if (vma->vm_flags & VM_PFNMAP) {
1822 /* IO region dirty page logging not allowed */
1823 if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1828 hva = min(reg_end, vma->vm_end);
1829 } while (hva < reg_end);
1831 mmap_read_unlock(current->mm);
1835 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
1839 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
1843 void kvm_arch_flush_shadow_all(struct kvm *kvm)
1845 kvm_free_stage2_pgd(&kvm->arch.mmu);
1848 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
1849 struct kvm_memory_slot *slot)
1851 gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
1852 phys_addr_t size = slot->npages << PAGE_SHIFT;
1854 write_lock(&kvm->mmu_lock);
1855 unmap_stage2_range(&kvm->arch.mmu, gpa, size);
1856 write_unlock(&kvm->mmu_lock);
1860 * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
1863 * - S/W ops are local to a CPU (not broadcast)
1864 * - We have line migration behind our back (speculation)
1865 * - System caches don't support S/W at all (damn!)
1867 * In the face of the above, the best we can do is to try and convert
1868 * S/W ops to VA ops. Because the guest is not allowed to infer the
1869 * S/W to PA mapping, it can only use S/W to nuke the whole cache,
1870 * which is a rather good thing for us.
1872 * Also, it is only used when turning caches on/off ("The expected
1873 * usage of the cache maintenance instructions that operate by set/way
1874 * is associated with the cache maintenance instructions associated
1875 * with the powerdown and powerup of caches, if this is required by
1876 * the implementation.").
1878 * We use the following policy:
1880 * - If we trap a S/W operation, we enable VM trapping to detect
1881 * caches being turned on/off, and do a full clean.
1883 * - We flush the caches on both caches being turned on and off.
1885 * - Once the caches are enabled, we stop trapping VM ops.
1887 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
1889 unsigned long hcr = *vcpu_hcr(vcpu);
1892 * If this is the first time we do a S/W operation
1893 * (i.e. HCR_TVM not set) flush the whole memory, and set the
1896 * Otherwise, rely on the VM trapping to wait for the MMU +
1897 * Caches to be turned off. At that point, we'll be able to
1898 * clean the caches again.
1900 if (!(hcr & HCR_TVM)) {
1901 trace_kvm_set_way_flush(*vcpu_pc(vcpu),
1902 vcpu_has_cache_enabled(vcpu));
1903 stage2_flush_vm(vcpu->kvm);
1904 *vcpu_hcr(vcpu) = hcr | HCR_TVM;
1908 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
1910 bool now_enabled = vcpu_has_cache_enabled(vcpu);
1913 * If switching the MMU+caches on, need to invalidate the caches.
1914 * If switching it off, need to clean the caches.
1915 * Clean + invalidate does the trick always.
1917 if (now_enabled != was_enabled)
1918 stage2_flush_vm(vcpu->kvm);
1920 /* Caches are now on, stop trapping VM ops (until a S/W op) */
1922 *vcpu_hcr(vcpu) &= ~HCR_TVM;
1924 trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);