xref: /freebsd/sys/arm64/vmm/vmm_arm64.c (revision 53bb5613a8a15363718b6e6de8d965bf9a2c5469)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2015 Mihai Carabas <mihai.carabas@gmail.com>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/smp.h>
33 #include <sys/kernel.h>
34 #include <sys/malloc.h>
35 #include <sys/mman.h>
36 #include <sys/pcpu.h>
37 #include <sys/proc.h>
38 #include <sys/sysctl.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/vmem.h>
42 
43 #include <vm/vm.h>
44 #include <vm/pmap.h>
45 #include <vm/vm_extern.h>
46 #include <vm/vm_map.h>
47 #include <vm/vm_page.h>
48 #include <vm/vm_param.h>
49 
50 #include <machine/armreg.h>
51 #include <machine/vm.h>
52 #include <machine/cpufunc.h>
53 #include <machine/cpu.h>
54 #include <machine/machdep.h>
55 #include <machine/vmm.h>
56 #include <machine/vmm_dev.h>
57 #include <machine/atomic.h>
58 #include <machine/hypervisor.h>
59 #include <machine/pmap.h>
60 
61 #include "mmu.h"
62 #include "arm64.h"
63 #include "hyp.h"
64 #include "reset.h"
65 #include "io/vgic.h"
66 #include "io/vgic_v3.h"
67 #include "io/vtimer.h"
68 #include "vmm_handlers.h"
69 #include "vmm_stat.h"
70 
71 #define	HANDLED		1
72 #define	UNHANDLED	0
73 
74 /* Number of bits in an EL2 virtual address */
75 #define	EL2_VIRT_BITS	48
76 CTASSERT((1ul << EL2_VIRT_BITS) >= HYP_VM_MAX_ADDRESS);
77 
78 /* TODO: Move the host hypctx off the stack */
79 #define	VMM_STACK_PAGES	4
80 #define	VMM_STACK_SIZE	(VMM_STACK_PAGES * PAGE_SIZE)
81 
82 static int vmm_pmap_levels, vmm_virt_bits, vmm_max_ipa_bits;
83 
84 /* Register values passed to arm_setup_vectors to set in the hypervisor */
85 struct vmm_init_regs {
86 	uint64_t tcr_el2;
87 	uint64_t vtcr_el2;
88 };
89 
90 MALLOC_DEFINE(M_HYP, "ARM VMM HYP", "ARM VMM HYP");
91 
92 extern char hyp_init_vectors[];
93 extern char hyp_vectors[];
94 extern char hyp_stub_vectors[];
95 
96 static vm_paddr_t hyp_code_base;
97 static size_t hyp_code_len;
98 
99 static char *stack[MAXCPU];
100 static vm_offset_t stack_hyp_va[MAXCPU];
101 
102 static vmem_t *el2_mem_alloc;
103 
104 static void arm_setup_vectors(void *arg);
105 
106 DPCPU_DEFINE_STATIC(struct hypctx *, vcpu);
107 
108 static inline void
109 arm64_set_active_vcpu(struct hypctx *hypctx)
110 {
111 	DPCPU_SET(vcpu, hypctx);
112 }
113 
114 struct hypctx *
115 arm64_get_active_vcpu(void)
116 {
117 	return (DPCPU_GET(vcpu));
118 }
119 
120 static void
121 arm_setup_vectors(void *arg)
122 {
123 	struct vmm_init_regs *el2_regs;
124 	uintptr_t stack_top;
125 	uint32_t sctlr_el2;
126 	register_t daif;
127 
128 	el2_regs = arg;
129 	arm64_set_active_vcpu(NULL);
130 
131 	/*
132 	 * Configure the system control register for EL2:
133 	 *
134 	 * SCTLR_EL2_M: MMU on
135 	 * SCTLR_EL2_C: Data cacheability not affected
136 	 * SCTLR_EL2_I: Instruction cacheability not affected
137 	 * SCTLR_EL2_A: Instruction alignment check
138 	 * SCTLR_EL2_SA: Stack pointer alignment check
139 	 * SCTLR_EL2_WXN: Treat writable memory as execute never
140 	 * ~SCTLR_EL2_EE: Data accesses are little-endian
141 	 */
142 	sctlr_el2 = SCTLR_EL2_RES1;
143 	sctlr_el2 |= SCTLR_EL2_M | SCTLR_EL2_C | SCTLR_EL2_I;
144 	sctlr_el2 |= SCTLR_EL2_A | SCTLR_EL2_SA;
145 	sctlr_el2 |= SCTLR_EL2_WXN;
146 	sctlr_el2 &= ~SCTLR_EL2_EE;
147 
148 	daif = intr_disable();
149 
150 	if (in_vhe()) {
151 		WRITE_SPECIALREG(vtcr_el2, el2_regs->vtcr_el2);
152 	} else {
153 		/*
154 		 * Install the temporary vectors which will be responsible for
155 		 * initializing the VMM when we next trap into EL2.
156 		 *
157 		 * x0: the exception vector table responsible for hypervisor
158 		 * initialization on the next call.
159 		 */
160 		vmm_call_hyp(vtophys(&vmm_hyp_code));
161 
162 		/* Create and map the hypervisor stack */
163 		stack_top = stack_hyp_va[PCPU_GET(cpuid)] + VMM_STACK_SIZE;
164 
165 		/* Special call to initialize EL2 */
166 		vmm_call_hyp(vmmpmap_to_ttbr0(), stack_top, el2_regs->tcr_el2,
167 		    sctlr_el2, el2_regs->vtcr_el2);
168 	}
169 
170 	intr_restore(daif);
171 }
172 
173 static void
174 arm_teardown_vectors(void *arg)
175 {
176 	register_t daif;
177 
178 	/*
179 	 * vmm_cleanup() will disable the MMU. For the next few instructions,
180 	 * before the hardware disables the MMU, one of the following is
181 	 * possible:
182 	 *
183 	 * a. The instruction addresses are fetched with the MMU disabled,
184 	 * and they must represent the actual physical addresses. This will work
185 	 * because we call the vmm_cleanup() function by its physical address.
186 	 *
187 	 * b. The instruction addresses are fetched using the old translation
188 	 * tables. This will work because we have an identity mapping in place
189 	 * in the translation tables and vmm_cleanup() is called by its physical
190 	 * address.
191 	 */
192 	daif = intr_disable();
193 	/* TODO: Invalidate the cache */
194 	vmm_call_hyp(HYP_CLEANUP, vtophys(hyp_stub_vectors));
195 	intr_restore(daif);
196 
197 	arm64_set_active_vcpu(NULL);
198 }
199 
200 static uint64_t
201 vmm_vtcr_el2_sl(u_int levels)
202 {
203 #if PAGE_SIZE == PAGE_SIZE_4K
204 	switch (levels) {
205 	case 2:
206 		return (VTCR_EL2_SL0_4K_LVL2);
207 	case 3:
208 		return (VTCR_EL2_SL0_4K_LVL1);
209 	case 4:
210 		return (VTCR_EL2_SL0_4K_LVL0);
211 	default:
212 		panic("%s: Invalid number of page table levels %u", __func__,
213 		    levels);
214 	}
215 #elif PAGE_SIZE == PAGE_SIZE_16K
216 	switch (levels) {
217 	case 2:
218 		return (VTCR_EL2_SL0_16K_LVL2);
219 	case 3:
220 		return (VTCR_EL2_SL0_16K_LVL1);
221 	case 4:
222 		return (VTCR_EL2_SL0_16K_LVL0);
223 	default:
224 		panic("%s: Invalid number of page table levels %u", __func__,
225 		    levels);
226 	}
227 #else
228 #error Unsupported page size
229 #endif
230 }
231 
232 int
233 vmmops_modinit(int ipinum)
234 {
235 	struct vmm_init_regs el2_regs;
236 	vm_offset_t next_hyp_va;
237 	vm_paddr_t vmm_base;
238 	uint64_t id_aa64mmfr0_el1, pa_range_bits, pa_range_field;
239 	uint64_t cnthctl_el2;
240 	int cpu, i;
241 	bool rv __diagused;
242 
243 	if (!has_hyp()) {
244 		printf(
245 		    "vmm: Processor doesn't have support for virtualization\n");
246 		return (ENXIO);
247 	}
248 
249 	if (!vgic_present()) {
250 		printf("vmm: No vgic found\n");
251 		return (ENODEV);
252 	}
253 
254 	if (!get_kernel_reg(ID_AA64MMFR0_EL1, &id_aa64mmfr0_el1)) {
255 		printf("vmm: Unable to read ID_AA64MMFR0_EL1\n");
256 		return (ENXIO);
257 	}
258 	pa_range_field = ID_AA64MMFR0_PARange_VAL(id_aa64mmfr0_el1);
259 	/*
260 	 * Use 3 levels to give us up to 39 bits with 4k pages, or
261 	 * 47 bits with 16k pages.
262 	 */
263 	/* TODO: Check the number of levels for 64k pages */
264 	vmm_pmap_levels = 3;
265 	switch (pa_range_field) {
266 	case ID_AA64MMFR0_PARange_4G:
267 		printf("vmm: Not enough physical address bits\n");
268 		return (ENXIO);
269 	case ID_AA64MMFR0_PARange_64G:
270 		vmm_virt_bits = 36;
271 #if PAGE_SIZE == PAGE_SIZE_16K
272 		vmm_pmap_levels = 2;
273 #endif
274 		break;
275 	default:
276 		vmm_virt_bits = 39;
277 		break;
278 	}
279 	pa_range_bits = pa_range_field >> ID_AA64MMFR0_PARange_SHIFT;
280 
281 	if (!in_vhe()) {
282 		/* Initialise the EL2 MMU */
283 		if (!vmmpmap_init()) {
284 			printf("vmm: Failed to init the EL2 MMU\n");
285 			return (ENOMEM);
286 		}
287 	}
288 
289 	/* Set up the stage 2 pmap callbacks */
290 	MPASS(pmap_clean_stage2_tlbi == NULL);
291 	pmap_clean_stage2_tlbi = vmm_clean_s2_tlbi;
292 	pmap_stage2_invalidate_range = vmm_s2_tlbi_range;
293 	pmap_stage2_invalidate_all = vmm_s2_tlbi_all;
294 
295 	if (!in_vhe()) {
296 		/*
297 		 * Create an allocator for the virtual address space used by
298 		 * EL2. EL2 code is identity-mapped; the allocator is used to
299 		 * find space for VM structures.
300 		 */
301 		el2_mem_alloc = vmem_create("VMM EL2", 0, 0, PAGE_SIZE, 0,
302 		    M_WAITOK);
303 
304 		/* Create the mappings for the hypervisor translation table. */
305 		hyp_code_len = round_page(&vmm_hyp_code_end - &vmm_hyp_code);
306 
307 		/* We need an physical identity mapping for when we activate the MMU */
308 		hyp_code_base = vmm_base = vtophys(&vmm_hyp_code);
309 		rv = vmmpmap_enter(vmm_base, hyp_code_len, vmm_base,
310 		    VM_PROT_READ | VM_PROT_EXECUTE);
311 		MPASS(rv);
312 
313 		next_hyp_va = roundup2(vmm_base + hyp_code_len, L2_SIZE);
314 
315 		/* Create a per-CPU hypervisor stack */
316 		CPU_FOREACH(cpu) {
317 			stack[cpu] = malloc(VMM_STACK_SIZE, M_HYP, M_WAITOK | M_ZERO);
318 			stack_hyp_va[cpu] = next_hyp_va;
319 
320 			for (i = 0; i < VMM_STACK_PAGES; i++) {
321 				rv = vmmpmap_enter(stack_hyp_va[cpu] + ptoa(i),
322 				    PAGE_SIZE, vtophys(stack[cpu] + ptoa(i)),
323 				    VM_PROT_READ | VM_PROT_WRITE);
324 				MPASS(rv);
325 			}
326 			next_hyp_va += L2_SIZE;
327 		}
328 
329 		el2_regs.tcr_el2 = TCR_EL2_RES1;
330 		el2_regs.tcr_el2 |= min(pa_range_bits << TCR_EL2_PS_SHIFT,
331 		    TCR_EL2_PS_52BITS);
332 		el2_regs.tcr_el2 |= TCR_EL2_T0SZ(64 - EL2_VIRT_BITS);
333 		el2_regs.tcr_el2 |= TCR_EL2_IRGN0_WBWA | TCR_EL2_ORGN0_WBWA;
334 #if PAGE_SIZE == PAGE_SIZE_4K
335 		el2_regs.tcr_el2 |= TCR_EL2_TG0_4K;
336 #elif PAGE_SIZE == PAGE_SIZE_16K
337 		el2_regs.tcr_el2 |= TCR_EL2_TG0_16K;
338 #else
339 #error Unsupported page size
340 #endif
341 #ifdef SMP
342 		el2_regs.tcr_el2 |= TCR_EL2_SH0_IS;
343 #endif
344 	}
345 
346 	switch (pa_range_bits << TCR_EL2_PS_SHIFT) {
347 	case TCR_EL2_PS_32BITS:
348 		vmm_max_ipa_bits = 32;
349 		break;
350 	case TCR_EL2_PS_36BITS:
351 		vmm_max_ipa_bits = 36;
352 		break;
353 	case TCR_EL2_PS_40BITS:
354 		vmm_max_ipa_bits = 40;
355 		break;
356 	case TCR_EL2_PS_42BITS:
357 		vmm_max_ipa_bits = 42;
358 		break;
359 	case TCR_EL2_PS_44BITS:
360 		vmm_max_ipa_bits = 44;
361 		break;
362 	case TCR_EL2_PS_48BITS:
363 		vmm_max_ipa_bits = 48;
364 		break;
365 	case TCR_EL2_PS_52BITS:
366 	default:
367 		vmm_max_ipa_bits = 52;
368 		break;
369 	}
370 
371 	/*
372 	 * Configure the Stage 2 translation control register:
373 	 *
374 	 * VTCR_IRGN0_WBWA: Translation table walks access inner cacheable
375 	 * normal memory
376 	 * VTCR_ORGN0_WBWA: Translation table walks access outer cacheable
377 	 * normal memory
378 	 * VTCR_EL2_TG0_4K/16K: Stage 2 uses the same page size as the kernel
379 	 * VTCR_EL2_SL0_4K_LVL1: Stage 2 uses concatenated level 1 tables
380 	 * VTCR_EL2_SH0_IS: Memory associated with Stage 2 walks is inner
381 	 * shareable
382 	 */
383 	el2_regs.vtcr_el2 = VTCR_EL2_RES1;
384 	el2_regs.vtcr_el2 |=
385 	    min(pa_range_bits << VTCR_EL2_PS_SHIFT, VTCR_EL2_PS_48BIT);
386 	el2_regs.vtcr_el2 |= VTCR_EL2_IRGN0_WBWA | VTCR_EL2_ORGN0_WBWA;
387 	el2_regs.vtcr_el2 |= VTCR_EL2_T0SZ(64 - vmm_virt_bits);
388 	el2_regs.vtcr_el2 |= vmm_vtcr_el2_sl(vmm_pmap_levels);
389 #if PAGE_SIZE == PAGE_SIZE_4K
390 	el2_regs.vtcr_el2 |= VTCR_EL2_TG0_4K;
391 #elif PAGE_SIZE == PAGE_SIZE_16K
392 	el2_regs.vtcr_el2 |= VTCR_EL2_TG0_16K;
393 #else
394 #error Unsupported page size
395 #endif
396 #ifdef SMP
397 	el2_regs.vtcr_el2 |= VTCR_EL2_SH0_IS;
398 #endif
399 	/*
400 	 * If FEAT_LPA2 is enabled in the host then we need to enable it here
401 	 * so the page tables created by pmap.c are correct. The meaning of
402 	 * the shareability field changes to become address bits when this
403 	 * is set.
404 	 */
405 	if ((READ_SPECIALREG(tcr_el1) & TCR_DS) != 0)
406 		el2_regs.vtcr_el2 |= VTCR_EL2_DS;
407 
408 	smp_rendezvous(NULL, arm_setup_vectors, NULL, &el2_regs);
409 
410 	if (!in_vhe()) {
411 		/* Add memory to the vmem allocator (checking there is space) */
412 		if (vmm_base > (L2_SIZE + PAGE_SIZE)) {
413 			/*
414 			 * Ensure there is an L2 block before the vmm code to check
415 			 * for buffer overflows on earlier data. Include the PAGE_SIZE
416 			 * of the minimum we can allocate.
417 			 */
418 			vmm_base -= L2_SIZE + PAGE_SIZE;
419 			vmm_base = rounddown2(vmm_base, L2_SIZE);
420 
421 			/*
422 			 * Check there is memory before the vmm code to add.
423 			 *
424 			 * Reserve the L2 block at address 0 so NULL dereference will
425 			 * raise an exception.
426 			 */
427 			if (vmm_base > L2_SIZE)
428 				vmem_add(el2_mem_alloc, L2_SIZE, vmm_base - L2_SIZE,
429 				    M_WAITOK);
430 		}
431 
432 		/*
433 		 * Add the memory after the stacks. There is most of an L2 block
434 		 * between the last stack and the first allocation so this should
435 		 * be safe without adding more padding.
436 		 */
437 		if (next_hyp_va < HYP_VM_MAX_ADDRESS - PAGE_SIZE)
438 			vmem_add(el2_mem_alloc, next_hyp_va,
439 			    HYP_VM_MAX_ADDRESS - next_hyp_va, M_WAITOK);
440 	}
441 	cnthctl_el2 = vmm_read_reg(HYP_REG_CNTHCTL);
442 
443 	vgic_init();
444 	vtimer_init(cnthctl_el2);
445 
446 	return (0);
447 }
448 
449 int
450 vmmops_modcleanup(void)
451 {
452 	int cpu;
453 
454 	if (!in_vhe()) {
455 		smp_rendezvous(NULL, arm_teardown_vectors, NULL, NULL);
456 
457 		CPU_FOREACH(cpu) {
458 			vmmpmap_remove(stack_hyp_va[cpu],
459 			    VMM_STACK_PAGES * PAGE_SIZE, false);
460 		}
461 
462 		vmmpmap_remove(hyp_code_base, hyp_code_len, false);
463 	}
464 
465 	vtimer_cleanup();
466 
467 	if (!in_vhe()) {
468 		vmmpmap_fini();
469 
470 		CPU_FOREACH(cpu)
471 			free(stack[cpu], M_HYP);
472 	}
473 
474 	pmap_clean_stage2_tlbi = NULL;
475 	pmap_stage2_invalidate_range = NULL;
476 	pmap_stage2_invalidate_all = NULL;
477 
478 	return (0);
479 }
480 
481 static vm_size_t
482 el2_hyp_size(struct vm *vm)
483 {
484 	return (round_page(sizeof(struct hyp) +
485 	    sizeof(struct hypctx *) * vm_get_maxcpus(vm)));
486 }
487 
488 static vm_size_t
489 el2_hypctx_size(void)
490 {
491 	return (round_page(sizeof(struct hypctx)));
492 }
493 
494 static vm_offset_t
495 el2_map_enter(vm_offset_t data, vm_size_t size, vm_prot_t prot)
496 {
497 	vmem_addr_t addr;
498 	int err __diagused;
499 	bool rv __diagused;
500 
501 	err = vmem_alloc(el2_mem_alloc, size, M_NEXTFIT | M_WAITOK, &addr);
502 	MPASS(err == 0);
503 	rv = vmmpmap_enter(addr, size, vtophys(data), prot);
504 	MPASS(rv);
505 
506 	return (addr);
507 }
508 
509 void *
510 vmmops_init(struct vm *vm, pmap_t pmap)
511 {
512 	struct hyp *hyp;
513 	vm_size_t size;
514 
515 	size = el2_hyp_size(vm);
516 	hyp = malloc_aligned(size, PAGE_SIZE, M_HYP, M_WAITOK | M_ZERO);
517 
518 	hyp->vm = vm;
519 	hyp->vgic_attached = false;
520 
521 	vtimer_vminit(hyp);
522 	vgic_vminit(hyp);
523 
524 	if (!in_vhe())
525 		hyp->el2_addr = el2_map_enter((vm_offset_t)hyp, size,
526 		    VM_PROT_READ | VM_PROT_WRITE);
527 
528 	return (hyp);
529 }
530 
531 void *
532 vmmops_vcpu_init(void *vmi, struct vcpu *vcpu1, int vcpuid)
533 {
534 	struct hyp *hyp = vmi;
535 	struct hypctx *hypctx;
536 	vm_size_t size;
537 
538 	size = el2_hypctx_size();
539 	hypctx = malloc_aligned(size, PAGE_SIZE, M_HYP, M_WAITOK | M_ZERO);
540 
541 	KASSERT(vcpuid >= 0 && vcpuid < vm_get_maxcpus(hyp->vm),
542 	    ("%s: Invalid vcpuid %d", __func__, vcpuid));
543 	hyp->ctx[vcpuid] = hypctx;
544 
545 	hypctx->hyp = hyp;
546 	hypctx->vcpu = vcpu1;
547 
548 	reset_vm_el01_regs(hypctx);
549 	reset_vm_el2_regs(hypctx);
550 
551 	vtimer_cpuinit(hypctx);
552 	vgic_cpuinit(hypctx);
553 
554 	if (!in_vhe())
555 		hypctx->el2_addr = el2_map_enter((vm_offset_t)hypctx, size,
556 		    VM_PROT_READ | VM_PROT_WRITE);
557 
558 	return (hypctx);
559 }
560 
561 static int
562 arm_vmm_pinit(pmap_t pmap)
563 {
564 
565 	pmap_pinit_stage(pmap, PM_STAGE2, vmm_pmap_levels);
566 	return (1);
567 }
568 
569 struct vmspace *
570 vmmops_vmspace_alloc(vm_offset_t min, vm_offset_t max)
571 {
572 	return (vmspace_alloc(min, max, arm_vmm_pinit));
573 }
574 
575 void
576 vmmops_vmspace_free(struct vmspace *vmspace)
577 {
578 
579 	pmap_remove_pages(vmspace_pmap(vmspace));
580 	vmspace_free(vmspace);
581 }
582 
583 static inline void
584 arm64_print_hyp_regs(struct vm_exit *vme)
585 {
586 	printf("esr_el2:   0x%016lx\n", vme->u.hyp.esr_el2);
587 	printf("far_el2:   0x%016lx\n", vme->u.hyp.far_el2);
588 	printf("hpfar_el2: 0x%016lx\n", vme->u.hyp.hpfar_el2);
589 	printf("elr_el2:   0x%016lx\n", vme->pc);
590 }
591 
592 static void
593 arm64_gen_inst_emul_data(struct hypctx *hypctx, uint32_t esr_iss,
594     struct vm_exit *vme_ret)
595 {
596 	struct vm_guest_paging *paging;
597 	struct vie *vie;
598 	uint32_t esr_sas, reg_num;
599 
600 	/*
601 	 * Get the page address from HPFAR_EL2.
602 	 */
603 	vme_ret->u.inst_emul.gpa =
604 	    HPFAR_EL2_FIPA_ADDR(hypctx->exit_info.hpfar_el2);
605 	/* Bits [11:0] are the same as bits [11:0] from the virtual address. */
606 	vme_ret->u.inst_emul.gpa += hypctx->exit_info.far_el2 &
607 	    FAR_EL2_HPFAR_PAGE_MASK;
608 
609 	esr_sas = (esr_iss & ISS_DATA_SAS_MASK) >> ISS_DATA_SAS_SHIFT;
610 	reg_num = (esr_iss & ISS_DATA_SRT_MASK) >> ISS_DATA_SRT_SHIFT;
611 
612 	vie = &vme_ret->u.inst_emul.vie;
613 	vie->access_size = 1 << esr_sas;
614 	vie->sign_extend = (esr_iss & ISS_DATA_SSE) ? 1 : 0;
615 	vie->dir = (esr_iss & ISS_DATA_WnR) ? VM_DIR_WRITE : VM_DIR_READ;
616 	vie->reg = reg_num;
617 
618 	paging = &vme_ret->u.inst_emul.paging;
619 	paging->ttbr0_addr = hypctx->ttbr0_el1 & ~(TTBR_ASID_MASK | TTBR_CnP);
620 	paging->ttbr1_addr = hypctx->ttbr1_el1 & ~(TTBR_ASID_MASK | TTBR_CnP);
621 	paging->tcr_el1 = hypctx->tcr_el1;
622 	paging->tcr2_el1 = hypctx->tcr2_el1;
623 	paging->flags = hypctx->tf.tf_spsr & (PSR_M_MASK | PSR_M_32);
624 	if ((hypctx->sctlr_el1 & SCTLR_M) != 0)
625 		paging->flags |= VM_GP_MMU_ENABLED;
626 }
627 
628 static void
629 arm64_gen_reg_emul_data(uint32_t esr_iss, struct vm_exit *vme_ret)
630 {
631 	uint32_t reg_num;
632 	struct vre *vre;
633 
634 	/* u.hyp member will be replaced by u.reg_emul */
635 	vre = &vme_ret->u.reg_emul.vre;
636 
637 	vre->inst_syndrome = esr_iss;
638 	/* ARMv8 Architecture Manual, p. D7-2273: 1 means read */
639 	vre->dir = (esr_iss & ISS_MSR_DIR) ? VM_DIR_READ : VM_DIR_WRITE;
640 	reg_num = ISS_MSR_Rt(esr_iss);
641 	vre->reg = reg_num;
642 }
643 
644 void
645 raise_data_insn_abort(struct hypctx *hypctx, uint64_t far, bool dabort, int fsc)
646 {
647 	uint64_t esr;
648 
649 	if ((hypctx->tf.tf_spsr & PSR_M_MASK) == PSR_M_EL0t)
650 		esr = EXCP_INSN_ABORT_L << ESR_ELx_EC_SHIFT;
651 	else
652 		esr = EXCP_INSN_ABORT << ESR_ELx_EC_SHIFT;
653 	/* Set the bit that changes from insn -> data abort */
654 	if (dabort)
655 		esr |= EXCP_DATA_ABORT_L << ESR_ELx_EC_SHIFT;
656 	/* Set the IL bit if set by hardware */
657 	esr |= hypctx->tf.tf_esr & ESR_ELx_IL;
658 
659 	vmmops_exception(hypctx, esr | fsc, far);
660 }
661 
662 static int
663 handle_el1_sync_excp(struct hypctx *hypctx, struct vm_exit *vme_ret,
664     pmap_t pmap)
665 {
666 	uint64_t gpa;
667 	uint32_t esr_ec, esr_iss;
668 
669 	esr_ec = ESR_ELx_EXCEPTION(hypctx->tf.tf_esr);
670 	esr_iss = hypctx->tf.tf_esr & ESR_ELx_ISS_MASK;
671 
672 	switch (esr_ec) {
673 	case EXCP_UNKNOWN:
674 		vmm_stat_incr(hypctx->vcpu, VMEXIT_UNKNOWN, 1);
675 		arm64_print_hyp_regs(vme_ret);
676 		vme_ret->exitcode = VM_EXITCODE_HYP;
677 		break;
678 	case EXCP_TRAP_WFI_WFE:
679 		if ((hypctx->tf.tf_esr & 0x3) == 0) { /* WFI */
680 			vmm_stat_incr(hypctx->vcpu, VMEXIT_WFI, 1);
681 			vme_ret->exitcode = VM_EXITCODE_WFI;
682 		} else {
683 			vmm_stat_incr(hypctx->vcpu, VMEXIT_WFE, 1);
684 			vme_ret->exitcode = VM_EXITCODE_HYP;
685 		}
686 		break;
687 	case EXCP_HVC:
688 		vmm_stat_incr(hypctx->vcpu, VMEXIT_HVC, 1);
689 		vme_ret->exitcode = VM_EXITCODE_HVC;
690 		break;
691 	case EXCP_MSR:
692 		vmm_stat_incr(hypctx->vcpu, VMEXIT_MSR, 1);
693 		arm64_gen_reg_emul_data(esr_iss, vme_ret);
694 		vme_ret->exitcode = VM_EXITCODE_REG_EMUL;
695 		break;
696 	case EXCP_BRK:
697 		vmm_stat_incr(hypctx->vcpu, VMEXIT_BRK, 1);
698 		vme_ret->exitcode = VM_EXITCODE_BRK;
699 		break;
700 	case EXCP_SOFTSTP_EL0:
701 		vmm_stat_incr(hypctx->vcpu, VMEXIT_SS, 1);
702 		vme_ret->exitcode = VM_EXITCODE_SS;
703 		break;
704 	case EXCP_INSN_ABORT_L:
705 	case EXCP_DATA_ABORT_L:
706 		vmm_stat_incr(hypctx->vcpu, esr_ec == EXCP_DATA_ABORT_L ?
707 		    VMEXIT_DATA_ABORT : VMEXIT_INSN_ABORT, 1);
708 		switch (hypctx->tf.tf_esr & ISS_DATA_DFSC_MASK) {
709 		case ISS_DATA_DFSC_TF_L0:
710 		case ISS_DATA_DFSC_TF_L1:
711 		case ISS_DATA_DFSC_TF_L2:
712 		case ISS_DATA_DFSC_TF_L3:
713 		case ISS_DATA_DFSC_AFF_L1:
714 		case ISS_DATA_DFSC_AFF_L2:
715 		case ISS_DATA_DFSC_AFF_L3:
716 		case ISS_DATA_DFSC_PF_L1:
717 		case ISS_DATA_DFSC_PF_L2:
718 		case ISS_DATA_DFSC_PF_L3:
719 			gpa = HPFAR_EL2_FIPA_ADDR(hypctx->exit_info.hpfar_el2);
720 			/* Check the IPA is valid */
721 			if (gpa >= (1ul << vmm_max_ipa_bits)) {
722 				raise_data_insn_abort(hypctx,
723 				    hypctx->exit_info.far_el2,
724 				    esr_ec == EXCP_DATA_ABORT_L,
725 				    ISS_DATA_DFSC_ASF_L0);
726 				vme_ret->inst_length = 0;
727 				return (HANDLED);
728 			}
729 
730 			if (vm_mem_allocated(hypctx->vcpu, gpa)) {
731 				vme_ret->exitcode = VM_EXITCODE_PAGING;
732 				vme_ret->inst_length = 0;
733 				vme_ret->u.paging.esr = hypctx->tf.tf_esr;
734 				vme_ret->u.paging.gpa = gpa;
735 			} else if (esr_ec == EXCP_INSN_ABORT_L) {
736 				/*
737 				 * Raise an external abort. Device memory is
738 				 * not executable
739 				 */
740 				raise_data_insn_abort(hypctx,
741 				    hypctx->exit_info.far_el2, false,
742 				    ISS_DATA_DFSC_EXT);
743 				vme_ret->inst_length = 0;
744 				return (HANDLED);
745 			} else {
746 				arm64_gen_inst_emul_data(hypctx, esr_iss,
747 				    vme_ret);
748 				vme_ret->exitcode = VM_EXITCODE_INST_EMUL;
749 			}
750 			break;
751 		default:
752 			arm64_print_hyp_regs(vme_ret);
753 			vme_ret->exitcode = VM_EXITCODE_HYP;
754 			break;
755 		}
756 
757 		break;
758 
759 	default:
760 		vmm_stat_incr(hypctx->vcpu, VMEXIT_UNHANDLED_SYNC, 1);
761 		arm64_print_hyp_regs(vme_ret);
762 		vme_ret->exitcode = VM_EXITCODE_HYP;
763 		break;
764 	}
765 
766 	/* We don't don't do any instruction emulation here */
767 	return (UNHANDLED);
768 }
769 
770 static int
771 arm64_handle_world_switch(struct hypctx *hypctx, int excp_type,
772     struct vm_exit *vme, pmap_t pmap)
773 {
774 	int handled;
775 
776 	switch (excp_type) {
777 	case EXCP_TYPE_EL1_SYNC:
778 		/* The exit code will be set by handle_el1_sync_excp(). */
779 		handled = handle_el1_sync_excp(hypctx, vme, pmap);
780 		break;
781 
782 	case EXCP_TYPE_EL1_IRQ:
783 	case EXCP_TYPE_EL1_FIQ:
784 		/* The host kernel will handle IRQs and FIQs. */
785 		vmm_stat_incr(hypctx->vcpu,
786 		    excp_type == EXCP_TYPE_EL1_IRQ ? VMEXIT_IRQ : VMEXIT_FIQ,1);
787 		vme->exitcode = VM_EXITCODE_BOGUS;
788 		handled = UNHANDLED;
789 		break;
790 
791 	case EXCP_TYPE_EL1_ERROR:
792 	case EXCP_TYPE_EL2_SYNC:
793 	case EXCP_TYPE_EL2_IRQ:
794 	case EXCP_TYPE_EL2_FIQ:
795 	case EXCP_TYPE_EL2_ERROR:
796 		vmm_stat_incr(hypctx->vcpu, VMEXIT_UNHANDLED_EL2, 1);
797 		vme->exitcode = VM_EXITCODE_BOGUS;
798 		handled = UNHANDLED;
799 		break;
800 
801 	default:
802 		vmm_stat_incr(hypctx->vcpu, VMEXIT_UNHANDLED, 1);
803 		vme->exitcode = VM_EXITCODE_BOGUS;
804 		handled = UNHANDLED;
805 		break;
806 	}
807 
808 	return (handled);
809 }
810 
811 static void
812 ptp_release(void **cookie)
813 {
814 	if (*cookie != NULL) {
815 		vm_gpa_release(*cookie);
816 		*cookie = NULL;
817 	}
818 }
819 
820 static void *
821 ptp_hold(struct vcpu *vcpu, vm_paddr_t ptpphys, size_t len, void **cookie)
822 {
823 	void *ptr;
824 
825 	ptp_release(cookie);
826 	ptr = vm_gpa_hold(vcpu, ptpphys, len, VM_PROT_RW, cookie);
827 	return (ptr);
828 }
829 
830 /* log2 of the number of bytes in a page table entry */
831 #define	PTE_SHIFT	3
832 int
833 vmmops_gla2gpa(void *vcpui, struct vm_guest_paging *paging, uint64_t gla,
834     int prot, uint64_t *gpa, int *is_fault)
835 {
836 	struct hypctx *hypctx;
837 	void *cookie;
838 	uint64_t mask, *ptep, pte, pte_addr;
839 	int address_bits, granule_shift, ia_bits, levels, pte_shift, tsz;
840 	bool is_el0;
841 
842 	/* Check if the MMU is off */
843 	if ((paging->flags & VM_GP_MMU_ENABLED) == 0) {
844 		*is_fault = 0;
845 		*gpa = gla;
846 		return (0);
847 	}
848 
849 	is_el0 = (paging->flags & PSR_M_MASK) == PSR_M_EL0t;
850 
851 	if (ADDR_IS_KERNEL(gla)) {
852 		/* If address translation is disabled raise an exception */
853 		if ((paging->tcr_el1 & TCR_EPD1) != 0) {
854 			*is_fault = 1;
855 			return (0);
856 		}
857 		if (is_el0 && (paging->tcr_el1 & TCR_E0PD1) != 0) {
858 			*is_fault = 1;
859 			return (0);
860 		}
861 		pte_addr = paging->ttbr1_addr;
862 		tsz = (paging->tcr_el1 & TCR_T1SZ_MASK) >> TCR_T1SZ_SHIFT;
863 		/* Clear the top byte if TBI is on */
864 		if ((paging->tcr_el1 & TCR_TBI1) != 0)
865 			gla |= (0xfful << 56);
866 		switch (paging->tcr_el1 & TCR_TG1_MASK) {
867 		case TCR_TG1_4K:
868 			granule_shift = PAGE_SHIFT_4K;
869 			break;
870 		case TCR_TG1_16K:
871 			granule_shift = PAGE_SHIFT_16K;
872 			break;
873 		case TCR_TG1_64K:
874 			granule_shift = PAGE_SHIFT_64K;
875 			break;
876 		default:
877 			*is_fault = 1;
878 			return (EINVAL);
879 		}
880 	} else {
881 		/* If address translation is disabled raise an exception */
882 		if ((paging->tcr_el1 & TCR_EPD0) != 0) {
883 			*is_fault = 1;
884 			return (0);
885 		}
886 		if (is_el0 && (paging->tcr_el1 & TCR_E0PD0) != 0) {
887 			*is_fault = 1;
888 			return (0);
889 		}
890 		pte_addr = paging->ttbr0_addr;
891 		tsz = (paging->tcr_el1 & TCR_T0SZ_MASK) >> TCR_T0SZ_SHIFT;
892 		/* Clear the top byte if TBI is on */
893 		if ((paging->tcr_el1 & TCR_TBI0) != 0)
894 			gla &= ~(0xfful << 56);
895 		switch (paging->tcr_el1 & TCR_TG0_MASK) {
896 		case TCR_TG0_4K:
897 			granule_shift = PAGE_SHIFT_4K;
898 			break;
899 		case TCR_TG0_16K:
900 			granule_shift = PAGE_SHIFT_16K;
901 			break;
902 		case TCR_TG0_64K:
903 			granule_shift = PAGE_SHIFT_64K;
904 			break;
905 		default:
906 			*is_fault = 1;
907 			return (EINVAL);
908 		}
909 	}
910 
911 	/*
912 	 * TODO: Support FEAT_TTST for smaller tsz values and FEAT_LPA2
913 	 * for larger values.
914 	 */
915 	switch (granule_shift) {
916 	case PAGE_SHIFT_4K:
917 	case PAGE_SHIFT_16K:
918 		/*
919 		 * See "Table D8-11 4KB granule, determining stage 1 initial
920 		 * lookup level" and "Table D8-21 16KB granule, determining
921 		 * stage 1 initial lookup level" from the "Arm Architecture
922 		 * Reference Manual for A-Profile architecture" revision I.a
923 		 * for the minimum and maximum values.
924 		 *
925 		 * TODO: Support less than 16 when FEAT_LPA2 is implemented
926 		 * and TCR_EL1.DS == 1
927 		 * TODO: Support more than 39 when FEAT_TTST is implemented
928 		 */
929 		if (tsz < 16 || tsz > 39) {
930 			*is_fault = 1;
931 			return (EINVAL);
932 		}
933 		break;
934 	case PAGE_SHIFT_64K:
935 	/* TODO: Support 64k granule. It will probably work, but is untested */
936 	default:
937 		*is_fault = 1;
938 		return (EINVAL);
939 	}
940 
941 	/*
942 	 * Calculate the input address bits. These are 64 bit in an address
943 	 * with the top tsz bits being all 0 or all 1.
944 	  */
945 	ia_bits = 64 - tsz;
946 
947 	/*
948 	 * Calculate the number of address bits used in the page table
949 	 * calculation. This is ia_bits minus the bottom granule_shift
950 	 * bits that are passed to the output address.
951 	 */
952 	address_bits = ia_bits - granule_shift;
953 
954 	/*
955 	 * Calculate the number of levels. Each level uses
956 	 * granule_shift - PTE_SHIFT bits of the input address.
957 	 * This is because the table is 1 << granule_shift and each
958 	 * entry is 1 << PTE_SHIFT bytes.
959 	 */
960 	levels = howmany(address_bits, granule_shift - PTE_SHIFT);
961 
962 	/* Mask of the upper unused bits in the virtual address */
963 	gla &= (1ul << ia_bits) - 1;
964 	hypctx = (struct hypctx *)vcpui;
965 	cookie = NULL;
966 	/* TODO: Check if the level supports block descriptors */
967 	for (;levels > 0; levels--) {
968 		int idx;
969 
970 		pte_shift = (levels - 1) * (granule_shift - PTE_SHIFT) +
971 		    granule_shift;
972 		idx = (gla >> pte_shift) &
973 		    ((1ul << (granule_shift - PTE_SHIFT)) - 1);
974 		while (idx > PAGE_SIZE / sizeof(pte)) {
975 			idx -= PAGE_SIZE / sizeof(pte);
976 			pte_addr += PAGE_SIZE;
977 		}
978 
979 		ptep = ptp_hold(hypctx->vcpu, pte_addr, PAGE_SIZE, &cookie);
980 		if (ptep == NULL)
981 			goto error;
982 		pte = ptep[idx];
983 
984 		/* Calculate the level we are looking at */
985 		switch (levels) {
986 		default:
987 			goto fault;
988 		/* TODO: Level -1 when FEAT_LPA2 is implemented */
989 		case 4: /* Level 0 */
990 			if ((pte & ATTR_DESCR_MASK) != L0_TABLE)
991 				goto fault;
992 			/* FALLTHROUGH */
993 		case 3: /* Level 1 */
994 		case 2: /* Level 2 */
995 			switch (pte & ATTR_DESCR_MASK) {
996 			/* Use L1 macro as all levels are the same */
997 			case L1_TABLE:
998 				/* Check if EL0 can access this address space */
999 				if (is_el0 &&
1000 				    (pte & TATTR_AP_TABLE_NO_EL0) != 0)
1001 					goto fault;
1002 				/* Check if the address space is writable */
1003 				if ((prot & PROT_WRITE) != 0 &&
1004 				    (pte & TATTR_AP_TABLE_RO) != 0)
1005 					goto fault;
1006 				if ((prot & PROT_EXEC) != 0) {
1007 					/* Check the table exec attribute */
1008 					if ((is_el0 &&
1009 					    (pte & TATTR_UXN_TABLE) != 0) ||
1010 					    (!is_el0 &&
1011 					     (pte & TATTR_PXN_TABLE) != 0))
1012 						goto fault;
1013 				}
1014 				pte_addr = pte & ~ATTR_MASK;
1015 				break;
1016 			case L1_BLOCK:
1017 				goto done;
1018 			default:
1019 				goto fault;
1020 			}
1021 			break;
1022 		case 1: /* Level 3 */
1023 			if ((pte & ATTR_DESCR_MASK) == L3_PAGE)
1024 				goto done;
1025 			goto fault;
1026 		}
1027 	}
1028 
1029 done:
1030 	/* Check if EL0 has access to the block/page */
1031 	if (is_el0 && (pte & ATTR_S1_AP(ATTR_S1_AP_USER)) == 0)
1032 		goto fault;
1033 	if ((prot & PROT_WRITE) != 0 && (pte & ATTR_S1_AP_RW_BIT) != 0)
1034 		goto fault;
1035 	if ((prot & PROT_EXEC) != 0) {
1036 		if ((is_el0 && (pte & ATTR_S1_UXN) != 0) ||
1037 		    (!is_el0 && (pte & ATTR_S1_PXN) != 0))
1038 			goto fault;
1039 	}
1040 	mask = (1ul << pte_shift) - 1;
1041 	*gpa = (pte & ~ATTR_MASK) | (gla & mask);
1042 	*is_fault = 0;
1043 	ptp_release(&cookie);
1044 	return (0);
1045 
1046 error:
1047 	ptp_release(&cookie);
1048 	return (EFAULT);
1049 fault:
1050 	*is_fault = 1;
1051 	ptp_release(&cookie);
1052 	return (0);
1053 }
1054 
1055 int
1056 vmmops_run(void *vcpui, register_t pc, pmap_t pmap, struct vm_eventinfo *evinfo)
1057 {
1058 	uint64_t excp_type;
1059 	int handled;
1060 	register_t daif;
1061 	struct hyp *hyp;
1062 	struct hypctx *hypctx;
1063 	struct vcpu *vcpu;
1064 	struct vm_exit *vme;
1065 	int mode;
1066 
1067 	hypctx = (struct hypctx *)vcpui;
1068 	hyp = hypctx->hyp;
1069 	vcpu = hypctx->vcpu;
1070 	vme = vm_exitinfo(vcpu);
1071 
1072 	hypctx->tf.tf_elr = (uint64_t)pc;
1073 
1074 	for (;;) {
1075 		if (hypctx->has_exception) {
1076 			hypctx->has_exception = false;
1077 			hypctx->elr_el1 = hypctx->tf.tf_elr;
1078 
1079 			mode = hypctx->tf.tf_spsr & (PSR_M_MASK | PSR_M_32);
1080 
1081 			if (mode == PSR_M_EL1t) {
1082 				hypctx->tf.tf_elr = hypctx->vbar_el1 + 0x0;
1083 			} else if (mode == PSR_M_EL1h) {
1084 				hypctx->tf.tf_elr = hypctx->vbar_el1 + 0x200;
1085 			} else if ((mode & PSR_M_32) == PSR_M_64) {
1086 				/* 64-bit EL0 */
1087 				hypctx->tf.tf_elr = hypctx->vbar_el1 + 0x400;
1088 			} else {
1089 				/* 32-bit EL0 */
1090 				hypctx->tf.tf_elr = hypctx->vbar_el1 + 0x600;
1091 			}
1092 
1093 			/* Set the new spsr */
1094 			hypctx->spsr_el1 = hypctx->tf.tf_spsr;
1095 
1096 			/* Set the new cpsr */
1097 			hypctx->tf.tf_spsr = hypctx->spsr_el1 & PSR_FLAGS;
1098 			hypctx->tf.tf_spsr |= PSR_DAIF | PSR_M_EL1h;
1099 
1100 			/*
1101 			 * Update fields that may change on exeption entry
1102 			 * based on how sctlr_el1 is configured.
1103 			 */
1104 			if ((hypctx->sctlr_el1 & SCTLR_SPAN) == 0)
1105 				hypctx->tf.tf_spsr |= PSR_PAN;
1106 			if ((hypctx->sctlr_el1 & SCTLR_DSSBS) == 0)
1107 				hypctx->tf.tf_spsr &= ~PSR_SSBS;
1108 			else
1109 				hypctx->tf.tf_spsr |= PSR_SSBS;
1110 		}
1111 
1112 		daif = intr_disable();
1113 
1114 		/* Check if the vcpu is suspended */
1115 		if (vcpu_suspended(evinfo)) {
1116 			intr_restore(daif);
1117 			vm_exit_suspended(vcpu, pc);
1118 			break;
1119 		}
1120 
1121 		if (vcpu_debugged(vcpu)) {
1122 			intr_restore(daif);
1123 			vm_exit_debug(vcpu, pc);
1124 			break;
1125 		}
1126 
1127 		/* Activate the stage2 pmap so the vmid is valid */
1128 		pmap_activate_vm(pmap);
1129 		hyp->vttbr_el2 = pmap_to_ttbr0(pmap);
1130 
1131 		/*
1132 		 * TODO: What happens if a timer interrupt is asserted exactly
1133 		 * here, but for the previous VM?
1134 		 */
1135 		arm64_set_active_vcpu(hypctx);
1136 		vgic_flush_hwstate(hypctx);
1137 
1138 		/* Call into EL2 to switch to the guest */
1139 		excp_type = vmm_enter_guest(hyp, hypctx);
1140 
1141 		vgic_sync_hwstate(hypctx);
1142 		vtimer_sync_hwstate(hypctx);
1143 
1144 		/*
1145 		 * Deactivate the stage2 pmap.
1146 		 */
1147 		PCPU_SET(curvmpmap, NULL);
1148 		intr_restore(daif);
1149 
1150 		vmm_stat_incr(vcpu, VMEXIT_COUNT, 1);
1151 		if (excp_type == EXCP_TYPE_MAINT_IRQ)
1152 			continue;
1153 
1154 		vme->pc = hypctx->tf.tf_elr;
1155 		vme->inst_length = INSN_SIZE;
1156 		vme->u.hyp.exception_nr = excp_type;
1157 		vme->u.hyp.esr_el2 = hypctx->tf.tf_esr;
1158 		vme->u.hyp.far_el2 = hypctx->exit_info.far_el2;
1159 		vme->u.hyp.hpfar_el2 = hypctx->exit_info.hpfar_el2;
1160 
1161 		handled = arm64_handle_world_switch(hypctx, excp_type, vme,
1162 		    pmap);
1163 		if (handled == UNHANDLED)
1164 			/* Exit loop to emulate instruction. */
1165 			break;
1166 		else
1167 			/* Resume guest execution from the next instruction. */
1168 			hypctx->tf.tf_elr += vme->inst_length;
1169 	}
1170 
1171 	return (0);
1172 }
1173 
1174 static void
1175 arm_pcpu_vmcleanup(void *arg)
1176 {
1177 	struct hyp *hyp;
1178 	int i, maxcpus;
1179 
1180 	hyp = arg;
1181 	maxcpus = vm_get_maxcpus(hyp->vm);
1182 	for (i = 0; i < maxcpus; i++) {
1183 		if (arm64_get_active_vcpu() == hyp->ctx[i]) {
1184 			arm64_set_active_vcpu(NULL);
1185 			break;
1186 		}
1187 	}
1188 }
1189 
1190 void
1191 vmmops_vcpu_cleanup(void *vcpui)
1192 {
1193 	struct hypctx *hypctx = vcpui;
1194 
1195 	vtimer_cpucleanup(hypctx);
1196 	vgic_cpucleanup(hypctx);
1197 
1198 	if (!in_vhe())
1199 		vmmpmap_remove(hypctx->el2_addr, el2_hypctx_size(), true);
1200 
1201 	free(hypctx, M_HYP);
1202 }
1203 
1204 void
1205 vmmops_cleanup(void *vmi)
1206 {
1207 	struct hyp *hyp = vmi;
1208 
1209 	vtimer_vmcleanup(hyp);
1210 	vgic_vmcleanup(hyp);
1211 
1212 	smp_rendezvous(NULL, arm_pcpu_vmcleanup, NULL, hyp);
1213 
1214 	if (!in_vhe())
1215 		vmmpmap_remove(hyp->el2_addr, el2_hyp_size(hyp->vm), true);
1216 
1217 	free(hyp, M_HYP);
1218 }
1219 
1220 /*
1221  * Return register value. Registers have different sizes and an explicit cast
1222  * must be made to ensure proper conversion.
1223  */
1224 static uint64_t *
1225 hypctx_regptr(struct hypctx *hypctx, int reg)
1226 {
1227 	switch (reg) {
1228 	case VM_REG_GUEST_X0 ... VM_REG_GUEST_X29:
1229 		return (&hypctx->tf.tf_x[reg]);
1230 	case VM_REG_GUEST_LR:
1231 		return (&hypctx->tf.tf_lr);
1232 	case VM_REG_GUEST_SP:
1233 		return (&hypctx->tf.tf_sp);
1234 	case VM_REG_GUEST_CPSR:
1235 		return (&hypctx->tf.tf_spsr);
1236 	case VM_REG_GUEST_PC:
1237 		return (&hypctx->tf.tf_elr);
1238 	case VM_REG_GUEST_SCTLR_EL1:
1239 		return (&hypctx->sctlr_el1);
1240 	case VM_REG_GUEST_TTBR0_EL1:
1241 		return (&hypctx->ttbr0_el1);
1242 	case VM_REG_GUEST_TTBR1_EL1:
1243 		return (&hypctx->ttbr1_el1);
1244 	case VM_REG_GUEST_TCR_EL1:
1245 		return (&hypctx->tcr_el1);
1246 	case VM_REG_GUEST_TCR2_EL1:
1247 		return (&hypctx->tcr2_el1);
1248 	default:
1249 		break;
1250 	}
1251 	return (NULL);
1252 }
1253 
1254 int
1255 vmmops_getreg(void *vcpui, int reg, uint64_t *retval)
1256 {
1257 	uint64_t *regp;
1258 	int running, hostcpu;
1259 	struct hypctx *hypctx = vcpui;
1260 
1261 	running = vcpu_is_running(hypctx->vcpu, &hostcpu);
1262 	if (running && hostcpu != curcpu)
1263 		panic("arm_getreg: %s%d is running", vm_name(hypctx->hyp->vm),
1264 		    vcpu_vcpuid(hypctx->vcpu));
1265 
1266 	regp = hypctx_regptr(hypctx, reg);
1267 	if (regp == NULL)
1268 		return (EINVAL);
1269 
1270 	*retval = *regp;
1271 	return (0);
1272 }
1273 
1274 int
1275 vmmops_setreg(void *vcpui, int reg, uint64_t val)
1276 {
1277 	uint64_t *regp;
1278 	struct hypctx *hypctx = vcpui;
1279 	int running, hostcpu;
1280 
1281 	running = vcpu_is_running(hypctx->vcpu, &hostcpu);
1282 	if (running && hostcpu != curcpu)
1283 		panic("arm_setreg: %s%d is running", vm_name(hypctx->hyp->vm),
1284 		    vcpu_vcpuid(hypctx->vcpu));
1285 
1286 	regp = hypctx_regptr(hypctx, reg);
1287 	if (regp == NULL)
1288 		return (EINVAL);
1289 
1290 	*regp = val;
1291 	return (0);
1292 }
1293 
1294 int
1295 vmmops_exception(void *vcpui, uint64_t esr, uint64_t far)
1296 {
1297 	struct hypctx *hypctx = vcpui;
1298 	int running, hostcpu;
1299 
1300 	running = vcpu_is_running(hypctx->vcpu, &hostcpu);
1301 	if (running && hostcpu != curcpu)
1302 		panic("%s: %s%d is running", __func__, vm_name(hypctx->hyp->vm),
1303 		    vcpu_vcpuid(hypctx->vcpu));
1304 
1305 	hypctx->far_el1 = far;
1306 	hypctx->esr_el1 = esr;
1307 	hypctx->has_exception = true;
1308 
1309 	return (0);
1310 }
1311 
1312 int
1313 vmmops_getcap(void *vcpui, int num, int *retval)
1314 {
1315 	struct hypctx *hypctx = vcpui;
1316 	int ret;
1317 
1318 	ret = ENOENT;
1319 
1320 	switch (num) {
1321 	case VM_CAP_UNRESTRICTED_GUEST:
1322 		*retval = 1;
1323 		ret = 0;
1324 		break;
1325 	case VM_CAP_BRK_EXIT:
1326 	case VM_CAP_SS_EXIT:
1327 	case VM_CAP_MASK_HWINTR:
1328 		*retval = (hypctx->setcaps & (1ul << num)) != 0;
1329 		break;
1330 	default:
1331 		break;
1332 	}
1333 
1334 	return (ret);
1335 }
1336 
1337 int
1338 vmmops_setcap(void *vcpui, int num, int val)
1339 {
1340 	struct hypctx *hypctx = vcpui;
1341 	int ret;
1342 
1343 	ret = 0;
1344 
1345 	switch (num) {
1346 	case VM_CAP_BRK_EXIT:
1347 		if ((val != 0) == ((hypctx->setcaps & (1ul << num)) != 0))
1348 			break;
1349 		if (val != 0)
1350 			hypctx->mdcr_el2 |= MDCR_EL2_TDE;
1351 		else
1352 			hypctx->mdcr_el2 &= ~MDCR_EL2_TDE;
1353 		break;
1354 	case VM_CAP_SS_EXIT:
1355 		if ((val != 0) == ((hypctx->setcaps & (1ul << num)) != 0))
1356 			break;
1357 
1358 		if (val != 0) {
1359 			hypctx->debug_spsr |= (hypctx->tf.tf_spsr & PSR_SS);
1360 			hypctx->debug_mdscr |= hypctx->mdscr_el1 &
1361 			    (MDSCR_SS | MDSCR_KDE);
1362 
1363 			hypctx->tf.tf_spsr |= PSR_SS;
1364 			hypctx->mdscr_el1 |= MDSCR_SS | MDSCR_KDE;
1365 			hypctx->mdcr_el2 |= MDCR_EL2_TDE;
1366 		} else {
1367 			hypctx->tf.tf_spsr &= ~PSR_SS;
1368 			hypctx->tf.tf_spsr |= hypctx->debug_spsr;
1369 			hypctx->debug_spsr &= ~PSR_SS;
1370 			hypctx->mdscr_el1 &= ~(MDSCR_SS | MDSCR_KDE);
1371 			hypctx->mdscr_el1 |= hypctx->debug_mdscr;
1372 			hypctx->debug_mdscr &= ~(MDSCR_SS | MDSCR_KDE);
1373 			hypctx->mdcr_el2 &= ~MDCR_EL2_TDE;
1374 		}
1375 		break;
1376 	case VM_CAP_MASK_HWINTR:
1377 		if ((val != 0) == ((hypctx->setcaps & (1ul << num)) != 0))
1378 			break;
1379 
1380 		if (val != 0) {
1381 			hypctx->debug_spsr |= (hypctx->tf.tf_spsr &
1382 			    (PSR_I | PSR_F));
1383 			hypctx->tf.tf_spsr |= PSR_I | PSR_F;
1384 		} else {
1385 			hypctx->tf.tf_spsr &= ~(PSR_I | PSR_F);
1386 			hypctx->tf.tf_spsr |= (hypctx->debug_spsr &
1387 			    (PSR_I | PSR_F));
1388 			hypctx->debug_spsr &= ~(PSR_I | PSR_F);
1389 		}
1390 		break;
1391 	default:
1392 		ret = ENOENT;
1393 		break;
1394 	}
1395 
1396 	if (ret == 0) {
1397 		if (val == 0)
1398 			hypctx->setcaps &= ~(1ul << num);
1399 		else
1400 			hypctx->setcaps |= (1ul << num);
1401 	}
1402 
1403 	return (ret);
1404 }
1405