xref: /linux/arch/arm64/kvm/mmu.c (revision 572af9f284669d31d9175122bbef9bc62cea8ded)
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 					   phys_addr_t size)
36 {
37 	phys_addr_t boundary = ALIGN_DOWN(addr + size, size);
38 
39 	return (boundary - 1 < end - 1) ? boundary : end;
40 }
41 
42 static phys_addr_t stage2_range_addr_end(phys_addr_t addr, phys_addr_t end)
43 {
44 	phys_addr_t size = kvm_granule_size(KVM_PGTABLE_MIN_BLOCK_LEVEL);
45 
46 	return __stage2_range_addr_end(addr, end, size);
47 }
48 
49 /*
50  * Release kvm_mmu_lock periodically if the memory region is large. Otherwise,
51  * we may see kernel panics with CONFIG_DETECT_HUNG_TASK,
52  * CONFIG_LOCKUP_DETECTOR, CONFIG_LOCKDEP. Additionally, holding the lock too
53  * long will also starve other vCPUs. We have to also make sure that the page
54  * tables are not freed while we released the lock.
55  */
56 static int stage2_apply_range(struct kvm_s2_mmu *mmu, phys_addr_t addr,
57 			      phys_addr_t end,
58 			      int (*fn)(struct kvm_pgtable *, u64, u64),
59 			      bool resched)
60 {
61 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
62 	int ret;
63 	u64 next;
64 
65 	do {
66 		struct kvm_pgtable *pgt = mmu->pgt;
67 		if (!pgt)
68 			return -EINVAL;
69 
70 		next = stage2_range_addr_end(addr, end);
71 		ret = fn(pgt, addr, next - addr);
72 		if (ret)
73 			break;
74 
75 		if (resched && next != end)
76 			cond_resched_rwlock_write(&kvm->mmu_lock);
77 	} while (addr = next, addr != end);
78 
79 	return ret;
80 }
81 
82 #define stage2_apply_range_resched(mmu, addr, end, fn)			\
83 	stage2_apply_range(mmu, addr, end, fn, true)
84 
85 /*
86  * Get the maximum number of page-tables pages needed to split a range
87  * of blocks into PAGE_SIZE PTEs. It assumes the range is already
88  * mapped at level 2, or at level 1 if allowed.
89  */
90 static int kvm_mmu_split_nr_page_tables(u64 range)
91 {
92 	int n = 0;
93 
94 	if (KVM_PGTABLE_MIN_BLOCK_LEVEL < 2)
95 		n += DIV_ROUND_UP(range, PUD_SIZE);
96 	n += DIV_ROUND_UP(range, PMD_SIZE);
97 	return n;
98 }
99 
100 static bool need_split_memcache_topup_or_resched(struct kvm *kvm)
101 {
102 	struct kvm_mmu_memory_cache *cache;
103 	u64 chunk_size, min;
104 
105 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
106 		return true;
107 
108 	chunk_size = kvm->arch.mmu.split_page_chunk_size;
109 	min = kvm_mmu_split_nr_page_tables(chunk_size);
110 	cache = &kvm->arch.mmu.split_page_cache;
111 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
112 }
113 
114 static int kvm_mmu_split_huge_pages(struct kvm *kvm, phys_addr_t addr,
115 				    phys_addr_t end)
116 {
117 	struct kvm_mmu_memory_cache *cache;
118 	struct kvm_pgtable *pgt;
119 	int ret, cache_capacity;
120 	u64 next, chunk_size;
121 
122 	lockdep_assert_held_write(&kvm->mmu_lock);
123 
124 	chunk_size = kvm->arch.mmu.split_page_chunk_size;
125 	cache_capacity = kvm_mmu_split_nr_page_tables(chunk_size);
126 
127 	if (chunk_size == 0)
128 		return 0;
129 
130 	cache = &kvm->arch.mmu.split_page_cache;
131 
132 	do {
133 		if (need_split_memcache_topup_or_resched(kvm)) {
134 			write_unlock(&kvm->mmu_lock);
135 			cond_resched();
136 			/* Eager page splitting is best-effort. */
137 			ret = __kvm_mmu_topup_memory_cache(cache,
138 							   cache_capacity,
139 							   cache_capacity);
140 			write_lock(&kvm->mmu_lock);
141 			if (ret)
142 				break;
143 		}
144 
145 		pgt = kvm->arch.mmu.pgt;
146 		if (!pgt)
147 			return -EINVAL;
148 
149 		next = __stage2_range_addr_end(addr, end, chunk_size);
150 		ret = kvm_pgtable_stage2_split(pgt, addr, next - addr, cache);
151 		if (ret)
152 			break;
153 	} while (addr = next, addr != end);
154 
155 	return ret;
156 }
157 
158 static bool memslot_is_logging(struct kvm_memory_slot *memslot)
159 {
160 	return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY);
161 }
162 
163 /**
164  * kvm_arch_flush_remote_tlbs() - flush all VM TLB entries for v7/8
165  * @kvm:	pointer to kvm structure.
166  *
167  * Interface to HYP function to flush all VM TLB entries
168  */
169 int kvm_arch_flush_remote_tlbs(struct kvm *kvm)
170 {
171 	kvm_call_hyp(__kvm_tlb_flush_vmid, &kvm->arch.mmu);
172 	return 0;
173 }
174 
175 int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm,
176 				      gfn_t gfn, u64 nr_pages)
177 {
178 	kvm_tlb_flush_vmid_range(&kvm->arch.mmu,
179 				gfn << PAGE_SHIFT, nr_pages << PAGE_SHIFT);
180 	return 0;
181 }
182 
183 static bool kvm_is_device_pfn(unsigned long pfn)
184 {
185 	return !pfn_is_map_memory(pfn);
186 }
187 
188 static void *stage2_memcache_zalloc_page(void *arg)
189 {
190 	struct kvm_mmu_memory_cache *mc = arg;
191 	void *virt;
192 
193 	/* Allocated with __GFP_ZERO, so no need to zero */
194 	virt = kvm_mmu_memory_cache_alloc(mc);
195 	if (virt)
196 		kvm_account_pgtable_pages(virt, 1);
197 	return virt;
198 }
199 
200 static void *kvm_host_zalloc_pages_exact(size_t size)
201 {
202 	return alloc_pages_exact(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
203 }
204 
205 static void *kvm_s2_zalloc_pages_exact(size_t size)
206 {
207 	void *virt = kvm_host_zalloc_pages_exact(size);
208 
209 	if (virt)
210 		kvm_account_pgtable_pages(virt, (size >> PAGE_SHIFT));
211 	return virt;
212 }
213 
214 static void kvm_s2_free_pages_exact(void *virt, size_t size)
215 {
216 	kvm_account_pgtable_pages(virt, -(size >> PAGE_SHIFT));
217 	free_pages_exact(virt, size);
218 }
219 
220 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops;
221 
222 static void stage2_free_unlinked_table_rcu_cb(struct rcu_head *head)
223 {
224 	struct page *page = container_of(head, struct page, rcu_head);
225 	void *pgtable = page_to_virt(page);
226 	s8 level = page_private(page);
227 
228 	kvm_pgtable_stage2_free_unlinked(&kvm_s2_mm_ops, pgtable, level);
229 }
230 
231 static void stage2_free_unlinked_table(void *addr, s8 level)
232 {
233 	struct page *page = virt_to_page(addr);
234 
235 	set_page_private(page, (unsigned long)level);
236 	call_rcu(&page->rcu_head, stage2_free_unlinked_table_rcu_cb);
237 }
238 
239 static void kvm_host_get_page(void *addr)
240 {
241 	get_page(virt_to_page(addr));
242 }
243 
244 static void kvm_host_put_page(void *addr)
245 {
246 	put_page(virt_to_page(addr));
247 }
248 
249 static void kvm_s2_put_page(void *addr)
250 {
251 	struct page *p = virt_to_page(addr);
252 	/* Dropping last refcount, the page will be freed */
253 	if (page_count(p) == 1)
254 		kvm_account_pgtable_pages(addr, -1);
255 	put_page(p);
256 }
257 
258 static int kvm_host_page_count(void *addr)
259 {
260 	return page_count(virt_to_page(addr));
261 }
262 
263 static phys_addr_t kvm_host_pa(void *addr)
264 {
265 	return __pa(addr);
266 }
267 
268 static void *kvm_host_va(phys_addr_t phys)
269 {
270 	return __va(phys);
271 }
272 
273 static void clean_dcache_guest_page(void *va, size_t size)
274 {
275 	__clean_dcache_guest_page(va, size);
276 }
277 
278 static void invalidate_icache_guest_page(void *va, size_t size)
279 {
280 	__invalidate_icache_guest_page(va, size);
281 }
282 
283 /*
284  * Unmapping vs dcache management:
285  *
286  * If a guest maps certain memory pages as uncached, all writes will
287  * bypass the data cache and go directly to RAM.  However, the CPUs
288  * can still speculate reads (not writes) and fill cache lines with
289  * data.
290  *
291  * Those cache lines will be *clean* cache lines though, so a
292  * clean+invalidate operation is equivalent to an invalidate
293  * operation, because no cache lines are marked dirty.
294  *
295  * Those clean cache lines could be filled prior to an uncached write
296  * by the guest, and the cache coherent IO subsystem would therefore
297  * end up writing old data to disk.
298  *
299  * This is why right after unmapping a page/section and invalidating
300  * the corresponding TLBs, we flush to make sure the IO subsystem will
301  * never hit in the cache.
302  *
303  * This is all avoided on systems that have ARM64_HAS_STAGE2_FWB, as
304  * we then fully enforce cacheability of RAM, no matter what the guest
305  * does.
306  */
307 /**
308  * __unmap_stage2_range -- Clear stage2 page table entries to unmap a range
309  * @mmu:   The KVM stage-2 MMU pointer
310  * @start: The intermediate physical base address of the range to unmap
311  * @size:  The size of the area to unmap
312  * @may_block: Whether or not we are permitted to block
313  *
314  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
315  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
316  * destroying the VM), otherwise another faulting VCPU may come in and mess
317  * with things behind our backs.
318  */
319 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
320 				 bool may_block)
321 {
322 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
323 	phys_addr_t end = start + size;
324 
325 	lockdep_assert_held_write(&kvm->mmu_lock);
326 	WARN_ON(size & ~PAGE_MASK);
327 	WARN_ON(stage2_apply_range(mmu, start, end, kvm_pgtable_stage2_unmap,
328 				   may_block));
329 }
330 
331 void kvm_stage2_unmap_range(struct kvm_s2_mmu *mmu, phys_addr_t start,
332 			    u64 size, bool may_block)
333 {
334 	__unmap_stage2_range(mmu, start, size, may_block);
335 }
336 
337 void kvm_stage2_flush_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
338 {
339 	stage2_apply_range_resched(mmu, addr, end, kvm_pgtable_stage2_flush);
340 }
341 
342 static void stage2_flush_memslot(struct kvm *kvm,
343 				 struct kvm_memory_slot *memslot)
344 {
345 	phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
346 	phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
347 
348 	kvm_stage2_flush_range(&kvm->arch.mmu, addr, end);
349 }
350 
351 /**
352  * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
353  * @kvm: The struct kvm pointer
354  *
355  * Go through the stage 2 page tables and invalidate any cache lines
356  * backing memory already mapped to the VM.
357  */
358 static void stage2_flush_vm(struct kvm *kvm)
359 {
360 	struct kvm_memslots *slots;
361 	struct kvm_memory_slot *memslot;
362 	int idx, bkt;
363 
364 	idx = srcu_read_lock(&kvm->srcu);
365 	write_lock(&kvm->mmu_lock);
366 
367 	slots = kvm_memslots(kvm);
368 	kvm_for_each_memslot(memslot, bkt, slots)
369 		stage2_flush_memslot(kvm, memslot);
370 
371 	kvm_nested_s2_flush(kvm);
372 
373 	write_unlock(&kvm->mmu_lock);
374 	srcu_read_unlock(&kvm->srcu, idx);
375 }
376 
377 /**
378  * free_hyp_pgds - free Hyp-mode page tables
379  */
380 void __init free_hyp_pgds(void)
381 {
382 	mutex_lock(&kvm_hyp_pgd_mutex);
383 	if (hyp_pgtable) {
384 		kvm_pgtable_hyp_destroy(hyp_pgtable);
385 		kfree(hyp_pgtable);
386 		hyp_pgtable = NULL;
387 	}
388 	mutex_unlock(&kvm_hyp_pgd_mutex);
389 }
390 
391 static bool kvm_host_owns_hyp_mappings(void)
392 {
393 	if (is_kernel_in_hyp_mode())
394 		return false;
395 
396 	if (static_branch_likely(&kvm_protected_mode_initialized))
397 		return false;
398 
399 	/*
400 	 * This can happen at boot time when __create_hyp_mappings() is called
401 	 * after the hyp protection has been enabled, but the static key has
402 	 * not been flipped yet.
403 	 */
404 	if (!hyp_pgtable && is_protected_kvm_enabled())
405 		return false;
406 
407 	WARN_ON(!hyp_pgtable);
408 
409 	return true;
410 }
411 
412 int __create_hyp_mappings(unsigned long start, unsigned long size,
413 			  unsigned long phys, enum kvm_pgtable_prot prot)
414 {
415 	int err;
416 
417 	if (WARN_ON(!kvm_host_owns_hyp_mappings()))
418 		return -EINVAL;
419 
420 	mutex_lock(&kvm_hyp_pgd_mutex);
421 	err = kvm_pgtable_hyp_map(hyp_pgtable, start, size, phys, prot);
422 	mutex_unlock(&kvm_hyp_pgd_mutex);
423 
424 	return err;
425 }
426 
427 static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
428 {
429 	if (!is_vmalloc_addr(kaddr)) {
430 		BUG_ON(!virt_addr_valid(kaddr));
431 		return __pa(kaddr);
432 	} else {
433 		return page_to_phys(vmalloc_to_page(kaddr)) +
434 		       offset_in_page(kaddr);
435 	}
436 }
437 
438 struct hyp_shared_pfn {
439 	u64 pfn;
440 	int count;
441 	struct rb_node node;
442 };
443 
444 static DEFINE_MUTEX(hyp_shared_pfns_lock);
445 static struct rb_root hyp_shared_pfns = RB_ROOT;
446 
447 static struct hyp_shared_pfn *find_shared_pfn(u64 pfn, struct rb_node ***node,
448 					      struct rb_node **parent)
449 {
450 	struct hyp_shared_pfn *this;
451 
452 	*node = &hyp_shared_pfns.rb_node;
453 	*parent = NULL;
454 	while (**node) {
455 		this = container_of(**node, struct hyp_shared_pfn, node);
456 		*parent = **node;
457 		if (this->pfn < pfn)
458 			*node = &((**node)->rb_left);
459 		else if (this->pfn > pfn)
460 			*node = &((**node)->rb_right);
461 		else
462 			return this;
463 	}
464 
465 	return NULL;
466 }
467 
468 static int share_pfn_hyp(u64 pfn)
469 {
470 	struct rb_node **node, *parent;
471 	struct hyp_shared_pfn *this;
472 	int ret = 0;
473 
474 	mutex_lock(&hyp_shared_pfns_lock);
475 	this = find_shared_pfn(pfn, &node, &parent);
476 	if (this) {
477 		this->count++;
478 		goto unlock;
479 	}
480 
481 	this = kzalloc(sizeof(*this), GFP_KERNEL);
482 	if (!this) {
483 		ret = -ENOMEM;
484 		goto unlock;
485 	}
486 
487 	this->pfn = pfn;
488 	this->count = 1;
489 	rb_link_node(&this->node, parent, node);
490 	rb_insert_color(&this->node, &hyp_shared_pfns);
491 	ret = kvm_call_hyp_nvhe(__pkvm_host_share_hyp, pfn, 1);
492 unlock:
493 	mutex_unlock(&hyp_shared_pfns_lock);
494 
495 	return ret;
496 }
497 
498 static int unshare_pfn_hyp(u64 pfn)
499 {
500 	struct rb_node **node, *parent;
501 	struct hyp_shared_pfn *this;
502 	int ret = 0;
503 
504 	mutex_lock(&hyp_shared_pfns_lock);
505 	this = find_shared_pfn(pfn, &node, &parent);
506 	if (WARN_ON(!this)) {
507 		ret = -ENOENT;
508 		goto unlock;
509 	}
510 
511 	this->count--;
512 	if (this->count)
513 		goto unlock;
514 
515 	rb_erase(&this->node, &hyp_shared_pfns);
516 	kfree(this);
517 	ret = kvm_call_hyp_nvhe(__pkvm_host_unshare_hyp, pfn, 1);
518 unlock:
519 	mutex_unlock(&hyp_shared_pfns_lock);
520 
521 	return ret;
522 }
523 
524 int kvm_share_hyp(void *from, void *to)
525 {
526 	phys_addr_t start, end, cur;
527 	u64 pfn;
528 	int ret;
529 
530 	if (is_kernel_in_hyp_mode())
531 		return 0;
532 
533 	/*
534 	 * The share hcall maps things in the 'fixed-offset' region of the hyp
535 	 * VA space, so we can only share physically contiguous data-structures
536 	 * for now.
537 	 */
538 	if (is_vmalloc_or_module_addr(from) || is_vmalloc_or_module_addr(to))
539 		return -EINVAL;
540 
541 	if (kvm_host_owns_hyp_mappings())
542 		return create_hyp_mappings(from, to, PAGE_HYP);
543 
544 	start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
545 	end = PAGE_ALIGN(__pa(to));
546 	for (cur = start; cur < end; cur += PAGE_SIZE) {
547 		pfn = __phys_to_pfn(cur);
548 		ret = share_pfn_hyp(pfn);
549 		if (ret)
550 			return ret;
551 	}
552 
553 	return 0;
554 }
555 
556 void kvm_unshare_hyp(void *from, void *to)
557 {
558 	phys_addr_t start, end, cur;
559 	u64 pfn;
560 
561 	if (is_kernel_in_hyp_mode() || kvm_host_owns_hyp_mappings() || !from)
562 		return;
563 
564 	start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
565 	end = PAGE_ALIGN(__pa(to));
566 	for (cur = start; cur < end; cur += PAGE_SIZE) {
567 		pfn = __phys_to_pfn(cur);
568 		WARN_ON(unshare_pfn_hyp(pfn));
569 	}
570 }
571 
572 /**
573  * create_hyp_mappings - duplicate a kernel virtual address range in Hyp mode
574  * @from:	The virtual kernel start address of the range
575  * @to:		The virtual kernel end address of the range (exclusive)
576  * @prot:	The protection to be applied to this range
577  *
578  * The same virtual address as the kernel virtual address is also used
579  * in Hyp-mode mapping (modulo HYP_PAGE_OFFSET) to the same underlying
580  * physical pages.
581  */
582 int create_hyp_mappings(void *from, void *to, enum kvm_pgtable_prot prot)
583 {
584 	phys_addr_t phys_addr;
585 	unsigned long virt_addr;
586 	unsigned long start = kern_hyp_va((unsigned long)from);
587 	unsigned long end = kern_hyp_va((unsigned long)to);
588 
589 	if (is_kernel_in_hyp_mode())
590 		return 0;
591 
592 	if (!kvm_host_owns_hyp_mappings())
593 		return -EPERM;
594 
595 	start = start & PAGE_MASK;
596 	end = PAGE_ALIGN(end);
597 
598 	for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
599 		int err;
600 
601 		phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
602 		err = __create_hyp_mappings(virt_addr, PAGE_SIZE, phys_addr,
603 					    prot);
604 		if (err)
605 			return err;
606 	}
607 
608 	return 0;
609 }
610 
611 static int __hyp_alloc_private_va_range(unsigned long base)
612 {
613 	lockdep_assert_held(&kvm_hyp_pgd_mutex);
614 
615 	if (!PAGE_ALIGNED(base))
616 		return -EINVAL;
617 
618 	/*
619 	 * Verify that BIT(VA_BITS - 1) hasn't been flipped by
620 	 * allocating the new area, as it would indicate we've
621 	 * overflowed the idmap/IO address range.
622 	 */
623 	if ((base ^ io_map_base) & BIT(VA_BITS - 1))
624 		return -ENOMEM;
625 
626 	io_map_base = base;
627 
628 	return 0;
629 }
630 
631 /**
632  * hyp_alloc_private_va_range - Allocates a private VA range.
633  * @size:	The size of the VA range to reserve.
634  * @haddr:	The hypervisor virtual start address of the allocation.
635  *
636  * The private virtual address (VA) range is allocated below io_map_base
637  * and aligned based on the order of @size.
638  *
639  * Return: 0 on success or negative error code on failure.
640  */
641 int hyp_alloc_private_va_range(size_t size, unsigned long *haddr)
642 {
643 	unsigned long base;
644 	int ret = 0;
645 
646 	mutex_lock(&kvm_hyp_pgd_mutex);
647 
648 	/*
649 	 * This assumes that we have enough space below the idmap
650 	 * page to allocate our VAs. If not, the check in
651 	 * __hyp_alloc_private_va_range() will kick. A potential
652 	 * alternative would be to detect that overflow and switch
653 	 * to an allocation above the idmap.
654 	 *
655 	 * The allocated size is always a multiple of PAGE_SIZE.
656 	 */
657 	size = PAGE_ALIGN(size);
658 	base = io_map_base - size;
659 	ret = __hyp_alloc_private_va_range(base);
660 
661 	mutex_unlock(&kvm_hyp_pgd_mutex);
662 
663 	if (!ret)
664 		*haddr = base;
665 
666 	return ret;
667 }
668 
669 static int __create_hyp_private_mapping(phys_addr_t phys_addr, size_t size,
670 					unsigned long *haddr,
671 					enum kvm_pgtable_prot prot)
672 {
673 	unsigned long addr;
674 	int ret = 0;
675 
676 	if (!kvm_host_owns_hyp_mappings()) {
677 		addr = kvm_call_hyp_nvhe(__pkvm_create_private_mapping,
678 					 phys_addr, size, prot);
679 		if (IS_ERR_VALUE(addr))
680 			return addr;
681 		*haddr = addr;
682 
683 		return 0;
684 	}
685 
686 	size = PAGE_ALIGN(size + offset_in_page(phys_addr));
687 	ret = hyp_alloc_private_va_range(size, &addr);
688 	if (ret)
689 		return ret;
690 
691 	ret = __create_hyp_mappings(addr, size, phys_addr, prot);
692 	if (ret)
693 		return ret;
694 
695 	*haddr = addr + offset_in_page(phys_addr);
696 	return ret;
697 }
698 
699 int create_hyp_stack(phys_addr_t phys_addr, unsigned long *haddr)
700 {
701 	unsigned long base;
702 	size_t size;
703 	int ret;
704 
705 	mutex_lock(&kvm_hyp_pgd_mutex);
706 	/*
707 	 * Efficient stack verification using the PAGE_SHIFT bit implies
708 	 * an alignment of our allocation on the order of the size.
709 	 */
710 	size = PAGE_SIZE * 2;
711 	base = ALIGN_DOWN(io_map_base - size, size);
712 
713 	ret = __hyp_alloc_private_va_range(base);
714 
715 	mutex_unlock(&kvm_hyp_pgd_mutex);
716 
717 	if (ret) {
718 		kvm_err("Cannot allocate hyp stack guard page\n");
719 		return ret;
720 	}
721 
722 	/*
723 	 * Since the stack grows downwards, map the stack to the page
724 	 * at the higher address and leave the lower guard page
725 	 * unbacked.
726 	 *
727 	 * Any valid stack address now has the PAGE_SHIFT bit as 1
728 	 * and addresses corresponding to the guard page have the
729 	 * PAGE_SHIFT bit as 0 - this is used for overflow detection.
730 	 */
731 	ret = __create_hyp_mappings(base + PAGE_SIZE, PAGE_SIZE, phys_addr,
732 				    PAGE_HYP);
733 	if (ret)
734 		kvm_err("Cannot map hyp stack\n");
735 
736 	*haddr = base + size;
737 
738 	return ret;
739 }
740 
741 /**
742  * create_hyp_io_mappings - Map IO into both kernel and HYP
743  * @phys_addr:	The physical start address which gets mapped
744  * @size:	Size of the region being mapped
745  * @kaddr:	Kernel VA for this mapping
746  * @haddr:	HYP VA for this mapping
747  */
748 int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size,
749 			   void __iomem **kaddr,
750 			   void __iomem **haddr)
751 {
752 	unsigned long addr;
753 	int ret;
754 
755 	if (is_protected_kvm_enabled())
756 		return -EPERM;
757 
758 	*kaddr = ioremap(phys_addr, size);
759 	if (!*kaddr)
760 		return -ENOMEM;
761 
762 	if (is_kernel_in_hyp_mode()) {
763 		*haddr = *kaddr;
764 		return 0;
765 	}
766 
767 	ret = __create_hyp_private_mapping(phys_addr, size,
768 					   &addr, PAGE_HYP_DEVICE);
769 	if (ret) {
770 		iounmap(*kaddr);
771 		*kaddr = NULL;
772 		*haddr = NULL;
773 		return ret;
774 	}
775 
776 	*haddr = (void __iomem *)addr;
777 	return 0;
778 }
779 
780 /**
781  * create_hyp_exec_mappings - Map an executable range into HYP
782  * @phys_addr:	The physical start address which gets mapped
783  * @size:	Size of the region being mapped
784  * @haddr:	HYP VA for this mapping
785  */
786 int create_hyp_exec_mappings(phys_addr_t phys_addr, size_t size,
787 			     void **haddr)
788 {
789 	unsigned long addr;
790 	int ret;
791 
792 	BUG_ON(is_kernel_in_hyp_mode());
793 
794 	ret = __create_hyp_private_mapping(phys_addr, size,
795 					   &addr, PAGE_HYP_EXEC);
796 	if (ret) {
797 		*haddr = NULL;
798 		return ret;
799 	}
800 
801 	*haddr = (void *)addr;
802 	return 0;
803 }
804 
805 static struct kvm_pgtable_mm_ops kvm_user_mm_ops = {
806 	/* We shouldn't need any other callback to walk the PT */
807 	.phys_to_virt		= kvm_host_va,
808 };
809 
810 static int get_user_mapping_size(struct kvm *kvm, u64 addr)
811 {
812 	struct kvm_pgtable pgt = {
813 		.pgd		= (kvm_pteref_t)kvm->mm->pgd,
814 		.ia_bits	= vabits_actual,
815 		.start_level	= (KVM_PGTABLE_LAST_LEVEL -
816 				   ARM64_HW_PGTABLE_LEVELS(pgt.ia_bits) + 1),
817 		.mm_ops		= &kvm_user_mm_ops,
818 	};
819 	unsigned long flags;
820 	kvm_pte_t pte = 0;	/* Keep GCC quiet... */
821 	s8 level = S8_MAX;
822 	int ret;
823 
824 	/*
825 	 * Disable IRQs so that we hazard against a concurrent
826 	 * teardown of the userspace page tables (which relies on
827 	 * IPI-ing threads).
828 	 */
829 	local_irq_save(flags);
830 	ret = kvm_pgtable_get_leaf(&pgt, addr, &pte, &level);
831 	local_irq_restore(flags);
832 
833 	if (ret)
834 		return ret;
835 
836 	/*
837 	 * Not seeing an error, but not updating level? Something went
838 	 * deeply wrong...
839 	 */
840 	if (WARN_ON(level > KVM_PGTABLE_LAST_LEVEL))
841 		return -EFAULT;
842 	if (WARN_ON(level < KVM_PGTABLE_FIRST_LEVEL))
843 		return -EFAULT;
844 
845 	/* Oops, the userspace PTs are gone... Replay the fault */
846 	if (!kvm_pte_valid(pte))
847 		return -EAGAIN;
848 
849 	return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(level));
850 }
851 
852 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
853 	.zalloc_page		= stage2_memcache_zalloc_page,
854 	.zalloc_pages_exact	= kvm_s2_zalloc_pages_exact,
855 	.free_pages_exact	= kvm_s2_free_pages_exact,
856 	.free_unlinked_table	= stage2_free_unlinked_table,
857 	.get_page		= kvm_host_get_page,
858 	.put_page		= kvm_s2_put_page,
859 	.page_count		= kvm_host_page_count,
860 	.phys_to_virt		= kvm_host_va,
861 	.virt_to_phys		= kvm_host_pa,
862 	.dcache_clean_inval_poc	= clean_dcache_guest_page,
863 	.icache_inval_pou	= invalidate_icache_guest_page,
864 };
865 
866 static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
867 {
868 	u32 kvm_ipa_limit = get_kvm_ipa_limit();
869 	u64 mmfr0, mmfr1;
870 	u32 phys_shift;
871 
872 	if (type & ~KVM_VM_TYPE_ARM_IPA_SIZE_MASK)
873 		return -EINVAL;
874 
875 	phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
876 	if (is_protected_kvm_enabled()) {
877 		phys_shift = kvm_ipa_limit;
878 	} else if (phys_shift) {
879 		if (phys_shift > kvm_ipa_limit ||
880 		    phys_shift < ARM64_MIN_PARANGE_BITS)
881 			return -EINVAL;
882 	} else {
883 		phys_shift = KVM_PHYS_SHIFT;
884 		if (phys_shift > kvm_ipa_limit) {
885 			pr_warn_once("%s using unsupported default IPA limit, upgrade your VMM\n",
886 				     current->comm);
887 			return -EINVAL;
888 		}
889 	}
890 
891 	mmfr0 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
892 	mmfr1 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
893 	mmu->vtcr = kvm_get_vtcr(mmfr0, mmfr1, phys_shift);
894 
895 	return 0;
896 }
897 
898 /**
899  * kvm_init_stage2_mmu - Initialise a S2 MMU structure
900  * @kvm:	The pointer to the KVM structure
901  * @mmu:	The pointer to the s2 MMU structure
902  * @type:	The machine type of the virtual machine
903  *
904  * Allocates only the stage-2 HW PGD level table(s).
905  * Note we don't need locking here as this is only called in two cases:
906  *
907  * - when the VM is created, which can't race against anything
908  *
909  * - when secondary kvm_s2_mmu structures are initialised for NV
910  *   guests, and the caller must hold kvm->lock as this is called on a
911  *   per-vcpu basis.
912  */
913 int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long type)
914 {
915 	int cpu, err;
916 	struct kvm_pgtable *pgt;
917 
918 	/*
919 	 * If we already have our page tables in place, and that the
920 	 * MMU context is the canonical one, we have a bug somewhere,
921 	 * as this is only supposed to ever happen once per VM.
922 	 *
923 	 * Otherwise, we're building nested page tables, and that's
924 	 * probably because userspace called KVM_ARM_VCPU_INIT more
925 	 * than once on the same vcpu. Since that's actually legal,
926 	 * don't kick a fuss and leave gracefully.
927 	 */
928 	if (mmu->pgt != NULL) {
929 		if (kvm_is_nested_s2_mmu(kvm, mmu))
930 			return 0;
931 
932 		kvm_err("kvm_arch already initialized?\n");
933 		return -EINVAL;
934 	}
935 
936 	err = kvm_init_ipa_range(mmu, type);
937 	if (err)
938 		return err;
939 
940 	pgt = kzalloc(sizeof(*pgt), GFP_KERNEL_ACCOUNT);
941 	if (!pgt)
942 		return -ENOMEM;
943 
944 	mmu->arch = &kvm->arch;
945 	err = kvm_pgtable_stage2_init(pgt, mmu, &kvm_s2_mm_ops);
946 	if (err)
947 		goto out_free_pgtable;
948 
949 	mmu->last_vcpu_ran = alloc_percpu(typeof(*mmu->last_vcpu_ran));
950 	if (!mmu->last_vcpu_ran) {
951 		err = -ENOMEM;
952 		goto out_destroy_pgtable;
953 	}
954 
955 	for_each_possible_cpu(cpu)
956 		*per_cpu_ptr(mmu->last_vcpu_ran, cpu) = -1;
957 
958 	 /* The eager page splitting is disabled by default */
959 	mmu->split_page_chunk_size = KVM_ARM_EAGER_SPLIT_CHUNK_SIZE_DEFAULT;
960 	mmu->split_page_cache.gfp_zero = __GFP_ZERO;
961 
962 	mmu->pgt = pgt;
963 	mmu->pgd_phys = __pa(pgt->pgd);
964 
965 	if (kvm_is_nested_s2_mmu(kvm, mmu))
966 		kvm_init_nested_s2_mmu(mmu);
967 
968 	return 0;
969 
970 out_destroy_pgtable:
971 	kvm_pgtable_stage2_destroy(pgt);
972 out_free_pgtable:
973 	kfree(pgt);
974 	return err;
975 }
976 
977 void kvm_uninit_stage2_mmu(struct kvm *kvm)
978 {
979 	kvm_free_stage2_pgd(&kvm->arch.mmu);
980 	kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
981 }
982 
983 static void stage2_unmap_memslot(struct kvm *kvm,
984 				 struct kvm_memory_slot *memslot)
985 {
986 	hva_t hva = memslot->userspace_addr;
987 	phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
988 	phys_addr_t size = PAGE_SIZE * memslot->npages;
989 	hva_t reg_end = hva + size;
990 
991 	/*
992 	 * A memory region could potentially cover multiple VMAs, and any holes
993 	 * between them, so iterate over all of them to find out if we should
994 	 * unmap any of them.
995 	 *
996 	 *     +--------------------------------------------+
997 	 * +---------------+----------------+   +----------------+
998 	 * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
999 	 * +---------------+----------------+   +----------------+
1000 	 *     |               memory region                |
1001 	 *     +--------------------------------------------+
1002 	 */
1003 	do {
1004 		struct vm_area_struct *vma;
1005 		hva_t vm_start, vm_end;
1006 
1007 		vma = find_vma_intersection(current->mm, hva, reg_end);
1008 		if (!vma)
1009 			break;
1010 
1011 		/*
1012 		 * Take the intersection of this VMA with the memory region
1013 		 */
1014 		vm_start = max(hva, vma->vm_start);
1015 		vm_end = min(reg_end, vma->vm_end);
1016 
1017 		if (!(vma->vm_flags & VM_PFNMAP)) {
1018 			gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
1019 			kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, vm_end - vm_start, true);
1020 		}
1021 		hva = vm_end;
1022 	} while (hva < reg_end);
1023 }
1024 
1025 /**
1026  * stage2_unmap_vm - Unmap Stage-2 RAM mappings
1027  * @kvm: The struct kvm pointer
1028  *
1029  * Go through the memregions and unmap any regular RAM
1030  * backing memory already mapped to the VM.
1031  */
1032 void stage2_unmap_vm(struct kvm *kvm)
1033 {
1034 	struct kvm_memslots *slots;
1035 	struct kvm_memory_slot *memslot;
1036 	int idx, bkt;
1037 
1038 	idx = srcu_read_lock(&kvm->srcu);
1039 	mmap_read_lock(current->mm);
1040 	write_lock(&kvm->mmu_lock);
1041 
1042 	slots = kvm_memslots(kvm);
1043 	kvm_for_each_memslot(memslot, bkt, slots)
1044 		stage2_unmap_memslot(kvm, memslot);
1045 
1046 	kvm_nested_s2_unmap(kvm, true);
1047 
1048 	write_unlock(&kvm->mmu_lock);
1049 	mmap_read_unlock(current->mm);
1050 	srcu_read_unlock(&kvm->srcu, idx);
1051 }
1052 
1053 void kvm_free_stage2_pgd(struct kvm_s2_mmu *mmu)
1054 {
1055 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
1056 	struct kvm_pgtable *pgt = NULL;
1057 
1058 	write_lock(&kvm->mmu_lock);
1059 	pgt = mmu->pgt;
1060 	if (pgt) {
1061 		mmu->pgd_phys = 0;
1062 		mmu->pgt = NULL;
1063 		free_percpu(mmu->last_vcpu_ran);
1064 	}
1065 	write_unlock(&kvm->mmu_lock);
1066 
1067 	if (pgt) {
1068 		kvm_pgtable_stage2_destroy(pgt);
1069 		kfree(pgt);
1070 	}
1071 }
1072 
1073 static void hyp_mc_free_fn(void *addr, void *unused)
1074 {
1075 	free_page((unsigned long)addr);
1076 }
1077 
1078 static void *hyp_mc_alloc_fn(void *unused)
1079 {
1080 	return (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1081 }
1082 
1083 void free_hyp_memcache(struct kvm_hyp_memcache *mc)
1084 {
1085 	if (is_protected_kvm_enabled())
1086 		__free_hyp_memcache(mc, hyp_mc_free_fn,
1087 				    kvm_host_va, NULL);
1088 }
1089 
1090 int topup_hyp_memcache(struct kvm_hyp_memcache *mc, unsigned long min_pages)
1091 {
1092 	if (!is_protected_kvm_enabled())
1093 		return 0;
1094 
1095 	return __topup_hyp_memcache(mc, min_pages, hyp_mc_alloc_fn,
1096 				    kvm_host_pa, NULL);
1097 }
1098 
1099 /**
1100  * kvm_phys_addr_ioremap - map a device range to guest IPA
1101  *
1102  * @kvm:	The KVM pointer
1103  * @guest_ipa:	The IPA at which to insert the mapping
1104  * @pa:		The physical address of the device
1105  * @size:	The size of the mapping
1106  * @writable:   Whether or not to create a writable mapping
1107  */
1108 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
1109 			  phys_addr_t pa, unsigned long size, bool writable)
1110 {
1111 	phys_addr_t addr;
1112 	int ret = 0;
1113 	struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };
1114 	struct kvm_s2_mmu *mmu = &kvm->arch.mmu;
1115 	struct kvm_pgtable *pgt = mmu->pgt;
1116 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_DEVICE |
1117 				     KVM_PGTABLE_PROT_R |
1118 				     (writable ? KVM_PGTABLE_PROT_W : 0);
1119 
1120 	if (is_protected_kvm_enabled())
1121 		return -EPERM;
1122 
1123 	size += offset_in_page(guest_ipa);
1124 	guest_ipa &= PAGE_MASK;
1125 
1126 	for (addr = guest_ipa; addr < guest_ipa + size; addr += PAGE_SIZE) {
1127 		ret = kvm_mmu_topup_memory_cache(&cache,
1128 						 kvm_mmu_cache_min_pages(mmu));
1129 		if (ret)
1130 			break;
1131 
1132 		write_lock(&kvm->mmu_lock);
1133 		ret = kvm_pgtable_stage2_map(pgt, addr, PAGE_SIZE, pa, prot,
1134 					     &cache, 0);
1135 		write_unlock(&kvm->mmu_lock);
1136 		if (ret)
1137 			break;
1138 
1139 		pa += PAGE_SIZE;
1140 	}
1141 
1142 	kvm_mmu_free_memory_cache(&cache);
1143 	return ret;
1144 }
1145 
1146 /**
1147  * kvm_stage2_wp_range() - write protect stage2 memory region range
1148  * @mmu:        The KVM stage-2 MMU pointer
1149  * @addr:	Start address of range
1150  * @end:	End address of range
1151  */
1152 void kvm_stage2_wp_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
1153 {
1154 	stage2_apply_range_resched(mmu, addr, end, kvm_pgtable_stage2_wrprotect);
1155 }
1156 
1157 /**
1158  * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
1159  * @kvm:	The KVM pointer
1160  * @slot:	The memory slot to write protect
1161  *
1162  * Called to start logging dirty pages after memory region
1163  * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
1164  * all present PUD, PMD and PTEs are write protected in the memory region.
1165  * Afterwards read of dirty page log can be called.
1166  *
1167  * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
1168  * serializing operations for VM memory regions.
1169  */
1170 static void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
1171 {
1172 	struct kvm_memslots *slots = kvm_memslots(kvm);
1173 	struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
1174 	phys_addr_t start, end;
1175 
1176 	if (WARN_ON_ONCE(!memslot))
1177 		return;
1178 
1179 	start = memslot->base_gfn << PAGE_SHIFT;
1180 	end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
1181 
1182 	write_lock(&kvm->mmu_lock);
1183 	kvm_stage2_wp_range(&kvm->arch.mmu, start, end);
1184 	kvm_nested_s2_wp(kvm);
1185 	write_unlock(&kvm->mmu_lock);
1186 	kvm_flush_remote_tlbs_memslot(kvm, memslot);
1187 }
1188 
1189 /**
1190  * kvm_mmu_split_memory_region() - split the stage 2 blocks into PAGE_SIZE
1191  *				   pages for memory slot
1192  * @kvm:	The KVM pointer
1193  * @slot:	The memory slot to split
1194  *
1195  * Acquires kvm->mmu_lock. Called with kvm->slots_lock mutex acquired,
1196  * serializing operations for VM memory regions.
1197  */
1198 static void kvm_mmu_split_memory_region(struct kvm *kvm, int slot)
1199 {
1200 	struct kvm_memslots *slots;
1201 	struct kvm_memory_slot *memslot;
1202 	phys_addr_t start, end;
1203 
1204 	lockdep_assert_held(&kvm->slots_lock);
1205 
1206 	slots = kvm_memslots(kvm);
1207 	memslot = id_to_memslot(slots, slot);
1208 
1209 	start = memslot->base_gfn << PAGE_SHIFT;
1210 	end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
1211 
1212 	write_lock(&kvm->mmu_lock);
1213 	kvm_mmu_split_huge_pages(kvm, start, end);
1214 	write_unlock(&kvm->mmu_lock);
1215 }
1216 
1217 /*
1218  * kvm_arch_mmu_enable_log_dirty_pt_masked() - enable dirty logging for selected pages.
1219  * @kvm:	The KVM pointer
1220  * @slot:	The memory slot associated with mask
1221  * @gfn_offset:	The gfn offset in memory slot
1222  * @mask:	The mask of pages at offset 'gfn_offset' in this memory
1223  *		slot to enable dirty logging on
1224  *
1225  * Writes protect selected pages to enable dirty logging, and then
1226  * splits them to PAGE_SIZE. Caller must acquire kvm->mmu_lock.
1227  */
1228 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1229 		struct kvm_memory_slot *slot,
1230 		gfn_t gfn_offset, unsigned long mask)
1231 {
1232 	phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
1233 	phys_addr_t start = (base_gfn +  __ffs(mask)) << PAGE_SHIFT;
1234 	phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
1235 
1236 	lockdep_assert_held_write(&kvm->mmu_lock);
1237 
1238 	kvm_stage2_wp_range(&kvm->arch.mmu, start, end);
1239 
1240 	/*
1241 	 * Eager-splitting is done when manual-protect is set.  We
1242 	 * also check for initially-all-set because we can avoid
1243 	 * eager-splitting if initially-all-set is false.
1244 	 * Initially-all-set equal false implies that huge-pages were
1245 	 * already split when enabling dirty logging: no need to do it
1246 	 * again.
1247 	 */
1248 	if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1249 		kvm_mmu_split_huge_pages(kvm, start, end);
1250 
1251 	kvm_nested_s2_wp(kvm);
1252 }
1253 
1254 static void kvm_send_hwpoison_signal(unsigned long address, short lsb)
1255 {
1256 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, current);
1257 }
1258 
1259 static bool fault_supports_stage2_huge_mapping(struct kvm_memory_slot *memslot,
1260 					       unsigned long hva,
1261 					       unsigned long map_size)
1262 {
1263 	gpa_t gpa_start;
1264 	hva_t uaddr_start, uaddr_end;
1265 	size_t size;
1266 
1267 	/* The memslot and the VMA are guaranteed to be aligned to PAGE_SIZE */
1268 	if (map_size == PAGE_SIZE)
1269 		return true;
1270 
1271 	size = memslot->npages * PAGE_SIZE;
1272 
1273 	gpa_start = memslot->base_gfn << PAGE_SHIFT;
1274 
1275 	uaddr_start = memslot->userspace_addr;
1276 	uaddr_end = uaddr_start + size;
1277 
1278 	/*
1279 	 * Pages belonging to memslots that don't have the same alignment
1280 	 * within a PMD/PUD for userspace and IPA cannot be mapped with stage-2
1281 	 * PMD/PUD entries, because we'll end up mapping the wrong pages.
1282 	 *
1283 	 * Consider a layout like the following:
1284 	 *
1285 	 *    memslot->userspace_addr:
1286 	 *    +-----+--------------------+--------------------+---+
1287 	 *    |abcde|fgh  Stage-1 block  |    Stage-1 block tv|xyz|
1288 	 *    +-----+--------------------+--------------------+---+
1289 	 *
1290 	 *    memslot->base_gfn << PAGE_SHIFT:
1291 	 *      +---+--------------------+--------------------+-----+
1292 	 *      |abc|def  Stage-2 block  |    Stage-2 block   |tvxyz|
1293 	 *      +---+--------------------+--------------------+-----+
1294 	 *
1295 	 * If we create those stage-2 blocks, we'll end up with this incorrect
1296 	 * mapping:
1297 	 *   d -> f
1298 	 *   e -> g
1299 	 *   f -> h
1300 	 */
1301 	if ((gpa_start & (map_size - 1)) != (uaddr_start & (map_size - 1)))
1302 		return false;
1303 
1304 	/*
1305 	 * Next, let's make sure we're not trying to map anything not covered
1306 	 * by the memslot. This means we have to prohibit block size mappings
1307 	 * for the beginning and end of a non-block aligned and non-block sized
1308 	 * memory slot (illustrated by the head and tail parts of the
1309 	 * userspace view above containing pages 'abcde' and 'xyz',
1310 	 * respectively).
1311 	 *
1312 	 * Note that it doesn't matter if we do the check using the
1313 	 * userspace_addr or the base_gfn, as both are equally aligned (per
1314 	 * the check above) and equally sized.
1315 	 */
1316 	return (hva & ~(map_size - 1)) >= uaddr_start &&
1317 	       (hva & ~(map_size - 1)) + map_size <= uaddr_end;
1318 }
1319 
1320 /*
1321  * Check if the given hva is backed by a transparent huge page (THP) and
1322  * whether it can be mapped using block mapping in stage2. If so, adjust
1323  * the stage2 PFN and IPA accordingly. Only PMD_SIZE THPs are currently
1324  * supported. This will need to be updated to support other THP sizes.
1325  *
1326  * Returns the size of the mapping.
1327  */
1328 static long
1329 transparent_hugepage_adjust(struct kvm *kvm, struct kvm_memory_slot *memslot,
1330 			    unsigned long hva, kvm_pfn_t *pfnp,
1331 			    phys_addr_t *ipap)
1332 {
1333 	kvm_pfn_t pfn = *pfnp;
1334 
1335 	/*
1336 	 * Make sure the adjustment is done only for THP pages. Also make
1337 	 * sure that the HVA and IPA are sufficiently aligned and that the
1338 	 * block map is contained within the memslot.
1339 	 */
1340 	if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE)) {
1341 		int sz = get_user_mapping_size(kvm, hva);
1342 
1343 		if (sz < 0)
1344 			return sz;
1345 
1346 		if (sz < PMD_SIZE)
1347 			return PAGE_SIZE;
1348 
1349 		*ipap &= PMD_MASK;
1350 		pfn &= ~(PTRS_PER_PMD - 1);
1351 		*pfnp = pfn;
1352 
1353 		return PMD_SIZE;
1354 	}
1355 
1356 	/* Use page mapping if we cannot use block mapping. */
1357 	return PAGE_SIZE;
1358 }
1359 
1360 static int get_vma_page_shift(struct vm_area_struct *vma, unsigned long hva)
1361 {
1362 	unsigned long pa;
1363 
1364 	if (is_vm_hugetlb_page(vma) && !(vma->vm_flags & VM_PFNMAP))
1365 		return huge_page_shift(hstate_vma(vma));
1366 
1367 	if (!(vma->vm_flags & VM_PFNMAP))
1368 		return PAGE_SHIFT;
1369 
1370 	VM_BUG_ON(is_vm_hugetlb_page(vma));
1371 
1372 	pa = (vma->vm_pgoff << PAGE_SHIFT) + (hva - vma->vm_start);
1373 
1374 #ifndef __PAGETABLE_PMD_FOLDED
1375 	if ((hva & (PUD_SIZE - 1)) == (pa & (PUD_SIZE - 1)) &&
1376 	    ALIGN_DOWN(hva, PUD_SIZE) >= vma->vm_start &&
1377 	    ALIGN(hva, PUD_SIZE) <= vma->vm_end)
1378 		return PUD_SHIFT;
1379 #endif
1380 
1381 	if ((hva & (PMD_SIZE - 1)) == (pa & (PMD_SIZE - 1)) &&
1382 	    ALIGN_DOWN(hva, PMD_SIZE) >= vma->vm_start &&
1383 	    ALIGN(hva, PMD_SIZE) <= vma->vm_end)
1384 		return PMD_SHIFT;
1385 
1386 	return PAGE_SHIFT;
1387 }
1388 
1389 /*
1390  * The page will be mapped in stage 2 as Normal Cacheable, so the VM will be
1391  * able to see the page's tags and therefore they must be initialised first. If
1392  * PG_mte_tagged is set, tags have already been initialised.
1393  *
1394  * The race in the test/set of the PG_mte_tagged flag is handled by:
1395  * - preventing VM_SHARED mappings in a memslot with MTE preventing two VMs
1396  *   racing to santise the same page
1397  * - mmap_lock protects between a VM faulting a page in and the VMM performing
1398  *   an mprotect() to add VM_MTE
1399  */
1400 static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn,
1401 			      unsigned long size)
1402 {
1403 	unsigned long i, nr_pages = size >> PAGE_SHIFT;
1404 	struct page *page = pfn_to_page(pfn);
1405 	struct folio *folio = page_folio(page);
1406 
1407 	if (!kvm_has_mte(kvm))
1408 		return;
1409 
1410 	if (folio_test_hugetlb(folio)) {
1411 		/* Hugetlb has MTE flags set on head page only */
1412 		if (folio_try_hugetlb_mte_tagging(folio)) {
1413 			for (i = 0; i < nr_pages; i++, page++)
1414 				mte_clear_page_tags(page_address(page));
1415 			folio_set_hugetlb_mte_tagged(folio);
1416 		}
1417 		return;
1418 	}
1419 
1420 	for (i = 0; i < nr_pages; i++, page++) {
1421 		if (try_page_mte_tagging(page)) {
1422 			mte_clear_page_tags(page_address(page));
1423 			set_page_mte_tagged(page);
1424 		}
1425 	}
1426 }
1427 
1428 static bool kvm_vma_mte_allowed(struct vm_area_struct *vma)
1429 {
1430 	return vma->vm_flags & VM_MTE_ALLOWED;
1431 }
1432 
1433 static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1434 			  struct kvm_s2_trans *nested,
1435 			  struct kvm_memory_slot *memslot, unsigned long hva,
1436 			  bool fault_is_perm)
1437 {
1438 	int ret = 0;
1439 	bool write_fault, writable, force_pte = false;
1440 	bool exec_fault, mte_allowed;
1441 	bool device = false, vfio_allow_any_uc = false;
1442 	unsigned long mmu_seq;
1443 	phys_addr_t ipa = fault_ipa;
1444 	struct kvm *kvm = vcpu->kvm;
1445 	struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
1446 	struct vm_area_struct *vma;
1447 	short vma_shift;
1448 	gfn_t gfn;
1449 	kvm_pfn_t pfn;
1450 	bool logging_active = memslot_is_logging(memslot);
1451 	long vma_pagesize, fault_granule;
1452 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
1453 	struct kvm_pgtable *pgt;
1454 	struct page *page;
1455 
1456 	if (fault_is_perm)
1457 		fault_granule = kvm_vcpu_trap_get_perm_fault_granule(vcpu);
1458 	write_fault = kvm_is_write_fault(vcpu);
1459 	exec_fault = kvm_vcpu_trap_is_exec_fault(vcpu);
1460 	VM_BUG_ON(write_fault && exec_fault);
1461 
1462 	if (fault_is_perm && !write_fault && !exec_fault) {
1463 		kvm_err("Unexpected L2 read permission error\n");
1464 		return -EFAULT;
1465 	}
1466 
1467 	/*
1468 	 * Permission faults just need to update the existing leaf entry,
1469 	 * and so normally don't require allocations from the memcache. The
1470 	 * only exception to this is when dirty logging is enabled at runtime
1471 	 * and a write fault needs to collapse a block entry into a table.
1472 	 */
1473 	if (!fault_is_perm || (logging_active && write_fault)) {
1474 		ret = kvm_mmu_topup_memory_cache(memcache,
1475 						 kvm_mmu_cache_min_pages(vcpu->arch.hw_mmu));
1476 		if (ret)
1477 			return ret;
1478 	}
1479 
1480 	/*
1481 	 * Let's check if we will get back a huge page backed by hugetlbfs, or
1482 	 * get block mapping for device MMIO region.
1483 	 */
1484 	mmap_read_lock(current->mm);
1485 	vma = vma_lookup(current->mm, hva);
1486 	if (unlikely(!vma)) {
1487 		kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
1488 		mmap_read_unlock(current->mm);
1489 		return -EFAULT;
1490 	}
1491 
1492 	/*
1493 	 * logging_active is guaranteed to never be true for VM_PFNMAP
1494 	 * memslots.
1495 	 */
1496 	if (logging_active) {
1497 		force_pte = true;
1498 		vma_shift = PAGE_SHIFT;
1499 	} else {
1500 		vma_shift = get_vma_page_shift(vma, hva);
1501 	}
1502 
1503 	switch (vma_shift) {
1504 #ifndef __PAGETABLE_PMD_FOLDED
1505 	case PUD_SHIFT:
1506 		if (fault_supports_stage2_huge_mapping(memslot, hva, PUD_SIZE))
1507 			break;
1508 		fallthrough;
1509 #endif
1510 	case CONT_PMD_SHIFT:
1511 		vma_shift = PMD_SHIFT;
1512 		fallthrough;
1513 	case PMD_SHIFT:
1514 		if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE))
1515 			break;
1516 		fallthrough;
1517 	case CONT_PTE_SHIFT:
1518 		vma_shift = PAGE_SHIFT;
1519 		force_pte = true;
1520 		fallthrough;
1521 	case PAGE_SHIFT:
1522 		break;
1523 	default:
1524 		WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
1525 	}
1526 
1527 	vma_pagesize = 1UL << vma_shift;
1528 
1529 	if (nested) {
1530 		unsigned long max_map_size;
1531 
1532 		max_map_size = force_pte ? PAGE_SIZE : PUD_SIZE;
1533 
1534 		ipa = kvm_s2_trans_output(nested);
1535 
1536 		/*
1537 		 * If we're about to create a shadow stage 2 entry, then we
1538 		 * can only create a block mapping if the guest stage 2 page
1539 		 * table uses at least as big a mapping.
1540 		 */
1541 		max_map_size = min(kvm_s2_trans_size(nested), max_map_size);
1542 
1543 		/*
1544 		 * Be careful that if the mapping size falls between
1545 		 * two host sizes, take the smallest of the two.
1546 		 */
1547 		if (max_map_size >= PMD_SIZE && max_map_size < PUD_SIZE)
1548 			max_map_size = PMD_SIZE;
1549 		else if (max_map_size >= PAGE_SIZE && max_map_size < PMD_SIZE)
1550 			max_map_size = PAGE_SIZE;
1551 
1552 		force_pte = (max_map_size == PAGE_SIZE);
1553 		vma_pagesize = min(vma_pagesize, (long)max_map_size);
1554 	}
1555 
1556 	/*
1557 	 * Both the canonical IPA and fault IPA must be hugepage-aligned to
1558 	 * ensure we find the right PFN and lay down the mapping in the right
1559 	 * place.
1560 	 */
1561 	if (vma_pagesize == PMD_SIZE || vma_pagesize == PUD_SIZE) {
1562 		fault_ipa &= ~(vma_pagesize - 1);
1563 		ipa &= ~(vma_pagesize - 1);
1564 	}
1565 
1566 	gfn = ipa >> PAGE_SHIFT;
1567 	mte_allowed = kvm_vma_mte_allowed(vma);
1568 
1569 	vfio_allow_any_uc = vma->vm_flags & VM_ALLOW_ANY_UNCACHED;
1570 
1571 	/* Don't use the VMA after the unlock -- it may have vanished */
1572 	vma = NULL;
1573 
1574 	/*
1575 	 * Read mmu_invalidate_seq so that KVM can detect if the results of
1576 	 * vma_lookup() or __kvm_faultin_pfn() become stale prior to
1577 	 * acquiring kvm->mmu_lock.
1578 	 *
1579 	 * Rely on mmap_read_unlock() for an implicit smp_rmb(), which pairs
1580 	 * with the smp_wmb() in kvm_mmu_invalidate_end().
1581 	 */
1582 	mmu_seq = vcpu->kvm->mmu_invalidate_seq;
1583 	mmap_read_unlock(current->mm);
1584 
1585 	pfn = __kvm_faultin_pfn(memslot, gfn, write_fault ? FOLL_WRITE : 0,
1586 				&writable, &page);
1587 	if (pfn == KVM_PFN_ERR_HWPOISON) {
1588 		kvm_send_hwpoison_signal(hva, vma_shift);
1589 		return 0;
1590 	}
1591 	if (is_error_noslot_pfn(pfn))
1592 		return -EFAULT;
1593 
1594 	if (kvm_is_device_pfn(pfn)) {
1595 		/*
1596 		 * If the page was identified as device early by looking at
1597 		 * the VMA flags, vma_pagesize is already representing the
1598 		 * largest quantity we can map.  If instead it was mapped
1599 		 * via __kvm_faultin_pfn(), vma_pagesize is set to PAGE_SIZE
1600 		 * and must not be upgraded.
1601 		 *
1602 		 * In both cases, we don't let transparent_hugepage_adjust()
1603 		 * change things at the last minute.
1604 		 */
1605 		device = true;
1606 	} else if (logging_active && !write_fault) {
1607 		/*
1608 		 * Only actually map the page as writable if this was a write
1609 		 * fault.
1610 		 */
1611 		writable = false;
1612 	}
1613 
1614 	if (exec_fault && device)
1615 		return -ENOEXEC;
1616 
1617 	/*
1618 	 * Potentially reduce shadow S2 permissions to match the guest's own
1619 	 * S2. For exec faults, we'd only reach this point if the guest
1620 	 * actually allowed it (see kvm_s2_handle_perm_fault).
1621 	 *
1622 	 * Also encode the level of the original translation in the SW bits
1623 	 * of the leaf entry as a proxy for the span of that translation.
1624 	 * This will be retrieved on TLB invalidation from the guest and
1625 	 * used to limit the invalidation scope if a TTL hint or a range
1626 	 * isn't provided.
1627 	 */
1628 	if (nested) {
1629 		writable &= kvm_s2_trans_writable(nested);
1630 		if (!kvm_s2_trans_readable(nested))
1631 			prot &= ~KVM_PGTABLE_PROT_R;
1632 
1633 		prot |= kvm_encode_nested_level(nested);
1634 	}
1635 
1636 	read_lock(&kvm->mmu_lock);
1637 	pgt = vcpu->arch.hw_mmu->pgt;
1638 	if (mmu_invalidate_retry(kvm, mmu_seq)) {
1639 		ret = -EAGAIN;
1640 		goto out_unlock;
1641 	}
1642 
1643 	/*
1644 	 * If we are not forced to use page mapping, check if we are
1645 	 * backed by a THP and thus use block mapping if possible.
1646 	 */
1647 	if (vma_pagesize == PAGE_SIZE && !(force_pte || device)) {
1648 		if (fault_is_perm && fault_granule > PAGE_SIZE)
1649 			vma_pagesize = fault_granule;
1650 		else
1651 			vma_pagesize = transparent_hugepage_adjust(kvm, memslot,
1652 								   hva, &pfn,
1653 								   &fault_ipa);
1654 
1655 		if (vma_pagesize < 0) {
1656 			ret = vma_pagesize;
1657 			goto out_unlock;
1658 		}
1659 	}
1660 
1661 	if (!fault_is_perm && !device && kvm_has_mte(kvm)) {
1662 		/* Check the VMM hasn't introduced a new disallowed VMA */
1663 		if (mte_allowed) {
1664 			sanitise_mte_tags(kvm, pfn, vma_pagesize);
1665 		} else {
1666 			ret = -EFAULT;
1667 			goto out_unlock;
1668 		}
1669 	}
1670 
1671 	if (writable)
1672 		prot |= KVM_PGTABLE_PROT_W;
1673 
1674 	if (exec_fault)
1675 		prot |= KVM_PGTABLE_PROT_X;
1676 
1677 	if (device) {
1678 		if (vfio_allow_any_uc)
1679 			prot |= KVM_PGTABLE_PROT_NORMAL_NC;
1680 		else
1681 			prot |= KVM_PGTABLE_PROT_DEVICE;
1682 	} else if (cpus_have_final_cap(ARM64_HAS_CACHE_DIC) &&
1683 		   (!nested || kvm_s2_trans_executable(nested))) {
1684 		prot |= KVM_PGTABLE_PROT_X;
1685 	}
1686 
1687 	/*
1688 	 * Under the premise of getting a FSC_PERM fault, we just need to relax
1689 	 * permissions only if vma_pagesize equals fault_granule. Otherwise,
1690 	 * kvm_pgtable_stage2_map() should be called to change block size.
1691 	 */
1692 	if (fault_is_perm && vma_pagesize == fault_granule) {
1693 		/*
1694 		 * Drop the SW bits in favour of those stored in the
1695 		 * PTE, which will be preserved.
1696 		 */
1697 		prot &= ~KVM_NV_GUEST_MAP_SZ;
1698 		ret = kvm_pgtable_stage2_relax_perms(pgt, fault_ipa, prot);
1699 	} else {
1700 		ret = kvm_pgtable_stage2_map(pgt, fault_ipa, vma_pagesize,
1701 					     __pfn_to_phys(pfn), prot,
1702 					     memcache,
1703 					     KVM_PGTABLE_WALK_HANDLE_FAULT |
1704 					     KVM_PGTABLE_WALK_SHARED);
1705 	}
1706 
1707 out_unlock:
1708 	kvm_release_faultin_page(kvm, page, !!ret, writable);
1709 	read_unlock(&kvm->mmu_lock);
1710 
1711 	/* Mark the page dirty only if the fault is handled successfully */
1712 	if (writable && !ret)
1713 		mark_page_dirty_in_slot(kvm, memslot, gfn);
1714 
1715 	return ret != -EAGAIN ? ret : 0;
1716 }
1717 
1718 /* Resolve the access fault by making the page young again. */
1719 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
1720 {
1721 	struct kvm_s2_mmu *mmu;
1722 
1723 	trace_kvm_access_fault(fault_ipa);
1724 
1725 	read_lock(&vcpu->kvm->mmu_lock);
1726 	mmu = vcpu->arch.hw_mmu;
1727 	kvm_pgtable_stage2_mkyoung(mmu->pgt, fault_ipa);
1728 	read_unlock(&vcpu->kvm->mmu_lock);
1729 }
1730 
1731 /**
1732  * kvm_handle_guest_abort - handles all 2nd stage aborts
1733  * @vcpu:	the VCPU pointer
1734  *
1735  * Any abort that gets to the host is almost guaranteed to be caused by a
1736  * missing second stage translation table entry, which can mean that either the
1737  * guest simply needs more memory and we must allocate an appropriate page or it
1738  * can mean that the guest tried to access I/O memory, which is emulated by user
1739  * space. The distinction is based on the IPA causing the fault and whether this
1740  * memory region has been registered as standard RAM by user space.
1741  */
1742 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
1743 {
1744 	struct kvm_s2_trans nested_trans, *nested = NULL;
1745 	unsigned long esr;
1746 	phys_addr_t fault_ipa; /* The address we faulted on */
1747 	phys_addr_t ipa; /* Always the IPA in the L1 guest phys space */
1748 	struct kvm_memory_slot *memslot;
1749 	unsigned long hva;
1750 	bool is_iabt, write_fault, writable;
1751 	gfn_t gfn;
1752 	int ret, idx;
1753 
1754 	esr = kvm_vcpu_get_esr(vcpu);
1755 
1756 	ipa = fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
1757 	is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
1758 
1759 	if (esr_fsc_is_translation_fault(esr)) {
1760 		/* Beyond sanitised PARange (which is the IPA limit) */
1761 		if (fault_ipa >= BIT_ULL(get_kvm_ipa_limit())) {
1762 			kvm_inject_size_fault(vcpu);
1763 			return 1;
1764 		}
1765 
1766 		/* Falls between the IPA range and the PARange? */
1767 		if (fault_ipa >= BIT_ULL(vcpu->arch.hw_mmu->pgt->ia_bits)) {
1768 			fault_ipa |= kvm_vcpu_get_hfar(vcpu) & GENMASK(11, 0);
1769 
1770 			if (is_iabt)
1771 				kvm_inject_pabt(vcpu, fault_ipa);
1772 			else
1773 				kvm_inject_dabt(vcpu, fault_ipa);
1774 			return 1;
1775 		}
1776 	}
1777 
1778 	/* Synchronous External Abort? */
1779 	if (kvm_vcpu_abt_issea(vcpu)) {
1780 		/*
1781 		 * For RAS the host kernel may handle this abort.
1782 		 * There is no need to pass the error into the guest.
1783 		 */
1784 		if (kvm_handle_guest_sea(fault_ipa, kvm_vcpu_get_esr(vcpu)))
1785 			kvm_inject_vabt(vcpu);
1786 
1787 		return 1;
1788 	}
1789 
1790 	trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_esr(vcpu),
1791 			      kvm_vcpu_get_hfar(vcpu), fault_ipa);
1792 
1793 	/* Check the stage-2 fault is trans. fault or write fault */
1794 	if (!esr_fsc_is_translation_fault(esr) &&
1795 	    !esr_fsc_is_permission_fault(esr) &&
1796 	    !esr_fsc_is_access_flag_fault(esr)) {
1797 		kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
1798 			kvm_vcpu_trap_get_class(vcpu),
1799 			(unsigned long)kvm_vcpu_trap_get_fault(vcpu),
1800 			(unsigned long)kvm_vcpu_get_esr(vcpu));
1801 		return -EFAULT;
1802 	}
1803 
1804 	idx = srcu_read_lock(&vcpu->kvm->srcu);
1805 
1806 	/*
1807 	 * We may have faulted on a shadow stage 2 page table if we are
1808 	 * running a nested guest.  In this case, we have to resolve the L2
1809 	 * IPA to the L1 IPA first, before knowing what kind of memory should
1810 	 * back the L1 IPA.
1811 	 *
1812 	 * If the shadow stage 2 page table walk faults, then we simply inject
1813 	 * this to the guest and carry on.
1814 	 *
1815 	 * If there are no shadow S2 PTs because S2 is disabled, there is
1816 	 * nothing to walk and we treat it as a 1:1 before going through the
1817 	 * canonical translation.
1818 	 */
1819 	if (kvm_is_nested_s2_mmu(vcpu->kvm,vcpu->arch.hw_mmu) &&
1820 	    vcpu->arch.hw_mmu->nested_stage2_enabled) {
1821 		u32 esr;
1822 
1823 		ret = kvm_walk_nested_s2(vcpu, fault_ipa, &nested_trans);
1824 		if (ret) {
1825 			esr = kvm_s2_trans_esr(&nested_trans);
1826 			kvm_inject_s2_fault(vcpu, esr);
1827 			goto out_unlock;
1828 		}
1829 
1830 		ret = kvm_s2_handle_perm_fault(vcpu, &nested_trans);
1831 		if (ret) {
1832 			esr = kvm_s2_trans_esr(&nested_trans);
1833 			kvm_inject_s2_fault(vcpu, esr);
1834 			goto out_unlock;
1835 		}
1836 
1837 		ipa = kvm_s2_trans_output(&nested_trans);
1838 		nested = &nested_trans;
1839 	}
1840 
1841 	gfn = ipa >> PAGE_SHIFT;
1842 	memslot = gfn_to_memslot(vcpu->kvm, gfn);
1843 	hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
1844 	write_fault = kvm_is_write_fault(vcpu);
1845 	if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
1846 		/*
1847 		 * The guest has put either its instructions or its page-tables
1848 		 * somewhere it shouldn't have. Userspace won't be able to do
1849 		 * anything about this (there's no syndrome for a start), so
1850 		 * re-inject the abort back into the guest.
1851 		 */
1852 		if (is_iabt) {
1853 			ret = -ENOEXEC;
1854 			goto out;
1855 		}
1856 
1857 		if (kvm_vcpu_abt_iss1tw(vcpu)) {
1858 			kvm_inject_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1859 			ret = 1;
1860 			goto out_unlock;
1861 		}
1862 
1863 		/*
1864 		 * Check for a cache maintenance operation. Since we
1865 		 * ended-up here, we know it is outside of any memory
1866 		 * slot. But we can't find out if that is for a device,
1867 		 * or if the guest is just being stupid. The only thing
1868 		 * we know for sure is that this range cannot be cached.
1869 		 *
1870 		 * So let's assume that the guest is just being
1871 		 * cautious, and skip the instruction.
1872 		 */
1873 		if (kvm_is_error_hva(hva) && kvm_vcpu_dabt_is_cm(vcpu)) {
1874 			kvm_incr_pc(vcpu);
1875 			ret = 1;
1876 			goto out_unlock;
1877 		}
1878 
1879 		/*
1880 		 * The IPA is reported as [MAX:12], so we need to
1881 		 * complement it with the bottom 12 bits from the
1882 		 * faulting VA. This is always 12 bits, irrespective
1883 		 * of the page size.
1884 		 */
1885 		ipa |= kvm_vcpu_get_hfar(vcpu) & GENMASK(11, 0);
1886 		ret = io_mem_abort(vcpu, ipa);
1887 		goto out_unlock;
1888 	}
1889 
1890 	/* Userspace should not be able to register out-of-bounds IPAs */
1891 	VM_BUG_ON(ipa >= kvm_phys_size(vcpu->arch.hw_mmu));
1892 
1893 	if (esr_fsc_is_access_flag_fault(esr)) {
1894 		handle_access_fault(vcpu, fault_ipa);
1895 		ret = 1;
1896 		goto out_unlock;
1897 	}
1898 
1899 	ret = user_mem_abort(vcpu, fault_ipa, nested, memslot, hva,
1900 			     esr_fsc_is_permission_fault(esr));
1901 	if (ret == 0)
1902 		ret = 1;
1903 out:
1904 	if (ret == -ENOEXEC) {
1905 		kvm_inject_pabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1906 		ret = 1;
1907 	}
1908 out_unlock:
1909 	srcu_read_unlock(&vcpu->kvm->srcu, idx);
1910 	return ret;
1911 }
1912 
1913 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1914 {
1915 	if (!kvm->arch.mmu.pgt)
1916 		return false;
1917 
1918 	__unmap_stage2_range(&kvm->arch.mmu, range->start << PAGE_SHIFT,
1919 			     (range->end - range->start) << PAGE_SHIFT,
1920 			     range->may_block);
1921 
1922 	kvm_nested_s2_unmap(kvm, range->may_block);
1923 	return false;
1924 }
1925 
1926 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1927 {
1928 	u64 size = (range->end - range->start) << PAGE_SHIFT;
1929 
1930 	if (!kvm->arch.mmu.pgt)
1931 		return false;
1932 
1933 	return kvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
1934 						   range->start << PAGE_SHIFT,
1935 						   size, true);
1936 	/*
1937 	 * TODO: Handle nested_mmu structures here using the reverse mapping in
1938 	 * a later version of patch series.
1939 	 */
1940 }
1941 
1942 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1943 {
1944 	u64 size = (range->end - range->start) << PAGE_SHIFT;
1945 
1946 	if (!kvm->arch.mmu.pgt)
1947 		return false;
1948 
1949 	return kvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
1950 						   range->start << PAGE_SHIFT,
1951 						   size, false);
1952 }
1953 
1954 phys_addr_t kvm_mmu_get_httbr(void)
1955 {
1956 	return __pa(hyp_pgtable->pgd);
1957 }
1958 
1959 phys_addr_t kvm_get_idmap_vector(void)
1960 {
1961 	return hyp_idmap_vector;
1962 }
1963 
1964 static int kvm_map_idmap_text(void)
1965 {
1966 	unsigned long size = hyp_idmap_end - hyp_idmap_start;
1967 	int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
1968 					PAGE_HYP_EXEC);
1969 	if (err)
1970 		kvm_err("Failed to idmap %lx-%lx\n",
1971 			hyp_idmap_start, hyp_idmap_end);
1972 
1973 	return err;
1974 }
1975 
1976 static void *kvm_hyp_zalloc_page(void *arg)
1977 {
1978 	return (void *)get_zeroed_page(GFP_KERNEL);
1979 }
1980 
1981 static struct kvm_pgtable_mm_ops kvm_hyp_mm_ops = {
1982 	.zalloc_page		= kvm_hyp_zalloc_page,
1983 	.get_page		= kvm_host_get_page,
1984 	.put_page		= kvm_host_put_page,
1985 	.phys_to_virt		= kvm_host_va,
1986 	.virt_to_phys		= kvm_host_pa,
1987 };
1988 
1989 int __init kvm_mmu_init(u32 *hyp_va_bits)
1990 {
1991 	int err;
1992 	u32 idmap_bits;
1993 	u32 kernel_bits;
1994 
1995 	hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
1996 	hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
1997 	hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
1998 	hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
1999 	hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
2000 
2001 	/*
2002 	 * We rely on the linker script to ensure at build time that the HYP
2003 	 * init code does not cross a page boundary.
2004 	 */
2005 	BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
2006 
2007 	/*
2008 	 * The ID map is always configured for 48 bits of translation, which
2009 	 * may be fewer than the number of VA bits used by the regular kernel
2010 	 * stage 1, when VA_BITS=52.
2011 	 *
2012 	 * At EL2, there is only one TTBR register, and we can't switch between
2013 	 * translation tables *and* update TCR_EL2.T0SZ at the same time. Bottom
2014 	 * line: we need to use the extended range with *both* our translation
2015 	 * tables.
2016 	 *
2017 	 * So use the maximum of the idmap VA bits and the regular kernel stage
2018 	 * 1 VA bits to assure that the hypervisor can both ID map its code page
2019 	 * and map any kernel memory.
2020 	 */
2021 	idmap_bits = IDMAP_VA_BITS;
2022 	kernel_bits = vabits_actual;
2023 	*hyp_va_bits = max(idmap_bits, kernel_bits);
2024 
2025 	kvm_debug("Using %u-bit virtual addresses at EL2\n", *hyp_va_bits);
2026 	kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
2027 	kvm_debug("HYP VA range: %lx:%lx\n",
2028 		  kern_hyp_va(PAGE_OFFSET),
2029 		  kern_hyp_va((unsigned long)high_memory - 1));
2030 
2031 	if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
2032 	    hyp_idmap_start <  kern_hyp_va((unsigned long)high_memory - 1) &&
2033 	    hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
2034 		/*
2035 		 * The idmap page is intersecting with the VA space,
2036 		 * it is not safe to continue further.
2037 		 */
2038 		kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
2039 		err = -EINVAL;
2040 		goto out;
2041 	}
2042 
2043 	hyp_pgtable = kzalloc(sizeof(*hyp_pgtable), GFP_KERNEL);
2044 	if (!hyp_pgtable) {
2045 		kvm_err("Hyp mode page-table not allocated\n");
2046 		err = -ENOMEM;
2047 		goto out;
2048 	}
2049 
2050 	err = kvm_pgtable_hyp_init(hyp_pgtable, *hyp_va_bits, &kvm_hyp_mm_ops);
2051 	if (err)
2052 		goto out_free_pgtable;
2053 
2054 	err = kvm_map_idmap_text();
2055 	if (err)
2056 		goto out_destroy_pgtable;
2057 
2058 	io_map_base = hyp_idmap_start;
2059 	return 0;
2060 
2061 out_destroy_pgtable:
2062 	kvm_pgtable_hyp_destroy(hyp_pgtable);
2063 out_free_pgtable:
2064 	kfree(hyp_pgtable);
2065 	hyp_pgtable = NULL;
2066 out:
2067 	return err;
2068 }
2069 
2070 void kvm_arch_commit_memory_region(struct kvm *kvm,
2071 				   struct kvm_memory_slot *old,
2072 				   const struct kvm_memory_slot *new,
2073 				   enum kvm_mr_change change)
2074 {
2075 	bool log_dirty_pages = new && new->flags & KVM_MEM_LOG_DIRTY_PAGES;
2076 
2077 	/*
2078 	 * At this point memslot has been committed and there is an
2079 	 * allocated dirty_bitmap[], dirty pages will be tracked while the
2080 	 * memory slot is write protected.
2081 	 */
2082 	if (log_dirty_pages) {
2083 
2084 		if (change == KVM_MR_DELETE)
2085 			return;
2086 
2087 		/*
2088 		 * Huge and normal pages are write-protected and split
2089 		 * on either of these two cases:
2090 		 *
2091 		 * 1. with initial-all-set: gradually with CLEAR ioctls,
2092 		 */
2093 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
2094 			return;
2095 		/*
2096 		 * or
2097 		 * 2. without initial-all-set: all in one shot when
2098 		 *    enabling dirty logging.
2099 		 */
2100 		kvm_mmu_wp_memory_region(kvm, new->id);
2101 		kvm_mmu_split_memory_region(kvm, new->id);
2102 	} else {
2103 		/*
2104 		 * Free any leftovers from the eager page splitting cache. Do
2105 		 * this when deleting, moving, disabling dirty logging, or
2106 		 * creating the memslot (a nop). Doing it for deletes makes
2107 		 * sure we don't leak memory, and there's no need to keep the
2108 		 * cache around for any of the other cases.
2109 		 */
2110 		kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
2111 	}
2112 }
2113 
2114 int kvm_arch_prepare_memory_region(struct kvm *kvm,
2115 				   const struct kvm_memory_slot *old,
2116 				   struct kvm_memory_slot *new,
2117 				   enum kvm_mr_change change)
2118 {
2119 	hva_t hva, reg_end;
2120 	int ret = 0;
2121 
2122 	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
2123 			change != KVM_MR_FLAGS_ONLY)
2124 		return 0;
2125 
2126 	/*
2127 	 * Prevent userspace from creating a memory region outside of the IPA
2128 	 * space addressable by the KVM guest IPA space.
2129 	 */
2130 	if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT))
2131 		return -EFAULT;
2132 
2133 	hva = new->userspace_addr;
2134 	reg_end = hva + (new->npages << PAGE_SHIFT);
2135 
2136 	mmap_read_lock(current->mm);
2137 	/*
2138 	 * A memory region could potentially cover multiple VMAs, and any holes
2139 	 * between them, so iterate over all of them.
2140 	 *
2141 	 *     +--------------------------------------------+
2142 	 * +---------------+----------------+   +----------------+
2143 	 * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
2144 	 * +---------------+----------------+   +----------------+
2145 	 *     |               memory region                |
2146 	 *     +--------------------------------------------+
2147 	 */
2148 	do {
2149 		struct vm_area_struct *vma;
2150 
2151 		vma = find_vma_intersection(current->mm, hva, reg_end);
2152 		if (!vma)
2153 			break;
2154 
2155 		if (kvm_has_mte(kvm) && !kvm_vma_mte_allowed(vma)) {
2156 			ret = -EINVAL;
2157 			break;
2158 		}
2159 
2160 		if (vma->vm_flags & VM_PFNMAP) {
2161 			/* IO region dirty page logging not allowed */
2162 			if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
2163 				ret = -EINVAL;
2164 				break;
2165 			}
2166 		}
2167 		hva = min(reg_end, vma->vm_end);
2168 	} while (hva < reg_end);
2169 
2170 	mmap_read_unlock(current->mm);
2171 	return ret;
2172 }
2173 
2174 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
2175 {
2176 }
2177 
2178 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
2179 {
2180 }
2181 
2182 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
2183 				   struct kvm_memory_slot *slot)
2184 {
2185 	gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
2186 	phys_addr_t size = slot->npages << PAGE_SHIFT;
2187 
2188 	write_lock(&kvm->mmu_lock);
2189 	kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, size, true);
2190 	kvm_nested_s2_unmap(kvm, true);
2191 	write_unlock(&kvm->mmu_lock);
2192 }
2193 
2194 /*
2195  * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
2196  *
2197  * Main problems:
2198  * - S/W ops are local to a CPU (not broadcast)
2199  * - We have line migration behind our back (speculation)
2200  * - System caches don't support S/W at all (damn!)
2201  *
2202  * In the face of the above, the best we can do is to try and convert
2203  * S/W ops to VA ops. Because the guest is not allowed to infer the
2204  * S/W to PA mapping, it can only use S/W to nuke the whole cache,
2205  * which is a rather good thing for us.
2206  *
2207  * Also, it is only used when turning caches on/off ("The expected
2208  * usage of the cache maintenance instructions that operate by set/way
2209  * is associated with the cache maintenance instructions associated
2210  * with the powerdown and powerup of caches, if this is required by
2211  * the implementation.").
2212  *
2213  * We use the following policy:
2214  *
2215  * - If we trap a S/W operation, we enable VM trapping to detect
2216  *   caches being turned on/off, and do a full clean.
2217  *
2218  * - We flush the caches on both caches being turned on and off.
2219  *
2220  * - Once the caches are enabled, we stop trapping VM ops.
2221  */
2222 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
2223 {
2224 	unsigned long hcr = *vcpu_hcr(vcpu);
2225 
2226 	/*
2227 	 * If this is the first time we do a S/W operation
2228 	 * (i.e. HCR_TVM not set) flush the whole memory, and set the
2229 	 * VM trapping.
2230 	 *
2231 	 * Otherwise, rely on the VM trapping to wait for the MMU +
2232 	 * Caches to be turned off. At that point, we'll be able to
2233 	 * clean the caches again.
2234 	 */
2235 	if (!(hcr & HCR_TVM)) {
2236 		trace_kvm_set_way_flush(*vcpu_pc(vcpu),
2237 					vcpu_has_cache_enabled(vcpu));
2238 		stage2_flush_vm(vcpu->kvm);
2239 		*vcpu_hcr(vcpu) = hcr | HCR_TVM;
2240 	}
2241 }
2242 
2243 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
2244 {
2245 	bool now_enabled = vcpu_has_cache_enabled(vcpu);
2246 
2247 	/*
2248 	 * If switching the MMU+caches on, need to invalidate the caches.
2249 	 * If switching it off, need to clean the caches.
2250 	 * Clean + invalidate does the trick always.
2251 	 */
2252 	if (now_enabled != was_enabled)
2253 		stage2_flush_vm(vcpu->kvm);
2254 
2255 	/* Caches are now on, stop trapping VM ops (until a S/W op) */
2256 	if (now_enabled)
2257 		*vcpu_hcr(vcpu) &= ~HCR_TVM;
2258 
2259 	trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
2260 }
2261