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