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