Merge branch 'acpi-ec'
[linux-drm-fsl-dcu.git] / arch / arm / kvm / 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 <trace/events/kvm.h>
24 #include <asm/pgalloc.h>
25 #include <asm/cacheflush.h>
26 #include <asm/kvm_arm.h>
27 #include <asm/kvm_mmu.h>
28 #include <asm/kvm_mmio.h>
29 #include <asm/kvm_asm.h>
30 #include <asm/kvm_emulate.h>
31
32 #include "trace.h"
33
34 extern char  __hyp_idmap_text_start[], __hyp_idmap_text_end[];
35
36 static pgd_t *boot_hyp_pgd;
37 static pgd_t *hyp_pgd;
38 static DEFINE_MUTEX(kvm_hyp_pgd_mutex);
39
40 static void *init_bounce_page;
41 static unsigned long hyp_idmap_start;
42 static unsigned long hyp_idmap_end;
43 static phys_addr_t hyp_idmap_vector;
44
45 #define hyp_pgd_order get_order(PTRS_PER_PGD * sizeof(pgd_t))
46
47 #define kvm_pmd_huge(_x)        (pmd_huge(_x) || pmd_trans_huge(_x))
48
49 static void kvm_tlb_flush_vmid_ipa(struct kvm *kvm, phys_addr_t ipa)
50 {
51         /*
52          * This function also gets called when dealing with HYP page
53          * tables. As HYP doesn't have an associated struct kvm (and
54          * the HYP page tables are fairly static), we don't do
55          * anything there.
56          */
57         if (kvm)
58                 kvm_call_hyp(__kvm_tlb_flush_vmid_ipa, kvm, ipa);
59 }
60
61 /*
62  * D-Cache management functions. They take the page table entries by
63  * value, as they are flushing the cache using the kernel mapping (or
64  * kmap on 32bit).
65  */
66 static void kvm_flush_dcache_pte(pte_t pte)
67 {
68         __kvm_flush_dcache_pte(pte);
69 }
70
71 static void kvm_flush_dcache_pmd(pmd_t pmd)
72 {
73         __kvm_flush_dcache_pmd(pmd);
74 }
75
76 static void kvm_flush_dcache_pud(pud_t pud)
77 {
78         __kvm_flush_dcache_pud(pud);
79 }
80
81 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
82                                   int min, int max)
83 {
84         void *page;
85
86         BUG_ON(max > KVM_NR_MEM_OBJS);
87         if (cache->nobjs >= min)
88                 return 0;
89         while (cache->nobjs < max) {
90                 page = (void *)__get_free_page(PGALLOC_GFP);
91                 if (!page)
92                         return -ENOMEM;
93                 cache->objects[cache->nobjs++] = page;
94         }
95         return 0;
96 }
97
98 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
99 {
100         while (mc->nobjs)
101                 free_page((unsigned long)mc->objects[--mc->nobjs]);
102 }
103
104 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
105 {
106         void *p;
107
108         BUG_ON(!mc || !mc->nobjs);
109         p = mc->objects[--mc->nobjs];
110         return p;
111 }
112
113 static void clear_pgd_entry(struct kvm *kvm, pgd_t *pgd, phys_addr_t addr)
114 {
115         pud_t *pud_table __maybe_unused = pud_offset(pgd, 0);
116         pgd_clear(pgd);
117         kvm_tlb_flush_vmid_ipa(kvm, addr);
118         pud_free(NULL, pud_table);
119         put_page(virt_to_page(pgd));
120 }
121
122 static void clear_pud_entry(struct kvm *kvm, pud_t *pud, phys_addr_t addr)
123 {
124         pmd_t *pmd_table = pmd_offset(pud, 0);
125         VM_BUG_ON(pud_huge(*pud));
126         pud_clear(pud);
127         kvm_tlb_flush_vmid_ipa(kvm, addr);
128         pmd_free(NULL, pmd_table);
129         put_page(virt_to_page(pud));
130 }
131
132 static void clear_pmd_entry(struct kvm *kvm, pmd_t *pmd, phys_addr_t addr)
133 {
134         pte_t *pte_table = pte_offset_kernel(pmd, 0);
135         VM_BUG_ON(kvm_pmd_huge(*pmd));
136         pmd_clear(pmd);
137         kvm_tlb_flush_vmid_ipa(kvm, addr);
138         pte_free_kernel(NULL, pte_table);
139         put_page(virt_to_page(pmd));
140 }
141
142 /*
143  * Unmapping vs dcache management:
144  *
145  * If a guest maps certain memory pages as uncached, all writes will
146  * bypass the data cache and go directly to RAM.  However, the CPUs
147  * can still speculate reads (not writes) and fill cache lines with
148  * data.
149  *
150  * Those cache lines will be *clean* cache lines though, so a
151  * clean+invalidate operation is equivalent to an invalidate
152  * operation, because no cache lines are marked dirty.
153  *
154  * Those clean cache lines could be filled prior to an uncached write
155  * by the guest, and the cache coherent IO subsystem would therefore
156  * end up writing old data to disk.
157  *
158  * This is why right after unmapping a page/section and invalidating
159  * the corresponding TLBs, we call kvm_flush_dcache_p*() to make sure
160  * the IO subsystem will never hit in the cache.
161  */
162 static void unmap_ptes(struct kvm *kvm, pmd_t *pmd,
163                        phys_addr_t addr, phys_addr_t end)
164 {
165         phys_addr_t start_addr = addr;
166         pte_t *pte, *start_pte;
167
168         start_pte = pte = pte_offset_kernel(pmd, addr);
169         do {
170                 if (!pte_none(*pte)) {
171                         pte_t old_pte = *pte;
172
173                         kvm_set_pte(pte, __pte(0));
174                         kvm_tlb_flush_vmid_ipa(kvm, addr);
175
176                         /* No need to invalidate the cache for device mappings */
177                         if ((pte_val(old_pte) & PAGE_S2_DEVICE) != PAGE_S2_DEVICE)
178                                 kvm_flush_dcache_pte(old_pte);
179
180                         put_page(virt_to_page(pte));
181                 }
182         } while (pte++, addr += PAGE_SIZE, addr != end);
183
184         if (kvm_pte_table_empty(kvm, start_pte))
185                 clear_pmd_entry(kvm, pmd, start_addr);
186 }
187
188 static void unmap_pmds(struct kvm *kvm, pud_t *pud,
189                        phys_addr_t addr, phys_addr_t end)
190 {
191         phys_addr_t next, start_addr = addr;
192         pmd_t *pmd, *start_pmd;
193
194         start_pmd = pmd = pmd_offset(pud, addr);
195         do {
196                 next = kvm_pmd_addr_end(addr, end);
197                 if (!pmd_none(*pmd)) {
198                         if (kvm_pmd_huge(*pmd)) {
199                                 pmd_t old_pmd = *pmd;
200
201                                 pmd_clear(pmd);
202                                 kvm_tlb_flush_vmid_ipa(kvm, addr);
203
204                                 kvm_flush_dcache_pmd(old_pmd);
205
206                                 put_page(virt_to_page(pmd));
207                         } else {
208                                 unmap_ptes(kvm, pmd, addr, next);
209                         }
210                 }
211         } while (pmd++, addr = next, addr != end);
212
213         if (kvm_pmd_table_empty(kvm, start_pmd))
214                 clear_pud_entry(kvm, pud, start_addr);
215 }
216
217 static void unmap_puds(struct kvm *kvm, pgd_t *pgd,
218                        phys_addr_t addr, phys_addr_t end)
219 {
220         phys_addr_t next, start_addr = addr;
221         pud_t *pud, *start_pud;
222
223         start_pud = pud = pud_offset(pgd, addr);
224         do {
225                 next = kvm_pud_addr_end(addr, end);
226                 if (!pud_none(*pud)) {
227                         if (pud_huge(*pud)) {
228                                 pud_t old_pud = *pud;
229
230                                 pud_clear(pud);
231                                 kvm_tlb_flush_vmid_ipa(kvm, addr);
232
233                                 kvm_flush_dcache_pud(old_pud);
234
235                                 put_page(virt_to_page(pud));
236                         } else {
237                                 unmap_pmds(kvm, pud, addr, next);
238                         }
239                 }
240         } while (pud++, addr = next, addr != end);
241
242         if (kvm_pud_table_empty(kvm, start_pud))
243                 clear_pgd_entry(kvm, pgd, start_addr);
244 }
245
246
247 static void unmap_range(struct kvm *kvm, pgd_t *pgdp,
248                         phys_addr_t start, u64 size)
249 {
250         pgd_t *pgd;
251         phys_addr_t addr = start, end = start + size;
252         phys_addr_t next;
253
254         pgd = pgdp + pgd_index(addr);
255         do {
256                 next = kvm_pgd_addr_end(addr, end);
257                 if (!pgd_none(*pgd))
258                         unmap_puds(kvm, pgd, addr, next);
259         } while (pgd++, addr = next, addr != end);
260 }
261
262 static void stage2_flush_ptes(struct kvm *kvm, pmd_t *pmd,
263                               phys_addr_t addr, phys_addr_t end)
264 {
265         pte_t *pte;
266
267         pte = pte_offset_kernel(pmd, addr);
268         do {
269                 if (!pte_none(*pte) &&
270                     (pte_val(*pte) & PAGE_S2_DEVICE) != PAGE_S2_DEVICE)
271                         kvm_flush_dcache_pte(*pte);
272         } while (pte++, addr += PAGE_SIZE, addr != end);
273 }
274
275 static void stage2_flush_pmds(struct kvm *kvm, pud_t *pud,
276                               phys_addr_t addr, phys_addr_t end)
277 {
278         pmd_t *pmd;
279         phys_addr_t next;
280
281         pmd = pmd_offset(pud, addr);
282         do {
283                 next = kvm_pmd_addr_end(addr, end);
284                 if (!pmd_none(*pmd)) {
285                         if (kvm_pmd_huge(*pmd))
286                                 kvm_flush_dcache_pmd(*pmd);
287                         else
288                                 stage2_flush_ptes(kvm, pmd, addr, next);
289                 }
290         } while (pmd++, addr = next, addr != end);
291 }
292
293 static void stage2_flush_puds(struct kvm *kvm, pgd_t *pgd,
294                               phys_addr_t addr, phys_addr_t end)
295 {
296         pud_t *pud;
297         phys_addr_t next;
298
299         pud = pud_offset(pgd, addr);
300         do {
301                 next = kvm_pud_addr_end(addr, end);
302                 if (!pud_none(*pud)) {
303                         if (pud_huge(*pud))
304                                 kvm_flush_dcache_pud(*pud);
305                         else
306                                 stage2_flush_pmds(kvm, pud, addr, next);
307                 }
308         } while (pud++, addr = next, addr != end);
309 }
310
311 static void stage2_flush_memslot(struct kvm *kvm,
312                                  struct kvm_memory_slot *memslot)
313 {
314         phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
315         phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
316         phys_addr_t next;
317         pgd_t *pgd;
318
319         pgd = kvm->arch.pgd + pgd_index(addr);
320         do {
321                 next = kvm_pgd_addr_end(addr, end);
322                 stage2_flush_puds(kvm, pgd, addr, next);
323         } while (pgd++, addr = next, addr != end);
324 }
325
326 /**
327  * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
328  * @kvm: The struct kvm pointer
329  *
330  * Go through the stage 2 page tables and invalidate any cache lines
331  * backing memory already mapped to the VM.
332  */
333 static void stage2_flush_vm(struct kvm *kvm)
334 {
335         struct kvm_memslots *slots;
336         struct kvm_memory_slot *memslot;
337         int idx;
338
339         idx = srcu_read_lock(&kvm->srcu);
340         spin_lock(&kvm->mmu_lock);
341
342         slots = kvm_memslots(kvm);
343         kvm_for_each_memslot(memslot, slots)
344                 stage2_flush_memslot(kvm, memslot);
345
346         spin_unlock(&kvm->mmu_lock);
347         srcu_read_unlock(&kvm->srcu, idx);
348 }
349
350 /**
351  * free_boot_hyp_pgd - free HYP boot page tables
352  *
353  * Free the HYP boot page tables. The bounce page is also freed.
354  */
355 void free_boot_hyp_pgd(void)
356 {
357         mutex_lock(&kvm_hyp_pgd_mutex);
358
359         if (boot_hyp_pgd) {
360                 unmap_range(NULL, boot_hyp_pgd, hyp_idmap_start, PAGE_SIZE);
361                 unmap_range(NULL, boot_hyp_pgd, TRAMPOLINE_VA, PAGE_SIZE);
362                 free_pages((unsigned long)boot_hyp_pgd, hyp_pgd_order);
363                 boot_hyp_pgd = NULL;
364         }
365
366         if (hyp_pgd)
367                 unmap_range(NULL, hyp_pgd, TRAMPOLINE_VA, PAGE_SIZE);
368
369         free_page((unsigned long)init_bounce_page);
370         init_bounce_page = NULL;
371
372         mutex_unlock(&kvm_hyp_pgd_mutex);
373 }
374
375 /**
376  * free_hyp_pgds - free Hyp-mode page tables
377  *
378  * Assumes hyp_pgd is a page table used strictly in Hyp-mode and
379  * therefore contains either mappings in the kernel memory area (above
380  * PAGE_OFFSET), or device mappings in the vmalloc range (from
381  * VMALLOC_START to VMALLOC_END).
382  *
383  * boot_hyp_pgd should only map two pages for the init code.
384  */
385 void free_hyp_pgds(void)
386 {
387         unsigned long addr;
388
389         free_boot_hyp_pgd();
390
391         mutex_lock(&kvm_hyp_pgd_mutex);
392
393         if (hyp_pgd) {
394                 for (addr = PAGE_OFFSET; virt_addr_valid(addr); addr += PGDIR_SIZE)
395                         unmap_range(NULL, hyp_pgd, KERN_TO_HYP(addr), PGDIR_SIZE);
396                 for (addr = VMALLOC_START; is_vmalloc_addr((void*)addr); addr += PGDIR_SIZE)
397                         unmap_range(NULL, hyp_pgd, KERN_TO_HYP(addr), PGDIR_SIZE);
398
399                 free_pages((unsigned long)hyp_pgd, hyp_pgd_order);
400                 hyp_pgd = NULL;
401         }
402
403         mutex_unlock(&kvm_hyp_pgd_mutex);
404 }
405
406 static void create_hyp_pte_mappings(pmd_t *pmd, unsigned long start,
407                                     unsigned long end, unsigned long pfn,
408                                     pgprot_t prot)
409 {
410         pte_t *pte;
411         unsigned long addr;
412
413         addr = start;
414         do {
415                 pte = pte_offset_kernel(pmd, addr);
416                 kvm_set_pte(pte, pfn_pte(pfn, prot));
417                 get_page(virt_to_page(pte));
418                 kvm_flush_dcache_to_poc(pte, sizeof(*pte));
419                 pfn++;
420         } while (addr += PAGE_SIZE, addr != end);
421 }
422
423 static int create_hyp_pmd_mappings(pud_t *pud, unsigned long start,
424                                    unsigned long end, unsigned long pfn,
425                                    pgprot_t prot)
426 {
427         pmd_t *pmd;
428         pte_t *pte;
429         unsigned long addr, next;
430
431         addr = start;
432         do {
433                 pmd = pmd_offset(pud, addr);
434
435                 BUG_ON(pmd_sect(*pmd));
436
437                 if (pmd_none(*pmd)) {
438                         pte = pte_alloc_one_kernel(NULL, addr);
439                         if (!pte) {
440                                 kvm_err("Cannot allocate Hyp pte\n");
441                                 return -ENOMEM;
442                         }
443                         pmd_populate_kernel(NULL, pmd, pte);
444                         get_page(virt_to_page(pmd));
445                         kvm_flush_dcache_to_poc(pmd, sizeof(*pmd));
446                 }
447
448                 next = pmd_addr_end(addr, end);
449
450                 create_hyp_pte_mappings(pmd, addr, next, pfn, prot);
451                 pfn += (next - addr) >> PAGE_SHIFT;
452         } while (addr = next, addr != end);
453
454         return 0;
455 }
456
457 static int create_hyp_pud_mappings(pgd_t *pgd, unsigned long start,
458                                    unsigned long end, unsigned long pfn,
459                                    pgprot_t prot)
460 {
461         pud_t *pud;
462         pmd_t *pmd;
463         unsigned long addr, next;
464         int ret;
465
466         addr = start;
467         do {
468                 pud = pud_offset(pgd, addr);
469
470                 if (pud_none_or_clear_bad(pud)) {
471                         pmd = pmd_alloc_one(NULL, addr);
472                         if (!pmd) {
473                                 kvm_err("Cannot allocate Hyp pmd\n");
474                                 return -ENOMEM;
475                         }
476                         pud_populate(NULL, pud, pmd);
477                         get_page(virt_to_page(pud));
478                         kvm_flush_dcache_to_poc(pud, sizeof(*pud));
479                 }
480
481                 next = pud_addr_end(addr, end);
482                 ret = create_hyp_pmd_mappings(pud, addr, next, pfn, prot);
483                 if (ret)
484                         return ret;
485                 pfn += (next - addr) >> PAGE_SHIFT;
486         } while (addr = next, addr != end);
487
488         return 0;
489 }
490
491 static int __create_hyp_mappings(pgd_t *pgdp,
492                                  unsigned long start, unsigned long end,
493                                  unsigned long pfn, pgprot_t prot)
494 {
495         pgd_t *pgd;
496         pud_t *pud;
497         unsigned long addr, next;
498         int err = 0;
499
500         mutex_lock(&kvm_hyp_pgd_mutex);
501         addr = start & PAGE_MASK;
502         end = PAGE_ALIGN(end);
503         do {
504                 pgd = pgdp + pgd_index(addr);
505
506                 if (pgd_none(*pgd)) {
507                         pud = pud_alloc_one(NULL, addr);
508                         if (!pud) {
509                                 kvm_err("Cannot allocate Hyp pud\n");
510                                 err = -ENOMEM;
511                                 goto out;
512                         }
513                         pgd_populate(NULL, pgd, pud);
514                         get_page(virt_to_page(pgd));
515                         kvm_flush_dcache_to_poc(pgd, sizeof(*pgd));
516                 }
517
518                 next = pgd_addr_end(addr, end);
519                 err = create_hyp_pud_mappings(pgd, addr, next, pfn, prot);
520                 if (err)
521                         goto out;
522                 pfn += (next - addr) >> PAGE_SHIFT;
523         } while (addr = next, addr != end);
524 out:
525         mutex_unlock(&kvm_hyp_pgd_mutex);
526         return err;
527 }
528
529 static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
530 {
531         if (!is_vmalloc_addr(kaddr)) {
532                 BUG_ON(!virt_addr_valid(kaddr));
533                 return __pa(kaddr);
534         } else {
535                 return page_to_phys(vmalloc_to_page(kaddr)) +
536                        offset_in_page(kaddr);
537         }
538 }
539
540 /**
541  * create_hyp_mappings - duplicate a kernel virtual address range in Hyp mode
542  * @from:       The virtual kernel start address of the range
543  * @to:         The virtual kernel end address of the range (exclusive)
544  *
545  * The same virtual address as the kernel virtual address is also used
546  * in Hyp-mode mapping (modulo HYP_PAGE_OFFSET) to the same underlying
547  * physical pages.
548  */
549 int create_hyp_mappings(void *from, void *to)
550 {
551         phys_addr_t phys_addr;
552         unsigned long virt_addr;
553         unsigned long start = KERN_TO_HYP((unsigned long)from);
554         unsigned long end = KERN_TO_HYP((unsigned long)to);
555
556         start = start & PAGE_MASK;
557         end = PAGE_ALIGN(end);
558
559         for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
560                 int err;
561
562                 phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
563                 err = __create_hyp_mappings(hyp_pgd, virt_addr,
564                                             virt_addr + PAGE_SIZE,
565                                             __phys_to_pfn(phys_addr),
566                                             PAGE_HYP);
567                 if (err)
568                         return err;
569         }
570
571         return 0;
572 }
573
574 /**
575  * create_hyp_io_mappings - duplicate a kernel IO mapping into Hyp mode
576  * @from:       The kernel start VA of the range
577  * @to:         The kernel end VA of the range (exclusive)
578  * @phys_addr:  The physical start address which gets mapped
579  *
580  * The resulting HYP VA is the same as the kernel VA, modulo
581  * HYP_PAGE_OFFSET.
582  */
583 int create_hyp_io_mappings(void *from, void *to, phys_addr_t phys_addr)
584 {
585         unsigned long start = KERN_TO_HYP((unsigned long)from);
586         unsigned long end = KERN_TO_HYP((unsigned long)to);
587
588         /* Check for a valid kernel IO mapping */
589         if (!is_vmalloc_addr(from) || !is_vmalloc_addr(to - 1))
590                 return -EINVAL;
591
592         return __create_hyp_mappings(hyp_pgd, start, end,
593                                      __phys_to_pfn(phys_addr), PAGE_HYP_DEVICE);
594 }
595
596 /**
597  * kvm_alloc_stage2_pgd - allocate level-1 table for stage-2 translation.
598  * @kvm:        The KVM struct pointer for the VM.
599  *
600  * Allocates the 1st level table only of size defined by S2_PGD_ORDER (can
601  * support either full 40-bit input addresses or limited to 32-bit input
602  * addresses). Clears the allocated pages.
603  *
604  * Note we don't need locking here as this is only called when the VM is
605  * created, which can only be done once.
606  */
607 int kvm_alloc_stage2_pgd(struct kvm *kvm)
608 {
609         int ret;
610         pgd_t *pgd;
611
612         if (kvm->arch.pgd != NULL) {
613                 kvm_err("kvm_arch already initialized?\n");
614                 return -EINVAL;
615         }
616
617         if (KVM_PREALLOC_LEVEL > 0) {
618                 /*
619                  * Allocate fake pgd for the page table manipulation macros to
620                  * work.  This is not used by the hardware and we have no
621                  * alignment requirement for this allocation.
622                  */
623                 pgd = (pgd_t *)kmalloc(PTRS_PER_S2_PGD * sizeof(pgd_t),
624                                        GFP_KERNEL | __GFP_ZERO);
625         } else {
626                 /*
627                  * Allocate actual first-level Stage-2 page table used by the
628                  * hardware for Stage-2 page table walks.
629                  */
630                 pgd = (pgd_t *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, S2_PGD_ORDER);
631         }
632
633         if (!pgd)
634                 return -ENOMEM;
635
636         ret = kvm_prealloc_hwpgd(kvm, pgd);
637         if (ret)
638                 goto out_err;
639
640         kvm_clean_pgd(pgd);
641         kvm->arch.pgd = pgd;
642         return 0;
643 out_err:
644         if (KVM_PREALLOC_LEVEL > 0)
645                 kfree(pgd);
646         else
647                 free_pages((unsigned long)pgd, S2_PGD_ORDER);
648         return ret;
649 }
650
651 /**
652  * unmap_stage2_range -- Clear stage2 page table entries to unmap a range
653  * @kvm:   The VM pointer
654  * @start: The intermediate physical base address of the range to unmap
655  * @size:  The size of the area to unmap
656  *
657  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
658  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
659  * destroying the VM), otherwise another faulting VCPU may come in and mess
660  * with things behind our backs.
661  */
662 static void unmap_stage2_range(struct kvm *kvm, phys_addr_t start, u64 size)
663 {
664         unmap_range(kvm, kvm->arch.pgd, start, size);
665 }
666
667 static void stage2_unmap_memslot(struct kvm *kvm,
668                                  struct kvm_memory_slot *memslot)
669 {
670         hva_t hva = memslot->userspace_addr;
671         phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
672         phys_addr_t size = PAGE_SIZE * memslot->npages;
673         hva_t reg_end = hva + size;
674
675         /*
676          * A memory region could potentially cover multiple VMAs, and any holes
677          * between them, so iterate over all of them to find out if we should
678          * unmap any of them.
679          *
680          *     +--------------------------------------------+
681          * +---------------+----------------+   +----------------+
682          * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
683          * +---------------+----------------+   +----------------+
684          *     |               memory region                |
685          *     +--------------------------------------------+
686          */
687         do {
688                 struct vm_area_struct *vma = find_vma(current->mm, hva);
689                 hva_t vm_start, vm_end;
690
691                 if (!vma || vma->vm_start >= reg_end)
692                         break;
693
694                 /*
695                  * Take the intersection of this VMA with the memory region
696                  */
697                 vm_start = max(hva, vma->vm_start);
698                 vm_end = min(reg_end, vma->vm_end);
699
700                 if (!(vma->vm_flags & VM_PFNMAP)) {
701                         gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
702                         unmap_stage2_range(kvm, gpa, vm_end - vm_start);
703                 }
704                 hva = vm_end;
705         } while (hva < reg_end);
706 }
707
708 /**
709  * stage2_unmap_vm - Unmap Stage-2 RAM mappings
710  * @kvm: The struct kvm pointer
711  *
712  * Go through the memregions and unmap any reguler RAM
713  * backing memory already mapped to the VM.
714  */
715 void stage2_unmap_vm(struct kvm *kvm)
716 {
717         struct kvm_memslots *slots;
718         struct kvm_memory_slot *memslot;
719         int idx;
720
721         idx = srcu_read_lock(&kvm->srcu);
722         spin_lock(&kvm->mmu_lock);
723
724         slots = kvm_memslots(kvm);
725         kvm_for_each_memslot(memslot, slots)
726                 stage2_unmap_memslot(kvm, memslot);
727
728         spin_unlock(&kvm->mmu_lock);
729         srcu_read_unlock(&kvm->srcu, idx);
730 }
731
732 /**
733  * kvm_free_stage2_pgd - free all stage-2 tables
734  * @kvm:        The KVM struct pointer for the VM.
735  *
736  * Walks the level-1 page table pointed to by kvm->arch.pgd and frees all
737  * underlying level-2 and level-3 tables before freeing the actual level-1 table
738  * and setting the struct pointer to NULL.
739  *
740  * Note we don't need locking here as this is only called when the VM is
741  * destroyed, which can only be done once.
742  */
743 void kvm_free_stage2_pgd(struct kvm *kvm)
744 {
745         if (kvm->arch.pgd == NULL)
746                 return;
747
748         unmap_stage2_range(kvm, 0, KVM_PHYS_SIZE);
749         kvm_free_hwpgd(kvm);
750         if (KVM_PREALLOC_LEVEL > 0)
751                 kfree(kvm->arch.pgd);
752         else
753                 free_pages((unsigned long)kvm->arch.pgd, S2_PGD_ORDER);
754         kvm->arch.pgd = NULL;
755 }
756
757 static pud_t *stage2_get_pud(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
758                              phys_addr_t addr)
759 {
760         pgd_t *pgd;
761         pud_t *pud;
762
763         pgd = kvm->arch.pgd + pgd_index(addr);
764         if (WARN_ON(pgd_none(*pgd))) {
765                 if (!cache)
766                         return NULL;
767                 pud = mmu_memory_cache_alloc(cache);
768                 pgd_populate(NULL, pgd, pud);
769                 get_page(virt_to_page(pgd));
770         }
771
772         return pud_offset(pgd, addr);
773 }
774
775 static pmd_t *stage2_get_pmd(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
776                              phys_addr_t addr)
777 {
778         pud_t *pud;
779         pmd_t *pmd;
780
781         pud = stage2_get_pud(kvm, cache, addr);
782         if (pud_none(*pud)) {
783                 if (!cache)
784                         return NULL;
785                 pmd = mmu_memory_cache_alloc(cache);
786                 pud_populate(NULL, pud, pmd);
787                 get_page(virt_to_page(pud));
788         }
789
790         return pmd_offset(pud, addr);
791 }
792
793 static int stage2_set_pmd_huge(struct kvm *kvm, struct kvm_mmu_memory_cache
794                                *cache, phys_addr_t addr, const pmd_t *new_pmd)
795 {
796         pmd_t *pmd, old_pmd;
797
798         pmd = stage2_get_pmd(kvm, cache, addr);
799         VM_BUG_ON(!pmd);
800
801         /*
802          * Mapping in huge pages should only happen through a fault.  If a
803          * page is merged into a transparent huge page, the individual
804          * subpages of that huge page should be unmapped through MMU
805          * notifiers before we get here.
806          *
807          * Merging of CompoundPages is not supported; they should become
808          * splitting first, unmapped, merged, and mapped back in on-demand.
809          */
810         VM_BUG_ON(pmd_present(*pmd) && pmd_pfn(*pmd) != pmd_pfn(*new_pmd));
811
812         old_pmd = *pmd;
813         kvm_set_pmd(pmd, *new_pmd);
814         if (pmd_present(old_pmd))
815                 kvm_tlb_flush_vmid_ipa(kvm, addr);
816         else
817                 get_page(virt_to_page(pmd));
818         return 0;
819 }
820
821 static int stage2_set_pte(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
822                           phys_addr_t addr, const pte_t *new_pte, bool iomap)
823 {
824         pmd_t *pmd;
825         pte_t *pte, old_pte;
826
827         /* Create stage-2 page table mapping - Levels 0 and 1 */
828         pmd = stage2_get_pmd(kvm, cache, addr);
829         if (!pmd) {
830                 /*
831                  * Ignore calls from kvm_set_spte_hva for unallocated
832                  * address ranges.
833                  */
834                 return 0;
835         }
836
837         /* Create stage-2 page mappings - Level 2 */
838         if (pmd_none(*pmd)) {
839                 if (!cache)
840                         return 0; /* ignore calls from kvm_set_spte_hva */
841                 pte = mmu_memory_cache_alloc(cache);
842                 kvm_clean_pte(pte);
843                 pmd_populate_kernel(NULL, pmd, pte);
844                 get_page(virt_to_page(pmd));
845         }
846
847         pte = pte_offset_kernel(pmd, addr);
848
849         if (iomap && pte_present(*pte))
850                 return -EFAULT;
851
852         /* Create 2nd stage page table mapping - Level 3 */
853         old_pte = *pte;
854         kvm_set_pte(pte, *new_pte);
855         if (pte_present(old_pte))
856                 kvm_tlb_flush_vmid_ipa(kvm, addr);
857         else
858                 get_page(virt_to_page(pte));
859
860         return 0;
861 }
862
863 /**
864  * kvm_phys_addr_ioremap - map a device range to guest IPA
865  *
866  * @kvm:        The KVM pointer
867  * @guest_ipa:  The IPA at which to insert the mapping
868  * @pa:         The physical address of the device
869  * @size:       The size of the mapping
870  */
871 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
872                           phys_addr_t pa, unsigned long size, bool writable)
873 {
874         phys_addr_t addr, end;
875         int ret = 0;
876         unsigned long pfn;
877         struct kvm_mmu_memory_cache cache = { 0, };
878
879         end = (guest_ipa + size + PAGE_SIZE - 1) & PAGE_MASK;
880         pfn = __phys_to_pfn(pa);
881
882         for (addr = guest_ipa; addr < end; addr += PAGE_SIZE) {
883                 pte_t pte = pfn_pte(pfn, PAGE_S2_DEVICE);
884
885                 if (writable)
886                         kvm_set_s2pte_writable(&pte);
887
888                 ret = mmu_topup_memory_cache(&cache, KVM_MMU_CACHE_MIN_PAGES,
889                                                 KVM_NR_MEM_OBJS);
890                 if (ret)
891                         goto out;
892                 spin_lock(&kvm->mmu_lock);
893                 ret = stage2_set_pte(kvm, &cache, addr, &pte, true);
894                 spin_unlock(&kvm->mmu_lock);
895                 if (ret)
896                         goto out;
897
898                 pfn++;
899         }
900
901 out:
902         mmu_free_memory_cache(&cache);
903         return ret;
904 }
905
906 static bool transparent_hugepage_adjust(pfn_t *pfnp, phys_addr_t *ipap)
907 {
908         pfn_t pfn = *pfnp;
909         gfn_t gfn = *ipap >> PAGE_SHIFT;
910
911         if (PageTransCompound(pfn_to_page(pfn))) {
912                 unsigned long mask;
913                 /*
914                  * The address we faulted on is backed by a transparent huge
915                  * page.  However, because we map the compound huge page and
916                  * not the individual tail page, we need to transfer the
917                  * refcount to the head page.  We have to be careful that the
918                  * THP doesn't start to split while we are adjusting the
919                  * refcounts.
920                  *
921                  * We are sure this doesn't happen, because mmu_notifier_retry
922                  * was successful and we are holding the mmu_lock, so if this
923                  * THP is trying to split, it will be blocked in the mmu
924                  * notifier before touching any of the pages, specifically
925                  * before being able to call __split_huge_page_refcount().
926                  *
927                  * We can therefore safely transfer the refcount from PG_tail
928                  * to PG_head and switch the pfn from a tail page to the head
929                  * page accordingly.
930                  */
931                 mask = PTRS_PER_PMD - 1;
932                 VM_BUG_ON((gfn & mask) != (pfn & mask));
933                 if (pfn & mask) {
934                         *ipap &= PMD_MASK;
935                         kvm_release_pfn_clean(pfn);
936                         pfn &= ~mask;
937                         kvm_get_pfn(pfn);
938                         *pfnp = pfn;
939                 }
940
941                 return true;
942         }
943
944         return false;
945 }
946
947 static bool kvm_is_write_fault(struct kvm_vcpu *vcpu)
948 {
949         if (kvm_vcpu_trap_is_iabt(vcpu))
950                 return false;
951
952         return kvm_vcpu_dabt_iswrite(vcpu);
953 }
954
955 static bool kvm_is_device_pfn(unsigned long pfn)
956 {
957         return !pfn_valid(pfn);
958 }
959
960 static void coherent_cache_guest_page(struct kvm_vcpu *vcpu, pfn_t pfn,
961                                       unsigned long size, bool uncached)
962 {
963         __coherent_cache_guest_page(vcpu, pfn, size, uncached);
964 }
965
966 static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
967                           struct kvm_memory_slot *memslot, unsigned long hva,
968                           unsigned long fault_status)
969 {
970         int ret;
971         bool write_fault, writable, hugetlb = false, force_pte = false;
972         unsigned long mmu_seq;
973         gfn_t gfn = fault_ipa >> PAGE_SHIFT;
974         struct kvm *kvm = vcpu->kvm;
975         struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
976         struct vm_area_struct *vma;
977         pfn_t pfn;
978         pgprot_t mem_type = PAGE_S2;
979         bool fault_ipa_uncached;
980
981         write_fault = kvm_is_write_fault(vcpu);
982         if (fault_status == FSC_PERM && !write_fault) {
983                 kvm_err("Unexpected L2 read permission error\n");
984                 return -EFAULT;
985         }
986
987         /* Let's check if we will get back a huge page backed by hugetlbfs */
988         down_read(&current->mm->mmap_sem);
989         vma = find_vma_intersection(current->mm, hva, hva + 1);
990         if (unlikely(!vma)) {
991                 kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
992                 up_read(&current->mm->mmap_sem);
993                 return -EFAULT;
994         }
995
996         if (is_vm_hugetlb_page(vma)) {
997                 hugetlb = true;
998                 gfn = (fault_ipa & PMD_MASK) >> PAGE_SHIFT;
999         } else {
1000                 /*
1001                  * Pages belonging to memslots that don't have the same
1002                  * alignment for userspace and IPA cannot be mapped using
1003                  * block descriptors even if the pages belong to a THP for
1004                  * the process, because the stage-2 block descriptor will
1005                  * cover more than a single THP and we loose atomicity for
1006                  * unmapping, updates, and splits of the THP or other pages
1007                  * in the stage-2 block range.
1008                  */
1009                 if ((memslot->userspace_addr & ~PMD_MASK) !=
1010                     ((memslot->base_gfn << PAGE_SHIFT) & ~PMD_MASK))
1011                         force_pte = true;
1012         }
1013         up_read(&current->mm->mmap_sem);
1014
1015         /* We need minimum second+third level pages */
1016         ret = mmu_topup_memory_cache(memcache, KVM_MMU_CACHE_MIN_PAGES,
1017                                      KVM_NR_MEM_OBJS);
1018         if (ret)
1019                 return ret;
1020
1021         mmu_seq = vcpu->kvm->mmu_notifier_seq;
1022         /*
1023          * Ensure the read of mmu_notifier_seq happens before we call
1024          * gfn_to_pfn_prot (which calls get_user_pages), so that we don't risk
1025          * the page we just got a reference to gets unmapped before we have a
1026          * chance to grab the mmu_lock, which ensure that if the page gets
1027          * unmapped afterwards, the call to kvm_unmap_hva will take it away
1028          * from us again properly. This smp_rmb() interacts with the smp_wmb()
1029          * in kvm_mmu_notifier_invalidate_<page|range_end>.
1030          */
1031         smp_rmb();
1032
1033         pfn = gfn_to_pfn_prot(kvm, gfn, write_fault, &writable);
1034         if (is_error_pfn(pfn))
1035                 return -EFAULT;
1036
1037         if (kvm_is_device_pfn(pfn))
1038                 mem_type = PAGE_S2_DEVICE;
1039
1040         spin_lock(&kvm->mmu_lock);
1041         if (mmu_notifier_retry(kvm, mmu_seq))
1042                 goto out_unlock;
1043         if (!hugetlb && !force_pte)
1044                 hugetlb = transparent_hugepage_adjust(&pfn, &fault_ipa);
1045
1046         fault_ipa_uncached = memslot->flags & KVM_MEMSLOT_INCOHERENT;
1047
1048         if (hugetlb) {
1049                 pmd_t new_pmd = pfn_pmd(pfn, mem_type);
1050                 new_pmd = pmd_mkhuge(new_pmd);
1051                 if (writable) {
1052                         kvm_set_s2pmd_writable(&new_pmd);
1053                         kvm_set_pfn_dirty(pfn);
1054                 }
1055                 coherent_cache_guest_page(vcpu, pfn, PMD_SIZE, fault_ipa_uncached);
1056                 ret = stage2_set_pmd_huge(kvm, memcache, fault_ipa, &new_pmd);
1057         } else {
1058                 pte_t new_pte = pfn_pte(pfn, mem_type);
1059                 if (writable) {
1060                         kvm_set_s2pte_writable(&new_pte);
1061                         kvm_set_pfn_dirty(pfn);
1062                 }
1063                 coherent_cache_guest_page(vcpu, pfn, PAGE_SIZE, fault_ipa_uncached);
1064                 ret = stage2_set_pte(kvm, memcache, fault_ipa, &new_pte,
1065                         pgprot_val(mem_type) == pgprot_val(PAGE_S2_DEVICE));
1066         }
1067
1068
1069 out_unlock:
1070         spin_unlock(&kvm->mmu_lock);
1071         kvm_release_pfn_clean(pfn);
1072         return ret;
1073 }
1074
1075 /**
1076  * kvm_handle_guest_abort - handles all 2nd stage aborts
1077  * @vcpu:       the VCPU pointer
1078  * @run:        the kvm_run structure
1079  *
1080  * Any abort that gets to the host is almost guaranteed to be caused by a
1081  * missing second stage translation table entry, which can mean that either the
1082  * guest simply needs more memory and we must allocate an appropriate page or it
1083  * can mean that the guest tried to access I/O memory, which is emulated by user
1084  * space. The distinction is based on the IPA causing the fault and whether this
1085  * memory region has been registered as standard RAM by user space.
1086  */
1087 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu, struct kvm_run *run)
1088 {
1089         unsigned long fault_status;
1090         phys_addr_t fault_ipa;
1091         struct kvm_memory_slot *memslot;
1092         unsigned long hva;
1093         bool is_iabt, write_fault, writable;
1094         gfn_t gfn;
1095         int ret, idx;
1096
1097         is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
1098         fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
1099
1100         trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_hsr(vcpu),
1101                               kvm_vcpu_get_hfar(vcpu), fault_ipa);
1102
1103         /* Check the stage-2 fault is trans. fault or write fault */
1104         fault_status = kvm_vcpu_trap_get_fault_type(vcpu);
1105         if (fault_status != FSC_FAULT && fault_status != FSC_PERM) {
1106                 kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
1107                         kvm_vcpu_trap_get_class(vcpu),
1108                         (unsigned long)kvm_vcpu_trap_get_fault(vcpu),
1109                         (unsigned long)kvm_vcpu_get_hsr(vcpu));
1110                 return -EFAULT;
1111         }
1112
1113         idx = srcu_read_lock(&vcpu->kvm->srcu);
1114
1115         gfn = fault_ipa >> PAGE_SHIFT;
1116         memslot = gfn_to_memslot(vcpu->kvm, gfn);
1117         hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
1118         write_fault = kvm_is_write_fault(vcpu);
1119         if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
1120                 if (is_iabt) {
1121                         /* Prefetch Abort on I/O address */
1122                         kvm_inject_pabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1123                         ret = 1;
1124                         goto out_unlock;
1125                 }
1126
1127                 /*
1128                  * The IPA is reported as [MAX:12], so we need to
1129                  * complement it with the bottom 12 bits from the
1130                  * faulting VA. This is always 12 bits, irrespective
1131                  * of the page size.
1132                  */
1133                 fault_ipa |= kvm_vcpu_get_hfar(vcpu) & ((1 << 12) - 1);
1134                 ret = io_mem_abort(vcpu, run, fault_ipa);
1135                 goto out_unlock;
1136         }
1137
1138         /* Userspace should not be able to register out-of-bounds IPAs */
1139         VM_BUG_ON(fault_ipa >= KVM_PHYS_SIZE);
1140
1141         ret = user_mem_abort(vcpu, fault_ipa, memslot, hva, fault_status);
1142         if (ret == 0)
1143                 ret = 1;
1144 out_unlock:
1145         srcu_read_unlock(&vcpu->kvm->srcu, idx);
1146         return ret;
1147 }
1148
1149 static void handle_hva_to_gpa(struct kvm *kvm,
1150                               unsigned long start,
1151                               unsigned long end,
1152                               void (*handler)(struct kvm *kvm,
1153                                               gpa_t gpa, void *data),
1154                               void *data)
1155 {
1156         struct kvm_memslots *slots;
1157         struct kvm_memory_slot *memslot;
1158
1159         slots = kvm_memslots(kvm);
1160
1161         /* we only care about the pages that the guest sees */
1162         kvm_for_each_memslot(memslot, slots) {
1163                 unsigned long hva_start, hva_end;
1164                 gfn_t gfn, gfn_end;
1165
1166                 hva_start = max(start, memslot->userspace_addr);
1167                 hva_end = min(end, memslot->userspace_addr +
1168                                         (memslot->npages << PAGE_SHIFT));
1169                 if (hva_start >= hva_end)
1170                         continue;
1171
1172                 /*
1173                  * {gfn(page) | page intersects with [hva_start, hva_end)} =
1174                  * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1175                  */
1176                 gfn = hva_to_gfn_memslot(hva_start, memslot);
1177                 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1178
1179                 for (; gfn < gfn_end; ++gfn) {
1180                         gpa_t gpa = gfn << PAGE_SHIFT;
1181                         handler(kvm, gpa, data);
1182                 }
1183         }
1184 }
1185
1186 static void kvm_unmap_hva_handler(struct kvm *kvm, gpa_t gpa, void *data)
1187 {
1188         unmap_stage2_range(kvm, gpa, PAGE_SIZE);
1189 }
1190
1191 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
1192 {
1193         unsigned long end = hva + PAGE_SIZE;
1194
1195         if (!kvm->arch.pgd)
1196                 return 0;
1197
1198         trace_kvm_unmap_hva(hva);
1199         handle_hva_to_gpa(kvm, hva, end, &kvm_unmap_hva_handler, NULL);
1200         return 0;
1201 }
1202
1203 int kvm_unmap_hva_range(struct kvm *kvm,
1204                         unsigned long start, unsigned long end)
1205 {
1206         if (!kvm->arch.pgd)
1207                 return 0;
1208
1209         trace_kvm_unmap_hva_range(start, end);
1210         handle_hva_to_gpa(kvm, start, end, &kvm_unmap_hva_handler, NULL);
1211         return 0;
1212 }
1213
1214 static void kvm_set_spte_handler(struct kvm *kvm, gpa_t gpa, void *data)
1215 {
1216         pte_t *pte = (pte_t *)data;
1217
1218         stage2_set_pte(kvm, NULL, gpa, pte, false);
1219 }
1220
1221
1222 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1223 {
1224         unsigned long end = hva + PAGE_SIZE;
1225         pte_t stage2_pte;
1226
1227         if (!kvm->arch.pgd)
1228                 return;
1229
1230         trace_kvm_set_spte_hva(hva);
1231         stage2_pte = pfn_pte(pte_pfn(pte), PAGE_S2);
1232         handle_hva_to_gpa(kvm, hva, end, &kvm_set_spte_handler, &stage2_pte);
1233 }
1234
1235 void kvm_mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1236 {
1237         mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
1238 }
1239
1240 phys_addr_t kvm_mmu_get_httbr(void)
1241 {
1242         return virt_to_phys(hyp_pgd);
1243 }
1244
1245 phys_addr_t kvm_mmu_get_boot_httbr(void)
1246 {
1247         return virt_to_phys(boot_hyp_pgd);
1248 }
1249
1250 phys_addr_t kvm_get_idmap_vector(void)
1251 {
1252         return hyp_idmap_vector;
1253 }
1254
1255 int kvm_mmu_init(void)
1256 {
1257         int err;
1258
1259         hyp_idmap_start = kvm_virt_to_phys(__hyp_idmap_text_start);
1260         hyp_idmap_end = kvm_virt_to_phys(__hyp_idmap_text_end);
1261         hyp_idmap_vector = kvm_virt_to_phys(__kvm_hyp_init);
1262
1263         if ((hyp_idmap_start ^ hyp_idmap_end) & PAGE_MASK) {
1264                 /*
1265                  * Our init code is crossing a page boundary. Allocate
1266                  * a bounce page, copy the code over and use that.
1267                  */
1268                 size_t len = __hyp_idmap_text_end - __hyp_idmap_text_start;
1269                 phys_addr_t phys_base;
1270
1271                 init_bounce_page = (void *)__get_free_page(GFP_KERNEL);
1272                 if (!init_bounce_page) {
1273                         kvm_err("Couldn't allocate HYP init bounce page\n");
1274                         err = -ENOMEM;
1275                         goto out;
1276                 }
1277
1278                 memcpy(init_bounce_page, __hyp_idmap_text_start, len);
1279                 /*
1280                  * Warning: the code we just copied to the bounce page
1281                  * must be flushed to the point of coherency.
1282                  * Otherwise, the data may be sitting in L2, and HYP
1283                  * mode won't be able to observe it as it runs with
1284                  * caches off at that point.
1285                  */
1286                 kvm_flush_dcache_to_poc(init_bounce_page, len);
1287
1288                 phys_base = kvm_virt_to_phys(init_bounce_page);
1289                 hyp_idmap_vector += phys_base - hyp_idmap_start;
1290                 hyp_idmap_start = phys_base;
1291                 hyp_idmap_end = phys_base + len;
1292
1293                 kvm_info("Using HYP init bounce page @%lx\n",
1294                          (unsigned long)phys_base);
1295         }
1296
1297         hyp_pgd = (pgd_t *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, hyp_pgd_order);
1298         boot_hyp_pgd = (pgd_t *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, hyp_pgd_order);
1299
1300         if (!hyp_pgd || !boot_hyp_pgd) {
1301                 kvm_err("Hyp mode PGD not allocated\n");
1302                 err = -ENOMEM;
1303                 goto out;
1304         }
1305
1306         /* Create the idmap in the boot page tables */
1307         err =   __create_hyp_mappings(boot_hyp_pgd,
1308                                       hyp_idmap_start, hyp_idmap_end,
1309                                       __phys_to_pfn(hyp_idmap_start),
1310                                       PAGE_HYP);
1311
1312         if (err) {
1313                 kvm_err("Failed to idmap %lx-%lx\n",
1314                         hyp_idmap_start, hyp_idmap_end);
1315                 goto out;
1316         }
1317
1318         /* Map the very same page at the trampoline VA */
1319         err =   __create_hyp_mappings(boot_hyp_pgd,
1320                                       TRAMPOLINE_VA, TRAMPOLINE_VA + PAGE_SIZE,
1321                                       __phys_to_pfn(hyp_idmap_start),
1322                                       PAGE_HYP);
1323         if (err) {
1324                 kvm_err("Failed to map trampoline @%lx into boot HYP pgd\n",
1325                         TRAMPOLINE_VA);
1326                 goto out;
1327         }
1328
1329         /* Map the same page again into the runtime page tables */
1330         err =   __create_hyp_mappings(hyp_pgd,
1331                                       TRAMPOLINE_VA, TRAMPOLINE_VA + PAGE_SIZE,
1332                                       __phys_to_pfn(hyp_idmap_start),
1333                                       PAGE_HYP);
1334         if (err) {
1335                 kvm_err("Failed to map trampoline @%lx into runtime HYP pgd\n",
1336                         TRAMPOLINE_VA);
1337                 goto out;
1338         }
1339
1340         return 0;
1341 out:
1342         free_hyp_pgds();
1343         return err;
1344 }
1345
1346 void kvm_arch_commit_memory_region(struct kvm *kvm,
1347                                    struct kvm_userspace_memory_region *mem,
1348                                    const struct kvm_memory_slot *old,
1349                                    enum kvm_mr_change change)
1350 {
1351 }
1352
1353 int kvm_arch_prepare_memory_region(struct kvm *kvm,
1354                                    struct kvm_memory_slot *memslot,
1355                                    struct kvm_userspace_memory_region *mem,
1356                                    enum kvm_mr_change change)
1357 {
1358         hva_t hva = mem->userspace_addr;
1359         hva_t reg_end = hva + mem->memory_size;
1360         bool writable = !(mem->flags & KVM_MEM_READONLY);
1361         int ret = 0;
1362
1363         if (change != KVM_MR_CREATE && change != KVM_MR_MOVE)
1364                 return 0;
1365
1366         /*
1367          * Prevent userspace from creating a memory region outside of the IPA
1368          * space addressable by the KVM guest IPA space.
1369          */
1370         if (memslot->base_gfn + memslot->npages >=
1371             (KVM_PHYS_SIZE >> PAGE_SHIFT))
1372                 return -EFAULT;
1373
1374         /*
1375          * A memory region could potentially cover multiple VMAs, and any holes
1376          * between them, so iterate over all of them to find out if we can map
1377          * any of them right now.
1378          *
1379          *     +--------------------------------------------+
1380          * +---------------+----------------+   +----------------+
1381          * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
1382          * +---------------+----------------+   +----------------+
1383          *     |               memory region                |
1384          *     +--------------------------------------------+
1385          */
1386         do {
1387                 struct vm_area_struct *vma = find_vma(current->mm, hva);
1388                 hva_t vm_start, vm_end;
1389
1390                 if (!vma || vma->vm_start >= reg_end)
1391                         break;
1392
1393                 /*
1394                  * Mapping a read-only VMA is only allowed if the
1395                  * memory region is configured as read-only.
1396                  */
1397                 if (writable && !(vma->vm_flags & VM_WRITE)) {
1398                         ret = -EPERM;
1399                         break;
1400                 }
1401
1402                 /*
1403                  * Take the intersection of this VMA with the memory region
1404                  */
1405                 vm_start = max(hva, vma->vm_start);
1406                 vm_end = min(reg_end, vma->vm_end);
1407
1408                 if (vma->vm_flags & VM_PFNMAP) {
1409                         gpa_t gpa = mem->guest_phys_addr +
1410                                     (vm_start - mem->userspace_addr);
1411                         phys_addr_t pa = (vma->vm_pgoff << PAGE_SHIFT) +
1412                                          vm_start - vma->vm_start;
1413
1414                         ret = kvm_phys_addr_ioremap(kvm, gpa, pa,
1415                                                     vm_end - vm_start,
1416                                                     writable);
1417                         if (ret)
1418                                 break;
1419                 }
1420                 hva = vm_end;
1421         } while (hva < reg_end);
1422
1423         spin_lock(&kvm->mmu_lock);
1424         if (ret)
1425                 unmap_stage2_range(kvm, mem->guest_phys_addr, mem->memory_size);
1426         else
1427                 stage2_flush_memslot(kvm, memslot);
1428         spin_unlock(&kvm->mmu_lock);
1429         return ret;
1430 }
1431
1432 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
1433                            struct kvm_memory_slot *dont)
1434 {
1435 }
1436
1437 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
1438                             unsigned long npages)
1439 {
1440         /*
1441          * Readonly memslots are not incoherent with the caches by definition,
1442          * but in practice, they are used mostly to emulate ROMs or NOR flashes
1443          * that the guest may consider devices and hence map as uncached.
1444          * To prevent incoherency issues in these cases, tag all readonly
1445          * regions as incoherent.
1446          */
1447         if (slot->flags & KVM_MEM_READONLY)
1448                 slot->flags |= KVM_MEMSLOT_INCOHERENT;
1449         return 0;
1450 }
1451
1452 void kvm_arch_memslots_updated(struct kvm *kvm)
1453 {
1454 }
1455
1456 void kvm_arch_flush_shadow_all(struct kvm *kvm)
1457 {
1458 }
1459
1460 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
1461                                    struct kvm_memory_slot *slot)
1462 {
1463         gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
1464         phys_addr_t size = slot->npages << PAGE_SHIFT;
1465
1466         spin_lock(&kvm->mmu_lock);
1467         unmap_stage2_range(kvm, gpa, size);
1468         spin_unlock(&kvm->mmu_lock);
1469 }
1470
1471 /*
1472  * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
1473  *
1474  * Main problems:
1475  * - S/W ops are local to a CPU (not broadcast)
1476  * - We have line migration behind our back (speculation)
1477  * - System caches don't support S/W at all (damn!)
1478  *
1479  * In the face of the above, the best we can do is to try and convert
1480  * S/W ops to VA ops. Because the guest is not allowed to infer the
1481  * S/W to PA mapping, it can only use S/W to nuke the whole cache,
1482  * which is a rather good thing for us.
1483  *
1484  * Also, it is only used when turning caches on/off ("The expected
1485  * usage of the cache maintenance instructions that operate by set/way
1486  * is associated with the cache maintenance instructions associated
1487  * with the powerdown and powerup of caches, if this is required by
1488  * the implementation.").
1489  *
1490  * We use the following policy:
1491  *
1492  * - If we trap a S/W operation, we enable VM trapping to detect
1493  *   caches being turned on/off, and do a full clean.
1494  *
1495  * - We flush the caches on both caches being turned on and off.
1496  *
1497  * - Once the caches are enabled, we stop trapping VM ops.
1498  */
1499 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
1500 {
1501         unsigned long hcr = vcpu_get_hcr(vcpu);
1502
1503         /*
1504          * If this is the first time we do a S/W operation
1505          * (i.e. HCR_TVM not set) flush the whole memory, and set the
1506          * VM trapping.
1507          *
1508          * Otherwise, rely on the VM trapping to wait for the MMU +
1509          * Caches to be turned off. At that point, we'll be able to
1510          * clean the caches again.
1511          */
1512         if (!(hcr & HCR_TVM)) {
1513                 trace_kvm_set_way_flush(*vcpu_pc(vcpu),
1514                                         vcpu_has_cache_enabled(vcpu));
1515                 stage2_flush_vm(vcpu->kvm);
1516                 vcpu_set_hcr(vcpu, hcr | HCR_TVM);
1517         }
1518 }
1519
1520 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
1521 {
1522         bool now_enabled = vcpu_has_cache_enabled(vcpu);
1523
1524         /*
1525          * If switching the MMU+caches on, need to invalidate the caches.
1526          * If switching it off, need to clean the caches.
1527          * Clean + invalidate does the trick always.
1528          */
1529         if (now_enabled != was_enabled)
1530                 stage2_flush_vm(vcpu->kvm);
1531
1532         /* Caches are now on, stop trapping VM ops (until a S/W op) */
1533         if (now_enabled)
1534                 vcpu_set_hcr(vcpu, vcpu_get_hcr(vcpu) & ~HCR_TVM);
1535
1536         trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
1537 }