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