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