xref: /linux/arch/arm64/kvm/mmu.c (revision 17fa96334e15c6b38e8d9dd3627f3a6c5ca034f8)
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/acpi.h>
8 #include <linux/cleanup.h>
9 #include <linux/mman.h>
10 #include <linux/kvm_host.h>
11 #include <linux/interval_tree.h>
12 #include <linux/io.h>
13 #include <linux/hugetlb.h>
14 #include <linux/sched/signal.h>
15 #include <trace/events/kvm.h>
16 #include <asm/acpi.h>
17 #include <asm/pgalloc.h>
18 #include <asm/cacheflush.h>
19 #include <asm/kvm_arm.h>
20 #include <asm/kvm_mmu.h>
21 #include <asm/kvm_pgtable.h>
22 #include <asm/kvm_pkvm.h>
23 #include <asm/kvm_asm.h>
24 #include <asm/kvm_emulate.h>
25 #include <asm/virt.h>
26 
27 #include "trace.h"
28 
29 static struct kvm_pgtable *hyp_pgtable;
30 static DEFINE_MUTEX(kvm_hyp_pgd_mutex);
31 
32 static unsigned long __ro_after_init hyp_idmap_start;
33 static unsigned long __ro_after_init hyp_idmap_end;
34 static phys_addr_t __ro_after_init hyp_idmap_vector;
35 
36 u32 __ro_after_init __hyp_va_bits;
37 
38 static unsigned long __ro_after_init io_map_base;
39 
40 #define KVM_PGT_FN(fn)		(!is_protected_kvm_enabled() ? fn : p ## fn)
41 
42 static int kvm_vm_init_vm_s2_ops(struct kvm *kvm);
43 
44 static phys_addr_t __stage2_range_addr_end(phys_addr_t addr, phys_addr_t end,
45 					   phys_addr_t size)
46 {
47 	phys_addr_t boundary = ALIGN_DOWN(addr + size, size);
48 
49 	return (boundary - 1 < end - 1) ? boundary : end;
50 }
51 
52 static phys_addr_t stage2_range_addr_end(phys_addr_t addr, phys_addr_t end)
53 {
54 	phys_addr_t size = kvm_granule_size(KVM_PGTABLE_MIN_BLOCK_LEVEL);
55 
56 	return __stage2_range_addr_end(addr, end, size);
57 }
58 
59 /*
60  * Release kvm_mmu_lock periodically if the memory region is large. Otherwise,
61  * we may see kernel panics with CONFIG_DETECT_HUNG_TASK,
62  * CONFIG_LOCKUP_DETECTOR, CONFIG_LOCKDEP. Additionally, holding the lock too
63  * long will also starve other vCPUs. We have to also make sure that the page
64  * tables are not freed while we released the lock.
65  */
66 static int stage2_apply_range(struct kvm_s2_mmu *mmu, phys_addr_t start,
67 			      phys_addr_t end,
68 			      int (*fn)(struct kvm_pgtable *, u64, u64),
69 			      bool resched)
70 {
71 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
72 	bool lock_dropped = false;
73 	phys_addr_t addr = start;
74 	int ret;
75 	u64 next;
76 
77 	do {
78 		struct kvm_pgtable *pgt = mmu->pgt;
79 		/*
80 		 * We may be raced on PGT teardown when we release the
81 		 * kvm->mmu_lock. That's fine as the PGT is legitimately no
82 		 * longer present.
83 		 */
84 		if (!pgt)
85 			return lock_dropped ? 0 : -EINVAL;
86 
87 		next = stage2_range_addr_end(addr, end);
88 		ret = fn(pgt, addr, next - addr);
89 		if (ret)
90 			break;
91 
92 		if (resched && next != end) {
93 			cond_resched_rwlock_write(&kvm->mmu_lock);
94 			lock_dropped = true;
95 		}
96 	} while (addr = next, addr != end);
97 
98 	return ret;
99 }
100 
101 #define stage2_apply_range_resched(mmu, addr, end, fn)			\
102 	stage2_apply_range(mmu, addr, end, fn, true)
103 
104 /*
105  * Get the maximum number of page-tables pages needed to split a range
106  * of blocks into PAGE_SIZE PTEs. It assumes the range is already
107  * mapped at level 2, or at level 1 if allowed.
108  */
109 static int kvm_mmu_split_nr_page_tables(u64 range)
110 {
111 	int n = 0;
112 
113 	if (KVM_PGTABLE_MIN_BLOCK_LEVEL < 2)
114 		n += DIV_ROUND_UP(range, PUD_SIZE);
115 	n += DIV_ROUND_UP(range, PMD_SIZE);
116 	return n;
117 }
118 
119 static bool need_split_memcache_topup_or_resched(struct kvm *kvm)
120 {
121 	struct kvm_mmu_memory_cache *cache;
122 	u64 chunk_size, min;
123 
124 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
125 		return true;
126 
127 	chunk_size = kvm->arch.mmu.split_page_chunk_size;
128 	min = kvm_mmu_split_nr_page_tables(chunk_size);
129 	cache = &kvm->arch.mmu.split_page_cache;
130 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
131 }
132 
133 static int kvm_mmu_split_huge_pages(struct kvm *kvm, phys_addr_t addr,
134 				    phys_addr_t end)
135 {
136 	struct kvm_mmu_memory_cache *cache;
137 	struct kvm_pgtable *pgt;
138 	int ret, cache_capacity;
139 	u64 next, chunk_size;
140 
141 	lockdep_assert_held_write(&kvm->mmu_lock);
142 
143 	chunk_size = kvm->arch.mmu.split_page_chunk_size;
144 	cache_capacity = kvm_mmu_split_nr_page_tables(chunk_size);
145 
146 	if (chunk_size == 0)
147 		return 0;
148 
149 	cache = &kvm->arch.mmu.split_page_cache;
150 
151 	do {
152 		if (need_split_memcache_topup_or_resched(kvm)) {
153 			write_unlock(&kvm->mmu_lock);
154 			cond_resched();
155 			/* Eager page splitting is best-effort. */
156 			ret = __kvm_mmu_topup_memory_cache(cache,
157 							   cache_capacity,
158 							   cache_capacity);
159 			write_lock(&kvm->mmu_lock);
160 			if (ret)
161 				break;
162 		}
163 
164 		pgt = kvm->arch.mmu.pgt;
165 		if (!pgt)
166 			return -EINVAL;
167 
168 		next = __stage2_range_addr_end(addr, end, chunk_size);
169 		ret = KVM_PGT_FN(kvm_pgtable_stage2_split)(pgt, addr, next - addr, cache);
170 		if (ret)
171 			break;
172 	} while (addr = next, addr != end);
173 
174 	return ret;
175 }
176 
177 static bool memslot_is_logging(struct kvm_memory_slot *memslot)
178 {
179 	return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY);
180 }
181 
182 static int pkvm_flush_remote_tlbs(struct kvm *kvm)
183 {
184 	kvm_call_hyp_nvhe(__pkvm_tlb_flush_vmid, kvm->arch.pkvm.handle);
185 	return 0;
186 }
187 
188 static int kvm_vm_flush_remote_tlbs(struct kvm *kvm)
189 {
190 	kvm_call_hyp(__kvm_tlb_flush_vmid, &kvm->arch.mmu);
191 	return 0;
192 }
193 
194 /**
195  * kvm_arch_flush_remote_tlbs() - flush all VM TLB entries for v7/8
196  * @kvm:	pointer to kvm structure.
197  *
198  * Interface to HYP function to flush all VM TLB entries
199  */
200 int kvm_arch_flush_remote_tlbs(struct kvm *kvm)
201 {
202 	return kvm->arch.vm_s2_ops->vm_flush_remote_tlbs(kvm);
203 }
204 
205 static int pkvm_flush_remote_tlbs_range(struct kvm *kvm,
206 					gfn_t gfn, u64 nr_pages)
207 {
208 	return pkvm_flush_remote_tlbs(kvm);
209 }
210 
211 static int kvm_vm_flush_remote_tlbs_range(struct kvm *kvm,
212 					 gfn_t gfn, u64 nr_pages)
213 {
214 	u64 size = nr_pages << PAGE_SHIFT;
215 	u64 addr = gfn << PAGE_SHIFT;
216 
217 	kvm_tlb_flush_vmid_range(&kvm->arch.mmu, addr, size);
218 	return 0;
219 }
220 
221 int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm,
222 				     gfn_t gfn, u64 nr_pages)
223 {
224 	return kvm->arch.vm_s2_ops->vm_flush_remote_tlbs_range(kvm, gfn, nr_pages);
225 }
226 
227 static void *stage2_memcache_zalloc_page(void *arg)
228 {
229 	struct kvm_mmu_memory_cache *mc = arg;
230 	void *virt;
231 
232 	/* Allocated with __GFP_ZERO, so no need to zero */
233 	virt = kvm_mmu_memory_cache_alloc(mc);
234 	if (virt)
235 		kvm_account_pgtable_pages(virt, 1);
236 	return virt;
237 }
238 
239 static void *kvm_host_zalloc_pages_exact(size_t size)
240 {
241 	return alloc_pages_exact(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
242 }
243 
244 static void *kvm_s2_zalloc_pages_exact(size_t size)
245 {
246 	void *virt = kvm_host_zalloc_pages_exact(size);
247 
248 	if (virt)
249 		kvm_account_pgtable_pages(virt, (size >> PAGE_SHIFT));
250 	return virt;
251 }
252 
253 static void kvm_s2_free_pages_exact(void *virt, size_t size)
254 {
255 	kvm_account_pgtable_pages(virt, -(size >> PAGE_SHIFT));
256 	free_pages_exact(virt, size);
257 }
258 
259 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops;
260 
261 static void stage2_free_unlinked_table_rcu_cb(struct rcu_head *head)
262 {
263 	struct page *page = container_of(head, struct page, rcu_head);
264 	void *pgtable = page_to_virt(page);
265 	s8 level = page_private(page);
266 
267 	KVM_PGT_FN(kvm_pgtable_stage2_free_unlinked)(&kvm_s2_mm_ops, pgtable, level);
268 }
269 
270 static void stage2_free_unlinked_table(void *addr, s8 level)
271 {
272 	struct page *page = virt_to_page(addr);
273 
274 	set_page_private(page, (unsigned long)level);
275 	call_rcu(&page->rcu_head, stage2_free_unlinked_table_rcu_cb);
276 }
277 
278 static void kvm_host_get_page(void *addr)
279 {
280 	get_page(virt_to_page(addr));
281 }
282 
283 static void kvm_host_put_page(void *addr)
284 {
285 	put_page(virt_to_page(addr));
286 }
287 
288 static void kvm_s2_put_page(void *addr)
289 {
290 	struct page *p = virt_to_page(addr);
291 	/* Dropping last refcount, the page will be freed */
292 	if (page_count(p) == 1)
293 		kvm_account_pgtable_pages(addr, -1);
294 	put_page(p);
295 }
296 
297 static int kvm_host_page_count(void *addr)
298 {
299 	return page_count(virt_to_page(addr));
300 }
301 
302 static phys_addr_t kvm_host_pa(void *addr)
303 {
304 	return __pa(addr);
305 }
306 
307 static void *kvm_host_va(phys_addr_t phys)
308 {
309 	return __va(phys);
310 }
311 
312 static void clean_dcache_guest_page(void *va, size_t size)
313 {
314 	__clean_dcache_guest_page(va, size);
315 }
316 
317 static void invalidate_icache_guest_page(void *va, size_t size)
318 {
319 	__invalidate_icache_guest_page(va, size);
320 }
321 
322 static int kvm_pgtable_stage2_unmap_tracked(struct kvm_pgtable *pgt,
323 					    u64 addr, u64 size);
324 
325 static void kvm_vm_stage2_unmap_range(struct kvm_s2_mmu *mmu,
326 				      phys_addr_t start,
327 				      u64 size, bool may_block)
328 {
329 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
330 	int (*fn)(struct kvm_pgtable *, u64, u64);
331 
332 	if (kvm_is_nested_s2_mmu(kvm, mmu))
333 		fn = kvm_pgtable_stage2_unmap_tracked;
334 	else
335 		fn = kvm_pgtable_stage2_unmap;
336 
337 	WARN_ON(stage2_apply_range(mmu, start, start + size, fn, may_block));
338 }
339 
340 static void pkvm_stage2_unmap_range(struct kvm_s2_mmu *mmu,
341 				    phys_addr_t start,
342 				    u64 size, bool may_block)
343 {
344 	WARN_ON(stage2_apply_range(mmu, start, start + size,
345 				   pkvm_pgtable_stage2_unmap, may_block));
346 }
347 
348 static void no_stage2_unmap_range(struct kvm_s2_mmu *mmu,
349 				  phys_addr_t start, u64 size, bool may_block)
350 {
351 }
352 
353 /*
354  * Unmapping vs dcache management:
355  *
356  * If a guest maps certain memory pages as uncached, all writes will
357  * bypass the data cache and go directly to RAM.  However, the CPUs
358  * can still speculate reads (not writes) and fill cache lines with
359  * data.
360  *
361  * Those cache lines will be *clean* cache lines though, so a
362  * clean+invalidate operation is equivalent to an invalidate
363  * operation, because no cache lines are marked dirty.
364  *
365  * Those clean cache lines could be filled prior to an uncached write
366  * by the guest, and the cache coherent IO subsystem would therefore
367  * end up writing old data to disk.
368  *
369  * This is why right after unmapping a page/section and invalidating
370  * the corresponding TLBs, we flush to make sure the IO subsystem will
371  * never hit in the cache.
372  *
373  * This is all avoided on systems that have ARM64_HAS_STAGE2_FWB, as
374  * we then fully enforce cacheability of RAM, no matter what the guest
375  * does.
376  */
377 
378 static int kvm_pgtable_stage2_unmap_tracked(struct kvm_pgtable *pgt, u64 addr, u64 size)
379 {
380 	int ret;
381 
382 	ret = kvm_pgtable_stage2_unmap(pgt, addr, size);
383 	if (ret)
384 		return ret;
385 
386 	kvm_remove_guest_s2_mappings(pgt->mmu, addr, size);
387 	return 0;
388 }
389 
390 /**
391  * kvm_stage2_unmap_range -- Clear stage2 page table entries to unmap a range
392  * @mmu:   The KVM stage-2 MMU pointer
393  * @start: The intermediate physical base address of the range to unmap
394  * @size:  The size of the area to unmap
395  * @may_block: Whether or not we are permitted to block
396  *
397  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
398  * be called while holding mmu_lock otherwise another faulting VCPU may
399  * come in and mess with things behind our backs.
400  */
401 void kvm_stage2_unmap_range(struct kvm_s2_mmu *mmu, phys_addr_t start,
402 			    u64 size, bool may_block)
403 {
404 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
405 
406 	lockdep_assert_held_write(&kvm->mmu_lock);
407 	WARN_ON(size & ~PAGE_MASK);
408 
409 	kvm->arch.vm_s2_ops->vm_stage2_unmap_range(mmu, start, size, may_block);
410 }
411 
412 void kvm_stage2_flush_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
413 {
414 	stage2_apply_range_resched(mmu, addr, end, KVM_PGT_FN(kvm_pgtable_stage2_flush));
415 }
416 
417 static void stage2_flush_memslot(struct kvm *kvm,
418 				 struct kvm_memory_slot *memslot)
419 {
420 	phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
421 	phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
422 
423 	kvm_stage2_flush_range(&kvm->arch.mmu, addr, end);
424 }
425 
426 /**
427  * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
428  * @kvm: The struct kvm pointer
429  *
430  * Go through the stage 2 page tables and invalidate any cache lines
431  * backing memory already mapped to the VM.
432  */
433 static void stage2_flush_vm(struct kvm *kvm)
434 {
435 	struct kvm_memslots *slots;
436 	struct kvm_memory_slot *memslot;
437 	int idx, bkt;
438 
439 	idx = srcu_read_lock(&kvm->srcu);
440 	write_lock(&kvm->mmu_lock);
441 
442 	slots = kvm_memslots(kvm);
443 	kvm_for_each_memslot(memslot, bkt, slots)
444 		stage2_flush_memslot(kvm, memslot);
445 
446 	kvm_nested_s2_flush(kvm);
447 
448 	write_unlock(&kvm->mmu_lock);
449 	srcu_read_unlock(&kvm->srcu, idx);
450 }
451 
452 /**
453  * free_hyp_pgds - free Hyp-mode page tables
454  */
455 void __init free_hyp_pgds(void)
456 {
457 	mutex_lock(&kvm_hyp_pgd_mutex);
458 	if (hyp_pgtable) {
459 		kvm_pgtable_hyp_destroy(hyp_pgtable);
460 		kfree(hyp_pgtable);
461 		hyp_pgtable = NULL;
462 	}
463 	mutex_unlock(&kvm_hyp_pgd_mutex);
464 }
465 
466 static bool kvm_host_owns_hyp_mappings(void)
467 {
468 	if (is_kernel_in_hyp_mode())
469 		return false;
470 
471 	if (static_branch_likely(&kvm_protected_mode_initialized))
472 		return false;
473 
474 	/*
475 	 * This can happen at boot time when __create_hyp_mappings() is called
476 	 * after the hyp protection has been enabled, but the static key has
477 	 * not been flipped yet.
478 	 */
479 	if (!hyp_pgtable && is_protected_kvm_enabled())
480 		return false;
481 
482 	WARN_ON(!hyp_pgtable);
483 
484 	return true;
485 }
486 
487 int __create_hyp_mappings(unsigned long start, unsigned long size,
488 			  unsigned long phys, enum kvm_pgtable_prot prot)
489 {
490 	int err;
491 
492 	if (WARN_ON(!kvm_host_owns_hyp_mappings()))
493 		return -EINVAL;
494 
495 	mutex_lock(&kvm_hyp_pgd_mutex);
496 	err = kvm_pgtable_hyp_map(hyp_pgtable, start, size, phys, prot);
497 	mutex_unlock(&kvm_hyp_pgd_mutex);
498 
499 	return err;
500 }
501 
502 static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
503 {
504 	if (!is_vmalloc_addr(kaddr)) {
505 		BUG_ON(!virt_addr_valid(kaddr));
506 		return __pa(kaddr);
507 	} else {
508 		return page_to_phys(vmalloc_to_page(kaddr)) +
509 		       offset_in_page(kaddr);
510 	}
511 }
512 
513 struct hyp_shared_pfn {
514 	u64 pfn;
515 	int count;
516 	struct rb_node node;
517 };
518 
519 static DEFINE_MUTEX(hyp_shared_pfns_lock);
520 static struct rb_root hyp_shared_pfns = RB_ROOT;
521 
522 static struct hyp_shared_pfn *find_shared_pfn(u64 pfn, struct rb_node ***node,
523 					      struct rb_node **parent)
524 {
525 	struct hyp_shared_pfn *this;
526 
527 	*node = &hyp_shared_pfns.rb_node;
528 	*parent = NULL;
529 	while (**node) {
530 		this = container_of(**node, struct hyp_shared_pfn, node);
531 		*parent = **node;
532 		if (this->pfn < pfn)
533 			*node = &((**node)->rb_left);
534 		else if (this->pfn > pfn)
535 			*node = &((**node)->rb_right);
536 		else
537 			return this;
538 	}
539 
540 	return NULL;
541 }
542 
543 static int share_pfn_hyp(u64 pfn)
544 {
545 	struct rb_node **node, *parent;
546 	struct hyp_shared_pfn *this;
547 	int ret = 0;
548 
549 	mutex_lock(&hyp_shared_pfns_lock);
550 	this = find_shared_pfn(pfn, &node, &parent);
551 	if (this) {
552 		this->count++;
553 		goto unlock;
554 	}
555 
556 	this = kzalloc_obj(*this);
557 	if (!this) {
558 		ret = -ENOMEM;
559 		goto unlock;
560 	}
561 
562 	this->pfn = pfn;
563 	this->count = 1;
564 	rb_link_node(&this->node, parent, node);
565 	rb_insert_color(&this->node, &hyp_shared_pfns);
566 	ret = kvm_call_hyp_nvhe(__pkvm_host_share_hyp, pfn);
567 	if (ret) {
568 		rb_erase(&this->node, &hyp_shared_pfns);
569 		kfree(this);
570 	}
571 unlock:
572 	mutex_unlock(&hyp_shared_pfns_lock);
573 
574 	return ret;
575 }
576 
577 static int unshare_pfn_hyp(u64 pfn)
578 {
579 	struct rb_node **node, *parent;
580 	struct hyp_shared_pfn *this;
581 	int ret = 0;
582 
583 	mutex_lock(&hyp_shared_pfns_lock);
584 	this = find_shared_pfn(pfn, &node, &parent);
585 	if (WARN_ON(!this)) {
586 		ret = -ENOENT;
587 		goto unlock;
588 	}
589 
590 	if (this->count > 1) {
591 		this->count--;
592 		goto unlock;
593 	}
594 
595 	ret = kvm_call_hyp_nvhe(__pkvm_host_unshare_hyp, pfn);
596 	if (ret)
597 		goto unlock;
598 
599 	rb_erase(&this->node, &hyp_shared_pfns);
600 	kfree(this);
601 unlock:
602 	mutex_unlock(&hyp_shared_pfns_lock);
603 
604 	return ret;
605 }
606 
607 int kvm_share_hyp(void *from, void *to)
608 {
609 	phys_addr_t start, end, cur;
610 	int ret = 0;
611 	u64 pfn;
612 
613 	if (is_kernel_in_hyp_mode())
614 		return 0;
615 
616 	/*
617 	 * The share hcall maps things in the 'fixed-offset' region of the hyp
618 	 * VA space, so we can only share physically contiguous data-structures
619 	 * for now.
620 	 */
621 	if (is_vmalloc_or_module_addr(from) || is_vmalloc_or_module_addr(to))
622 		return -EINVAL;
623 
624 	if (kvm_host_owns_hyp_mappings())
625 		return create_hyp_mappings(from, to, PAGE_HYP);
626 
627 	start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
628 	end = PAGE_ALIGN(__pa(to));
629 	for (cur = start; cur < end; cur += PAGE_SIZE) {
630 		pfn = __phys_to_pfn(cur);
631 		ret = share_pfn_hyp(pfn);
632 		if (ret)
633 			break;
634 	}
635 
636 	if (!ret)
637 		return 0;
638 
639 	/*
640 	 * Roll back the pages shared by this call. A failed unshare leaks
641 	 * the page (it stays shared with the hypervisor and is no longer
642 	 * reusable for pKVM) but breaks no isolation guarantee, so warn and
643 	 * continue. Not expected in practice.
644 	 */
645 	for (end = cur, cur = start; cur < end; cur += PAGE_SIZE) {
646 		pfn = __phys_to_pfn(cur);
647 		WARN_ON(unshare_pfn_hyp(pfn));
648 	}
649 
650 	return ret;
651 }
652 
653 void kvm_unshare_hyp(void *from, void *to)
654 {
655 	phys_addr_t start, end, cur;
656 	u64 pfn;
657 
658 	if (is_kernel_in_hyp_mode() || kvm_host_owns_hyp_mappings() || !from)
659 		return;
660 
661 	start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
662 	end = PAGE_ALIGN(__pa(to));
663 	for (cur = start; cur < end; cur += PAGE_SIZE) {
664 		pfn = __phys_to_pfn(cur);
665 		/*
666 		 * A failed unshare leaks the page: it stays shared with the
667 		 * hypervisor and is no longer reusable for pKVM. No isolation
668 		 * guarantee is broken, and this is not expected in practice.
669 		 */
670 		WARN_ON(unshare_pfn_hyp(pfn));
671 	}
672 }
673 
674 /**
675  * create_hyp_mappings - duplicate a kernel virtual address range in Hyp mode
676  * @from:	The virtual kernel start address of the range
677  * @to:		The virtual kernel end address of the range (exclusive)
678  * @prot:	The protection to be applied to this range
679  *
680  * The same virtual address as the kernel virtual address is also used
681  * in Hyp-mode mapping (modulo HYP_PAGE_OFFSET) to the same underlying
682  * physical pages.
683  */
684 int create_hyp_mappings(void *from, void *to, enum kvm_pgtable_prot prot)
685 {
686 	phys_addr_t phys_addr;
687 	unsigned long virt_addr;
688 	unsigned long start = kern_hyp_va((unsigned long)from);
689 	unsigned long end = kern_hyp_va((unsigned long)to);
690 
691 	if (is_kernel_in_hyp_mode())
692 		return 0;
693 
694 	if (!kvm_host_owns_hyp_mappings())
695 		return -EPERM;
696 
697 	start = start & PAGE_MASK;
698 	end = PAGE_ALIGN(end);
699 
700 	for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
701 		int err;
702 
703 		phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
704 		err = __create_hyp_mappings(virt_addr, PAGE_SIZE, phys_addr,
705 					    prot);
706 		if (err)
707 			return err;
708 	}
709 
710 	return 0;
711 }
712 
713 static int __hyp_alloc_private_va_range(unsigned long base)
714 {
715 	lockdep_assert_held(&kvm_hyp_pgd_mutex);
716 
717 	if (!PAGE_ALIGNED(base))
718 		return -EINVAL;
719 
720 	/*
721 	 * Verify that BIT(VA_BITS - 1) hasn't been flipped by
722 	 * allocating the new area, as it would indicate we've
723 	 * overflowed the idmap/IO address range.
724 	 */
725 	if ((base ^ io_map_base) & BIT(VA_BITS - 1))
726 		return -ENOMEM;
727 
728 	io_map_base = base;
729 
730 	return 0;
731 }
732 
733 /**
734  * hyp_alloc_private_va_range - Allocates a private VA range.
735  * @size:	The size of the VA range to reserve.
736  * @haddr:	The hypervisor virtual start address of the allocation.
737  *
738  * The private virtual address (VA) range is allocated below io_map_base
739  * and aligned based on the order of @size.
740  *
741  * Return: 0 on success or negative error code on failure.
742  */
743 int hyp_alloc_private_va_range(size_t size, unsigned long *haddr)
744 {
745 	unsigned long base;
746 	int ret = 0;
747 
748 	mutex_lock(&kvm_hyp_pgd_mutex);
749 
750 	/*
751 	 * This assumes that we have enough space below the idmap
752 	 * page to allocate our VAs. If not, the check in
753 	 * __hyp_alloc_private_va_range() will kick. A potential
754 	 * alternative would be to detect that overflow and switch
755 	 * to an allocation above the idmap.
756 	 *
757 	 * The allocated size is always a multiple of PAGE_SIZE.
758 	 */
759 	size = PAGE_ALIGN(size);
760 	base = io_map_base - size;
761 	ret = __hyp_alloc_private_va_range(base);
762 
763 	mutex_unlock(&kvm_hyp_pgd_mutex);
764 
765 	if (!ret)
766 		*haddr = base;
767 
768 	return ret;
769 }
770 
771 static int __create_hyp_private_mapping(phys_addr_t phys_addr, size_t size,
772 					unsigned long *haddr,
773 					enum kvm_pgtable_prot prot)
774 {
775 	unsigned long addr;
776 	int ret = 0;
777 
778 	if (!kvm_host_owns_hyp_mappings()) {
779 		addr = kvm_call_hyp_nvhe(__pkvm_create_private_mapping,
780 					 phys_addr, size, prot);
781 		if (IS_ERR_VALUE(addr))
782 			return addr;
783 		*haddr = addr;
784 
785 		return 0;
786 	}
787 
788 	size = PAGE_ALIGN(size + offset_in_page(phys_addr));
789 	ret = hyp_alloc_private_va_range(size, &addr);
790 	if (ret)
791 		return ret;
792 
793 	ret = __create_hyp_mappings(addr, size, phys_addr, prot);
794 	if (ret)
795 		return ret;
796 
797 	*haddr = addr + offset_in_page(phys_addr);
798 	return ret;
799 }
800 
801 int create_hyp_stack(phys_addr_t phys_addr, unsigned long *haddr)
802 {
803 	unsigned long base;
804 	size_t size;
805 	int ret;
806 
807 	mutex_lock(&kvm_hyp_pgd_mutex);
808 	/*
809 	 * Efficient stack verification using the NVHE_STACK_SHIFT bit implies
810 	 * an alignment of our allocation on the order of the size.
811 	 */
812 	size = NVHE_STACK_SIZE * 2;
813 	base = ALIGN_DOWN(io_map_base - size, size);
814 
815 	ret = __hyp_alloc_private_va_range(base);
816 
817 	mutex_unlock(&kvm_hyp_pgd_mutex);
818 
819 	if (ret) {
820 		kvm_err("Cannot allocate hyp stack guard page\n");
821 		return ret;
822 	}
823 
824 	/*
825 	 * Since the stack grows downwards, map the stack to the page
826 	 * at the higher address and leave the lower guard page
827 	 * unbacked.
828 	 *
829 	 * Any valid stack address now has the NVHE_STACK_SHIFT bit as 1
830 	 * and addresses corresponding to the guard page have the
831 	 * NVHE_STACK_SHIFT bit as 0 - this is used for overflow detection.
832 	 */
833 	ret = __create_hyp_mappings(base + NVHE_STACK_SIZE, NVHE_STACK_SIZE,
834 				    phys_addr, PAGE_HYP);
835 	if (ret)
836 		kvm_err("Cannot map hyp stack\n");
837 
838 	*haddr = base + size;
839 
840 	return ret;
841 }
842 
843 /**
844  * create_hyp_io_mappings - Map IO into both kernel and HYP
845  * @phys_addr:	The physical start address which gets mapped
846  * @size:	Size of the region being mapped
847  * @kaddr:	Kernel VA for this mapping
848  * @haddr:	HYP VA for this mapping
849  */
850 int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size,
851 			   void __iomem **kaddr,
852 			   void __iomem **haddr)
853 {
854 	unsigned long addr;
855 	int ret;
856 
857 	if (is_protected_kvm_enabled())
858 		return -EPERM;
859 
860 	*kaddr = ioremap(phys_addr, size);
861 	if (!*kaddr)
862 		return -ENOMEM;
863 
864 	if (is_kernel_in_hyp_mode()) {
865 		*haddr = *kaddr;
866 		return 0;
867 	}
868 
869 	ret = __create_hyp_private_mapping(phys_addr, size,
870 					   &addr, PAGE_HYP_DEVICE);
871 	if (ret) {
872 		iounmap(*kaddr);
873 		*kaddr = NULL;
874 		*haddr = NULL;
875 		return ret;
876 	}
877 
878 	*haddr = (void __iomem *)addr;
879 	return 0;
880 }
881 
882 /**
883  * create_hyp_exec_mappings - Map an executable range into HYP
884  * @phys_addr:	The physical start address which gets mapped
885  * @size:	Size of the region being mapped
886  * @haddr:	HYP VA for this mapping
887  */
888 int create_hyp_exec_mappings(phys_addr_t phys_addr, size_t size,
889 			     void **haddr)
890 {
891 	unsigned long addr;
892 	int ret;
893 
894 	BUG_ON(is_kernel_in_hyp_mode());
895 
896 	ret = __create_hyp_private_mapping(phys_addr, size,
897 					   &addr, PAGE_HYP_EXEC);
898 	if (ret) {
899 		*haddr = NULL;
900 		return ret;
901 	}
902 
903 	*haddr = (void *)addr;
904 	return 0;
905 }
906 
907 static struct kvm_pgtable_mm_ops kvm_user_mm_ops = {
908 	/* We shouldn't need any other callback to walk the PT */
909 	.phys_to_virt		= kvm_host_va,
910 };
911 
912 static int get_user_mapping_size(struct kvm *kvm, u64 addr)
913 {
914 	struct kvm_pgtable pgt = {
915 		.pgd		= (kvm_pteref_t)kvm->mm->pgd,
916 		.ia_bits	= vabits_actual,
917 		.start_level	= (KVM_PGTABLE_LAST_LEVEL -
918 				   ARM64_HW_PGTABLE_LEVELS(pgt.ia_bits) + 1),
919 		.mm_ops		= &kvm_user_mm_ops,
920 	};
921 	unsigned long flags;
922 	kvm_pte_t pte = 0;	/* Keep GCC quiet... */
923 	s8 level = S8_MAX;
924 	int ret;
925 
926 	/*
927 	 * Disable IRQs so that we hazard against a concurrent
928 	 * teardown of the userspace page tables (which relies on
929 	 * IPI-ing threads).
930 	 */
931 	local_irq_save(flags);
932 	ret = kvm_pgtable_get_leaf(&pgt, addr, &pte, &level, 0);
933 	local_irq_restore(flags);
934 
935 	if (ret)
936 		return ret;
937 
938 	/*
939 	 * Not seeing an error, but not updating level? Something went
940 	 * deeply wrong...
941 	 */
942 	if (WARN_ON(level > KVM_PGTABLE_LAST_LEVEL))
943 		return -EFAULT;
944 	if (WARN_ON(level < KVM_PGTABLE_FIRST_LEVEL))
945 		return -EFAULT;
946 
947 	/* Oops, the userspace PTs are gone... Replay the fault */
948 	if (!kvm_pte_valid(pte))
949 		return -EAGAIN;
950 
951 	return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(level));
952 }
953 
954 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
955 	.zalloc_page		= stage2_memcache_zalloc_page,
956 	.zalloc_pages_exact	= kvm_s2_zalloc_pages_exact,
957 	.free_pages_exact	= kvm_s2_free_pages_exact,
958 	.free_unlinked_table	= stage2_free_unlinked_table,
959 	.get_page		= kvm_host_get_page,
960 	.put_page		= kvm_s2_put_page,
961 	.page_count		= kvm_host_page_count,
962 	.phys_to_virt		= kvm_host_va,
963 	.virt_to_phys		= kvm_host_pa,
964 	.dcache_clean_inval_poc	= clean_dcache_guest_page,
965 	.icache_inval_pou	= invalidate_icache_guest_page,
966 };
967 
968 static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
969 {
970 	u32 kvm_ipa_limit = get_kvm_ipa_limit();
971 	u64 mmfr0, mmfr1;
972 	u32 phys_shift;
973 
974 	phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
975 	if (is_protected_kvm_enabled()) {
976 		phys_shift = kvm_ipa_limit;
977 	} else if (phys_shift) {
978 		if (phys_shift > kvm_ipa_limit ||
979 		    phys_shift < ARM64_MIN_PARANGE_BITS)
980 			return -EINVAL;
981 	} else {
982 		phys_shift = KVM_PHYS_SHIFT;
983 		if (phys_shift > kvm_ipa_limit) {
984 			pr_warn_once("%s using unsupported default IPA limit, upgrade your VMM\n",
985 				     current->comm);
986 			return -EINVAL;
987 		}
988 	}
989 
990 	mmfr0 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
991 	mmfr1 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
992 	mmu->vtcr = kvm_get_vtcr(mmfr0, mmfr1, phys_shift);
993 
994 	return 0;
995 }
996 
997 /*
998  * Assume that @pgt is valid and unlinked from the KVM MMU to free the
999  * page-table without taking the kvm_mmu_lock and without performing any
1000  * TLB invalidations.
1001  *
1002  * Also, the range of addresses can be large enough to cause need_resched
1003  * warnings, for instance on CONFIG_PREEMPT_NONE kernels. Hence, invoke
1004  * cond_resched() periodically to prevent hogging the CPU for a long time
1005  * and schedule something else, if required.
1006  */
1007 static void stage2_destroy_range(struct kvm_pgtable *pgt, phys_addr_t addr,
1008 				   phys_addr_t end)
1009 {
1010 	u64 next;
1011 
1012 	do {
1013 		next = stage2_range_addr_end(addr, end);
1014 		KVM_PGT_FN(kvm_pgtable_stage2_destroy_range)(pgt, addr,
1015 							     next - addr);
1016 		if (next != end)
1017 			cond_resched();
1018 	} while (addr = next, addr != end);
1019 }
1020 
1021 static void kvm_stage2_destroy(struct kvm_pgtable *pgt)
1022 {
1023 	unsigned int ia_bits = VTCR_EL2_IPA(pgt->mmu->vtcr);
1024 
1025 	stage2_destroy_range(pgt, 0, BIT(ia_bits));
1026 	KVM_PGT_FN(kvm_pgtable_stage2_destroy_pgd)(pgt);
1027 }
1028 
1029 /**
1030  * kvm_init_stage2_mmu - Initialise a S2 MMU structure
1031  * @kvm:	The pointer to the KVM structure
1032  * @mmu:	The pointer to the s2 MMU structure
1033  * @type:	The machine type of the virtual machine
1034  *
1035  * Allocates only the stage-2 HW PGD level table(s).
1036  * Note we don't need locking here as this is only called in two cases:
1037  *
1038  * - when the VM is created, which can't race against anything
1039  *
1040  * - when secondary kvm_s2_mmu structures are initialised for NV
1041  *   guests, and the caller must hold kvm->lock as this is called on a
1042  *   per-vcpu basis.
1043  */
1044 int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long type)
1045 {
1046 	int cpu, err;
1047 	struct kvm_pgtable *pgt;
1048 
1049 	/* Initialize the VM ops for the VM instance for the first time */
1050 	if (mmu == &kvm->arch.mmu) {
1051 		err = kvm_vm_init_vm_s2_ops(kvm);
1052 		if (err)
1053 			return err;
1054 	}
1055 	/*
1056 	 * If we already have our page tables in place, and that the
1057 	 * MMU context is the canonical one, we have a bug somewhere,
1058 	 * as this is only supposed to ever happen once per VM.
1059 	 *
1060 	 * Otherwise, we're building nested page tables, and that's
1061 	 * probably because userspace called KVM_ARM_VCPU_INIT more
1062 	 * than once on the same vcpu. Since that's actually legal,
1063 	 * don't kick a fuss and leave gracefully.
1064 	 */
1065 	if (mmu->pgt != NULL) {
1066 		if (kvm_is_nested_s2_mmu(kvm, mmu))
1067 			return 0;
1068 
1069 		kvm_err("kvm_arch already initialized?\n");
1070 		return -EINVAL;
1071 	}
1072 
1073 	err = kvm_init_ipa_range(mmu, type);
1074 	if (err)
1075 		return err;
1076 
1077 	pgt = kzalloc_obj(*pgt, GFP_KERNEL_ACCOUNT);
1078 	if (!pgt)
1079 		return -ENOMEM;
1080 
1081 	mmu->arch = &kvm->arch;
1082 	err = KVM_PGT_FN(kvm_pgtable_stage2_init)(pgt, mmu, &kvm_s2_mm_ops);
1083 	if (err)
1084 		goto out_free_pgtable;
1085 
1086 	mmu->pgt = pgt;
1087 	if (is_protected_kvm_enabled())
1088 		return 0;
1089 
1090 	mmu->last_vcpu_ran = alloc_percpu(typeof(*mmu->last_vcpu_ran));
1091 	if (!mmu->last_vcpu_ran) {
1092 		err = -ENOMEM;
1093 		goto out_destroy_pgtable;
1094 	}
1095 
1096 	for_each_possible_cpu(cpu)
1097 		*per_cpu_ptr(mmu->last_vcpu_ran, cpu) = -1;
1098 
1099 	 /* The eager page splitting is disabled by default */
1100 	mmu->split_page_chunk_size = KVM_ARM_EAGER_SPLIT_CHUNK_SIZE_DEFAULT;
1101 	mmu->split_page_cache.gfp_zero = __GFP_ZERO;
1102 
1103 	mmu->pgd_phys = __pa(pgt->pgd);
1104 
1105 	mmu->guest_s2_mappings = RB_ROOT_CACHED;
1106 
1107 	if (kvm_is_nested_s2_mmu(kvm, mmu))
1108 		kvm_init_nested_s2_mmu(mmu);
1109 
1110 	return 0;
1111 
1112 out_destroy_pgtable:
1113 	kvm_stage2_destroy(pgt);
1114 	mmu->pgt = NULL;
1115 out_free_pgtable:
1116 	kfree(pgt);
1117 	return err;
1118 }
1119 
1120 void kvm_uninit_stage2_mmu(struct kvm *kvm)
1121 {
1122 	kvm_free_stage2_pgd(&kvm->arch.mmu);
1123 	kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
1124 }
1125 
1126 static void stage2_unmap_memslot(struct kvm *kvm,
1127 				 struct kvm_memory_slot *memslot)
1128 {
1129 	hva_t hva = memslot->userspace_addr;
1130 	phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
1131 	phys_addr_t size = PAGE_SIZE * memslot->npages;
1132 	hva_t reg_end = hva + size;
1133 
1134 	/*
1135 	 * A memory region could potentially cover multiple VMAs, and any holes
1136 	 * between them, so iterate over all of them to find out if we should
1137 	 * unmap any of them.
1138 	 *
1139 	 *     +--------------------------------------------+
1140 	 * +---------------+----------------+   +----------------+
1141 	 * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
1142 	 * +---------------+----------------+   +----------------+
1143 	 *     |               memory region                |
1144 	 *     +--------------------------------------------+
1145 	 */
1146 	do {
1147 		struct vm_area_struct *vma;
1148 		hva_t vm_start, vm_end;
1149 
1150 		vma = find_vma_intersection(current->mm, hva, reg_end);
1151 		if (!vma)
1152 			break;
1153 
1154 		/*
1155 		 * Take the intersection of this VMA with the memory region
1156 		 */
1157 		vm_start = max(hva, vma->vm_start);
1158 		vm_end = min(reg_end, vma->vm_end);
1159 
1160 		if (!(vma->vm_flags & VM_PFNMAP)) {
1161 			gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
1162 			kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, vm_end - vm_start, true);
1163 		}
1164 		hva = vm_end;
1165 	} while (hva < reg_end);
1166 }
1167 
1168 /**
1169  * stage2_unmap_vm - Unmap Stage-2 RAM mappings
1170  * @kvm: The struct kvm pointer
1171  *
1172  * Go through the memregions and unmap any regular RAM
1173  * backing memory already mapped to the VM.
1174  */
1175 void stage2_unmap_vm(struct kvm *kvm)
1176 {
1177 	struct kvm_memslots *slots;
1178 	struct kvm_memory_slot *memslot;
1179 	int idx, bkt;
1180 
1181 	idx = srcu_read_lock(&kvm->srcu);
1182 	mmap_read_lock(current->mm);
1183 	write_lock(&kvm->mmu_lock);
1184 
1185 	slots = kvm_memslots(kvm);
1186 	kvm_for_each_memslot(memslot, bkt, slots)
1187 		stage2_unmap_memslot(kvm, memslot);
1188 
1189 	kvm_nested_s2_unmap(kvm, true);
1190 
1191 	write_unlock(&kvm->mmu_lock);
1192 	mmap_read_unlock(current->mm);
1193 	srcu_read_unlock(&kvm->srcu, idx);
1194 }
1195 
1196 static void guest_s2_tracking_destroy(struct rb_root_cached *tree)
1197 {
1198 	struct kvm_guest_s2_mapping *mapping;
1199 	struct interval_tree_node *node;
1200 
1201 	while ((node = interval_tree_iter_first(tree, 0, ULONG_MAX))) {
1202 		interval_tree_remove(node, tree);
1203 		mapping = container_of(node, struct kvm_guest_s2_mapping,
1204 				       canonical);
1205 		kfree(mapping);
1206 		cond_resched();
1207 	}
1208 }
1209 
1210 void kvm_free_stage2_pgd(struct kvm_s2_mmu *mmu)
1211 {
1212 	struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
1213 	struct kvm_pgtable *pgt = NULL;
1214 	struct rb_root_cached mappings_tree;
1215 
1216 	write_lock(&kvm->mmu_lock);
1217 	pgt = mmu->pgt;
1218 	if (pgt) {
1219 		mmu->pgd_phys = 0;
1220 		mmu->pgt = NULL;
1221 		free_percpu(mmu->last_vcpu_ran);
1222 	}
1223 
1224 	if (kvm_is_nested_s2_mmu(kvm, mmu))
1225 		kvm_init_nested_s2_mmu(mmu);
1226 
1227 	mappings_tree = mmu->guest_s2_mappings;
1228 	mmu->guest_s2_mappings = RB_ROOT_CACHED;
1229 
1230 	write_unlock(&kvm->mmu_lock);
1231 
1232 	if (pgt) {
1233 		kvm_stage2_destroy(pgt);
1234 		kfree(pgt);
1235 	}
1236 
1237 	if (!kvm_is_nested_s2_mmu(kvm, mmu))
1238 		guest_s2_tracking_destroy(&mappings_tree);
1239 }
1240 
1241 static void hyp_mc_free_fn(void *addr, void *mc)
1242 {
1243 	struct kvm_hyp_memcache *memcache = mc;
1244 
1245 	if (memcache->flags & HYP_MEMCACHE_ACCOUNT_STAGE2)
1246 		kvm_account_pgtable_pages(addr, -1);
1247 
1248 	free_page((unsigned long)addr);
1249 }
1250 
1251 static void *hyp_mc_alloc_fn(void *mc)
1252 {
1253 	struct kvm_hyp_memcache *memcache = mc;
1254 	void *addr;
1255 	gfp_t gfp;
1256 
1257 	gfp = memcache->flags & HYP_MEMCACHE_ACCOUNT_KMEMCG ? GFP_KERNEL_ACCOUNT : GFP_KERNEL;
1258 	addr = (void *)__get_free_page(gfp);
1259 	if (addr && memcache->flags & HYP_MEMCACHE_ACCOUNT_STAGE2)
1260 		kvm_account_pgtable_pages(addr, 1);
1261 
1262 	return addr;
1263 }
1264 
1265 void free_hyp_memcache(struct kvm_hyp_memcache *mc)
1266 {
1267 	if (!is_protected_kvm_enabled())
1268 		return;
1269 
1270 	kfree(mc->mapping);
1271 	__free_hyp_memcache(mc, hyp_mc_free_fn, kvm_host_va, mc);
1272 }
1273 
1274 int topup_hyp_memcache(struct kvm_hyp_memcache *mc, unsigned long min_pages)
1275 {
1276 	if (!is_protected_kvm_enabled())
1277 		return 0;
1278 
1279 	if (!mc->mapping) {
1280 		mc->mapping = kzalloc_obj(struct pkvm_mapping,
1281 					  GFP_KERNEL_ACCOUNT);
1282 		if (!mc->mapping)
1283 			return -ENOMEM;
1284 	}
1285 
1286 	return __topup_hyp_memcache(mc, min_pages, hyp_mc_alloc_fn,
1287 				    kvm_host_pa, mc);
1288 }
1289 
1290 /**
1291  * kvm_phys_addr_ioremap - map a device range to guest IPA
1292  *
1293  * @kvm:	The KVM pointer
1294  * @guest_ipa:	The IPA at which to insert the mapping
1295  * @pa:		The physical address of the device
1296  * @size:	The size of the mapping
1297  * @writable:   Whether or not to create a writable mapping
1298  */
1299 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
1300 			  phys_addr_t pa, unsigned long size, bool writable)
1301 {
1302 	phys_addr_t addr;
1303 	int ret = 0;
1304 	struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };
1305 	struct kvm_s2_mmu *mmu = &kvm->arch.mmu;
1306 	struct kvm_pgtable *pgt = mmu->pgt;
1307 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_DEVICE |
1308 				     KVM_PGTABLE_PROT_R |
1309 				     (writable ? KVM_PGTABLE_PROT_W : 0);
1310 
1311 	if (kvm_vm_hyp_is_distrusting(kvm))
1312 		return -EPERM;
1313 
1314 	size += offset_in_page(guest_ipa);
1315 	guest_ipa &= PAGE_MASK;
1316 
1317 	for (addr = guest_ipa; addr < guest_ipa + size; addr += PAGE_SIZE) {
1318 		ret = kvm_mmu_topup_memory_cache(&cache,
1319 						 kvm_mmu_cache_min_pages(mmu));
1320 		if (ret)
1321 			break;
1322 
1323 		write_lock(&kvm->mmu_lock);
1324 		ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, addr, PAGE_SIZE,
1325 				 pa, prot, &cache, 0);
1326 		write_unlock(&kvm->mmu_lock);
1327 		if (ret)
1328 			break;
1329 
1330 		pa += PAGE_SIZE;
1331 	}
1332 
1333 	kvm_mmu_free_memory_cache(&cache);
1334 	return ret;
1335 }
1336 
1337 /**
1338  * kvm_stage2_wp_range() - write protect stage2 memory region range
1339  * @mmu:        The KVM stage-2 MMU pointer
1340  * @addr:	Start address of range
1341  * @end:	End address of range
1342  */
1343 void kvm_stage2_wp_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
1344 {
1345 	stage2_apply_range_resched(mmu, addr, end, KVM_PGT_FN(kvm_pgtable_stage2_wrprotect));
1346 }
1347 
1348 /**
1349  * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
1350  * @kvm:	The KVM pointer
1351  * @slot:	The memory slot to write protect
1352  *
1353  * Called to start logging dirty pages after memory region
1354  * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
1355  * all present PUD, PMD and PTEs are write protected in the memory region.
1356  * Afterwards read of dirty page log can be called.
1357  *
1358  * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
1359  * serializing operations for VM memory regions.
1360  */
1361 static void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
1362 {
1363 	struct kvm_memslots *slots = kvm_memslots(kvm);
1364 	struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
1365 	phys_addr_t start, end;
1366 
1367 	if (WARN_ON_ONCE(!memslot))
1368 		return;
1369 
1370 	start = memslot->base_gfn << PAGE_SHIFT;
1371 	end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
1372 
1373 	write_lock(&kvm->mmu_lock);
1374 	kvm_stage2_wp_range(&kvm->arch.mmu, start, end);
1375 	kvm_nested_s2_wp(kvm);
1376 	write_unlock(&kvm->mmu_lock);
1377 	kvm_flush_remote_tlbs_memslot(kvm, memslot);
1378 }
1379 
1380 /**
1381  * kvm_mmu_split_memory_region() - split the stage 2 blocks into PAGE_SIZE
1382  *				   pages for memory slot
1383  * @kvm:	The KVM pointer
1384  * @slot:	The memory slot to split
1385  *
1386  * Acquires kvm->mmu_lock. Called with kvm->slots_lock mutex acquired,
1387  * serializing operations for VM memory regions.
1388  */
1389 static void kvm_mmu_split_memory_region(struct kvm *kvm, int slot)
1390 {
1391 	struct kvm_memslots *slots;
1392 	struct kvm_memory_slot *memslot;
1393 	phys_addr_t start, end;
1394 
1395 	lockdep_assert_held(&kvm->slots_lock);
1396 
1397 	slots = kvm_memslots(kvm);
1398 	memslot = id_to_memslot(slots, slot);
1399 
1400 	start = memslot->base_gfn << PAGE_SHIFT;
1401 	end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
1402 
1403 	write_lock(&kvm->mmu_lock);
1404 	kvm_mmu_split_huge_pages(kvm, start, end);
1405 	write_unlock(&kvm->mmu_lock);
1406 }
1407 
1408 /*
1409  * kvm_arch_mmu_enable_log_dirty_pt_masked() - enable dirty logging for selected pages.
1410  * @kvm:	The KVM pointer
1411  * @slot:	The memory slot associated with mask
1412  * @gfn_offset:	The gfn offset in memory slot
1413  * @mask:	The mask of pages at offset 'gfn_offset' in this memory
1414  *		slot to enable dirty logging on
1415  *
1416  * Writes protect selected pages to enable dirty logging, and then
1417  * splits them to PAGE_SIZE. Caller must acquire kvm->mmu_lock.
1418  */
1419 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1420 		struct kvm_memory_slot *slot,
1421 		gfn_t gfn_offset, unsigned long mask)
1422 {
1423 	phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
1424 	phys_addr_t start = (base_gfn +  __ffs(mask)) << PAGE_SHIFT;
1425 	phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
1426 
1427 	lockdep_assert_held_write(&kvm->mmu_lock);
1428 
1429 	kvm_stage2_wp_range(&kvm->arch.mmu, start, end);
1430 
1431 	/*
1432 	 * Eager-splitting is done when manual-protect is set.  We
1433 	 * also check for initially-all-set because we can avoid
1434 	 * eager-splitting if initially-all-set is false.
1435 	 * Initially-all-set equal false implies that huge-pages were
1436 	 * already split when enabling dirty logging: no need to do it
1437 	 * again.
1438 	 */
1439 	if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1440 		kvm_mmu_split_huge_pages(kvm, start, end);
1441 
1442 	kvm_nested_s2_wp(kvm);
1443 }
1444 
1445 static void kvm_send_hwpoison_signal(unsigned long address, short lsb)
1446 {
1447 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, current);
1448 }
1449 
1450 struct kvm_s2_fault_desc {
1451 	struct kvm_vcpu		*vcpu;
1452 	phys_addr_t		fault_ipa;
1453 	struct kvm_s2_trans	*nested;
1454 	struct kvm_memory_slot	*memslot;
1455 	unsigned long		hva;
1456 	unsigned long		esr;
1457 	struct kvm_s2_mmu	*mmu;
1458 };
1459 
1460 struct kvm_s2_fault_vma_info {
1461 	unsigned long	mmu_seq;
1462 	long		vma_pagesize;
1463 	vm_flags_t	vm_flags;
1464 	unsigned long	max_map_size;
1465 	struct page	*page;
1466 	kvm_pfn_t	pfn;
1467 	gfn_t		gfn;
1468 	bool		device;
1469 	bool		mte_allowed;
1470 	bool		is_vma_cacheable;
1471 	bool		map_writable;
1472 	bool		map_non_cacheable;
1473 };
1474 
1475 struct kvm_s2_fault_result {
1476 	unsigned long mapping_size;
1477 };
1478 
1479 static bool fault_supports_stage2_huge_mapping(const struct kvm_s2_fault_desc *s2fd,
1480 					       unsigned long map_size)
1481 {
1482 	struct kvm_memory_slot *memslot = s2fd->memslot;
1483 	unsigned long hva = s2fd->hva;
1484 	hva_t uaddr_start, uaddr_end;
1485 	gpa_t gpa_start;
1486 	size_t size;
1487 
1488 	/* The memslot and the VMA are guaranteed to be aligned to PAGE_SIZE */
1489 	if (map_size == PAGE_SIZE)
1490 		return true;
1491 
1492 	/* pKVM only supports PMD_SIZE huge-mappings for non-protected VMs */
1493 	if (is_protected_kvm_enabled()) {
1494 		if (vcpu_is_protected(s2fd->vcpu) || map_size != PMD_SIZE)
1495 			return false;
1496 	}
1497 
1498 	size = memslot->npages * PAGE_SIZE;
1499 
1500 	gpa_start = memslot->base_gfn << PAGE_SHIFT;
1501 
1502 	uaddr_start = memslot->userspace_addr;
1503 	uaddr_end = uaddr_start + size;
1504 
1505 	/*
1506 	 * Pages belonging to memslots that don't have the same alignment
1507 	 * within a PMD/PUD for userspace and IPA cannot be mapped with stage-2
1508 	 * PMD/PUD entries, because we'll end up mapping the wrong pages.
1509 	 *
1510 	 * Consider a layout like the following:
1511 	 *
1512 	 *    memslot->userspace_addr:
1513 	 *    +-----+--------------------+--------------------+---+
1514 	 *    |abcde|fgh  Stage-1 block  |    Stage-1 block tv|xyz|
1515 	 *    +-----+--------------------+--------------------+---+
1516 	 *
1517 	 *    memslot->base_gfn << PAGE_SHIFT:
1518 	 *      +---+--------------------+--------------------+-----+
1519 	 *      |abc|def  Stage-2 block  |    Stage-2 block   |tvxyz|
1520 	 *      +---+--------------------+--------------------+-----+
1521 	 *
1522 	 * If we create those stage-2 blocks, we'll end up with this incorrect
1523 	 * mapping:
1524 	 *   d -> f
1525 	 *   e -> g
1526 	 *   f -> h
1527 	 */
1528 	if ((gpa_start & (map_size - 1)) != (uaddr_start & (map_size - 1)))
1529 		return false;
1530 
1531 	/*
1532 	 * Next, let's make sure we're not trying to map anything not covered
1533 	 * by the memslot. This means we have to prohibit block size mappings
1534 	 * for the beginning and end of a non-block aligned and non-block sized
1535 	 * memory slot (illustrated by the head and tail parts of the
1536 	 * userspace view above containing pages 'abcde' and 'xyz',
1537 	 * respectively).
1538 	 *
1539 	 * Note that it doesn't matter if we do the check using the
1540 	 * userspace_addr or the base_gfn, as both are equally aligned (per
1541 	 * the check above) and equally sized.
1542 	 */
1543 	return (hva & ~(map_size - 1)) >= uaddr_start &&
1544 	       (hva & ~(map_size - 1)) + map_size <= uaddr_end;
1545 }
1546 
1547 /*
1548  * Check if the given hva is backed by a transparent huge page (THP) and
1549  * whether it can be mapped using block mapping in stage2. If so, adjust
1550  * the stage2 PFN and IPA accordingly. Only PMD_SIZE THPs are currently
1551  * supported. This will need to be updated to support other THP sizes.
1552  *
1553  * Returns the size of the mapping.
1554  */
1555 static long
1556 transparent_hugepage_adjust(const struct kvm_s2_fault_desc *s2fd, kvm_pfn_t *pfnp, gfn_t *gfnp)
1557 {
1558 	struct kvm *kvm = s2fd->vcpu->kvm;
1559 	kvm_pfn_t pfn = *pfnp;
1560 	gfn_t gfn = *gfnp;
1561 
1562 	/*
1563 	 * Make sure the adjustment is done only for THP pages. Also make
1564 	 * sure that the HVA and IPA are sufficiently aligned and that the
1565 	 * block map is contained within the memslot.
1566 	 */
1567 	if (fault_supports_stage2_huge_mapping(s2fd, PMD_SIZE)) {
1568 		int sz = get_user_mapping_size(kvm, s2fd->hva);
1569 
1570 		if (sz < 0)
1571 			return sz;
1572 
1573 		if (sz < PMD_SIZE)
1574 			return PAGE_SIZE;
1575 
1576 		gfn &= ~(PTRS_PER_PMD - 1);
1577 		*gfnp = gfn;
1578 		pfn &= ~(PTRS_PER_PMD - 1);
1579 		*pfnp = pfn;
1580 
1581 		return PMD_SIZE;
1582 	}
1583 
1584 	/* Use page mapping if we cannot use block mapping. */
1585 	return PAGE_SIZE;
1586 }
1587 
1588 static int get_vma_page_shift(struct vm_area_struct *vma)
1589 {
1590 	if (vma_is_hugetlb(vma))
1591 		return huge_page_shift(hstate_vma(vma));
1592 
1593 	return PAGE_SHIFT;
1594 }
1595 
1596 /*
1597  * The page will be mapped in stage 2 as Normal Cacheable, so the VM will be
1598  * able to see the page's tags and therefore they must be initialised first. If
1599  * PG_mte_tagged is set, tags have already been initialised.
1600  *
1601  * Must be called with kvm->mmu_lock held to ensure the memory remains mapped
1602  * while the tags are zeroed.
1603  */
1604 static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn,
1605 			      unsigned long size)
1606 {
1607 	unsigned long i, nr_pages = size >> PAGE_SHIFT;
1608 	struct page *page = pfn_to_page(pfn);
1609 	struct folio *folio = page_folio(page);
1610 
1611 	if (!kvm_has_mte(kvm))
1612 		return;
1613 
1614 	if (is_zero_pfn(pfn)) {
1615 		WARN_ON_ONCE(nr_pages != 1);
1616 		return;
1617 	}
1618 
1619 	if (folio_test_hugetlb(folio)) {
1620 		/* Hugetlb has MTE flags set on head page only */
1621 		if (folio_try_hugetlb_mte_tagging(folio)) {
1622 			for (i = 0; i < nr_pages; i++, page++)
1623 				mte_clear_page_tags(page_address(page));
1624 			folio_set_hugetlb_mte_tagged(folio);
1625 		}
1626 		return;
1627 	}
1628 
1629 	for (i = 0; i < nr_pages; i++, page++) {
1630 		if (try_page_mte_tagging(page)) {
1631 			mte_clear_page_tags(page_address(page));
1632 			set_page_mte_tagged(page);
1633 		}
1634 	}
1635 }
1636 
1637 static bool kvm_vma_mte_allowed(struct vm_area_struct *vma)
1638 {
1639 	return vma->vm_flags & VM_MTE_ALLOWED;
1640 }
1641 
1642 static bool kvm_vma_is_cacheable(struct vm_area_struct *vma)
1643 {
1644 	switch (FIELD_GET(PTE_ATTRINDX_MASK, pgprot_val(vma->vm_page_prot))) {
1645 	case MT_NORMAL_NC:
1646 	case MT_DEVICE_nGnRnE:
1647 	case MT_DEVICE_nGnRE:
1648 		return false;
1649 	default:
1650 		return true;
1651 	}
1652 }
1653 
1654 static void *get_mmu_memcache(struct kvm_vcpu *vcpu)
1655 {
1656 	if (!is_protected_kvm_enabled())
1657 		return &vcpu->arch.mmu_page_cache;
1658 	else
1659 		return &vcpu->arch.stage2_mc;
1660 }
1661 
1662 static int topup_mmu_memcache(struct kvm_s2_mmu *mmu, void *memcache)
1663 {
1664 	int min_pages = kvm_mmu_cache_min_pages(mmu);
1665 
1666 	if (!is_protected_kvm_enabled())
1667 		return kvm_mmu_topup_memory_cache(memcache, min_pages);
1668 
1669 	return topup_hyp_memcache(memcache, min_pages);
1670 }
1671 
1672 /*
1673  * Potentially reduce shadow S2 permissions to match the guest's own S2. For
1674  * exec faults, we'd only reach this point if the guest actually allowed it (see
1675  * kvm_s2_handle_perm_fault).
1676  *
1677  * Also encode the level of the original translation in the SW bits of the leaf
1678  * entry as a proxy for the span of that translation. This will be retrieved on
1679  * TLB invalidation from the guest and used to limit the invalidation scope if a
1680  * TTL hint or a range isn't provided.
1681  */
1682 static enum kvm_pgtable_prot adjust_nested_fault_perms(struct kvm_s2_trans *nested,
1683 						       enum kvm_pgtable_prot prot)
1684 {
1685 	if (!kvm_s2_trans_writable(nested))
1686 		prot &= ~KVM_PGTABLE_PROT_W;
1687 	if (!kvm_s2_trans_readable(nested))
1688 		prot &= ~KVM_PGTABLE_PROT_R;
1689 
1690 	return prot | kvm_encode_nested_level(nested);
1691 }
1692 
1693 static enum kvm_pgtable_prot adjust_nested_exec_perms(struct kvm *kvm,
1694 						      struct kvm_s2_trans *nested,
1695 						      enum kvm_pgtable_prot prot)
1696 {
1697 	if (!kvm_s2_trans_exec_el0(kvm, nested))
1698 		prot &= ~KVM_PGTABLE_PROT_UX;
1699 	if (!kvm_s2_trans_exec_el1(kvm, nested))
1700 		prot &= ~KVM_PGTABLE_PROT_PX;
1701 
1702 	return prot;
1703 }
1704 
1705 static bool kvm_s2_fault_is_perm(const struct kvm_s2_fault_desc *s2fd)
1706 {
1707 	return esr_fsc_is_permission_fault(s2fd->esr);
1708 }
1709 
1710 static bool kvm_s2_fault_is_exec(const struct kvm_s2_fault_desc *s2fd)
1711 {
1712 	return esr_abt_is_exec_fault(s2fd->esr);
1713 }
1714 
1715 static bool kvm_s2_fault_is_write(const struct kvm_s2_fault_desc *s2fd)
1716 {
1717 	return esr_abt_is_write_fault(s2fd->esr);
1718 }
1719 
1720 static u64 kvm_s2_perm_fault_granule(const struct kvm_s2_fault_desc *s2fd)
1721 {
1722 	u64 level;
1723 
1724 	if (!kvm_s2_fault_is_perm(s2fd))
1725 		return 0;
1726 	level = s2fd->esr & ESR_ELx_FSC_LEVEL;
1727 	return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(level));
1728 }
1729 
1730 static int kvm_s2_fault_get_vma_info(const struct kvm_s2_fault_desc *s2fd,
1731 				     struct kvm_s2_fault_vma_info *s2vi);
1732 
1733 static gfn_t get_canonical_gfn(const struct kvm_s2_fault_desc *s2fd,
1734 			       const struct kvm_s2_fault_vma_info *s2vi);
1735 
1736 static int gmem_abort(const struct kvm_s2_fault_desc *s2fd,
1737 		      struct kvm_s2_fault_result *result)
1738 {
1739 	bool write_fault, exec_fault;
1740 	bool perm_fault = kvm_s2_fault_is_perm(s2fd);
1741 	enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
1742 	enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
1743 	struct kvm_pgtable *pgt = s2fd->mmu->pgt;
1744 	struct kvm_guest_s2_mapping *mapping = NULL;
1745 	struct kvm_s2_fault_vma_info s2vi = {};
1746 	struct kvm *kvm = s2fd->vcpu->kvm;
1747 	void *memcache = NULL;
1748 	gfn_t canonical_gfn;
1749 	int ret;
1750 
1751 	if (!perm_fault) {
1752 		memcache = get_mmu_memcache(s2fd->vcpu);
1753 		ret = topup_mmu_memcache(s2fd->mmu, memcache);
1754 		if (ret)
1755 			return ret;
1756 		if (kvm_is_nested_s2_mmu(kvm, pgt->mmu)) {
1757 			mapping = kmalloc_obj(struct kvm_guest_s2_mapping, GFP_KERNEL_ACCOUNT);
1758 			if (!mapping)
1759 				return -ENOMEM;
1760 		}
1761 	}
1762 
1763 	s2vi.vma_pagesize = PAGE_SIZE;
1764 	s2vi.gfn = ALIGN_DOWN(s2fd->fault_ipa, s2vi.vma_pagesize) >> PAGE_SHIFT;
1765 	canonical_gfn = get_canonical_gfn(s2fd, &s2vi);
1766 
1767 	write_fault = kvm_s2_fault_is_write(s2fd);
1768 	exec_fault = kvm_s2_fault_is_exec(s2fd);
1769 
1770 	VM_WARN_ON_ONCE(write_fault && exec_fault);
1771 
1772 	s2vi.mmu_seq = kvm->mmu_invalidate_seq;
1773 	/* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
1774 	smp_rmb();
1775 
1776 	ret = kvm_gmem_get_pfn(kvm, s2fd->memslot, canonical_gfn, &s2vi.pfn, NULL);
1777 	if (ret) {
1778 		/* If result is non-NULL this is a synthetic fault. */
1779 		if (!result)
1780 			kvm_prepare_memory_fault_exit(s2fd->vcpu, gfn_to_gpa(canonical_gfn),
1781 						      s2vi.vma_pagesize, write_fault, exec_fault,
1782 						      false);
1783 		kfree(mapping);
1784 		return ret;
1785 	}
1786 
1787 	if (!(s2fd->memslot->flags & KVM_MEM_READONLY))
1788 		prot |= KVM_PGTABLE_PROT_W;
1789 
1790 	if (s2fd->nested)
1791 		prot = adjust_nested_fault_perms(s2fd->nested, prot);
1792 
1793 	if (exec_fault || cpus_have_final_cap(ARM64_HAS_CACHE_DIC))
1794 		prot |= KVM_PGTABLE_PROT_X;
1795 
1796 	if (s2fd->nested)
1797 		prot = adjust_nested_exec_perms(kvm, s2fd->nested, prot);
1798 
1799 	kvm_fault_lock(kvm);
1800 	if (mmu_invalidate_retry(kvm, s2vi.mmu_seq)) {
1801 		ret = -EAGAIN;
1802 		goto out_unlock;
1803 	}
1804 
1805 	if (perm_fault) {
1806 		/*
1807 		 * Drop the SW bits in favour of those stored in the
1808 		 * PTE, which will be preserved.
1809 		 */
1810 		prot &= ~KVM_NV_GUEST_MAP_SZ;
1811 		ret = KVM_PGT_FN(kvm_pgtable_stage2_relax_perms)(pgt, gfn_to_gpa(s2vi.gfn),
1812 								 prot, flags);
1813 	} else {
1814 		ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, gfn_to_gpa(s2vi.gfn),
1815 							 s2vi.vma_pagesize,
1816 							 __pfn_to_phys(s2vi.pfn), prot,
1817 							 memcache, flags);
1818 		/*
1819 		 * -EAGAIN from kvm_pgtable_stage2_map() can install mappings.
1820 		 * We don't know which subrange is installed, track the whole
1821 		 * thing.
1822 		 */
1823 		if ((ret == 0 || ret == -EAGAIN) && kvm_is_nested_s2_mmu(kvm, pgt->mmu)) {
1824 			kvm_record_guest_s2_mapping(pgt->mmu, canonical_gfn << PAGE_SHIFT,
1825 						    s2fd->fault_ipa, s2vi.vma_pagesize, mapping);
1826 			mapping = NULL;
1827 		}
1828 	}
1829 
1830 out_unlock:
1831 	kvm_fault_unlock(kvm);
1832 	kfree(mapping);
1833 
1834 	if ((prot & KVM_PGTABLE_PROT_W) && !ret)
1835 		mark_page_dirty_in_slot(kvm, s2fd->memslot, canonical_gfn);
1836 
1837 	if (ret == -EAGAIN)
1838 		return result ? ret : 0;
1839 
1840 	if (result && !ret)
1841 		result->mapping_size = s2vi.vma_pagesize;
1842 
1843 	return ret;
1844 }
1845 
1846 static int protected_pkvm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
1847 {
1848 	unsigned int flags = FOLL_HWPOISON | FOLL_LONGTERM | FOLL_WRITE;
1849 	struct kvm_s2_fault_vma_info s2vi = {};
1850 	struct kvm_vcpu *vcpu = s2fd->vcpu;
1851 	struct kvm_pgtable *pgt = s2fd->mmu->pgt;
1852 	struct mm_struct *mm = current->mm;
1853 	struct kvm *kvm = vcpu->kvm;
1854 	void *hyp_memcache;
1855 	int ret;
1856 
1857 	hyp_memcache = get_mmu_memcache(vcpu);
1858 	ret = topup_mmu_memcache(s2fd->mmu, hyp_memcache);
1859 	if (ret)
1860 		return -ENOMEM;
1861 
1862 	ret = kvm_s2_fault_get_vma_info(s2fd, &s2vi);
1863 	if (ret)
1864 		return ret;
1865 
1866 	ret = account_locked_vm(mm, 1, true);
1867 	if (ret)
1868 		return ret;
1869 
1870 	mmap_read_lock(mm);
1871 	ret = pin_user_pages(s2fd->hva, 1, flags, &s2vi.page);
1872 	mmap_read_unlock(mm);
1873 
1874 	if (ret == -EHWPOISON) {
1875 		kvm_send_hwpoison_signal(s2fd->hva, PAGE_SHIFT);
1876 		ret = 0;
1877 		goto dec_account;
1878 	} else if (ret != 1) {
1879 		ret = -EFAULT;
1880 		goto dec_account;
1881 	} else if (!folio_test_swapbacked(page_folio(s2vi.page))) {
1882 		/*
1883 		 * We really can't deal with page-cache pages returned by GUP
1884 		 * because (a) we may trigger writeback of a page for which we
1885 		 * no longer have access and (b) page_mkclean() won't find the
1886 		 * stage-2 mapping in the rmap so we can get out-of-whack with
1887 		 * the filesystem when marking the page dirty during unpinning
1888 		 * (see cc5095747edf ("ext4: don't BUG if someone dirty pages
1889 		 * without asking ext4 first")).
1890 		 *
1891 		 * Ideally we'd just restrict ourselves to anonymous pages, but
1892 		 * we also want to allow memfd (i.e. shmem) pages, so check for
1893 		 * pages backed by swap in the knowledge that the GUP pin will
1894 		 * prevent try_to_unmap() from succeeding.
1895 		 */
1896 		ret = -EIO;
1897 		goto unpin;
1898 	}
1899 
1900 	write_lock(&kvm->mmu_lock);
1901 	ret = pkvm_pgtable_stage2_map(pgt, gfn_to_gpa(s2vi.gfn), PAGE_SIZE,
1902 				      page_to_phys(s2vi.page), KVM_PGTABLE_PROT_RWX,
1903 				      hyp_memcache, 0);
1904 	write_unlock(&kvm->mmu_lock);
1905 	if (ret) {
1906 		if (ret == -EAGAIN)
1907 			ret = 0;
1908 		goto unpin;
1909 	}
1910 
1911 	return 0;
1912 unpin:
1913 	unpin_user_page(s2vi.page);
1914 dec_account:
1915 	account_locked_vm(mm, 1, false);
1916 	return ret;
1917 }
1918 
1919 static short kvm_s2_resolve_vma_size(const struct kvm_s2_fault_desc *s2fd,
1920 				     struct kvm_s2_fault_vma_info *s2vi,
1921 				     struct vm_area_struct *vma)
1922 {
1923 	short vma_shift;
1924 
1925 	if (memslot_is_logging(s2fd->memslot)) {
1926 		s2vi->max_map_size = PAGE_SIZE;
1927 		vma_shift = PAGE_SHIFT;
1928 	} else {
1929 		s2vi->max_map_size = PUD_SIZE;
1930 		vma_shift = get_vma_page_shift(vma);
1931 	}
1932 
1933 	switch (vma_shift) {
1934 #ifndef __PAGETABLE_PMD_FOLDED
1935 	case PUD_SHIFT:
1936 		if (fault_supports_stage2_huge_mapping(s2fd, PUD_SIZE))
1937 			break;
1938 		fallthrough;
1939 #endif
1940 	case CONT_PMD_SHIFT:
1941 		vma_shift = PMD_SHIFT;
1942 		fallthrough;
1943 	case PMD_SHIFT:
1944 		if (fault_supports_stage2_huge_mapping(s2fd, PMD_SIZE))
1945 			break;
1946 		fallthrough;
1947 	case CONT_PTE_SHIFT:
1948 		vma_shift = PAGE_SHIFT;
1949 		s2vi->max_map_size = PAGE_SIZE;
1950 		fallthrough;
1951 	case PAGE_SHIFT:
1952 		break;
1953 	default:
1954 		WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
1955 	}
1956 
1957 	if (s2fd->nested) {
1958 		unsigned long max_map_size;
1959 
1960 		max_map_size = min(s2vi->max_map_size, PUD_SIZE);
1961 
1962 		/*
1963 		 * If we're about to create a shadow stage 2 entry, then we
1964 		 * can only create a block mapping if the guest stage 2 page
1965 		 * table uses at least as big a mapping.
1966 		 */
1967 		max_map_size = min(kvm_s2_trans_size(s2fd->nested), max_map_size);
1968 
1969 		/*
1970 		 * Be careful that if the mapping size falls between
1971 		 * two host sizes, take the smallest of the two.
1972 		 */
1973 		if (max_map_size >= PMD_SIZE && max_map_size < PUD_SIZE)
1974 			max_map_size = PMD_SIZE;
1975 		else if (max_map_size >= PAGE_SIZE && max_map_size < PMD_SIZE)
1976 			max_map_size = PAGE_SIZE;
1977 
1978 		s2vi->max_map_size = max_map_size;
1979 		vma_shift = min_t(short, vma_shift, __ffs(max_map_size));
1980 	}
1981 
1982 	return vma_shift;
1983 }
1984 
1985 static int kvm_s2_fault_get_vma_info(const struct kvm_s2_fault_desc *s2fd,
1986 				     struct kvm_s2_fault_vma_info *s2vi)
1987 {
1988 	struct vm_area_struct *vma;
1989 	struct kvm *kvm = s2fd->vcpu->kvm;
1990 
1991 	mmap_read_lock(current->mm);
1992 	vma = vma_lookup(current->mm, s2fd->hva);
1993 	if (unlikely(!vma)) {
1994 		kvm_err("Failed to find VMA for hva 0x%lx\n", s2fd->hva);
1995 		mmap_read_unlock(current->mm);
1996 		return -EFAULT;
1997 	}
1998 
1999 	s2vi->vma_pagesize = BIT(kvm_s2_resolve_vma_size(s2fd, s2vi, vma));
2000 
2001 	/*
2002 	 * Both the canonical IPA and fault IPA must be aligned to the
2003 	 * mapping size to ensure we find the right PFN and lay down the
2004 	 * mapping in the right place.
2005 	 */
2006 	s2vi->gfn = ALIGN_DOWN(s2fd->fault_ipa, s2vi->vma_pagesize) >> PAGE_SHIFT;
2007 
2008 	s2vi->mte_allowed = kvm_vma_mte_allowed(vma);
2009 
2010 	s2vi->vm_flags = vma->vm_flags;
2011 
2012 	s2vi->is_vma_cacheable = kvm_vma_is_cacheable(vma);
2013 
2014 	/*
2015 	 * Read mmu_invalidate_seq so that KVM can detect if the results of
2016 	 * vma_lookup() or __kvm_faultin_pfn() become stale prior to
2017 	 * acquiring kvm->mmu_lock.
2018 	 *
2019 	 * Rely on mmap_read_unlock() for an implicit smp_rmb(), which pairs
2020 	 * with the smp_wmb() in kvm_mmu_invalidate_end().
2021 	 */
2022 	s2vi->mmu_seq = kvm->mmu_invalidate_seq;
2023 	mmap_read_unlock(current->mm);
2024 
2025 	return 0;
2026 }
2027 
2028 static gfn_t get_canonical_gfn(const struct kvm_s2_fault_desc *s2fd,
2029 			       const struct kvm_s2_fault_vma_info *s2vi)
2030 {
2031 	phys_addr_t ipa;
2032 
2033 	if (!s2fd->nested)
2034 		return s2vi->gfn;
2035 
2036 	ipa = kvm_s2_trans_output(s2fd->nested);
2037 	return ALIGN_DOWN(ipa, s2vi->vma_pagesize) >> PAGE_SHIFT;
2038 }
2039 
2040 static int kvm_s2_fault_pin_pfn(const struct kvm_s2_fault_desc *s2fd,
2041 				struct kvm_s2_fault_vma_info *s2vi)
2042 {
2043 	int ret;
2044 
2045 	ret = kvm_s2_fault_get_vma_info(s2fd, s2vi);
2046 	if (ret)
2047 		return ret;
2048 
2049 	s2vi->pfn = __kvm_faultin_pfn(s2fd->memslot, get_canonical_gfn(s2fd, s2vi),
2050 				      kvm_s2_fault_is_write(s2fd) ? FOLL_WRITE : 0,
2051 				      &s2vi->map_writable, &s2vi->page);
2052 	if (unlikely(is_error_noslot_pfn(s2vi->pfn))) {
2053 		if (s2vi->pfn == KVM_PFN_ERR_HWPOISON)
2054 			return -EHWPOISON;
2055 		return -EFAULT;
2056 	}
2057 
2058 	/*
2059 	 * Check if this is non-struct page memory PFN, and cannot support
2060 	 * CMOs. It could potentially be unsafe to access as cacheable.
2061 	 */
2062 	if (s2vi->vm_flags & (VM_PFNMAP | VM_MIXEDMAP) && !pfn_is_map_memory(s2vi->pfn)) {
2063 		if (s2vi->is_vma_cacheable) {
2064 			/*
2065 			 * Whilst the VMA owner expects cacheable mapping to this
2066 			 * PFN, hardware also has to support the FWB and CACHE DIC
2067 			 * features.
2068 			 *
2069 			 * ARM64 KVM relies on kernel VA mapping to the PFN to
2070 			 * perform cache maintenance as the CMO instructions work on
2071 			 * virtual addresses. VM_PFNMAP region are not necessarily
2072 			 * mapped to a KVA and hence the presence of hardware features
2073 			 * S2FWB and CACHE DIC are mandatory to avoid the need for
2074 			 * cache maintenance.
2075 			 */
2076 			if (!kvm_supports_cacheable_pfnmap()) {
2077 				kvm_release_faultin_page(s2fd->vcpu->kvm, s2vi->page, true, false);
2078 				return -EFAULT;
2079 			}
2080 		} else {
2081 			s2vi->map_non_cacheable = true;
2082 		}
2083 
2084 		s2vi->device = true;
2085 	}
2086 
2087 	return 1;
2088 }
2089 
2090 static int kvm_s2_fault_compute_prot(const struct kvm_s2_fault_desc *s2fd,
2091 				     const struct kvm_s2_fault_vma_info *s2vi,
2092 				     enum kvm_pgtable_prot *prot)
2093 {
2094 	struct kvm *kvm = s2fd->vcpu->kvm;
2095 
2096 	if (kvm_s2_fault_is_exec(s2fd) && s2vi->map_non_cacheable)
2097 		return -ENOEXEC;
2098 
2099 	/*
2100 	 * Guest performs atomic/exclusive operations on memory with unsupported
2101 	 * attributes (e.g. ld64b/st64b on normal memory when no FEAT_LS64WB)
2102 	 * and trigger the exception here. Since the memslot is valid, inject
2103 	 * the fault back to the guest.
2104 	 */
2105 	if (esr_fsc_is_excl_atomic_fault(s2fd->esr)) {
2106 		kvm_inject_dabt_excl_atomic(s2fd->vcpu, kvm_vcpu_get_hfar(s2fd->vcpu));
2107 		return 1;
2108 	}
2109 
2110 	*prot = KVM_PGTABLE_PROT_R;
2111 
2112 	if (s2vi->map_writable && (s2vi->device ||
2113 				   !memslot_is_logging(s2fd->memslot) ||
2114 				   kvm_s2_fault_is_write(s2fd)))
2115 		*prot |= KVM_PGTABLE_PROT_W;
2116 
2117 	if (s2fd->nested)
2118 		*prot = adjust_nested_fault_perms(s2fd->nested, *prot);
2119 
2120 	if (kvm_s2_fault_is_exec(s2fd))
2121 		*prot |= KVM_PGTABLE_PROT_X;
2122 
2123 	if (s2vi->map_non_cacheable)
2124 		*prot |= (s2vi->vm_flags & VM_ALLOW_ANY_UNCACHED) ?
2125 			KVM_PGTABLE_PROT_NORMAL_NC : KVM_PGTABLE_PROT_DEVICE;
2126 	else if (cpus_have_final_cap(ARM64_HAS_CACHE_DIC))
2127 		*prot |= KVM_PGTABLE_PROT_X;
2128 
2129 	if (s2fd->nested)
2130 		*prot = adjust_nested_exec_perms(kvm, s2fd->nested, *prot);
2131 
2132 	if (!kvm_s2_fault_is_perm(s2fd) && !s2vi->map_non_cacheable && kvm_has_mte(kvm)) {
2133 		/* Check the VMM hasn't introduced a new disallowed VMA */
2134 		if (!s2vi->mte_allowed)
2135 			return -EFAULT;
2136 	}
2137 
2138 	return 0;
2139 }
2140 
2141 static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd,
2142 			    const struct kvm_s2_fault_vma_info *s2vi,
2143 			    enum kvm_pgtable_prot prot,
2144 			    void *memcache,
2145 			    struct kvm_s2_fault_result *result)
2146 {
2147 	enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
2148 	struct kvm_guest_s2_mapping *mapping = NULL;
2149 	bool writable = prot & KVM_PGTABLE_PROT_W;
2150 	struct kvm *kvm = s2fd->vcpu->kvm;
2151 	phys_addr_t canonical_ipa;
2152 	struct kvm_pgtable *pgt;
2153 	long perm_fault_granule;
2154 	long mapping_size;
2155 	kvm_pfn_t pfn;
2156 	gfn_t gfn;
2157 	int ret;
2158 
2159 	if (kvm_is_nested_s2_mmu(kvm, s2fd->mmu)) {
2160 		mapping = kmalloc_obj(struct kvm_guest_s2_mapping,
2161 				      GFP_KERNEL_ACCOUNT);
2162 		if (!mapping) {
2163 			kvm_release_page_unused(s2vi->page);
2164 			return -ENOMEM;
2165 		}
2166 	}
2167 
2168 	kvm_fault_lock(kvm);
2169 	pgt = s2fd->mmu->pgt;
2170 	ret = -EAGAIN;
2171 	if (mmu_invalidate_retry(kvm, s2vi->mmu_seq))
2172 		goto out_unlock;
2173 
2174 	perm_fault_granule = kvm_s2_perm_fault_granule(s2fd);
2175 	mapping_size = s2vi->vma_pagesize;
2176 	pfn = s2vi->pfn;
2177 	gfn = s2vi->gfn;
2178 	canonical_ipa = gfn_to_gpa(get_canonical_gfn(s2fd, s2vi));
2179 
2180 	/*
2181 	 * If we are not forced to use page mapping, check if we are
2182 	 * backed by a huge stage-1 mapping and thus use block mapping if
2183 	 * possible.
2184 	 */
2185 	if (mapping_size == PAGE_SIZE && s2vi->max_map_size != PAGE_SIZE) {
2186 		if (perm_fault_granule > PAGE_SIZE) {
2187 			mapping_size = perm_fault_granule;
2188 		} else {
2189 			mapping_size = transparent_hugepage_adjust(s2fd, &pfn, &gfn);
2190 			if (mapping_size < 0) {
2191 				ret = mapping_size;
2192 				goto out_unlock;
2193 			}
2194 		}
2195 		canonical_ipa = ALIGN_DOWN(canonical_ipa, mapping_size);
2196 	}
2197 
2198 	if (!perm_fault_granule && !s2vi->map_non_cacheable && kvm_has_mte(kvm))
2199 		sanitise_mte_tags(kvm, pfn, mapping_size);
2200 
2201 	/*
2202 	 * Under the premise of getting a FSC_PERM fault, we just need to relax
2203 	 * permissions only if mapping_size equals perm_fault_granule. Otherwise,
2204 	 * kvm_pgtable_stage2_map() should be called to change block size.
2205 	 */
2206 	if (mapping_size == perm_fault_granule) {
2207 		/*
2208 		 * Drop the SW bits in favour of those stored in the
2209 		 * PTE, which will be preserved.
2210 		 */
2211 		prot &= ~KVM_NV_GUEST_MAP_SZ;
2212 		ret = KVM_PGT_FN(kvm_pgtable_stage2_relax_perms)(pgt, gfn_to_gpa(gfn),
2213 								 prot, flags);
2214 	} else {
2215 		ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, gfn_to_gpa(gfn), mapping_size,
2216 							 __pfn_to_phys(pfn), prot,
2217 							 memcache, flags);
2218 		/*
2219 		 * -EAGAIN from kvm_pgtable_stage2_map() can install mappings.
2220 		 * We don't know which subrange is installed, track the whole
2221 		 * thing.
2222 		 */
2223 		if ((ret == 0 || ret == -EAGAIN) && kvm_is_nested_s2_mmu(kvm, pgt->mmu)) {
2224 			kvm_record_guest_s2_mapping(pgt->mmu, canonical_ipa,
2225 						    gfn_to_gpa(gfn), mapping_size, mapping);
2226 			mapping = NULL;
2227 		}
2228 	}
2229 
2230 out_unlock:
2231 	kvm_release_faultin_page(kvm, s2vi->page, !!ret, writable);
2232 	kvm_fault_unlock(kvm);
2233 	kfree(mapping);
2234 
2235 	/*
2236 	 * Mark the page dirty only if the fault is handled successfully,
2237 	 * making sure we adjust the canonical IPA if the mapping size has
2238 	 * been updated (via a THP upgrade, for example).
2239 	 */
2240 	if (writable && !ret)
2241 		mark_page_dirty_in_slot(kvm, s2fd->memslot,
2242 					gpa_to_gfn(canonical_ipa));
2243 
2244 	if (ret == -EAGAIN)
2245 		return result ? ret : 0;
2246 
2247 	if (result && !ret)
2248 		result->mapping_size = mapping_size;
2249 
2250 	return ret;
2251 }
2252 
2253 static int user_mem_abort(const struct kvm_s2_fault_desc *s2fd,
2254 			  struct kvm_s2_fault_result *result)
2255 {
2256 	bool perm_fault = kvm_s2_fault_is_perm(s2fd);
2257 	struct kvm_s2_fault_vma_info s2vi = {};
2258 	enum kvm_pgtable_prot prot;
2259 	void *memcache;
2260 	int ret;
2261 
2262 	/*
2263 	 * Permission faults just need to update the existing leaf entry,
2264 	 * and so normally don't require allocations from the memcache. The
2265 	 * only exception to this is when dirty logging is enabled at runtime
2266 	 * and a fault needs to collapse a block entry into a table.
2267 	 * Under pKVM a permission fault can also collapse pages into a block,
2268 	 * which needs a fresh mapping object, and the hypervisor requires the
2269 	 * min-pages memcache even when the install allocates nothing.
2270 	 */
2271 	memcache = get_mmu_memcache(s2fd->vcpu);
2272 	if (!perm_fault || memslot_is_logging(s2fd->memslot) ||
2273 	    is_protected_kvm_enabled()) {
2274 		ret = topup_mmu_memcache(s2fd->mmu, memcache);
2275 		if (ret)
2276 			return ret;
2277 	}
2278 
2279 	ret = kvm_s2_fault_pin_pfn(s2fd, &s2vi);
2280 	if (ret == -EHWPOISON) {
2281 		/* If result is specified, let the caller handle this. */
2282 		if (result)
2283 			return -EHWPOISON;
2284 		kvm_send_hwpoison_signal(s2fd->hva, __ffs(s2vi.vma_pagesize));
2285 		return 0;
2286 	}
2287 	if (ret != 1)
2288 		return ret;
2289 
2290 	ret = kvm_s2_fault_compute_prot(s2fd, &s2vi, &prot);
2291 	if (ret) {
2292 		kvm_release_page_unused(s2vi.page);
2293 		return ret;
2294 	}
2295 
2296 	return kvm_s2_fault_map(s2fd, &s2vi, prot, memcache, result);
2297 }
2298 
2299 static int kvm_vm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
2300 {
2301 	VM_WARN_ON_ONCE(kvm_s2_fault_is_perm(s2fd) &&
2302 			!esr_abt_is_write_fault(s2fd->esr) &&
2303 			!kvm_s2_fault_is_exec(s2fd));
2304 
2305 	if (kvm_slot_has_gmem(s2fd->memslot))
2306 		return gmem_abort(s2fd, NULL);
2307 	else
2308 		return user_mem_abort(s2fd, NULL);
2309 }
2310 
2311 /* Resolve the access fault by making the page young again. */
2312 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
2313 {
2314 	enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
2315 	struct kvm_s2_mmu *mmu;
2316 
2317 	trace_kvm_access_fault(fault_ipa);
2318 
2319 	read_lock(&vcpu->kvm->mmu_lock);
2320 	mmu = vcpu->arch.hw_mmu;
2321 	KVM_PGT_FN(kvm_pgtable_stage2_mkyoung)(mmu->pgt, fault_ipa, flags);
2322 	read_unlock(&vcpu->kvm->mmu_lock);
2323 }
2324 
2325 /*
2326  * Returns true if the SEA should be handled locally within KVM if the abort
2327  * is caused by a kernel memory allocation (e.g. stage-2 table memory).
2328  */
2329 static bool host_owns_sea(struct kvm_vcpu *vcpu, u64 esr)
2330 {
2331 	/*
2332 	 * Without FEAT_RAS HCR_EL2.TEA is RES0, meaning any external abort
2333 	 * taken from a guest EL to EL2 is due to a host-imposed access (e.g.
2334 	 * stage-2 PTW).
2335 	 */
2336 	if (!cpus_have_final_cap(ARM64_HAS_RAS_EXTN))
2337 		return true;
2338 
2339 	/* KVM owns the VNCR when the vCPU isn't in a nested context. */
2340 	if (is_hyp_ctxt(vcpu) && !kvm_vcpu_trap_is_iabt(vcpu) && (esr & ESR_ELx_VNCR))
2341 		return true;
2342 
2343 	/*
2344 	 * Determining if an external abort during a table walk happened at
2345 	 * stage-2 is only possible with S1PTW is set. Otherwise, since KVM
2346 	 * sets HCR_EL2.TEA, SEAs due to a stage-1 walk (i.e. accessing the
2347 	 * PA of the stage-1 descriptor) can reach here and are reported
2348 	 * with a TTW ESR value.
2349 	 */
2350 	return (esr_fsc_is_sea_ttw(esr) && (esr & ESR_ELx_S1PTW));
2351 }
2352 
2353 int kvm_handle_guest_sea(struct kvm_vcpu *vcpu)
2354 {
2355 	struct kvm *kvm = vcpu->kvm;
2356 	struct kvm_run *run = vcpu->run;
2357 	u64 esr = kvm_vcpu_get_esr(vcpu);
2358 	u64 esr_mask = ESR_ELx_EC_MASK	|
2359 		       ESR_ELx_IL	|
2360 		       ESR_ELx_FnV	|
2361 		       ESR_ELx_EA	|
2362 		       ESR_ELx_CM	|
2363 		       ESR_ELx_WNR	|
2364 		       ESR_ELx_FSC;
2365 	u64 ipa;
2366 
2367 	/*
2368 	 * Give APEI the opportunity to claim the abort before handling it
2369 	 * within KVM. apei_claim_sea() expects to be called with IRQs enabled.
2370 	 */
2371 	lockdep_assert_irqs_enabled();
2372 	if (apei_claim_sea(NULL) == 0)
2373 		return 1;
2374 
2375 	if (host_owns_sea(vcpu, esr) ||
2376 	    !test_bit(KVM_ARCH_FLAG_EXIT_SEA, &vcpu->kvm->arch.flags))
2377 		return kvm_inject_serror(vcpu);
2378 
2379 	/* ESR_ELx.SET is RES0 when FEAT_RAS isn't implemented. */
2380 	if (kvm_has_ras(kvm))
2381 		esr_mask |= ESR_ELx_SET_MASK;
2382 
2383 	/*
2384 	 * Exit to userspace, and provide faulting guest virtual and physical
2385 	 * addresses in case userspace wants to emulate SEA to guest by
2386 	 * writing to FAR_ELx and HPFAR_ELx registers.
2387 	 */
2388 	memset(&run->arm_sea, 0, sizeof(run->arm_sea));
2389 	run->exit_reason = KVM_EXIT_ARM_SEA;
2390 	run->arm_sea.esr = esr & esr_mask;
2391 
2392 	if (!(esr & ESR_ELx_FnV))
2393 		run->arm_sea.gva = kvm_vcpu_get_hfar(vcpu);
2394 
2395 	ipa = kvm_vcpu_get_fault_ipa(vcpu);
2396 	if (ipa != INVALID_GPA) {
2397 		run->arm_sea.flags |= KVM_EXIT_ARM_SEA_FLAG_GPA_VALID;
2398 		run->arm_sea.gpa = ipa;
2399 	}
2400 
2401 	return 0;
2402 }
2403 
2404 /**
2405  * kvm_handle_guest_abort - handles all 2nd stage aborts
2406  * @vcpu:	the VCPU pointer
2407  *
2408  * Any abort that gets to the host is almost guaranteed to be caused by a
2409  * missing second stage translation table entry, which can mean that either the
2410  * guest simply needs more memory and we must allocate an appropriate page or it
2411  * can mean that the guest tried to access I/O memory, which is emulated by user
2412  * space. The distinction is based on the IPA causing the fault and whether this
2413  * memory region has been registered as standard RAM by user space.
2414  */
2415 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
2416 {
2417 	struct kvm_s2_trans nested_trans, *nested = NULL;
2418 	unsigned long esr = kvm_vcpu_get_esr(vcpu);
2419 	struct kvm_s2_mmu *mmu = vcpu->arch.hw_mmu;
2420 	struct kvm *kvm = vcpu->kvm;
2421 	phys_addr_t fault_ipa; /* The address we faulted on */
2422 	phys_addr_t ipa; /* Always the IPA in the L1 guest phys space */
2423 	struct kvm_memory_slot *memslot;
2424 	unsigned long hva;
2425 	bool is_iabt, write_fault, writable;
2426 	gfn_t gfn;
2427 	int ret, idx;
2428 
2429 	if (esr_abt_is_sea(esr))
2430 		return kvm_handle_guest_sea(vcpu);
2431 
2432 	/*
2433 	 * The fault IPA should be reliable at this point as we're not dealing
2434 	 * with an SEA.
2435 	 */
2436 	ipa = fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
2437 	if (KVM_BUG_ON(ipa == INVALID_GPA, kvm))
2438 		return -EFAULT;
2439 
2440 	is_iabt = esr_trap_is_iabt(esr);
2441 
2442 	if (esr_fsc_is_translation_fault(esr)) {
2443 		/* Beyond sanitised PARange (which is the IPA limit) */
2444 		if (fault_ipa >= BIT_ULL(get_kvm_ipa_limit())) {
2445 			kvm_inject_size_fault(vcpu);
2446 			return 1;
2447 		}
2448 
2449 		/* Falls between the IPA range and the PARange? */
2450 		if (fault_ipa >= BIT_ULL(VTCR_EL2_IPA(mmu->vtcr))) {
2451 			fault_ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
2452 
2453 			return kvm_inject_sea(vcpu, is_iabt, fault_ipa);
2454 		}
2455 	}
2456 
2457 	trace_kvm_guest_fault(*vcpu_pc(vcpu), esr,
2458 			      kvm_vcpu_get_hfar(vcpu), fault_ipa);
2459 
2460 	/* Check the stage-2 fault is trans. fault or write fault */
2461 	if (!esr_fsc_is_translation_fault(esr) &&
2462 	    !esr_fsc_is_permission_fault(esr) &&
2463 	    !esr_fsc_is_access_flag_fault(esr) &&
2464 	    !esr_fsc_is_excl_atomic_fault(esr)) {
2465 		kvm_err("Unsupported FSC: EC=%#lx xFSC=%#lx ESR_EL2=%#lx\n",
2466 			ESR_ELx_EC(esr),
2467 			(unsigned long)(esr & ESR_ELx_FSC),
2468 			(unsigned long)esr);
2469 		return -EFAULT;
2470 	}
2471 
2472 	idx = srcu_read_lock(&kvm->srcu);
2473 
2474 	/*
2475 	 * We may have faulted on a shadow stage 2 page table if we are
2476 	 * running a nested guest.  In this case, we have to resolve the L2
2477 	 * IPA to the L1 IPA first, before knowing what kind of memory should
2478 	 * back the L1 IPA.
2479 	 *
2480 	 * If the shadow stage 2 page table walk faults, then we simply inject
2481 	 * this to the guest and carry on.
2482 	 *
2483 	 * If there are no shadow S2 PTs because S2 is disabled, there is
2484 	 * nothing to walk and we treat it as a 1:1 before going through the
2485 	 * canonical translation.
2486 	 */
2487 	if (kvm_is_nested_s2_mmu(kvm, mmu) && mmu->nested_stage2_enabled) {
2488 		u32 esr;
2489 
2490 		ret = kvm_walk_nested_s2(vcpu, fault_ipa, &nested_trans);
2491 		if (ret == -EAGAIN) {
2492 			ret = 1;
2493 			goto out_unlock;
2494 		}
2495 
2496 		if (ret) {
2497 			esr = kvm_s2_trans_esr(&nested_trans);
2498 			kvm_inject_s2_fault(vcpu, esr);
2499 			goto out_unlock;
2500 		}
2501 
2502 		ret = kvm_s2_handle_perm_fault(vcpu, &nested_trans);
2503 		if (ret) {
2504 			esr = kvm_s2_trans_esr(&nested_trans);
2505 			kvm_inject_s2_fault(vcpu, esr);
2506 			goto out_unlock;
2507 		}
2508 
2509 		ipa = kvm_s2_trans_output(&nested_trans);
2510 		nested = &nested_trans;
2511 	}
2512 
2513 	gfn = ipa >> PAGE_SHIFT;
2514 	memslot = gfn_to_memslot(kvm, gfn);
2515 	hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
2516 	write_fault = esr_abt_is_write_fault(esr);
2517 	if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
2518 		/*
2519 		 * The guest has put either its instructions or its page-tables
2520 		 * somewhere it shouldn't have. Userspace won't be able to do
2521 		 * anything about this (there's no syndrome for a start), so
2522 		 * re-inject the abort back into the guest.
2523 		 */
2524 		if (is_iabt) {
2525 			ret = -ENOEXEC;
2526 			goto out;
2527 		}
2528 
2529 		if (esr_abt_is_s1ptw(esr)) {
2530 			ret = kvm_inject_sea_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
2531 			goto out_unlock;
2532 		}
2533 
2534 		/*
2535 		 * Check for a cache maintenance operation. Since we
2536 		 * ended-up here, we know it is outside of any memory
2537 		 * slot. But we can't find out if that is for a device,
2538 		 * or if the guest is just being stupid. The only thing
2539 		 * we know for sure is that this range cannot be cached.
2540 		 *
2541 		 * So let's assume that the guest is just being
2542 		 * cautious, and skip the instruction.
2543 		 */
2544 		if (kvm_is_error_hva(hva) && esr_dabt_is_cm(esr)) {
2545 			kvm_incr_pc(vcpu);
2546 			ret = 1;
2547 			goto out_unlock;
2548 		}
2549 
2550 		/*
2551 		 * The IPA is reported as [MAX:12], so we need to
2552 		 * complement it with the bottom 12 bits from the
2553 		 * faulting VA. This is always 12 bits, irrespective
2554 		 * of the page size.
2555 		 */
2556 		ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
2557 		ret = io_mem_abort(vcpu, ipa);
2558 		goto out_unlock;
2559 	}
2560 
2561 	/* Userspace should not be able to register out-of-bounds IPAs */
2562 	VM_BUG_ON(ipa >= kvm_phys_size(mmu));
2563 
2564 	if (esr_fsc_is_access_flag_fault(esr)) {
2565 		handle_access_fault(vcpu, fault_ipa);
2566 		ret = 1;
2567 		goto out_unlock;
2568 	}
2569 
2570 	const struct kvm_s2_fault_desc s2fd = {
2571 		.vcpu		= vcpu,
2572 		.fault_ipa	= fault_ipa,
2573 		.nested		= nested,
2574 		.memslot	= memslot,
2575 		.hva		= hva,
2576 		.esr		= esr,
2577 		.mmu		= mmu,
2578 	};
2579 
2580 	ret = kvm->arch.vm_s2_ops->vm_mem_abort(&s2fd);
2581 	if (ret == 0)
2582 		ret = 1;
2583 out:
2584 	if (ret == -ENOEXEC)
2585 		ret = kvm_inject_sea_iabt(vcpu, kvm_vcpu_get_hfar(vcpu));
2586 out_unlock:
2587 	srcu_read_unlock(&kvm->srcu, idx);
2588 	return ret;
2589 }
2590 
2591 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
2592 {
2593 	gpa_t gpa = range->start << PAGE_SHIFT;
2594 	size_t size = (range->end - range->start) << PAGE_SHIFT;
2595 	bool may_block = range->may_block;
2596 
2597 	if (!kvm->arch.mmu.pgt)
2598 		return false;
2599 
2600 	kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, size, may_block);
2601 	kvm_nested_unmap_cipa_range(kvm, gpa, size, may_block);
2602 
2603 	return false;
2604 }
2605 
2606 static bool kvm_vm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2607 {
2608 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2609 
2610 	return kvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2611 						   range->start << PAGE_SHIFT,
2612 						   size, true);
2613 }
2614 
2615 static bool pkvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2616 {
2617 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2618 
2619 	return pkvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2620 						    range->start << PAGE_SHIFT,
2621 						    size, true);
2622 }
2623 
2624 static bool no_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2625 {
2626 	/* The hypervisor doesn't support aging */
2627 	return false;
2628 }
2629 
2630 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2631 {
2632 	if (!kvm->arch.mmu.pgt)
2633 		return false;
2634 
2635 	return kvm->arch.vm_s2_ops->vm_age_gfn(kvm, range);
2636 	/*
2637 	 * TODO: Handle nested_mmu structures here using the reverse mapping in
2638 	 * a later version of patch series.
2639 	 */
2640 }
2641 
2642 static bool kvm_vm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2643 {
2644 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2645 
2646 	return kvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2647 						   range->start << PAGE_SHIFT,
2648 						   size, false);
2649 }
2650 
2651 static bool pkvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2652 {
2653 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2654 
2655 	return pkvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2656 						    range->start << PAGE_SHIFT,
2657 						    size, false);
2658 }
2659 
2660 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2661 {
2662 	if (!kvm->arch.mmu.pgt)
2663 		return false;
2664 
2665 	return kvm->arch.vm_s2_ops->vm_test_age_gfn(kvm, range);
2666 }
2667 
2668 phys_addr_t kvm_mmu_get_httbr(void)
2669 {
2670 	return __pa(hyp_pgtable->pgd);
2671 }
2672 
2673 phys_addr_t kvm_get_idmap_vector(void)
2674 {
2675 	return hyp_idmap_vector;
2676 }
2677 
2678 static int kvm_map_idmap_text(void)
2679 {
2680 	unsigned long size = hyp_idmap_end - hyp_idmap_start;
2681 	int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
2682 					PAGE_HYP_EXEC);
2683 	if (err)
2684 		kvm_err("Failed to idmap %lx-%lx\n",
2685 			hyp_idmap_start, hyp_idmap_end);
2686 
2687 	return err;
2688 }
2689 
2690 static void *kvm_hyp_zalloc_page(void *arg)
2691 {
2692 	return (void *)get_zeroed_page(GFP_KERNEL);
2693 }
2694 
2695 static struct kvm_pgtable_mm_ops kvm_hyp_mm_ops = {
2696 	.zalloc_page		= kvm_hyp_zalloc_page,
2697 	.get_page		= kvm_host_get_page,
2698 	.put_page		= kvm_host_put_page,
2699 	.phys_to_virt		= kvm_host_va,
2700 	.virt_to_phys		= kvm_host_pa,
2701 };
2702 
2703 int __init kvm_mmu_init(u32 hyp_va_bits)
2704 {
2705 	int err;
2706 
2707 	hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
2708 	hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
2709 	hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
2710 	hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
2711 	hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
2712 
2713 	/*
2714 	 * We rely on the linker script to ensure at build time that the HYP
2715 	 * init code does not cross a page boundary.
2716 	 */
2717 	BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
2718 
2719 	kvm_debug("Using %u-bit virtual addresses at EL2\n", hyp_va_bits);
2720 	kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
2721 	kvm_debug("HYP VA range: %lx:%lx\n",
2722 		  kern_hyp_va(PAGE_OFFSET),
2723 		  kern_hyp_va((unsigned long)high_memory - 1));
2724 
2725 	if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
2726 	    hyp_idmap_start <  kern_hyp_va((unsigned long)high_memory - 1) &&
2727 	    hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
2728 		/*
2729 		 * The idmap page is intersecting with the VA space,
2730 		 * it is not safe to continue further.
2731 		 */
2732 		kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
2733 		err = -EINVAL;
2734 		goto out;
2735 	}
2736 
2737 	hyp_pgtable = kzalloc_obj(*hyp_pgtable);
2738 	if (!hyp_pgtable) {
2739 		kvm_err("Hyp mode page-table not allocated\n");
2740 		err = -ENOMEM;
2741 		goto out;
2742 	}
2743 
2744 	err = kvm_pgtable_hyp_init(hyp_pgtable, hyp_va_bits, &kvm_hyp_mm_ops);
2745 	if (err)
2746 		goto out_free_pgtable;
2747 
2748 	err = kvm_map_idmap_text();
2749 	if (err)
2750 		goto out_destroy_pgtable;
2751 
2752 	io_map_base = hyp_idmap_start;
2753 	__hyp_va_bits = hyp_va_bits;
2754 	return 0;
2755 
2756 out_destroy_pgtable:
2757 	kvm_pgtable_hyp_destroy(hyp_pgtable);
2758 out_free_pgtable:
2759 	kfree(hyp_pgtable);
2760 	hyp_pgtable = NULL;
2761 out:
2762 	return err;
2763 }
2764 
2765 void kvm_arch_commit_memory_region(struct kvm *kvm,
2766 				   struct kvm_memory_slot *old,
2767 				   const struct kvm_memory_slot *new,
2768 				   enum kvm_mr_change change)
2769 {
2770 	bool log_dirty_pages = new && new->flags & KVM_MEM_LOG_DIRTY_PAGES;
2771 
2772 	/*
2773 	 * At this point memslot has been committed and there is an
2774 	 * allocated dirty_bitmap[], dirty pages will be tracked while the
2775 	 * memory slot is write protected.
2776 	 */
2777 	if (log_dirty_pages) {
2778 
2779 		if (change == KVM_MR_DELETE)
2780 			return;
2781 
2782 		/*
2783 		 * Huge and normal pages are write-protected and split
2784 		 * on either of these two cases:
2785 		 *
2786 		 * 1. with initial-all-set: gradually with CLEAR ioctls,
2787 		 */
2788 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
2789 			return;
2790 		/*
2791 		 * or
2792 		 * 2. without initial-all-set: all in one shot when
2793 		 *    enabling dirty logging.
2794 		 */
2795 		kvm_mmu_wp_memory_region(kvm, new->id);
2796 		kvm_mmu_split_memory_region(kvm, new->id);
2797 	} else {
2798 		/*
2799 		 * Free any leftovers from the eager page splitting cache. Do
2800 		 * this when deleting, moving, disabling dirty logging, or
2801 		 * creating the memslot (a nop). Doing it for deletes makes
2802 		 * sure we don't leak memory, and there's no need to keep the
2803 		 * cache around for any of the other cases.
2804 		 */
2805 		kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
2806 	}
2807 }
2808 
2809 int kvm_arch_prepare_memory_region(struct kvm *kvm,
2810 				   const struct kvm_memory_slot *old,
2811 				   struct kvm_memory_slot *new,
2812 				   enum kvm_mr_change change)
2813 {
2814 	hva_t hva, reg_end;
2815 	int ret = 0;
2816 
2817 	if (kvm_vm_is_protected(kvm)) {
2818 		/* Cannot modify memslots once a pVM has run. */
2819 		if (pkvm_hyp_vm_is_created(kvm) &&
2820 		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE)) {
2821 			return -EPERM;
2822 		}
2823 
2824 		if (new &&
2825 		    new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)) {
2826 			return -EPERM;
2827 		}
2828 	}
2829 
2830 	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
2831 			change != KVM_MR_FLAGS_ONLY)
2832 		return 0;
2833 
2834 	/*
2835 	 * Prevent userspace from creating a memory region outside of the IPA
2836 	 * space addressable by the KVM guest IPA space.
2837 	 */
2838 	if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT))
2839 		return -EFAULT;
2840 
2841 	/*
2842 	 * Only support guest_memfd backed memslots with mappable memory, since
2843 	 * there aren't any CoCo VMs that support only private memory on arm64.
2844 	 */
2845 	if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
2846 		return -EINVAL;
2847 
2848 	/* guest_memfd is incompatible with MTE. */
2849 	if (kvm_slot_has_gmem(new) && kvm_has_mte(kvm))
2850 		return -EINVAL;
2851 
2852 	hva = new->userspace_addr;
2853 	reg_end = hva + (new->npages << PAGE_SHIFT);
2854 
2855 	mmap_read_lock(current->mm);
2856 	/*
2857 	 * A memory region could potentially cover multiple VMAs, and any holes
2858 	 * between them, so iterate over all of them.
2859 	 *
2860 	 *     +--------------------------------------------+
2861 	 * +---------------+----------------+   +----------------+
2862 	 * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
2863 	 * +---------------+----------------+   +----------------+
2864 	 *     |               memory region                |
2865 	 *     +--------------------------------------------+
2866 	 */
2867 	do {
2868 		struct vm_area_struct *vma;
2869 
2870 		vma = find_vma_intersection(current->mm, hva, reg_end);
2871 		if (!vma)
2872 			break;
2873 
2874 		if (kvm_has_mte(kvm) && !kvm_vma_mte_allowed(vma)) {
2875 			ret = -EINVAL;
2876 			break;
2877 		}
2878 
2879 		if (vma->vm_flags & VM_PFNMAP) {
2880 			/* IO region dirty page logging not allowed */
2881 			if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
2882 				ret = -EINVAL;
2883 				break;
2884 			}
2885 
2886 			/*
2887 			 * Cacheable PFNMAP is allowed only if the hardware
2888 			 * supports it.
2889 			 */
2890 			if (kvm_vma_is_cacheable(vma) && !kvm_supports_cacheable_pfnmap()) {
2891 				ret = -EINVAL;
2892 				break;
2893 			}
2894 		}
2895 		hva = min(reg_end, vma->vm_end);
2896 	} while (hva < reg_end);
2897 
2898 	mmap_read_unlock(current->mm);
2899 	return ret;
2900 }
2901 
2902 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
2903 {
2904 }
2905 
2906 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
2907 {
2908 }
2909 
2910 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
2911 				   struct kvm_memory_slot *slot)
2912 {
2913 	gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
2914 	phys_addr_t size = slot->npages << PAGE_SHIFT;
2915 
2916 	write_lock(&kvm->mmu_lock);
2917 	kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, size, true);
2918 	kvm_nested_unmap_cipa_range(kvm, gpa, size, true);
2919 	write_unlock(&kvm->mmu_lock);
2920 }
2921 
2922 /*
2923  * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
2924  *
2925  * Main problems:
2926  * - S/W ops are local to a CPU (not broadcast)
2927  * - We have line migration behind our back (speculation)
2928  * - System caches don't support S/W at all (damn!)
2929  *
2930  * In the face of the above, the best we can do is to try and convert
2931  * S/W ops to VA ops. Because the guest is not allowed to infer the
2932  * S/W to PA mapping, it can only use S/W to nuke the whole cache,
2933  * which is a rather good thing for us.
2934  *
2935  * Also, it is only used when turning caches on/off ("The expected
2936  * usage of the cache maintenance instructions that operate by set/way
2937  * is associated with the cache maintenance instructions associated
2938  * with the powerdown and powerup of caches, if this is required by
2939  * the implementation.").
2940  *
2941  * We use the following policy:
2942  *
2943  * - If we trap a S/W operation, we enable VM trapping to detect
2944  *   caches being turned on/off, and do a full clean.
2945  *
2946  * - We flush the caches on both caches being turned on and off.
2947  *
2948  * - Once the caches are enabled, we stop trapping VM ops.
2949  */
2950 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
2951 {
2952 	unsigned long hcr = *vcpu_hcr(vcpu);
2953 
2954 	/*
2955 	 * If this is the first time we do a S/W operation
2956 	 * (i.e. HCR_EL2_TVM not set) flush the whole memory, and set the
2957 	 * VM trapping.
2958 	 *
2959 	 * Otherwise, rely on the VM trapping to wait for the MMU +
2960 	 * Caches to be turned off. At that point, we'll be able to
2961 	 * clean the caches again.
2962 	 */
2963 	if (!(hcr & HCR_EL2_TVM)) {
2964 		trace_kvm_set_way_flush(*vcpu_pc(vcpu),
2965 					vcpu_has_cache_enabled(vcpu));
2966 		stage2_flush_vm(vcpu->kvm);
2967 		*vcpu_hcr(vcpu) = hcr | HCR_EL2_TVM;
2968 	}
2969 }
2970 
2971 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
2972 {
2973 	bool now_enabled = vcpu_has_cache_enabled(vcpu);
2974 
2975 	/*
2976 	 * If switching the MMU+caches on, need to invalidate the caches.
2977 	 * If switching it off, need to clean the caches.
2978 	 * Clean + invalidate does the trick always.
2979 	 */
2980 	if (now_enabled != was_enabled)
2981 		stage2_flush_vm(vcpu->kvm);
2982 
2983 	/* Caches are now on, stop trapping VM ops (until a S/W op) */
2984 	if (now_enabled)
2985 		*vcpu_hcr(vcpu) &= ~HCR_EL2_TVM;
2986 
2987 	trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
2988 }
2989 
2990 /*
2991  * Try to walk to the specified GPA in canonical mmu - if unmapped returns 0, if
2992  * mapped returns the granule size, otherwise returns an error.
2993  */
2994 static long kvm_walk_s2(struct kvm_pgtable *pgt,
2995 			gpa_t gpa, s8 *level)
2996 {
2997 	struct kvm *kvm = kvm_s2_mmu_to_kvm(pgt->mmu);
2998 	kvm_pte_t pte;
2999 	long ret;
3000 
3001 	guard(read_lock)(&kvm->mmu_lock);
3002 
3003 	ret = kvm_pgtable_get_leaf(pgt, gpa, &pte, level,
3004 				   KVM_PGTABLE_WALK_SHARED);
3005 	if (ret)
3006 		return ret;
3007 	/* Unpopulated, must fault. */
3008 	if (!kvm_pte_valid(pte))
3009 		return 0;
3010 	return kvm_granule_size(*level);
3011 }
3012 
3013 /* Synthesised data abort at specified page table level. */
3014 #define PRE_FAULT_ESR(level)				\
3015 	 ((ESR_ELx_EC_DABT_LOW << ESR_ELx_EC_SHIFT) |	\
3016 	  ESR_ELx_IL | ESR_ELx_FSC_FAULT_L(level))
3017 
3018 /* Retrieve either a read-only or a read/write hva. */
3019 static hva_t gfn_to_hva_memslot_read(struct kvm_memory_slot *slot, gfn_t gfn)
3020 {
3021 	return gfn_to_hva_memslot_prot(slot, gfn, /*writable=*/NULL);
3022 }
3023 
3024 static long __pre_fault_s2(struct kvm_s2_mmu *mmu, struct kvm_vcpu *vcpu,
3025 			   gpa_t gpa, struct kvm_memory_slot *memslot, s8 level)
3026 {
3027 	const bool is_gmem = kvm_slot_has_gmem(memslot);
3028 	const gfn_t gfn = gpa_to_gfn(gpa);
3029 	const hva_t hva = is_gmem ? 0 : gfn_to_hva_memslot_read(memslot, gfn);
3030 	const struct kvm_s2_fault_desc s2fd = {
3031 		.vcpu		= vcpu,
3032 		.fault_ipa	= gpa,
3033 		.nested		= NULL,
3034 		.memslot	= memslot,
3035 		.hva		= hva,
3036 		.esr		= PRE_FAULT_ESR(level),
3037 		.mmu		= mmu,
3038 	};
3039 	struct kvm_s2_fault_result result = {};
3040 	long ret;
3041 
3042 	if (kvm_is_error_hva(hva))
3043 		return -EFAULT;
3044 
3045 	if (is_gmem)
3046 		ret = gmem_abort(&s2fd, &result);
3047 	else
3048 		ret = user_mem_abort(&s2fd, &result);
3049 	if (IS_ERR_VALUE(ret))
3050 		return ret;
3051 	return result.mapping_size;
3052 }
3053 
3054 static long pre_fault_s2(struct kvm_s2_mmu *mmu, struct kvm_vcpu *vcpu,
3055 			 gpa_t gpa, struct kvm_memory_slot *memslot)
3056 {
3057 	s8 level;
3058 	long ret;
3059 
3060 	/* Try a walk first. */
3061 	ret = kvm_walk_s2(mmu->pgt, gpa, &level);
3062 	if (ret)
3063 		return ret;
3064 	/* OK, have to fault page in. */
3065 	return __pre_fault_s2(mmu, vcpu, gpa, memslot, level);
3066 }
3067 
3068 static unsigned long
3069 pre_fault_bytes_consumed(gpa_t gpa, unsigned long granule_size,
3070 			 unsigned long bytes_remaining)
3071 {
3072 	/* Granules are always a power-of-2. */
3073 	const unsigned long granule_bytes_remaining =
3074 		granule_size - (gpa % granule_size);
3075 
3076 	return min(granule_bytes_remaining, bytes_remaining);
3077 }
3078 
3079 /* If you lose the race this many times, time to give up. */
3080 #define MAX_PRE_FAULT_RETRIES 3
3081 
3082 int kvm_arch_pre_fault_allowed(struct kvm_vcpu *vcpu)
3083 {
3084 	if (is_protected_kvm_enabled())
3085 		return -EOPNOTSUPP;
3086 	if (!kvm_vcpu_initialized(vcpu))
3087 		return -ENOEXEC;
3088 
3089 	return 0;
3090 }
3091 
3092 /**
3093  * kvm_arch_vcpu_pre_fault_memory - pre-fault stage-2 page tables for the
3094  * specified GPA.
3095  * @vcpu:	The VCPU pointer
3096  * @range:	{gpa, size, flags} tuple
3097  *
3098  * The mapping performed is always best-effort - faulting in is necessarily
3099  * racey. The ranges faulted in are canonical, nested page tables are ignored.
3100  *
3101  * @range->gpa specifies the GPA to pre-fault, @range->size specifies how many
3102  * bytes remain to be pre-faulted and @range->flags is reserved and must be 0.
3103  *
3104  * Returns: the number of bytes the pre-fault consumed, or an error.
3105  */
3106 long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
3107 				    struct kvm_pre_fault_memory *range)
3108 {
3109 	struct kvm *kvm = vcpu->kvm;
3110 	const u64 bytes_remaining = range->size;
3111 	struct kvm_s2_mmu *mmu = &kvm->arch.mmu; /* Canonical. */
3112 	struct kvm_memory_slot *memslot;
3113 	const gpa_t gpa = range->gpa;
3114 	int num_retries = 0;
3115 	long ret;
3116 
3117 	memslot = gfn_to_memslot(kvm, gpa_to_gfn(gpa));
3118 	if (!memslot)
3119 		return -ENOENT;
3120 	/* SRCU must be released for progress and only userland can do that. */
3121 	if (memslot->flags & KVM_MEMSLOT_INVALID)
3122 		return -EAGAIN;
3123 
3124 	do {
3125 		ret = pre_fault_s2(mmu, vcpu, gpa, memslot);
3126 	} while (ret == -EAGAIN && num_retries++ < MAX_PRE_FAULT_RETRIES);
3127 
3128 	if (IS_ERR_VALUE(ret))
3129 		return ret;
3130 	return pre_fault_bytes_consumed(gpa, ret, bytes_remaining);
3131 }
3132 
3133 static const struct kvm_vm_s2_ops protected_pkvm_vm_s2_ops = {
3134 	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
3135 	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
3136 	.vm_age_gfn			= no_age_gfn,
3137 	.vm_test_age_gfn		= no_age_gfn,
3138 	.vm_stage2_unmap_range		= no_stage2_unmap_range,
3139 	.vm_mem_abort			= protected_pkvm_mem_abort,
3140 };
3141 
3142 static const struct kvm_vm_s2_ops pkvm_vm_s2_ops = {
3143 	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
3144 	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
3145 	.vm_age_gfn			= pkvm_age_gfn,
3146 	.vm_test_age_gfn		= pkvm_test_age_gfn,
3147 	.vm_stage2_unmap_range		= pkvm_stage2_unmap_range,
3148 	.vm_mem_abort			= kvm_vm_mem_abort,
3149 };
3150 
3151 static const struct kvm_vm_s2_ops kvm_default_vm_s2_ops = {
3152 	.vm_flush_remote_tlbs		= kvm_vm_flush_remote_tlbs,
3153 	.vm_flush_remote_tlbs_range	= kvm_vm_flush_remote_tlbs_range,
3154 	.vm_age_gfn			= kvm_vm_age_gfn,
3155 	.vm_test_age_gfn		= kvm_vm_test_age_gfn,
3156 	.vm_stage2_unmap_range		= kvm_vm_stage2_unmap_range,
3157 	.vm_mem_abort			= kvm_vm_mem_abort,
3158 };
3159 
3160 #define KVM_VM_S2_OPS(flavor, ops)		\
3161 		[(flavor)] = &(ops)
3162 
3163 static const struct kvm_vm_s2_ops *arm64_vm_s2_ops[] = {
3164 	KVM_VM_S2_OPS(VM_VHE, kvm_default_vm_s2_ops),
3165 	KVM_VM_S2_OPS(VM_NVHE, kvm_default_vm_s2_ops),
3166 	KVM_VM_S2_OPS(VM_PKVM, pkvm_vm_s2_ops),
3167 	KVM_VM_S2_OPS(VM_PROTECTED_PKVM, protected_pkvm_vm_s2_ops),
3168 };
3169 
3170 static int kvm_vm_init_vm_s2_ops(struct kvm *kvm)
3171 {
3172 	BUILD_BUG_ON(ARRAY_SIZE(arm64_vm_s2_ops) != VM_FLAVOR_MAX);
3173 
3174 	kvm->arch.vm_s2_ops = arm64_vm_s2_ops[kvm->arch.vm_flavor];
3175 	if (WARN_ON(!kvm->arch.vm_s2_ops))
3176 		return -EINVAL;
3177 	return 0;
3178 }
3179