xref: /linux/arch/arm64/kvm/mmu.c (revision 29c925376df478c26415c46561c010d6ca514f8d)
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 (is_vm_hugetlb_page(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 	}
1785 
1786 	if (!(s2fd->memslot->flags & KVM_MEM_READONLY))
1787 		prot |= KVM_PGTABLE_PROT_W;
1788 
1789 	if (s2fd->nested)
1790 		prot = adjust_nested_fault_perms(s2fd->nested, prot);
1791 
1792 	if (exec_fault || cpus_have_final_cap(ARM64_HAS_CACHE_DIC))
1793 		prot |= KVM_PGTABLE_PROT_X;
1794 
1795 	if (s2fd->nested)
1796 		prot = adjust_nested_exec_perms(kvm, s2fd->nested, prot);
1797 
1798 	kvm_fault_lock(kvm);
1799 	if (mmu_invalidate_retry(kvm, s2vi.mmu_seq)) {
1800 		ret = -EAGAIN;
1801 		goto out_unlock;
1802 	}
1803 
1804 	if (perm_fault) {
1805 		/*
1806 		 * Drop the SW bits in favour of those stored in the
1807 		 * PTE, which will be preserved.
1808 		 */
1809 		prot &= ~KVM_NV_GUEST_MAP_SZ;
1810 		ret = KVM_PGT_FN(kvm_pgtable_stage2_relax_perms)(pgt, gfn_to_gpa(s2vi.gfn),
1811 								 prot, flags);
1812 	} else {
1813 		ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, gfn_to_gpa(s2vi.gfn),
1814 							 s2vi.vma_pagesize,
1815 							 __pfn_to_phys(s2vi.pfn), prot,
1816 							 memcache, flags);
1817 		/*
1818 		 * -EAGAIN from kvm_pgtable_stage2_map() can install mappings.
1819 		 * We don't know which subrange is installed, track the whole
1820 		 * thing.
1821 		 */
1822 		if ((ret == 0 || ret == -EAGAIN) && kvm_is_nested_s2_mmu(kvm, pgt->mmu)) {
1823 			kvm_record_guest_s2_mapping(pgt->mmu, canonical_gfn << PAGE_SHIFT,
1824 						    s2fd->fault_ipa, s2vi.vma_pagesize, mapping);
1825 			mapping = NULL;
1826 		}
1827 	}
1828 
1829 out_unlock:
1830 	kvm_fault_unlock(kvm);
1831 	kfree(mapping);
1832 
1833 	if ((prot & KVM_PGTABLE_PROT_W) && !ret)
1834 		mark_page_dirty_in_slot(kvm, s2fd->memslot, canonical_gfn);
1835 
1836 	if (ret == -EAGAIN)
1837 		return result ? ret : 0;
1838 
1839 	if (result && !ret)
1840 		result->mapping_size = s2vi.vma_pagesize;
1841 
1842 	return ret;
1843 }
1844 
1845 static int protected_pkvm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
1846 {
1847 	unsigned int flags = FOLL_HWPOISON | FOLL_LONGTERM | FOLL_WRITE;
1848 	struct kvm_s2_fault_vma_info s2vi = {};
1849 	struct kvm_vcpu *vcpu = s2fd->vcpu;
1850 	struct kvm_pgtable *pgt = s2fd->mmu->pgt;
1851 	struct mm_struct *mm = current->mm;
1852 	struct kvm *kvm = vcpu->kvm;
1853 	void *hyp_memcache;
1854 	int ret;
1855 
1856 	hyp_memcache = get_mmu_memcache(vcpu);
1857 	ret = topup_mmu_memcache(s2fd->mmu, hyp_memcache);
1858 	if (ret)
1859 		return -ENOMEM;
1860 
1861 	ret = kvm_s2_fault_get_vma_info(s2fd, &s2vi);
1862 	if (ret)
1863 		return ret;
1864 
1865 	ret = account_locked_vm(mm, 1, true);
1866 	if (ret)
1867 		return ret;
1868 
1869 	mmap_read_lock(mm);
1870 	ret = pin_user_pages(s2fd->hva, 1, flags, &s2vi.page);
1871 	mmap_read_unlock(mm);
1872 
1873 	if (ret == -EHWPOISON) {
1874 		kvm_send_hwpoison_signal(s2fd->hva, PAGE_SHIFT);
1875 		ret = 0;
1876 		goto dec_account;
1877 	} else if (ret != 1) {
1878 		ret = -EFAULT;
1879 		goto dec_account;
1880 	} else if (!folio_test_swapbacked(page_folio(s2vi.page))) {
1881 		/*
1882 		 * We really can't deal with page-cache pages returned by GUP
1883 		 * because (a) we may trigger writeback of a page for which we
1884 		 * no longer have access and (b) page_mkclean() won't find the
1885 		 * stage-2 mapping in the rmap so we can get out-of-whack with
1886 		 * the filesystem when marking the page dirty during unpinning
1887 		 * (see cc5095747edf ("ext4: don't BUG if someone dirty pages
1888 		 * without asking ext4 first")).
1889 		 *
1890 		 * Ideally we'd just restrict ourselves to anonymous pages, but
1891 		 * we also want to allow memfd (i.e. shmem) pages, so check for
1892 		 * pages backed by swap in the knowledge that the GUP pin will
1893 		 * prevent try_to_unmap() from succeeding.
1894 		 */
1895 		ret = -EIO;
1896 		goto unpin;
1897 	}
1898 
1899 	write_lock(&kvm->mmu_lock);
1900 	ret = pkvm_pgtable_stage2_map(pgt, gfn_to_gpa(s2vi.gfn), PAGE_SIZE,
1901 				      page_to_phys(s2vi.page), KVM_PGTABLE_PROT_RWX,
1902 				      hyp_memcache, 0);
1903 	write_unlock(&kvm->mmu_lock);
1904 	if (ret) {
1905 		if (ret == -EAGAIN)
1906 			ret = 0;
1907 		goto unpin;
1908 	}
1909 
1910 	return 0;
1911 unpin:
1912 	unpin_user_page(s2vi.page);
1913 dec_account:
1914 	account_locked_vm(mm, 1, false);
1915 	return ret;
1916 }
1917 
1918 static short kvm_s2_resolve_vma_size(const struct kvm_s2_fault_desc *s2fd,
1919 				     struct kvm_s2_fault_vma_info *s2vi,
1920 				     struct vm_area_struct *vma)
1921 {
1922 	short vma_shift;
1923 
1924 	if (memslot_is_logging(s2fd->memslot)) {
1925 		s2vi->max_map_size = PAGE_SIZE;
1926 		vma_shift = PAGE_SHIFT;
1927 	} else {
1928 		s2vi->max_map_size = PUD_SIZE;
1929 		vma_shift = get_vma_page_shift(vma);
1930 	}
1931 
1932 	switch (vma_shift) {
1933 #ifndef __PAGETABLE_PMD_FOLDED
1934 	case PUD_SHIFT:
1935 		if (fault_supports_stage2_huge_mapping(s2fd, PUD_SIZE))
1936 			break;
1937 		fallthrough;
1938 #endif
1939 	case CONT_PMD_SHIFT:
1940 		vma_shift = PMD_SHIFT;
1941 		fallthrough;
1942 	case PMD_SHIFT:
1943 		if (fault_supports_stage2_huge_mapping(s2fd, PMD_SIZE))
1944 			break;
1945 		fallthrough;
1946 	case CONT_PTE_SHIFT:
1947 		vma_shift = PAGE_SHIFT;
1948 		s2vi->max_map_size = PAGE_SIZE;
1949 		fallthrough;
1950 	case PAGE_SHIFT:
1951 		break;
1952 	default:
1953 		WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
1954 	}
1955 
1956 	if (s2fd->nested) {
1957 		unsigned long max_map_size;
1958 
1959 		max_map_size = min(s2vi->max_map_size, PUD_SIZE);
1960 
1961 		/*
1962 		 * If we're about to create a shadow stage 2 entry, then we
1963 		 * can only create a block mapping if the guest stage 2 page
1964 		 * table uses at least as big a mapping.
1965 		 */
1966 		max_map_size = min(kvm_s2_trans_size(s2fd->nested), max_map_size);
1967 
1968 		/*
1969 		 * Be careful that if the mapping size falls between
1970 		 * two host sizes, take the smallest of the two.
1971 		 */
1972 		if (max_map_size >= PMD_SIZE && max_map_size < PUD_SIZE)
1973 			max_map_size = PMD_SIZE;
1974 		else if (max_map_size >= PAGE_SIZE && max_map_size < PMD_SIZE)
1975 			max_map_size = PAGE_SIZE;
1976 
1977 		s2vi->max_map_size = max_map_size;
1978 		vma_shift = min_t(short, vma_shift, __ffs(max_map_size));
1979 	}
1980 
1981 	return vma_shift;
1982 }
1983 
1984 static int kvm_s2_fault_get_vma_info(const struct kvm_s2_fault_desc *s2fd,
1985 				     struct kvm_s2_fault_vma_info *s2vi)
1986 {
1987 	struct vm_area_struct *vma;
1988 	struct kvm *kvm = s2fd->vcpu->kvm;
1989 
1990 	mmap_read_lock(current->mm);
1991 	vma = vma_lookup(current->mm, s2fd->hva);
1992 	if (unlikely(!vma)) {
1993 		kvm_err("Failed to find VMA for hva 0x%lx\n", s2fd->hva);
1994 		mmap_read_unlock(current->mm);
1995 		return -EFAULT;
1996 	}
1997 
1998 	s2vi->vma_pagesize = BIT(kvm_s2_resolve_vma_size(s2fd, s2vi, vma));
1999 
2000 	/*
2001 	 * Both the canonical IPA and fault IPA must be aligned to the
2002 	 * mapping size to ensure we find the right PFN and lay down the
2003 	 * mapping in the right place.
2004 	 */
2005 	s2vi->gfn = ALIGN_DOWN(s2fd->fault_ipa, s2vi->vma_pagesize) >> PAGE_SHIFT;
2006 
2007 	s2vi->mte_allowed = kvm_vma_mte_allowed(vma);
2008 
2009 	s2vi->vm_flags = vma->vm_flags;
2010 
2011 	s2vi->is_vma_cacheable = kvm_vma_is_cacheable(vma);
2012 
2013 	/*
2014 	 * Read mmu_invalidate_seq so that KVM can detect if the results of
2015 	 * vma_lookup() or __kvm_faultin_pfn() become stale prior to
2016 	 * acquiring kvm->mmu_lock.
2017 	 *
2018 	 * Rely on mmap_read_unlock() for an implicit smp_rmb(), which pairs
2019 	 * with the smp_wmb() in kvm_mmu_invalidate_end().
2020 	 */
2021 	s2vi->mmu_seq = kvm->mmu_invalidate_seq;
2022 	mmap_read_unlock(current->mm);
2023 
2024 	return 0;
2025 }
2026 
2027 static gfn_t get_canonical_gfn(const struct kvm_s2_fault_desc *s2fd,
2028 			       const struct kvm_s2_fault_vma_info *s2vi)
2029 {
2030 	phys_addr_t ipa;
2031 
2032 	if (!s2fd->nested)
2033 		return s2vi->gfn;
2034 
2035 	ipa = kvm_s2_trans_output(s2fd->nested);
2036 	return ALIGN_DOWN(ipa, s2vi->vma_pagesize) >> PAGE_SHIFT;
2037 }
2038 
2039 static int kvm_s2_fault_pin_pfn(const struct kvm_s2_fault_desc *s2fd,
2040 				struct kvm_s2_fault_vma_info *s2vi)
2041 {
2042 	int ret;
2043 
2044 	ret = kvm_s2_fault_get_vma_info(s2fd, s2vi);
2045 	if (ret)
2046 		return ret;
2047 
2048 	s2vi->pfn = __kvm_faultin_pfn(s2fd->memslot, get_canonical_gfn(s2fd, s2vi),
2049 				      kvm_s2_fault_is_write(s2fd) ? FOLL_WRITE : 0,
2050 				      &s2vi->map_writable, &s2vi->page);
2051 	if (unlikely(is_error_noslot_pfn(s2vi->pfn))) {
2052 		if (s2vi->pfn == KVM_PFN_ERR_HWPOISON)
2053 			return -EHWPOISON;
2054 		return -EFAULT;
2055 	}
2056 
2057 	/*
2058 	 * Check if this is non-struct page memory PFN, and cannot support
2059 	 * CMOs. It could potentially be unsafe to access as cacheable.
2060 	 */
2061 	if (s2vi->vm_flags & (VM_PFNMAP | VM_MIXEDMAP) && !pfn_is_map_memory(s2vi->pfn)) {
2062 		if (s2vi->is_vma_cacheable) {
2063 			/*
2064 			 * Whilst the VMA owner expects cacheable mapping to this
2065 			 * PFN, hardware also has to support the FWB and CACHE DIC
2066 			 * features.
2067 			 *
2068 			 * ARM64 KVM relies on kernel VA mapping to the PFN to
2069 			 * perform cache maintenance as the CMO instructions work on
2070 			 * virtual addresses. VM_PFNMAP region are not necessarily
2071 			 * mapped to a KVA and hence the presence of hardware features
2072 			 * S2FWB and CACHE DIC are mandatory to avoid the need for
2073 			 * cache maintenance.
2074 			 */
2075 			if (!kvm_supports_cacheable_pfnmap()) {
2076 				kvm_release_faultin_page(s2fd->vcpu->kvm, s2vi->page, true, false);
2077 				return -EFAULT;
2078 			}
2079 		} else {
2080 			s2vi->map_non_cacheable = true;
2081 		}
2082 
2083 		s2vi->device = true;
2084 	}
2085 
2086 	return 1;
2087 }
2088 
2089 static int kvm_s2_fault_compute_prot(const struct kvm_s2_fault_desc *s2fd,
2090 				     const struct kvm_s2_fault_vma_info *s2vi,
2091 				     enum kvm_pgtable_prot *prot)
2092 {
2093 	struct kvm *kvm = s2fd->vcpu->kvm;
2094 
2095 	if (kvm_s2_fault_is_exec(s2fd) && s2vi->map_non_cacheable)
2096 		return -ENOEXEC;
2097 
2098 	/*
2099 	 * Guest performs atomic/exclusive operations on memory with unsupported
2100 	 * attributes (e.g. ld64b/st64b on normal memory when no FEAT_LS64WB)
2101 	 * and trigger the exception here. Since the memslot is valid, inject
2102 	 * the fault back to the guest.
2103 	 */
2104 	if (esr_fsc_is_excl_atomic_fault(s2fd->esr)) {
2105 		kvm_inject_dabt_excl_atomic(s2fd->vcpu, kvm_vcpu_get_hfar(s2fd->vcpu));
2106 		return 1;
2107 	}
2108 
2109 	*prot = KVM_PGTABLE_PROT_R;
2110 
2111 	if (s2vi->map_writable && (s2vi->device ||
2112 				   !memslot_is_logging(s2fd->memslot) ||
2113 				   kvm_s2_fault_is_write(s2fd)))
2114 		*prot |= KVM_PGTABLE_PROT_W;
2115 
2116 	if (s2fd->nested)
2117 		*prot = adjust_nested_fault_perms(s2fd->nested, *prot);
2118 
2119 	if (kvm_s2_fault_is_exec(s2fd))
2120 		*prot |= KVM_PGTABLE_PROT_X;
2121 
2122 	if (s2vi->map_non_cacheable)
2123 		*prot |= (s2vi->vm_flags & VM_ALLOW_ANY_UNCACHED) ?
2124 			KVM_PGTABLE_PROT_NORMAL_NC : KVM_PGTABLE_PROT_DEVICE;
2125 	else if (cpus_have_final_cap(ARM64_HAS_CACHE_DIC))
2126 		*prot |= KVM_PGTABLE_PROT_X;
2127 
2128 	if (s2fd->nested)
2129 		*prot = adjust_nested_exec_perms(kvm, s2fd->nested, *prot);
2130 
2131 	if (!kvm_s2_fault_is_perm(s2fd) && !s2vi->map_non_cacheable && kvm_has_mte(kvm)) {
2132 		/* Check the VMM hasn't introduced a new disallowed VMA */
2133 		if (!s2vi->mte_allowed)
2134 			return -EFAULT;
2135 	}
2136 
2137 	return 0;
2138 }
2139 
2140 static int kvm_s2_fault_map(const struct kvm_s2_fault_desc *s2fd,
2141 			    const struct kvm_s2_fault_vma_info *s2vi,
2142 			    enum kvm_pgtable_prot prot,
2143 			    void *memcache,
2144 			    struct kvm_s2_fault_result *result)
2145 {
2146 	enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
2147 	struct kvm_guest_s2_mapping *mapping = NULL;
2148 	bool writable = prot & KVM_PGTABLE_PROT_W;
2149 	struct kvm *kvm = s2fd->vcpu->kvm;
2150 	phys_addr_t canonical_ipa;
2151 	struct kvm_pgtable *pgt;
2152 	long perm_fault_granule;
2153 	long mapping_size;
2154 	kvm_pfn_t pfn;
2155 	gfn_t gfn;
2156 	int ret;
2157 
2158 	if (kvm_is_nested_s2_mmu(kvm, s2fd->mmu)) {
2159 		mapping = kmalloc_obj(struct kvm_guest_s2_mapping,
2160 				      GFP_KERNEL_ACCOUNT);
2161 		if (!mapping) {
2162 			kvm_release_page_unused(s2vi->page);
2163 			return -ENOMEM;
2164 		}
2165 	}
2166 
2167 	kvm_fault_lock(kvm);
2168 	pgt = s2fd->mmu->pgt;
2169 	ret = -EAGAIN;
2170 	if (mmu_invalidate_retry(kvm, s2vi->mmu_seq))
2171 		goto out_unlock;
2172 
2173 	perm_fault_granule = kvm_s2_perm_fault_granule(s2fd);
2174 	mapping_size = s2vi->vma_pagesize;
2175 	pfn = s2vi->pfn;
2176 	gfn = s2vi->gfn;
2177 	canonical_ipa = gfn_to_gpa(get_canonical_gfn(s2fd, s2vi));
2178 
2179 	/*
2180 	 * If we are not forced to use page mapping, check if we are
2181 	 * backed by a huge stage-1 mapping and thus use block mapping if
2182 	 * possible.
2183 	 */
2184 	if (mapping_size == PAGE_SIZE && s2vi->max_map_size != PAGE_SIZE) {
2185 		if (perm_fault_granule > PAGE_SIZE) {
2186 			mapping_size = perm_fault_granule;
2187 		} else {
2188 			mapping_size = transparent_hugepage_adjust(s2fd, &pfn, &gfn);
2189 			if (mapping_size < 0) {
2190 				ret = mapping_size;
2191 				goto out_unlock;
2192 			}
2193 		}
2194 		canonical_ipa = ALIGN_DOWN(canonical_ipa, mapping_size);
2195 	}
2196 
2197 	if (!perm_fault_granule && !s2vi->map_non_cacheable && kvm_has_mte(kvm))
2198 		sanitise_mte_tags(kvm, pfn, mapping_size);
2199 
2200 	/*
2201 	 * Under the premise of getting a FSC_PERM fault, we just need to relax
2202 	 * permissions only if mapping_size equals perm_fault_granule. Otherwise,
2203 	 * kvm_pgtable_stage2_map() should be called to change block size.
2204 	 */
2205 	if (mapping_size == perm_fault_granule) {
2206 		/*
2207 		 * Drop the SW bits in favour of those stored in the
2208 		 * PTE, which will be preserved.
2209 		 */
2210 		prot &= ~KVM_NV_GUEST_MAP_SZ;
2211 		ret = KVM_PGT_FN(kvm_pgtable_stage2_relax_perms)(pgt, gfn_to_gpa(gfn),
2212 								 prot, flags);
2213 	} else {
2214 		ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, gfn_to_gpa(gfn), mapping_size,
2215 							 __pfn_to_phys(pfn), prot,
2216 							 memcache, flags);
2217 		/*
2218 		 * -EAGAIN from kvm_pgtable_stage2_map() can install mappings.
2219 		 * We don't know which subrange is installed, track the whole
2220 		 * thing.
2221 		 */
2222 		if ((ret == 0 || ret == -EAGAIN) && kvm_is_nested_s2_mmu(kvm, pgt->mmu)) {
2223 			kvm_record_guest_s2_mapping(pgt->mmu, canonical_ipa,
2224 						    gfn_to_gpa(gfn), mapping_size, mapping);
2225 			mapping = NULL;
2226 		}
2227 	}
2228 
2229 out_unlock:
2230 	kvm_release_faultin_page(kvm, s2vi->page, !!ret, writable);
2231 	kvm_fault_unlock(kvm);
2232 	kfree(mapping);
2233 
2234 	/*
2235 	 * Mark the page dirty only if the fault is handled successfully,
2236 	 * making sure we adjust the canonical IPA if the mapping size has
2237 	 * been updated (via a THP upgrade, for example).
2238 	 */
2239 	if (writable && !ret)
2240 		mark_page_dirty_in_slot(kvm, s2fd->memslot,
2241 					gpa_to_gfn(canonical_ipa));
2242 
2243 	if (ret == -EAGAIN)
2244 		return result ? ret : 0;
2245 
2246 	if (result && !ret)
2247 		result->mapping_size = mapping_size;
2248 
2249 	return ret;
2250 }
2251 
2252 static int user_mem_abort(const struct kvm_s2_fault_desc *s2fd,
2253 			  struct kvm_s2_fault_result *result)
2254 {
2255 	bool perm_fault = kvm_s2_fault_is_perm(s2fd);
2256 	struct kvm_s2_fault_vma_info s2vi = {};
2257 	enum kvm_pgtable_prot prot;
2258 	void *memcache;
2259 	int ret;
2260 
2261 	/*
2262 	 * Permission faults just need to update the existing leaf entry,
2263 	 * and so normally don't require allocations from the memcache. The
2264 	 * only exception to this is when dirty logging is enabled at runtime
2265 	 * and a fault needs to collapse a block entry into a table.
2266 	 * Under pKVM a permission fault can also collapse pages into a block,
2267 	 * which needs a fresh mapping object, and the hypervisor requires the
2268 	 * min-pages memcache even when the install allocates nothing.
2269 	 */
2270 	memcache = get_mmu_memcache(s2fd->vcpu);
2271 	if (!perm_fault || memslot_is_logging(s2fd->memslot) ||
2272 	    is_protected_kvm_enabled()) {
2273 		ret = topup_mmu_memcache(s2fd->mmu, memcache);
2274 		if (ret)
2275 			return ret;
2276 	}
2277 
2278 	ret = kvm_s2_fault_pin_pfn(s2fd, &s2vi);
2279 	if (ret == -EHWPOISON) {
2280 		/* If result is specified, let the caller handle this. */
2281 		if (result)
2282 			return -EHWPOISON;
2283 		kvm_send_hwpoison_signal(s2fd->hva, __ffs(s2vi.vma_pagesize));
2284 		return 0;
2285 	}
2286 	if (ret != 1)
2287 		return ret;
2288 
2289 	ret = kvm_s2_fault_compute_prot(s2fd, &s2vi, &prot);
2290 	if (ret) {
2291 		kvm_release_page_unused(s2vi.page);
2292 		return ret;
2293 	}
2294 
2295 	return kvm_s2_fault_map(s2fd, &s2vi, prot, memcache, result);
2296 }
2297 
2298 static int kvm_vm_mem_abort(const struct kvm_s2_fault_desc *s2fd)
2299 {
2300 	VM_WARN_ON_ONCE(kvm_s2_fault_is_perm(s2fd) &&
2301 			!esr_abt_is_write_fault(s2fd->esr) &&
2302 			!kvm_s2_fault_is_exec(s2fd));
2303 
2304 	if (kvm_slot_has_gmem(s2fd->memslot))
2305 		return gmem_abort(s2fd, NULL);
2306 	else
2307 		return user_mem_abort(s2fd, NULL);
2308 }
2309 
2310 /* Resolve the access fault by making the page young again. */
2311 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
2312 {
2313 	enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
2314 	struct kvm_s2_mmu *mmu;
2315 
2316 	trace_kvm_access_fault(fault_ipa);
2317 
2318 	read_lock(&vcpu->kvm->mmu_lock);
2319 	mmu = vcpu->arch.hw_mmu;
2320 	KVM_PGT_FN(kvm_pgtable_stage2_mkyoung)(mmu->pgt, fault_ipa, flags);
2321 	read_unlock(&vcpu->kvm->mmu_lock);
2322 }
2323 
2324 /*
2325  * Returns true if the SEA should be handled locally within KVM if the abort
2326  * is caused by a kernel memory allocation (e.g. stage-2 table memory).
2327  */
2328 static bool host_owns_sea(struct kvm_vcpu *vcpu, u64 esr)
2329 {
2330 	/*
2331 	 * Without FEAT_RAS HCR_EL2.TEA is RES0, meaning any external abort
2332 	 * taken from a guest EL to EL2 is due to a host-imposed access (e.g.
2333 	 * stage-2 PTW).
2334 	 */
2335 	if (!cpus_have_final_cap(ARM64_HAS_RAS_EXTN))
2336 		return true;
2337 
2338 	/* KVM owns the VNCR when the vCPU isn't in a nested context. */
2339 	if (is_hyp_ctxt(vcpu) && !kvm_vcpu_trap_is_iabt(vcpu) && (esr & ESR_ELx_VNCR))
2340 		return true;
2341 
2342 	/*
2343 	 * Determining if an external abort during a table walk happened at
2344 	 * stage-2 is only possible with S1PTW is set. Otherwise, since KVM
2345 	 * sets HCR_EL2.TEA, SEAs due to a stage-1 walk (i.e. accessing the
2346 	 * PA of the stage-1 descriptor) can reach here and are reported
2347 	 * with a TTW ESR value.
2348 	 */
2349 	return (esr_fsc_is_sea_ttw(esr) && (esr & ESR_ELx_S1PTW));
2350 }
2351 
2352 int kvm_handle_guest_sea(struct kvm_vcpu *vcpu)
2353 {
2354 	struct kvm *kvm = vcpu->kvm;
2355 	struct kvm_run *run = vcpu->run;
2356 	u64 esr = kvm_vcpu_get_esr(vcpu);
2357 	u64 esr_mask = ESR_ELx_EC_MASK	|
2358 		       ESR_ELx_IL	|
2359 		       ESR_ELx_FnV	|
2360 		       ESR_ELx_EA	|
2361 		       ESR_ELx_CM	|
2362 		       ESR_ELx_WNR	|
2363 		       ESR_ELx_FSC;
2364 	u64 ipa;
2365 
2366 	/*
2367 	 * Give APEI the opportunity to claim the abort before handling it
2368 	 * within KVM. apei_claim_sea() expects to be called with IRQs enabled.
2369 	 */
2370 	lockdep_assert_irqs_enabled();
2371 	if (apei_claim_sea(NULL) == 0)
2372 		return 1;
2373 
2374 	if (host_owns_sea(vcpu, esr) ||
2375 	    !test_bit(KVM_ARCH_FLAG_EXIT_SEA, &vcpu->kvm->arch.flags))
2376 		return kvm_inject_serror(vcpu);
2377 
2378 	/* ESR_ELx.SET is RES0 when FEAT_RAS isn't implemented. */
2379 	if (kvm_has_ras(kvm))
2380 		esr_mask |= ESR_ELx_SET_MASK;
2381 
2382 	/*
2383 	 * Exit to userspace, and provide faulting guest virtual and physical
2384 	 * addresses in case userspace wants to emulate SEA to guest by
2385 	 * writing to FAR_ELx and HPFAR_ELx registers.
2386 	 */
2387 	memset(&run->arm_sea, 0, sizeof(run->arm_sea));
2388 	run->exit_reason = KVM_EXIT_ARM_SEA;
2389 	run->arm_sea.esr = esr & esr_mask;
2390 
2391 	if (!(esr & ESR_ELx_FnV))
2392 		run->arm_sea.gva = kvm_vcpu_get_hfar(vcpu);
2393 
2394 	ipa = kvm_vcpu_get_fault_ipa(vcpu);
2395 	if (ipa != INVALID_GPA) {
2396 		run->arm_sea.flags |= KVM_EXIT_ARM_SEA_FLAG_GPA_VALID;
2397 		run->arm_sea.gpa = ipa;
2398 	}
2399 
2400 	return 0;
2401 }
2402 
2403 /**
2404  * kvm_handle_guest_abort - handles all 2nd stage aborts
2405  * @vcpu:	the VCPU pointer
2406  *
2407  * Any abort that gets to the host is almost guaranteed to be caused by a
2408  * missing second stage translation table entry, which can mean that either the
2409  * guest simply needs more memory and we must allocate an appropriate page or it
2410  * can mean that the guest tried to access I/O memory, which is emulated by user
2411  * space. The distinction is based on the IPA causing the fault and whether this
2412  * memory region has been registered as standard RAM by user space.
2413  */
2414 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
2415 {
2416 	struct kvm_s2_trans nested_trans, *nested = NULL;
2417 	unsigned long esr = kvm_vcpu_get_esr(vcpu);
2418 	struct kvm_s2_mmu *mmu = vcpu->arch.hw_mmu;
2419 	struct kvm *kvm = vcpu->kvm;
2420 	phys_addr_t fault_ipa; /* The address we faulted on */
2421 	phys_addr_t ipa; /* Always the IPA in the L1 guest phys space */
2422 	struct kvm_memory_slot *memslot;
2423 	unsigned long hva;
2424 	bool is_iabt, write_fault, writable;
2425 	gfn_t gfn;
2426 	int ret, idx;
2427 
2428 	if (esr_abt_is_sea(esr))
2429 		return kvm_handle_guest_sea(vcpu);
2430 
2431 	/*
2432 	 * The fault IPA should be reliable at this point as we're not dealing
2433 	 * with an SEA.
2434 	 */
2435 	ipa = fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
2436 	if (KVM_BUG_ON(ipa == INVALID_GPA, kvm))
2437 		return -EFAULT;
2438 
2439 	is_iabt = esr_trap_is_iabt(esr);
2440 
2441 	if (esr_fsc_is_translation_fault(esr)) {
2442 		/* Beyond sanitised PARange (which is the IPA limit) */
2443 		if (fault_ipa >= BIT_ULL(get_kvm_ipa_limit())) {
2444 			kvm_inject_size_fault(vcpu);
2445 			return 1;
2446 		}
2447 
2448 		/* Falls between the IPA range and the PARange? */
2449 		if (fault_ipa >= BIT_ULL(VTCR_EL2_IPA(mmu->vtcr))) {
2450 			fault_ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
2451 
2452 			return kvm_inject_sea(vcpu, is_iabt, fault_ipa);
2453 		}
2454 	}
2455 
2456 	trace_kvm_guest_fault(*vcpu_pc(vcpu), esr,
2457 			      kvm_vcpu_get_hfar(vcpu), fault_ipa);
2458 
2459 	/* Check the stage-2 fault is trans. fault or write fault */
2460 	if (!esr_fsc_is_translation_fault(esr) &&
2461 	    !esr_fsc_is_permission_fault(esr) &&
2462 	    !esr_fsc_is_access_flag_fault(esr) &&
2463 	    !esr_fsc_is_excl_atomic_fault(esr)) {
2464 		kvm_err("Unsupported FSC: EC=%#lx xFSC=%#lx ESR_EL2=%#lx\n",
2465 			ESR_ELx_EC(esr),
2466 			(unsigned long)(esr & ESR_ELx_FSC),
2467 			(unsigned long)esr);
2468 		return -EFAULT;
2469 	}
2470 
2471 	idx = srcu_read_lock(&kvm->srcu);
2472 
2473 	/*
2474 	 * We may have faulted on a shadow stage 2 page table if we are
2475 	 * running a nested guest.  In this case, we have to resolve the L2
2476 	 * IPA to the L1 IPA first, before knowing what kind of memory should
2477 	 * back the L1 IPA.
2478 	 *
2479 	 * If the shadow stage 2 page table walk faults, then we simply inject
2480 	 * this to the guest and carry on.
2481 	 *
2482 	 * If there are no shadow S2 PTs because S2 is disabled, there is
2483 	 * nothing to walk and we treat it as a 1:1 before going through the
2484 	 * canonical translation.
2485 	 */
2486 	if (kvm_is_nested_s2_mmu(kvm, mmu) && mmu->nested_stage2_enabled) {
2487 		u32 esr;
2488 
2489 		ret = kvm_walk_nested_s2(vcpu, fault_ipa, &nested_trans);
2490 		if (ret == -EAGAIN) {
2491 			ret = 1;
2492 			goto out_unlock;
2493 		}
2494 
2495 		if (ret) {
2496 			esr = kvm_s2_trans_esr(&nested_trans);
2497 			kvm_inject_s2_fault(vcpu, esr);
2498 			goto out_unlock;
2499 		}
2500 
2501 		ret = kvm_s2_handle_perm_fault(vcpu, &nested_trans);
2502 		if (ret) {
2503 			esr = kvm_s2_trans_esr(&nested_trans);
2504 			kvm_inject_s2_fault(vcpu, esr);
2505 			goto out_unlock;
2506 		}
2507 
2508 		ipa = kvm_s2_trans_output(&nested_trans);
2509 		nested = &nested_trans;
2510 	}
2511 
2512 	gfn = ipa >> PAGE_SHIFT;
2513 	memslot = gfn_to_memslot(kvm, gfn);
2514 	hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
2515 	write_fault = esr_abt_is_write_fault(esr);
2516 	if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
2517 		/*
2518 		 * The guest has put either its instructions or its page-tables
2519 		 * somewhere it shouldn't have. Userspace won't be able to do
2520 		 * anything about this (there's no syndrome for a start), so
2521 		 * re-inject the abort back into the guest.
2522 		 */
2523 		if (is_iabt) {
2524 			ret = -ENOEXEC;
2525 			goto out;
2526 		}
2527 
2528 		if (esr_abt_is_s1ptw(esr)) {
2529 			ret = kvm_inject_sea_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
2530 			goto out_unlock;
2531 		}
2532 
2533 		/*
2534 		 * Check for a cache maintenance operation. Since we
2535 		 * ended-up here, we know it is outside of any memory
2536 		 * slot. But we can't find out if that is for a device,
2537 		 * or if the guest is just being stupid. The only thing
2538 		 * we know for sure is that this range cannot be cached.
2539 		 *
2540 		 * So let's assume that the guest is just being
2541 		 * cautious, and skip the instruction.
2542 		 */
2543 		if (kvm_is_error_hva(hva) && esr_dabt_is_cm(esr)) {
2544 			kvm_incr_pc(vcpu);
2545 			ret = 1;
2546 			goto out_unlock;
2547 		}
2548 
2549 		/*
2550 		 * The IPA is reported as [MAX:12], so we need to
2551 		 * complement it with the bottom 12 bits from the
2552 		 * faulting VA. This is always 12 bits, irrespective
2553 		 * of the page size.
2554 		 */
2555 		ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
2556 		ret = io_mem_abort(vcpu, ipa);
2557 		goto out_unlock;
2558 	}
2559 
2560 	/* Userspace should not be able to register out-of-bounds IPAs */
2561 	VM_BUG_ON(ipa >= kvm_phys_size(mmu));
2562 
2563 	if (esr_fsc_is_access_flag_fault(esr)) {
2564 		handle_access_fault(vcpu, fault_ipa);
2565 		ret = 1;
2566 		goto out_unlock;
2567 	}
2568 
2569 	const struct kvm_s2_fault_desc s2fd = {
2570 		.vcpu		= vcpu,
2571 		.fault_ipa	= fault_ipa,
2572 		.nested		= nested,
2573 		.memslot	= memslot,
2574 		.hva		= hva,
2575 		.esr		= esr,
2576 		.mmu		= mmu,
2577 	};
2578 
2579 	ret = kvm->arch.vm_s2_ops->vm_mem_abort(&s2fd);
2580 	if (ret == 0)
2581 		ret = 1;
2582 out:
2583 	if (ret == -ENOEXEC)
2584 		ret = kvm_inject_sea_iabt(vcpu, kvm_vcpu_get_hfar(vcpu));
2585 out_unlock:
2586 	srcu_read_unlock(&kvm->srcu, idx);
2587 	return ret;
2588 }
2589 
2590 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
2591 {
2592 	gpa_t gpa = range->start << PAGE_SHIFT;
2593 	size_t size = (range->end - range->start) << PAGE_SHIFT;
2594 	bool may_block = range->may_block;
2595 
2596 	if (!kvm->arch.mmu.pgt)
2597 		return false;
2598 
2599 	kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, size, may_block);
2600 	kvm_nested_unmap_cipa_range(kvm, gpa, size, may_block);
2601 
2602 	return false;
2603 }
2604 
2605 static bool kvm_vm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2606 {
2607 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2608 
2609 	return kvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2610 						   range->start << PAGE_SHIFT,
2611 						   size, true);
2612 }
2613 
2614 static bool pkvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2615 {
2616 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2617 
2618 	return pkvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2619 						    range->start << PAGE_SHIFT,
2620 						    size, true);
2621 }
2622 
2623 static bool no_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2624 {
2625 	/* The hypervisor doesn't support aging */
2626 	return false;
2627 }
2628 
2629 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2630 {
2631 	if (!kvm->arch.mmu.pgt)
2632 		return false;
2633 
2634 	return kvm->arch.vm_s2_ops->vm_age_gfn(kvm, range);
2635 	/*
2636 	 * TODO: Handle nested_mmu structures here using the reverse mapping in
2637 	 * a later version of patch series.
2638 	 */
2639 }
2640 
2641 static bool kvm_vm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2642 {
2643 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2644 
2645 	return kvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2646 						   range->start << PAGE_SHIFT,
2647 						   size, false);
2648 }
2649 
2650 static bool pkvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2651 {
2652 	u64 size = (range->end - range->start) << PAGE_SHIFT;
2653 
2654 	return pkvm_pgtable_stage2_test_clear_young(kvm->arch.mmu.pgt,
2655 						    range->start << PAGE_SHIFT,
2656 						    size, false);
2657 }
2658 
2659 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
2660 {
2661 	if (!kvm->arch.mmu.pgt)
2662 		return false;
2663 
2664 	return kvm->arch.vm_s2_ops->vm_test_age_gfn(kvm, range);
2665 }
2666 
2667 phys_addr_t kvm_mmu_get_httbr(void)
2668 {
2669 	return __pa(hyp_pgtable->pgd);
2670 }
2671 
2672 phys_addr_t kvm_get_idmap_vector(void)
2673 {
2674 	return hyp_idmap_vector;
2675 }
2676 
2677 static int kvm_map_idmap_text(void)
2678 {
2679 	unsigned long size = hyp_idmap_end - hyp_idmap_start;
2680 	int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
2681 					PAGE_HYP_EXEC);
2682 	if (err)
2683 		kvm_err("Failed to idmap %lx-%lx\n",
2684 			hyp_idmap_start, hyp_idmap_end);
2685 
2686 	return err;
2687 }
2688 
2689 static void *kvm_hyp_zalloc_page(void *arg)
2690 {
2691 	return (void *)get_zeroed_page(GFP_KERNEL);
2692 }
2693 
2694 static struct kvm_pgtable_mm_ops kvm_hyp_mm_ops = {
2695 	.zalloc_page		= kvm_hyp_zalloc_page,
2696 	.get_page		= kvm_host_get_page,
2697 	.put_page		= kvm_host_put_page,
2698 	.phys_to_virt		= kvm_host_va,
2699 	.virt_to_phys		= kvm_host_pa,
2700 };
2701 
2702 int __init kvm_mmu_init(u32 hyp_va_bits)
2703 {
2704 	int err;
2705 
2706 	hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
2707 	hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
2708 	hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
2709 	hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
2710 	hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
2711 
2712 	/*
2713 	 * We rely on the linker script to ensure at build time that the HYP
2714 	 * init code does not cross a page boundary.
2715 	 */
2716 	BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
2717 
2718 	kvm_debug("Using %u-bit virtual addresses at EL2\n", hyp_va_bits);
2719 	kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
2720 	kvm_debug("HYP VA range: %lx:%lx\n",
2721 		  kern_hyp_va(PAGE_OFFSET),
2722 		  kern_hyp_va((unsigned long)high_memory - 1));
2723 
2724 	if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
2725 	    hyp_idmap_start <  kern_hyp_va((unsigned long)high_memory - 1) &&
2726 	    hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
2727 		/*
2728 		 * The idmap page is intersecting with the VA space,
2729 		 * it is not safe to continue further.
2730 		 */
2731 		kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
2732 		err = -EINVAL;
2733 		goto out;
2734 	}
2735 
2736 	hyp_pgtable = kzalloc_obj(*hyp_pgtable);
2737 	if (!hyp_pgtable) {
2738 		kvm_err("Hyp mode page-table not allocated\n");
2739 		err = -ENOMEM;
2740 		goto out;
2741 	}
2742 
2743 	err = kvm_pgtable_hyp_init(hyp_pgtable, hyp_va_bits, &kvm_hyp_mm_ops);
2744 	if (err)
2745 		goto out_free_pgtable;
2746 
2747 	err = kvm_map_idmap_text();
2748 	if (err)
2749 		goto out_destroy_pgtable;
2750 
2751 	io_map_base = hyp_idmap_start;
2752 	__hyp_va_bits = hyp_va_bits;
2753 	return 0;
2754 
2755 out_destroy_pgtable:
2756 	kvm_pgtable_hyp_destroy(hyp_pgtable);
2757 out_free_pgtable:
2758 	kfree(hyp_pgtable);
2759 	hyp_pgtable = NULL;
2760 out:
2761 	return err;
2762 }
2763 
2764 void kvm_arch_commit_memory_region(struct kvm *kvm,
2765 				   struct kvm_memory_slot *old,
2766 				   const struct kvm_memory_slot *new,
2767 				   enum kvm_mr_change change)
2768 {
2769 	bool log_dirty_pages = new && new->flags & KVM_MEM_LOG_DIRTY_PAGES;
2770 
2771 	/*
2772 	 * At this point memslot has been committed and there is an
2773 	 * allocated dirty_bitmap[], dirty pages will be tracked while the
2774 	 * memory slot is write protected.
2775 	 */
2776 	if (log_dirty_pages) {
2777 
2778 		if (change == KVM_MR_DELETE)
2779 			return;
2780 
2781 		/*
2782 		 * Huge and normal pages are write-protected and split
2783 		 * on either of these two cases:
2784 		 *
2785 		 * 1. with initial-all-set: gradually with CLEAR ioctls,
2786 		 */
2787 		if (kvm_dirty_log_manual_protect_and_init_set(kvm))
2788 			return;
2789 		/*
2790 		 * or
2791 		 * 2. without initial-all-set: all in one shot when
2792 		 *    enabling dirty logging.
2793 		 */
2794 		kvm_mmu_wp_memory_region(kvm, new->id);
2795 		kvm_mmu_split_memory_region(kvm, new->id);
2796 	} else {
2797 		/*
2798 		 * Free any leftovers from the eager page splitting cache. Do
2799 		 * this when deleting, moving, disabling dirty logging, or
2800 		 * creating the memslot (a nop). Doing it for deletes makes
2801 		 * sure we don't leak memory, and there's no need to keep the
2802 		 * cache around for any of the other cases.
2803 		 */
2804 		kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
2805 	}
2806 }
2807 
2808 int kvm_arch_prepare_memory_region(struct kvm *kvm,
2809 				   const struct kvm_memory_slot *old,
2810 				   struct kvm_memory_slot *new,
2811 				   enum kvm_mr_change change)
2812 {
2813 	hva_t hva, reg_end;
2814 	int ret = 0;
2815 
2816 	if (kvm_vm_is_protected(kvm)) {
2817 		/* Cannot modify memslots once a pVM has run. */
2818 		if (pkvm_hyp_vm_is_created(kvm) &&
2819 		    (change == KVM_MR_DELETE || change == KVM_MR_MOVE)) {
2820 			return -EPERM;
2821 		}
2822 
2823 		if (new &&
2824 		    new->flags & (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY)) {
2825 			return -EPERM;
2826 		}
2827 	}
2828 
2829 	if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
2830 			change != KVM_MR_FLAGS_ONLY)
2831 		return 0;
2832 
2833 	/*
2834 	 * Prevent userspace from creating a memory region outside of the IPA
2835 	 * space addressable by the KVM guest IPA space.
2836 	 */
2837 	if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT))
2838 		return -EFAULT;
2839 
2840 	/*
2841 	 * Only support guest_memfd backed memslots with mappable memory, since
2842 	 * there aren't any CoCo VMs that support only private memory on arm64.
2843 	 */
2844 	if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
2845 		return -EINVAL;
2846 
2847 	/* guest_memfd is incompatible with MTE. */
2848 	if (kvm_slot_has_gmem(new) && kvm_has_mte(kvm))
2849 		return -EINVAL;
2850 
2851 	hva = new->userspace_addr;
2852 	reg_end = hva + (new->npages << PAGE_SHIFT);
2853 
2854 	mmap_read_lock(current->mm);
2855 	/*
2856 	 * A memory region could potentially cover multiple VMAs, and any holes
2857 	 * between them, so iterate over all of them.
2858 	 *
2859 	 *     +--------------------------------------------+
2860 	 * +---------------+----------------+   +----------------+
2861 	 * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
2862 	 * +---------------+----------------+   +----------------+
2863 	 *     |               memory region                |
2864 	 *     +--------------------------------------------+
2865 	 */
2866 	do {
2867 		struct vm_area_struct *vma;
2868 
2869 		vma = find_vma_intersection(current->mm, hva, reg_end);
2870 		if (!vma)
2871 			break;
2872 
2873 		if (kvm_has_mte(kvm) && !kvm_vma_mte_allowed(vma)) {
2874 			ret = -EINVAL;
2875 			break;
2876 		}
2877 
2878 		if (vma->vm_flags & VM_PFNMAP) {
2879 			/* IO region dirty page logging not allowed */
2880 			if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
2881 				ret = -EINVAL;
2882 				break;
2883 			}
2884 
2885 			/*
2886 			 * Cacheable PFNMAP is allowed only if the hardware
2887 			 * supports it.
2888 			 */
2889 			if (kvm_vma_is_cacheable(vma) && !kvm_supports_cacheable_pfnmap()) {
2890 				ret = -EINVAL;
2891 				break;
2892 			}
2893 		}
2894 		hva = min(reg_end, vma->vm_end);
2895 	} while (hva < reg_end);
2896 
2897 	mmap_read_unlock(current->mm);
2898 	return ret;
2899 }
2900 
2901 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
2902 {
2903 }
2904 
2905 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
2906 {
2907 }
2908 
2909 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
2910 				   struct kvm_memory_slot *slot)
2911 {
2912 	gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
2913 	phys_addr_t size = slot->npages << PAGE_SHIFT;
2914 
2915 	write_lock(&kvm->mmu_lock);
2916 	kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, size, true);
2917 	kvm_nested_unmap_cipa_range(kvm, gpa, size, true);
2918 	write_unlock(&kvm->mmu_lock);
2919 }
2920 
2921 /*
2922  * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
2923  *
2924  * Main problems:
2925  * - S/W ops are local to a CPU (not broadcast)
2926  * - We have line migration behind our back (speculation)
2927  * - System caches don't support S/W at all (damn!)
2928  *
2929  * In the face of the above, the best we can do is to try and convert
2930  * S/W ops to VA ops. Because the guest is not allowed to infer the
2931  * S/W to PA mapping, it can only use S/W to nuke the whole cache,
2932  * which is a rather good thing for us.
2933  *
2934  * Also, it is only used when turning caches on/off ("The expected
2935  * usage of the cache maintenance instructions that operate by set/way
2936  * is associated with the cache maintenance instructions associated
2937  * with the powerdown and powerup of caches, if this is required by
2938  * the implementation.").
2939  *
2940  * We use the following policy:
2941  *
2942  * - If we trap a S/W operation, we enable VM trapping to detect
2943  *   caches being turned on/off, and do a full clean.
2944  *
2945  * - We flush the caches on both caches being turned on and off.
2946  *
2947  * - Once the caches are enabled, we stop trapping VM ops.
2948  */
2949 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
2950 {
2951 	unsigned long hcr = *vcpu_hcr(vcpu);
2952 
2953 	/*
2954 	 * If this is the first time we do a S/W operation
2955 	 * (i.e. HCR_TVM not set) flush the whole memory, and set the
2956 	 * VM trapping.
2957 	 *
2958 	 * Otherwise, rely on the VM trapping to wait for the MMU +
2959 	 * Caches to be turned off. At that point, we'll be able to
2960 	 * clean the caches again.
2961 	 */
2962 	if (!(hcr & HCR_TVM)) {
2963 		trace_kvm_set_way_flush(*vcpu_pc(vcpu),
2964 					vcpu_has_cache_enabled(vcpu));
2965 		stage2_flush_vm(vcpu->kvm);
2966 		*vcpu_hcr(vcpu) = hcr | HCR_TVM;
2967 	}
2968 }
2969 
2970 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
2971 {
2972 	bool now_enabled = vcpu_has_cache_enabled(vcpu);
2973 
2974 	/*
2975 	 * If switching the MMU+caches on, need to invalidate the caches.
2976 	 * If switching it off, need to clean the caches.
2977 	 * Clean + invalidate does the trick always.
2978 	 */
2979 	if (now_enabled != was_enabled)
2980 		stage2_flush_vm(vcpu->kvm);
2981 
2982 	/* Caches are now on, stop trapping VM ops (until a S/W op) */
2983 	if (now_enabled)
2984 		*vcpu_hcr(vcpu) &= ~HCR_TVM;
2985 
2986 	trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
2987 }
2988 
2989 /*
2990  * Try to walk to the specified GPA in canonical mmu - if unmapped returns 0, if
2991  * mapped returns the granule size, otherwise returns an error.
2992  */
2993 static long kvm_walk_s2(struct kvm_pgtable *pgt,
2994 			gpa_t gpa, s8 *level)
2995 {
2996 	struct kvm *kvm = kvm_s2_mmu_to_kvm(pgt->mmu);
2997 	kvm_pte_t pte;
2998 	long ret;
2999 
3000 	guard(read_lock)(&kvm->mmu_lock);
3001 
3002 	ret = kvm_pgtable_get_leaf(pgt, gpa, &pte, level,
3003 				   KVM_PGTABLE_WALK_SHARED);
3004 	if (ret)
3005 		return ret;
3006 	/* Unpopulated, must fault. */
3007 	if (!kvm_pte_valid(pte))
3008 		return 0;
3009 	return kvm_granule_size(*level);
3010 }
3011 
3012 /* Synthesised data abort at specified page table level. */
3013 #define PRE_FAULT_ESR(level)				\
3014 	 ((ESR_ELx_EC_DABT_LOW << ESR_ELx_EC_SHIFT) |	\
3015 	  ESR_ELx_IL | ESR_ELx_FSC_FAULT_L(level))
3016 
3017 /* Retrieve either a read-only or a read/write hva. */
3018 static hva_t gfn_to_hva_memslot_read(struct kvm_memory_slot *slot, gfn_t gfn)
3019 {
3020 	return gfn_to_hva_memslot_prot(slot, gfn, /*writable=*/NULL);
3021 }
3022 
3023 static long __pre_fault_s2(struct kvm_s2_mmu *mmu, struct kvm_vcpu *vcpu,
3024 			   gpa_t gpa, struct kvm_memory_slot *memslot, s8 level)
3025 {
3026 	const bool is_gmem = kvm_slot_has_gmem(memslot);
3027 	const gfn_t gfn = gpa_to_gfn(gpa);
3028 	const hva_t hva = is_gmem ? 0 : gfn_to_hva_memslot_read(memslot, gfn);
3029 	const struct kvm_s2_fault_desc s2fd = {
3030 		.vcpu		= vcpu,
3031 		.fault_ipa	= gpa,
3032 		.nested		= NULL,
3033 		.memslot	= memslot,
3034 		.hva		= hva,
3035 		.esr		= PRE_FAULT_ESR(level),
3036 		.mmu		= mmu,
3037 	};
3038 	struct kvm_s2_fault_result result = {};
3039 	long ret;
3040 
3041 	if (kvm_is_error_hva(hva))
3042 		return -EFAULT;
3043 
3044 	if (is_gmem)
3045 		ret = gmem_abort(&s2fd, &result);
3046 	else
3047 		ret = user_mem_abort(&s2fd, &result);
3048 	if (IS_ERR_VALUE(ret))
3049 		return ret;
3050 	return result.mapping_size;
3051 }
3052 
3053 static long pre_fault_s2(struct kvm_s2_mmu *mmu, struct kvm_vcpu *vcpu,
3054 			 gpa_t gpa, struct kvm_memory_slot *memslot)
3055 {
3056 	s8 level;
3057 	long ret;
3058 
3059 	/* Try a walk first. */
3060 	ret = kvm_walk_s2(mmu->pgt, gpa, &level);
3061 	if (ret)
3062 		return ret;
3063 	/* OK, have to fault page in. */
3064 	return __pre_fault_s2(mmu, vcpu, gpa, memslot, level);
3065 }
3066 
3067 static unsigned long
3068 pre_fault_bytes_consumed(gpa_t gpa, unsigned long granule_size,
3069 			 unsigned long bytes_remaining)
3070 {
3071 	/* Granules are always a power-of-2. */
3072 	const unsigned long granule_bytes_remaining =
3073 		granule_size - (gpa % granule_size);
3074 
3075 	return min(granule_bytes_remaining, bytes_remaining);
3076 }
3077 
3078 /* If you lose the race this many times, time to give up. */
3079 #define MAX_PRE_FAULT_RETRIES 3
3080 
3081 int kvm_arch_pre_fault_allowed(struct kvm_vcpu *vcpu)
3082 {
3083 	if (is_protected_kvm_enabled())
3084 		return -EOPNOTSUPP;
3085 	if (!kvm_vcpu_initialized(vcpu))
3086 		return -ENOEXEC;
3087 
3088 	return 0;
3089 }
3090 
3091 /**
3092  * kvm_arch_vcpu_pre_fault_memory - pre-fault stage-2 page tables for the
3093  * specified GPA.
3094  * @vcpu:	The VCPU pointer
3095  * @range:	{gpa, size, flags} tuple
3096  *
3097  * The mapping performed is always best-effort - faulting in is necessarily
3098  * racey. The ranges faulted in are canonical, nested page tables are ignored.
3099  *
3100  * @range->gpa specifies the GPA to pre-fault, @range->size specifies how many
3101  * bytes remain to be pre-faulted and @range->flags is reserved and must be 0.
3102  *
3103  * Returns: the number of bytes the pre-fault consumed, or an error.
3104  */
3105 long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
3106 				    struct kvm_pre_fault_memory *range)
3107 {
3108 	struct kvm *kvm = vcpu->kvm;
3109 	const u64 bytes_remaining = range->size;
3110 	struct kvm_s2_mmu *mmu = &kvm->arch.mmu; /* Canonical. */
3111 	struct kvm_memory_slot *memslot;
3112 	const gpa_t gpa = range->gpa;
3113 	int num_retries = 0;
3114 	long ret;
3115 
3116 	memslot = gfn_to_memslot(kvm, gpa_to_gfn(gpa));
3117 	if (!memslot)
3118 		return -ENOENT;
3119 	/* SRCU must be released for progress and only userland can do that. */
3120 	if (memslot->flags & KVM_MEMSLOT_INVALID)
3121 		return -EAGAIN;
3122 
3123 	do {
3124 		ret = pre_fault_s2(mmu, vcpu, gpa, memslot);
3125 	} while (ret == -EAGAIN && num_retries++ < MAX_PRE_FAULT_RETRIES);
3126 
3127 	if (IS_ERR_VALUE(ret))
3128 		return ret;
3129 	return pre_fault_bytes_consumed(gpa, ret, bytes_remaining);
3130 }
3131 
3132 static const struct kvm_vm_s2_ops protected_pkvm_vm_s2_ops = {
3133 	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
3134 	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
3135 	.vm_age_gfn			= no_age_gfn,
3136 	.vm_test_age_gfn		= no_age_gfn,
3137 	.vm_stage2_unmap_range		= no_stage2_unmap_range,
3138 	.vm_mem_abort			= protected_pkvm_mem_abort,
3139 };
3140 
3141 static const struct kvm_vm_s2_ops pkvm_vm_s2_ops = {
3142 	.vm_flush_remote_tlbs		= pkvm_flush_remote_tlbs,
3143 	.vm_flush_remote_tlbs_range	= pkvm_flush_remote_tlbs_range,
3144 	.vm_age_gfn			= pkvm_age_gfn,
3145 	.vm_test_age_gfn		= pkvm_test_age_gfn,
3146 	.vm_stage2_unmap_range		= pkvm_stage2_unmap_range,
3147 	.vm_mem_abort			= kvm_vm_mem_abort,
3148 };
3149 
3150 static const struct kvm_vm_s2_ops kvm_default_vm_s2_ops = {
3151 	.vm_flush_remote_tlbs		= kvm_vm_flush_remote_tlbs,
3152 	.vm_flush_remote_tlbs_range	= kvm_vm_flush_remote_tlbs_range,
3153 	.vm_age_gfn			= kvm_vm_age_gfn,
3154 	.vm_test_age_gfn		= kvm_vm_test_age_gfn,
3155 	.vm_stage2_unmap_range		= kvm_vm_stage2_unmap_range,
3156 	.vm_mem_abort			= kvm_vm_mem_abort,
3157 };
3158 
3159 #define KVM_VM_S2_OPS(flavor, ops)		\
3160 		[(flavor)] = &(ops)
3161 
3162 static const struct kvm_vm_s2_ops *arm64_vm_s2_ops[] = {
3163 	KVM_VM_S2_OPS(VM_VHE, kvm_default_vm_s2_ops),
3164 	KVM_VM_S2_OPS(VM_NVHE, kvm_default_vm_s2_ops),
3165 	KVM_VM_S2_OPS(VM_PKVM, pkvm_vm_s2_ops),
3166 	KVM_VM_S2_OPS(VM_PROTECTED_PKVM, protected_pkvm_vm_s2_ops),
3167 };
3168 
3169 static int kvm_vm_init_vm_s2_ops(struct kvm *kvm)
3170 {
3171 	BUILD_BUG_ON(ARRAY_SIZE(arm64_vm_s2_ops) != VM_FLAVOR_MAX);
3172 
3173 	kvm->arch.vm_s2_ops = arm64_vm_s2_ops[kvm->arch.vm_flavor];
3174 	if (WARN_ON(!kvm->arch.vm_s2_ops))
3175 		return -EINVAL;
3176 	return 0;
3177 }
3178