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