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