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