xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision 4d846d26)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
37 #endif
38 #include <sys/mman.h>
39 #ifdef BHYVE_SNAPSHOT
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #endif
43 #include <sys/time.h>
44 #ifdef BHYVE_SNAPSHOT
45 #include <sys/un.h>
46 #endif
47 
48 #include <amd64/vmm/intel/vmcs.h>
49 #include <x86/apicreg.h>
50 
51 #include <machine/atomic.h>
52 #include <machine/segments.h>
53 
54 #ifndef WITHOUT_CAPSICUM
55 #include <capsicum_helpers.h>
56 #endif
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <err.h>
61 #include <errno.h>
62 #ifdef BHYVE_SNAPSHOT
63 #include <fcntl.h>
64 #endif
65 #include <libgen.h>
66 #include <unistd.h>
67 #include <assert.h>
68 #include <pthread.h>
69 #include <pthread_np.h>
70 #include <sysexits.h>
71 #include <stdbool.h>
72 #include <stdint.h>
73 #ifdef BHYVE_SNAPSHOT
74 #include <ucl.h>
75 #include <unistd.h>
76 
77 #include <libxo/xo.h>
78 #endif
79 
80 #include <machine/vmm.h>
81 #ifndef WITHOUT_CAPSICUM
82 #include <machine/vmm_dev.h>
83 #endif
84 #include <machine/vmm_instruction_emul.h>
85 #include <vmmapi.h>
86 
87 #include "bhyverun.h"
88 #include "acpi.h"
89 #include "atkbdc.h"
90 #include "bootrom.h"
91 #include "config.h"
92 #include "inout.h"
93 #include "debug.h"
94 #include "e820.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 "qemu_fwcfg.h"
106 #include "smbiostbl.h"
107 #ifdef BHYVE_SNAPSHOT
108 #include "snapshot.h"
109 #endif
110 #include "xmsr.h"
111 #include "spinup_ap.h"
112 #include "rtc.h"
113 #include "vmgenc.h"
114 
115 #define GUEST_NIO_PORT		0x488	/* guest upcalls via i/o port */
116 
117 #define MB		(1024UL * 1024)
118 #define GB		(1024UL * MB)
119 
120 static const char * const vmx_exit_reason_desc[] = {
121 	[EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
122 	[EXIT_REASON_EXT_INTR] = "External interrupt",
123 	[EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
124 	[EXIT_REASON_INIT] = "INIT signal",
125 	[EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
126 	[EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
127 	[EXIT_REASON_SMI] = "Other SMI",
128 	[EXIT_REASON_INTR_WINDOW] = "Interrupt window",
129 	[EXIT_REASON_NMI_WINDOW] = "NMI window",
130 	[EXIT_REASON_TASK_SWITCH] = "Task switch",
131 	[EXIT_REASON_CPUID] = "CPUID",
132 	[EXIT_REASON_GETSEC] = "GETSEC",
133 	[EXIT_REASON_HLT] = "HLT",
134 	[EXIT_REASON_INVD] = "INVD",
135 	[EXIT_REASON_INVLPG] = "INVLPG",
136 	[EXIT_REASON_RDPMC] = "RDPMC",
137 	[EXIT_REASON_RDTSC] = "RDTSC",
138 	[EXIT_REASON_RSM] = "RSM",
139 	[EXIT_REASON_VMCALL] = "VMCALL",
140 	[EXIT_REASON_VMCLEAR] = "VMCLEAR",
141 	[EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
142 	[EXIT_REASON_VMPTRLD] = "VMPTRLD",
143 	[EXIT_REASON_VMPTRST] = "VMPTRST",
144 	[EXIT_REASON_VMREAD] = "VMREAD",
145 	[EXIT_REASON_VMRESUME] = "VMRESUME",
146 	[EXIT_REASON_VMWRITE] = "VMWRITE",
147 	[EXIT_REASON_VMXOFF] = "VMXOFF",
148 	[EXIT_REASON_VMXON] = "VMXON",
149 	[EXIT_REASON_CR_ACCESS] = "Control-register accesses",
150 	[EXIT_REASON_DR_ACCESS] = "MOV DR",
151 	[EXIT_REASON_INOUT] = "I/O instruction",
152 	[EXIT_REASON_RDMSR] = "RDMSR",
153 	[EXIT_REASON_WRMSR] = "WRMSR",
154 	[EXIT_REASON_INVAL_VMCS] =
155 	    "VM-entry failure due to invalid guest state",
156 	[EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
157 	[EXIT_REASON_MWAIT] = "MWAIT",
158 	[EXIT_REASON_MTF] = "Monitor trap flag",
159 	[EXIT_REASON_MONITOR] = "MONITOR",
160 	[EXIT_REASON_PAUSE] = "PAUSE",
161 	[EXIT_REASON_MCE_DURING_ENTRY] =
162 	    "VM-entry failure due to machine-check event",
163 	[EXIT_REASON_TPR] = "TPR below threshold",
164 	[EXIT_REASON_APIC_ACCESS] = "APIC access",
165 	[EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
166 	[EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
167 	[EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
168 	[EXIT_REASON_EPT_FAULT] = "EPT violation",
169 	[EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
170 	[EXIT_REASON_INVEPT] = "INVEPT",
171 	[EXIT_REASON_RDTSCP] = "RDTSCP",
172 	[EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
173 	[EXIT_REASON_INVVPID] = "INVVPID",
174 	[EXIT_REASON_WBINVD] = "WBINVD",
175 	[EXIT_REASON_XSETBV] = "XSETBV",
176 	[EXIT_REASON_APIC_WRITE] = "APIC write",
177 	[EXIT_REASON_RDRAND] = "RDRAND",
178 	[EXIT_REASON_INVPCID] = "INVPCID",
179 	[EXIT_REASON_VMFUNC] = "VMFUNC",
180 	[EXIT_REASON_ENCLS] = "ENCLS",
181 	[EXIT_REASON_RDSEED] = "RDSEED",
182 	[EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
183 	[EXIT_REASON_XSAVES] = "XSAVES",
184 	[EXIT_REASON_XRSTORS] = "XRSTORS"
185 };
186 
187 typedef int (*vmexit_handler_t)(struct vmctx *, struct vcpu *, struct vm_exit *);
188 
189 int guest_ncpus;
190 uint16_t cpu_cores, cpu_sockets, cpu_threads;
191 
192 int raw_stdio = 0;
193 
194 static char *progname;
195 static const int BSP = 0;
196 
197 static cpuset_t cpumask;
198 
199 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
200 
201 static struct bhyvestats {
202 	uint64_t	vmexit_bogus;
203 	uint64_t	vmexit_reqidle;
204 	uint64_t	vmexit_hlt;
205 	uint64_t	vmexit_pause;
206 	uint64_t	vmexit_mtrap;
207 	uint64_t	vmexit_inst_emul;
208 	uint64_t	cpu_switch_rotate;
209 	uint64_t	cpu_switch_direct;
210 } stats;
211 
212 static struct vcpu_info {
213 	struct vmctx	*ctx;
214 	struct vcpu	*vcpu;
215 	int		vcpuid;
216 } *vcpu_info;
217 
218 static cpuset_t **vcpumap;
219 
220 static void
221 usage(int code)
222 {
223 
224         fprintf(stderr,
225 		"Usage: %s [-AaCDeHhPSuWwxY]\n"
226 		"       %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
227 		"       %*s [-G port] [-k config_file] [-l lpc] [-m mem] [-o var=value]\n"
228 		"       %*s [-p vcpu:hostcpu] [-r file] [-s pci] [-U uuid] vmname\n"
229 		"       -A: create ACPI tables\n"
230 		"       -a: local apic is in xAPIC mode (deprecated)\n"
231 		"       -C: include guest memory in core file\n"
232 		"       -c: number of CPUs and/or topology specification\n"
233 		"       -D: destroy on power-off\n"
234 		"       -e: exit on unhandled I/O access\n"
235 		"       -G: start a debug server\n"
236 		"       -H: vmexit from the guest on HLT\n"
237 		"       -h: help\n"
238 		"       -k: key=value flat config file\n"
239 		"       -K: PS2 keyboard layout\n"
240 		"       -l: LPC device configuration\n"
241 		"       -m: memory size\n"
242 		"       -o: set config 'var' to 'value'\n"
243 		"       -P: vmexit from the guest on pause\n"
244 		"       -p: pin 'vcpu' to 'hostcpu'\n"
245 #ifdef BHYVE_SNAPSHOT
246 		"       -r: path to checkpoint file\n"
247 #endif
248 		"       -S: guest memory cannot be swapped\n"
249 		"       -s: <slot,driver,configinfo> PCI slot config\n"
250 		"       -U: UUID\n"
251 		"       -u: RTC keeps UTC time\n"
252 		"       -W: force virtio to use single-vector MSI\n"
253 		"       -w: ignore unimplemented MSRs\n"
254 		"       -x: local APIC is in x2APIC mode\n"
255 		"       -Y: disable MPtable generation\n",
256 		progname, (int)strlen(progname), "", (int)strlen(progname), "",
257 		(int)strlen(progname), "");
258 
259 	exit(code);
260 }
261 
262 /*
263  * XXX This parser is known to have the following issues:
264  * 1.  It accepts null key=value tokens ",," as setting "cpus" to an
265  *     empty string.
266  *
267  * The acceptance of a null specification ('-c ""') is by design to match the
268  * manual page syntax specification, this results in a topology of 1 vCPU.
269  */
270 static int
271 topology_parse(const char *opt)
272 {
273 	char *cp, *str, *tofree;
274 
275 	if (*opt == '\0') {
276 		set_config_value("sockets", "1");
277 		set_config_value("cores", "1");
278 		set_config_value("threads", "1");
279 		set_config_value("cpus", "1");
280 		return (0);
281 	}
282 
283 	tofree = str = strdup(opt);
284 	if (str == NULL)
285 		errx(4, "Failed to allocate memory");
286 
287 	while ((cp = strsep(&str, ",")) != NULL) {
288 		if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
289 			set_config_value("cpus", cp + strlen("cpus="));
290 		else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
291 			set_config_value("sockets", cp + strlen("sockets="));
292 		else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
293 			set_config_value("cores", cp + strlen("cores="));
294 		else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
295 			set_config_value("threads", cp + strlen("threads="));
296 #ifdef notyet  /* Do not expose this until vmm.ko implements it */
297 		else if (strncmp(cp, "maxcpus=", strlen("maxcpus=")) == 0)
298 			set_config_value("maxcpus", cp + strlen("maxcpus="));
299 #endif
300 		else if (strchr(cp, '=') != NULL)
301 			goto out;
302 		else
303 			set_config_value("cpus", cp);
304 	}
305 	free(tofree);
306 	return (0);
307 
308 out:
309 	free(tofree);
310 	return (-1);
311 }
312 
313 static int
314 parse_int_value(const char *key, const char *value, int minval, int maxval)
315 {
316 	char *cp;
317 	long lval;
318 
319 	errno = 0;
320 	lval = strtol(value, &cp, 0);
321 	if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
322 	    lval > maxval)
323 		errx(4, "Invalid value for %s: '%s'", key, value);
324 	return (lval);
325 }
326 
327 /*
328  * Set the sockets, cores, threads, and guest_cpus variables based on
329  * the configured topology.
330  *
331  * The limits of UINT16_MAX are due to the types passed to
332  * vm_set_topology().  vmm.ko may enforce tighter limits.
333  */
334 static void
335 calc_topology(void)
336 {
337 	const char *value;
338 	bool explicit_cpus;
339 	uint64_t ncpus;
340 
341 	value = get_config_value("cpus");
342 	if (value != NULL) {
343 		guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
344 		explicit_cpus = true;
345 	} else {
346 		guest_ncpus = 1;
347 		explicit_cpus = false;
348 	}
349 	value = get_config_value("cores");
350 	if (value != NULL)
351 		cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
352 	else
353 		cpu_cores = 1;
354 	value = get_config_value("threads");
355 	if (value != NULL)
356 		cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
357 	else
358 		cpu_threads = 1;
359 	value = get_config_value("sockets");
360 	if (value != NULL)
361 		cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
362 	else
363 		cpu_sockets = guest_ncpus;
364 
365 	/*
366 	 * Compute sockets * cores * threads avoiding overflow.  The
367 	 * range check above insures these are 16 bit values.
368 	 */
369 	ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
370 	if (ncpus > UINT16_MAX)
371 		errx(4, "Computed number of vCPUs too high: %ju",
372 		    (uintmax_t)ncpus);
373 
374 	if (explicit_cpus) {
375 		if (guest_ncpus != (int)ncpus)
376 			errx(4, "Topology (%d sockets, %d cores, %d threads) "
377 			    "does not match %d vCPUs",
378 			    cpu_sockets, cpu_cores, cpu_threads,
379 			    guest_ncpus);
380 	} else
381 		guest_ncpus = ncpus;
382 }
383 
384 static int
385 pincpu_parse(const char *opt)
386 {
387 	const char *value;
388 	char *newval;
389 	char key[16];
390 	int vcpu, pcpu;
391 
392 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
393 		fprintf(stderr, "invalid format: %s\n", opt);
394 		return (-1);
395 	}
396 
397 	if (vcpu < 0) {
398 		fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
399 		return (-1);
400 	}
401 
402 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
403 		fprintf(stderr, "hostcpu '%d' outside valid range from "
404 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
405 		return (-1);
406 	}
407 
408 	snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
409 	value = get_config_value(key);
410 
411 	if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
412 	    value != NULL ? "," : "", pcpu) == -1) {
413 		perror("failed to build new cpuset string");
414 		return (-1);
415 	}
416 
417 	set_config_value(key, newval);
418 	free(newval);
419 	return (0);
420 }
421 
422 static void
423 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
424 {
425 	char *cp, *token;
426 	int pcpu, start;
427 
428 	CPU_ZERO(set);
429 	start = -1;
430 	token = __DECONST(char *, list);
431 	for (;;) {
432 		pcpu = strtoul(token, &cp, 0);
433 		if (cp == token)
434 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
435 		if (pcpu < 0 || pcpu >= CPU_SETSIZE)
436 			errx(4, "hostcpu '%d' outside valid range from 0 to %d",
437 			    pcpu, CPU_SETSIZE - 1);
438 		switch (*cp) {
439 		case ',':
440 		case '\0':
441 			if (start >= 0) {
442 				if (start > pcpu)
443 					errx(4, "Invalid hostcpu range %d-%d",
444 					    start, pcpu);
445 				while (start < pcpu) {
446 					CPU_SET(start, set);
447 					start++;
448 				}
449 				start = -1;
450 			}
451 			CPU_SET(pcpu, set);
452 			break;
453 		case '-':
454 			if (start >= 0)
455 				errx(4, "invalid cpuset for vcpu %d: '%s'",
456 				    vcpu, list);
457 			start = pcpu;
458 			break;
459 		default:
460 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
461 		}
462 		if (*cp == '\0')
463 			break;
464 		token = cp + 1;
465 	}
466 }
467 
468 static void
469 build_vcpumaps(void)
470 {
471 	char key[16];
472 	const char *value;
473 	int vcpu;
474 
475 	vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
476 	for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
477 		snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
478 		value = get_config_value(key);
479 		if (value == NULL)
480 			continue;
481 		vcpumap[vcpu] = malloc(sizeof(cpuset_t));
482 		if (vcpumap[vcpu] == NULL)
483 			err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
484 		parse_cpuset(vcpu, value, vcpumap[vcpu]);
485 	}
486 }
487 
488 void
489 vm_inject_fault(struct vcpu *vcpu, int vector, int errcode_valid,
490     int errcode)
491 {
492 	int error, restart_instruction;
493 
494 	restart_instruction = 1;
495 
496 	error = vm_inject_exception(vcpu, vector, errcode_valid, errcode,
497 	    restart_instruction);
498 	assert(error == 0);
499 }
500 
501 void *
502 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
503 {
504 
505 	return (vm_map_gpa(ctx, gaddr, len));
506 }
507 
508 #ifdef BHYVE_SNAPSHOT
509 uintptr_t
510 paddr_host2guest(struct vmctx *ctx, void *addr)
511 {
512 	return (vm_rev_map_gpa(ctx, addr));
513 }
514 #endif
515 
516 int
517 fbsdrun_virtio_msix(void)
518 {
519 
520 	return (get_config_bool_default("virtio_msix", true));
521 }
522 
523 static void *
524 fbsdrun_start_thread(void *param)
525 {
526 	char tname[MAXCOMLEN + 1];
527 	struct vcpu_info *vi = param;
528 	int error;
529 
530 	snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
531 	pthread_set_name_np(pthread_self(), tname);
532 
533 	if (vcpumap[vi->vcpuid] != NULL) {
534 		error = pthread_setaffinity_np(pthread_self(),
535 		    sizeof(cpuset_t), vcpumap[vi->vcpuid]);
536 		assert(error == 0);
537 	}
538 
539 #ifdef BHYVE_SNAPSHOT
540 	checkpoint_cpu_add(vi->vcpuid);
541 #endif
542 	gdb_cpu_add(vi->vcpu);
543 
544 	vm_loop(vi->ctx, vi->vcpu);
545 
546 	/* not reached */
547 	exit(1);
548 	return (NULL);
549 }
550 
551 static void
552 fbsdrun_addcpu(struct vcpu_info *vi)
553 {
554 	pthread_t thr;
555 	int error;
556 
557 	error = vm_activate_cpu(vi->vcpu);
558 	if (error != 0)
559 		err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
560 
561 	CPU_SET_ATOMIC(vi->vcpuid, &cpumask);
562 
563 	vm_suspend_cpu(vi->vcpu);
564 
565 	error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
566 	assert(error == 0);
567 }
568 
569 static int
570 fbsdrun_deletecpu(int vcpu)
571 {
572 
573 	if (!CPU_ISSET(vcpu, &cpumask)) {
574 		fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
575 		exit(4);
576 	}
577 
578 	CPU_CLR_ATOMIC(vcpu, &cpumask);
579 	return (CPU_EMPTY(&cpumask));
580 }
581 
582 static int
583 vmexit_handle_notify(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
584     struct vm_exit *vme __unused, uint32_t eax __unused)
585 {
586 #if BHYVE_DEBUG
587 	/*
588 	 * put guest-driven debug here
589 	 */
590 #endif
591 	return (VMEXIT_CONTINUE);
592 }
593 
594 static int
595 vmexit_inout(struct vmctx *ctx, struct vcpu *vcpu, struct vm_exit *vme)
596 {
597 	int error;
598 	int bytes, port, in, out;
599 
600 	port = vme->u.inout.port;
601 	bytes = vme->u.inout.bytes;
602 	in = vme->u.inout.in;
603 	out = !in;
604 
605         /* Extra-special case of host notifications */
606         if (out && port == GUEST_NIO_PORT) {
607                 error = vmexit_handle_notify(ctx, vcpu, vme, vme->u.inout.eax);
608 		return (error);
609 	}
610 
611 	error = emulate_inout(ctx, vcpu, vme);
612 	if (error) {
613 		fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
614 		    in ? "in" : "out",
615 		    bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
616 		    port, vme->rip);
617 		return (VMEXIT_ABORT);
618 	} else {
619 		return (VMEXIT_CONTINUE);
620 	}
621 }
622 
623 static int
624 vmexit_rdmsr(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_exit *vme)
625 {
626 	uint64_t val;
627 	uint32_t eax, edx;
628 	int error;
629 
630 	val = 0;
631 	error = emulate_rdmsr(vcpu, vme->u.msr.code, &val);
632 	if (error != 0) {
633 		fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
634 		    vme->u.msr.code, vcpu_id(vcpu));
635 		if (get_config_bool("x86.strictmsr")) {
636 			vm_inject_gp(vcpu);
637 			return (VMEXIT_CONTINUE);
638 		}
639 	}
640 
641 	eax = val;
642 	error = vm_set_register(vcpu, VM_REG_GUEST_RAX, eax);
643 	assert(error == 0);
644 
645 	edx = val >> 32;
646 	error = vm_set_register(vcpu, VM_REG_GUEST_RDX, edx);
647 	assert(error == 0);
648 
649 	return (VMEXIT_CONTINUE);
650 }
651 
652 static int
653 vmexit_wrmsr(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_exit *vme)
654 {
655 	int error;
656 
657 	error = emulate_wrmsr(vcpu, vme->u.msr.code, vme->u.msr.wval);
658 	if (error != 0) {
659 		fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
660 		    vme->u.msr.code, vme->u.msr.wval, vcpu_id(vcpu));
661 		if (get_config_bool("x86.strictmsr")) {
662 			vm_inject_gp(vcpu);
663 			return (VMEXIT_CONTINUE);
664 		}
665 	}
666 	return (VMEXIT_CONTINUE);
667 }
668 
669 #define	DEBUG_EPT_MISCONFIG
670 #ifdef DEBUG_EPT_MISCONFIG
671 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
672 
673 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
674 static int ept_misconfig_ptenum;
675 #endif
676 
677 static const char *
678 vmexit_vmx_desc(uint32_t exit_reason)
679 {
680 
681 	if (exit_reason >= nitems(vmx_exit_reason_desc) ||
682 	    vmx_exit_reason_desc[exit_reason] == NULL)
683 		return ("Unknown");
684 	return (vmx_exit_reason_desc[exit_reason]);
685 }
686 
687 static int
688 vmexit_vmx(struct vmctx *ctx, struct vcpu *vcpu, struct vm_exit *vme)
689 {
690 
691 	fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
692 	fprintf(stderr, "\treason\t\tVMX\n");
693 	fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
694 	fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
695 	fprintf(stderr, "\tstatus\t\t%d\n", vme->u.vmx.status);
696 	fprintf(stderr, "\texit_reason\t%u (%s)\n", vme->u.vmx.exit_reason,
697 	    vmexit_vmx_desc(vme->u.vmx.exit_reason));
698 	fprintf(stderr, "\tqualification\t0x%016lx\n",
699 	    vme->u.vmx.exit_qualification);
700 	fprintf(stderr, "\tinst_type\t\t%d\n", vme->u.vmx.inst_type);
701 	fprintf(stderr, "\tinst_error\t\t%d\n", vme->u.vmx.inst_error);
702 #ifdef DEBUG_EPT_MISCONFIG
703 	if (vme->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
704 		vm_get_register(vcpu,
705 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
706 		    &ept_misconfig_gpa);
707 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
708 		    &ept_misconfig_ptenum);
709 		fprintf(stderr, "\tEPT misconfiguration:\n");
710 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
711 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
712 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
713 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
714 		    ept_misconfig_pte[3]);
715 	}
716 #endif	/* DEBUG_EPT_MISCONFIG */
717 	return (VMEXIT_ABORT);
718 }
719 
720 static int
721 vmexit_svm(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_exit *vme)
722 {
723 
724 	fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
725 	fprintf(stderr, "\treason\t\tSVM\n");
726 	fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
727 	fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
728 	fprintf(stderr, "\texitcode\t%#lx\n", vme->u.svm.exitcode);
729 	fprintf(stderr, "\texitinfo1\t%#lx\n", vme->u.svm.exitinfo1);
730 	fprintf(stderr, "\texitinfo2\t%#lx\n", vme->u.svm.exitinfo2);
731 	return (VMEXIT_ABORT);
732 }
733 
734 static int
735 vmexit_bogus(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
736     struct vm_exit *vme)
737 {
738 
739 	assert(vme->inst_length == 0);
740 
741 	stats.vmexit_bogus++;
742 
743 	return (VMEXIT_CONTINUE);
744 }
745 
746 static int
747 vmexit_reqidle(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
748     struct vm_exit *vme)
749 {
750 
751 	assert(vme->inst_length == 0);
752 
753 	stats.vmexit_reqidle++;
754 
755 	return (VMEXIT_CONTINUE);
756 }
757 
758 static int
759 vmexit_hlt(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
760     struct vm_exit *vme __unused)
761 {
762 
763 	stats.vmexit_hlt++;
764 
765 	/*
766 	 * Just continue execution with the next instruction. We use
767 	 * the HLT VM exit as a way to be friendly with the host
768 	 * scheduler.
769 	 */
770 	return (VMEXIT_CONTINUE);
771 }
772 
773 static int
774 vmexit_pause(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
775     struct vm_exit *vme __unused)
776 {
777 
778 	stats.vmexit_pause++;
779 
780 	return (VMEXIT_CONTINUE);
781 }
782 
783 static int
784 vmexit_mtrap(struct vmctx *ctx __unused, struct vcpu *vcpu,
785     struct vm_exit *vme)
786 {
787 
788 	assert(vme->inst_length == 0);
789 
790 	stats.vmexit_mtrap++;
791 
792 #ifdef BHYVE_SNAPSHOT
793 	checkpoint_cpu_suspend(vcpu_id(vcpu));
794 #endif
795 	gdb_cpu_mtrap(vcpu);
796 #ifdef BHYVE_SNAPSHOT
797 	checkpoint_cpu_resume(vcpu_id(vcpu));
798 #endif
799 
800 	return (VMEXIT_CONTINUE);
801 }
802 
803 static int
804 vmexit_inst_emul(struct vmctx *ctx __unused, struct vcpu *vcpu,
805     struct vm_exit *vme)
806 {
807 	int err, i, cs_d;
808 	struct vie *vie;
809 	enum vm_cpu_mode mode;
810 
811 	stats.vmexit_inst_emul++;
812 
813 	vie = &vme->u.inst_emul.vie;
814 	if (!vie->decoded) {
815 		/*
816 		 * Attempt to decode in userspace as a fallback.  This allows
817 		 * updating instruction decode in bhyve without rebooting the
818 		 * kernel (rapid prototyping), albeit with much slower
819 		 * emulation.
820 		 */
821 		vie_restart(vie);
822 		mode = vme->u.inst_emul.paging.cpu_mode;
823 		cs_d = vme->u.inst_emul.cs_d;
824 		if (vmm_decode_instruction(mode, cs_d, vie) != 0)
825 			goto fail;
826 		if (vm_set_register(vcpu, VM_REG_GUEST_RIP,
827 		    vme->rip + vie->num_processed) != 0)
828 			goto fail;
829 	}
830 
831 	err = emulate_mem(vcpu, vme->u.inst_emul.gpa, vie,
832 	    &vme->u.inst_emul.paging);
833 	if (err) {
834 		if (err == ESRCH) {
835 			EPRINTLN("Unhandled memory access to 0x%lx\n",
836 			    vme->u.inst_emul.gpa);
837 		}
838 		goto fail;
839 	}
840 
841 	return (VMEXIT_CONTINUE);
842 
843 fail:
844 	fprintf(stderr, "Failed to emulate instruction sequence [ ");
845 	for (i = 0; i < vie->num_valid; i++)
846 		fprintf(stderr, "%02x", vie->inst[i]);
847 	FPRINTLN(stderr, " ] at 0x%lx", vme->rip);
848 	return (VMEXIT_ABORT);
849 }
850 
851 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
852 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
853 
854 static int
855 vmexit_suspend(struct vmctx *ctx, struct vcpu *vcpu, struct vm_exit *vme)
856 {
857 	enum vm_suspend_how how;
858 	int vcpuid = vcpu_id(vcpu);
859 
860 	how = vme->u.suspended.how;
861 
862 	fbsdrun_deletecpu(vcpuid);
863 
864 	if (vcpuid != BSP) {
865 		pthread_mutex_lock(&resetcpu_mtx);
866 		pthread_cond_signal(&resetcpu_cond);
867 		pthread_mutex_unlock(&resetcpu_mtx);
868 		pthread_exit(NULL);
869 	}
870 
871 	pthread_mutex_lock(&resetcpu_mtx);
872 	while (!CPU_EMPTY(&cpumask)) {
873 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
874 	}
875 	pthread_mutex_unlock(&resetcpu_mtx);
876 
877 	switch (how) {
878 	case VM_SUSPEND_RESET:
879 		exit(0);
880 	case VM_SUSPEND_POWEROFF:
881 		if (get_config_bool_default("destroy_on_poweroff", false))
882 			vm_destroy(ctx);
883 		exit(1);
884 	case VM_SUSPEND_HALT:
885 		exit(2);
886 	case VM_SUSPEND_TRIPLEFAULT:
887 		exit(3);
888 	default:
889 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
890 		exit(100);
891 	}
892 	return (0);	/* NOTREACHED */
893 }
894 
895 static int
896 vmexit_debug(struct vmctx *ctx __unused, struct vcpu *vcpu,
897     struct vm_exit *vme __unused)
898 {
899 
900 #ifdef BHYVE_SNAPSHOT
901 	checkpoint_cpu_suspend(vcpu_id(vcpu));
902 #endif
903 	gdb_cpu_suspend(vcpu);
904 #ifdef BHYVE_SNAPSHOT
905 	checkpoint_cpu_resume(vcpu_id(vcpu));
906 #endif
907 	/*
908 	 * XXX-MJ sleep for a short period to avoid chewing up the CPU in the
909 	 * window between activation of the vCPU thread and the STARTUP IPI.
910 	 */
911 	usleep(1000);
912 	return (VMEXIT_CONTINUE);
913 }
914 
915 static int
916 vmexit_breakpoint(struct vmctx *ctx __unused, struct vcpu *vcpu,
917     struct vm_exit *vme)
918 {
919 
920 	gdb_cpu_breakpoint(vcpu, vme);
921 	return (VMEXIT_CONTINUE);
922 }
923 
924 static int
925 vmexit_ipi(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
926     struct vm_exit *vme)
927 {
928 	int error = -1;
929 	int i;
930 	switch (vme->u.ipi.mode) {
931 	case APIC_DELMODE_INIT:
932 		CPU_FOREACH_ISSET(i, &vme->u.ipi.dmask) {
933 			error = vm_suspend_cpu(vcpu_info[i].vcpu);
934 			if (error) {
935 				warnx("%s: failed to suspend cpu %d\n",
936 				    __func__, i);
937 				break;
938 			}
939 		}
940 		break;
941 	case APIC_DELMODE_STARTUP:
942 		CPU_FOREACH_ISSET(i, &vme->u.ipi.dmask) {
943 			spinup_ap(vcpu_info[i].vcpu,
944 			    vme->u.ipi.vector << PAGE_SHIFT);
945 		}
946 		error = 0;
947 		break;
948 	default:
949 		break;
950 	}
951 
952 	return (error);
953 }
954 
955 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
956 	[VM_EXITCODE_INOUT]  = vmexit_inout,
957 	[VM_EXITCODE_INOUT_STR]  = vmexit_inout,
958 	[VM_EXITCODE_VMX]    = vmexit_vmx,
959 	[VM_EXITCODE_SVM]    = vmexit_svm,
960 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
961 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
962 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
963 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
964 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
965 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
966 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
967 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
968 	[VM_EXITCODE_DEBUG] = vmexit_debug,
969 	[VM_EXITCODE_BPT] = vmexit_breakpoint,
970 	[VM_EXITCODE_IPI] = vmexit_ipi,
971 };
972 
973 static void
974 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
975 {
976 	struct vm_exit vme;
977 	int error, rc;
978 	enum vm_exitcode exitcode;
979 	cpuset_t active_cpus;
980 
981 	error = vm_active_cpus(ctx, &active_cpus);
982 	assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
983 
984 	while (1) {
985 		error = vm_run(vcpu, &vme);
986 		if (error != 0)
987 			break;
988 
989 		exitcode = vme.exitcode;
990 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
991 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
992 			    exitcode);
993 			exit(4);
994 		}
995 
996 		rc = (*handler[exitcode])(ctx, vcpu, &vme);
997 
998 		switch (rc) {
999 		case VMEXIT_CONTINUE:
1000 			break;
1001 		case VMEXIT_ABORT:
1002 			abort();
1003 		default:
1004 			exit(4);
1005 		}
1006 	}
1007 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
1008 }
1009 
1010 static int
1011 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
1012 {
1013 	uint16_t sockets, cores, threads, maxcpus;
1014 	int tmp, error;
1015 
1016 	/*
1017 	 * The guest is allowed to spinup more than one processor only if the
1018 	 * UNRESTRICTED_GUEST capability is available.
1019 	 */
1020 	error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1021 	if (error != 0)
1022 		return (1);
1023 
1024 	error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
1025 	if (error == 0)
1026 		return (maxcpus);
1027 	else
1028 		return (1);
1029 }
1030 
1031 static void
1032 fbsdrun_set_capabilities(struct vcpu *vcpu, bool bsp)
1033 {
1034 	int err, tmp;
1035 
1036 	if (get_config_bool_default("x86.vmexit_on_hlt", false)) {
1037 		err = vm_get_capability(vcpu, VM_CAP_HALT_EXIT, &tmp);
1038 		if (err < 0) {
1039 			fprintf(stderr, "VM exit on HLT not supported\n");
1040 			exit(4);
1041 		}
1042 		vm_set_capability(vcpu, VM_CAP_HALT_EXIT, 1);
1043 		if (bsp)
1044 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
1045 	}
1046 
1047 	if (get_config_bool_default("x86.vmexit_on_pause", false)) {
1048 		/*
1049 		 * pause exit support required for this mode
1050 		 */
1051 		err = vm_get_capability(vcpu, VM_CAP_PAUSE_EXIT, &tmp);
1052 		if (err < 0) {
1053 			fprintf(stderr,
1054 			    "SMP mux requested, no pause support\n");
1055 			exit(4);
1056 		}
1057 		vm_set_capability(vcpu, VM_CAP_PAUSE_EXIT, 1);
1058 		if (bsp)
1059 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1060         }
1061 
1062 	if (get_config_bool_default("x86.x2apic", false))
1063 		err = vm_set_x2apic_state(vcpu, X2APIC_ENABLED);
1064 	else
1065 		err = vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
1066 
1067 	if (err) {
1068 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1069 		exit(4);
1070 	}
1071 
1072 	vm_set_capability(vcpu, VM_CAP_ENABLE_INVPCID, 1);
1073 
1074 	err = vm_set_capability(vcpu, VM_CAP_IPI_EXIT, 1);
1075 	assert(err == 0);
1076 }
1077 
1078 static struct vmctx *
1079 do_open(const char *vmname)
1080 {
1081 	struct vmctx *ctx;
1082 	int error;
1083 	bool reinit, romboot;
1084 
1085 	reinit = romboot = false;
1086 
1087 	if (lpc_bootrom())
1088 		romboot = true;
1089 
1090 	error = vm_create(vmname);
1091 	if (error) {
1092 		if (errno == EEXIST) {
1093 			if (romboot) {
1094 				reinit = true;
1095 			} else {
1096 				/*
1097 				 * The virtual machine has been setup by the
1098 				 * userspace bootloader.
1099 				 */
1100 			}
1101 		} else {
1102 			perror("vm_create");
1103 			exit(4);
1104 		}
1105 	} else {
1106 		if (!romboot) {
1107 			/*
1108 			 * If the virtual machine was just created then a
1109 			 * bootrom must be configured to boot it.
1110 			 */
1111 			fprintf(stderr, "virtual machine cannot be booted\n");
1112 			exit(4);
1113 		}
1114 	}
1115 
1116 	ctx = vm_open(vmname);
1117 	if (ctx == NULL) {
1118 		perror("vm_open");
1119 		exit(4);
1120 	}
1121 
1122 #ifndef WITHOUT_CAPSICUM
1123 	if (vm_limit_rights(ctx) != 0)
1124 		err(EX_OSERR, "vm_limit_rights");
1125 #endif
1126 
1127 	if (reinit) {
1128 		error = vm_reinit(ctx);
1129 		if (error) {
1130 			perror("vm_reinit");
1131 			exit(4);
1132 		}
1133 	}
1134 	error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads,
1135 	    0 /* maxcpus, unimplemented */);
1136 	if (error)
1137 		errx(EX_OSERR, "vm_set_topology");
1138 	return (ctx);
1139 }
1140 
1141 static void
1142 spinup_vcpu(struct vcpu_info *vi, bool bsp)
1143 {
1144 	int error;
1145 
1146 	if (!bsp) {
1147 		fbsdrun_set_capabilities(vi->vcpu, false);
1148 
1149 		/*
1150 		 * Enable the 'unrestricted guest' mode for APs.
1151 		 *
1152 		 * APs startup in power-on 16-bit mode.
1153 		 */
1154 		error = vm_set_capability(vi->vcpu, VM_CAP_UNRESTRICTED_GUEST, 1);
1155 		assert(error == 0);
1156 	}
1157 
1158 	fbsdrun_addcpu(vi);
1159 }
1160 
1161 static bool
1162 parse_config_option(const char *option)
1163 {
1164 	const char *value;
1165 	char *path;
1166 
1167 	value = strchr(option, '=');
1168 	if (value == NULL || value[1] == '\0')
1169 		return (false);
1170 	path = strndup(option, value - option);
1171 	if (path == NULL)
1172 		err(4, "Failed to allocate memory");
1173 	set_config_value(path, value + 1);
1174 	return (true);
1175 }
1176 
1177 static void
1178 parse_simple_config_file(const char *path)
1179 {
1180 	FILE *fp;
1181 	char *line, *cp;
1182 	size_t linecap;
1183 	unsigned int lineno;
1184 
1185 	fp = fopen(path, "r");
1186 	if (fp == NULL)
1187 		err(4, "Failed to open configuration file %s", path);
1188 	line = NULL;
1189 	linecap = 0;
1190 	lineno = 1;
1191 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
1192 		if (*line == '#' || *line == '\n')
1193 			continue;
1194 		cp = strchr(line, '\n');
1195 		if (cp != NULL)
1196 			*cp = '\0';
1197 		if (!parse_config_option(line))
1198 			errx(4, "%s line %u: invalid config option '%s'", path,
1199 			    lineno, line);
1200 	}
1201 	free(line);
1202 	fclose(fp);
1203 }
1204 
1205 static void
1206 parse_gdb_options(const char *opt)
1207 {
1208 	const char *sport;
1209 	char *colon;
1210 
1211 	if (opt[0] == 'w') {
1212 		set_config_bool("gdb.wait", true);
1213 		opt++;
1214 	}
1215 
1216 	colon = strrchr(opt, ':');
1217 	if (colon == NULL) {
1218 		sport = opt;
1219 	} else {
1220 		*colon = '\0';
1221 		colon++;
1222 		sport = colon;
1223 		set_config_value("gdb.address", opt);
1224 	}
1225 
1226 	set_config_value("gdb.port", sport);
1227 }
1228 
1229 static void
1230 set_defaults(void)
1231 {
1232 
1233 	set_config_bool("acpi_tables", false);
1234 	set_config_value("memory.size", "256M");
1235 	set_config_bool("x86.strictmsr", true);
1236 	set_config_value("lpc.fwcfg", "bhyve");
1237 }
1238 
1239 int
1240 main(int argc, char *argv[])
1241 {
1242 	int c, error;
1243 	int max_vcpus, memflags;
1244 	struct vcpu *bsp;
1245 	struct vmctx *ctx;
1246 	struct qemu_fwcfg_item *e820_fwcfg_item;
1247 	uint64_t rip;
1248 	size_t memsize;
1249 	const char *optstr, *value, *vmname;
1250 #ifdef BHYVE_SNAPSHOT
1251 	char *restore_file;
1252 	struct restore_state rstate;
1253 
1254 	restore_file = NULL;
1255 #endif
1256 
1257 	init_config();
1258 	set_defaults();
1259 	progname = basename(argv[0]);
1260 
1261 #ifdef BHYVE_SNAPSHOT
1262 	optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:r:";
1263 #else
1264 	optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:";
1265 #endif
1266 	while ((c = getopt(argc, argv, optstr)) != -1) {
1267 		switch (c) {
1268 		case 'a':
1269 			set_config_bool("x86.x2apic", false);
1270 			break;
1271 		case 'A':
1272 			set_config_bool("acpi_tables", true);
1273 			break;
1274 		case 'D':
1275 			set_config_bool("destroy_on_poweroff", true);
1276 			break;
1277 		case 'p':
1278                         if (pincpu_parse(optarg) != 0) {
1279                             errx(EX_USAGE, "invalid vcpu pinning "
1280                                  "configuration '%s'", optarg);
1281                         }
1282 			break;
1283                 case 'c':
1284 			if (topology_parse(optarg) != 0) {
1285 			    errx(EX_USAGE, "invalid cpu topology "
1286 				"'%s'", optarg);
1287 			}
1288 			break;
1289 		case 'C':
1290 			set_config_bool("memory.guest_in_core", true);
1291 			break;
1292 		case 'f':
1293 			if (qemu_fwcfg_parse_cmdline_arg(optarg) != 0) {
1294 			    errx(EX_USAGE, "invalid fwcfg item '%s'", optarg);
1295 			}
1296 			break;
1297 		case 'G':
1298 			parse_gdb_options(optarg);
1299 			break;
1300 		case 'k':
1301 			parse_simple_config_file(optarg);
1302 			break;
1303 		case 'K':
1304 			set_config_value("keyboard.layout", optarg);
1305 			break;
1306 		case 'l':
1307 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1308 				lpc_print_supported_devices();
1309 				exit(0);
1310 			} else if (lpc_device_parse(optarg) != 0) {
1311 				errx(EX_USAGE, "invalid lpc device "
1312 				    "configuration '%s'", optarg);
1313 			}
1314 			break;
1315 #ifdef BHYVE_SNAPSHOT
1316 		case 'r':
1317 			restore_file = optarg;
1318 			break;
1319 #endif
1320 		case 's':
1321 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1322 				pci_print_supported_devices();
1323 				exit(0);
1324 			} else if (pci_parse_slot(optarg) != 0)
1325 				exit(4);
1326 			else
1327 				break;
1328 		case 'S':
1329 			set_config_bool("memory.wired", true);
1330 			break;
1331                 case 'm':
1332 			set_config_value("memory.size", optarg);
1333 			break;
1334 		case 'o':
1335 			if (!parse_config_option(optarg))
1336 				errx(EX_USAGE, "invalid configuration option '%s'", optarg);
1337 			break;
1338 		case 'H':
1339 			set_config_bool("x86.vmexit_on_hlt", true);
1340 			break;
1341 		case 'I':
1342 			/*
1343 			 * The "-I" option was used to add an ioapic to the
1344 			 * virtual machine.
1345 			 *
1346 			 * An ioapic is now provided unconditionally for each
1347 			 * virtual machine and this option is now deprecated.
1348 			 */
1349 			break;
1350 		case 'P':
1351 			set_config_bool("x86.vmexit_on_pause", true);
1352 			break;
1353 		case 'e':
1354 			set_config_bool("x86.strictio", true);
1355 			break;
1356 		case 'u':
1357 			set_config_bool("rtc.use_localtime", false);
1358 			break;
1359 		case 'U':
1360 			set_config_value("uuid", optarg);
1361 			break;
1362 		case 'w':
1363 			set_config_bool("x86.strictmsr", false);
1364 			break;
1365 		case 'W':
1366 			set_config_bool("virtio_msix", false);
1367 			break;
1368 		case 'x':
1369 			set_config_bool("x86.x2apic", true);
1370 			break;
1371 		case 'Y':
1372 			set_config_bool("x86.mptable", false);
1373 			break;
1374 		case 'h':
1375 			usage(0);
1376 		default:
1377 			usage(1);
1378 		}
1379 	}
1380 	argc -= optind;
1381 	argv += optind;
1382 
1383 	if (argc > 1)
1384 		usage(1);
1385 
1386 #ifdef BHYVE_SNAPSHOT
1387 	if (restore_file != NULL) {
1388 		error = load_restore_file(restore_file, &rstate);
1389 		if (error) {
1390 			fprintf(stderr, "Failed to read checkpoint info from "
1391 					"file: '%s'.\n", restore_file);
1392 			exit(1);
1393 		}
1394 		vmname = lookup_vmname(&rstate);
1395 		if (vmname != NULL)
1396 			set_config_value("name", vmname);
1397 	}
1398 #endif
1399 
1400 	if (argc == 1)
1401 		set_config_value("name", argv[0]);
1402 
1403 	vmname = get_config_value("name");
1404 	if (vmname == NULL)
1405 		usage(1);
1406 
1407 	if (get_config_bool_default("config.dump", false)) {
1408 		dump_config();
1409 		exit(1);
1410 	}
1411 
1412 	calc_topology();
1413 	build_vcpumaps();
1414 
1415 	value = get_config_value("memory.size");
1416 	error = vm_parse_memsize(value, &memsize);
1417 	if (error)
1418 		errx(EX_USAGE, "invalid memsize '%s'", value);
1419 
1420 	ctx = do_open(vmname);
1421 
1422 #ifdef BHYVE_SNAPSHOT
1423 	if (restore_file != NULL) {
1424 		guest_ncpus = lookup_guest_ncpus(&rstate);
1425 		memflags = lookup_memflags(&rstate);
1426 		memsize = lookup_memsize(&rstate);
1427 	}
1428 
1429 	if (guest_ncpus < 1) {
1430 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
1431 		exit(1);
1432 	}
1433 #endif
1434 
1435 	bsp = vm_vcpu_open(ctx, BSP);
1436 	max_vcpus = num_vcpus_allowed(ctx, bsp);
1437 	if (guest_ncpus > max_vcpus) {
1438 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
1439 			guest_ncpus, max_vcpus);
1440 		exit(4);
1441 	}
1442 
1443 	fbsdrun_set_capabilities(bsp, true);
1444 
1445 	/* Allocate per-VCPU resources. */
1446 	vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
1447 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
1448 		vcpu_info[vcpuid].ctx = ctx;
1449 		vcpu_info[vcpuid].vcpuid = vcpuid;
1450 		if (vcpuid == BSP)
1451 			vcpu_info[vcpuid].vcpu = bsp;
1452 		else
1453 			vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
1454 	}
1455 
1456 	memflags = 0;
1457 	if (get_config_bool_default("memory.wired", false))
1458 		memflags |= VM_MEM_F_WIRED;
1459 	if (get_config_bool_default("memory.guest_in_core", false))
1460 		memflags |= VM_MEM_F_INCORE;
1461 	vm_set_memflags(ctx, memflags);
1462 	error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1463 	if (error) {
1464 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1465 		exit(4);
1466 	}
1467 
1468 	error = init_msr();
1469 	if (error) {
1470 		fprintf(stderr, "init_msr error %d", error);
1471 		exit(4);
1472 	}
1473 
1474 	init_mem(guest_ncpus);
1475 	init_inout();
1476 	kernemu_dev_init();
1477 	init_bootrom(ctx);
1478 	atkbdc_init(ctx);
1479 	pci_irq_init(ctx);
1480 	ioapic_init(ctx);
1481 
1482 	rtc_init(ctx);
1483 	sci_init(ctx);
1484 
1485 	if (qemu_fwcfg_init(ctx) != 0) {
1486 		fprintf(stderr, "qemu fwcfg initialization error");
1487 		exit(4);
1488 	}
1489 
1490 	if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
1491 	    &guest_ncpus) != 0) {
1492 		fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu");
1493 		exit(4);
1494 	}
1495 
1496 	if (e820_init(ctx) != 0) {
1497 		fprintf(stderr, "Unable to setup E820");
1498 		exit(4);
1499 	}
1500 
1501 	/*
1502 	 * Exit if a device emulation finds an error in its initilization
1503 	 */
1504 	if (init_pci(ctx) != 0) {
1505 		perror("device emulation initialization error");
1506 		exit(4);
1507 	}
1508 
1509 	/*
1510 	 * Initialize after PCI, to allow a bootrom file to reserve the high
1511 	 * region.
1512 	 */
1513 	if (get_config_bool("acpi_tables"))
1514 		vmgenc_init(ctx);
1515 
1516 	init_gdb(ctx);
1517 
1518 	if (lpc_bootrom()) {
1519 		if (vm_set_capability(bsp, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1520 			fprintf(stderr, "ROM boot failed: unrestricted guest "
1521 			    "capability not available\n");
1522 			exit(4);
1523 		}
1524 		error = vcpu_reset(bsp);
1525 		assert(error == 0);
1526 	}
1527 
1528 	/*
1529 	 * Add all vCPUs.
1530 	 */
1531 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1532 		spinup_vcpu(&vcpu_info[vcpuid], vcpuid == BSP);
1533 
1534 #ifdef BHYVE_SNAPSHOT
1535 	if (restore_file != NULL) {
1536 		fprintf(stdout, "Pausing pci devs...\r\n");
1537 		if (vm_pause_user_devs() != 0) {
1538 			fprintf(stderr, "Failed to pause PCI device state.\n");
1539 			exit(1);
1540 		}
1541 
1542 		fprintf(stdout, "Restoring vm mem...\r\n");
1543 		if (restore_vm_mem(ctx, &rstate) != 0) {
1544 			fprintf(stderr, "Failed to restore VM memory.\n");
1545 			exit(1);
1546 		}
1547 
1548 		fprintf(stdout, "Restoring pci devs...\r\n");
1549 		if (vm_restore_user_devs(&rstate) != 0) {
1550 			fprintf(stderr, "Failed to restore PCI device state.\n");
1551 			exit(1);
1552 		}
1553 
1554 		fprintf(stdout, "Restoring kernel structs...\r\n");
1555 		if (vm_restore_kern_structs(ctx, &rstate) != 0) {
1556 			fprintf(stderr, "Failed to restore kernel structs.\n");
1557 			exit(1);
1558 		}
1559 
1560 		fprintf(stdout, "Resuming pci devs...\r\n");
1561 		if (vm_resume_user_devs() != 0) {
1562 			fprintf(stderr, "Failed to resume PCI device state.\n");
1563 			exit(1);
1564 		}
1565 	}
1566 #endif
1567 
1568 	error = vm_get_register(bsp, VM_REG_GUEST_RIP, &rip);
1569 	assert(error == 0);
1570 
1571 	/*
1572 	 * build the guest tables, MP etc.
1573 	 */
1574 	if (get_config_bool_default("x86.mptable", true)) {
1575 		error = mptable_build(ctx, guest_ncpus);
1576 		if (error) {
1577 			perror("error to build the guest tables");
1578 			exit(4);
1579 		}
1580 	}
1581 
1582 	error = smbios_build(ctx);
1583 	if (error != 0)
1584 		exit(4);
1585 
1586 	if (get_config_bool("acpi_tables")) {
1587 		error = acpi_build(ctx, guest_ncpus);
1588 		assert(error == 0);
1589 	}
1590 
1591 	e820_fwcfg_item = e820_get_fwcfg_item();
1592 	if (e820_fwcfg_item == NULL) {
1593 	    fprintf(stderr, "invalid e820 table");
1594 		exit(4);
1595 	}
1596 	if (qemu_fwcfg_add_file("etc/e820", e820_fwcfg_item->size,
1597 		e820_fwcfg_item->data) != 0) {
1598 		fprintf(stderr, "could not add qemu fwcfg etc/e820");
1599 		exit(4);
1600 	}
1601 	free(e820_fwcfg_item);
1602 
1603 	if (lpc_bootrom() && strcmp(lpc_fwcfg(), "bhyve") == 0) {
1604 		fwctl_init();
1605 	}
1606 
1607 	/*
1608 	 * Change the proc title to include the VM name.
1609 	 */
1610 	setproctitle("%s", vmname);
1611 
1612 #ifdef BHYVE_SNAPSHOT
1613 	/* initialize mutex/cond variables */
1614 	init_snapshot();
1615 
1616 	/*
1617 	 * checkpointing thread for communication with bhyvectl
1618 	 */
1619 	if (init_checkpoint_thread(ctx) != 0)
1620 		errx(EX_OSERR, "Failed to start checkpoint thread");
1621 #endif
1622 
1623 #ifndef WITHOUT_CAPSICUM
1624 	caph_cache_catpages();
1625 
1626 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1627 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1628 
1629 	if (caph_enter() == -1)
1630 		errx(EX_OSERR, "cap_enter() failed");
1631 #endif
1632 
1633 #ifdef BHYVE_SNAPSHOT
1634 	if (restore_file != NULL) {
1635 		destroy_restore_state(&rstate);
1636 		if (vm_restore_time(ctx) < 0)
1637 			err(EX_OSERR, "Unable to restore time");
1638 
1639 		for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1640 			vm_resume_cpu(vcpu_info[vcpuid].vcpu);
1641 	} else
1642 #endif
1643 		vm_resume_cpu(bsp);
1644 
1645 	/*
1646 	 * Head off to the main event dispatch loop
1647 	 */
1648 	mevent_dispatch();
1649 
1650 	exit(4);
1651 }
1652