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