KVM: arm64: Convert kvm_set_spte_hva() to generic page-table API
[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 #define KVM_S2PTE_FLAG_IS_IOMAP         (1UL << 0)
35 #define KVM_S2_FLAG_LOGGING_ACTIVE      (1UL << 1)
36
37 static bool is_iomap(unsigned long flags)
38 {
39         return flags & KVM_S2PTE_FLAG_IS_IOMAP;
40 }
41
42 static bool memslot_is_logging(struct kvm_memory_slot *memslot)
43 {
44         return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY);
45 }
46
47 /**
48  * kvm_flush_remote_tlbs() - flush all VM TLB entries for v7/8
49  * @kvm:        pointer to kvm structure.
50  *
51  * Interface to HYP function to flush all VM TLB entries
52  */
53 void kvm_flush_remote_tlbs(struct kvm *kvm)
54 {
55         kvm_call_hyp(__kvm_tlb_flush_vmid, &kvm->arch.mmu);
56 }
57
58 static void kvm_tlb_flush_vmid_ipa(struct kvm_s2_mmu *mmu, phys_addr_t ipa,
59                                    int level)
60 {
61         kvm_call_hyp(__kvm_tlb_flush_vmid_ipa, mmu, ipa, level);
62 }
63
64 /*
65  * D-Cache management functions. They take the page table entries by
66  * value, as they are flushing the cache using the kernel mapping (or
67  * kmap on 32bit).
68  */
69 static void kvm_flush_dcache_pte(pte_t pte)
70 {
71         __kvm_flush_dcache_pte(pte);
72 }
73
74 static void kvm_flush_dcache_pmd(pmd_t pmd)
75 {
76         __kvm_flush_dcache_pmd(pmd);
77 }
78
79 static void kvm_flush_dcache_pud(pud_t pud)
80 {
81         __kvm_flush_dcache_pud(pud);
82 }
83
84 static bool kvm_is_device_pfn(unsigned long pfn)
85 {
86         return !pfn_valid(pfn);
87 }
88
89 /**
90  * stage2_dissolve_pmd() - clear and flush huge PMD entry
91  * @mmu:        pointer to mmu structure to operate on
92  * @addr:       IPA
93  * @pmd:        pmd pointer for IPA
94  *
95  * Function clears a PMD entry, flushes addr 1st and 2nd stage TLBs.
96  */
97 static void stage2_dissolve_pmd(struct kvm_s2_mmu *mmu, phys_addr_t addr, pmd_t *pmd)
98 {
99         if (!pmd_thp_or_huge(*pmd))
100                 return;
101
102         pmd_clear(pmd);
103         kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PMD_LEVEL);
104         put_page(virt_to_page(pmd));
105 }
106
107 /**
108  * stage2_dissolve_pud() - clear and flush huge PUD entry
109  * @mmu:        pointer to mmu structure to operate on
110  * @addr:       IPA
111  * @pud:        pud pointer for IPA
112  *
113  * Function clears a PUD entry, flushes addr 1st and 2nd stage TLBs.
114  */
115 static void stage2_dissolve_pud(struct kvm_s2_mmu *mmu, phys_addr_t addr, pud_t *pudp)
116 {
117         struct kvm *kvm = mmu->kvm;
118
119         if (!stage2_pud_huge(kvm, *pudp))
120                 return;
121
122         stage2_pud_clear(kvm, pudp);
123         kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PUD_LEVEL);
124         put_page(virt_to_page(pudp));
125 }
126
127 static void clear_stage2_pgd_entry(struct kvm_s2_mmu *mmu, pgd_t *pgd, phys_addr_t addr)
128 {
129         struct kvm *kvm = mmu->kvm;
130         p4d_t *p4d_table __maybe_unused = stage2_p4d_offset(kvm, pgd, 0UL);
131         stage2_pgd_clear(kvm, pgd);
132         kvm_tlb_flush_vmid_ipa(mmu, addr, S2_NO_LEVEL_HINT);
133         stage2_p4d_free(kvm, p4d_table);
134         put_page(virt_to_page(pgd));
135 }
136
137 static void clear_stage2_p4d_entry(struct kvm_s2_mmu *mmu, p4d_t *p4d, phys_addr_t addr)
138 {
139         struct kvm *kvm = mmu->kvm;
140         pud_t *pud_table __maybe_unused = stage2_pud_offset(kvm, p4d, 0);
141         stage2_p4d_clear(kvm, p4d);
142         kvm_tlb_flush_vmid_ipa(mmu, addr, S2_NO_LEVEL_HINT);
143         stage2_pud_free(kvm, pud_table);
144         put_page(virt_to_page(p4d));
145 }
146
147 static void clear_stage2_pud_entry(struct kvm_s2_mmu *mmu, pud_t *pud, phys_addr_t addr)
148 {
149         struct kvm *kvm = mmu->kvm;
150         pmd_t *pmd_table __maybe_unused = stage2_pmd_offset(kvm, pud, 0);
151
152         VM_BUG_ON(stage2_pud_huge(kvm, *pud));
153         stage2_pud_clear(kvm, pud);
154         kvm_tlb_flush_vmid_ipa(mmu, addr, S2_NO_LEVEL_HINT);
155         stage2_pmd_free(kvm, pmd_table);
156         put_page(virt_to_page(pud));
157 }
158
159 static void clear_stage2_pmd_entry(struct kvm_s2_mmu *mmu, pmd_t *pmd, phys_addr_t addr)
160 {
161         pte_t *pte_table = pte_offset_kernel(pmd, 0);
162         VM_BUG_ON(pmd_thp_or_huge(*pmd));
163         pmd_clear(pmd);
164         kvm_tlb_flush_vmid_ipa(mmu, addr, S2_NO_LEVEL_HINT);
165         free_page((unsigned long)pte_table);
166         put_page(virt_to_page(pmd));
167 }
168
169 static inline void kvm_set_pte(pte_t *ptep, pte_t new_pte)
170 {
171         WRITE_ONCE(*ptep, new_pte);
172         dsb(ishst);
173 }
174
175 static inline void kvm_set_pmd(pmd_t *pmdp, pmd_t new_pmd)
176 {
177         WRITE_ONCE(*pmdp, new_pmd);
178         dsb(ishst);
179 }
180
181 static inline void kvm_pmd_populate(pmd_t *pmdp, pte_t *ptep)
182 {
183         kvm_set_pmd(pmdp, kvm_mk_pmd(ptep));
184 }
185
186 static inline void kvm_pud_populate(pud_t *pudp, pmd_t *pmdp)
187 {
188         WRITE_ONCE(*pudp, kvm_mk_pud(pmdp));
189         dsb(ishst);
190 }
191
192 static inline void kvm_p4d_populate(p4d_t *p4dp, pud_t *pudp)
193 {
194         WRITE_ONCE(*p4dp, kvm_mk_p4d(pudp));
195         dsb(ishst);
196 }
197
198 static inline void kvm_pgd_populate(pgd_t *pgdp, p4d_t *p4dp)
199 {
200 #ifndef __PAGETABLE_P4D_FOLDED
201         WRITE_ONCE(*pgdp, kvm_mk_pgd(p4dp));
202         dsb(ishst);
203 #endif
204 }
205
206 /*
207  * Unmapping vs dcache management:
208  *
209  * If a guest maps certain memory pages as uncached, all writes will
210  * bypass the data cache and go directly to RAM.  However, the CPUs
211  * can still speculate reads (not writes) and fill cache lines with
212  * data.
213  *
214  * Those cache lines will be *clean* cache lines though, so a
215  * clean+invalidate operation is equivalent to an invalidate
216  * operation, because no cache lines are marked dirty.
217  *
218  * Those clean cache lines could be filled prior to an uncached write
219  * by the guest, and the cache coherent IO subsystem would therefore
220  * end up writing old data to disk.
221  *
222  * This is why right after unmapping a page/section and invalidating
223  * the corresponding TLBs, we call kvm_flush_dcache_p*() to make sure
224  * the IO subsystem will never hit in the cache.
225  *
226  * This is all avoided on systems that have ARM64_HAS_STAGE2_FWB, as
227  * we then fully enforce cacheability of RAM, no matter what the guest
228  * does.
229  */
230 static void unmap_stage2_ptes(struct kvm_s2_mmu *mmu, pmd_t *pmd,
231                        phys_addr_t addr, phys_addr_t end)
232 {
233         phys_addr_t start_addr = addr;
234         pte_t *pte, *start_pte;
235
236         start_pte = pte = pte_offset_kernel(pmd, addr);
237         do {
238                 if (!pte_none(*pte)) {
239                         pte_t old_pte = *pte;
240
241                         kvm_set_pte(pte, __pte(0));
242                         kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PTE_LEVEL);
243
244                         /* No need to invalidate the cache for device mappings */
245                         if (!kvm_is_device_pfn(pte_pfn(old_pte)))
246                                 kvm_flush_dcache_pte(old_pte);
247
248                         put_page(virt_to_page(pte));
249                 }
250         } while (pte++, addr += PAGE_SIZE, addr != end);
251
252         if (stage2_pte_table_empty(mmu->kvm, start_pte))
253                 clear_stage2_pmd_entry(mmu, pmd, start_addr);
254 }
255
256 static void unmap_stage2_pmds(struct kvm_s2_mmu *mmu, pud_t *pud,
257                        phys_addr_t addr, phys_addr_t end)
258 {
259         struct kvm *kvm = mmu->kvm;
260         phys_addr_t next, start_addr = addr;
261         pmd_t *pmd, *start_pmd;
262
263         start_pmd = pmd = stage2_pmd_offset(kvm, pud, addr);
264         do {
265                 next = stage2_pmd_addr_end(kvm, addr, end);
266                 if (!pmd_none(*pmd)) {
267                         if (pmd_thp_or_huge(*pmd)) {
268                                 pmd_t old_pmd = *pmd;
269
270                                 pmd_clear(pmd);
271                                 kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PMD_LEVEL);
272
273                                 kvm_flush_dcache_pmd(old_pmd);
274
275                                 put_page(virt_to_page(pmd));
276                         } else {
277                                 unmap_stage2_ptes(mmu, pmd, addr, next);
278                         }
279                 }
280         } while (pmd++, addr = next, addr != end);
281
282         if (stage2_pmd_table_empty(kvm, start_pmd))
283                 clear_stage2_pud_entry(mmu, pud, start_addr);
284 }
285
286 static void unmap_stage2_puds(struct kvm_s2_mmu *mmu, p4d_t *p4d,
287                        phys_addr_t addr, phys_addr_t end)
288 {
289         struct kvm *kvm = mmu->kvm;
290         phys_addr_t next, start_addr = addr;
291         pud_t *pud, *start_pud;
292
293         start_pud = pud = stage2_pud_offset(kvm, p4d, addr);
294         do {
295                 next = stage2_pud_addr_end(kvm, addr, end);
296                 if (!stage2_pud_none(kvm, *pud)) {
297                         if (stage2_pud_huge(kvm, *pud)) {
298                                 pud_t old_pud = *pud;
299
300                                 stage2_pud_clear(kvm, pud);
301                                 kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PUD_LEVEL);
302                                 kvm_flush_dcache_pud(old_pud);
303                                 put_page(virt_to_page(pud));
304                         } else {
305                                 unmap_stage2_pmds(mmu, pud, addr, next);
306                         }
307                 }
308         } while (pud++, addr = next, addr != end);
309
310         if (stage2_pud_table_empty(kvm, start_pud))
311                 clear_stage2_p4d_entry(mmu, p4d, start_addr);
312 }
313
314 static void unmap_stage2_p4ds(struct kvm_s2_mmu *mmu, pgd_t *pgd,
315                        phys_addr_t addr, phys_addr_t end)
316 {
317         struct kvm *kvm = mmu->kvm;
318         phys_addr_t next, start_addr = addr;
319         p4d_t *p4d, *start_p4d;
320
321         start_p4d = p4d = stage2_p4d_offset(kvm, pgd, addr);
322         do {
323                 next = stage2_p4d_addr_end(kvm, addr, end);
324                 if (!stage2_p4d_none(kvm, *p4d))
325                         unmap_stage2_puds(mmu, p4d, addr, next);
326         } while (p4d++, addr = next, addr != end);
327
328         if (stage2_p4d_table_empty(kvm, start_p4d))
329                 clear_stage2_pgd_entry(mmu, pgd, start_addr);
330 }
331
332 /**
333  * unmap_stage2_range -- Clear stage2 page table entries to unmap a range
334  * @kvm:   The VM pointer
335  * @start: The intermediate physical base address of the range to unmap
336  * @size:  The size of the area to unmap
337  *
338  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
339  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
340  * destroying the VM), otherwise another faulting VCPU may come in and mess
341  * with things behind our backs.
342  */
343 static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
344                                  bool may_block)
345 {
346         struct kvm *kvm = mmu->kvm;
347         pgd_t *pgd;
348         phys_addr_t addr = start, end = start + size;
349         phys_addr_t next;
350
351         assert_spin_locked(&kvm->mmu_lock);
352         WARN_ON(size & ~PAGE_MASK);
353
354         pgd = mmu->pgd + stage2_pgd_index(kvm, addr);
355         do {
356                 /*
357                  * Make sure the page table is still active, as another thread
358                  * could have possibly freed the page table, while we released
359                  * the lock.
360                  */
361                 if (!READ_ONCE(mmu->pgd))
362                         break;
363                 next = stage2_pgd_addr_end(kvm, addr, end);
364                 if (!stage2_pgd_none(kvm, *pgd))
365                         unmap_stage2_p4ds(mmu, pgd, addr, next);
366                 /*
367                  * If the range is too large, release the kvm->mmu_lock
368                  * to prevent starvation and lockup detector warnings.
369                  */
370                 if (may_block && next != end)
371                         cond_resched_lock(&kvm->mmu_lock);
372         } while (pgd++, addr = next, addr != end);
373 }
374
375 static void unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size)
376 {
377         __unmap_stage2_range(mmu, start, size, true);
378 }
379
380 static void stage2_flush_ptes(struct kvm_s2_mmu *mmu, pmd_t *pmd,
381                               phys_addr_t addr, phys_addr_t end)
382 {
383         pte_t *pte;
384
385         pte = pte_offset_kernel(pmd, addr);
386         do {
387                 if (!pte_none(*pte) && !kvm_is_device_pfn(pte_pfn(*pte)))
388                         kvm_flush_dcache_pte(*pte);
389         } while (pte++, addr += PAGE_SIZE, addr != end);
390 }
391
392 static void stage2_flush_pmds(struct kvm_s2_mmu *mmu, pud_t *pud,
393                               phys_addr_t addr, phys_addr_t end)
394 {
395         struct kvm *kvm = mmu->kvm;
396         pmd_t *pmd;
397         phys_addr_t next;
398
399         pmd = stage2_pmd_offset(kvm, pud, addr);
400         do {
401                 next = stage2_pmd_addr_end(kvm, addr, end);
402                 if (!pmd_none(*pmd)) {
403                         if (pmd_thp_or_huge(*pmd))
404                                 kvm_flush_dcache_pmd(*pmd);
405                         else
406                                 stage2_flush_ptes(mmu, pmd, addr, next);
407                 }
408         } while (pmd++, addr = next, addr != end);
409 }
410
411 static void stage2_flush_puds(struct kvm_s2_mmu *mmu, p4d_t *p4d,
412                               phys_addr_t addr, phys_addr_t end)
413 {
414         struct kvm *kvm = mmu->kvm;
415         pud_t *pud;
416         phys_addr_t next;
417
418         pud = stage2_pud_offset(kvm, p4d, addr);
419         do {
420                 next = stage2_pud_addr_end(kvm, addr, end);
421                 if (!stage2_pud_none(kvm, *pud)) {
422                         if (stage2_pud_huge(kvm, *pud))
423                                 kvm_flush_dcache_pud(*pud);
424                         else
425                                 stage2_flush_pmds(mmu, pud, addr, next);
426                 }
427         } while (pud++, addr = next, addr != end);
428 }
429
430 static void stage2_flush_p4ds(struct kvm_s2_mmu *mmu, pgd_t *pgd,
431                               phys_addr_t addr, phys_addr_t end)
432 {
433         struct kvm *kvm = mmu->kvm;
434         p4d_t *p4d;
435         phys_addr_t next;
436
437         p4d = stage2_p4d_offset(kvm, pgd, addr);
438         do {
439                 next = stage2_p4d_addr_end(kvm, addr, end);
440                 if (!stage2_p4d_none(kvm, *p4d))
441                         stage2_flush_puds(mmu, p4d, addr, next);
442         } while (p4d++, addr = next, addr != end);
443 }
444
445 static void stage2_flush_memslot(struct kvm *kvm,
446                                  struct kvm_memory_slot *memslot)
447 {
448         struct kvm_s2_mmu *mmu = &kvm->arch.mmu;
449         phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
450         phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
451         phys_addr_t next;
452         pgd_t *pgd;
453
454         pgd = mmu->pgd + stage2_pgd_index(kvm, addr);
455         do {
456                 next = stage2_pgd_addr_end(kvm, addr, end);
457                 if (!stage2_pgd_none(kvm, *pgd))
458                         stage2_flush_p4ds(mmu, pgd, addr, next);
459
460                 if (next != end)
461                         cond_resched_lock(&kvm->mmu_lock);
462         } while (pgd++, addr = next, addr != end);
463 }
464
465 /**
466  * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
467  * @kvm: The struct kvm pointer
468  *
469  * Go through the stage 2 page tables and invalidate any cache lines
470  * backing memory already mapped to the VM.
471  */
472 static void stage2_flush_vm(struct kvm *kvm)
473 {
474         struct kvm_memslots *slots;
475         struct kvm_memory_slot *memslot;
476         int idx;
477
478         idx = srcu_read_lock(&kvm->srcu);
479         spin_lock(&kvm->mmu_lock);
480
481         slots = kvm_memslots(kvm);
482         kvm_for_each_memslot(memslot, slots)
483                 stage2_flush_memslot(kvm, memslot);
484
485         spin_unlock(&kvm->mmu_lock);
486         srcu_read_unlock(&kvm->srcu, idx);
487 }
488
489 /**
490  * free_hyp_pgds - free Hyp-mode page tables
491  */
492 void free_hyp_pgds(void)
493 {
494         mutex_lock(&kvm_hyp_pgd_mutex);
495         if (hyp_pgtable) {
496                 kvm_pgtable_hyp_destroy(hyp_pgtable);
497                 kfree(hyp_pgtable);
498         }
499         mutex_unlock(&kvm_hyp_pgd_mutex);
500 }
501
502 static int __create_hyp_mappings(unsigned long start, unsigned long size,
503                                  unsigned long phys, enum kvm_pgtable_prot prot)
504 {
505         int err;
506
507         mutex_lock(&kvm_hyp_pgd_mutex);
508         err = kvm_pgtable_hyp_map(hyp_pgtable, start, size, phys, prot);
509         mutex_unlock(&kvm_hyp_pgd_mutex);
510
511         return err;
512 }
513
514 static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
515 {
516         if (!is_vmalloc_addr(kaddr)) {
517                 BUG_ON(!virt_addr_valid(kaddr));
518                 return __pa(kaddr);
519         } else {
520                 return page_to_phys(vmalloc_to_page(kaddr)) +
521                        offset_in_page(kaddr);
522         }
523 }
524
525 /**
526  * create_hyp_mappings - duplicate a kernel virtual address range in Hyp mode
527  * @from:       The virtual kernel start address of the range
528  * @to:         The virtual kernel end address of the range (exclusive)
529  * @prot:       The protection to be applied to this range
530  *
531  * The same virtual address as the kernel virtual address is also used
532  * in Hyp-mode mapping (modulo HYP_PAGE_OFFSET) to the same underlying
533  * physical pages.
534  */
535 int create_hyp_mappings(void *from, void *to, enum kvm_pgtable_prot prot)
536 {
537         phys_addr_t phys_addr;
538         unsigned long virt_addr;
539         unsigned long start = kern_hyp_va((unsigned long)from);
540         unsigned long end = kern_hyp_va((unsigned long)to);
541
542         if (is_kernel_in_hyp_mode())
543                 return 0;
544
545         start = start & PAGE_MASK;
546         end = PAGE_ALIGN(end);
547
548         for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
549                 int err;
550
551                 phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
552                 err = __create_hyp_mappings(virt_addr, PAGE_SIZE, phys_addr,
553                                             prot);
554                 if (err)
555                         return err;
556         }
557
558         return 0;
559 }
560
561 static int __create_hyp_private_mapping(phys_addr_t phys_addr, size_t size,
562                                         unsigned long *haddr,
563                                         enum kvm_pgtable_prot prot)
564 {
565         unsigned long base;
566         int ret = 0;
567
568         mutex_lock(&kvm_hyp_pgd_mutex);
569
570         /*
571          * This assumes that we have enough space below the idmap
572          * page to allocate our VAs. If not, the check below will
573          * kick. A potential alternative would be to detect that
574          * overflow and switch to an allocation above the idmap.
575          *
576          * The allocated size is always a multiple of PAGE_SIZE.
577          */
578         size = PAGE_ALIGN(size + offset_in_page(phys_addr));
579         base = io_map_base - size;
580
581         /*
582          * Verify that BIT(VA_BITS - 1) hasn't been flipped by
583          * allocating the new area, as it would indicate we've
584          * overflowed the idmap/IO address range.
585          */
586         if ((base ^ io_map_base) & BIT(VA_BITS - 1))
587                 ret = -ENOMEM;
588         else
589                 io_map_base = base;
590
591         mutex_unlock(&kvm_hyp_pgd_mutex);
592
593         if (ret)
594                 goto out;
595
596         ret = __create_hyp_mappings(base, size, phys_addr, prot);
597         if (ret)
598                 goto out;
599
600         *haddr = base + offset_in_page(phys_addr);
601 out:
602         return ret;
603 }
604
605 /**
606  * create_hyp_io_mappings - Map IO into both kernel and HYP
607  * @phys_addr:  The physical start address which gets mapped
608  * @size:       Size of the region being mapped
609  * @kaddr:      Kernel VA for this mapping
610  * @haddr:      HYP VA for this mapping
611  */
612 int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size,
613                            void __iomem **kaddr,
614                            void __iomem **haddr)
615 {
616         unsigned long addr;
617         int ret;
618
619         *kaddr = ioremap(phys_addr, size);
620         if (!*kaddr)
621                 return -ENOMEM;
622
623         if (is_kernel_in_hyp_mode()) {
624                 *haddr = *kaddr;
625                 return 0;
626         }
627
628         ret = __create_hyp_private_mapping(phys_addr, size,
629                                            &addr, PAGE_HYP_DEVICE);
630         if (ret) {
631                 iounmap(*kaddr);
632                 *kaddr = NULL;
633                 *haddr = NULL;
634                 return ret;
635         }
636
637         *haddr = (void __iomem *)addr;
638         return 0;
639 }
640
641 /**
642  * create_hyp_exec_mappings - Map an executable range into HYP
643  * @phys_addr:  The physical start address which gets mapped
644  * @size:       Size of the region being mapped
645  * @haddr:      HYP VA for this mapping
646  */
647 int create_hyp_exec_mappings(phys_addr_t phys_addr, size_t size,
648                              void **haddr)
649 {
650         unsigned long addr;
651         int ret;
652
653         BUG_ON(is_kernel_in_hyp_mode());
654
655         ret = __create_hyp_private_mapping(phys_addr, size,
656                                            &addr, PAGE_HYP_EXEC);
657         if (ret) {
658                 *haddr = NULL;
659                 return ret;
660         }
661
662         *haddr = (void *)addr;
663         return 0;
664 }
665
666 /**
667  * kvm_init_stage2_mmu - Initialise a S2 MMU strucrure
668  * @kvm:        The pointer to the KVM structure
669  * @mmu:        The pointer to the s2 MMU structure
670  *
671  * Allocates only the stage-2 HW PGD level table(s).
672  * Note we don't need locking here as this is only called when the VM is
673  * created, which can only be done once.
674  */
675 int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu)
676 {
677         int cpu, err;
678         struct kvm_pgtable *pgt;
679
680         if (mmu->pgt != NULL) {
681                 kvm_err("kvm_arch already initialized?\n");
682                 return -EINVAL;
683         }
684
685         pgt = kzalloc(sizeof(*pgt), GFP_KERNEL);
686         if (!pgt)
687                 return -ENOMEM;
688
689         err = kvm_pgtable_stage2_init(pgt, kvm);
690         if (err)
691                 goto out_free_pgtable;
692
693         mmu->last_vcpu_ran = alloc_percpu(typeof(*mmu->last_vcpu_ran));
694         if (!mmu->last_vcpu_ran) {
695                 err = -ENOMEM;
696                 goto out_destroy_pgtable;
697         }
698
699         for_each_possible_cpu(cpu)
700                 *per_cpu_ptr(mmu->last_vcpu_ran, cpu) = -1;
701
702         mmu->kvm = kvm;
703         mmu->pgt = pgt;
704         mmu->pgd_phys = __pa(pgt->pgd);
705         mmu->pgd = (void *)pgt->pgd;
706         mmu->vmid.vmid_gen = 0;
707         return 0;
708
709 out_destroy_pgtable:
710         kvm_pgtable_stage2_destroy(pgt);
711 out_free_pgtable:
712         kfree(pgt);
713         return err;
714 }
715
716 static void stage2_unmap_memslot(struct kvm *kvm,
717                                  struct kvm_memory_slot *memslot)
718 {
719         hva_t hva = memslot->userspace_addr;
720         phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
721         phys_addr_t size = PAGE_SIZE * memslot->npages;
722         hva_t reg_end = hva + size;
723
724         /*
725          * A memory region could potentially cover multiple VMAs, and any holes
726          * between them, so iterate over all of them to find out if we should
727          * unmap any of them.
728          *
729          *     +--------------------------------------------+
730          * +---------------+----------------+   +----------------+
731          * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
732          * +---------------+----------------+   +----------------+
733          *     |               memory region                |
734          *     +--------------------------------------------+
735          */
736         do {
737                 struct vm_area_struct *vma = find_vma(current->mm, hva);
738                 hva_t vm_start, vm_end;
739
740                 if (!vma || vma->vm_start >= reg_end)
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;
769
770         idx = srcu_read_lock(&kvm->srcu);
771         mmap_read_lock(current->mm);
772         spin_lock(&kvm->mmu_lock);
773
774         slots = kvm_memslots(kvm);
775         kvm_for_each_memslot(memslot, slots)
776                 stage2_unmap_memslot(kvm, memslot);
777
778         spin_unlock(&kvm->mmu_lock);
779         mmap_read_unlock(current->mm);
780         srcu_read_unlock(&kvm->srcu, idx);
781 }
782
783 void kvm_free_stage2_pgd(struct kvm_s2_mmu *mmu)
784 {
785         struct kvm *kvm = mmu->kvm;
786         struct kvm_pgtable *pgt = NULL;
787
788         spin_lock(&kvm->mmu_lock);
789         pgt = mmu->pgt;
790         if (pgt) {
791                 mmu->pgd = NULL;
792                 mmu->pgd_phys = 0;
793                 mmu->pgt = NULL;
794                 free_percpu(mmu->last_vcpu_ran);
795         }
796         spin_unlock(&kvm->mmu_lock);
797
798         if (pgt) {
799                 kvm_pgtable_stage2_destroy(pgt);
800                 kfree(pgt);
801         }
802 }
803
804 static p4d_t *stage2_get_p4d(struct kvm_s2_mmu *mmu, struct kvm_mmu_memory_cache *cache,
805                              phys_addr_t addr)
806 {
807         struct kvm *kvm = mmu->kvm;
808         pgd_t *pgd;
809         p4d_t *p4d;
810
811         pgd = mmu->pgd + stage2_pgd_index(kvm, addr);
812         if (stage2_pgd_none(kvm, *pgd)) {
813                 if (!cache)
814                         return NULL;
815                 p4d = kvm_mmu_memory_cache_alloc(cache);
816                 stage2_pgd_populate(kvm, pgd, p4d);
817                 get_page(virt_to_page(pgd));
818         }
819
820         return stage2_p4d_offset(kvm, pgd, addr);
821 }
822
823 static pud_t *stage2_get_pud(struct kvm_s2_mmu *mmu, struct kvm_mmu_memory_cache *cache,
824                              phys_addr_t addr)
825 {
826         struct kvm *kvm = mmu->kvm;
827         p4d_t *p4d;
828         pud_t *pud;
829
830         p4d = stage2_get_p4d(mmu, cache, addr);
831         if (stage2_p4d_none(kvm, *p4d)) {
832                 if (!cache)
833                         return NULL;
834                 pud = kvm_mmu_memory_cache_alloc(cache);
835                 stage2_p4d_populate(kvm, p4d, pud);
836                 get_page(virt_to_page(p4d));
837         }
838
839         return stage2_pud_offset(kvm, p4d, addr);
840 }
841
842 static pmd_t *stage2_get_pmd(struct kvm_s2_mmu *mmu, struct kvm_mmu_memory_cache *cache,
843                              phys_addr_t addr)
844 {
845         struct kvm *kvm = mmu->kvm;
846         pud_t *pud;
847         pmd_t *pmd;
848
849         pud = stage2_get_pud(mmu, cache, addr);
850         if (!pud || stage2_pud_huge(kvm, *pud))
851                 return NULL;
852
853         if (stage2_pud_none(kvm, *pud)) {
854                 if (!cache)
855                         return NULL;
856                 pmd = kvm_mmu_memory_cache_alloc(cache);
857                 stage2_pud_populate(kvm, pud, pmd);
858                 get_page(virt_to_page(pud));
859         }
860
861         return stage2_pmd_offset(kvm, pud, addr);
862 }
863
864 static int stage2_set_pmd_huge(struct kvm_s2_mmu *mmu,
865                                struct kvm_mmu_memory_cache *cache,
866                                phys_addr_t addr, const pmd_t *new_pmd)
867 {
868         pmd_t *pmd, old_pmd;
869
870 retry:
871         pmd = stage2_get_pmd(mmu, cache, addr);
872         VM_BUG_ON(!pmd);
873
874         old_pmd = *pmd;
875         /*
876          * Multiple vcpus faulting on the same PMD entry, can
877          * lead to them sequentially updating the PMD with the
878          * same value. Following the break-before-make
879          * (pmd_clear() followed by tlb_flush()) process can
880          * hinder forward progress due to refaults generated
881          * on missing translations.
882          *
883          * Skip updating the page table if the entry is
884          * unchanged.
885          */
886         if (pmd_val(old_pmd) == pmd_val(*new_pmd))
887                 return 0;
888
889         if (pmd_present(old_pmd)) {
890                 /*
891                  * If we already have PTE level mapping for this block,
892                  * we must unmap it to avoid inconsistent TLB state and
893                  * leaking the table page. We could end up in this situation
894                  * if the memory slot was marked for dirty logging and was
895                  * reverted, leaving PTE level mappings for the pages accessed
896                  * during the period. So, unmap the PTE level mapping for this
897                  * block and retry, as we could have released the upper level
898                  * table in the process.
899                  *
900                  * Normal THP split/merge follows mmu_notifier callbacks and do
901                  * get handled accordingly.
902                  */
903                 if (!pmd_thp_or_huge(old_pmd)) {
904                         unmap_stage2_range(mmu, addr & S2_PMD_MASK, S2_PMD_SIZE);
905                         goto retry;
906                 }
907                 /*
908                  * Mapping in huge pages should only happen through a
909                  * fault.  If a page is merged into a transparent huge
910                  * page, the individual subpages of that huge page
911                  * should be unmapped through MMU notifiers before we
912                  * get here.
913                  *
914                  * Merging of CompoundPages is not supported; they
915                  * should become splitting first, unmapped, merged,
916                  * and mapped back in on-demand.
917                  */
918                 WARN_ON_ONCE(pmd_pfn(old_pmd) != pmd_pfn(*new_pmd));
919                 pmd_clear(pmd);
920                 kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PMD_LEVEL);
921         } else {
922                 get_page(virt_to_page(pmd));
923         }
924
925         kvm_set_pmd(pmd, *new_pmd);
926         return 0;
927 }
928
929 static int stage2_set_pud_huge(struct kvm_s2_mmu *mmu,
930                                struct kvm_mmu_memory_cache *cache,
931                                phys_addr_t addr, const pud_t *new_pudp)
932 {
933         struct kvm *kvm = mmu->kvm;
934         pud_t *pudp, old_pud;
935
936 retry:
937         pudp = stage2_get_pud(mmu, cache, addr);
938         VM_BUG_ON(!pudp);
939
940         old_pud = *pudp;
941
942         /*
943          * A large number of vcpus faulting on the same stage 2 entry,
944          * can lead to a refault due to the stage2_pud_clear()/tlb_flush().
945          * Skip updating the page tables if there is no change.
946          */
947         if (pud_val(old_pud) == pud_val(*new_pudp))
948                 return 0;
949
950         if (stage2_pud_present(kvm, old_pud)) {
951                 /*
952                  * If we already have table level mapping for this block, unmap
953                  * the range for this block and retry.
954                  */
955                 if (!stage2_pud_huge(kvm, old_pud)) {
956                         unmap_stage2_range(mmu, addr & S2_PUD_MASK, S2_PUD_SIZE);
957                         goto retry;
958                 }
959
960                 WARN_ON_ONCE(kvm_pud_pfn(old_pud) != kvm_pud_pfn(*new_pudp));
961                 stage2_pud_clear(kvm, pudp);
962                 kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PUD_LEVEL);
963         } else {
964                 get_page(virt_to_page(pudp));
965         }
966
967         kvm_set_pud(pudp, *new_pudp);
968         return 0;
969 }
970
971 /*
972  * stage2_get_leaf_entry - walk the stage2 VM page tables and return
973  * true if a valid and present leaf-entry is found. A pointer to the
974  * leaf-entry is returned in the appropriate level variable - pudpp,
975  * pmdpp, ptepp.
976  */
977 static bool stage2_get_leaf_entry(struct kvm_s2_mmu *mmu, phys_addr_t addr,
978                                   pud_t **pudpp, pmd_t **pmdpp, pte_t **ptepp)
979 {
980         struct kvm *kvm = mmu->kvm;
981         pud_t *pudp;
982         pmd_t *pmdp;
983         pte_t *ptep;
984
985         *pudpp = NULL;
986         *pmdpp = NULL;
987         *ptepp = NULL;
988
989         pudp = stage2_get_pud(mmu, NULL, addr);
990         if (!pudp || stage2_pud_none(kvm, *pudp) || !stage2_pud_present(kvm, *pudp))
991                 return false;
992
993         if (stage2_pud_huge(kvm, *pudp)) {
994                 *pudpp = pudp;
995                 return true;
996         }
997
998         pmdp = stage2_pmd_offset(kvm, pudp, addr);
999         if (!pmdp || pmd_none(*pmdp) || !pmd_present(*pmdp))
1000                 return false;
1001
1002         if (pmd_thp_or_huge(*pmdp)) {
1003                 *pmdpp = pmdp;
1004                 return true;
1005         }
1006
1007         ptep = pte_offset_kernel(pmdp, addr);
1008         if (!ptep || pte_none(*ptep) || !pte_present(*ptep))
1009                 return false;
1010
1011         *ptepp = ptep;
1012         return true;
1013 }
1014
1015 static bool stage2_is_exec(struct kvm_s2_mmu *mmu, phys_addr_t addr, unsigned long sz)
1016 {
1017         pud_t *pudp;
1018         pmd_t *pmdp;
1019         pte_t *ptep;
1020         bool found;
1021
1022         found = stage2_get_leaf_entry(mmu, addr, &pudp, &pmdp, &ptep);
1023         if (!found)
1024                 return false;
1025
1026         if (pudp)
1027                 return sz <= PUD_SIZE && kvm_s2pud_exec(pudp);
1028         else if (pmdp)
1029                 return sz <= PMD_SIZE && kvm_s2pmd_exec(pmdp);
1030         else
1031                 return sz == PAGE_SIZE && kvm_s2pte_exec(ptep);
1032 }
1033
1034 static int stage2_set_pte(struct kvm_s2_mmu *mmu,
1035                           struct kvm_mmu_memory_cache *cache,
1036                           phys_addr_t addr, const pte_t *new_pte,
1037                           unsigned long flags)
1038 {
1039         struct kvm *kvm = mmu->kvm;
1040         pud_t *pud;
1041         pmd_t *pmd;
1042         pte_t *pte, old_pte;
1043         bool iomap = flags & KVM_S2PTE_FLAG_IS_IOMAP;
1044         bool logging_active = flags & KVM_S2_FLAG_LOGGING_ACTIVE;
1045
1046         VM_BUG_ON(logging_active && !cache);
1047
1048         /* Create stage-2 page table mapping - Levels 0 and 1 */
1049         pud = stage2_get_pud(mmu, cache, addr);
1050         if (!pud) {
1051                 /*
1052                  * Ignore calls from kvm_set_spte_hva for unallocated
1053                  * address ranges.
1054                  */
1055                 return 0;
1056         }
1057
1058         /*
1059          * While dirty page logging - dissolve huge PUD, then continue
1060          * on to allocate page.
1061          */
1062         if (logging_active)
1063                 stage2_dissolve_pud(mmu, addr, pud);
1064
1065         if (stage2_pud_none(kvm, *pud)) {
1066                 if (!cache)
1067                         return 0; /* ignore calls from kvm_set_spte_hva */
1068                 pmd = kvm_mmu_memory_cache_alloc(cache);
1069                 stage2_pud_populate(kvm, pud, pmd);
1070                 get_page(virt_to_page(pud));
1071         }
1072
1073         pmd = stage2_pmd_offset(kvm, pud, addr);
1074         if (!pmd) {
1075                 /*
1076                  * Ignore calls from kvm_set_spte_hva for unallocated
1077                  * address ranges.
1078                  */
1079                 return 0;
1080         }
1081
1082         /*
1083          * While dirty page logging - dissolve huge PMD, then continue on to
1084          * allocate page.
1085          */
1086         if (logging_active)
1087                 stage2_dissolve_pmd(mmu, addr, pmd);
1088
1089         /* Create stage-2 page mappings - Level 2 */
1090         if (pmd_none(*pmd)) {
1091                 if (!cache)
1092                         return 0; /* ignore calls from kvm_set_spte_hva */
1093                 pte = kvm_mmu_memory_cache_alloc(cache);
1094                 kvm_pmd_populate(pmd, pte);
1095                 get_page(virt_to_page(pmd));
1096         }
1097
1098         pte = pte_offset_kernel(pmd, addr);
1099
1100         if (iomap && pte_present(*pte))
1101                 return -EFAULT;
1102
1103         /* Create 2nd stage page table mapping - Level 3 */
1104         old_pte = *pte;
1105         if (pte_present(old_pte)) {
1106                 /* Skip page table update if there is no change */
1107                 if (pte_val(old_pte) == pte_val(*new_pte))
1108                         return 0;
1109
1110                 kvm_set_pte(pte, __pte(0));
1111                 kvm_tlb_flush_vmid_ipa(mmu, addr, S2_PTE_LEVEL);
1112         } else {
1113                 get_page(virt_to_page(pte));
1114         }
1115
1116         kvm_set_pte(pte, *new_pte);
1117         return 0;
1118 }
1119
1120 #ifndef __HAVE_ARCH_PTEP_TEST_AND_CLEAR_YOUNG
1121 static int stage2_ptep_test_and_clear_young(pte_t *pte)
1122 {
1123         if (pte_young(*pte)) {
1124                 *pte = pte_mkold(*pte);
1125                 return 1;
1126         }
1127         return 0;
1128 }
1129 #else
1130 static int stage2_ptep_test_and_clear_young(pte_t *pte)
1131 {
1132         return __ptep_test_and_clear_young(pte);
1133 }
1134 #endif
1135
1136 static int stage2_pmdp_test_and_clear_young(pmd_t *pmd)
1137 {
1138         return stage2_ptep_test_and_clear_young((pte_t *)pmd);
1139 }
1140
1141 static int stage2_pudp_test_and_clear_young(pud_t *pud)
1142 {
1143         return stage2_ptep_test_and_clear_young((pte_t *)pud);
1144 }
1145
1146 /**
1147  * kvm_phys_addr_ioremap - map a device range to guest IPA
1148  *
1149  * @kvm:        The KVM pointer
1150  * @guest_ipa:  The IPA at which to insert the mapping
1151  * @pa:         The physical address of the device
1152  * @size:       The size of the mapping
1153  */
1154 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
1155                           phys_addr_t pa, unsigned long size, bool writable)
1156 {
1157         phys_addr_t addr;
1158         int ret = 0;
1159         struct kvm_mmu_memory_cache cache = { 0, __GFP_ZERO, NULL, };
1160         struct kvm_pgtable *pgt = kvm->arch.mmu.pgt;
1161         enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_DEVICE |
1162                                      KVM_PGTABLE_PROT_R |
1163                                      (writable ? KVM_PGTABLE_PROT_W : 0);
1164
1165         size += offset_in_page(guest_ipa);
1166         guest_ipa &= PAGE_MASK;
1167
1168         for (addr = guest_ipa; addr < guest_ipa + size; addr += PAGE_SIZE) {
1169                 ret = kvm_mmu_topup_memory_cache(&cache,
1170                                                  kvm_mmu_cache_min_pages(kvm));
1171                 if (ret)
1172                         break;
1173
1174                 spin_lock(&kvm->mmu_lock);
1175                 ret = kvm_pgtable_stage2_map(pgt, addr, PAGE_SIZE, pa, prot,
1176                                              &cache);
1177                 spin_unlock(&kvm->mmu_lock);
1178                 if (ret)
1179                         break;
1180
1181                 pa += PAGE_SIZE;
1182         }
1183
1184         kvm_mmu_free_memory_cache(&cache);
1185         return ret;
1186 }
1187
1188 /**
1189  * stage2_wp_ptes - write protect PMD range
1190  * @pmd:        pointer to pmd entry
1191  * @addr:       range start address
1192  * @end:        range end address
1193  */
1194 static void stage2_wp_ptes(pmd_t *pmd, phys_addr_t addr, phys_addr_t end)
1195 {
1196         pte_t *pte;
1197
1198         pte = pte_offset_kernel(pmd, addr);
1199         do {
1200                 if (!pte_none(*pte)) {
1201                         if (!kvm_s2pte_readonly(pte))
1202                                 kvm_set_s2pte_readonly(pte);
1203                 }
1204         } while (pte++, addr += PAGE_SIZE, addr != end);
1205 }
1206
1207 /**
1208  * stage2_wp_pmds - write protect PUD range
1209  * kvm:         kvm instance for the VM
1210  * @pud:        pointer to pud entry
1211  * @addr:       range start address
1212  * @end:        range end address
1213  */
1214 static void stage2_wp_pmds(struct kvm_s2_mmu *mmu, pud_t *pud,
1215                            phys_addr_t addr, phys_addr_t end)
1216 {
1217         struct kvm *kvm = mmu->kvm;
1218         pmd_t *pmd;
1219         phys_addr_t next;
1220
1221         pmd = stage2_pmd_offset(kvm, pud, addr);
1222
1223         do {
1224                 next = stage2_pmd_addr_end(kvm, addr, end);
1225                 if (!pmd_none(*pmd)) {
1226                         if (pmd_thp_or_huge(*pmd)) {
1227                                 if (!kvm_s2pmd_readonly(pmd))
1228                                         kvm_set_s2pmd_readonly(pmd);
1229                         } else {
1230                                 stage2_wp_ptes(pmd, addr, next);
1231                         }
1232                 }
1233         } while (pmd++, addr = next, addr != end);
1234 }
1235
1236 /**
1237  * stage2_wp_puds - write protect P4D range
1238  * @p4d:        pointer to p4d entry
1239  * @addr:       range start address
1240  * @end:        range end address
1241  */
1242 static void  stage2_wp_puds(struct kvm_s2_mmu *mmu, p4d_t *p4d,
1243                             phys_addr_t addr, phys_addr_t end)
1244 {
1245         struct kvm *kvm = mmu->kvm;
1246         pud_t *pud;
1247         phys_addr_t next;
1248
1249         pud = stage2_pud_offset(kvm, p4d, addr);
1250         do {
1251                 next = stage2_pud_addr_end(kvm, addr, end);
1252                 if (!stage2_pud_none(kvm, *pud)) {
1253                         if (stage2_pud_huge(kvm, *pud)) {
1254                                 if (!kvm_s2pud_readonly(pud))
1255                                         kvm_set_s2pud_readonly(pud);
1256                         } else {
1257                                 stage2_wp_pmds(mmu, pud, addr, next);
1258                         }
1259                 }
1260         } while (pud++, addr = next, addr != end);
1261 }
1262
1263 /**
1264  * stage2_wp_p4ds - write protect PGD range
1265  * @pgd:        pointer to pgd entry
1266  * @addr:       range start address
1267  * @end:        range end address
1268  */
1269 static void  stage2_wp_p4ds(struct kvm_s2_mmu *mmu, pgd_t *pgd,
1270                             phys_addr_t addr, phys_addr_t end)
1271 {
1272         struct kvm *kvm = mmu->kvm;
1273         p4d_t *p4d;
1274         phys_addr_t next;
1275
1276         p4d = stage2_p4d_offset(kvm, pgd, addr);
1277         do {
1278                 next = stage2_p4d_addr_end(kvm, addr, end);
1279                 if (!stage2_p4d_none(kvm, *p4d))
1280                         stage2_wp_puds(mmu, p4d, addr, next);
1281         } while (p4d++, addr = next, addr != end);
1282 }
1283
1284 /**
1285  * stage2_wp_range() - write protect stage2 memory region range
1286  * @kvm:        The KVM pointer
1287  * @addr:       Start address of range
1288  * @end:        End address of range
1289  */
1290 static void stage2_wp_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
1291 {
1292         struct kvm *kvm = mmu->kvm;
1293         pgd_t *pgd;
1294         phys_addr_t next;
1295
1296         pgd = mmu->pgd + stage2_pgd_index(kvm, addr);
1297         do {
1298                 /*
1299                  * Release kvm_mmu_lock periodically if the memory region is
1300                  * large. Otherwise, we may see kernel panics with
1301                  * CONFIG_DETECT_HUNG_TASK, CONFIG_LOCKUP_DETECTOR,
1302                  * CONFIG_LOCKDEP. Additionally, holding the lock too long
1303                  * will also starve other vCPUs. We have to also make sure
1304                  * that the page tables are not freed while we released
1305                  * the lock.
1306                  */
1307                 cond_resched_lock(&kvm->mmu_lock);
1308                 if (!READ_ONCE(mmu->pgd))
1309                         break;
1310                 next = stage2_pgd_addr_end(kvm, addr, end);
1311                 if (stage2_pgd_present(kvm, *pgd))
1312                         stage2_wp_p4ds(mmu, pgd, addr, next);
1313         } while (pgd++, addr = next, addr != end);
1314 }
1315
1316 /**
1317  * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
1318  * @kvm:        The KVM pointer
1319  * @slot:       The memory slot to write protect
1320  *
1321  * Called to start logging dirty pages after memory region
1322  * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
1323  * all present PUD, PMD and PTEs are write protected in the memory region.
1324  * Afterwards read of dirty page log can be called.
1325  *
1326  * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
1327  * serializing operations for VM memory regions.
1328  */
1329 void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
1330 {
1331         struct kvm_memslots *slots = kvm_memslots(kvm);
1332         struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
1333         phys_addr_t start, end;
1334
1335         if (WARN_ON_ONCE(!memslot))
1336                 return;
1337
1338         start = memslot->base_gfn << PAGE_SHIFT;
1339         end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
1340
1341         spin_lock(&kvm->mmu_lock);
1342         stage2_wp_range(&kvm->arch.mmu, start, end);
1343         spin_unlock(&kvm->mmu_lock);
1344         kvm_flush_remote_tlbs(kvm);
1345 }
1346
1347 /**
1348  * kvm_mmu_write_protect_pt_masked() - write protect dirty pages
1349  * @kvm:        The KVM pointer
1350  * @slot:       The memory slot associated with mask
1351  * @gfn_offset: The gfn offset in memory slot
1352  * @mask:       The mask of dirty pages at offset 'gfn_offset' in this memory
1353  *              slot to be write protected
1354  *
1355  * Walks bits set in mask write protects the associated pte's. Caller must
1356  * acquire kvm_mmu_lock.
1357  */
1358 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1359                 struct kvm_memory_slot *slot,
1360                 gfn_t gfn_offset, unsigned long mask)
1361 {
1362         phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
1363         phys_addr_t start = (base_gfn +  __ffs(mask)) << PAGE_SHIFT;
1364         phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
1365
1366         stage2_wp_range(&kvm->arch.mmu, start, end);
1367 }
1368
1369 /*
1370  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1371  * dirty pages.
1372  *
1373  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1374  * enable dirty logging for them.
1375  */
1376 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1377                 struct kvm_memory_slot *slot,
1378                 gfn_t gfn_offset, unsigned long mask)
1379 {
1380         kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1381 }
1382
1383 static void clean_dcache_guest_page(kvm_pfn_t pfn, unsigned long size)
1384 {
1385         __clean_dcache_guest_page(pfn, size);
1386 }
1387
1388 static void invalidate_icache_guest_page(kvm_pfn_t pfn, unsigned long size)
1389 {
1390         __invalidate_icache_guest_page(pfn, size);
1391 }
1392
1393 static void kvm_send_hwpoison_signal(unsigned long address, short lsb)
1394 {
1395         send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, current);
1396 }
1397
1398 static bool fault_supports_stage2_huge_mapping(struct kvm_memory_slot *memslot,
1399                                                unsigned long hva,
1400                                                unsigned long map_size)
1401 {
1402         gpa_t gpa_start;
1403         hva_t uaddr_start, uaddr_end;
1404         size_t size;
1405
1406         /* The memslot and the VMA are guaranteed to be aligned to PAGE_SIZE */
1407         if (map_size == PAGE_SIZE)
1408                 return true;
1409
1410         size = memslot->npages * PAGE_SIZE;
1411
1412         gpa_start = memslot->base_gfn << PAGE_SHIFT;
1413
1414         uaddr_start = memslot->userspace_addr;
1415         uaddr_end = uaddr_start + size;
1416
1417         /*
1418          * Pages belonging to memslots that don't have the same alignment
1419          * within a PMD/PUD for userspace and IPA cannot be mapped with stage-2
1420          * PMD/PUD entries, because we'll end up mapping the wrong pages.
1421          *
1422          * Consider a layout like the following:
1423          *
1424          *    memslot->userspace_addr:
1425          *    +-----+--------------------+--------------------+---+
1426          *    |abcde|fgh  Stage-1 block  |    Stage-1 block tv|xyz|
1427          *    +-----+--------------------+--------------------+---+
1428          *
1429          *    memslot->base_gfn << PAGE_SHIFT:
1430          *      +---+--------------------+--------------------+-----+
1431          *      |abc|def  Stage-2 block  |    Stage-2 block   |tvxyz|
1432          *      +---+--------------------+--------------------+-----+
1433          *
1434          * If we create those stage-2 blocks, we'll end up with this incorrect
1435          * mapping:
1436          *   d -> f
1437          *   e -> g
1438          *   f -> h
1439          */
1440         if ((gpa_start & (map_size - 1)) != (uaddr_start & (map_size - 1)))
1441                 return false;
1442
1443         /*
1444          * Next, let's make sure we're not trying to map anything not covered
1445          * by the memslot. This means we have to prohibit block size mappings
1446          * for the beginning and end of a non-block aligned and non-block sized
1447          * memory slot (illustrated by the head and tail parts of the
1448          * userspace view above containing pages 'abcde' and 'xyz',
1449          * respectively).
1450          *
1451          * Note that it doesn't matter if we do the check using the
1452          * userspace_addr or the base_gfn, as both are equally aligned (per
1453          * the check above) and equally sized.
1454          */
1455         return (hva & ~(map_size - 1)) >= uaddr_start &&
1456                (hva & ~(map_size - 1)) + map_size <= uaddr_end;
1457 }
1458
1459 /*
1460  * Check if the given hva is backed by a transparent huge page (THP) and
1461  * whether it can be mapped using block mapping in stage2. If so, adjust
1462  * the stage2 PFN and IPA accordingly. Only PMD_SIZE THPs are currently
1463  * supported. This will need to be updated to support other THP sizes.
1464  *
1465  * Returns the size of the mapping.
1466  */
1467 static unsigned long
1468 transparent_hugepage_adjust(struct kvm_memory_slot *memslot,
1469                             unsigned long hva, kvm_pfn_t *pfnp,
1470                             phys_addr_t *ipap)
1471 {
1472         kvm_pfn_t pfn = *pfnp;
1473
1474         /*
1475          * Make sure the adjustment is done only for THP pages. Also make
1476          * sure that the HVA and IPA are sufficiently aligned and that the
1477          * block map is contained within the memslot.
1478          */
1479         if (kvm_is_transparent_hugepage(pfn) &&
1480             fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE)) {
1481                 /*
1482                  * The address we faulted on is backed by a transparent huge
1483                  * page.  However, because we map the compound huge page and
1484                  * not the individual tail page, we need to transfer the
1485                  * refcount to the head page.  We have to be careful that the
1486                  * THP doesn't start to split while we are adjusting the
1487                  * refcounts.
1488                  *
1489                  * We are sure this doesn't happen, because mmu_notifier_retry
1490                  * was successful and we are holding the mmu_lock, so if this
1491                  * THP is trying to split, it will be blocked in the mmu
1492                  * notifier before touching any of the pages, specifically
1493                  * before being able to call __split_huge_page_refcount().
1494                  *
1495                  * We can therefore safely transfer the refcount from PG_tail
1496                  * to PG_head and switch the pfn from a tail page to the head
1497                  * page accordingly.
1498                  */
1499                 *ipap &= PMD_MASK;
1500                 kvm_release_pfn_clean(pfn);
1501                 pfn &= ~(PTRS_PER_PMD - 1);
1502                 kvm_get_pfn(pfn);
1503                 *pfnp = pfn;
1504
1505                 return PMD_SIZE;
1506         }
1507
1508         /* Use page mapping if we cannot use block mapping. */
1509         return PAGE_SIZE;
1510 }
1511
1512 static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1513                           struct kvm_memory_slot *memslot, unsigned long hva,
1514                           unsigned long fault_status)
1515 {
1516         int ret;
1517         bool write_fault, writable, force_pte = false;
1518         bool exec_fault, needs_exec;
1519         unsigned long mmu_seq;
1520         gfn_t gfn = fault_ipa >> PAGE_SHIFT;
1521         struct kvm *kvm = vcpu->kvm;
1522         struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
1523         struct vm_area_struct *vma;
1524         short vma_shift;
1525         kvm_pfn_t pfn;
1526         pgprot_t mem_type = PAGE_S2;
1527         bool logging_active = memslot_is_logging(memslot);
1528         unsigned long vma_pagesize, flags = 0;
1529         struct kvm_s2_mmu *mmu = vcpu->arch.hw_mmu;
1530
1531         write_fault = kvm_is_write_fault(vcpu);
1532         exec_fault = kvm_vcpu_trap_is_iabt(vcpu);
1533         VM_BUG_ON(write_fault && exec_fault);
1534
1535         if (fault_status == FSC_PERM && !write_fault && !exec_fault) {
1536                 kvm_err("Unexpected L2 read permission error\n");
1537                 return -EFAULT;
1538         }
1539
1540         /* Let's check if we will get back a huge page backed by hugetlbfs */
1541         mmap_read_lock(current->mm);
1542         vma = find_vma_intersection(current->mm, hva, hva + 1);
1543         if (unlikely(!vma)) {
1544                 kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
1545                 mmap_read_unlock(current->mm);
1546                 return -EFAULT;
1547         }
1548
1549         if (is_vm_hugetlb_page(vma))
1550                 vma_shift = huge_page_shift(hstate_vma(vma));
1551         else
1552                 vma_shift = PAGE_SHIFT;
1553
1554         vma_pagesize = 1ULL << vma_shift;
1555         if (logging_active ||
1556             (vma->vm_flags & VM_PFNMAP) ||
1557             !fault_supports_stage2_huge_mapping(memslot, hva, vma_pagesize)) {
1558                 force_pte = true;
1559                 vma_pagesize = PAGE_SIZE;
1560         }
1561
1562         /*
1563          * The stage2 has a minimum of 2 level table (For arm64 see
1564          * kvm_arm_setup_stage2()). Hence, we are guaranteed that we can
1565          * use PMD_SIZE huge mappings (even when the PMD is folded into PGD).
1566          * As for PUD huge maps, we must make sure that we have at least
1567          * 3 levels, i.e, PMD is not folded.
1568          */
1569         if (vma_pagesize == PMD_SIZE ||
1570             (vma_pagesize == PUD_SIZE && kvm_stage2_has_pmd(kvm)))
1571                 gfn = (fault_ipa & huge_page_mask(hstate_vma(vma))) >> PAGE_SHIFT;
1572         mmap_read_unlock(current->mm);
1573
1574         /* We need minimum second+third level pages */
1575         ret = kvm_mmu_topup_memory_cache(memcache, kvm_mmu_cache_min_pages(kvm));
1576         if (ret)
1577                 return ret;
1578
1579         mmu_seq = vcpu->kvm->mmu_notifier_seq;
1580         /*
1581          * Ensure the read of mmu_notifier_seq happens before we call
1582          * gfn_to_pfn_prot (which calls get_user_pages), so that we don't risk
1583          * the page we just got a reference to gets unmapped before we have a
1584          * chance to grab the mmu_lock, which ensure that if the page gets
1585          * unmapped afterwards, the call to kvm_unmap_hva will take it away
1586          * from us again properly. This smp_rmb() interacts with the smp_wmb()
1587          * in kvm_mmu_notifier_invalidate_<page|range_end>.
1588          */
1589         smp_rmb();
1590
1591         pfn = gfn_to_pfn_prot(kvm, gfn, write_fault, &writable);
1592         if (pfn == KVM_PFN_ERR_HWPOISON) {
1593                 kvm_send_hwpoison_signal(hva, vma_shift);
1594                 return 0;
1595         }
1596         if (is_error_noslot_pfn(pfn))
1597                 return -EFAULT;
1598
1599         if (kvm_is_device_pfn(pfn)) {
1600                 mem_type = PAGE_S2_DEVICE;
1601                 flags |= KVM_S2PTE_FLAG_IS_IOMAP;
1602         } else if (logging_active) {
1603                 /*
1604                  * Faults on pages in a memslot with logging enabled
1605                  * should not be mapped with huge pages (it introduces churn
1606                  * and performance degradation), so force a pte mapping.
1607                  */
1608                 flags |= KVM_S2_FLAG_LOGGING_ACTIVE;
1609
1610                 /*
1611                  * Only actually map the page as writable if this was a write
1612                  * fault.
1613                  */
1614                 if (!write_fault)
1615                         writable = false;
1616         }
1617
1618         if (exec_fault && is_iomap(flags))
1619                 return -ENOEXEC;
1620
1621         spin_lock(&kvm->mmu_lock);
1622         if (mmu_notifier_retry(kvm, mmu_seq))
1623                 goto out_unlock;
1624
1625         /*
1626          * If we are not forced to use page mapping, check if we are
1627          * backed by a THP and thus use block mapping if possible.
1628          */
1629         if (vma_pagesize == PAGE_SIZE && !force_pte)
1630                 vma_pagesize = transparent_hugepage_adjust(memslot, hva,
1631                                                            &pfn, &fault_ipa);
1632         if (writable)
1633                 kvm_set_pfn_dirty(pfn);
1634
1635         if (fault_status != FSC_PERM && !is_iomap(flags))
1636                 clean_dcache_guest_page(pfn, vma_pagesize);
1637
1638         if (exec_fault)
1639                 invalidate_icache_guest_page(pfn, vma_pagesize);
1640
1641         /*
1642          * If we took an execution fault we have made the
1643          * icache/dcache coherent above and should now let the s2
1644          * mapping be executable.
1645          *
1646          * Write faults (!exec_fault && FSC_PERM) are orthogonal to
1647          * execute permissions, and we preserve whatever we have.
1648          */
1649         needs_exec = exec_fault ||
1650                 (fault_status == FSC_PERM &&
1651                  stage2_is_exec(mmu, fault_ipa, vma_pagesize));
1652
1653         if (vma_pagesize == PUD_SIZE) {
1654                 pud_t new_pud = kvm_pfn_pud(pfn, mem_type);
1655
1656                 new_pud = kvm_pud_mkhuge(new_pud);
1657                 if (writable)
1658                         new_pud = kvm_s2pud_mkwrite(new_pud);
1659
1660                 if (needs_exec)
1661                         new_pud = kvm_s2pud_mkexec(new_pud);
1662
1663                 ret = stage2_set_pud_huge(mmu, memcache, fault_ipa, &new_pud);
1664         } else if (vma_pagesize == PMD_SIZE) {
1665                 pmd_t new_pmd = kvm_pfn_pmd(pfn, mem_type);
1666
1667                 new_pmd = kvm_pmd_mkhuge(new_pmd);
1668
1669                 if (writable)
1670                         new_pmd = kvm_s2pmd_mkwrite(new_pmd);
1671
1672                 if (needs_exec)
1673                         new_pmd = kvm_s2pmd_mkexec(new_pmd);
1674
1675                 ret = stage2_set_pmd_huge(mmu, memcache, fault_ipa, &new_pmd);
1676         } else {
1677                 pte_t new_pte = kvm_pfn_pte(pfn, mem_type);
1678
1679                 if (writable) {
1680                         new_pte = kvm_s2pte_mkwrite(new_pte);
1681                         mark_page_dirty(kvm, gfn);
1682                 }
1683
1684                 if (needs_exec)
1685                         new_pte = kvm_s2pte_mkexec(new_pte);
1686
1687                 ret = stage2_set_pte(mmu, memcache, fault_ipa, &new_pte, flags);
1688         }
1689
1690 out_unlock:
1691         spin_unlock(&kvm->mmu_lock);
1692         kvm_set_pfn_accessed(pfn);
1693         kvm_release_pfn_clean(pfn);
1694         return ret;
1695 }
1696
1697 /*
1698  * Resolve the access fault by making the page young again.
1699  * Note that because the faulting entry is guaranteed not to be
1700  * cached in the TLB, we don't need to invalidate anything.
1701  * Only the HW Access Flag updates are supported for Stage 2 (no DBM),
1702  * so there is no need for atomic (pte|pmd)_mkyoung operations.
1703  */
1704 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
1705 {
1706         pud_t *pud;
1707         pmd_t *pmd;
1708         pte_t *pte;
1709         kvm_pfn_t pfn;
1710         bool pfn_valid = false;
1711
1712         trace_kvm_access_fault(fault_ipa);
1713
1714         spin_lock(&vcpu->kvm->mmu_lock);
1715
1716         if (!stage2_get_leaf_entry(vcpu->arch.hw_mmu, fault_ipa, &pud, &pmd, &pte))
1717                 goto out;
1718
1719         if (pud) {              /* HugeTLB */
1720                 *pud = kvm_s2pud_mkyoung(*pud);
1721                 pfn = kvm_pud_pfn(*pud);
1722                 pfn_valid = true;
1723         } else  if (pmd) {      /* THP, HugeTLB */
1724                 *pmd = pmd_mkyoung(*pmd);
1725                 pfn = pmd_pfn(*pmd);
1726                 pfn_valid = true;
1727         } else {
1728                 *pte = pte_mkyoung(*pte);       /* Just a page... */
1729                 pfn = pte_pfn(*pte);
1730                 pfn_valid = true;
1731         }
1732
1733 out:
1734         spin_unlock(&vcpu->kvm->mmu_lock);
1735         if (pfn_valid)
1736                 kvm_set_pfn_accessed(pfn);
1737 }
1738
1739 /**
1740  * kvm_handle_guest_abort - handles all 2nd stage aborts
1741  * @vcpu:       the VCPU pointer
1742  *
1743  * Any abort that gets to the host is almost guaranteed to be caused by a
1744  * missing second stage translation table entry, which can mean that either the
1745  * guest simply needs more memory and we must allocate an appropriate page or it
1746  * can mean that the guest tried to access I/O memory, which is emulated by user
1747  * space. The distinction is based on the IPA causing the fault and whether this
1748  * memory region has been registered as standard RAM by user space.
1749  */
1750 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
1751 {
1752         unsigned long fault_status;
1753         phys_addr_t fault_ipa;
1754         struct kvm_memory_slot *memslot;
1755         unsigned long hva;
1756         bool is_iabt, write_fault, writable;
1757         gfn_t gfn;
1758         int ret, idx;
1759
1760         fault_status = kvm_vcpu_trap_get_fault_type(vcpu);
1761
1762         fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
1763         is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
1764
1765         /* Synchronous External Abort? */
1766         if (kvm_vcpu_abt_issea(vcpu)) {
1767                 /*
1768                  * For RAS the host kernel may handle this abort.
1769                  * There is no need to pass the error into the guest.
1770                  */
1771                 if (kvm_handle_guest_sea(fault_ipa, kvm_vcpu_get_esr(vcpu)))
1772                         kvm_inject_vabt(vcpu);
1773
1774                 return 1;
1775         }
1776
1777         trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_esr(vcpu),
1778                               kvm_vcpu_get_hfar(vcpu), fault_ipa);
1779
1780         /* Check the stage-2 fault is trans. fault or write fault */
1781         if (fault_status != FSC_FAULT && fault_status != FSC_PERM &&
1782             fault_status != FSC_ACCESS) {
1783                 kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
1784                         kvm_vcpu_trap_get_class(vcpu),
1785                         (unsigned long)kvm_vcpu_trap_get_fault(vcpu),
1786                         (unsigned long)kvm_vcpu_get_esr(vcpu));
1787                 return -EFAULT;
1788         }
1789
1790         idx = srcu_read_lock(&vcpu->kvm->srcu);
1791
1792         gfn = fault_ipa >> PAGE_SHIFT;
1793         memslot = gfn_to_memslot(vcpu->kvm, gfn);
1794         hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
1795         write_fault = kvm_is_write_fault(vcpu);
1796         if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
1797                 /*
1798                  * The guest has put either its instructions or its page-tables
1799                  * somewhere it shouldn't have. Userspace won't be able to do
1800                  * anything about this (there's no syndrome for a start), so
1801                  * re-inject the abort back into the guest.
1802                  */
1803                 if (is_iabt) {
1804                         ret = -ENOEXEC;
1805                         goto out;
1806                 }
1807
1808                 if (kvm_vcpu_dabt_iss1tw(vcpu)) {
1809                         kvm_inject_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1810                         ret = 1;
1811                         goto out_unlock;
1812                 }
1813
1814                 /*
1815                  * Check for a cache maintenance operation. Since we
1816                  * ended-up here, we know it is outside of any memory
1817                  * slot. But we can't find out if that is for a device,
1818                  * or if the guest is just being stupid. The only thing
1819                  * we know for sure is that this range cannot be cached.
1820                  *
1821                  * So let's assume that the guest is just being
1822                  * cautious, and skip the instruction.
1823                  */
1824                 if (kvm_is_error_hva(hva) && kvm_vcpu_dabt_is_cm(vcpu)) {
1825                         kvm_skip_instr(vcpu, kvm_vcpu_trap_il_is32bit(vcpu));
1826                         ret = 1;
1827                         goto out_unlock;
1828                 }
1829
1830                 /*
1831                  * The IPA is reported as [MAX:12], so we need to
1832                  * complement it with the bottom 12 bits from the
1833                  * faulting VA. This is always 12 bits, irrespective
1834                  * of the page size.
1835                  */
1836                 fault_ipa |= kvm_vcpu_get_hfar(vcpu) & ((1 << 12) - 1);
1837                 ret = io_mem_abort(vcpu, fault_ipa);
1838                 goto out_unlock;
1839         }
1840
1841         /* Userspace should not be able to register out-of-bounds IPAs */
1842         VM_BUG_ON(fault_ipa >= kvm_phys_size(vcpu->kvm));
1843
1844         if (fault_status == FSC_ACCESS) {
1845                 handle_access_fault(vcpu, fault_ipa);
1846                 ret = 1;
1847                 goto out_unlock;
1848         }
1849
1850         ret = user_mem_abort(vcpu, fault_ipa, memslot, hva, fault_status);
1851         if (ret == 0)
1852                 ret = 1;
1853 out:
1854         if (ret == -ENOEXEC) {
1855                 kvm_inject_pabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1856                 ret = 1;
1857         }
1858 out_unlock:
1859         srcu_read_unlock(&vcpu->kvm->srcu, idx);
1860         return ret;
1861 }
1862
1863 static int handle_hva_to_gpa(struct kvm *kvm,
1864                              unsigned long start,
1865                              unsigned long end,
1866                              int (*handler)(struct kvm *kvm,
1867                                             gpa_t gpa, u64 size,
1868                                             void *data),
1869                              void *data)
1870 {
1871         struct kvm_memslots *slots;
1872         struct kvm_memory_slot *memslot;
1873         int ret = 0;
1874
1875         slots = kvm_memslots(kvm);
1876
1877         /* we only care about the pages that the guest sees */
1878         kvm_for_each_memslot(memslot, slots) {
1879                 unsigned long hva_start, hva_end;
1880                 gfn_t gpa;
1881
1882                 hva_start = max(start, memslot->userspace_addr);
1883                 hva_end = min(end, memslot->userspace_addr +
1884                                         (memslot->npages << PAGE_SHIFT));
1885                 if (hva_start >= hva_end)
1886                         continue;
1887
1888                 gpa = hva_to_gfn_memslot(hva_start, memslot) << PAGE_SHIFT;
1889                 ret |= handler(kvm, gpa, (u64)(hva_end - hva_start), data);
1890         }
1891
1892         return ret;
1893 }
1894
1895 static int kvm_unmap_hva_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1896 {
1897         unsigned flags = *(unsigned *)data;
1898         bool may_block = flags & MMU_NOTIFIER_RANGE_BLOCKABLE;
1899
1900         __unmap_stage2_range(&kvm->arch.mmu, gpa, size, may_block);
1901         return 0;
1902 }
1903
1904 int kvm_unmap_hva_range(struct kvm *kvm,
1905                         unsigned long start, unsigned long end, unsigned flags)
1906 {
1907         if (!kvm->arch.mmu.pgd)
1908                 return 0;
1909
1910         trace_kvm_unmap_hva_range(start, end);
1911         handle_hva_to_gpa(kvm, start, end, &kvm_unmap_hva_handler, &flags);
1912         return 0;
1913 }
1914
1915 static int kvm_set_spte_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1916 {
1917         kvm_pfn_t *pfn = (kvm_pfn_t *)data;
1918
1919         WARN_ON(size != PAGE_SIZE);
1920
1921         /*
1922          * The MMU notifiers will have unmapped a huge PMD before calling
1923          * ->change_pte() (which in turn calls kvm_set_spte_hva()) and
1924          * therefore we never need to clear out a huge PMD through this
1925          * calling path and a memcache is not required.
1926          */
1927         kvm_pgtable_stage2_map(kvm->arch.mmu.pgt, gpa, PAGE_SIZE,
1928                                __pfn_to_phys(*pfn), KVM_PGTABLE_PROT_R, NULL);
1929         return 0;
1930 }
1931
1932 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1933 {
1934         unsigned long end = hva + PAGE_SIZE;
1935         kvm_pfn_t pfn = pte_pfn(pte);
1936
1937         if (!kvm->arch.mmu.pgt)
1938                 return 0;
1939
1940         trace_kvm_set_spte_hva(hva);
1941
1942         /*
1943          * We've moved a page around, probably through CoW, so let's treat it
1944          * just like a translation fault and clean the cache to the PoC.
1945          */
1946         clean_dcache_guest_page(pfn, PAGE_SIZE);
1947         handle_hva_to_gpa(kvm, hva, end, &kvm_set_spte_handler, &pfn);
1948         return 0;
1949 }
1950
1951 static int kvm_age_hva_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1952 {
1953         pud_t *pud;
1954         pmd_t *pmd;
1955         pte_t *pte;
1956
1957         WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
1958         if (!stage2_get_leaf_entry(&kvm->arch.mmu, gpa, &pud, &pmd, &pte))
1959                 return 0;
1960
1961         if (pud)
1962                 return stage2_pudp_test_and_clear_young(pud);
1963         else if (pmd)
1964                 return stage2_pmdp_test_and_clear_young(pmd);
1965         else
1966                 return stage2_ptep_test_and_clear_young(pte);
1967 }
1968
1969 static int kvm_test_age_hva_handler(struct kvm *kvm, gpa_t gpa, u64 size, void *data)
1970 {
1971         pud_t *pud;
1972         pmd_t *pmd;
1973         pte_t *pte;
1974
1975         WARN_ON(size != PAGE_SIZE && size != PMD_SIZE && size != PUD_SIZE);
1976         if (!stage2_get_leaf_entry(&kvm->arch.mmu, gpa, &pud, &pmd, &pte))
1977                 return 0;
1978
1979         if (pud)
1980                 return kvm_s2pud_young(*pud);
1981         else if (pmd)
1982                 return pmd_young(*pmd);
1983         else
1984                 return pte_young(*pte);
1985 }
1986
1987 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1988 {
1989         if (!kvm->arch.mmu.pgd)
1990                 return 0;
1991         trace_kvm_age_hva(start, end);
1992         return handle_hva_to_gpa(kvm, start, end, kvm_age_hva_handler, NULL);
1993 }
1994
1995 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1996 {
1997         if (!kvm->arch.mmu.pgd)
1998                 return 0;
1999         trace_kvm_test_age_hva(hva);
2000         return handle_hva_to_gpa(kvm, hva, hva + PAGE_SIZE,
2001                                  kvm_test_age_hva_handler, NULL);
2002 }
2003
2004 phys_addr_t kvm_mmu_get_httbr(void)
2005 {
2006         return __pa(hyp_pgtable->pgd);
2007 }
2008
2009 phys_addr_t kvm_get_idmap_vector(void)
2010 {
2011         return hyp_idmap_vector;
2012 }
2013
2014 static int kvm_map_idmap_text(void)
2015 {
2016         unsigned long size = hyp_idmap_end - hyp_idmap_start;
2017         int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
2018                                         PAGE_HYP_EXEC);
2019         if (err)
2020                 kvm_err("Failed to idmap %lx-%lx\n",
2021                         hyp_idmap_start, hyp_idmap_end);
2022
2023         return err;
2024 }
2025
2026 int kvm_mmu_init(void)
2027 {
2028         int err;
2029         u32 hyp_va_bits;
2030
2031         hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
2032         hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
2033         hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
2034         hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
2035         hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
2036
2037         /*
2038          * We rely on the linker script to ensure at build time that the HYP
2039          * init code does not cross a page boundary.
2040          */
2041         BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
2042
2043         hyp_va_bits = 64 - ((idmap_t0sz & TCR_T0SZ_MASK) >> TCR_T0SZ_OFFSET);
2044         kvm_debug("Using %u-bit virtual addresses at EL2\n", hyp_va_bits);
2045         kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
2046         kvm_debug("HYP VA range: %lx:%lx\n",
2047                   kern_hyp_va(PAGE_OFFSET),
2048                   kern_hyp_va((unsigned long)high_memory - 1));
2049
2050         if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
2051             hyp_idmap_start <  kern_hyp_va((unsigned long)high_memory - 1) &&
2052             hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
2053                 /*
2054                  * The idmap page is intersecting with the VA space,
2055                  * it is not safe to continue further.
2056                  */
2057                 kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
2058                 err = -EINVAL;
2059                 goto out;
2060         }
2061
2062         hyp_pgtable = kzalloc(sizeof(*hyp_pgtable), GFP_KERNEL);
2063         if (!hyp_pgtable) {
2064                 kvm_err("Hyp mode page-table not allocated\n");
2065                 err = -ENOMEM;
2066                 goto out;
2067         }
2068
2069         err = kvm_pgtable_hyp_init(hyp_pgtable, hyp_va_bits);
2070         if (err)
2071                 goto out_free_pgtable;
2072
2073         err = kvm_map_idmap_text();
2074         if (err)
2075                 goto out_destroy_pgtable;
2076
2077         io_map_base = hyp_idmap_start;
2078         return 0;
2079
2080 out_destroy_pgtable:
2081         kvm_pgtable_hyp_destroy(hyp_pgtable);
2082 out_free_pgtable:
2083         kfree(hyp_pgtable);
2084         hyp_pgtable = NULL;
2085 out:
2086         return err;
2087 }
2088
2089 void kvm_arch_commit_memory_region(struct kvm *kvm,
2090                                    const struct kvm_userspace_memory_region *mem,
2091                                    struct kvm_memory_slot *old,
2092                                    const struct kvm_memory_slot *new,
2093                                    enum kvm_mr_change change)
2094 {
2095         /*
2096          * At this point memslot has been committed and there is an
2097          * allocated dirty_bitmap[], dirty pages will be tracked while the
2098          * memory slot is write protected.
2099          */
2100         if (change != KVM_MR_DELETE && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
2101                 /*
2102                  * If we're with initial-all-set, we don't need to write
2103                  * protect any pages because they're all reported as dirty.
2104                  * Huge pages and normal pages will be write protect gradually.
2105                  */
2106                 if (!kvm_dirty_log_manual_protect_and_init_set(kvm)) {
2107                         kvm_mmu_wp_memory_region(kvm, mem->slot);
2108                 }
2109         }
2110 }
2111
2112 int kvm_arch_prepare_memory_region(struct kvm *kvm,
2113                                    struct kvm_memory_slot *memslot,
2114                                    const struct kvm_userspace_memory_region *mem,
2115                                    enum kvm_mr_change change)
2116 {
2117         hva_t hva = mem->userspace_addr;
2118         hva_t reg_end = hva + mem->memory_size;
2119         bool writable = !(mem->flags & KVM_MEM_READONLY);
2120         int ret = 0;
2121
2122         if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
2123                         change != KVM_MR_FLAGS_ONLY)
2124                 return 0;
2125
2126         /*
2127          * Prevent userspace from creating a memory region outside of the IPA
2128          * space addressable by the KVM guest IPA space.
2129          */
2130         if (memslot->base_gfn + memslot->npages >=
2131             (kvm_phys_size(kvm) >> PAGE_SHIFT))
2132                 return -EFAULT;
2133
2134         mmap_read_lock(current->mm);
2135         /*
2136          * A memory region could potentially cover multiple VMAs, and any holes
2137          * between them, so iterate over all of them to find out if we can map
2138          * any of them right now.
2139          *
2140          *     +--------------------------------------------+
2141          * +---------------+----------------+   +----------------+
2142          * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
2143          * +---------------+----------------+   +----------------+
2144          *     |               memory region                |
2145          *     +--------------------------------------------+
2146          */
2147         do {
2148                 struct vm_area_struct *vma = find_vma(current->mm, hva);
2149                 hva_t vm_start, vm_end;
2150
2151                 if (!vma || vma->vm_start >= reg_end)
2152                         break;
2153
2154                 /*
2155                  * Take the intersection of this VMA with the memory region
2156                  */
2157                 vm_start = max(hva, vma->vm_start);
2158                 vm_end = min(reg_end, vma->vm_end);
2159
2160                 if (vma->vm_flags & VM_PFNMAP) {
2161                         gpa_t gpa = mem->guest_phys_addr +
2162                                     (vm_start - mem->userspace_addr);
2163                         phys_addr_t pa;
2164
2165                         pa = (phys_addr_t)vma->vm_pgoff << PAGE_SHIFT;
2166                         pa += vm_start - vma->vm_start;
2167
2168                         /* IO region dirty page logging not allowed */
2169                         if (memslot->flags & KVM_MEM_LOG_DIRTY_PAGES) {
2170                                 ret = -EINVAL;
2171                                 goto out;
2172                         }
2173
2174                         ret = kvm_phys_addr_ioremap(kvm, gpa, pa,
2175                                                     vm_end - vm_start,
2176                                                     writable);
2177                         if (ret)
2178                                 break;
2179                 }
2180                 hva = vm_end;
2181         } while (hva < reg_end);
2182
2183         if (change == KVM_MR_FLAGS_ONLY)
2184                 goto out;
2185
2186         spin_lock(&kvm->mmu_lock);
2187         if (ret)
2188                 unmap_stage2_range(&kvm->arch.mmu, mem->guest_phys_addr, mem->memory_size);
2189         else
2190                 stage2_flush_memslot(kvm, memslot);
2191         spin_unlock(&kvm->mmu_lock);
2192 out:
2193         mmap_read_unlock(current->mm);
2194         return ret;
2195 }
2196
2197 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
2198 {
2199 }
2200
2201 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
2202 {
2203 }
2204
2205 void kvm_arch_flush_shadow_all(struct kvm *kvm)
2206 {
2207         kvm_free_stage2_pgd(&kvm->arch.mmu);
2208 }
2209
2210 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
2211                                    struct kvm_memory_slot *slot)
2212 {
2213         gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
2214         phys_addr_t size = slot->npages << PAGE_SHIFT;
2215
2216         spin_lock(&kvm->mmu_lock);
2217         unmap_stage2_range(&kvm->arch.mmu, gpa, size);
2218         spin_unlock(&kvm->mmu_lock);
2219 }
2220
2221 /*
2222  * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
2223  *
2224  * Main problems:
2225  * - S/W ops are local to a CPU (not broadcast)
2226  * - We have line migration behind our back (speculation)
2227  * - System caches don't support S/W at all (damn!)
2228  *
2229  * In the face of the above, the best we can do is to try and convert
2230  * S/W ops to VA ops. Because the guest is not allowed to infer the
2231  * S/W to PA mapping, it can only use S/W to nuke the whole cache,
2232  * which is a rather good thing for us.
2233  *
2234  * Also, it is only used when turning caches on/off ("The expected
2235  * usage of the cache maintenance instructions that operate by set/way
2236  * is associated with the cache maintenance instructions associated
2237  * with the powerdown and powerup of caches, if this is required by
2238  * the implementation.").
2239  *
2240  * We use the following policy:
2241  *
2242  * - If we trap a S/W operation, we enable VM trapping to detect
2243  *   caches being turned on/off, and do a full clean.
2244  *
2245  * - We flush the caches on both caches being turned on and off.
2246  *
2247  * - Once the caches are enabled, we stop trapping VM ops.
2248  */
2249 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
2250 {
2251         unsigned long hcr = *vcpu_hcr(vcpu);
2252
2253         /*
2254          * If this is the first time we do a S/W operation
2255          * (i.e. HCR_TVM not set) flush the whole memory, and set the
2256          * VM trapping.
2257          *
2258          * Otherwise, rely on the VM trapping to wait for the MMU +
2259          * Caches to be turned off. At that point, we'll be able to
2260          * clean the caches again.
2261          */
2262         if (!(hcr & HCR_TVM)) {
2263                 trace_kvm_set_way_flush(*vcpu_pc(vcpu),
2264                                         vcpu_has_cache_enabled(vcpu));
2265                 stage2_flush_vm(vcpu->kvm);
2266                 *vcpu_hcr(vcpu) = hcr | HCR_TVM;
2267         }
2268 }
2269
2270 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
2271 {
2272         bool now_enabled = vcpu_has_cache_enabled(vcpu);
2273
2274         /*
2275          * If switching the MMU+caches on, need to invalidate the caches.
2276          * If switching it off, need to clean the caches.
2277          * Clean + invalidate does the trick always.
2278          */
2279         if (now_enabled != was_enabled)
2280                 stage2_flush_vm(vcpu->kvm);
2281
2282         /* Caches are now on, stop trapping VM ops (until a S/W op) */
2283         if (now_enabled)
2284                 *vcpu_hcr(vcpu) &= ~HCR_TVM;
2285
2286         trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
2287 }