arm64: kvm: allows kvm cpu hotplug
[firefly-linux-kernel-4.4.55.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 #include <asm/virt.h>
32
33 #include "trace.h"
34
35 extern char  __hyp_idmap_text_start[], __hyp_idmap_text_end[];
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 #define hyp_pgd_order get_order(PTRS_PER_PGD * sizeof(pgd_t))
47
48 #define kvm_pmd_huge(_x)        (pmd_huge(_x) || pmd_trans_huge(_x))
49 #define kvm_pud_huge(_x)        pud_huge(_x)
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         /*
73          * This function also gets called when dealing with HYP page
74          * tables. As HYP doesn't have an associated struct kvm (and
75          * the HYP page tables are fairly static), we don't do
76          * anything there.
77          */
78         if (kvm)
79                 kvm_call_hyp(__kvm_tlb_flush_vmid_ipa, kvm, ipa);
80 }
81
82 /*
83  * D-Cache management functions. They take the page table entries by
84  * value, as they are flushing the cache using the kernel mapping (or
85  * kmap on 32bit).
86  */
87 static void kvm_flush_dcache_pte(pte_t pte)
88 {
89         __kvm_flush_dcache_pte(pte);
90 }
91
92 static void kvm_flush_dcache_pmd(pmd_t pmd)
93 {
94         __kvm_flush_dcache_pmd(pmd);
95 }
96
97 static void kvm_flush_dcache_pud(pud_t pud)
98 {
99         __kvm_flush_dcache_pud(pud);
100 }
101
102 static bool kvm_is_device_pfn(unsigned long pfn)
103 {
104         return !pfn_valid(pfn);
105 }
106
107 /**
108  * stage2_dissolve_pmd() - clear and flush huge PMD entry
109  * @kvm:        pointer to kvm structure.
110  * @addr:       IPA
111  * @pmd:        pmd pointer for IPA
112  *
113  * Function clears a PMD entry, flushes addr 1st and 2nd stage TLBs. Marks all
114  * pages in the range dirty.
115  */
116 static void stage2_dissolve_pmd(struct kvm *kvm, phys_addr_t addr, pmd_t *pmd)
117 {
118         if (!kvm_pmd_huge(*pmd))
119                 return;
120
121         pmd_clear(pmd);
122         kvm_tlb_flush_vmid_ipa(kvm, addr);
123         put_page(virt_to_page(pmd));
124 }
125
126 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
127                                   int min, int max)
128 {
129         void *page;
130
131         BUG_ON(max > KVM_NR_MEM_OBJS);
132         if (cache->nobjs >= min)
133                 return 0;
134         while (cache->nobjs < max) {
135                 page = (void *)__get_free_page(PGALLOC_GFP);
136                 if (!page)
137                         return -ENOMEM;
138                 cache->objects[cache->nobjs++] = page;
139         }
140         return 0;
141 }
142
143 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
144 {
145         while (mc->nobjs)
146                 free_page((unsigned long)mc->objects[--mc->nobjs]);
147 }
148
149 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
150 {
151         void *p;
152
153         BUG_ON(!mc || !mc->nobjs);
154         p = mc->objects[--mc->nobjs];
155         return p;
156 }
157
158 static void clear_pgd_entry(struct kvm *kvm, pgd_t *pgd, phys_addr_t addr)
159 {
160         pud_t *pud_table __maybe_unused = pud_offset(pgd, 0);
161         pgd_clear(pgd);
162         kvm_tlb_flush_vmid_ipa(kvm, addr);
163         pud_free(NULL, pud_table);
164         put_page(virt_to_page(pgd));
165 }
166
167 static void clear_pud_entry(struct kvm *kvm, pud_t *pud, phys_addr_t addr)
168 {
169         pmd_t *pmd_table = pmd_offset(pud, 0);
170         VM_BUG_ON(pud_huge(*pud));
171         pud_clear(pud);
172         kvm_tlb_flush_vmid_ipa(kvm, addr);
173         pmd_free(NULL, pmd_table);
174         put_page(virt_to_page(pud));
175 }
176
177 static void clear_pmd_entry(struct kvm *kvm, pmd_t *pmd, phys_addr_t addr)
178 {
179         pte_t *pte_table = pte_offset_kernel(pmd, 0);
180         VM_BUG_ON(kvm_pmd_huge(*pmd));
181         pmd_clear(pmd);
182         kvm_tlb_flush_vmid_ipa(kvm, addr);
183         pte_free_kernel(NULL, pte_table);
184         put_page(virt_to_page(pmd));
185 }
186
187 /*
188  * Unmapping vs dcache management:
189  *
190  * If a guest maps certain memory pages as uncached, all writes will
191  * bypass the data cache and go directly to RAM.  However, the CPUs
192  * can still speculate reads (not writes) and fill cache lines with
193  * data.
194  *
195  * Those cache lines will be *clean* cache lines though, so a
196  * clean+invalidate operation is equivalent to an invalidate
197  * operation, because no cache lines are marked dirty.
198  *
199  * Those clean cache lines could be filled prior to an uncached write
200  * by the guest, and the cache coherent IO subsystem would therefore
201  * end up writing old data to disk.
202  *
203  * This is why right after unmapping a page/section and invalidating
204  * the corresponding TLBs, we call kvm_flush_dcache_p*() to make sure
205  * the IO subsystem will never hit in the cache.
206  */
207 static void unmap_ptes(struct kvm *kvm, pmd_t *pmd,
208                        phys_addr_t addr, phys_addr_t end)
209 {
210         phys_addr_t start_addr = addr;
211         pte_t *pte, *start_pte;
212
213         start_pte = pte = pte_offset_kernel(pmd, addr);
214         do {
215                 if (!pte_none(*pte)) {
216                         pte_t old_pte = *pte;
217
218                         kvm_set_pte(pte, __pte(0));
219                         kvm_tlb_flush_vmid_ipa(kvm, addr);
220
221                         /* No need to invalidate the cache for device mappings */
222                         if (!kvm_is_device_pfn(pte_pfn(old_pte)))
223                                 kvm_flush_dcache_pte(old_pte);
224
225                         put_page(virt_to_page(pte));
226                 }
227         } while (pte++, addr += PAGE_SIZE, addr != end);
228
229         if (kvm_pte_table_empty(kvm, start_pte))
230                 clear_pmd_entry(kvm, pmd, start_addr);
231 }
232
233 static void unmap_pmds(struct kvm *kvm, pud_t *pud,
234                        phys_addr_t addr, phys_addr_t end)
235 {
236         phys_addr_t next, start_addr = addr;
237         pmd_t *pmd, *start_pmd;
238
239         start_pmd = pmd = pmd_offset(pud, addr);
240         do {
241                 next = kvm_pmd_addr_end(addr, end);
242                 if (!pmd_none(*pmd)) {
243                         if (kvm_pmd_huge(*pmd)) {
244                                 pmd_t old_pmd = *pmd;
245
246                                 pmd_clear(pmd);
247                                 kvm_tlb_flush_vmid_ipa(kvm, addr);
248
249                                 kvm_flush_dcache_pmd(old_pmd);
250
251                                 put_page(virt_to_page(pmd));
252                         } else {
253                                 unmap_ptes(kvm, pmd, addr, next);
254                         }
255                 }
256         } while (pmd++, addr = next, addr != end);
257
258         if (kvm_pmd_table_empty(kvm, start_pmd))
259                 clear_pud_entry(kvm, pud, start_addr);
260 }
261
262 static void unmap_puds(struct kvm *kvm, pgd_t *pgd,
263                        phys_addr_t addr, phys_addr_t end)
264 {
265         phys_addr_t next, start_addr = addr;
266         pud_t *pud, *start_pud;
267
268         start_pud = pud = pud_offset(pgd, addr);
269         do {
270                 next = kvm_pud_addr_end(addr, end);
271                 if (!pud_none(*pud)) {
272                         if (pud_huge(*pud)) {
273                                 pud_t old_pud = *pud;
274
275                                 pud_clear(pud);
276                                 kvm_tlb_flush_vmid_ipa(kvm, addr);
277
278                                 kvm_flush_dcache_pud(old_pud);
279
280                                 put_page(virt_to_page(pud));
281                         } else {
282                                 unmap_pmds(kvm, pud, addr, next);
283                         }
284                 }
285         } while (pud++, addr = next, addr != end);
286
287         if (kvm_pud_table_empty(kvm, start_pud))
288                 clear_pgd_entry(kvm, pgd, start_addr);
289 }
290
291
292 static void unmap_range(struct kvm *kvm, pgd_t *pgdp,
293                         phys_addr_t start, u64 size)
294 {
295         pgd_t *pgd;
296         phys_addr_t addr = start, end = start + size;
297         phys_addr_t next;
298
299         pgd = pgdp + kvm_pgd_index(addr);
300         do {
301                 next = kvm_pgd_addr_end(addr, end);
302                 if (!pgd_none(*pgd))
303                         unmap_puds(kvm, pgd, addr, next);
304         } while (pgd++, addr = next, addr != end);
305 }
306
307 static void stage2_flush_ptes(struct kvm *kvm, pmd_t *pmd,
308                               phys_addr_t addr, phys_addr_t end)
309 {
310         pte_t *pte;
311
312         pte = pte_offset_kernel(pmd, addr);
313         do {
314                 if (!pte_none(*pte) && !kvm_is_device_pfn(pte_pfn(*pte)))
315                         kvm_flush_dcache_pte(*pte);
316         } while (pte++, addr += PAGE_SIZE, addr != end);
317 }
318
319 static void stage2_flush_pmds(struct kvm *kvm, pud_t *pud,
320                               phys_addr_t addr, phys_addr_t end)
321 {
322         pmd_t *pmd;
323         phys_addr_t next;
324
325         pmd = pmd_offset(pud, addr);
326         do {
327                 next = kvm_pmd_addr_end(addr, end);
328                 if (!pmd_none(*pmd)) {
329                         if (kvm_pmd_huge(*pmd))
330                                 kvm_flush_dcache_pmd(*pmd);
331                         else
332                                 stage2_flush_ptes(kvm, pmd, addr, next);
333                 }
334         } while (pmd++, addr = next, addr != end);
335 }
336
337 static void stage2_flush_puds(struct kvm *kvm, pgd_t *pgd,
338                               phys_addr_t addr, phys_addr_t end)
339 {
340         pud_t *pud;
341         phys_addr_t next;
342
343         pud = pud_offset(pgd, addr);
344         do {
345                 next = kvm_pud_addr_end(addr, end);
346                 if (!pud_none(*pud)) {
347                         if (pud_huge(*pud))
348                                 kvm_flush_dcache_pud(*pud);
349                         else
350                                 stage2_flush_pmds(kvm, pud, addr, next);
351                 }
352         } while (pud++, addr = next, addr != end);
353 }
354
355 static void stage2_flush_memslot(struct kvm *kvm,
356                                  struct kvm_memory_slot *memslot)
357 {
358         phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
359         phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
360         phys_addr_t next;
361         pgd_t *pgd;
362
363         pgd = kvm->arch.pgd + kvm_pgd_index(addr);
364         do {
365                 next = kvm_pgd_addr_end(addr, end);
366                 stage2_flush_puds(kvm, pgd, addr, next);
367         } while (pgd++, addr = next, addr != end);
368 }
369
370 /**
371  * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
372  * @kvm: The struct kvm pointer
373  *
374  * Go through the stage 2 page tables and invalidate any cache lines
375  * backing memory already mapped to the VM.
376  */
377 static void stage2_flush_vm(struct kvm *kvm)
378 {
379         struct kvm_memslots *slots;
380         struct kvm_memory_slot *memslot;
381         int idx;
382
383         idx = srcu_read_lock(&kvm->srcu);
384         spin_lock(&kvm->mmu_lock);
385
386         slots = kvm_memslots(kvm);
387         kvm_for_each_memslot(memslot, slots)
388                 stage2_flush_memslot(kvm, memslot);
389
390         spin_unlock(&kvm->mmu_lock);
391         srcu_read_unlock(&kvm->srcu, idx);
392 }
393
394 /**
395  * free_boot_hyp_pgd - free HYP boot page tables
396  *
397  * Free the HYP boot page tables. The bounce page is also freed.
398  */
399 void free_boot_hyp_pgd(void)
400 {
401         mutex_lock(&kvm_hyp_pgd_mutex);
402
403         if (boot_hyp_pgd) {
404                 unmap_range(NULL, boot_hyp_pgd, hyp_idmap_start, PAGE_SIZE);
405                 unmap_range(NULL, boot_hyp_pgd, TRAMPOLINE_VA, PAGE_SIZE);
406                 free_pages((unsigned long)boot_hyp_pgd, hyp_pgd_order);
407                 boot_hyp_pgd = NULL;
408         }
409
410         if (hyp_pgd)
411                 unmap_range(NULL, hyp_pgd, TRAMPOLINE_VA, PAGE_SIZE);
412
413         mutex_unlock(&kvm_hyp_pgd_mutex);
414 }
415
416 /**
417  * free_hyp_pgds - free Hyp-mode page tables
418  *
419  * Assumes hyp_pgd is a page table used strictly in Hyp-mode and
420  * therefore contains either mappings in the kernel memory area (above
421  * PAGE_OFFSET), or device mappings in the vmalloc range (from
422  * VMALLOC_START to VMALLOC_END).
423  *
424  * boot_hyp_pgd should only map two pages for the init code.
425  */
426 void free_hyp_pgds(void)
427 {
428         unsigned long addr;
429
430         free_boot_hyp_pgd();
431
432         mutex_lock(&kvm_hyp_pgd_mutex);
433
434         if (hyp_pgd) {
435                 for (addr = PAGE_OFFSET; virt_addr_valid(addr); addr += PGDIR_SIZE)
436                         unmap_range(NULL, hyp_pgd, KERN_TO_HYP(addr), PGDIR_SIZE);
437                 for (addr = VMALLOC_START; is_vmalloc_addr((void*)addr); addr += PGDIR_SIZE)
438                         unmap_range(NULL, hyp_pgd, KERN_TO_HYP(addr), PGDIR_SIZE);
439
440                 free_pages((unsigned long)hyp_pgd, hyp_pgd_order);
441                 hyp_pgd = NULL;
442         }
443         if (merged_hyp_pgd) {
444                 clear_page(merged_hyp_pgd);
445                 free_page((unsigned long)merged_hyp_pgd);
446                 merged_hyp_pgd = NULL;
447         }
448
449         mutex_unlock(&kvm_hyp_pgd_mutex);
450 }
451
452 static void create_hyp_pte_mappings(pmd_t *pmd, unsigned long start,
453                                     unsigned long end, unsigned long pfn,
454                                     pgprot_t prot)
455 {
456         pte_t *pte;
457         unsigned long addr;
458
459         addr = start;
460         do {
461                 pte = pte_offset_kernel(pmd, addr);
462                 kvm_set_pte(pte, pfn_pte(pfn, prot));
463                 get_page(virt_to_page(pte));
464                 kvm_flush_dcache_to_poc(pte, sizeof(*pte));
465                 pfn++;
466         } while (addr += PAGE_SIZE, addr != end);
467 }
468
469 static int create_hyp_pmd_mappings(pud_t *pud, unsigned long start,
470                                    unsigned long end, unsigned long pfn,
471                                    pgprot_t prot)
472 {
473         pmd_t *pmd;
474         pte_t *pte;
475         unsigned long addr, next;
476
477         addr = start;
478         do {
479                 pmd = pmd_offset(pud, addr);
480
481                 BUG_ON(pmd_sect(*pmd));
482
483                 if (pmd_none(*pmd)) {
484                         pte = pte_alloc_one_kernel(NULL, addr);
485                         if (!pte) {
486                                 kvm_err("Cannot allocate Hyp pte\n");
487                                 return -ENOMEM;
488                         }
489                         pmd_populate_kernel(NULL, pmd, pte);
490                         get_page(virt_to_page(pmd));
491                         kvm_flush_dcache_to_poc(pmd, sizeof(*pmd));
492                 }
493
494                 next = pmd_addr_end(addr, end);
495
496                 create_hyp_pte_mappings(pmd, addr, next, pfn, prot);
497                 pfn += (next - addr) >> PAGE_SHIFT;
498         } while (addr = next, addr != end);
499
500         return 0;
501 }
502
503 static int create_hyp_pud_mappings(pgd_t *pgd, unsigned long start,
504                                    unsigned long end, unsigned long pfn,
505                                    pgprot_t prot)
506 {
507         pud_t *pud;
508         pmd_t *pmd;
509         unsigned long addr, next;
510         int ret;
511
512         addr = start;
513         do {
514                 pud = pud_offset(pgd, addr);
515
516                 if (pud_none_or_clear_bad(pud)) {
517                         pmd = pmd_alloc_one(NULL, addr);
518                         if (!pmd) {
519                                 kvm_err("Cannot allocate Hyp pmd\n");
520                                 return -ENOMEM;
521                         }
522                         pud_populate(NULL, pud, pmd);
523                         get_page(virt_to_page(pud));
524                         kvm_flush_dcache_to_poc(pud, sizeof(*pud));
525                 }
526
527                 next = pud_addr_end(addr, end);
528                 ret = create_hyp_pmd_mappings(pud, addr, next, pfn, prot);
529                 if (ret)
530                         return ret;
531                 pfn += (next - addr) >> PAGE_SHIFT;
532         } while (addr = next, addr != end);
533
534         return 0;
535 }
536
537 static int __create_hyp_mappings(pgd_t *pgdp,
538                                  unsigned long start, unsigned long end,
539                                  unsigned long pfn, pgprot_t prot)
540 {
541         pgd_t *pgd;
542         pud_t *pud;
543         unsigned long addr, next;
544         int err = 0;
545
546         mutex_lock(&kvm_hyp_pgd_mutex);
547         addr = start & PAGE_MASK;
548         end = PAGE_ALIGN(end);
549         do {
550                 pgd = pgdp + pgd_index(addr);
551
552                 if (pgd_none(*pgd)) {
553                         pud = pud_alloc_one(NULL, addr);
554                         if (!pud) {
555                                 kvm_err("Cannot allocate Hyp pud\n");
556                                 err = -ENOMEM;
557                                 goto out;
558                         }
559                         pgd_populate(NULL, pgd, pud);
560                         get_page(virt_to_page(pgd));
561                         kvm_flush_dcache_to_poc(pgd, sizeof(*pgd));
562                 }
563
564                 next = pgd_addr_end(addr, end);
565                 err = create_hyp_pud_mappings(pgd, addr, next, pfn, prot);
566                 if (err)
567                         goto out;
568                 pfn += (next - addr) >> PAGE_SHIFT;
569         } while (addr = next, addr != end);
570 out:
571         mutex_unlock(&kvm_hyp_pgd_mutex);
572         return err;
573 }
574
575 static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
576 {
577         if (!is_vmalloc_addr(kaddr)) {
578                 BUG_ON(!virt_addr_valid(kaddr));
579                 return __pa(kaddr);
580         } else {
581                 return page_to_phys(vmalloc_to_page(kaddr)) +
582                        offset_in_page(kaddr);
583         }
584 }
585
586 /**
587  * create_hyp_mappings - duplicate a kernel virtual address range in Hyp mode
588  * @from:       The virtual kernel start address of the range
589  * @to:         The virtual kernel end address of the range (exclusive)
590  *
591  * The same virtual address as the kernel virtual address is also used
592  * in Hyp-mode mapping (modulo HYP_PAGE_OFFSET) to the same underlying
593  * physical pages.
594  */
595 int create_hyp_mappings(void *from, void *to)
596 {
597         phys_addr_t phys_addr;
598         unsigned long virt_addr;
599         unsigned long start = KERN_TO_HYP((unsigned long)from);
600         unsigned long end = KERN_TO_HYP((unsigned long)to);
601
602         if (is_kernel_in_hyp_mode())
603                 return 0;
604
605         start = start & PAGE_MASK;
606         end = PAGE_ALIGN(end);
607
608         for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
609                 int err;
610
611                 phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
612                 err = __create_hyp_mappings(hyp_pgd, virt_addr,
613                                             virt_addr + PAGE_SIZE,
614                                             __phys_to_pfn(phys_addr),
615                                             PAGE_HYP);
616                 if (err)
617                         return err;
618         }
619
620         return 0;
621 }
622
623 /**
624  * create_hyp_io_mappings - duplicate a kernel IO mapping into Hyp mode
625  * @from:       The kernel start VA of the range
626  * @to:         The kernel end VA of the range (exclusive)
627  * @phys_addr:  The physical start address which gets mapped
628  *
629  * The resulting HYP VA is the same as the kernel VA, modulo
630  * HYP_PAGE_OFFSET.
631  */
632 int create_hyp_io_mappings(void *from, void *to, phys_addr_t phys_addr)
633 {
634         unsigned long start = KERN_TO_HYP((unsigned long)from);
635         unsigned long end = KERN_TO_HYP((unsigned long)to);
636
637         if (is_kernel_in_hyp_mode())
638                 return 0;
639
640         /* Check for a valid kernel IO mapping */
641         if (!is_vmalloc_addr(from) || !is_vmalloc_addr(to - 1))
642                 return -EINVAL;
643
644         return __create_hyp_mappings(hyp_pgd, start, end,
645                                      __phys_to_pfn(phys_addr), PAGE_HYP_DEVICE);
646 }
647
648 /* Free the HW pgd, one page at a time */
649 static void kvm_free_hwpgd(void *hwpgd)
650 {
651         free_pages_exact(hwpgd, kvm_get_hwpgd_size());
652 }
653
654 /* Allocate the HW PGD, making sure that each page gets its own refcount */
655 static void *kvm_alloc_hwpgd(void)
656 {
657         unsigned int size = kvm_get_hwpgd_size();
658
659         return alloc_pages_exact(size, GFP_KERNEL | __GFP_ZERO);
660 }
661
662 /**
663  * kvm_alloc_stage2_pgd - allocate level-1 table for stage-2 translation.
664  * @kvm:        The KVM struct pointer for the VM.
665  *
666  * Allocates only the stage-2 HW PGD level table(s) (can support either full
667  * 40-bit input addresses or limited to 32-bit input addresses). Clears the
668  * allocated pages.
669  *
670  * Note we don't need locking here as this is only called when the VM is
671  * created, which can only be done once.
672  */
673 int kvm_alloc_stage2_pgd(struct kvm *kvm)
674 {
675         pgd_t *pgd;
676         void *hwpgd;
677
678         if (kvm->arch.pgd != NULL) {
679                 kvm_err("kvm_arch already initialized?\n");
680                 return -EINVAL;
681         }
682
683         hwpgd = kvm_alloc_hwpgd();
684         if (!hwpgd)
685                 return -ENOMEM;
686
687         /* When the kernel uses more levels of page tables than the
688          * guest, we allocate a fake PGD and pre-populate it to point
689          * to the next-level page table, which will be the real
690          * initial page table pointed to by the VTTBR.
691          *
692          * When KVM_PREALLOC_LEVEL==2, we allocate a single page for
693          * the PMD and the kernel will use folded pud.
694          * When KVM_PREALLOC_LEVEL==1, we allocate 2 consecutive PUD
695          * pages.
696          */
697         if (KVM_PREALLOC_LEVEL > 0) {
698                 int i;
699
700                 /*
701                  * Allocate fake pgd for the page table manipulation macros to
702                  * work.  This is not used by the hardware and we have no
703                  * alignment requirement for this allocation.
704                  */
705                 pgd = kmalloc(PTRS_PER_S2_PGD * sizeof(pgd_t),
706                                 GFP_KERNEL | __GFP_ZERO);
707
708                 if (!pgd) {
709                         kvm_free_hwpgd(hwpgd);
710                         return -ENOMEM;
711                 }
712
713                 /* Plug the HW PGD into the fake one. */
714                 for (i = 0; i < PTRS_PER_S2_PGD; i++) {
715                         if (KVM_PREALLOC_LEVEL == 1)
716                                 pgd_populate(NULL, pgd + i,
717                                              (pud_t *)hwpgd + i * PTRS_PER_PUD);
718                         else if (KVM_PREALLOC_LEVEL == 2)
719                                 pud_populate(NULL, pud_offset(pgd, 0) + i,
720                                              (pmd_t *)hwpgd + i * PTRS_PER_PMD);
721                 }
722         } else {
723                 /*
724                  * Allocate actual first-level Stage-2 page table used by the
725                  * hardware for Stage-2 page table walks.
726                  */
727                 pgd = (pgd_t *)hwpgd;
728         }
729
730         kvm_clean_pgd(pgd);
731         kvm->arch.pgd = pgd;
732         return 0;
733 }
734
735 /**
736  * unmap_stage2_range -- Clear stage2 page table entries to unmap a range
737  * @kvm:   The VM pointer
738  * @start: The intermediate physical base address of the range to unmap
739  * @size:  The size of the area to unmap
740  *
741  * Clear a range of stage-2 mappings, lowering the various ref-counts.  Must
742  * be called while holding mmu_lock (unless for freeing the stage2 pgd before
743  * destroying the VM), otherwise another faulting VCPU may come in and mess
744  * with things behind our backs.
745  */
746 static void unmap_stage2_range(struct kvm *kvm, phys_addr_t start, u64 size)
747 {
748         unmap_range(kvm, kvm->arch.pgd, start, size);
749 }
750
751 static void stage2_unmap_memslot(struct kvm *kvm,
752                                  struct kvm_memory_slot *memslot)
753 {
754         hva_t hva = memslot->userspace_addr;
755         phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
756         phys_addr_t size = PAGE_SIZE * memslot->npages;
757         hva_t reg_end = hva + size;
758
759         /*
760          * A memory region could potentially cover multiple VMAs, and any holes
761          * between them, so iterate over all of them to find out if we should
762          * unmap any of them.
763          *
764          *     +--------------------------------------------+
765          * +---------------+----------------+   +----------------+
766          * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
767          * +---------------+----------------+   +----------------+
768          *     |               memory region                |
769          *     +--------------------------------------------+
770          */
771         do {
772                 struct vm_area_struct *vma = find_vma(current->mm, hva);
773                 hva_t vm_start, vm_end;
774
775                 if (!vma || vma->vm_start >= reg_end)
776                         break;
777
778                 /*
779                  * Take the intersection of this VMA with the memory region
780                  */
781                 vm_start = max(hva, vma->vm_start);
782                 vm_end = min(reg_end, vma->vm_end);
783
784                 if (!(vma->vm_flags & VM_PFNMAP)) {
785                         gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
786                         unmap_stage2_range(kvm, gpa, vm_end - vm_start);
787                 }
788                 hva = vm_end;
789         } while (hva < reg_end);
790 }
791
792 /**
793  * stage2_unmap_vm - Unmap Stage-2 RAM mappings
794  * @kvm: The struct kvm pointer
795  *
796  * Go through the memregions and unmap any reguler RAM
797  * backing memory already mapped to the VM.
798  */
799 void stage2_unmap_vm(struct kvm *kvm)
800 {
801         struct kvm_memslots *slots;
802         struct kvm_memory_slot *memslot;
803         int idx;
804
805         idx = srcu_read_lock(&kvm->srcu);
806         spin_lock(&kvm->mmu_lock);
807
808         slots = kvm_memslots(kvm);
809         kvm_for_each_memslot(memslot, slots)
810                 stage2_unmap_memslot(kvm, memslot);
811
812         spin_unlock(&kvm->mmu_lock);
813         srcu_read_unlock(&kvm->srcu, idx);
814 }
815
816 /**
817  * kvm_free_stage2_pgd - free all stage-2 tables
818  * @kvm:        The KVM struct pointer for the VM.
819  *
820  * Walks the level-1 page table pointed to by kvm->arch.pgd and frees all
821  * underlying level-2 and level-3 tables before freeing the actual level-1 table
822  * and setting the struct pointer to NULL.
823  *
824  * Note we don't need locking here as this is only called when the VM is
825  * destroyed, which can only be done once.
826  */
827 void kvm_free_stage2_pgd(struct kvm *kvm)
828 {
829         if (kvm->arch.pgd == NULL)
830                 return;
831
832         unmap_stage2_range(kvm, 0, KVM_PHYS_SIZE);
833         kvm_free_hwpgd(kvm_get_hwpgd(kvm));
834         if (KVM_PREALLOC_LEVEL > 0)
835                 kfree(kvm->arch.pgd);
836
837         kvm->arch.pgd = NULL;
838 }
839
840 static pud_t *stage2_get_pud(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
841                              phys_addr_t addr)
842 {
843         pgd_t *pgd;
844         pud_t *pud;
845
846         pgd = kvm->arch.pgd + kvm_pgd_index(addr);
847         if (WARN_ON(pgd_none(*pgd))) {
848                 if (!cache)
849                         return NULL;
850                 pud = mmu_memory_cache_alloc(cache);
851                 pgd_populate(NULL, pgd, pud);
852                 get_page(virt_to_page(pgd));
853         }
854
855         return pud_offset(pgd, addr);
856 }
857
858 static pmd_t *stage2_get_pmd(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
859                              phys_addr_t addr)
860 {
861         pud_t *pud;
862         pmd_t *pmd;
863
864         pud = stage2_get_pud(kvm, cache, addr);
865         if (pud_none(*pud)) {
866                 if (!cache)
867                         return NULL;
868                 pmd = mmu_memory_cache_alloc(cache);
869                 pud_populate(NULL, pud, pmd);
870                 get_page(virt_to_page(pud));
871         }
872
873         return pmd_offset(pud, addr);
874 }
875
876 static int stage2_set_pmd_huge(struct kvm *kvm, struct kvm_mmu_memory_cache
877                                *cache, phys_addr_t addr, const pmd_t *new_pmd)
878 {
879         pmd_t *pmd, old_pmd;
880
881         pmd = stage2_get_pmd(kvm, cache, addr);
882         VM_BUG_ON(!pmd);
883
884         /*
885          * Mapping in huge pages should only happen through a fault.  If a
886          * page is merged into a transparent huge page, the individual
887          * subpages of that huge page should be unmapped through MMU
888          * notifiers before we get here.
889          *
890          * Merging of CompoundPages is not supported; they should become
891          * splitting first, unmapped, merged, and mapped back in on-demand.
892          */
893         VM_BUG_ON(pmd_present(*pmd) && pmd_pfn(*pmd) != pmd_pfn(*new_pmd));
894
895         old_pmd = *pmd;
896         if (pmd_present(old_pmd)) {
897                 pmd_clear(pmd);
898                 kvm_tlb_flush_vmid_ipa(kvm, addr);
899         } else {
900                 get_page(virt_to_page(pmd));
901         }
902
903         kvm_set_pmd(pmd, *new_pmd);
904         return 0;
905 }
906
907 static int stage2_set_pte(struct kvm *kvm, struct kvm_mmu_memory_cache *cache,
908                           phys_addr_t addr, const pte_t *new_pte,
909                           unsigned long flags)
910 {
911         pmd_t *pmd;
912         pte_t *pte, old_pte;
913         bool iomap = flags & KVM_S2PTE_FLAG_IS_IOMAP;
914         bool logging_active = flags & KVM_S2_FLAG_LOGGING_ACTIVE;
915
916         VM_BUG_ON(logging_active && !cache);
917
918         /* Create stage-2 page table mapping - Levels 0 and 1 */
919         pmd = stage2_get_pmd(kvm, cache, addr);
920         if (!pmd) {
921                 /*
922                  * Ignore calls from kvm_set_spte_hva for unallocated
923                  * address ranges.
924                  */
925                 return 0;
926         }
927
928         /*
929          * While dirty page logging - dissolve huge PMD, then continue on to
930          * allocate page.
931          */
932         if (logging_active)
933                 stage2_dissolve_pmd(kvm, addr, pmd);
934
935         /* Create stage-2 page mappings - Level 2 */
936         if (pmd_none(*pmd)) {
937                 if (!cache)
938                         return 0; /* ignore calls from kvm_set_spte_hva */
939                 pte = mmu_memory_cache_alloc(cache);
940                 kvm_clean_pte(pte);
941                 pmd_populate_kernel(NULL, pmd, pte);
942                 get_page(virt_to_page(pmd));
943         }
944
945         pte = pte_offset_kernel(pmd, addr);
946
947         if (iomap && pte_present(*pte))
948                 return -EFAULT;
949
950         /* Create 2nd stage page table mapping - Level 3 */
951         old_pte = *pte;
952         if (pte_present(old_pte)) {
953                 kvm_set_pte(pte, __pte(0));
954                 kvm_tlb_flush_vmid_ipa(kvm, addr);
955         } else {
956                 get_page(virt_to_page(pte));
957         }
958
959         kvm_set_pte(pte, *new_pte);
960         return 0;
961 }
962
963 /**
964  * kvm_phys_addr_ioremap - map a device range to guest IPA
965  *
966  * @kvm:        The KVM pointer
967  * @guest_ipa:  The IPA at which to insert the mapping
968  * @pa:         The physical address of the device
969  * @size:       The size of the mapping
970  */
971 int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
972                           phys_addr_t pa, unsigned long size, bool writable)
973 {
974         phys_addr_t addr, end;
975         int ret = 0;
976         unsigned long pfn;
977         struct kvm_mmu_memory_cache cache = { 0, };
978
979         end = (guest_ipa + size + PAGE_SIZE - 1) & PAGE_MASK;
980         pfn = __phys_to_pfn(pa);
981
982         for (addr = guest_ipa; addr < end; addr += PAGE_SIZE) {
983                 pte_t pte = pfn_pte(pfn, PAGE_S2_DEVICE);
984
985                 if (writable)
986                         kvm_set_s2pte_writable(&pte);
987
988                 ret = mmu_topup_memory_cache(&cache, KVM_MMU_CACHE_MIN_PAGES,
989                                                 KVM_NR_MEM_OBJS);
990                 if (ret)
991                         goto out;
992                 spin_lock(&kvm->mmu_lock);
993                 ret = stage2_set_pte(kvm, &cache, addr, &pte,
994                                                 KVM_S2PTE_FLAG_IS_IOMAP);
995                 spin_unlock(&kvm->mmu_lock);
996                 if (ret)
997                         goto out;
998
999                 pfn++;
1000         }
1001
1002 out:
1003         mmu_free_memory_cache(&cache);
1004         return ret;
1005 }
1006
1007 static bool transparent_hugepage_adjust(pfn_t *pfnp, phys_addr_t *ipap)
1008 {
1009         pfn_t pfn = *pfnp;
1010         gfn_t gfn = *ipap >> PAGE_SHIFT;
1011
1012         if (PageTransCompound(pfn_to_page(pfn))) {
1013                 unsigned long mask;
1014                 /*
1015                  * The address we faulted on is backed by a transparent huge
1016                  * page.  However, because we map the compound huge page and
1017                  * not the individual tail page, we need to transfer the
1018                  * refcount to the head page.  We have to be careful that the
1019                  * THP doesn't start to split while we are adjusting the
1020                  * refcounts.
1021                  *
1022                  * We are sure this doesn't happen, because mmu_notifier_retry
1023                  * was successful and we are holding the mmu_lock, so if this
1024                  * THP is trying to split, it will be blocked in the mmu
1025                  * notifier before touching any of the pages, specifically
1026                  * before being able to call __split_huge_page_refcount().
1027                  *
1028                  * We can therefore safely transfer the refcount from PG_tail
1029                  * to PG_head and switch the pfn from a tail page to the head
1030                  * page accordingly.
1031                  */
1032                 mask = PTRS_PER_PMD - 1;
1033                 VM_BUG_ON((gfn & mask) != (pfn & mask));
1034                 if (pfn & mask) {
1035                         *ipap &= PMD_MASK;
1036                         kvm_release_pfn_clean(pfn);
1037                         pfn &= ~mask;
1038                         kvm_get_pfn(pfn);
1039                         *pfnp = pfn;
1040                 }
1041
1042                 return true;
1043         }
1044
1045         return false;
1046 }
1047
1048 static bool kvm_is_write_fault(struct kvm_vcpu *vcpu)
1049 {
1050         if (kvm_vcpu_trap_is_iabt(vcpu))
1051                 return false;
1052
1053         return kvm_vcpu_dabt_iswrite(vcpu);
1054 }
1055
1056 /**
1057  * stage2_wp_ptes - write protect PMD range
1058  * @pmd:        pointer to pmd entry
1059  * @addr:       range start address
1060  * @end:        range end address
1061  */
1062 static void stage2_wp_ptes(pmd_t *pmd, phys_addr_t addr, phys_addr_t end)
1063 {
1064         pte_t *pte;
1065
1066         pte = pte_offset_kernel(pmd, addr);
1067         do {
1068                 if (!pte_none(*pte)) {
1069                         if (!kvm_s2pte_readonly(pte))
1070                                 kvm_set_s2pte_readonly(pte);
1071                 }
1072         } while (pte++, addr += PAGE_SIZE, addr != end);
1073 }
1074
1075 /**
1076  * stage2_wp_pmds - write protect PUD range
1077  * @pud:        pointer to pud entry
1078  * @addr:       range start address
1079  * @end:        range end address
1080  */
1081 static void stage2_wp_pmds(pud_t *pud, phys_addr_t addr, phys_addr_t end)
1082 {
1083         pmd_t *pmd;
1084         phys_addr_t next;
1085
1086         pmd = pmd_offset(pud, addr);
1087
1088         do {
1089                 next = kvm_pmd_addr_end(addr, end);
1090                 if (!pmd_none(*pmd)) {
1091                         if (kvm_pmd_huge(*pmd)) {
1092                                 if (!kvm_s2pmd_readonly(pmd))
1093                                         kvm_set_s2pmd_readonly(pmd);
1094                         } else {
1095                                 stage2_wp_ptes(pmd, addr, next);
1096                         }
1097                 }
1098         } while (pmd++, addr = next, addr != end);
1099 }
1100
1101 /**
1102   * stage2_wp_puds - write protect PGD range
1103   * @pgd:       pointer to pgd entry
1104   * @addr:      range start address
1105   * @end:       range end address
1106   *
1107   * Process PUD entries, for a huge PUD we cause a panic.
1108   */
1109 static void  stage2_wp_puds(pgd_t *pgd, phys_addr_t addr, phys_addr_t end)
1110 {
1111         pud_t *pud;
1112         phys_addr_t next;
1113
1114         pud = pud_offset(pgd, addr);
1115         do {
1116                 next = kvm_pud_addr_end(addr, end);
1117                 if (!pud_none(*pud)) {
1118                         /* TODO:PUD not supported, revisit later if supported */
1119                         BUG_ON(kvm_pud_huge(*pud));
1120                         stage2_wp_pmds(pud, addr, next);
1121                 }
1122         } while (pud++, addr = next, addr != end);
1123 }
1124
1125 /**
1126  * stage2_wp_range() - write protect stage2 memory region range
1127  * @kvm:        The KVM pointer
1128  * @addr:       Start address of range
1129  * @end:        End address of range
1130  */
1131 static void stage2_wp_range(struct kvm *kvm, phys_addr_t addr, phys_addr_t end)
1132 {
1133         pgd_t *pgd;
1134         phys_addr_t next;
1135
1136         pgd = kvm->arch.pgd + kvm_pgd_index(addr);
1137         do {
1138                 /*
1139                  * Release kvm_mmu_lock periodically if the memory region is
1140                  * large. Otherwise, we may see kernel panics with
1141                  * CONFIG_DETECT_HUNG_TASK, CONFIG_LOCKUP_DETECTOR,
1142                  * CONFIG_LOCKDEP. Additionally, holding the lock too long
1143                  * will also starve other vCPUs.
1144                  */
1145                 if (need_resched() || spin_needbreak(&kvm->mmu_lock))
1146                         cond_resched_lock(&kvm->mmu_lock);
1147
1148                 next = kvm_pgd_addr_end(addr, end);
1149                 if (pgd_present(*pgd))
1150                         stage2_wp_puds(pgd, addr, next);
1151         } while (pgd++, addr = next, addr != end);
1152 }
1153
1154 /**
1155  * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
1156  * @kvm:        The KVM pointer
1157  * @slot:       The memory slot to write protect
1158  *
1159  * Called to start logging dirty pages after memory region
1160  * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
1161  * all present PMD and PTEs are write protected in the memory region.
1162  * Afterwards read of dirty page log can be called.
1163  *
1164  * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
1165  * serializing operations for VM memory regions.
1166  */
1167 void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
1168 {
1169         struct kvm_memslots *slots = kvm_memslots(kvm);
1170         struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
1171         phys_addr_t start = memslot->base_gfn << PAGE_SHIFT;
1172         phys_addr_t end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
1173
1174         spin_lock(&kvm->mmu_lock);
1175         stage2_wp_range(kvm, start, end);
1176         spin_unlock(&kvm->mmu_lock);
1177         kvm_flush_remote_tlbs(kvm);
1178 }
1179
1180 /**
1181  * kvm_mmu_write_protect_pt_masked() - write protect dirty pages
1182  * @kvm:        The KVM pointer
1183  * @slot:       The memory slot associated with mask
1184  * @gfn_offset: The gfn offset in memory slot
1185  * @mask:       The mask of dirty pages at offset 'gfn_offset' in this memory
1186  *              slot to be write protected
1187  *
1188  * Walks bits set in mask write protects the associated pte's. Caller must
1189  * acquire kvm_mmu_lock.
1190  */
1191 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1192                 struct kvm_memory_slot *slot,
1193                 gfn_t gfn_offset, unsigned long mask)
1194 {
1195         phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
1196         phys_addr_t start = (base_gfn +  __ffs(mask)) << PAGE_SHIFT;
1197         phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
1198
1199         stage2_wp_range(kvm, start, end);
1200 }
1201
1202 /*
1203  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1204  * dirty pages.
1205  *
1206  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1207  * enable dirty logging for them.
1208  */
1209 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1210                 struct kvm_memory_slot *slot,
1211                 gfn_t gfn_offset, unsigned long mask)
1212 {
1213         kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1214 }
1215
1216 static void coherent_cache_guest_page(struct kvm_vcpu *vcpu, pfn_t pfn,
1217                                       unsigned long size, bool uncached)
1218 {
1219         __coherent_cache_guest_page(vcpu, pfn, size, uncached);
1220 }
1221
1222 static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
1223                           struct kvm_memory_slot *memslot, unsigned long hva,
1224                           unsigned long fault_status)
1225 {
1226         int ret;
1227         bool write_fault, writable, hugetlb = false, force_pte = false;
1228         unsigned long mmu_seq;
1229         gfn_t gfn = fault_ipa >> PAGE_SHIFT;
1230         struct kvm *kvm = vcpu->kvm;
1231         struct kvm_mmu_memory_cache *memcache = &vcpu->arch.mmu_page_cache;
1232         struct vm_area_struct *vma;
1233         pfn_t pfn;
1234         pgprot_t mem_type = PAGE_S2;
1235         bool fault_ipa_uncached;
1236         bool logging_active = memslot_is_logging(memslot);
1237         unsigned long flags = 0;
1238
1239         write_fault = kvm_is_write_fault(vcpu);
1240         if (fault_status == FSC_PERM && !write_fault) {
1241                 kvm_err("Unexpected L2 read permission error\n");
1242                 return -EFAULT;
1243         }
1244
1245         /* Let's check if we will get back a huge page backed by hugetlbfs */
1246         down_read(&current->mm->mmap_sem);
1247         vma = find_vma_intersection(current->mm, hva, hva + 1);
1248         if (unlikely(!vma)) {
1249                 kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
1250                 up_read(&current->mm->mmap_sem);
1251                 return -EFAULT;
1252         }
1253
1254         if (is_vm_hugetlb_page(vma) && !logging_active) {
1255                 hugetlb = true;
1256                 gfn = (fault_ipa & PMD_MASK) >> PAGE_SHIFT;
1257         } else {
1258                 /*
1259                  * Pages belonging to memslots that don't have the same
1260                  * alignment for userspace and IPA cannot be mapped using
1261                  * block descriptors even if the pages belong to a THP for
1262                  * the process, because the stage-2 block descriptor will
1263                  * cover more than a single THP and we loose atomicity for
1264                  * unmapping, updates, and splits of the THP or other pages
1265                  * in the stage-2 block range.
1266                  */
1267                 if ((memslot->userspace_addr & ~PMD_MASK) !=
1268                     ((memslot->base_gfn << PAGE_SHIFT) & ~PMD_MASK))
1269                         force_pte = true;
1270         }
1271         up_read(&current->mm->mmap_sem);
1272
1273         /* We need minimum second+third level pages */
1274         ret = mmu_topup_memory_cache(memcache, KVM_MMU_CACHE_MIN_PAGES,
1275                                      KVM_NR_MEM_OBJS);
1276         if (ret)
1277                 return ret;
1278
1279         mmu_seq = vcpu->kvm->mmu_notifier_seq;
1280         /*
1281          * Ensure the read of mmu_notifier_seq happens before we call
1282          * gfn_to_pfn_prot (which calls get_user_pages), so that we don't risk
1283          * the page we just got a reference to gets unmapped before we have a
1284          * chance to grab the mmu_lock, which ensure that if the page gets
1285          * unmapped afterwards, the call to kvm_unmap_hva will take it away
1286          * from us again properly. This smp_rmb() interacts with the smp_wmb()
1287          * in kvm_mmu_notifier_invalidate_<page|range_end>.
1288          */
1289         smp_rmb();
1290
1291         pfn = gfn_to_pfn_prot(kvm, gfn, write_fault, &writable);
1292         if (is_error_pfn(pfn))
1293                 return -EFAULT;
1294
1295         if (kvm_is_device_pfn(pfn)) {
1296                 mem_type = PAGE_S2_DEVICE;
1297                 flags |= KVM_S2PTE_FLAG_IS_IOMAP;
1298         } else if (logging_active) {
1299                 /*
1300                  * Faults on pages in a memslot with logging enabled
1301                  * should not be mapped with huge pages (it introduces churn
1302                  * and performance degradation), so force a pte mapping.
1303                  */
1304                 force_pte = true;
1305                 flags |= KVM_S2_FLAG_LOGGING_ACTIVE;
1306
1307                 /*
1308                  * Only actually map the page as writable if this was a write
1309                  * fault.
1310                  */
1311                 if (!write_fault)
1312                         writable = false;
1313         }
1314
1315         spin_lock(&kvm->mmu_lock);
1316         if (mmu_notifier_retry(kvm, mmu_seq))
1317                 goto out_unlock;
1318
1319         if (!hugetlb && !force_pte)
1320                 hugetlb = transparent_hugepage_adjust(&pfn, &fault_ipa);
1321
1322         fault_ipa_uncached = memslot->flags & KVM_MEMSLOT_INCOHERENT;
1323
1324         if (hugetlb) {
1325                 pmd_t new_pmd = pfn_pmd(pfn, mem_type);
1326                 new_pmd = pmd_mkhuge(new_pmd);
1327                 if (writable) {
1328                         kvm_set_s2pmd_writable(&new_pmd);
1329                         kvm_set_pfn_dirty(pfn);
1330                 }
1331                 coherent_cache_guest_page(vcpu, pfn, PMD_SIZE, fault_ipa_uncached);
1332                 ret = stage2_set_pmd_huge(kvm, memcache, fault_ipa, &new_pmd);
1333         } else {
1334                 pte_t new_pte = pfn_pte(pfn, mem_type);
1335
1336                 if (writable) {
1337                         kvm_set_s2pte_writable(&new_pte);
1338                         kvm_set_pfn_dirty(pfn);
1339                         mark_page_dirty(kvm, gfn);
1340                 }
1341                 coherent_cache_guest_page(vcpu, pfn, PAGE_SIZE, fault_ipa_uncached);
1342                 ret = stage2_set_pte(kvm, memcache, fault_ipa, &new_pte, flags);
1343         }
1344
1345 out_unlock:
1346         spin_unlock(&kvm->mmu_lock);
1347         kvm_set_pfn_accessed(pfn);
1348         kvm_release_pfn_clean(pfn);
1349         return ret;
1350 }
1351
1352 /*
1353  * Resolve the access fault by making the page young again.
1354  * Note that because the faulting entry is guaranteed not to be
1355  * cached in the TLB, we don't need to invalidate anything.
1356  */
1357 static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
1358 {
1359         pmd_t *pmd;
1360         pte_t *pte;
1361         pfn_t pfn;
1362         bool pfn_valid = false;
1363
1364         trace_kvm_access_fault(fault_ipa);
1365
1366         spin_lock(&vcpu->kvm->mmu_lock);
1367
1368         pmd = stage2_get_pmd(vcpu->kvm, NULL, fault_ipa);
1369         if (!pmd || pmd_none(*pmd))     /* Nothing there */
1370                 goto out;
1371
1372         if (kvm_pmd_huge(*pmd)) {       /* THP, HugeTLB */
1373                 *pmd = pmd_mkyoung(*pmd);
1374                 pfn = pmd_pfn(*pmd);
1375                 pfn_valid = true;
1376                 goto out;
1377         }
1378
1379         pte = pte_offset_kernel(pmd, fault_ipa);
1380         if (pte_none(*pte))             /* Nothing there either */
1381                 goto out;
1382
1383         *pte = pte_mkyoung(*pte);       /* Just a page... */
1384         pfn = pte_pfn(*pte);
1385         pfn_valid = true;
1386 out:
1387         spin_unlock(&vcpu->kvm->mmu_lock);
1388         if (pfn_valid)
1389                 kvm_set_pfn_accessed(pfn);
1390 }
1391
1392 /**
1393  * kvm_handle_guest_abort - handles all 2nd stage aborts
1394  * @vcpu:       the VCPU pointer
1395  * @run:        the kvm_run structure
1396  *
1397  * Any abort that gets to the host is almost guaranteed to be caused by a
1398  * missing second stage translation table entry, which can mean that either the
1399  * guest simply needs more memory and we must allocate an appropriate page or it
1400  * can mean that the guest tried to access I/O memory, which is emulated by user
1401  * space. The distinction is based on the IPA causing the fault and whether this
1402  * memory region has been registered as standard RAM by user space.
1403  */
1404 int kvm_handle_guest_abort(struct kvm_vcpu *vcpu, struct kvm_run *run)
1405 {
1406         unsigned long fault_status;
1407         phys_addr_t fault_ipa;
1408         struct kvm_memory_slot *memslot;
1409         unsigned long hva;
1410         bool is_iabt, write_fault, writable;
1411         gfn_t gfn;
1412         int ret, idx;
1413
1414         is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
1415         fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
1416
1417         trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_hsr(vcpu),
1418                               kvm_vcpu_get_hfar(vcpu), fault_ipa);
1419
1420         /* Check the stage-2 fault is trans. fault or write fault */
1421         fault_status = kvm_vcpu_trap_get_fault_type(vcpu);
1422         if (fault_status != FSC_FAULT && fault_status != FSC_PERM &&
1423             fault_status != FSC_ACCESS) {
1424                 kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
1425                         kvm_vcpu_trap_get_class(vcpu),
1426                         (unsigned long)kvm_vcpu_trap_get_fault(vcpu),
1427                         (unsigned long)kvm_vcpu_get_hsr(vcpu));
1428                 return -EFAULT;
1429         }
1430
1431         idx = srcu_read_lock(&vcpu->kvm->srcu);
1432
1433         gfn = fault_ipa >> PAGE_SHIFT;
1434         memslot = gfn_to_memslot(vcpu->kvm, gfn);
1435         hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
1436         write_fault = kvm_is_write_fault(vcpu);
1437         if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
1438                 if (is_iabt) {
1439                         /* Prefetch Abort on I/O address */
1440                         kvm_inject_pabt(vcpu, kvm_vcpu_get_hfar(vcpu));
1441                         ret = 1;
1442                         goto out_unlock;
1443                 }
1444
1445                 /*
1446                  * The IPA is reported as [MAX:12], so we need to
1447                  * complement it with the bottom 12 bits from the
1448                  * faulting VA. This is always 12 bits, irrespective
1449                  * of the page size.
1450                  */
1451                 fault_ipa |= kvm_vcpu_get_hfar(vcpu) & ((1 << 12) - 1);
1452                 ret = io_mem_abort(vcpu, run, fault_ipa);
1453                 goto out_unlock;
1454         }
1455
1456         /* Userspace should not be able to register out-of-bounds IPAs */
1457         VM_BUG_ON(fault_ipa >= KVM_PHYS_SIZE);
1458
1459         if (fault_status == FSC_ACCESS) {
1460                 handle_access_fault(vcpu, fault_ipa);
1461                 ret = 1;
1462                 goto out_unlock;
1463         }
1464
1465         ret = user_mem_abort(vcpu, fault_ipa, memslot, hva, fault_status);
1466         if (ret == 0)
1467                 ret = 1;
1468 out_unlock:
1469         srcu_read_unlock(&vcpu->kvm->srcu, idx);
1470         return ret;
1471 }
1472
1473 static int handle_hva_to_gpa(struct kvm *kvm,
1474                              unsigned long start,
1475                              unsigned long end,
1476                              int (*handler)(struct kvm *kvm,
1477                                             gpa_t gpa, void *data),
1478                              void *data)
1479 {
1480         struct kvm_memslots *slots;
1481         struct kvm_memory_slot *memslot;
1482         int ret = 0;
1483
1484         slots = kvm_memslots(kvm);
1485
1486         /* we only care about the pages that the guest sees */
1487         kvm_for_each_memslot(memslot, slots) {
1488                 unsigned long hva_start, hva_end;
1489                 gfn_t gfn, gfn_end;
1490
1491                 hva_start = max(start, memslot->userspace_addr);
1492                 hva_end = min(end, memslot->userspace_addr +
1493                                         (memslot->npages << PAGE_SHIFT));
1494                 if (hva_start >= hva_end)
1495                         continue;
1496
1497                 /*
1498                  * {gfn(page) | page intersects with [hva_start, hva_end)} =
1499                  * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1500                  */
1501                 gfn = hva_to_gfn_memslot(hva_start, memslot);
1502                 gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1503
1504                 for (; gfn < gfn_end; ++gfn) {
1505                         gpa_t gpa = gfn << PAGE_SHIFT;
1506                         ret |= handler(kvm, gpa, data);
1507                 }
1508         }
1509
1510         return ret;
1511 }
1512
1513 static int kvm_unmap_hva_handler(struct kvm *kvm, gpa_t gpa, void *data)
1514 {
1515         unmap_stage2_range(kvm, gpa, PAGE_SIZE);
1516         return 0;
1517 }
1518
1519 int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
1520 {
1521         unsigned long end = hva + PAGE_SIZE;
1522
1523         if (!kvm->arch.pgd)
1524                 return 0;
1525
1526         trace_kvm_unmap_hva(hva);
1527         handle_hva_to_gpa(kvm, hva, end, &kvm_unmap_hva_handler, NULL);
1528         return 0;
1529 }
1530
1531 int kvm_unmap_hva_range(struct kvm *kvm,
1532                         unsigned long start, unsigned long end)
1533 {
1534         if (!kvm->arch.pgd)
1535                 return 0;
1536
1537         trace_kvm_unmap_hva_range(start, end);
1538         handle_hva_to_gpa(kvm, start, end, &kvm_unmap_hva_handler, NULL);
1539         return 0;
1540 }
1541
1542 static int kvm_set_spte_handler(struct kvm *kvm, gpa_t gpa, void *data)
1543 {
1544         pte_t *pte = (pte_t *)data;
1545
1546         /*
1547          * We can always call stage2_set_pte with KVM_S2PTE_FLAG_LOGGING_ACTIVE
1548          * flag clear because MMU notifiers will have unmapped a huge PMD before
1549          * calling ->change_pte() (which in turn calls kvm_set_spte_hva()) and
1550          * therefore stage2_set_pte() never needs to clear out a huge PMD
1551          * through this calling path.
1552          */
1553         stage2_set_pte(kvm, NULL, gpa, pte, 0);
1554         return 0;
1555 }
1556
1557
1558 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1559 {
1560         unsigned long end = hva + PAGE_SIZE;
1561         pte_t stage2_pte;
1562
1563         if (!kvm->arch.pgd)
1564                 return;
1565
1566         trace_kvm_set_spte_hva(hva);
1567         stage2_pte = pfn_pte(pte_pfn(pte), PAGE_S2);
1568         handle_hva_to_gpa(kvm, hva, end, &kvm_set_spte_handler, &stage2_pte);
1569 }
1570
1571 static int kvm_age_hva_handler(struct kvm *kvm, gpa_t gpa, void *data)
1572 {
1573         pmd_t *pmd;
1574         pte_t *pte;
1575
1576         pmd = stage2_get_pmd(kvm, NULL, gpa);
1577         if (!pmd || pmd_none(*pmd))     /* Nothing there */
1578                 return 0;
1579
1580         if (kvm_pmd_huge(*pmd)) {       /* THP, HugeTLB */
1581                 if (pmd_young(*pmd)) {
1582                         *pmd = pmd_mkold(*pmd);
1583                         return 1;
1584                 }
1585
1586                 return 0;
1587         }
1588
1589         pte = pte_offset_kernel(pmd, gpa);
1590         if (pte_none(*pte))
1591                 return 0;
1592
1593         if (pte_young(*pte)) {
1594                 *pte = pte_mkold(*pte); /* Just a page... */
1595                 return 1;
1596         }
1597
1598         return 0;
1599 }
1600
1601 static int kvm_test_age_hva_handler(struct kvm *kvm, gpa_t gpa, void *data)
1602 {
1603         pmd_t *pmd;
1604         pte_t *pte;
1605
1606         pmd = stage2_get_pmd(kvm, NULL, gpa);
1607         if (!pmd || pmd_none(*pmd))     /* Nothing there */
1608                 return 0;
1609
1610         if (kvm_pmd_huge(*pmd))         /* THP, HugeTLB */
1611                 return pmd_young(*pmd);
1612
1613         pte = pte_offset_kernel(pmd, gpa);
1614         if (!pte_none(*pte))            /* Just a page... */
1615                 return pte_young(*pte);
1616
1617         return 0;
1618 }
1619
1620 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1621 {
1622         trace_kvm_age_hva(start, end);
1623         return handle_hva_to_gpa(kvm, start, end, kvm_age_hva_handler, NULL);
1624 }
1625
1626 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1627 {
1628         trace_kvm_test_age_hva(hva);
1629         return handle_hva_to_gpa(kvm, hva, hva, kvm_test_age_hva_handler, NULL);
1630 }
1631
1632 void kvm_mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1633 {
1634         mmu_free_memory_cache(&vcpu->arch.mmu_page_cache);
1635 }
1636
1637 phys_addr_t kvm_mmu_get_httbr(void)
1638 {
1639         if (__kvm_cpu_uses_extended_idmap())
1640                 return virt_to_phys(merged_hyp_pgd);
1641         else
1642                 return virt_to_phys(hyp_pgd);
1643 }
1644
1645 phys_addr_t kvm_mmu_get_boot_httbr(void)
1646 {
1647         if (__kvm_cpu_uses_extended_idmap())
1648                 return virt_to_phys(merged_hyp_pgd);
1649         else
1650                 return virt_to_phys(boot_hyp_pgd);
1651 }
1652
1653 phys_addr_t kvm_get_idmap_vector(void)
1654 {
1655         return hyp_idmap_vector;
1656 }
1657
1658 phys_addr_t kvm_get_idmap_start(void)
1659 {
1660         return hyp_idmap_start;
1661 }
1662
1663 int kvm_mmu_init(void)
1664 {
1665         int err;
1666
1667         hyp_idmap_start = kvm_virt_to_phys(__hyp_idmap_text_start);
1668         hyp_idmap_end = kvm_virt_to_phys(__hyp_idmap_text_end);
1669         hyp_idmap_vector = kvm_virt_to_phys(__kvm_hyp_init);
1670
1671         /*
1672          * We rely on the linker script to ensure at build time that the HYP
1673          * init code does not cross a page boundary.
1674          */
1675         BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
1676
1677         hyp_pgd = (pgd_t *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, hyp_pgd_order);
1678         boot_hyp_pgd = (pgd_t *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, hyp_pgd_order);
1679
1680         if (!hyp_pgd || !boot_hyp_pgd) {
1681                 kvm_err("Hyp mode PGD not allocated\n");
1682                 err = -ENOMEM;
1683                 goto out;
1684         }
1685
1686         /* Create the idmap in the boot page tables */
1687         err =   __create_hyp_mappings(boot_hyp_pgd,
1688                                       hyp_idmap_start, hyp_idmap_end,
1689                                       __phys_to_pfn(hyp_idmap_start),
1690                                       PAGE_HYP);
1691
1692         if (err) {
1693                 kvm_err("Failed to idmap %lx-%lx\n",
1694                         hyp_idmap_start, hyp_idmap_end);
1695                 goto out;
1696         }
1697
1698         if (__kvm_cpu_uses_extended_idmap()) {
1699                 merged_hyp_pgd = (pgd_t *)__get_free_page(GFP_KERNEL | __GFP_ZERO);
1700                 if (!merged_hyp_pgd) {
1701                         kvm_err("Failed to allocate extra HYP pgd\n");
1702                         goto out;
1703                 }
1704                 __kvm_extend_hypmap(boot_hyp_pgd, hyp_pgd, merged_hyp_pgd,
1705                                     hyp_idmap_start);
1706                 return 0;
1707         }
1708
1709         /* Map the very same page at the trampoline VA */
1710         err =   __create_hyp_mappings(boot_hyp_pgd,
1711                                       TRAMPOLINE_VA, TRAMPOLINE_VA + PAGE_SIZE,
1712                                       __phys_to_pfn(hyp_idmap_start),
1713                                       PAGE_HYP);
1714         if (err) {
1715                 kvm_err("Failed to map trampoline @%lx into boot HYP pgd\n",
1716                         TRAMPOLINE_VA);
1717                 goto out;
1718         }
1719
1720         /* Map the same page again into the runtime page tables */
1721         err =   __create_hyp_mappings(hyp_pgd,
1722                                       TRAMPOLINE_VA, TRAMPOLINE_VA + PAGE_SIZE,
1723                                       __phys_to_pfn(hyp_idmap_start),
1724                                       PAGE_HYP);
1725         if (err) {
1726                 kvm_err("Failed to map trampoline @%lx into runtime HYP pgd\n",
1727                         TRAMPOLINE_VA);
1728                 goto out;
1729         }
1730
1731         return 0;
1732 out:
1733         free_hyp_pgds();
1734         return err;
1735 }
1736
1737 void kvm_arch_commit_memory_region(struct kvm *kvm,
1738                                    const struct kvm_userspace_memory_region *mem,
1739                                    const struct kvm_memory_slot *old,
1740                                    const struct kvm_memory_slot *new,
1741                                    enum kvm_mr_change change)
1742 {
1743         /*
1744          * At this point memslot has been committed and there is an
1745          * allocated dirty_bitmap[], dirty pages will be be tracked while the
1746          * memory slot is write protected.
1747          */
1748         if (change != KVM_MR_DELETE && mem->flags & KVM_MEM_LOG_DIRTY_PAGES)
1749                 kvm_mmu_wp_memory_region(kvm, mem->slot);
1750 }
1751
1752 int kvm_arch_prepare_memory_region(struct kvm *kvm,
1753                                    struct kvm_memory_slot *memslot,
1754                                    const struct kvm_userspace_memory_region *mem,
1755                                    enum kvm_mr_change change)
1756 {
1757         hva_t hva = mem->userspace_addr;
1758         hva_t reg_end = hva + mem->memory_size;
1759         bool writable = !(mem->flags & KVM_MEM_READONLY);
1760         int ret = 0;
1761
1762         if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
1763                         change != KVM_MR_FLAGS_ONLY)
1764                 return 0;
1765
1766         /*
1767          * Prevent userspace from creating a memory region outside of the IPA
1768          * space addressable by the KVM guest IPA space.
1769          */
1770         if (memslot->base_gfn + memslot->npages >=
1771             (KVM_PHYS_SIZE >> PAGE_SHIFT))
1772                 return -EFAULT;
1773
1774         /*
1775          * A memory region could potentially cover multiple VMAs, and any holes
1776          * between them, so iterate over all of them to find out if we can map
1777          * any of them right now.
1778          *
1779          *     +--------------------------------------------+
1780          * +---------------+----------------+   +----------------+
1781          * |   : VMA 1     |      VMA 2     |   |    VMA 3  :    |
1782          * +---------------+----------------+   +----------------+
1783          *     |               memory region                |
1784          *     +--------------------------------------------+
1785          */
1786         do {
1787                 struct vm_area_struct *vma = find_vma(current->mm, hva);
1788                 hva_t vm_start, vm_end;
1789
1790                 if (!vma || vma->vm_start >= reg_end)
1791                         break;
1792
1793                 /*
1794                  * Mapping a read-only VMA is only allowed if the
1795                  * memory region is configured as read-only.
1796                  */
1797                 if (writable && !(vma->vm_flags & VM_WRITE)) {
1798                         ret = -EPERM;
1799                         break;
1800                 }
1801
1802                 /*
1803                  * Take the intersection of this VMA with the memory region
1804                  */
1805                 vm_start = max(hva, vma->vm_start);
1806                 vm_end = min(reg_end, vma->vm_end);
1807
1808                 if (vma->vm_flags & VM_PFNMAP) {
1809                         gpa_t gpa = mem->guest_phys_addr +
1810                                     (vm_start - mem->userspace_addr);
1811                         phys_addr_t pa;
1812
1813                         pa = (phys_addr_t)vma->vm_pgoff << PAGE_SHIFT;
1814                         pa += vm_start - vma->vm_start;
1815
1816                         /* IO region dirty page logging not allowed */
1817                         if (memslot->flags & KVM_MEM_LOG_DIRTY_PAGES)
1818                                 return -EINVAL;
1819
1820                         ret = kvm_phys_addr_ioremap(kvm, gpa, pa,
1821                                                     vm_end - vm_start,
1822                                                     writable);
1823                         if (ret)
1824                                 break;
1825                 }
1826                 hva = vm_end;
1827         } while (hva < reg_end);
1828
1829         if (change == KVM_MR_FLAGS_ONLY)
1830                 return ret;
1831
1832         spin_lock(&kvm->mmu_lock);
1833         if (ret)
1834                 unmap_stage2_range(kvm, mem->guest_phys_addr, mem->memory_size);
1835         else
1836                 stage2_flush_memslot(kvm, memslot);
1837         spin_unlock(&kvm->mmu_lock);
1838         return ret;
1839 }
1840
1841 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
1842                            struct kvm_memory_slot *dont)
1843 {
1844 }
1845
1846 int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
1847                             unsigned long npages)
1848 {
1849         /*
1850          * Readonly memslots are not incoherent with the caches by definition,
1851          * but in practice, they are used mostly to emulate ROMs or NOR flashes
1852          * that the guest may consider devices and hence map as uncached.
1853          * To prevent incoherency issues in these cases, tag all readonly
1854          * regions as incoherent.
1855          */
1856         if (slot->flags & KVM_MEM_READONLY)
1857                 slot->flags |= KVM_MEMSLOT_INCOHERENT;
1858         return 0;
1859 }
1860
1861 void kvm_arch_memslots_updated(struct kvm *kvm, struct kvm_memslots *slots)
1862 {
1863 }
1864
1865 void kvm_arch_flush_shadow_all(struct kvm *kvm)
1866 {
1867         kvm_free_stage2_pgd(kvm);
1868 }
1869
1870 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
1871                                    struct kvm_memory_slot *slot)
1872 {
1873         gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
1874         phys_addr_t size = slot->npages << PAGE_SHIFT;
1875
1876         spin_lock(&kvm->mmu_lock);
1877         unmap_stage2_range(kvm, gpa, size);
1878         spin_unlock(&kvm->mmu_lock);
1879 }
1880
1881 /*
1882  * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
1883  *
1884  * Main problems:
1885  * - S/W ops are local to a CPU (not broadcast)
1886  * - We have line migration behind our back (speculation)
1887  * - System caches don't support S/W at all (damn!)
1888  *
1889  * In the face of the above, the best we can do is to try and convert
1890  * S/W ops to VA ops. Because the guest is not allowed to infer the
1891  * S/W to PA mapping, it can only use S/W to nuke the whole cache,
1892  * which is a rather good thing for us.
1893  *
1894  * Also, it is only used when turning caches on/off ("The expected
1895  * usage of the cache maintenance instructions that operate by set/way
1896  * is associated with the cache maintenance instructions associated
1897  * with the powerdown and powerup of caches, if this is required by
1898  * the implementation.").
1899  *
1900  * We use the following policy:
1901  *
1902  * - If we trap a S/W operation, we enable VM trapping to detect
1903  *   caches being turned on/off, and do a full clean.
1904  *
1905  * - We flush the caches on both caches being turned on and off.
1906  *
1907  * - Once the caches are enabled, we stop trapping VM ops.
1908  */
1909 void kvm_set_way_flush(struct kvm_vcpu *vcpu)
1910 {
1911         unsigned long hcr = vcpu_get_hcr(vcpu);
1912
1913         /*
1914          * If this is the first time we do a S/W operation
1915          * (i.e. HCR_TVM not set) flush the whole memory, and set the
1916          * VM trapping.
1917          *
1918          * Otherwise, rely on the VM trapping to wait for the MMU +
1919          * Caches to be turned off. At that point, we'll be able to
1920          * clean the caches again.
1921          */
1922         if (!(hcr & HCR_TVM)) {
1923                 trace_kvm_set_way_flush(*vcpu_pc(vcpu),
1924                                         vcpu_has_cache_enabled(vcpu));
1925                 stage2_flush_vm(vcpu->kvm);
1926                 vcpu_set_hcr(vcpu, hcr | HCR_TVM);
1927         }
1928 }
1929
1930 void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
1931 {
1932         bool now_enabled = vcpu_has_cache_enabled(vcpu);
1933
1934         /*
1935          * If switching the MMU+caches on, need to invalidate the caches.
1936          * If switching it off, need to clean the caches.
1937          * Clean + invalidate does the trick always.
1938          */
1939         if (now_enabled != was_enabled)
1940                 stage2_flush_vm(vcpu->kvm);
1941
1942         /* Caches are now on, stop trapping VM ops (until a S/W op) */
1943         if (now_enabled)
1944                 vcpu_set_hcr(vcpu, vcpu_get_hcr(vcpu) & ~HCR_TVM);
1945
1946         trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
1947 }