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_call_hyp(__kvm_tlb_flush_vmid, &kvm->arch.mmu);
84 ++kvm->stat.remote_tlb_flush;
85 }
86
kvm_is_device_pfn(unsigned long pfn)87 static bool kvm_is_device_pfn(unsigned long pfn)
88 {
89 return !pfn_valid(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 = vabits_actual,
608 .start_level = (KVM_PGTABLE_MAX_LEVELS -
609 CONFIG_PGTABLE_LEVELS),
610 .mm_ops = &kvm_user_mm_ops,
611 };
612 kvm_pte_t pte = 0; /* Keep GCC quiet... */
613 u32 level = ~0;
614 int ret;
615
616 ret = kvm_pgtable_get_leaf(&pgt, addr, &pte, &level);
617 VM_BUG_ON(ret);
618 VM_BUG_ON(level >= KVM_PGTABLE_MAX_LEVELS);
619 VM_BUG_ON(!(pte & PTE_VALID));
620
621 return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(level));
622 }
623
624 static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
625 .zalloc_page = stage2_memcache_zalloc_page,
626 .zalloc_pages_exact = kvm_host_zalloc_pages_exact,
627 .free_pages_exact = free_pages_exact,
628 .get_page = kvm_host_get_page,
629 .put_page = kvm_host_put_page,
630 .page_count = kvm_host_page_count,
631 .phys_to_virt = kvm_host_va,
632 .virt_to_phys = kvm_host_pa,
633 .dcache_clean_inval_poc = clean_dcache_guest_page,
634 .icache_inval_pou = invalidate_icache_guest_page,
635 };
636
637 /**
638 * kvm_init_stage2_mmu - Initialise a S2 MMU strucrure
639 * @kvm: The pointer to the KVM structure
640 * @mmu: The pointer to the s2 MMU structure
641 * @type: The machine type of the virtual machine
642 *
643 * Allocates only the stage-2 HW PGD level table(s).
644 * Note we don't need locking here as this is only called when the VM is
645 * created, which can only be done once.
646 */
kvm_init_stage2_mmu(struct kvm * kvm,struct kvm_s2_mmu * mmu,unsigned long type)647 int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long type)
648 {
649 u32 kvm_ipa_limit = get_kvm_ipa_limit();
650 int cpu, err;
651 struct kvm_pgtable *pgt;
652 u64 mmfr0, mmfr1;
653 u32 phys_shift;
654
655 phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
656 if (is_protected_kvm_enabled()) {
657 phys_shift = kvm_ipa_limit;
658 } else if (phys_shift) {
659 if (phys_shift > kvm_ipa_limit ||
660 phys_shift < ARM64_MIN_PARANGE_BITS)
661 return -EINVAL;
662 } else {
663 phys_shift = KVM_PHYS_SHIFT;
664 if (phys_shift > kvm_ipa_limit) {
665 pr_warn_once("%s using unsupported default IPA limit, upgrade your VMM\n",
666 current->comm);
667 return -EINVAL;
668 }
669 }
670
671 mmfr0 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
672 mmfr1 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
673 kvm->arch.vtcr = kvm_get_vtcr(mmfr0, mmfr1, phys_shift);
674 INIT_LIST_HEAD(&kvm->arch.pkvm.pinned_pages);
675 mmu->arch = &kvm->arch;
676
677 if (is_protected_kvm_enabled())
678 return 0;
679
680 if (mmu->pgt != NULL) {
681 kvm_err("kvm_arch already initialized?\n");
682 return -EINVAL;
683 }
684
685 pgt = kzalloc(sizeof(*pgt), GFP_KERNEL_ACCOUNT);
686 if (!pgt)
687 return -ENOMEM;
688
689 mmu->arch = &kvm->arch;
690 err = kvm_pgtable_stage2_init(pgt, mmu, &kvm_s2_mm_ops);
691 if (err)
692 goto out_free_pgtable;
693
694 mmu->last_vcpu_ran = alloc_percpu(typeof(*mmu->last_vcpu_ran));
695 if (!mmu->last_vcpu_ran) {
696 err = -ENOMEM;
697 goto out_destroy_pgtable;
698 }
699
700 for_each_possible_cpu(cpu)
701 *per_cpu_ptr(mmu->last_vcpu_ran, cpu) = -1;
702
703 mmu->pgt = pgt;
704 mmu->pgd_phys = __pa(pgt->pgd);
705 WRITE_ONCE(mmu->vmid.vmid_gen, 0);
706 return 0;
707
708 out_destroy_pgtable:
709 kvm_pgtable_stage2_destroy(pgt);
710 out_free_pgtable:
711 kfree(pgt);
712 return err;
713 }
714
stage2_unmap_memslot(struct kvm * kvm,struct kvm_memory_slot * memslot)715 static void stage2_unmap_memslot(struct kvm *kvm,
716 struct kvm_memory_slot *memslot)
717 {
718 hva_t hva = memslot->userspace_addr;
719 phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
720 phys_addr_t size = PAGE_SIZE * memslot->npages;
721 hva_t reg_end = hva + size;
722
723 /*
724 * A memory region could potentially cover multiple VMAs, and any holes
725 * between them, so iterate over all of them to find out if we should
726 * unmap any of them.
727 *
728 * +--------------------------------------------+
729 * +---------------+----------------+ +----------------+
730 * | : VMA 1 | VMA 2 | | VMA 3 : |
731 * +---------------+----------------+ +----------------+
732 * | memory region |
733 * +--------------------------------------------+
734 */
735 do {
736 struct vm_area_struct *vma;
737 hva_t vm_start, vm_end;
738
739 vma = find_vma_intersection(current->mm, hva, reg_end);
740 if (!vma)
741 break;
742
743 /*
744 * Take the intersection of this VMA with the memory region
745 */
746 vm_start = max(hva, vma->vm_start);
747 vm_end = min(reg_end, vma->vm_end);
748
749 if (!(vma->vm_flags & VM_PFNMAP)) {
750 gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
751 unmap_stage2_range(&kvm->arch.mmu, gpa, vm_end - vm_start);
752 }
753 hva = vm_end;
754 } while (hva < reg_end);
755 }
756
757 /**
758 * stage2_unmap_vm - Unmap Stage-2 RAM mappings
759 * @kvm: The struct kvm pointer
760 *
761 * Go through the memregions and unmap any regular RAM
762 * backing memory already mapped to the VM.
763 */
stage2_unmap_vm(struct kvm * kvm)764 void stage2_unmap_vm(struct kvm *kvm)
765 {
766 struct kvm_memslots *slots;
767 struct kvm_memory_slot *memslot;
768 int idx;
769
770 idx = srcu_read_lock(&kvm->srcu);
771 mmap_read_lock(current->mm);
772 spin_lock(&kvm->mmu_lock);
773
774 slots = kvm_memslots(kvm);
775 kvm_for_each_memslot(memslot, slots)
776 stage2_unmap_memslot(kvm, memslot);
777
778 spin_unlock(&kvm->mmu_lock);
779 mmap_read_unlock(current->mm);
780 srcu_read_unlock(&kvm->srcu, idx);
781 }
782
kvm_free_stage2_pgd(struct kvm_s2_mmu * mmu)783 void kvm_free_stage2_pgd(struct kvm_s2_mmu *mmu)
784 {
785 struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
786 struct kvm_pgtable *pgt = NULL;
787
788 if (is_protected_kvm_enabled())
789 return;
790
791 spin_lock(&kvm->mmu_lock);
792 pgt = mmu->pgt;
793 if (pgt) {
794 mmu->pgd_phys = 0;
795 mmu->pgt = NULL;
796 free_percpu(mmu->last_vcpu_ran);
797 }
798 spin_unlock(&kvm->mmu_lock);
799
800 if (pgt) {
801 kvm_pgtable_stage2_destroy(pgt);
802 kfree(pgt);
803 }
804 }
805
hyp_mc_free_fn(void * addr,void * unused)806 static void hyp_mc_free_fn(void *addr, void *unused)
807 {
808 free_page((unsigned long)addr);
809 }
810
hyp_mc_alloc_fn(void * unused)811 static void *hyp_mc_alloc_fn(void *unused)
812 {
813 return (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
814 }
815
free_hyp_memcache(struct kvm_hyp_memcache * mc)816 void free_hyp_memcache(struct kvm_hyp_memcache *mc)
817 {
818 if (is_protected_kvm_enabled())
819 __free_hyp_memcache(mc, hyp_mc_free_fn,
820 kvm_host_va, NULL);
821 }
822
topup_hyp_memcache(struct kvm_vcpu * vcpu)823 int topup_hyp_memcache(struct kvm_vcpu *vcpu)
824 {
825 if (!is_protected_kvm_enabled())
826 return 0;
827
828 return __topup_hyp_memcache(&vcpu->arch.pkvm_memcache,
829 kvm_mmu_cache_min_pages(vcpu->kvm),
830 hyp_mc_alloc_fn,
831 kvm_host_pa, NULL);
832 }
833
834 /**
835 * kvm_phys_addr_ioremap - map a device range to guest IPA
836 *
837 * @kvm: The KVM pointer
838 * @guest_ipa: The IPA at which to insert the mapping
839 * @pa: The physical address of the device
840 * @size: The size of the mapping
841 * @writable: Whether or not to create a writable mapping
842 */
kvm_phys_addr_ioremap(struct kvm * kvm,phys_addr_t guest_ipa,phys_addr_t pa,unsigned long size,bool writable)843 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
844 phys_addr_t pa, unsigned long size, bool writable)
845 {
846 phys_addr_t addr;
847 int ret = 0;
848 struct kvm_mmu_memory_cache cache = { 0, __GFP_ZERO, NULL, };
849 struct kvm_pgtable *pgt = kvm->arch.mmu.pgt;
850 enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_DEVICE |
851 KVM_PGTABLE_PROT_R |
852 (writable ? KVM_PGTABLE_PROT_W : 0);
853
854 if (is_protected_kvm_enabled())
855 return -EPERM;
856
857 size += offset_in_page(guest_ipa);
858 guest_ipa &= PAGE_MASK;
859
860 for (addr = guest_ipa; addr < guest_ipa + size; addr += PAGE_SIZE) {
861 ret = kvm_mmu_topup_memory_cache(&cache,
862 kvm_mmu_cache_min_pages(kvm));
863 if (ret)
864 break;
865
866 spin_lock(&kvm->mmu_lock);
867 ret = kvm_pgtable_stage2_map(pgt, addr, PAGE_SIZE, pa, prot,
868 &cache);
869 spin_unlock(&kvm->mmu_lock);
870 if (ret)
871 break;
872
873 pa += PAGE_SIZE;
874 }
875
876 kvm_mmu_free_memory_cache(&cache);
877 return ret;
878 }
879
880 /**
881 * stage2_wp_range() - write protect stage2 memory region range
882 * @mmu: The KVM stage-2 MMU pointer
883 * @addr: Start address of range
884 * @end: End address of range
885 */
stage2_wp_range(struct kvm_s2_mmu * mmu,phys_addr_t addr,phys_addr_t end)886 static void stage2_wp_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
887 {
888 struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
889 stage2_apply_range_resched(kvm, addr, end, kvm_pgtable_stage2_wrprotect);
890 }
891
892 /**
893 * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
894 * @kvm: The KVM pointer
895 * @slot: The memory slot to write protect
896 *
897 * Called to start logging dirty pages after memory region
898 * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
899 * all present PUD, PMD and PTEs are write protected in the memory region.
900 * Afterwards read of dirty page log can be called.
901 *
902 * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
903 * serializing operations for VM memory regions.
904 */
kvm_mmu_wp_memory_region(struct kvm * kvm,int slot)905 static void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
906 {
907 struct kvm_memslots *slots = kvm_memslots(kvm);
908 struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
909 phys_addr_t start, end;
910
911 if (WARN_ON_ONCE(!memslot))
912 return;
913
914 start = memslot->base_gfn << PAGE_SHIFT;
915 end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
916
917 spin_lock(&kvm->mmu_lock);
918 stage2_wp_range(&kvm->arch.mmu, start, end);
919 spin_unlock(&kvm->mmu_lock);
920 kvm_flush_remote_tlbs(kvm);
921 }
922
923 /**
924 * kvm_mmu_write_protect_pt_masked() - write protect dirty pages
925 * @kvm: The KVM pointer
926 * @slot: The memory slot associated with mask
927 * @gfn_offset: The gfn offset in memory slot
928 * @mask: The mask of dirty pages at offset 'gfn_offset' in this memory
929 * slot to be write protected
930 *
931 * Walks bits set in mask write protects the associated pte's. Caller must
932 * acquire kvm_mmu_lock.
933 */
kvm_mmu_write_protect_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)934 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
935 struct kvm_memory_slot *slot,
936 gfn_t gfn_offset, unsigned long mask)
937 {
938 phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
939 phys_addr_t start = (base_gfn + __ffs(mask)) << PAGE_SHIFT;
940 phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
941
942 stage2_wp_range(&kvm->arch.mmu, start, end);
943 }
944
945 /*
946 * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
947 * dirty pages.
948 *
949 * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
950 * enable dirty logging for them.
951 */
kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn_offset,unsigned long mask)952 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
953 struct kvm_memory_slot *slot,
954 gfn_t gfn_offset, unsigned long mask)
955 {
956 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
957 }
958
kvm_send_hwpoison_signal(unsigned long address,short lsb)959 static void kvm_send_hwpoison_signal(unsigned long address, short lsb)
960 {
961 send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, current);
962 }
963
fault_supports_stage2_huge_mapping(struct kvm_memory_slot * memslot,unsigned long hva,unsigned long map_size)964 static bool fault_supports_stage2_huge_mapping(struct kvm_memory_slot *memslot,
965 unsigned long hva,
966 unsigned long map_size)
967 {
968 gpa_t gpa_start;
969 hva_t uaddr_start, uaddr_end;
970 size_t size;
971
972 /* The memslot and the VMA are guaranteed to be aligned to PAGE_SIZE */
973 if (map_size == PAGE_SIZE)
974 return true;
975
976 size = memslot->npages * PAGE_SIZE;
977
978 gpa_start = memslot->base_gfn << PAGE_SHIFT;
979
980 uaddr_start = memslot->userspace_addr;
981 uaddr_end = uaddr_start + size;
982
983 /*
984 * Pages belonging to memslots that don't have the same alignment
985 * within a PMD/PUD for userspace and IPA cannot be mapped with stage-2
986 * PMD/PUD entries, because we'll end up mapping the wrong pages.
987 *
988 * Consider a layout like the following:
989 *
990 * memslot->userspace_addr:
991 * +-----+--------------------+--------------------+---+
992 * |abcde|fgh Stage-1 block | Stage-1 block tv|xyz|
993 * +-----+--------------------+--------------------+---+
994 *
995 * memslot->base_gfn << PAGE_SHIFT:
996 * +---+--------------------+--------------------+-----+
997 * |abc|def Stage-2 block | Stage-2 block |tvxyz|
998 * +---+--------------------+--------------------+-----+
999 *
1000 * If we create those stage-2 blocks, we'll end up with this incorrect
1001 * mapping:
1002 * d -> f
1003 * e -> g
1004 * f -> h
1005 */
1006 if ((gpa_start & (map_size - 1)) != (uaddr_start & (map_size - 1)))
1007 return false;
1008
1009 /*
1010 * Next, let's make sure we're not trying to map anything not covered
1011 * by the memslot. This means we have to prohibit block size mappings
1012 * for the beginning and end of a non-block aligned and non-block sized
1013 * memory slot (illustrated by the head and tail parts of the
1014 * userspace view above containing pages 'abcde' and 'xyz',
1015 * respectively).
1016 *
1017 * Note that it doesn't matter if we do the check using the
1018 * userspace_addr or the base_gfn, as both are equally aligned (per
1019 * the check above) and equally sized.
1020 */
1021 return (hva & ~(map_size - 1)) >= uaddr_start &&
1022 (hva & ~(map_size - 1)) + map_size <= uaddr_end;
1023 }
1024
1025 /*
1026 * Check if the given hva is backed by a transparent huge page (THP) and
1027 * whether it can be mapped using block mapping in stage2. If so, adjust
1028 * the stage2 PFN and IPA accordingly. Only PMD_SIZE THPs are currently
1029 * supported. This will need to be updated to support other THP sizes.
1030 *
1031 * Returns the size of the mapping.
1032 */
1033 static unsigned long
transparent_hugepage_adjust(struct kvm * kvm,struct kvm_memory_slot * memslot,unsigned long hva,kvm_pfn_t * pfnp,phys_addr_t * ipap)1034 transparent_hugepage_adjust(struct kvm *kvm, struct kvm_memory_slot *memslot,
1035 unsigned long hva, kvm_pfn_t *pfnp,
1036 phys_addr_t *ipap)
1037 {
1038 kvm_pfn_t pfn = *pfnp;
1039
1040 /*
1041 * Make sure the adjustment is done only for THP pages. Also make
1042 * sure that the HVA and IPA are sufficiently aligned and that the
1043 * block map is contained within the memslot.
1044 */
1045 if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE) &&
1046 get_user_mapping_size(kvm, hva) >= PMD_SIZE) {
1047 /*
1048 * The address we faulted on is backed by a transparent huge
1049 * page. However, because we map the compound huge page and
1050 * not the individual tail page, we need to transfer the
1051 * refcount to the head page. We have to be careful that the
1052 * THP doesn't start to split while we are adjusting the
1053 * refcounts.
1054 *
1055 * We are sure this doesn't happen, because mmu_notifier_retry
1056 * was successful and we are holding the mmu_lock, so if this
1057 * THP is trying to split, it will be blocked in the mmu
1058 * notifier before touching any of the pages, specifically
1059 * before being able to call __split_huge_page_refcount().
1060 *
1061 * We can therefore safely transfer the refcount from PG_tail
1062 * to PG_head and switch the pfn from a tail page to the head
1063 * page accordingly.
1064 */
1065 *ipap &= PMD_MASK;
1066 kvm_release_pfn_clean(pfn);
1067 pfn &= ~(PTRS_PER_PMD - 1);
1068 get_page(pfn_to_page(pfn));
1069 *pfnp = pfn;
1070
1071 return PMD_SIZE;
1072 }
1073
1074 /* Use page mapping if we cannot use block mapping. */
1075 return PAGE_SIZE;
1076 }
1077
get_vma_page_shift(struct vm_area_struct * vma,unsigned long hva)1078 static int get_vma_page_shift(struct vm_area_struct *vma, unsigned long hva)
1079 {
1080 unsigned long pa;
1081
1082 if (is_vm_hugetlb_page(vma) && !(vma->vm_flags & VM_PFNMAP))
1083 return huge_page_shift(hstate_vma(vma));
1084
1085 if (!(vma->vm_flags & VM_PFNMAP))
1086 return PAGE_SHIFT;
1087
1088 VM_BUG_ON(is_vm_hugetlb_page(vma));
1089
1090 pa = (vma->vm_pgoff << PAGE_SHIFT) + (hva - vma->vm_start);
1091
1092 #ifndef __PAGETABLE_PMD_FOLDED
1093 if ((hva & (PUD_SIZE - 1)) == (pa & (PUD_SIZE - 1)) &&
1094 ALIGN_DOWN(hva, PUD_SIZE) >= vma->vm_start &&
1095 ALIGN(hva, PUD_SIZE) <= vma->vm_end)
1096 return PUD_SHIFT;
1097 #endif
1098
1099 if ((hva & (PMD_SIZE - 1)) == (pa & (PMD_SIZE - 1)) &&
1100 ALIGN_DOWN(hva, PMD_SIZE) >= vma->vm_start &&
1101 ALIGN(hva, PMD_SIZE) <= vma->vm_end)
1102 return PMD_SHIFT;
1103
1104 return PAGE_SHIFT;
1105 }
1106
1107 /*
1108 * The page will be mapped in stage 2 as Normal Cacheable, so the VM will be
1109 * able to see the page's tags and therefore they must be initialised first. If
1110 * PG_mte_tagged is set, tags have already been initialised.
1111 *
1112 * The race in the test/set of the PG_mte_tagged flag is handled by:
1113 * - preventing VM_SHARED mappings in a memslot with MTE preventing two VMs
1114 * racing to santise the same page
1115 * - mmap_lock protects between a VM faulting a page in and the VMM performing
1116 * an mprotect() to add VM_MTE
1117 */
sanitise_mte_tags(struct kvm * kvm,kvm_pfn_t pfn,unsigned long size)1118 static int sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn,
1119 unsigned long size)
1120 {
1121 unsigned long i, nr_pages = size >> PAGE_SHIFT;
1122 struct page *page;
1123
1124 if (!kvm_has_mte(kvm))
1125 return 0;
1126
1127 /*
1128 * pfn_to_online_page() is used to reject ZONE_DEVICE pages
1129 * that may not support tags.
1130 */
1131 page = pfn_to_online_page(pfn);
1132
1133 if (!page)
1134 return -EFAULT;
1135
1136 for (i = 0; i < nr_pages; i++, page++) {
1137 if (!test_bit(PG_mte_tagged, &page->flags)) {
1138 mte_clear_page_tags(page_address(page));
1139 set_bit(PG_mte_tagged, &page->flags);
1140 }
1141 }
1142
1143 return 0;
1144 }
1145
pkvm_host_donate_guest(u64 pfn,u64 gfn)1146 static int pkvm_host_donate_guest(u64 pfn, u64 gfn)
1147 {
1148 struct arm_smccc_res res;
1149
1150 arm_smccc_1_1_hvc(KVM_HOST_SMCCC_FUNC(__pkvm_host_donate_guest),
1151 pfn, gfn, &res);
1152 WARN_ON(res.a0 != SMCCC_RET_SUCCESS);
1153
1154 /*
1155 * Getting -EPERM at this point implies that the pfn has already been
1156 * donated. This should only ever happen when two vCPUs faulted on the
1157 * same page, and the current one lost the race to do the donation.
1158 */
1159 return (res.a1 == -EPERM) ? -EAGAIN : res.a1;
1160 }
1161
pkvm_mem_abort(struct kvm_vcpu * vcpu,phys_addr_t fault_ipa,unsigned long hva)1162 static int pkvm_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1163 unsigned long hva)
1164 {
1165 struct mm_struct *mm = current->mm;
1166 unsigned int flags = FOLL_HWPOISON | FOLL_LONGTERM | FOLL_WRITE;
1167 struct kvm_pinned_page *ppage;
1168 struct kvm *kvm = vcpu->kvm;
1169 struct page *page;
1170 u64 pfn;
1171 int ret;
1172
1173 ret = topup_hyp_memcache(vcpu);
1174 if (ret)
1175 return -ENOMEM;
1176
1177 ppage = kmalloc(sizeof(*ppage), GFP_KERNEL_ACCOUNT);
1178 if (!ppage)
1179 return -ENOMEM;
1180
1181 ret = account_locked_vm(mm, 1, true);
1182 if (ret)
1183 goto free_ppage;
1184
1185 mmap_read_lock(mm);
1186 ret = pin_user_pages(hva, 1, flags, &page, NULL);
1187 mmap_read_unlock(mm);
1188
1189 if (ret == -EHWPOISON) {
1190 kvm_send_hwpoison_signal(hva, PAGE_SHIFT);
1191 ret = 0;
1192 goto dec_account;
1193 } else if (ret != 1) {
1194 ret = -EFAULT;
1195 goto dec_account;
1196 } else if (!PageSwapBacked(page)) {
1197 /*
1198 * We really can't deal with page-cache pages returned by GUP
1199 * because (a) we may trigger writeback of a page for which we
1200 * no longer have access and (b) page_mkclean() won't find the
1201 * stage-2 mapping in the rmap so we can get out-of-whack with
1202 * the filesystem when marking the page dirty during unpinning.
1203 *
1204 * Ideally we'd just restrict ourselves to anonymous pages, but
1205 * we also want to allow memfd (i.e. shmem) pages, so check for
1206 * pages backed by swap in the knowledge that the GUP pin will
1207 * prevent try_to_unmap() from succeeding.
1208 */
1209 ret = -EIO;
1210 goto unpin;
1211 }
1212
1213 spin_lock(&kvm->mmu_lock);
1214 pfn = page_to_pfn(page);
1215 ret = pkvm_host_donate_guest(pfn, fault_ipa >> PAGE_SHIFT);
1216 if (ret) {
1217 if (ret == -EAGAIN)
1218 ret = 0;
1219 goto unlock;
1220 }
1221
1222 ppage->page = page;
1223 INIT_LIST_HEAD(&ppage->link);
1224 list_add(&ppage->link, &kvm->arch.pkvm.pinned_pages);
1225 spin_unlock(&kvm->mmu_lock);
1226
1227 return 0;
1228
1229 unlock:
1230 spin_unlock(&kvm->mmu_lock);
1231 unpin:
1232 unpin_user_pages(&page, 1);
1233 dec_account:
1234 account_locked_vm(mm, 1, false);
1235 free_ppage:
1236 kfree(ppage);
1237
1238 return ret;
1239 }
1240
user_mem_abort(struct kvm_vcpu * vcpu,phys_addr_t fault_ipa,struct kvm_memory_slot * memslot,unsigned long hva,unsigned long fault_status)1241 static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1242 struct kvm_memory_slot *memslot, unsigned long hva,
1243 unsigned long fault_status)
1244 {
1245 int ret = 0;
1246 bool write_fault, writable, force_pte = false;
1247 bool exec_fault;
1248 bool device = false;
1249 bool shared;
1250 unsigned long mmu_seq;
1251 struct kvm *kvm = vcpu->kvm;
1252 struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
1253 struct vm_area_struct *vma;
1254 short vma_shift;
1255 gfn_t gfn;
1256 kvm_pfn_t pfn;
1257 bool logging_active = memslot_is_logging(memslot);
1258 unsigned long fault_level = kvm_vcpu_trap_get_fault_level(vcpu);
1259 unsigned long vma_pagesize, fault_granule;
1260 enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
1261 struct kvm_pgtable *pgt;
1262
1263 fault_granule = 1UL << ARM64_HW_PGTABLE_LEVEL_SHIFT(fault_level);
1264 write_fault = kvm_is_write_fault(vcpu);
1265 exec_fault = kvm_vcpu_trap_is_exec_fault(vcpu);
1266 VM_BUG_ON(write_fault && exec_fault);
1267
1268 if (fault_status == FSC_PERM && !write_fault && !exec_fault) {
1269 kvm_err("Unexpected L2 read permission error\n");
1270 return -EFAULT;
1271 }
1272
1273 /*
1274 * Let's check if we will get back a huge page backed by hugetlbfs, or
1275 * get block mapping for device MMIO region.
1276 */
1277 mmap_read_lock(current->mm);
1278 vma = find_vma_intersection(current->mm, hva, hva + 1);
1279 if (unlikely(!vma)) {
1280 kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
1281 mmap_read_unlock(current->mm);
1282 return -EFAULT;
1283 }
1284
1285 /*
1286 * logging_active is guaranteed to never be true for VM_PFNMAP
1287 * memslots.
1288 */
1289 if (logging_active) {
1290 force_pte = true;
1291 vma_shift = PAGE_SHIFT;
1292 } else {
1293 vma_shift = get_vma_page_shift(vma, hva);
1294 }
1295
1296 shared = (vma->vm_flags & VM_SHARED);
1297
1298 switch (vma_shift) {
1299 #ifndef __PAGETABLE_PMD_FOLDED
1300 case PUD_SHIFT:
1301 if (fault_supports_stage2_huge_mapping(memslot, hva, PUD_SIZE))
1302 break;
1303 fallthrough;
1304 #endif
1305 case CONT_PMD_SHIFT:
1306 vma_shift = PMD_SHIFT;
1307 fallthrough;
1308 case PMD_SHIFT:
1309 if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE))
1310 break;
1311 fallthrough;
1312 case CONT_PTE_SHIFT:
1313 vma_shift = PAGE_SHIFT;
1314 force_pte = true;
1315 fallthrough;
1316 case PAGE_SHIFT:
1317 break;
1318 default:
1319 WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
1320 }
1321
1322 vma_pagesize = 1UL << vma_shift;
1323 if (vma_pagesize == PMD_SIZE || vma_pagesize == PUD_SIZE)
1324 fault_ipa &= ~(vma_pagesize - 1);
1325
1326 gfn = fault_ipa >> PAGE_SHIFT;
1327 mmap_read_unlock(current->mm);
1328
1329 /*
1330 * Permission faults just need to update the existing leaf entry,
1331 * and so normally don't require allocations from the memcache. The
1332 * only exception to this is when dirty logging is enabled at runtime
1333 * and a write fault needs to collapse a block entry into a table.
1334 */
1335 if (fault_status != FSC_PERM || (logging_active && write_fault)) {
1336 ret = kvm_mmu_topup_memory_cache(memcache,
1337 kvm_mmu_cache_min_pages(kvm));
1338 if (ret)
1339 return ret;
1340 }
1341
1342 mmu_seq = vcpu->kvm->mmu_notifier_seq;
1343 /*
1344 * Ensure the read of mmu_notifier_seq happens before we call
1345 * gfn_to_pfn_prot (which calls get_user_pages), so that we don't risk
1346 * the page we just got a reference to gets unmapped before we have a
1347 * chance to grab the mmu_lock, which ensure that if the page gets
1348 * unmapped afterwards, the call to kvm_unmap_hva will take it away
1349 * from us again properly. This smp_rmb() interacts with the smp_wmb()
1350 * in kvm_mmu_notifier_invalidate_<page|range_end>.
1351 *
1352 * Besides, __gfn_to_pfn_memslot() instead of gfn_to_pfn_prot() is
1353 * used to avoid unnecessary overhead introduced to locate the memory
1354 * slot because it's always fixed even @gfn is adjusted for huge pages.
1355 */
1356 smp_rmb();
1357
1358 pfn = __gfn_to_pfn_memslot(memslot, gfn, false, NULL,
1359 write_fault, &writable);
1360 if (pfn == KVM_PFN_ERR_HWPOISON) {
1361 kvm_send_hwpoison_signal(hva, vma_shift);
1362 return 0;
1363 }
1364 if (is_error_noslot_pfn(pfn))
1365 return -EFAULT;
1366
1367 if (kvm_is_device_pfn(pfn)) {
1368 /*
1369 * If the page was identified as device early by looking at
1370 * the VMA flags, vma_pagesize is already representing the
1371 * largest quantity we can map. If instead it was mapped
1372 * via gfn_to_pfn_prot(), vma_pagesize is set to PAGE_SIZE
1373 * and must not be upgraded.
1374 *
1375 * In both cases, we don't let transparent_hugepage_adjust()
1376 * change things at the last minute.
1377 */
1378 device = true;
1379 } else if (logging_active && !write_fault) {
1380 /*
1381 * Only actually map the page as writable if this was a write
1382 * fault.
1383 */
1384 writable = false;
1385 }
1386
1387 if (exec_fault && device)
1388 return -ENOEXEC;
1389
1390 spin_lock(&kvm->mmu_lock);
1391 pgt = vcpu->arch.hw_mmu->pgt;
1392 if (mmu_notifier_retry(kvm, mmu_seq))
1393 goto out_unlock;
1394
1395 /*
1396 * If we are not forced to use page mapping, check if we are
1397 * backed by a THP and thus use block mapping if possible.
1398 */
1399 if (vma_pagesize == PAGE_SIZE && !(force_pte || device)) {
1400 if (fault_status == FSC_PERM && fault_granule > PAGE_SIZE)
1401 vma_pagesize = fault_granule;
1402 else
1403 vma_pagesize = transparent_hugepage_adjust(kvm, memslot,
1404 hva, &pfn,
1405 &fault_ipa);
1406 }
1407
1408 if (fault_status != FSC_PERM && !device && kvm_has_mte(kvm)) {
1409 /* Check the VMM hasn't introduced a new VM_SHARED VMA */
1410 if (!shared)
1411 ret = sanitise_mte_tags(kvm, pfn, vma_pagesize);
1412 else
1413 ret = -EFAULT;
1414 if (ret)
1415 goto out_unlock;
1416 }
1417
1418 if (writable)
1419 prot |= KVM_PGTABLE_PROT_W;
1420
1421 if (exec_fault)
1422 prot |= KVM_PGTABLE_PROT_X;
1423
1424 if (device)
1425 prot |= KVM_PGTABLE_PROT_DEVICE;
1426 else if (cpus_have_const_cap(ARM64_HAS_CACHE_DIC))
1427 prot |= KVM_PGTABLE_PROT_X;
1428
1429 /*
1430 * Under the premise of getting a FSC_PERM fault, we just need to relax
1431 * permissions only if vma_pagesize equals fault_granule. Otherwise,
1432 * kvm_pgtable_stage2_map() should be called to change block size.
1433 */
1434 if (fault_status == FSC_PERM && vma_pagesize == fault_granule) {
1435 ret = kvm_pgtable_stage2_relax_perms(pgt, fault_ipa, prot);
1436 } else {
1437 ret = kvm_pgtable_stage2_map(pgt, fault_ipa, vma_pagesize,
1438 __pfn_to_phys(pfn), prot,
1439 memcache);
1440 }
1441
1442 /* Mark the page dirty only if the fault is handled successfully */
1443 if (writable && !ret) {
1444 kvm_set_pfn_dirty(pfn);
1445 mark_page_dirty_in_slot(memslot, gfn);
1446 }
1447
1448 out_unlock:
1449 spin_unlock(&kvm->mmu_lock);
1450 kvm_set_pfn_accessed(pfn);
1451 kvm_release_pfn_clean(pfn);
1452 return ret != -EAGAIN ? ret : 0;
1453 }
1454
1455 /* Resolve the access fault by making the page young again. */
handle_access_fault(struct kvm_vcpu * vcpu,phys_addr_t fault_ipa)1456 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
1457 {
1458 pte_t pte;
1459 kvm_pte_t kpte;
1460 struct kvm_s2_mmu *mmu;
1461
1462 trace_kvm_access_fault(fault_ipa);
1463
1464 spin_lock(&vcpu->kvm->mmu_lock);
1465 mmu = vcpu->arch.hw_mmu;
1466 kpte = kvm_pgtable_stage2_mkyoung(mmu->pgt, fault_ipa);
1467 spin_unlock(&vcpu->kvm->mmu_lock);
1468
1469 pte = __pte(kpte);
1470 if (pte_valid(pte))
1471 kvm_set_pfn_accessed(pte_pfn(pte));
1472 }
1473
1474 /**
1475 * kvm_handle_guest_abort - handles all 2nd stage aborts
1476 * @vcpu: the VCPU pointer
1477 *
1478 * Any abort that gets to the host is almost guaranteed to be caused by a
1479 * missing second stage translation table entry, which can mean that either the
1480 * guest simply needs more memory and we must allocate an appropriate page or it
1481 * can mean that the guest tried to access I/O memory, which is emulated by user
1482 * space. The distinction is based on the IPA causing the fault and whether this
1483 * memory region has been registered as standard RAM by user space.
1484 */
kvm_handle_guest_abort(struct kvm_vcpu * vcpu)1485 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
1486 {
1487 unsigned long fault_status;
1488 phys_addr_t fault_ipa;
1489 struct kvm_memory_slot *memslot;
1490 unsigned long hva;
1491 bool is_iabt, write_fault, writable;
1492 gfn_t gfn;
1493 int ret, idx;
1494
1495 fault_status = kvm_vcpu_trap_get_fault_type(vcpu);
1496
1497 fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
1498 is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
1499
1500 /* Synchronous External Abort? */
1501 if (kvm_vcpu_abt_issea(vcpu)) {
1502 /*
1503 * For RAS the host kernel may handle this abort.
1504 * There is no need to pass the error into the guest.
1505 */
1506 if (kvm_handle_guest_sea(fault_ipa, kvm_vcpu_get_esr(vcpu)))
1507 kvm_inject_vabt(vcpu);
1508
1509 return 1;
1510 }
1511
1512 trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_esr(vcpu),
1513 kvm_vcpu_get_hfar(vcpu), fault_ipa);
1514
1515 /* Check the stage-2 fault is trans. fault or write fault */
1516 if (fault_status != FSC_FAULT && fault_status != FSC_PERM &&
1517 fault_status != FSC_ACCESS) {
1518 kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
1519 kvm_vcpu_trap_get_class(vcpu),
1520 (unsigned long)kvm_vcpu_trap_get_fault(vcpu),
1521 (unsigned long)kvm_vcpu_get_esr(vcpu));
1522 return -EFAULT;
1523 }
1524
1525 idx = srcu_read_lock(&vcpu->kvm->srcu);
1526
1527 gfn = fault_ipa >> PAGE_SHIFT;
1528 memslot = gfn_to_memslot(vcpu->kvm, gfn);
1529 hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
1530 write_fault = kvm_is_write_fault(vcpu);
1531 if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
1532 /*
1533 * The guest has put either its instructions or its page-tables
1534 * somewhere it shouldn't have. Userspace won't be able to do
1535 * anything about this (there's no syndrome for a start), so
1536 * re-inject the abort back into the guest.
1537 */
1538 if (is_iabt) {
1539 ret = -ENOEXEC;
1540 goto out;
1541 }
1542
1543 if (kvm_vcpu_abt_iss1tw(vcpu)) {
1544 kvm_inject_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1545 ret = 1;
1546 goto out_unlock;
1547 }
1548
1549 /*
1550 * Check for a cache maintenance operation. Since we
1551 * ended-up here, we know it is outside of any memory
1552 * slot. But we can't find out if that is for a device,
1553 * or if the guest is just being stupid. The only thing
1554 * we know for sure is that this range cannot be cached.
1555 *
1556 * So let's assume that the guest is just being
1557 * cautious, and skip the instruction.
1558 */
1559 if (kvm_is_error_hva(hva) && kvm_vcpu_dabt_is_cm(vcpu)) {
1560 kvm_incr_pc(vcpu);
1561 ret = 1;
1562 goto out_unlock;
1563 }
1564
1565 /*
1566 * The IPA is reported as [MAX:12], so we need to
1567 * complement it with the bottom 12 bits from the
1568 * faulting VA. This is always 12 bits, irrespective
1569 * of the page size.
1570 */
1571 fault_ipa |= kvm_vcpu_get_hfar(vcpu) & FAR_MASK;
1572 ret = io_mem_abort(vcpu, fault_ipa);
1573 goto out_unlock;
1574 }
1575
1576 /* Userspace should not be able to register out-of-bounds IPAs */
1577 VM_BUG_ON(fault_ipa >= kvm_phys_size(vcpu->kvm));
1578
1579 if (fault_status == FSC_ACCESS) {
1580 handle_access_fault(vcpu, fault_ipa);
1581 ret = 1;
1582 goto out_unlock;
1583 }
1584
1585
1586 if (is_protected_kvm_enabled())
1587 ret = pkvm_mem_abort(vcpu, fault_ipa, hva);
1588 else
1589 ret = user_mem_abort(vcpu, fault_ipa, memslot, hva, fault_status);
1590 if (ret == 0)
1591 ret = 1;
1592 out:
1593 if (ret == -ENOEXEC) {
1594 kvm_inject_pabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1595 ret = 1;
1596 }
1597 out_unlock:
1598 srcu_read_unlock(&vcpu->kvm->srcu, idx);
1599 return ret;
1600 }
1601
handle_hva_to_gpa(struct kvm * kvm,unsigned long start,unsigned long end,int (* handler)(struct kvm * kvm,gpa_t gpa,u64 size,void * data),void * data)1602 static int handle_hva_to_gpa(struct kvm *kvm,
1603 unsigned long start,
1604 unsigned long end,
1605 int (*handler)(struct kvm *kvm,
1606 gpa_t gpa, u64 size,
1607 void *data),
1608 void *data)
1609 {
1610 struct kvm_memslots *slots;
1611 struct kvm_memory_slot *memslot;
1612 int ret = 0;
1613
1614 slots = kvm_memslots(kvm);
1615
1616 /* we only care about the pages that the guest sees */
1617 kvm_for_each_memslot(memslot, slots) {
1618 unsigned long hva_start, hva_end;
1619 gfn_t gpa;
1620
1621 hva_start = max(start, memslot->userspace_addr);
1622 hva_end = min(end, memslot->userspace_addr +
1623 (memslot->npages << PAGE_SHIFT));
1624 if (hva_start >= hva_end)
1625 continue;
1626
1627 gpa = hva_to_gfn_memslot(hva_start, memslot) << PAGE_SHIFT;
1628 ret |= handler(kvm, gpa, (u64)(hva_end - hva_start), data);
1629 }
1630
1631 return ret;
1632 }
1633
kvm_unmap_hva_handler(struct kvm * kvm,gpa_t gpa,u64 size,void * data)1634 static int kvm_unmap_hva_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1635 {
1636 unsigned flags = *(unsigned *)data;
1637 bool may_block = flags & MMU_NOTIFIER_RANGE_BLOCKABLE;
1638
1639 __unmap_stage2_range(&kvm->arch.mmu, gpa, size, may_block);
1640 return 0;
1641 }
1642
kvm_unmap_hva_range(struct kvm * kvm,unsigned long start,unsigned long end,unsigned flags)1643 int kvm_unmap_hva_range(struct kvm *kvm,
1644 unsigned long start, unsigned long end, unsigned flags)
1645 {
1646 if (!kvm->arch.mmu.pgt)
1647 return 0;
1648
1649 trace_kvm_unmap_hva_range(start, end);
1650 handle_hva_to_gpa(kvm, start, end, &kvm_unmap_hva_handler, &flags);
1651 return 0;
1652 }
1653
kvm_set_spte_handler(struct kvm * kvm,gpa_t gpa,u64 size,void * data)1654 static int kvm_set_spte_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1655 {
1656 kvm_pfn_t *pfn = (kvm_pfn_t *)data;
1657 int ret;
1658
1659 WARN_ON(size != PAGE_SIZE);
1660
1661 ret = sanitise_mte_tags(kvm, *pfn, PAGE_SIZE);
1662 if (ret)
1663 return 0;
1664
1665 /*
1666 * We've moved a page around, probably through CoW, so let's treat
1667 * it just like a translation fault and the map handler will clean
1668 * the cache to the PoC.
1669 *
1670 * The MMU notifiers will have unmapped a huge PMD before calling
1671 * ->change_pte() (which in turn calls kvm_set_spte_hva()) and
1672 * therefore we never need to clear out a huge PMD through this
1673 * calling path and a memcache is not required.
1674 */
1675 kvm_pgtable_stage2_map(kvm->arch.mmu.pgt, gpa, PAGE_SIZE,
1676 __pfn_to_phys(*pfn), KVM_PGTABLE_PROT_R, NULL);
1677 return 0;
1678 }
1679
kvm_set_spte_hva(struct kvm * kvm,unsigned long hva,pte_t pte)1680 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1681 {
1682 unsigned long end = hva + PAGE_SIZE;
1683 kvm_pfn_t pfn = pte_pfn(pte);
1684
1685 if (!kvm->arch.mmu.pgt)
1686 return 0;
1687
1688 trace_kvm_set_spte_hva(hva);
1689
1690 handle_hva_to_gpa(kvm, hva, end, &kvm_set_spte_handler, &pfn);
1691 return 0;
1692 }
1693
kvm_age_hva_handler(struct kvm * kvm,gpa_t gpa,u64 size,void * data)1694 static int kvm_age_hva_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1695 {
1696 pte_t pte;
1697 kvm_pte_t kpte;
1698
1699 WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
1700 kpte = kvm_pgtable_stage2_mkold(kvm->arch.mmu.pgt, gpa);
1701 pte = __pte(kpte);
1702 return pte_valid(pte) && pte_young(pte);
1703 }
1704
kvm_test_age_hva_handler(struct kvm * kvm,gpa_t gpa,u64 size,void * data)1705 static int kvm_test_age_hva_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1706 {
1707 WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
1708 return kvm_pgtable_stage2_is_young(kvm->arch.mmu.pgt, gpa);
1709 }
1710
kvm_age_hva(struct kvm * kvm,unsigned long start,unsigned long end)1711 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1712 {
1713 if (!kvm->arch.mmu.pgt)
1714 return 0;
1715 trace_kvm_age_hva(start, end);
1716 return handle_hva_to_gpa(kvm, start, end, kvm_age_hva_handler, NULL);
1717 }
1718
kvm_test_age_hva(struct kvm * kvm,unsigned long hva)1719 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1720 {
1721 if (!kvm->arch.mmu.pgt)
1722 return 0;
1723 trace_kvm_test_age_hva(hva);
1724 return handle_hva_to_gpa(kvm, hva, hva + PAGE_SIZE,
1725 kvm_test_age_hva_handler, NULL);
1726 }
1727
kvm_mmu_get_httbr(void)1728 phys_addr_t kvm_mmu_get_httbr(void)
1729 {
1730 return __pa(hyp_pgtable->pgd);
1731 }
1732
kvm_get_idmap_vector(void)1733 phys_addr_t kvm_get_idmap_vector(void)
1734 {
1735 return hyp_idmap_vector;
1736 }
1737
kvm_map_idmap_text(void)1738 static int kvm_map_idmap_text(void)
1739 {
1740 unsigned long size = hyp_idmap_end - hyp_idmap_start;
1741 int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
1742 PAGE_HYP_EXEC);
1743 if (err)
1744 kvm_err("Failed to idmap %lx-%lx\n",
1745 hyp_idmap_start, hyp_idmap_end);
1746
1747 return err;
1748 }
1749
kvm_hyp_zalloc_page(void * arg)1750 static void *kvm_hyp_zalloc_page(void *arg)
1751 {
1752 return (void *)get_zeroed_page(GFP_KERNEL);
1753 }
1754
1755 static struct kvm_pgtable_mm_ops kvm_hyp_mm_ops = {
1756 .zalloc_page = kvm_hyp_zalloc_page,
1757 .get_page = kvm_host_get_page,
1758 .put_page = kvm_host_put_page,
1759 .phys_to_virt = kvm_host_va,
1760 .virt_to_phys = kvm_host_pa,
1761 };
1762
kvm_mmu_init(u32 * hyp_va_bits)1763 int kvm_mmu_init(u32 *hyp_va_bits)
1764 {
1765 int err;
1766
1767 hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
1768 hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
1769 hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
1770 hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
1771 hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
1772
1773 /*
1774 * We rely on the linker script to ensure at build time that the HYP
1775 * init code does not cross a page boundary.
1776 */
1777 BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
1778
1779 *hyp_va_bits = 64 - ((idmap_t0sz & TCR_T0SZ_MASK) >> TCR_T0SZ_OFFSET);
1780 kvm_debug("Using %u-bit virtual addresses at EL2\n", *hyp_va_bits);
1781 kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
1782 kvm_debug("HYP VA range: %lx:%lx\n",
1783 kern_hyp_va(PAGE_OFFSET),
1784 kern_hyp_va((unsigned long)high_memory - 1));
1785
1786 if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
1787 hyp_idmap_start < kern_hyp_va((unsigned long)high_memory - 1) &&
1788 hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
1789 /*
1790 * The idmap page is intersecting with the VA space,
1791 * it is not safe to continue further.
1792 */
1793 kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
1794 err = -EINVAL;
1795 goto out;
1796 }
1797
1798 hyp_pgtable = kzalloc(sizeof(*hyp_pgtable), GFP_KERNEL);
1799 if (!hyp_pgtable) {
1800 kvm_err("Hyp mode page-table not allocated\n");
1801 err = -ENOMEM;
1802 goto out;
1803 }
1804
1805 err = kvm_pgtable_hyp_init(hyp_pgtable, *hyp_va_bits, &kvm_hyp_mm_ops);
1806 if (err)
1807 goto out_free_pgtable;
1808
1809 err = kvm_map_idmap_text();
1810 if (err)
1811 goto out_destroy_pgtable;
1812
1813 io_map_base = hyp_idmap_start;
1814 return 0;
1815
1816 out_destroy_pgtable:
1817 kvm_pgtable_hyp_destroy(hyp_pgtable);
1818 out_free_pgtable:
1819 kfree(hyp_pgtable);
1820 hyp_pgtable = NULL;
1821 out:
1822 return err;
1823 }
1824
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)1825 void kvm_arch_commit_memory_region(struct kvm *kvm,
1826 const struct kvm_userspace_memory_region *mem,
1827 struct kvm_memory_slot *old,
1828 const struct kvm_memory_slot *new,
1829 enum kvm_mr_change change)
1830 {
1831 /*
1832 * At this point memslot has been committed and there is an
1833 * allocated dirty_bitmap[], dirty pages will be tracked while the
1834 * memory slot is write protected.
1835 */
1836 if (change != KVM_MR_DELETE && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1837 /*
1838 * If we're with initial-all-set, we don't need to write
1839 * protect any pages because they're all reported as dirty.
1840 * Huge pages and normal pages will be write protect gradually.
1841 */
1842 if (!kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1843 kvm_mmu_wp_memory_region(kvm, mem->slot);
1844 }
1845 }
1846 }
1847
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)1848 int kvm_arch_prepare_memory_region(struct kvm *kvm,
1849 struct kvm_memory_slot *memslot,
1850 const struct kvm_userspace_memory_region *mem,
1851 enum kvm_mr_change change)
1852 {
1853 hva_t hva = mem->userspace_addr;
1854 hva_t reg_end = hva + mem->memory_size;
1855 int ret = 0;
1856
1857 /* In protected mode, cannot modify memslots once a VM has run. */
1858 if (is_protected_kvm_enabled() &&
1859 (change == KVM_MR_DELETE || change == KVM_MR_MOVE) &&
1860 kvm->arch.pkvm.shadow_handle) {
1861 return -EPERM;
1862 }
1863
1864 if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
1865 change != KVM_MR_FLAGS_ONLY)
1866 return 0;
1867
1868 /*
1869 * Prevent userspace from creating a memory region outside of the IPA
1870 * space addressable by the KVM guest IPA space.
1871 */
1872 if ((memslot->base_gfn + memslot->npages) > (kvm_phys_size(kvm) >> PAGE_SHIFT))
1873 return -EFAULT;
1874
1875 mmap_read_lock(current->mm);
1876 /*
1877 * A memory region could potentially cover multiple VMAs, and any holes
1878 * between them, so iterate over all of them.
1879 *
1880 * +--------------------------------------------+
1881 * +---------------+----------------+ +----------------+
1882 * | : VMA 1 | VMA 2 | | VMA 3 : |
1883 * +---------------+----------------+ +----------------+
1884 * | memory region |
1885 * +--------------------------------------------+
1886 */
1887 do {
1888 struct vm_area_struct *vma;
1889
1890 vma = find_vma_intersection(current->mm, hva, reg_end);
1891 if (!vma)
1892 break;
1893
1894 /*
1895 * VM_SHARED mappings are not allowed with MTE to avoid races
1896 * when updating the PG_mte_tagged page flag, see
1897 * sanitise_mte_tags for more details.
1898 */
1899 if (kvm_has_mte(kvm) && vma->vm_flags & VM_SHARED) {
1900 ret = -EINVAL;
1901 break;
1902 }
1903
1904 if (vma->vm_flags & VM_PFNMAP) {
1905 /* IO region dirty page logging not allowed */
1906 if (memslot->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1907 ret = -EINVAL;
1908 break;
1909 }
1910 }
1911 hva = min(reg_end, vma->vm_end);
1912 } while (hva < reg_end);
1913
1914 mmap_read_unlock(current->mm);
1915 return ret;
1916 }
1917
kvm_arch_free_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)1918 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
1919 {
1920 }
1921
kvm_arch_memslots_updated(struct kvm * kvm,u64 gen)1922 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
1923 {
1924 }
1925
kvm_arch_flush_shadow_all(struct kvm * kvm)1926 void kvm_arch_flush_shadow_all(struct kvm *kvm)
1927 {
1928 kvm_free_stage2_pgd(&kvm->arch.mmu);
1929 }
1930
kvm_arch_flush_shadow_memslot(struct kvm * kvm,struct kvm_memory_slot * slot)1931 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
1932 struct kvm_memory_slot *slot)
1933 {
1934 gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
1935 phys_addr_t size = slot->npages << PAGE_SHIFT;
1936
1937 /* Stage-2 is managed by hyp in protected mode. */
1938 if (is_protected_kvm_enabled())
1939 return;
1940
1941 spin_lock(&kvm->mmu_lock);
1942 unmap_stage2_range(&kvm->arch.mmu, gpa, size);
1943 spin_unlock(&kvm->mmu_lock);
1944 }
1945
1946 /*
1947 * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
1948 *
1949 * Main problems:
1950 * - S/W ops are local to a CPU (not broadcast)
1951 * - We have line migration behind our back (speculation)
1952 * - System caches don't support S/W at all (damn!)
1953 *
1954 * In the face of the above, the best we can do is to try and convert
1955 * S/W ops to VA ops. Because the guest is not allowed to infer the
1956 * S/W to PA mapping, it can only use S/W to nuke the whole cache,
1957 * which is a rather good thing for us.
1958 *
1959 * Also, it is only used when turning caches on/off ("The expected
1960 * usage of the cache maintenance instructions that operate by set/way
1961 * is associated with the cache maintenance instructions associated
1962 * with the powerdown and powerup of caches, if this is required by
1963 * the implementation.").
1964 *
1965 * We use the following policy:
1966 *
1967 * - If we trap a S/W operation, we enable VM trapping to detect
1968 * caches being turned on/off, and do a full clean.
1969 *
1970 * - We flush the caches on both caches being turned on and off.
1971 *
1972 * - Once the caches are enabled, we stop trapping VM ops.
1973 */
kvm_set_way_flush(struct kvm_vcpu * vcpu)1974 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
1975 {
1976 unsigned long hcr = *vcpu_hcr(vcpu);
1977
1978 /*
1979 * If this is the first time we do a S/W operation
1980 * (i.e. HCR_TVM not set) flush the whole memory, and set the
1981 * VM trapping.
1982 *
1983 * Otherwise, rely on the VM trapping to wait for the MMU +
1984 * Caches to be turned off. At that point, we'll be able to
1985 * clean the caches again.
1986 */
1987 if (!(hcr & HCR_TVM)) {
1988 trace_kvm_set_way_flush(*vcpu_pc(vcpu),
1989 vcpu_has_cache_enabled(vcpu));
1990 stage2_flush_vm(vcpu->kvm);
1991 *vcpu_hcr(vcpu) = hcr | HCR_TVM;
1992 }
1993 }
1994
kvm_toggle_cache(struct kvm_vcpu * vcpu,bool was_enabled)1995 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
1996 {
1997 bool now_enabled = vcpu_has_cache_enabled(vcpu);
1998
1999 /*
2000 * If switching the MMU+caches on, need to invalidate the caches.
2001 * If switching it off, need to clean the caches.
2002 * Clean + invalidate does the trick always.
2003 */
2004 if (now_enabled != was_enabled)
2005 stage2_flush_vm(vcpu->kvm);
2006
2007 /* Caches are now on, stop trapping VM ops (until a S/W op) */
2008 if (now_enabled)
2009 *vcpu_hcr(vcpu) &= ~HCR_TVM;
2010
2011 trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
2012 }
2013