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