xref: /linux/arch/arm64/kvm/mmu.c (revision 84b9b44b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2012 - Virtual Open Systems and Columbia University
4  * Author: Christoffer Dall <c.dall@virtualopensystems.com>
5  */
6 
7 #include <linux/mman.h>
8 #include <linux/kvm_host.h>
9 #include <linux/io.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>
21 #include <asm/virt.h>
22 
23 #include "trace.h"
24 
25 static struct kvm_pgtable *hyp_pgtable;
26 static DEFINE_MUTEX(kvm_hyp_pgd_mutex);
27 
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;
31 
32 static unsigned long __ro_after_init io_map_base;
33 
34 static phys_addr_t stage2_range_addr_end(phys_addr_t addr, phys_addr_t end)
35 {
36 	phys_addr_t size = kvm_granule_size(KVM_PGTABLE_MIN_BLOCK_LEVEL);
37 	phys_addr_t boundary = ALIGN_DOWN(addr + size, size);
38 
39 	return (boundary - 1 < end - 1) ? boundary : end;
40 }
41 
42 /*
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.
48  */
49 static int stage2_apply_range(struct kvm_s2_mmu *mmu, phys_addr_t addr,
50 			      phys_addr_t end,
51 			      int (*fn)(struct kvm_pgtable *, u64, u64),
52 			      bool resched)
53 {
54 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
55 	int ret;
56 	u64 next;
57 
58 	do {
59 		struct kvm_pgtable *pgt = mmu->pgt;
60 		if (!pgt)
61 			return -EINVAL;
62 
63 		next = stage2_range_addr_end(addr, end);
64 		ret = fn(pgt, addr, next - addr);
65 		if (ret)
66 			break;
67 
68 		if (resched && next != end)
69 			cond_resched_rwlock_write(&kvm->mmu_lock);
70 	} while (addr = next, addr != end);
71 
72 	return ret;
73 }
74 
75 #define stage2_apply_range_resched(mmu, addr, end, fn)			\
76 	stage2_apply_range(mmu, addr, end, fn, true)
77 
78 static bool memslot_is_logging(struct kvm_memory_slot *memslot)
79 {
80 	return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY);
81 }
82 
83 /**
84  * kvm_flush_remote_tlbs() - flush all VM TLB entries for v7/8
85  * @kvm:	pointer to kvm structure.
86  *
87  * Interface to HYP function to flush all VM TLB entries
88  */
89 void kvm_flush_remote_tlbs(struct kvm *kvm)
90 {
91 	++kvm->stat.generic.remote_tlb_flush_requests;
92 	kvm_call_hyp(__kvm_tlb_flush_vmid, &kvm->arch.mmu);
93 }
94 
95 static bool kvm_is_device_pfn(unsigned long pfn)
96 {
97 	return !pfn_is_map_memory(pfn);
98 }
99 
100 static void *stage2_memcache_zalloc_page(void *arg)
101 {
102 	struct kvm_mmu_memory_cache *mc = arg;
103 	void *virt;
104 
105 	/* Allocated with __GFP_ZERO, so no need to zero */
106 	virt = kvm_mmu_memory_cache_alloc(mc);
107 	if (virt)
108 		kvm_account_pgtable_pages(virt, 1);
109 	return virt;
110 }
111 
112 static void *kvm_host_zalloc_pages_exact(size_t size)
113 {
114 	return alloc_pages_exact(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
115 }
116 
117 static void *kvm_s2_zalloc_pages_exact(size_t size)
118 {
119 	void *virt = kvm_host_zalloc_pages_exact(size);
120 
121 	if (virt)
122 		kvm_account_pgtable_pages(virt, (size >> PAGE_SHIFT));
123 	return virt;
124 }
125 
126 static void kvm_s2_free_pages_exact(void *virt, size_t size)
127 {
128 	kvm_account_pgtable_pages(virt, -(size >> PAGE_SHIFT));
129 	free_pages_exact(virt, size);
130 }
131 
132 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops;
133 
134 static void stage2_free_removed_table_rcu_cb(struct rcu_head *head)
135 {
136 	struct page *page = container_of(head, struct page, rcu_head);
137 	void *pgtable = page_to_virt(page);
138 	u32 level = page_private(page);
139 
140 	kvm_pgtable_stage2_free_removed(&kvm_s2_mm_ops, pgtable, level);
141 }
142 
143 static void stage2_free_removed_table(void *addr, u32 level)
144 {
145 	struct page *page = virt_to_page(addr);
146 
147 	set_page_private(page, (unsigned long)level);
148 	call_rcu(&page->rcu_head, stage2_free_removed_table_rcu_cb);
149 }
150 
151 static void kvm_host_get_page(void *addr)
152 {
153 	get_page(virt_to_page(addr));
154 }
155 
156 static void kvm_host_put_page(void *addr)
157 {
158 	put_page(virt_to_page(addr));
159 }
160 
161 static void kvm_s2_put_page(void *addr)
162 {
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);
167 	put_page(p);
168 }
169 
170 static int kvm_host_page_count(void *addr)
171 {
172 	return page_count(virt_to_page(addr));
173 }
174 
175 static phys_addr_t kvm_host_pa(void *addr)
176 {
177 	return __pa(addr);
178 }
179 
180 static void *kvm_host_va(phys_addr_t phys)
181 {
182 	return __va(phys);
183 }
184 
185 static void clean_dcache_guest_page(void *va, size_t size)
186 {
187 	__clean_dcache_guest_page(va, size);
188 }
189 
190 static void invalidate_icache_guest_page(void *va, size_t size)
191 {
192 	__invalidate_icache_guest_page(va, size);
193 }
194 
195 /*
196  * Unmapping vs dcache management:
197  *
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
201  * data.
202  *
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.
206  *
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.
210  *
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.
214  *
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
217  * does.
218  */
219 /**
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
225  *
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.
230  */
231 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
232 				 bool may_block)
233 {
234 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
235 	phys_addr_t end = start + size;
236 
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,
240 				   may_block));
241 }
242 
243 static void unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size)
244 {
245 	__unmap_stage2_range(mmu, start, size, true);
246 }
247 
248 static void stage2_flush_memslot(struct kvm *kvm,
249 				 struct kvm_memory_slot *memslot)
250 {
251 	phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
252 	phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
253 
254 	stage2_apply_range_resched(&kvm->arch.mmu, addr, end, kvm_pgtable_stage2_flush);
255 }
256 
257 /**
258  * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
259  * @kvm: The struct kvm pointer
260  *
261  * Go through the stage 2 page tables and invalidate any cache lines
262  * backing memory already mapped to the VM.
263  */
264 static void stage2_flush_vm(struct kvm *kvm)
265 {
266 	struct kvm_memslots *slots;
267 	struct kvm_memory_slot *memslot;
268 	int idx, bkt;
269 
270 	idx = srcu_read_lock(&kvm->srcu);
271 	write_lock(&kvm->mmu_lock);
272 
273 	slots = kvm_memslots(kvm);
274 	kvm_for_each_memslot(memslot, bkt, slots)
275 		stage2_flush_memslot(kvm, memslot);
276 
277 	write_unlock(&kvm->mmu_lock);
278 	srcu_read_unlock(&kvm->srcu, idx);
279 }
280 
281 /**
282  * free_hyp_pgds - free Hyp-mode page tables
283  */
284 void __init free_hyp_pgds(void)
285 {
286 	mutex_lock(&kvm_hyp_pgd_mutex);
287 	if (hyp_pgtable) {
288 		kvm_pgtable_hyp_destroy(hyp_pgtable);
289 		kfree(hyp_pgtable);
290 		hyp_pgtable = NULL;
291 	}
292 	mutex_unlock(&kvm_hyp_pgd_mutex);
293 }
294 
295 static bool kvm_host_owns_hyp_mappings(void)
296 {
297 	if (is_kernel_in_hyp_mode())
298 		return false;
299 
300 	if (static_branch_likely(&kvm_protected_mode_initialized))
301 		return false;
302 
303 	/*
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.
307 	 */
308 	if (!hyp_pgtable && is_protected_kvm_enabled())
309 		return false;
310 
311 	WARN_ON(!hyp_pgtable);
312 
313 	return true;
314 }
315 
316 int __create_hyp_mappings(unsigned long start, unsigned long size,
317 			  unsigned long phys, enum kvm_pgtable_prot prot)
318 {
319 	int err;
320 
321 	if (WARN_ON(!kvm_host_owns_hyp_mappings()))
322 		return -EINVAL;
323 
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);
327 
328 	return err;
329 }
330 
331 static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
332 {
333 	if (!is_vmalloc_addr(kaddr)) {
334 		BUG_ON(!virt_addr_valid(kaddr));
335 		return __pa(kaddr);
336 	} else {
337 		return page_to_phys(vmalloc_to_page(kaddr)) +
338 		       offset_in_page(kaddr);
339 	}
340 }
341 
342 struct hyp_shared_pfn {
343 	u64 pfn;
344 	int count;
345 	struct rb_node node;
346 };
347 
348 static DEFINE_MUTEX(hyp_shared_pfns_lock);
349 static struct rb_root hyp_shared_pfns = RB_ROOT;
350 
351 static struct hyp_shared_pfn *find_shared_pfn(u64 pfn, struct rb_node ***node,
352 					      struct rb_node **parent)
353 {
354 	struct hyp_shared_pfn *this;
355 
356 	*node = &hyp_shared_pfns.rb_node;
357 	*parent = NULL;
358 	while (**node) {
359 		this = container_of(**node, struct hyp_shared_pfn, node);
360 		*parent = **node;
361 		if (this->pfn < pfn)
362 			*node = &((**node)->rb_left);
363 		else if (this->pfn > pfn)
364 			*node = &((**node)->rb_right);
365 		else
366 			return this;
367 	}
368 
369 	return NULL;
370 }
371 
372 static int share_pfn_hyp(u64 pfn)
373 {
374 	struct rb_node **node, *parent;
375 	struct hyp_shared_pfn *this;
376 	int ret = 0;
377 
378 	mutex_lock(&hyp_shared_pfns_lock);
379 	this = find_shared_pfn(pfn, &node, &parent);
380 	if (this) {
381 		this->count++;
382 		goto unlock;
383 	}
384 
385 	this = kzalloc(sizeof(*this), GFP_KERNEL);
386 	if (!this) {
387 		ret = -ENOMEM;
388 		goto unlock;
389 	}
390 
391 	this->pfn = pfn;
392 	this->count = 1;
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);
396 unlock:
397 	mutex_unlock(&hyp_shared_pfns_lock);
398 
399 	return ret;
400 }
401 
402 static int unshare_pfn_hyp(u64 pfn)
403 {
404 	struct rb_node **node, *parent;
405 	struct hyp_shared_pfn *this;
406 	int ret = 0;
407 
408 	mutex_lock(&hyp_shared_pfns_lock);
409 	this = find_shared_pfn(pfn, &node, &parent);
410 	if (WARN_ON(!this)) {
411 		ret = -ENOENT;
412 		goto unlock;
413 	}
414 
415 	this->count--;
416 	if (this->count)
417 		goto unlock;
418 
419 	rb_erase(&this->node, &hyp_shared_pfns);
420 	kfree(this);
421 	ret = kvm_call_hyp_nvhe(__pkvm_host_unshare_hyp, pfn, 1);
422 unlock:
423 	mutex_unlock(&hyp_shared_pfns_lock);
424 
425 	return ret;
426 }
427 
428 int kvm_share_hyp(void *from, void *to)
429 {
430 	phys_addr_t start, end, cur;
431 	u64 pfn;
432 	int ret;
433 
434 	if (is_kernel_in_hyp_mode())
435 		return 0;
436 
437 	/*
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
440 	 * for now.
441 	 */
442 	if (is_vmalloc_or_module_addr(from) || is_vmalloc_or_module_addr(to))
443 		return -EINVAL;
444 
445 	if (kvm_host_owns_hyp_mappings())
446 		return create_hyp_mappings(from, to, PAGE_HYP);
447 
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);
453 		if (ret)
454 			return ret;
455 	}
456 
457 	return 0;
458 }
459 
460 void kvm_unshare_hyp(void *from, void *to)
461 {
462 	phys_addr_t start, end, cur;
463 	u64 pfn;
464 
465 	if (is_kernel_in_hyp_mode() || kvm_host_owns_hyp_mappings() || !from)
466 		return;
467 
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));
473 	}
474 }
475 
476 /**
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
481  *
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
484  * physical pages.
485  */
486 int create_hyp_mappings(void *from, void *to, enum kvm_pgtable_prot prot)
487 {
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);
492 
493 	if (is_kernel_in_hyp_mode())
494 		return 0;
495 
496 	if (!kvm_host_owns_hyp_mappings())
497 		return -EPERM;
498 
499 	start = start & PAGE_MASK;
500 	end = PAGE_ALIGN(end);
501 
502 	for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
503 		int err;
504 
505 		phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
506 		err = __create_hyp_mappings(virt_addr, PAGE_SIZE, phys_addr,
507 					    prot);
508 		if (err)
509 			return err;
510 	}
511 
512 	return 0;
513 }
514 
515 
516 /**
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.
520  *
521  * The private virtual address (VA) range is allocated below io_map_base
522  * and aligned based on the order of @size.
523  *
524  * Return: 0 on success or negative error code on failure.
525  */
526 int hyp_alloc_private_va_range(size_t size, unsigned long *haddr)
527 {
528 	unsigned long base;
529 	int ret = 0;
530 
531 	mutex_lock(&kvm_hyp_pgd_mutex);
532 
533 	/*
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.
538 	 *
539 	 * The allocated size is always a multiple of PAGE_SIZE.
540 	 */
541 	base = io_map_base - PAGE_ALIGN(size);
542 
543 	/* Align the allocation based on the order of its size */
544 	base = ALIGN_DOWN(base, PAGE_SIZE << get_order(size));
545 
546 	/*
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.
550 	 */
551 	if ((base ^ io_map_base) & BIT(VA_BITS - 1))
552 		ret = -ENOMEM;
553 	else
554 		*haddr = io_map_base = base;
555 
556 	mutex_unlock(&kvm_hyp_pgd_mutex);
557 
558 	return ret;
559 }
560 
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)
564 {
565 	unsigned long addr;
566 	int ret = 0;
567 
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))
572 			return addr;
573 		*haddr = addr;
574 
575 		return 0;
576 	}
577 
578 	size = PAGE_ALIGN(size + offset_in_page(phys_addr));
579 	ret = hyp_alloc_private_va_range(size, &addr);
580 	if (ret)
581 		return ret;
582 
583 	ret = __create_hyp_mappings(addr, size, phys_addr, prot);
584 	if (ret)
585 		return ret;
586 
587 	*haddr = addr + offset_in_page(phys_addr);
588 	return ret;
589 }
590 
591 /**
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
597  */
598 int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size,
599 			   void __iomem **kaddr,
600 			   void __iomem **haddr)
601 {
602 	unsigned long addr;
603 	int ret;
604 
605 	if (is_protected_kvm_enabled())
606 		return -EPERM;
607 
608 	*kaddr = ioremap(phys_addr, size);
609 	if (!*kaddr)
610 		return -ENOMEM;
611 
612 	if (is_kernel_in_hyp_mode()) {
613 		*haddr = *kaddr;
614 		return 0;
615 	}
616 
617 	ret = __create_hyp_private_mapping(phys_addr, size,
618 					   &addr, PAGE_HYP_DEVICE);
619 	if (ret) {
620 		iounmap(*kaddr);
621 		*kaddr = NULL;
622 		*haddr = NULL;
623 		return ret;
624 	}
625 
626 	*haddr = (void __iomem *)addr;
627 	return 0;
628 }
629 
630 /**
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
635  */
636 int create_hyp_exec_mappings(phys_addr_t phys_addr, size_t size,
637 			     void **haddr)
638 {
639 	unsigned long addr;
640 	int ret;
641 
642 	BUG_ON(is_kernel_in_hyp_mode());
643 
644 	ret = __create_hyp_private_mapping(phys_addr, size,
645 					   &addr, PAGE_HYP_EXEC);
646 	if (ret) {
647 		*haddr = NULL;
648 		return ret;
649 	}
650 
651 	*haddr = (void *)addr;
652 	return 0;
653 }
654 
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,
658 };
659 
660 static int get_user_mapping_size(struct kvm *kvm, u64 addr)
661 {
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,
668 	};
669 	unsigned long flags;
670 	kvm_pte_t pte = 0;	/* Keep GCC quiet... */
671 	u32 level = ~0;
672 	int ret;
673 
674 	/*
675 	 * Disable IRQs so that we hazard against a concurrent
676 	 * teardown of the userspace page tables (which relies on
677 	 * IPI-ing threads).
678 	 */
679 	local_irq_save(flags);
680 	ret = kvm_pgtable_get_leaf(&pgt, addr, &pte, &level);
681 	local_irq_restore(flags);
682 
683 	if (ret)
684 		return ret;
685 
686 	/*
687 	 * Not seeing an error, but not updating level? Something went
688 	 * deeply wrong...
689 	 */
690 	if (WARN_ON(level >= KVM_PGTABLE_MAX_LEVELS))
691 		return -EFAULT;
692 
693 	/* Oops, the userspace PTs are gone... Replay the fault */
694 	if (!kvm_pte_valid(pte))
695 		return -EAGAIN;
696 
697 	return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(level));
698 }
699 
700 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
701 	.zalloc_page		= stage2_memcache_zalloc_page,
702 	.zalloc_pages_exact	= kvm_s2_zalloc_pages_exact,
703 	.free_pages_exact	= kvm_s2_free_pages_exact,
704 	.free_removed_table	= stage2_free_removed_table,
705 	.get_page		= kvm_host_get_page,
706 	.put_page		= kvm_s2_put_page,
707 	.page_count		= kvm_host_page_count,
708 	.phys_to_virt		= kvm_host_va,
709 	.virt_to_phys		= kvm_host_pa,
710 	.dcache_clean_inval_poc	= clean_dcache_guest_page,
711 	.icache_inval_pou	= invalidate_icache_guest_page,
712 };
713 
714 /**
715  * kvm_init_stage2_mmu - Initialise a S2 MMU structure
716  * @kvm:	The pointer to the KVM structure
717  * @mmu:	The pointer to the s2 MMU structure
718  * @type:	The machine type of the virtual machine
719  *
720  * Allocates only the stage-2 HW PGD level table(s).
721  * Note we don't need locking here as this is only called when the VM is
722  * created, which can only be done once.
723  */
724 int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long type)
725 {
726 	u32 kvm_ipa_limit = get_kvm_ipa_limit();
727 	int cpu, err;
728 	struct kvm_pgtable *pgt;
729 	u64 mmfr0, mmfr1;
730 	u32 phys_shift;
731 
732 	if (type & ~KVM_VM_TYPE_ARM_IPA_SIZE_MASK)
733 		return -EINVAL;
734 
735 	phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
736 	if (is_protected_kvm_enabled()) {
737 		phys_shift = kvm_ipa_limit;
738 	} else if (phys_shift) {
739 		if (phys_shift > kvm_ipa_limit ||
740 		    phys_shift < ARM64_MIN_PARANGE_BITS)
741 			return -EINVAL;
742 	} else {
743 		phys_shift = KVM_PHYS_SHIFT;
744 		if (phys_shift > kvm_ipa_limit) {
745 			pr_warn_once("%s using unsupported default IPA limit, upgrade your VMM\n",
746 				     current->comm);
747 			return -EINVAL;
748 		}
749 	}
750 
751 	mmfr0 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
752 	mmfr1 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
753 	kvm->arch.vtcr = kvm_get_vtcr(mmfr0, mmfr1, phys_shift);
754 
755 	if (mmu->pgt != NULL) {
756 		kvm_err("kvm_arch already initialized?\n");
757 		return -EINVAL;
758 	}
759 
760 	pgt = kzalloc(sizeof(*pgt), GFP_KERNEL_ACCOUNT);
761 	if (!pgt)
762 		return -ENOMEM;
763 
764 	mmu->arch = &kvm->arch;
765 	err = kvm_pgtable_stage2_init(pgt, mmu, &kvm_s2_mm_ops);
766 	if (err)
767 		goto out_free_pgtable;
768 
769 	mmu->last_vcpu_ran = alloc_percpu(typeof(*mmu->last_vcpu_ran));
770 	if (!mmu->last_vcpu_ran) {
771 		err = -ENOMEM;
772 		goto out_destroy_pgtable;
773 	}
774 
775 	for_each_possible_cpu(cpu)
776 		*per_cpu_ptr(mmu->last_vcpu_ran, cpu) = -1;
777 
778 	mmu->pgt = pgt;
779 	mmu->pgd_phys = __pa(pgt->pgd);
780 	return 0;
781 
782 out_destroy_pgtable:
783 	kvm_pgtable_stage2_destroy(pgt);
784 out_free_pgtable:
785 	kfree(pgt);
786 	return err;
787 }
788 
789 static void stage2_unmap_memslot(struct kvm *kvm,
790 				 struct kvm_memory_slot *memslot)
791 {
792 	hva_t hva = memslot->userspace_addr;
793 	phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
794 	phys_addr_t size = PAGE_SIZE * memslot->npages;
795 	hva_t reg_end = hva + size;
796 
797 	/*
798 	 * A memory region could potentially cover multiple VMAs, and any holes
799 	 * between them, so iterate over all of them to find out if we should
800 	 * unmap any of them.
801 	 *
802 	 *     +--------------------------------------------+
803 	 * +---------------+----------------+   +----------------+
804 	 * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
805 	 * +---------------+----------------+   +----------------+
806 	 *     |               memory region                |
807 	 *     +--------------------------------------------+
808 	 */
809 	do {
810 		struct vm_area_struct *vma;
811 		hva_t vm_start, vm_end;
812 
813 		vma = find_vma_intersection(current->mm, hva, reg_end);
814 		if (!vma)
815 			break;
816 
817 		/*
818 		 * Take the intersection of this VMA with the memory region
819 		 */
820 		vm_start = max(hva, vma->vm_start);
821 		vm_end = min(reg_end, vma->vm_end);
822 
823 		if (!(vma->vm_flags & VM_PFNMAP)) {
824 			gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
825 			unmap_stage2_range(&kvm->arch.mmu, gpa, vm_end - vm_start);
826 		}
827 		hva = vm_end;
828 	} while (hva < reg_end);
829 }
830 
831 /**
832  * stage2_unmap_vm - Unmap Stage-2 RAM mappings
833  * @kvm: The struct kvm pointer
834  *
835  * Go through the memregions and unmap any regular RAM
836  * backing memory already mapped to the VM.
837  */
838 void stage2_unmap_vm(struct kvm *kvm)
839 {
840 	struct kvm_memslots *slots;
841 	struct kvm_memory_slot *memslot;
842 	int idx, bkt;
843 
844 	idx = srcu_read_lock(&kvm->srcu);
845 	mmap_read_lock(current->mm);
846 	write_lock(&kvm->mmu_lock);
847 
848 	slots = kvm_memslots(kvm);
849 	kvm_for_each_memslot(memslot, bkt, slots)
850 		stage2_unmap_memslot(kvm, memslot);
851 
852 	write_unlock(&kvm->mmu_lock);
853 	mmap_read_unlock(current->mm);
854 	srcu_read_unlock(&kvm->srcu, idx);
855 }
856 
857 void kvm_free_stage2_pgd(struct kvm_s2_mmu *mmu)
858 {
859 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
860 	struct kvm_pgtable *pgt = NULL;
861 
862 	write_lock(&kvm->mmu_lock);
863 	pgt = mmu->pgt;
864 	if (pgt) {
865 		mmu->pgd_phys = 0;
866 		mmu->pgt = NULL;
867 		free_percpu(mmu->last_vcpu_ran);
868 	}
869 	write_unlock(&kvm->mmu_lock);
870 
871 	if (pgt) {
872 		kvm_pgtable_stage2_destroy(pgt);
873 		kfree(pgt);
874 	}
875 }
876 
877 static void hyp_mc_free_fn(void *addr, void *unused)
878 {
879 	free_page((unsigned long)addr);
880 }
881 
882 static void *hyp_mc_alloc_fn(void *unused)
883 {
884 	return (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
885 }
886 
887 void free_hyp_memcache(struct kvm_hyp_memcache *mc)
888 {
889 	if (is_protected_kvm_enabled())
890 		__free_hyp_memcache(mc, hyp_mc_free_fn,
891 				    kvm_host_va, NULL);
892 }
893 
894 int topup_hyp_memcache(struct kvm_hyp_memcache *mc, unsigned long min_pages)
895 {
896 	if (!is_protected_kvm_enabled())
897 		return 0;
898 
899 	return __topup_hyp_memcache(mc, min_pages, hyp_mc_alloc_fn,
900 				    kvm_host_pa, NULL);
901 }
902 
903 /**
904  * kvm_phys_addr_ioremap - map a device range to guest IPA
905  *
906  * @kvm:	The KVM pointer
907  * @guest_ipa:	The IPA at which to insert the mapping
908  * @pa:		The physical address of the device
909  * @size:	The size of the mapping
910  * @writable:   Whether or not to create a writable mapping
911  */
912 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
913 			  phys_addr_t pa, unsigned long size, bool writable)
914 {
915 	phys_addr_t addr;
916 	int ret = 0;
917 	struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };
918 	struct kvm_pgtable *pgt = kvm->arch.mmu.pgt;
919 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_DEVICE |
920 				     KVM_PGTABLE_PROT_R |
921 				     (writable ? KVM_PGTABLE_PROT_W : 0);
922 
923 	if (is_protected_kvm_enabled())
924 		return -EPERM;
925 
926 	size += offset_in_page(guest_ipa);
927 	guest_ipa &= PAGE_MASK;
928 
929 	for (addr = guest_ipa; addr < guest_ipa + size; addr += PAGE_SIZE) {
930 		ret = kvm_mmu_topup_memory_cache(&cache,
931 						 kvm_mmu_cache_min_pages(kvm));
932 		if (ret)
933 			break;
934 
935 		write_lock(&kvm->mmu_lock);
936 		ret = kvm_pgtable_stage2_map(pgt, addr, PAGE_SIZE, pa, prot,
937 					     &cache, 0);
938 		write_unlock(&kvm->mmu_lock);
939 		if (ret)
940 			break;
941 
942 		pa += PAGE_SIZE;
943 	}
944 
945 	kvm_mmu_free_memory_cache(&cache);
946 	return ret;
947 }
948 
949 /**
950  * stage2_wp_range() - write protect stage2 memory region range
951  * @mmu:        The KVM stage-2 MMU pointer
952  * @addr:	Start address of range
953  * @end:	End address of range
954  */
955 static void stage2_wp_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
956 {
957 	stage2_apply_range_resched(mmu, addr, end, kvm_pgtable_stage2_wrprotect);
958 }
959 
960 /**
961  * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
962  * @kvm:	The KVM pointer
963  * @slot:	The memory slot to write protect
964  *
965  * Called to start logging dirty pages after memory region
966  * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
967  * all present PUD, PMD and PTEs are write protected in the memory region.
968  * Afterwards read of dirty page log can be called.
969  *
970  * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
971  * serializing operations for VM memory regions.
972  */
973 static void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
974 {
975 	struct kvm_memslots *slots = kvm_memslots(kvm);
976 	struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
977 	phys_addr_t start, end;
978 
979 	if (WARN_ON_ONCE(!memslot))
980 		return;
981 
982 	start = memslot->base_gfn << PAGE_SHIFT;
983 	end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
984 
985 	write_lock(&kvm->mmu_lock);
986 	stage2_wp_range(&kvm->arch.mmu, start, end);
987 	write_unlock(&kvm->mmu_lock);
988 	kvm_flush_remote_tlbs(kvm);
989 }
990 
991 /**
992  * kvm_mmu_write_protect_pt_masked() - write protect dirty pages
993  * @kvm:	The KVM pointer
994  * @slot:	The memory slot associated with mask
995  * @gfn_offset:	The gfn offset in memory slot
996  * @mask:	The mask of dirty pages at offset 'gfn_offset' in this memory
997  *		slot to be write protected
998  *
999  * Walks bits set in mask write protects the associated pte's. Caller must
1000  * acquire kvm_mmu_lock.
1001  */
1002 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1003 		struct kvm_memory_slot *slot,
1004 		gfn_t gfn_offset, unsigned long mask)
1005 {
1006 	phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
1007 	phys_addr_t start = (base_gfn +  __ffs(mask)) << PAGE_SHIFT;
1008 	phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
1009 
1010 	stage2_wp_range(&kvm->arch.mmu, start, end);
1011 }
1012 
1013 /*
1014  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1015  * dirty pages.
1016  *
1017  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1018  * enable dirty logging for them.
1019  */
1020 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1021 		struct kvm_memory_slot *slot,
1022 		gfn_t gfn_offset, unsigned long mask)
1023 {
1024 	kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1025 }
1026 
1027 static void kvm_send_hwpoison_signal(unsigned long address, short lsb)
1028 {
1029 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, current);
1030 }
1031 
1032 static bool fault_supports_stage2_huge_mapping(struct kvm_memory_slot *memslot,
1033 					       unsigned long hva,
1034 					       unsigned long map_size)
1035 {
1036 	gpa_t gpa_start;
1037 	hva_t uaddr_start, uaddr_end;
1038 	size_t size;
1039 
1040 	/* The memslot and the VMA are guaranteed to be aligned to PAGE_SIZE */
1041 	if (map_size == PAGE_SIZE)
1042 		return true;
1043 
1044 	size = memslot->npages * PAGE_SIZE;
1045 
1046 	gpa_start = memslot->base_gfn << PAGE_SHIFT;
1047 
1048 	uaddr_start = memslot->userspace_addr;
1049 	uaddr_end = uaddr_start + size;
1050 
1051 	/*
1052 	 * Pages belonging to memslots that don't have the same alignment
1053 	 * within a PMD/PUD for userspace and IPA cannot be mapped with stage-2
1054 	 * PMD/PUD entries, because we'll end up mapping the wrong pages.
1055 	 *
1056 	 * Consider a layout like the following:
1057 	 *
1058 	 *    memslot->userspace_addr:
1059 	 *    +-----+--------------------+--------------------+---+
1060 	 *    |abcde|fgh  Stage-1 block  |    Stage-1 block tv|xyz|
1061 	 *    +-----+--------------------+--------------------+---+
1062 	 *
1063 	 *    memslot->base_gfn << PAGE_SHIFT:
1064 	 *      +---+--------------------+--------------------+-----+
1065 	 *      |abc|def  Stage-2 block  |    Stage-2 block   |tvxyz|
1066 	 *      +---+--------------------+--------------------+-----+
1067 	 *
1068 	 * If we create those stage-2 blocks, we'll end up with this incorrect
1069 	 * mapping:
1070 	 *   d -> f
1071 	 *   e -> g
1072 	 *   f -> h
1073 	 */
1074 	if ((gpa_start & (map_size - 1)) != (uaddr_start & (map_size - 1)))
1075 		return false;
1076 
1077 	/*
1078 	 * Next, let's make sure we're not trying to map anything not covered
1079 	 * by the memslot. This means we have to prohibit block size mappings
1080 	 * for the beginning and end of a non-block aligned and non-block sized
1081 	 * memory slot (illustrated by the head and tail parts of the
1082 	 * userspace view above containing pages 'abcde' and 'xyz',
1083 	 * respectively).
1084 	 *
1085 	 * Note that it doesn't matter if we do the check using the
1086 	 * userspace_addr or the base_gfn, as both are equally aligned (per
1087 	 * the check above) and equally sized.
1088 	 */
1089 	return (hva & ~(map_size - 1)) >= uaddr_start &&
1090 	       (hva & ~(map_size - 1)) + map_size <= uaddr_end;
1091 }
1092 
1093 /*
1094  * Check if the given hva is backed by a transparent huge page (THP) and
1095  * whether it can be mapped using block mapping in stage2. If so, adjust
1096  * the stage2 PFN and IPA accordingly. Only PMD_SIZE THPs are currently
1097  * supported. This will need to be updated to support other THP sizes.
1098  *
1099  * Returns the size of the mapping.
1100  */
1101 static long
1102 transparent_hugepage_adjust(struct kvm *kvm, struct kvm_memory_slot *memslot,
1103 			    unsigned long hva, kvm_pfn_t *pfnp,
1104 			    phys_addr_t *ipap)
1105 {
1106 	kvm_pfn_t pfn = *pfnp;
1107 
1108 	/*
1109 	 * Make sure the adjustment is done only for THP pages. Also make
1110 	 * sure that the HVA and IPA are sufficiently aligned and that the
1111 	 * block map is contained within the memslot.
1112 	 */
1113 	if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE)) {
1114 		int sz = get_user_mapping_size(kvm, hva);
1115 
1116 		if (sz < 0)
1117 			return sz;
1118 
1119 		if (sz < PMD_SIZE)
1120 			return PAGE_SIZE;
1121 
1122 		/*
1123 		 * The address we faulted on is backed by a transparent huge
1124 		 * page.  However, because we map the compound huge page and
1125 		 * not the individual tail page, we need to transfer the
1126 		 * refcount to the head page.  We have to be careful that the
1127 		 * THP doesn't start to split while we are adjusting the
1128 		 * refcounts.
1129 		 *
1130 		 * We are sure this doesn't happen, because mmu_invalidate_retry
1131 		 * was successful and we are holding the mmu_lock, so if this
1132 		 * THP is trying to split, it will be blocked in the mmu
1133 		 * notifier before touching any of the pages, specifically
1134 		 * before being able to call __split_huge_page_refcount().
1135 		 *
1136 		 * We can therefore safely transfer the refcount from PG_tail
1137 		 * to PG_head and switch the pfn from a tail page to the head
1138 		 * page accordingly.
1139 		 */
1140 		*ipap &= PMD_MASK;
1141 		kvm_release_pfn_clean(pfn);
1142 		pfn &= ~(PTRS_PER_PMD - 1);
1143 		get_page(pfn_to_page(pfn));
1144 		*pfnp = pfn;
1145 
1146 		return PMD_SIZE;
1147 	}
1148 
1149 	/* Use page mapping if we cannot use block mapping. */
1150 	return PAGE_SIZE;
1151 }
1152 
1153 static int get_vma_page_shift(struct vm_area_struct *vma, unsigned long hva)
1154 {
1155 	unsigned long pa;
1156 
1157 	if (is_vm_hugetlb_page(vma) && !(vma->vm_flags & VM_PFNMAP))
1158 		return huge_page_shift(hstate_vma(vma));
1159 
1160 	if (!(vma->vm_flags & VM_PFNMAP))
1161 		return PAGE_SHIFT;
1162 
1163 	VM_BUG_ON(is_vm_hugetlb_page(vma));
1164 
1165 	pa = (vma->vm_pgoff << PAGE_SHIFT) + (hva - vma->vm_start);
1166 
1167 #ifndef __PAGETABLE_PMD_FOLDED
1168 	if ((hva & (PUD_SIZE - 1)) == (pa & (PUD_SIZE - 1)) &&
1169 	    ALIGN_DOWN(hva, PUD_SIZE) >= vma->vm_start &&
1170 	    ALIGN(hva, PUD_SIZE) <= vma->vm_end)
1171 		return PUD_SHIFT;
1172 #endif
1173 
1174 	if ((hva & (PMD_SIZE - 1)) == (pa & (PMD_SIZE - 1)) &&
1175 	    ALIGN_DOWN(hva, PMD_SIZE) >= vma->vm_start &&
1176 	    ALIGN(hva, PMD_SIZE) <= vma->vm_end)
1177 		return PMD_SHIFT;
1178 
1179 	return PAGE_SHIFT;
1180 }
1181 
1182 /*
1183  * The page will be mapped in stage 2 as Normal Cacheable, so the VM will be
1184  * able to see the page's tags and therefore they must be initialised first. If
1185  * PG_mte_tagged is set, tags have already been initialised.
1186  *
1187  * The race in the test/set of the PG_mte_tagged flag is handled by:
1188  * - preventing VM_SHARED mappings in a memslot with MTE preventing two VMs
1189  *   racing to santise the same page
1190  * - mmap_lock protects between a VM faulting a page in and the VMM performing
1191  *   an mprotect() to add VM_MTE
1192  */
1193 static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn,
1194 			      unsigned long size)
1195 {
1196 	unsigned long i, nr_pages = size >> PAGE_SHIFT;
1197 	struct page *page = pfn_to_page(pfn);
1198 
1199 	if (!kvm_has_mte(kvm))
1200 		return;
1201 
1202 	for (i = 0; i < nr_pages; i++, page++) {
1203 		if (try_page_mte_tagging(page)) {
1204 			mte_clear_page_tags(page_address(page));
1205 			set_page_mte_tagged(page);
1206 		}
1207 	}
1208 }
1209 
1210 static bool kvm_vma_mte_allowed(struct vm_area_struct *vma)
1211 {
1212 	return vma->vm_flags & VM_MTE_ALLOWED;
1213 }
1214 
1215 static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1216 			  struct kvm_memory_slot *memslot, unsigned long hva,
1217 			  unsigned long fault_status)
1218 {
1219 	int ret = 0;
1220 	bool write_fault, writable, force_pte = false;
1221 	bool exec_fault, mte_allowed;
1222 	bool device = false;
1223 	unsigned long mmu_seq;
1224 	struct kvm *kvm = vcpu->kvm;
1225 	struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
1226 	struct vm_area_struct *vma;
1227 	short vma_shift;
1228 	gfn_t gfn;
1229 	kvm_pfn_t pfn;
1230 	bool logging_active = memslot_is_logging(memslot);
1231 	unsigned long fault_level = kvm_vcpu_trap_get_fault_level(vcpu);
1232 	long vma_pagesize, fault_granule;
1233 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
1234 	struct kvm_pgtable *pgt;
1235 
1236 	fault_granule = 1UL << ARM64_HW_PGTABLE_LEVEL_SHIFT(fault_level);
1237 	write_fault = kvm_is_write_fault(vcpu);
1238 	exec_fault = kvm_vcpu_trap_is_exec_fault(vcpu);
1239 	VM_BUG_ON(write_fault && exec_fault);
1240 
1241 	if (fault_status == ESR_ELx_FSC_PERM && !write_fault && !exec_fault) {
1242 		kvm_err("Unexpected L2 read permission error\n");
1243 		return -EFAULT;
1244 	}
1245 
1246 	/*
1247 	 * Permission faults just need to update the existing leaf entry,
1248 	 * and so normally don't require allocations from the memcache. The
1249 	 * only exception to this is when dirty logging is enabled at runtime
1250 	 * and a write fault needs to collapse a block entry into a table.
1251 	 */
1252 	if (fault_status != ESR_ELx_FSC_PERM ||
1253 	    (logging_active && write_fault)) {
1254 		ret = kvm_mmu_topup_memory_cache(memcache,
1255 						 kvm_mmu_cache_min_pages(kvm));
1256 		if (ret)
1257 			return ret;
1258 	}
1259 
1260 	/*
1261 	 * Let's check if we will get back a huge page backed by hugetlbfs, or
1262 	 * get block mapping for device MMIO region.
1263 	 */
1264 	mmap_read_lock(current->mm);
1265 	vma = vma_lookup(current->mm, hva);
1266 	if (unlikely(!vma)) {
1267 		kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
1268 		mmap_read_unlock(current->mm);
1269 		return -EFAULT;
1270 	}
1271 
1272 	/*
1273 	 * logging_active is guaranteed to never be true for VM_PFNMAP
1274 	 * memslots.
1275 	 */
1276 	if (logging_active) {
1277 		force_pte = true;
1278 		vma_shift = PAGE_SHIFT;
1279 	} else {
1280 		vma_shift = get_vma_page_shift(vma, hva);
1281 	}
1282 
1283 	switch (vma_shift) {
1284 #ifndef __PAGETABLE_PMD_FOLDED
1285 	case PUD_SHIFT:
1286 		if (fault_supports_stage2_huge_mapping(memslot, hva, PUD_SIZE))
1287 			break;
1288 		fallthrough;
1289 #endif
1290 	case CONT_PMD_SHIFT:
1291 		vma_shift = PMD_SHIFT;
1292 		fallthrough;
1293 	case PMD_SHIFT:
1294 		if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE))
1295 			break;
1296 		fallthrough;
1297 	case CONT_PTE_SHIFT:
1298 		vma_shift = PAGE_SHIFT;
1299 		force_pte = true;
1300 		fallthrough;
1301 	case PAGE_SHIFT:
1302 		break;
1303 	default:
1304 		WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
1305 	}
1306 
1307 	vma_pagesize = 1UL << vma_shift;
1308 	if (vma_pagesize == PMD_SIZE || vma_pagesize == PUD_SIZE)
1309 		fault_ipa &= ~(vma_pagesize - 1);
1310 
1311 	gfn = fault_ipa >> PAGE_SHIFT;
1312 	mte_allowed = kvm_vma_mte_allowed(vma);
1313 
1314 	/* Don't use the VMA after the unlock -- it may have vanished */
1315 	vma = NULL;
1316 
1317 	/*
1318 	 * Read mmu_invalidate_seq so that KVM can detect if the results of
1319 	 * vma_lookup() or __gfn_to_pfn_memslot() become stale prior to
1320 	 * acquiring kvm->mmu_lock.
1321 	 *
1322 	 * Rely on mmap_read_unlock() for an implicit smp_rmb(), which pairs
1323 	 * with the smp_wmb() in kvm_mmu_invalidate_end().
1324 	 */
1325 	mmu_seq = vcpu->kvm->mmu_invalidate_seq;
1326 	mmap_read_unlock(current->mm);
1327 
1328 	pfn = __gfn_to_pfn_memslot(memslot, gfn, false, false, NULL,
1329 				   write_fault, &writable, NULL);
1330 	if (pfn == KVM_PFN_ERR_HWPOISON) {
1331 		kvm_send_hwpoison_signal(hva, vma_shift);
1332 		return 0;
1333 	}
1334 	if (is_error_noslot_pfn(pfn))
1335 		return -EFAULT;
1336 
1337 	if (kvm_is_device_pfn(pfn)) {
1338 		/*
1339 		 * If the page was identified as device early by looking at
1340 		 * the VMA flags, vma_pagesize is already representing the
1341 		 * largest quantity we can map.  If instead it was mapped
1342 		 * via gfn_to_pfn_prot(), vma_pagesize is set to PAGE_SIZE
1343 		 * and must not be upgraded.
1344 		 *
1345 		 * In both cases, we don't let transparent_hugepage_adjust()
1346 		 * change things at the last minute.
1347 		 */
1348 		device = true;
1349 	} else if (logging_active && !write_fault) {
1350 		/*
1351 		 * Only actually map the page as writable if this was a write
1352 		 * fault.
1353 		 */
1354 		writable = false;
1355 	}
1356 
1357 	if (exec_fault && device)
1358 		return -ENOEXEC;
1359 
1360 	read_lock(&kvm->mmu_lock);
1361 	pgt = vcpu->arch.hw_mmu->pgt;
1362 	if (mmu_invalidate_retry(kvm, mmu_seq))
1363 		goto out_unlock;
1364 
1365 	/*
1366 	 * If we are not forced to use page mapping, check if we are
1367 	 * backed by a THP and thus use block mapping if possible.
1368 	 */
1369 	if (vma_pagesize == PAGE_SIZE && !(force_pte || device)) {
1370 		if (fault_status ==  ESR_ELx_FSC_PERM &&
1371 		    fault_granule > PAGE_SIZE)
1372 			vma_pagesize = fault_granule;
1373 		else
1374 			vma_pagesize = transparent_hugepage_adjust(kvm, memslot,
1375 								   hva, &pfn,
1376 								   &fault_ipa);
1377 
1378 		if (vma_pagesize < 0) {
1379 			ret = vma_pagesize;
1380 			goto out_unlock;
1381 		}
1382 	}
1383 
1384 	if (fault_status != ESR_ELx_FSC_PERM && !device && kvm_has_mte(kvm)) {
1385 		/* Check the VMM hasn't introduced a new disallowed VMA */
1386 		if (mte_allowed) {
1387 			sanitise_mte_tags(kvm, pfn, vma_pagesize);
1388 		} else {
1389 			ret = -EFAULT;
1390 			goto out_unlock;
1391 		}
1392 	}
1393 
1394 	if (writable)
1395 		prot |= KVM_PGTABLE_PROT_W;
1396 
1397 	if (exec_fault)
1398 		prot |= KVM_PGTABLE_PROT_X;
1399 
1400 	if (device)
1401 		prot |= KVM_PGTABLE_PROT_DEVICE;
1402 	else if (cpus_have_const_cap(ARM64_HAS_CACHE_DIC))
1403 		prot |= KVM_PGTABLE_PROT_X;
1404 
1405 	/*
1406 	 * Under the premise of getting a FSC_PERM fault, we just need to relax
1407 	 * permissions only if vma_pagesize equals fault_granule. Otherwise,
1408 	 * kvm_pgtable_stage2_map() should be called to change block size.
1409 	 */
1410 	if (fault_status == ESR_ELx_FSC_PERM && vma_pagesize == fault_granule)
1411 		ret = kvm_pgtable_stage2_relax_perms(pgt, fault_ipa, prot);
1412 	else
1413 		ret = kvm_pgtable_stage2_map(pgt, fault_ipa, vma_pagesize,
1414 					     __pfn_to_phys(pfn), prot,
1415 					     memcache,
1416 					     KVM_PGTABLE_WALK_HANDLE_FAULT |
1417 					     KVM_PGTABLE_WALK_SHARED);
1418 
1419 	/* Mark the page dirty only if the fault is handled successfully */
1420 	if (writable && !ret) {
1421 		kvm_set_pfn_dirty(pfn);
1422 		mark_page_dirty_in_slot(kvm, memslot, gfn);
1423 	}
1424 
1425 out_unlock:
1426 	read_unlock(&kvm->mmu_lock);
1427 	kvm_set_pfn_accessed(pfn);
1428 	kvm_release_pfn_clean(pfn);
1429 	return ret != -EAGAIN ? ret : 0;
1430 }
1431 
1432 /* Resolve the access fault by making the page young again. */
1433 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
1434 {
1435 	kvm_pte_t pte;
1436 	struct kvm_s2_mmu *mmu;
1437 
1438 	trace_kvm_access_fault(fault_ipa);
1439 
1440 	read_lock(&vcpu->kvm->mmu_lock);
1441 	mmu = vcpu->arch.hw_mmu;
1442 	pte = kvm_pgtable_stage2_mkyoung(mmu->pgt, fault_ipa);
1443 	read_unlock(&vcpu->kvm->mmu_lock);
1444 
1445 	if (kvm_pte_valid(pte))
1446 		kvm_set_pfn_accessed(kvm_pte_to_pfn(pte));
1447 }
1448 
1449 /**
1450  * kvm_handle_guest_abort - handles all 2nd stage aborts
1451  * @vcpu:	the VCPU pointer
1452  *
1453  * Any abort that gets to the host is almost guaranteed to be caused by a
1454  * missing second stage translation table entry, which can mean that either the
1455  * guest simply needs more memory and we must allocate an appropriate page or it
1456  * can mean that the guest tried to access I/O memory, which is emulated by user
1457  * space. The distinction is based on the IPA causing the fault and whether this
1458  * memory region has been registered as standard RAM by user space.
1459  */
1460 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
1461 {
1462 	unsigned long fault_status;
1463 	phys_addr_t fault_ipa;
1464 	struct kvm_memory_slot *memslot;
1465 	unsigned long hva;
1466 	bool is_iabt, write_fault, writable;
1467 	gfn_t gfn;
1468 	int ret, idx;
1469 
1470 	fault_status = kvm_vcpu_trap_get_fault_type(vcpu);
1471 
1472 	fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
1473 	is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
1474 
1475 	if (fault_status == ESR_ELx_FSC_FAULT) {
1476 		/* Beyond sanitised PARange (which is the IPA limit) */
1477 		if (fault_ipa >= BIT_ULL(get_kvm_ipa_limit())) {
1478 			kvm_inject_size_fault(vcpu);
1479 			return 1;
1480 		}
1481 
1482 		/* Falls between the IPA range and the PARange? */
1483 		if (fault_ipa >= BIT_ULL(vcpu->arch.hw_mmu->pgt->ia_bits)) {
1484 			fault_ipa |= kvm_vcpu_get_hfar(vcpu) & GENMASK(11, 0);
1485 
1486 			if (is_iabt)
1487 				kvm_inject_pabt(vcpu, fault_ipa);
1488 			else
1489 				kvm_inject_dabt(vcpu, fault_ipa);
1490 			return 1;
1491 		}
1492 	}
1493 
1494 	/* Synchronous External Abort? */
1495 	if (kvm_vcpu_abt_issea(vcpu)) {
1496 		/*
1497 		 * For RAS the host kernel may handle this abort.
1498 		 * There is no need to pass the error into the guest.
1499 		 */
1500 		if (kvm_handle_guest_sea(fault_ipa, kvm_vcpu_get_esr(vcpu)))
1501 			kvm_inject_vabt(vcpu);
1502 
1503 		return 1;
1504 	}
1505 
1506 	trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_esr(vcpu),
1507 			      kvm_vcpu_get_hfar(vcpu), fault_ipa);
1508 
1509 	/* Check the stage-2 fault is trans. fault or write fault */
1510 	if (fault_status != ESR_ELx_FSC_FAULT &&
1511 	    fault_status != ESR_ELx_FSC_PERM &&
1512 	    fault_status != ESR_ELx_FSC_ACCESS) {
1513 		kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
1514 			kvm_vcpu_trap_get_class(vcpu),
1515 			(unsigned long)kvm_vcpu_trap_get_fault(vcpu),
1516 			(unsigned long)kvm_vcpu_get_esr(vcpu));
1517 		return -EFAULT;
1518 	}
1519 
1520 	idx = srcu_read_lock(&vcpu->kvm->srcu);
1521 
1522 	gfn = fault_ipa >> PAGE_SHIFT;
1523 	memslot = gfn_to_memslot(vcpu->kvm, gfn);
1524 	hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
1525 	write_fault = kvm_is_write_fault(vcpu);
1526 	if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
1527 		/*
1528 		 * The guest has put either its instructions or its page-tables
1529 		 * somewhere it shouldn't have. Userspace won't be able to do
1530 		 * anything about this (there's no syndrome for a start), so
1531 		 * re-inject the abort back into the guest.
1532 		 */
1533 		if (is_iabt) {
1534 			ret = -ENOEXEC;
1535 			goto out;
1536 		}
1537 
1538 		if (kvm_vcpu_abt_iss1tw(vcpu)) {
1539 			kvm_inject_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1540 			ret = 1;
1541 			goto out_unlock;
1542 		}
1543 
1544 		/*
1545 		 * Check for a cache maintenance operation. Since we
1546 		 * ended-up here, we know it is outside of any memory
1547 		 * slot. But we can't find out if that is for a device,
1548 		 * or if the guest is just being stupid. The only thing
1549 		 * we know for sure is that this range cannot be cached.
1550 		 *
1551 		 * So let's assume that the guest is just being
1552 		 * cautious, and skip the instruction.
1553 		 */
1554 		if (kvm_is_error_hva(hva) && kvm_vcpu_dabt_is_cm(vcpu)) {
1555 			kvm_incr_pc(vcpu);
1556 			ret = 1;
1557 			goto out_unlock;
1558 		}
1559 
1560 		/*
1561 		 * The IPA is reported as [MAX:12], so we need to
1562 		 * complement it with the bottom 12 bits from the
1563 		 * faulting VA. This is always 12 bits, irrespective
1564 		 * of the page size.
1565 		 */
1566 		fault_ipa |= kvm_vcpu_get_hfar(vcpu) & ((1 << 12) - 1);
1567 		ret = io_mem_abort(vcpu, fault_ipa);
1568 		goto out_unlock;
1569 	}
1570 
1571 	/* Userspace should not be able to register out-of-bounds IPAs */
1572 	VM_BUG_ON(fault_ipa >= kvm_phys_size(vcpu->kvm));
1573 
1574 	if (fault_status == ESR_ELx_FSC_ACCESS) {
1575 		handle_access_fault(vcpu, fault_ipa);
1576 		ret = 1;
1577 		goto out_unlock;
1578 	}
1579 
1580 	ret = user_mem_abort(vcpu, fault_ipa, memslot, hva, fault_status);
1581 	if (ret == 0)
1582 		ret = 1;
1583 out:
1584 	if (ret == -ENOEXEC) {
1585 		kvm_inject_pabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1586 		ret = 1;
1587 	}
1588 out_unlock:
1589 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
1590 	return ret;
1591 }
1592 
1593 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1594 {
1595 	if (!kvm->arch.mmu.pgt)
1596 		return false;
1597 
1598 	__unmap_stage2_range(&kvm->arch.mmu, range->start << PAGE_SHIFT,
1599 			     (range->end - range->start) << PAGE_SHIFT,
1600 			     range->may_block);
1601 
1602 	return false;
1603 }
1604 
1605 bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1606 {
1607 	kvm_pfn_t pfn = pte_pfn(range->pte);
1608 
1609 	if (!kvm->arch.mmu.pgt)
1610 		return false;
1611 
1612 	WARN_ON(range->end - range->start != 1);
1613 
1614 	/*
1615 	 * If the page isn't tagged, defer to user_mem_abort() for sanitising
1616 	 * the MTE tags. The S2 pte should have been unmapped by
1617 	 * mmu_notifier_invalidate_range_end().
1618 	 */
1619 	if (kvm_has_mte(kvm) && !page_mte_tagged(pfn_to_page(pfn)))
1620 		return false;
1621 
1622 	/*
1623 	 * We've moved a page around, probably through CoW, so let's treat
1624 	 * it just like a translation fault and the map handler will clean
1625 	 * the cache to the PoC.
1626 	 *
1627 	 * The MMU notifiers will have unmapped a huge PMD before calling
1628 	 * ->change_pte() (which in turn calls kvm_set_spte_gfn()) and
1629 	 * therefore we never need to clear out a huge PMD through this
1630 	 * calling path and a memcache is not required.
1631 	 */
1632 	kvm_pgtable_stage2_map(kvm->arch.mmu.pgt, range->start << PAGE_SHIFT,
1633 			       PAGE_SIZE, __pfn_to_phys(pfn),
1634 			       KVM_PGTABLE_PROT_R, NULL, 0);
1635 
1636 	return false;
1637 }
1638 
1639 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1640 {
1641 	u64 size = (range->end - range->start) << PAGE_SHIFT;
1642 	kvm_pte_t kpte;
1643 	pte_t pte;
1644 
1645 	if (!kvm->arch.mmu.pgt)
1646 		return false;
1647 
1648 	WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
1649 
1650 	kpte = kvm_pgtable_stage2_mkold(kvm->arch.mmu.pgt,
1651 					range->start << PAGE_SHIFT);
1652 	pte = __pte(kpte);
1653 	return pte_valid(pte) && pte_young(pte);
1654 }
1655 
1656 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1657 {
1658 	if (!kvm->arch.mmu.pgt)
1659 		return false;
1660 
1661 	return kvm_pgtable_stage2_is_young(kvm->arch.mmu.pgt,
1662 					   range->start << PAGE_SHIFT);
1663 }
1664 
1665 phys_addr_t kvm_mmu_get_httbr(void)
1666 {
1667 	return __pa(hyp_pgtable->pgd);
1668 }
1669 
1670 phys_addr_t kvm_get_idmap_vector(void)
1671 {
1672 	return hyp_idmap_vector;
1673 }
1674 
1675 static int kvm_map_idmap_text(void)
1676 {
1677 	unsigned long size = hyp_idmap_end - hyp_idmap_start;
1678 	int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
1679 					PAGE_HYP_EXEC);
1680 	if (err)
1681 		kvm_err("Failed to idmap %lx-%lx\n",
1682 			hyp_idmap_start, hyp_idmap_end);
1683 
1684 	return err;
1685 }
1686 
1687 static void *kvm_hyp_zalloc_page(void *arg)
1688 {
1689 	return (void *)get_zeroed_page(GFP_KERNEL);
1690 }
1691 
1692 static struct kvm_pgtable_mm_ops kvm_hyp_mm_ops = {
1693 	.zalloc_page		= kvm_hyp_zalloc_page,
1694 	.get_page		= kvm_host_get_page,
1695 	.put_page		= kvm_host_put_page,
1696 	.phys_to_virt		= kvm_host_va,
1697 	.virt_to_phys		= kvm_host_pa,
1698 };
1699 
1700 int __init kvm_mmu_init(u32 *hyp_va_bits)
1701 {
1702 	int err;
1703 	u32 idmap_bits;
1704 	u32 kernel_bits;
1705 
1706 	hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
1707 	hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
1708 	hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
1709 	hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
1710 	hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
1711 
1712 	/*
1713 	 * We rely on the linker script to ensure at build time that the HYP
1714 	 * init code does not cross a page boundary.
1715 	 */
1716 	BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
1717 
1718 	/*
1719 	 * The ID map may be configured to use an extended virtual address
1720 	 * range. This is only the case if system RAM is out of range for the
1721 	 * currently configured page size and VA_BITS_MIN, in which case we will
1722 	 * also need the extended virtual range for the HYP ID map, or we won't
1723 	 * be able to enable the EL2 MMU.
1724 	 *
1725 	 * However, in some cases the ID map may be configured for fewer than
1726 	 * the number of VA bits used by the regular kernel stage 1. This
1727 	 * happens when VA_BITS=52 and the kernel image is placed in PA space
1728 	 * below 48 bits.
1729 	 *
1730 	 * At EL2, there is only one TTBR register, and we can't switch between
1731 	 * translation tables *and* update TCR_EL2.T0SZ at the same time. Bottom
1732 	 * line: we need to use the extended range with *both* our translation
1733 	 * tables.
1734 	 *
1735 	 * So use the maximum of the idmap VA bits and the regular kernel stage
1736 	 * 1 VA bits to assure that the hypervisor can both ID map its code page
1737 	 * and map any kernel memory.
1738 	 */
1739 	idmap_bits = 64 - ((idmap_t0sz & TCR_T0SZ_MASK) >> TCR_T0SZ_OFFSET);
1740 	kernel_bits = vabits_actual;
1741 	*hyp_va_bits = max(idmap_bits, kernel_bits);
1742 
1743 	kvm_debug("Using %u-bit virtual addresses at EL2\n", *hyp_va_bits);
1744 	kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
1745 	kvm_debug("HYP VA range: %lx:%lx\n",
1746 		  kern_hyp_va(PAGE_OFFSET),
1747 		  kern_hyp_va((unsigned long)high_memory - 1));
1748 
1749 	if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
1750 	    hyp_idmap_start <  kern_hyp_va((unsigned long)high_memory - 1) &&
1751 	    hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
1752 		/*
1753 		 * The idmap page is intersecting with the VA space,
1754 		 * it is not safe to continue further.
1755 		 */
1756 		kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
1757 		err = -EINVAL;
1758 		goto out;
1759 	}
1760 
1761 	hyp_pgtable = kzalloc(sizeof(*hyp_pgtable), GFP_KERNEL);
1762 	if (!hyp_pgtable) {
1763 		kvm_err("Hyp mode page-table not allocated\n");
1764 		err = -ENOMEM;
1765 		goto out;
1766 	}
1767 
1768 	err = kvm_pgtable_hyp_init(hyp_pgtable, *hyp_va_bits, &kvm_hyp_mm_ops);
1769 	if (err)
1770 		goto out_free_pgtable;
1771 
1772 	err = kvm_map_idmap_text();
1773 	if (err)
1774 		goto out_destroy_pgtable;
1775 
1776 	io_map_base = hyp_idmap_start;
1777 	return 0;
1778 
1779 out_destroy_pgtable:
1780 	kvm_pgtable_hyp_destroy(hyp_pgtable);
1781 out_free_pgtable:
1782 	kfree(hyp_pgtable);
1783 	hyp_pgtable = NULL;
1784 out:
1785 	return err;
1786 }
1787 
1788 void kvm_arch_commit_memory_region(struct kvm *kvm,
1789 				   struct kvm_memory_slot *old,
1790 				   const struct kvm_memory_slot *new,
1791 				   enum kvm_mr_change change)
1792 {
1793 	/*
1794 	 * At this point memslot has been committed and there is an
1795 	 * allocated dirty_bitmap[], dirty pages will be tracked while the
1796 	 * memory slot is write protected.
1797 	 */
1798 	if (change != KVM_MR_DELETE && new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1799 		/*
1800 		 * If we're with initial-all-set, we don't need to write
1801 		 * protect any pages because they're all reported as dirty.
1802 		 * Huge pages and normal pages will be write protect gradually.
1803 		 */
1804 		if (!kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1805 			kvm_mmu_wp_memory_region(kvm, new->id);
1806 		}
1807 	}
1808 }
1809 
1810 int kvm_arch_prepare_memory_region(struct kvm *kvm,
1811 				   const struct kvm_memory_slot *old,
1812 				   struct kvm_memory_slot *new,
1813 				   enum kvm_mr_change change)
1814 {
1815 	hva_t hva, reg_end;
1816 	int ret = 0;
1817 
1818 	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
1819 			change != KVM_MR_FLAGS_ONLY)
1820 		return 0;
1821 
1822 	/*
1823 	 * Prevent userspace from creating a memory region outside of the IPA
1824 	 * space addressable by the KVM guest IPA space.
1825 	 */
1826 	if ((new->base_gfn + new->npages) > (kvm_phys_size(kvm) >> PAGE_SHIFT))
1827 		return -EFAULT;
1828 
1829 	hva = new->userspace_addr;
1830 	reg_end = hva + (new->npages << PAGE_SHIFT);
1831 
1832 	mmap_read_lock(current->mm);
1833 	/*
1834 	 * A memory region could potentially cover multiple VMAs, and any holes
1835 	 * between them, so iterate over all of them.
1836 	 *
1837 	 *     +--------------------------------------------+
1838 	 * +---------------+----------------+   +----------------+
1839 	 * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
1840 	 * +---------------+----------------+   +----------------+
1841 	 *     |               memory region                |
1842 	 *     +--------------------------------------------+
1843 	 */
1844 	do {
1845 		struct vm_area_struct *vma;
1846 
1847 		vma = find_vma_intersection(current->mm, hva, reg_end);
1848 		if (!vma)
1849 			break;
1850 
1851 		if (kvm_has_mte(kvm) && !kvm_vma_mte_allowed(vma)) {
1852 			ret = -EINVAL;
1853 			break;
1854 		}
1855 
1856 		if (vma->vm_flags & VM_PFNMAP) {
1857 			/* IO region dirty page logging not allowed */
1858 			if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1859 				ret = -EINVAL;
1860 				break;
1861 			}
1862 		}
1863 		hva = min(reg_end, vma->vm_end);
1864 	} while (hva < reg_end);
1865 
1866 	mmap_read_unlock(current->mm);
1867 	return ret;
1868 }
1869 
1870 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
1871 {
1872 }
1873 
1874 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
1875 {
1876 }
1877 
1878 void kvm_arch_flush_shadow_all(struct kvm *kvm)
1879 {
1880 	kvm_free_stage2_pgd(&kvm->arch.mmu);
1881 }
1882 
1883 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
1884 				   struct kvm_memory_slot *slot)
1885 {
1886 	gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
1887 	phys_addr_t size = slot->npages << PAGE_SHIFT;
1888 
1889 	write_lock(&kvm->mmu_lock);
1890 	unmap_stage2_range(&kvm->arch.mmu, gpa, size);
1891 	write_unlock(&kvm->mmu_lock);
1892 }
1893 
1894 /*
1895  * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
1896  *
1897  * Main problems:
1898  * - S/W ops are local to a CPU (not broadcast)
1899  * - We have line migration behind our back (speculation)
1900  * - System caches don't support S/W at all (damn!)
1901  *
1902  * In the face of the above, the best we can do is to try and convert
1903  * S/W ops to VA ops. Because the guest is not allowed to infer the
1904  * S/W to PA mapping, it can only use S/W to nuke the whole cache,
1905  * which is a rather good thing for us.
1906  *
1907  * Also, it is only used when turning caches on/off ("The expected
1908  * usage of the cache maintenance instructions that operate by set/way
1909  * is associated with the cache maintenance instructions associated
1910  * with the powerdown and powerup of caches, if this is required by
1911  * the implementation.").
1912  *
1913  * We use the following policy:
1914  *
1915  * - If we trap a S/W operation, we enable VM trapping to detect
1916  *   caches being turned on/off, and do a full clean.
1917  *
1918  * - We flush the caches on both caches being turned on and off.
1919  *
1920  * - Once the caches are enabled, we stop trapping VM ops.
1921  */
1922 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
1923 {
1924 	unsigned long hcr = *vcpu_hcr(vcpu);
1925 
1926 	/*
1927 	 * If this is the first time we do a S/W operation
1928 	 * (i.e. HCR_TVM not set) flush the whole memory, and set the
1929 	 * VM trapping.
1930 	 *
1931 	 * Otherwise, rely on the VM trapping to wait for the MMU +
1932 	 * Caches to be turned off. At that point, we'll be able to
1933 	 * clean the caches again.
1934 	 */
1935 	if (!(hcr & HCR_TVM)) {
1936 		trace_kvm_set_way_flush(*vcpu_pc(vcpu),
1937 					vcpu_has_cache_enabled(vcpu));
1938 		stage2_flush_vm(vcpu->kvm);
1939 		*vcpu_hcr(vcpu) = hcr | HCR_TVM;
1940 	}
1941 }
1942 
1943 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
1944 {
1945 	bool now_enabled = vcpu_has_cache_enabled(vcpu);
1946 
1947 	/*
1948 	 * If switching the MMU+caches on, need to invalidate the caches.
1949 	 * If switching it off, need to clean the caches.
1950 	 * Clean + invalidate does the trick always.
1951 	 */
1952 	if (now_enabled != was_enabled)
1953 		stage2_flush_vm(vcpu->kvm);
1954 
1955 	/* Caches are now on, stop trapping VM ops (until a S/W op) */
1956 	if (now_enabled)
1957 		*vcpu_hcr(vcpu) &= ~HCR_TVM;
1958 
1959 	trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
1960 }
1961