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