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