xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision 0610f417a4a664b7e3a8c57de800ae1f326a40e3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
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 NETAPP, INC ``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 NETAPP, INC 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  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
37 #endif
38 #include <sys/mman.h>
39 #include <sys/time.h>
40 
41 #include <amd64/vmm/intel/vmcs.h>
42 
43 #include <machine/atomic.h>
44 #include <machine/segments.h>
45 
46 #ifndef WITHOUT_CAPSICUM
47 #include <capsicum_helpers.h>
48 #endif
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <libgen.h>
55 #include <unistd.h>
56 #include <assert.h>
57 #include <pthread.h>
58 #include <pthread_np.h>
59 #include <sysexits.h>
60 #include <stdbool.h>
61 #include <stdint.h>
62 
63 #include <machine/vmm.h>
64 #ifndef WITHOUT_CAPSICUM
65 #include <machine/vmm_dev.h>
66 #endif
67 #include <vmmapi.h>
68 
69 #include "bhyverun.h"
70 #include "acpi.h"
71 #include "atkbdc.h"
72 #include "inout.h"
73 #include "dbgport.h"
74 #include "fwctl.h"
75 #include "gdb.h"
76 #include "ioapic.h"
77 #include "mem.h"
78 #include "mevent.h"
79 #include "mptbl.h"
80 #include "pci_emul.h"
81 #include "pci_irq.h"
82 #include "pci_lpc.h"
83 #include "smbiostbl.h"
84 #include "xmsr.h"
85 #include "spinup_ap.h"
86 #include "rtc.h"
87 
88 #define GUEST_NIO_PORT		0x488	/* guest upcalls via i/o port */
89 
90 #define MB		(1024UL * 1024)
91 #define GB		(1024UL * MB)
92 
93 static const char * const vmx_exit_reason_desc[] = {
94 	[EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
95 	[EXIT_REASON_EXT_INTR] = "External interrupt",
96 	[EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
97 	[EXIT_REASON_INIT] = "INIT signal",
98 	[EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
99 	[EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
100 	[EXIT_REASON_SMI] = "Other SMI",
101 	[EXIT_REASON_INTR_WINDOW] = "Interrupt window",
102 	[EXIT_REASON_NMI_WINDOW] = "NMI window",
103 	[EXIT_REASON_TASK_SWITCH] = "Task switch",
104 	[EXIT_REASON_CPUID] = "CPUID",
105 	[EXIT_REASON_GETSEC] = "GETSEC",
106 	[EXIT_REASON_HLT] = "HLT",
107 	[EXIT_REASON_INVD] = "INVD",
108 	[EXIT_REASON_INVLPG] = "INVLPG",
109 	[EXIT_REASON_RDPMC] = "RDPMC",
110 	[EXIT_REASON_RDTSC] = "RDTSC",
111 	[EXIT_REASON_RSM] = "RSM",
112 	[EXIT_REASON_VMCALL] = "VMCALL",
113 	[EXIT_REASON_VMCLEAR] = "VMCLEAR",
114 	[EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
115 	[EXIT_REASON_VMPTRLD] = "VMPTRLD",
116 	[EXIT_REASON_VMPTRST] = "VMPTRST",
117 	[EXIT_REASON_VMREAD] = "VMREAD",
118 	[EXIT_REASON_VMRESUME] = "VMRESUME",
119 	[EXIT_REASON_VMWRITE] = "VMWRITE",
120 	[EXIT_REASON_VMXOFF] = "VMXOFF",
121 	[EXIT_REASON_VMXON] = "VMXON",
122 	[EXIT_REASON_CR_ACCESS] = "Control-register accesses",
123 	[EXIT_REASON_DR_ACCESS] = "MOV DR",
124 	[EXIT_REASON_INOUT] = "I/O instruction",
125 	[EXIT_REASON_RDMSR] = "RDMSR",
126 	[EXIT_REASON_WRMSR] = "WRMSR",
127 	[EXIT_REASON_INVAL_VMCS] =
128 	    "VM-entry failure due to invalid guest state",
129 	[EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
130 	[EXIT_REASON_MWAIT] = "MWAIT",
131 	[EXIT_REASON_MTF] = "Monitor trap flag",
132 	[EXIT_REASON_MONITOR] = "MONITOR",
133 	[EXIT_REASON_PAUSE] = "PAUSE",
134 	[EXIT_REASON_MCE_DURING_ENTRY] =
135 	    "VM-entry failure due to machine-check event",
136 	[EXIT_REASON_TPR] = "TPR below threshold",
137 	[EXIT_REASON_APIC_ACCESS] = "APIC access",
138 	[EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
139 	[EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
140 	[EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
141 	[EXIT_REASON_EPT_FAULT] = "EPT violation",
142 	[EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
143 	[EXIT_REASON_INVEPT] = "INVEPT",
144 	[EXIT_REASON_RDTSCP] = "RDTSCP",
145 	[EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
146 	[EXIT_REASON_INVVPID] = "INVVPID",
147 	[EXIT_REASON_WBINVD] = "WBINVD",
148 	[EXIT_REASON_XSETBV] = "XSETBV",
149 	[EXIT_REASON_APIC_WRITE] = "APIC write",
150 	[EXIT_REASON_RDRAND] = "RDRAND",
151 	[EXIT_REASON_INVPCID] = "INVPCID",
152 	[EXIT_REASON_VMFUNC] = "VMFUNC",
153 	[EXIT_REASON_ENCLS] = "ENCLS",
154 	[EXIT_REASON_RDSEED] = "RDSEED",
155 	[EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
156 	[EXIT_REASON_XSAVES] = "XSAVES",
157 	[EXIT_REASON_XRSTORS] = "XRSTORS"
158 };
159 
160 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
161 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
162 
163 char *vmname;
164 
165 int guest_ncpus;
166 uint16_t cores, maxcpus, sockets, threads;
167 
168 char *guest_uuid_str;
169 
170 static int gdb_port = 0;
171 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
172 static int virtio_msix = 1;
173 static int x2apic_mode = 0;	/* default is xAPIC */
174 
175 static int strictio;
176 static int strictmsr = 1;
177 
178 static int acpi;
179 
180 static char *progname;
181 static const int BSP = 0;
182 
183 static cpuset_t cpumask;
184 
185 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
186 
187 static struct vm_exit vmexit[VM_MAXCPU];
188 
189 struct bhyvestats {
190 	uint64_t	vmexit_bogus;
191 	uint64_t	vmexit_reqidle;
192 	uint64_t	vmexit_hlt;
193 	uint64_t	vmexit_pause;
194 	uint64_t	vmexit_mtrap;
195 	uint64_t	vmexit_inst_emul;
196 	uint64_t	cpu_switch_rotate;
197 	uint64_t	cpu_switch_direct;
198 } stats;
199 
200 struct mt_vmm_info {
201 	pthread_t	mt_thr;
202 	struct vmctx	*mt_ctx;
203 	int		mt_vcpu;
204 } mt_vmm_info[VM_MAXCPU];
205 
206 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
207 
208 static void
209 usage(int code)
210 {
211 
212         fprintf(stderr,
213 		"Usage: %s [-abehuwxACHPSWY]\n"
214 		"       %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
215 		"       %*s [-g <gdb port>] [-l <lpc>]\n"
216 		"       %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
217 		"       -a: local apic is in xAPIC mode (deprecated)\n"
218 		"       -A: create ACPI tables\n"
219 		"       -c: number of cpus and/or topology specification\n"
220 		"       -C: include guest memory in core file\n"
221 		"       -e: exit on unhandled I/O access\n"
222 		"       -g: gdb port\n"
223 		"       -h: help\n"
224 		"       -H: vmexit from the guest on hlt\n"
225 		"       -l: LPC device configuration\n"
226 		"       -m: memory size in MB\n"
227 		"       -p: pin 'vcpu' to 'hostcpu'\n"
228 		"       -P: vmexit from the guest on pause\n"
229 		"       -s: <slot,driver,configinfo> PCI slot config\n"
230 		"       -S: guest memory cannot be swapped\n"
231 		"       -u: RTC keeps UTC time\n"
232 		"       -U: uuid\n"
233 		"       -w: ignore unimplemented MSRs\n"
234 		"       -W: force virtio to use single-vector MSI\n"
235 		"       -x: local apic is in x2APIC mode\n"
236 		"       -Y: disable MPtable generation\n",
237 		progname, (int)strlen(progname), "", (int)strlen(progname), "",
238 		(int)strlen(progname), "");
239 
240 	exit(code);
241 }
242 
243 /*
244  * XXX This parser is known to have the following issues:
245  * 1.  It accepts null key=value tokens ",,".
246  * 2.  It accepts whitespace after = and before value.
247  * 3.  Values out of range of INT are silently wrapped.
248  * 4.  It doesn't check non-final values.
249  * 5.  The apparently bogus limits of UINT16_MAX are for future expansion.
250  *
251  * The acceptance of a null specification ('-c ""') is by design to match the
252  * manual page syntax specification, this results in a topology of 1 vCPU.
253  */
254 static int
255 topology_parse(const char *opt)
256 {
257 	uint64_t ncpus;
258 	int c, chk, n, s, t, tmp;
259 	char *cp, *str;
260 	bool ns, scts;
261 
262 	c = 1, n = 1, s = 1, t = 1;
263 	ns = false, scts = false;
264 	str = strdup(opt);
265 	if (str == NULL)
266 		goto out;
267 
268 	while ((cp = strsep(&str, ",")) != NULL) {
269 		if (sscanf(cp, "%i%n", &tmp, &chk) == 1) {
270 			n = tmp;
271 			ns = true;
272 		} else if (sscanf(cp, "cpus=%i%n", &tmp, &chk) == 1) {
273 			n = tmp;
274 			ns = true;
275 		} else if (sscanf(cp, "sockets=%i%n", &tmp, &chk) == 1) {
276 			s = tmp;
277 			scts = true;
278 		} else if (sscanf(cp, "cores=%i%n", &tmp, &chk) == 1) {
279 			c = tmp;
280 			scts = true;
281 		} else if (sscanf(cp, "threads=%i%n", &tmp, &chk) == 1) {
282 			t = tmp;
283 			scts = true;
284 #ifdef notyet  /* Do not expose this until vmm.ko implements it */
285 		} else if (sscanf(cp, "maxcpus=%i%n", &tmp, &chk) == 1) {
286 			m = tmp;
287 #endif
288 		/* Skip the empty argument case from -c "" */
289 		} else if (cp[0] == '\0')
290 			continue;
291 		else
292 			goto out;
293 		/* Any trailing garbage causes an error */
294 		if (cp[chk] != '\0')
295 			goto out;
296 	}
297 	free(str);
298 	str = NULL;
299 
300 	/*
301 	 * Range check 1 <= n <= UINT16_MAX all values
302 	 */
303 	if (n < 1 || s < 1 || c < 1 || t < 1 ||
304 	    n > UINT16_MAX || s > UINT16_MAX || c > UINT16_MAX  ||
305 	    t > UINT16_MAX)
306 		return (-1);
307 
308 	/* If only the cpus was specified, use that as sockets */
309 	if (!scts)
310 		s = n;
311 	/*
312 	 * Compute sockets * cores * threads avoiding overflow
313 	 * The range check above insures these are 16 bit values
314 	 * If n was specified check it against computed ncpus
315 	 */
316 	ncpus = (uint64_t)s * c * t;
317 	if (ncpus > UINT16_MAX || (ns && n != ncpus))
318 		return (-1);
319 
320 	guest_ncpus = ncpus;
321 	sockets = s;
322 	cores = c;
323 	threads = t;
324 	return(0);
325 
326 out:
327 	free(str);
328 	return (-1);
329 }
330 
331 static int
332 pincpu_parse(const char *opt)
333 {
334 	int vcpu, pcpu;
335 
336 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
337 		fprintf(stderr, "invalid format: %s\n", opt);
338 		return (-1);
339 	}
340 
341 	if (vcpu < 0 || vcpu >= VM_MAXCPU) {
342 		fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
343 		    vcpu, VM_MAXCPU - 1);
344 		return (-1);
345 	}
346 
347 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
348 		fprintf(stderr, "hostcpu '%d' outside valid range from "
349 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
350 		return (-1);
351 	}
352 
353 	if (vcpumap[vcpu] == NULL) {
354 		if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
355 			perror("malloc");
356 			return (-1);
357 		}
358 		CPU_ZERO(vcpumap[vcpu]);
359 	}
360 	CPU_SET(pcpu, vcpumap[vcpu]);
361 	return (0);
362 }
363 
364 void
365 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
366     int errcode)
367 {
368 	struct vmctx *ctx;
369 	int error, restart_instruction;
370 
371 	ctx = arg;
372 	restart_instruction = 1;
373 
374 	error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
375 	    restart_instruction);
376 	assert(error == 0);
377 }
378 
379 void *
380 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
381 {
382 
383 	return (vm_map_gpa(ctx, gaddr, len));
384 }
385 
386 int
387 fbsdrun_vmexit_on_pause(void)
388 {
389 
390 	return (guest_vmexit_on_pause);
391 }
392 
393 int
394 fbsdrun_vmexit_on_hlt(void)
395 {
396 
397 	return (guest_vmexit_on_hlt);
398 }
399 
400 int
401 fbsdrun_virtio_msix(void)
402 {
403 
404 	return (virtio_msix);
405 }
406 
407 static void *
408 fbsdrun_start_thread(void *param)
409 {
410 	char tname[MAXCOMLEN + 1];
411 	struct mt_vmm_info *mtp;
412 	int vcpu;
413 
414 	mtp = param;
415 	vcpu = mtp->mt_vcpu;
416 
417 	snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
418 	pthread_set_name_np(mtp->mt_thr, tname);
419 
420 	if (gdb_port != 0)
421 		gdb_cpu_add(vcpu);
422 
423 	vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
424 
425 	/* not reached */
426 	exit(1);
427 	return (NULL);
428 }
429 
430 void
431 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
432 {
433 	int error;
434 
435 	assert(fromcpu == BSP);
436 
437 	/*
438 	 * The 'newcpu' must be activated in the context of 'fromcpu'. If
439 	 * vm_activate_cpu() is delayed until newcpu's pthread starts running
440 	 * then vmm.ko is out-of-sync with bhyve and this can create a race
441 	 * with vm_suspend().
442 	 */
443 	error = vm_activate_cpu(ctx, newcpu);
444 	if (error != 0)
445 		err(EX_OSERR, "could not activate CPU %d", newcpu);
446 
447 	CPU_SET_ATOMIC(newcpu, &cpumask);
448 
449 	/*
450 	 * Set up the vmexit struct to allow execution to start
451 	 * at the given RIP
452 	 */
453 	vmexit[newcpu].rip = rip;
454 	vmexit[newcpu].inst_length = 0;
455 
456 	mt_vmm_info[newcpu].mt_ctx = ctx;
457 	mt_vmm_info[newcpu].mt_vcpu = newcpu;
458 
459 	error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
460 	    fbsdrun_start_thread, &mt_vmm_info[newcpu]);
461 	assert(error == 0);
462 }
463 
464 static int
465 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
466 {
467 
468 	if (!CPU_ISSET(vcpu, &cpumask)) {
469 		fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
470 		exit(4);
471 	}
472 
473 	CPU_CLR_ATOMIC(vcpu, &cpumask);
474 	return (CPU_EMPTY(&cpumask));
475 }
476 
477 static int
478 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
479 		     uint32_t eax)
480 {
481 #if BHYVE_DEBUG
482 	/*
483 	 * put guest-driven debug here
484 	 */
485 #endif
486 	return (VMEXIT_CONTINUE);
487 }
488 
489 static int
490 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
491 {
492 	int error;
493 	int bytes, port, in, out;
494 	int vcpu;
495 
496 	vcpu = *pvcpu;
497 
498 	port = vme->u.inout.port;
499 	bytes = vme->u.inout.bytes;
500 	in = vme->u.inout.in;
501 	out = !in;
502 
503         /* Extra-special case of host notifications */
504         if (out && port == GUEST_NIO_PORT) {
505                 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax);
506 		return (error);
507 	}
508 
509 	error = emulate_inout(ctx, vcpu, vme, strictio);
510 	if (error) {
511 		fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
512 		    in ? "in" : "out",
513 		    bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
514 		    port, vmexit->rip);
515 		return (VMEXIT_ABORT);
516 	} else {
517 		return (VMEXIT_CONTINUE);
518 	}
519 }
520 
521 static int
522 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
523 {
524 	uint64_t val;
525 	uint32_t eax, edx;
526 	int error;
527 
528 	val = 0;
529 	error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
530 	if (error != 0) {
531 		fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
532 		    vme->u.msr.code, *pvcpu);
533 		if (strictmsr) {
534 			vm_inject_gp(ctx, *pvcpu);
535 			return (VMEXIT_CONTINUE);
536 		}
537 	}
538 
539 	eax = val;
540 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
541 	assert(error == 0);
542 
543 	edx = val >> 32;
544 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
545 	assert(error == 0);
546 
547 	return (VMEXIT_CONTINUE);
548 }
549 
550 static int
551 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
552 {
553 	int error;
554 
555 	error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
556 	if (error != 0) {
557 		fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
558 		    vme->u.msr.code, vme->u.msr.wval, *pvcpu);
559 		if (strictmsr) {
560 			vm_inject_gp(ctx, *pvcpu);
561 			return (VMEXIT_CONTINUE);
562 		}
563 	}
564 	return (VMEXIT_CONTINUE);
565 }
566 
567 static int
568 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
569 {
570 
571 	(void)spinup_ap(ctx, *pvcpu,
572 		    vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
573 
574 	return (VMEXIT_CONTINUE);
575 }
576 
577 #define	DEBUG_EPT_MISCONFIG
578 #ifdef DEBUG_EPT_MISCONFIG
579 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
580 
581 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
582 static int ept_misconfig_ptenum;
583 #endif
584 
585 static const char *
586 vmexit_vmx_desc(uint32_t exit_reason)
587 {
588 
589 	if (exit_reason >= nitems(vmx_exit_reason_desc) ||
590 	    vmx_exit_reason_desc[exit_reason] == NULL)
591 		return ("Unknown");
592 	return (vmx_exit_reason_desc[exit_reason]);
593 }
594 
595 static int
596 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
597 {
598 
599 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
600 	fprintf(stderr, "\treason\t\tVMX\n");
601 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
602 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
603 	fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
604 	fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
605 	    vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
606 	fprintf(stderr, "\tqualification\t0x%016lx\n",
607 	    vmexit->u.vmx.exit_qualification);
608 	fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
609 	fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
610 #ifdef DEBUG_EPT_MISCONFIG
611 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
612 		vm_get_register(ctx, *pvcpu,
613 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
614 		    &ept_misconfig_gpa);
615 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
616 		    &ept_misconfig_ptenum);
617 		fprintf(stderr, "\tEPT misconfiguration:\n");
618 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
619 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
620 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
621 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
622 		    ept_misconfig_pte[3]);
623 	}
624 #endif	/* DEBUG_EPT_MISCONFIG */
625 	return (VMEXIT_ABORT);
626 }
627 
628 static int
629 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
630 {
631 
632 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
633 	fprintf(stderr, "\treason\t\tSVM\n");
634 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
635 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
636 	fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
637 	fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
638 	fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
639 	return (VMEXIT_ABORT);
640 }
641 
642 static int
643 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
644 {
645 
646 	assert(vmexit->inst_length == 0);
647 
648 	stats.vmexit_bogus++;
649 
650 	return (VMEXIT_CONTINUE);
651 }
652 
653 static int
654 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
655 {
656 
657 	assert(vmexit->inst_length == 0);
658 
659 	stats.vmexit_reqidle++;
660 
661 	return (VMEXIT_CONTINUE);
662 }
663 
664 static int
665 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
666 {
667 
668 	stats.vmexit_hlt++;
669 
670 	/*
671 	 * Just continue execution with the next instruction. We use
672 	 * the HLT VM exit as a way to be friendly with the host
673 	 * scheduler.
674 	 */
675 	return (VMEXIT_CONTINUE);
676 }
677 
678 static int
679 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
680 {
681 
682 	stats.vmexit_pause++;
683 
684 	return (VMEXIT_CONTINUE);
685 }
686 
687 static int
688 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
689 {
690 
691 	assert(vmexit->inst_length == 0);
692 
693 	stats.vmexit_mtrap++;
694 
695 	if (gdb_port == 0) {
696 		fprintf(stderr, "vm_loop: unexpected VMEXIT_MTRAP\n");
697 		exit(4);
698 	}
699 	gdb_cpu_mtrap(*pvcpu);
700 	return (VMEXIT_CONTINUE);
701 }
702 
703 static int
704 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
705 {
706 	int err, i;
707 	struct vie *vie;
708 
709 	stats.vmexit_inst_emul++;
710 
711 	vie = &vmexit->u.inst_emul.vie;
712 	err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
713 	    vie, &vmexit->u.inst_emul.paging);
714 
715 	if (err) {
716 		if (err == ESRCH) {
717 			fprintf(stderr, "Unhandled memory access to 0x%lx\n",
718 			    vmexit->u.inst_emul.gpa);
719 		}
720 
721 		fprintf(stderr, "Failed to emulate instruction [");
722 		for (i = 0; i < vie->num_valid; i++) {
723 			fprintf(stderr, "0x%02x%s", vie->inst[i],
724 			    i != (vie->num_valid - 1) ? " " : "");
725 		}
726 		fprintf(stderr, "] at 0x%lx\n", vmexit->rip);
727 		return (VMEXIT_ABORT);
728 	}
729 
730 	return (VMEXIT_CONTINUE);
731 }
732 
733 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
734 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
735 
736 static int
737 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
738 {
739 	enum vm_suspend_how how;
740 
741 	how = vmexit->u.suspended.how;
742 
743 	fbsdrun_deletecpu(ctx, *pvcpu);
744 
745 	if (*pvcpu != BSP) {
746 		pthread_mutex_lock(&resetcpu_mtx);
747 		pthread_cond_signal(&resetcpu_cond);
748 		pthread_mutex_unlock(&resetcpu_mtx);
749 		pthread_exit(NULL);
750 	}
751 
752 	pthread_mutex_lock(&resetcpu_mtx);
753 	while (!CPU_EMPTY(&cpumask)) {
754 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
755 	}
756 	pthread_mutex_unlock(&resetcpu_mtx);
757 
758 	switch (how) {
759 	case VM_SUSPEND_RESET:
760 		exit(0);
761 	case VM_SUSPEND_POWEROFF:
762 		exit(1);
763 	case VM_SUSPEND_HALT:
764 		exit(2);
765 	case VM_SUSPEND_TRIPLEFAULT:
766 		exit(3);
767 	default:
768 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
769 		exit(100);
770 	}
771 	return (0);	/* NOTREACHED */
772 }
773 
774 static int
775 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
776 {
777 
778 	if (gdb_port == 0) {
779 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
780 		exit(4);
781 	}
782 	gdb_cpu_suspend(*pvcpu);
783 	return (VMEXIT_CONTINUE);
784 }
785 
786 static int
787 vmexit_breakpoint(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
788 {
789 
790 	if (gdb_port == 0) {
791 		fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
792 		exit(4);
793 	}
794 	gdb_cpu_breakpoint(*pvcpu, vmexit);
795 	return (VMEXIT_CONTINUE);
796 }
797 
798 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
799 	[VM_EXITCODE_INOUT]  = vmexit_inout,
800 	[VM_EXITCODE_INOUT_STR]  = vmexit_inout,
801 	[VM_EXITCODE_VMX]    = vmexit_vmx,
802 	[VM_EXITCODE_SVM]    = vmexit_svm,
803 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
804 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
805 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
806 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
807 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
808 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
809 	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
810 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
811 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
812 	[VM_EXITCODE_DEBUG] = vmexit_debug,
813 	[VM_EXITCODE_BPT] = vmexit_breakpoint,
814 };
815 
816 static void
817 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
818 {
819 	int error, rc;
820 	enum vm_exitcode exitcode;
821 	cpuset_t active_cpus;
822 
823 	if (vcpumap[vcpu] != NULL) {
824 		error = pthread_setaffinity_np(pthread_self(),
825 		    sizeof(cpuset_t), vcpumap[vcpu]);
826 		assert(error == 0);
827 	}
828 
829 	error = vm_active_cpus(ctx, &active_cpus);
830 	assert(CPU_ISSET(vcpu, &active_cpus));
831 
832 	error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
833 	assert(error == 0);
834 
835 	while (1) {
836 		error = vm_run(ctx, vcpu, &vmexit[vcpu]);
837 		if (error != 0)
838 			break;
839 
840 		exitcode = vmexit[vcpu].exitcode;
841 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
842 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
843 			    exitcode);
844 			exit(4);
845 		}
846 
847 		rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
848 
849 		switch (rc) {
850 		case VMEXIT_CONTINUE:
851 			break;
852 		case VMEXIT_ABORT:
853 			abort();
854 		default:
855 			exit(4);
856 		}
857 	}
858 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
859 }
860 
861 static int
862 num_vcpus_allowed(struct vmctx *ctx)
863 {
864 	int tmp, error;
865 
866 	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
867 
868 	/*
869 	 * The guest is allowed to spinup more than one processor only if the
870 	 * UNRESTRICTED_GUEST capability is available.
871 	 */
872 	if (error == 0)
873 		return (VM_MAXCPU);
874 	else
875 		return (1);
876 }
877 
878 void
879 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
880 {
881 	int err, tmp;
882 
883 	if (fbsdrun_vmexit_on_hlt()) {
884 		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
885 		if (err < 0) {
886 			fprintf(stderr, "VM exit on HLT not supported\n");
887 			exit(4);
888 		}
889 		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
890 		if (cpu == BSP)
891 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
892 	}
893 
894         if (fbsdrun_vmexit_on_pause()) {
895 		/*
896 		 * pause exit support required for this mode
897 		 */
898 		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
899 		if (err < 0) {
900 			fprintf(stderr,
901 			    "SMP mux requested, no pause support\n");
902 			exit(4);
903 		}
904 		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
905 		if (cpu == BSP)
906 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
907         }
908 
909 	if (x2apic_mode)
910 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
911 	else
912 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
913 
914 	if (err) {
915 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
916 		exit(4);
917 	}
918 
919 	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
920 }
921 
922 static struct vmctx *
923 do_open(const char *vmname)
924 {
925 	struct vmctx *ctx;
926 	int error;
927 	bool reinit, romboot;
928 #ifndef WITHOUT_CAPSICUM
929 	cap_rights_t rights;
930 	const cap_ioctl_t *cmds;
931 	size_t ncmds;
932 #endif
933 
934 	reinit = romboot = false;
935 
936 	if (lpc_bootrom())
937 		romboot = true;
938 
939 	error = vm_create(vmname);
940 	if (error) {
941 		if (errno == EEXIST) {
942 			if (romboot) {
943 				reinit = true;
944 			} else {
945 				/*
946 				 * The virtual machine has been setup by the
947 				 * userspace bootloader.
948 				 */
949 			}
950 		} else {
951 			perror("vm_create");
952 			exit(4);
953 		}
954 	} else {
955 		if (!romboot) {
956 			/*
957 			 * If the virtual machine was just created then a
958 			 * bootrom must be configured to boot it.
959 			 */
960 			fprintf(stderr, "virtual machine cannot be booted\n");
961 			exit(4);
962 		}
963 	}
964 
965 	ctx = vm_open(vmname);
966 	if (ctx == NULL) {
967 		perror("vm_open");
968 		exit(4);
969 	}
970 
971 #ifndef WITHOUT_CAPSICUM
972 	cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
973 	if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1)
974 		errx(EX_OSERR, "Unable to apply rights for sandbox");
975 	vm_get_ioctls(&ncmds);
976 	cmds = vm_get_ioctls(NULL);
977 	if (cmds == NULL)
978 		errx(EX_OSERR, "out of memory");
979 	if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1)
980 		errx(EX_OSERR, "Unable to apply rights for sandbox");
981 	free((cap_ioctl_t *)cmds);
982 #endif
983 
984 	if (reinit) {
985 		error = vm_reinit(ctx);
986 		if (error) {
987 			perror("vm_reinit");
988 			exit(4);
989 		}
990 	}
991 	error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
992 	if (error)
993 		errx(EX_OSERR, "vm_set_topology");
994 	return (ctx);
995 }
996 
997 int
998 main(int argc, char *argv[])
999 {
1000 	int c, error, dbg_port, err, bvmcons;
1001 	int max_vcpus, mptgen, memflags;
1002 	int rtc_localtime;
1003 	bool gdb_stop;
1004 	struct vmctx *ctx;
1005 	uint64_t rip;
1006 	size_t memsize;
1007 	char *optstr;
1008 
1009 	bvmcons = 0;
1010 	progname = basename(argv[0]);
1011 	dbg_port = 0;
1012 	gdb_stop = false;
1013 	guest_ncpus = 1;
1014 	sockets = cores = threads = 1;
1015 	maxcpus = 0;
1016 	memsize = 256 * MB;
1017 	mptgen = 1;
1018 	rtc_localtime = 1;
1019 	memflags = 0;
1020 
1021 	optstr = "abehuwxACHIPSWYp:g:G:c:s:m:l:U:";
1022 	while ((c = getopt(argc, argv, optstr)) != -1) {
1023 		switch (c) {
1024 		case 'a':
1025 			x2apic_mode = 0;
1026 			break;
1027 		case 'A':
1028 			acpi = 1;
1029 			break;
1030 		case 'b':
1031 			bvmcons = 1;
1032 			break;
1033 		case 'p':
1034                         if (pincpu_parse(optarg) != 0) {
1035                             errx(EX_USAGE, "invalid vcpu pinning "
1036                                  "configuration '%s'", optarg);
1037                         }
1038 			break;
1039                 case 'c':
1040 			if (topology_parse(optarg) != 0) {
1041 			    errx(EX_USAGE, "invalid cpu topology "
1042 				"'%s'", optarg);
1043 			}
1044 			break;
1045 		case 'C':
1046 			memflags |= VM_MEM_F_INCORE;
1047 			break;
1048 		case 'g':
1049 			dbg_port = atoi(optarg);
1050 			break;
1051 		case 'G':
1052 			if (optarg[0] == 'w') {
1053 				gdb_stop = true;
1054 				optarg++;
1055 			}
1056 			gdb_port = atoi(optarg);
1057 			break;
1058 		case 'l':
1059 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1060 				lpc_print_supported_devices();
1061 				exit(0);
1062 			} else if (lpc_device_parse(optarg) != 0) {
1063 				errx(EX_USAGE, "invalid lpc device "
1064 				    "configuration '%s'", optarg);
1065 			}
1066 			break;
1067 		case 's':
1068 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1069 				pci_print_supported_devices();
1070 				exit(0);
1071 			} else if (pci_parse_slot(optarg) != 0)
1072 				exit(4);
1073 			else
1074 				break;
1075 		case 'S':
1076 			memflags |= VM_MEM_F_WIRED;
1077 			break;
1078                 case 'm':
1079 			error = vm_parse_memsize(optarg, &memsize);
1080 			if (error)
1081 				errx(EX_USAGE, "invalid memsize '%s'", optarg);
1082 			break;
1083 		case 'H':
1084 			guest_vmexit_on_hlt = 1;
1085 			break;
1086 		case 'I':
1087 			/*
1088 			 * The "-I" option was used to add an ioapic to the
1089 			 * virtual machine.
1090 			 *
1091 			 * An ioapic is now provided unconditionally for each
1092 			 * virtual machine and this option is now deprecated.
1093 			 */
1094 			break;
1095 		case 'P':
1096 			guest_vmexit_on_pause = 1;
1097 			break;
1098 		case 'e':
1099 			strictio = 1;
1100 			break;
1101 		case 'u':
1102 			rtc_localtime = 0;
1103 			break;
1104 		case 'U':
1105 			guest_uuid_str = optarg;
1106 			break;
1107 		case 'w':
1108 			strictmsr = 0;
1109 			break;
1110 		case 'W':
1111 			virtio_msix = 0;
1112 			break;
1113 		case 'x':
1114 			x2apic_mode = 1;
1115 			break;
1116 		case 'Y':
1117 			mptgen = 0;
1118 			break;
1119 		case 'h':
1120 			usage(0);
1121 		default:
1122 			usage(1);
1123 		}
1124 	}
1125 	argc -= optind;
1126 	argv += optind;
1127 
1128 	if (argc != 1)
1129 		usage(1);
1130 
1131 	vmname = argv[0];
1132 	ctx = do_open(vmname);
1133 
1134 	max_vcpus = num_vcpus_allowed(ctx);
1135 	if (guest_ncpus > max_vcpus) {
1136 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
1137 			guest_ncpus, max_vcpus);
1138 		exit(4);
1139 	}
1140 
1141 	fbsdrun_set_capabilities(ctx, BSP);
1142 
1143 	vm_set_memflags(ctx, memflags);
1144 	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1145 	if (err) {
1146 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1147 		exit(4);
1148 	}
1149 
1150 	error = init_msr();
1151 	if (error) {
1152 		fprintf(stderr, "init_msr error %d", error);
1153 		exit(4);
1154 	}
1155 
1156 	init_mem();
1157 	init_inout();
1158 	atkbdc_init(ctx);
1159 	pci_irq_init(ctx);
1160 	ioapic_init(ctx);
1161 
1162 	rtc_init(ctx, rtc_localtime);
1163 	sci_init(ctx);
1164 
1165 	/*
1166 	 * Exit if a device emulation finds an error in its initilization
1167 	 */
1168 	if (init_pci(ctx) != 0) {
1169 		perror("device emulation initialization error");
1170 		exit(4);
1171 	}
1172 
1173 	if (dbg_port != 0)
1174 		init_dbgport(dbg_port);
1175 
1176 	if (gdb_port != 0)
1177 		init_gdb(ctx, gdb_port, gdb_stop);
1178 
1179 	if (bvmcons)
1180 		init_bvmcons();
1181 
1182 	if (lpc_bootrom()) {
1183 		if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1184 			fprintf(stderr, "ROM boot failed: unrestricted guest "
1185 			    "capability not available\n");
1186 			exit(4);
1187 		}
1188 		error = vcpu_reset(ctx, BSP);
1189 		assert(error == 0);
1190 	}
1191 
1192 	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1193 	assert(error == 0);
1194 
1195 	/*
1196 	 * build the guest tables, MP etc.
1197 	 */
1198 	if (mptgen) {
1199 		error = mptable_build(ctx, guest_ncpus);
1200 		if (error) {
1201 			perror("error to build the guest tables");
1202 			exit(4);
1203 		}
1204 	}
1205 
1206 	error = smbios_build(ctx);
1207 	assert(error == 0);
1208 
1209 	if (acpi) {
1210 		error = acpi_build(ctx, guest_ncpus);
1211 		assert(error == 0);
1212 	}
1213 
1214 	if (lpc_bootrom())
1215 		fwctl_init();
1216 
1217 	/*
1218 	 * Change the proc title to include the VM name.
1219 	 */
1220 	setproctitle("%s", vmname);
1221 
1222 #ifndef WITHOUT_CAPSICUM
1223 	caph_cache_catpages();
1224 
1225 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1226 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1227 
1228 	if (caph_enter() == -1)
1229 		errx(EX_OSERR, "cap_enter() failed");
1230 #endif
1231 
1232 	/*
1233 	 * Add CPU 0
1234 	 */
1235 	fbsdrun_addcpu(ctx, BSP, BSP, rip);
1236 
1237 	/*
1238 	 * Head off to the main event dispatch loop
1239 	 */
1240 	mevent_dispatch();
1241 
1242 	exit(4);
1243 }
1244