xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
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 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 vcpu *, struct vm_run *);
186 
187 int guest_ncpus;
188 uint16_t cpu_cores, cpu_sockets, cpu_threads;
189 
190 int raw_stdio = 0;
191 
192 static char *progname;
193 static const int BSP = 0;
194 
195 static cpuset_t cpumask;
196 
197 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
198 
199 static struct vcpu_info {
200 	struct vmctx	*ctx;
201 	struct vcpu	*vcpu;
202 	int		vcpuid;
203 } *vcpu_info;
204 
205 static cpuset_t **vcpumap;
206 
207 static void
208 usage(int code)
209 {
210 
211 	fprintf(stderr,
212 		"Usage: %s [-AaCDeHhPSuWwxY]\n"
213 		"       %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
214 		"       %*s [-G port] [-k config_file] [-l lpc] [-m mem] [-o var=value]\n"
215 		"       %*s [-p vcpu:hostcpu] [-r file] [-s pci] [-U uuid] vmname\n"
216 		"       -A: create ACPI tables\n"
217 		"       -a: local apic is in xAPIC mode (deprecated)\n"
218 		"       -C: include guest memory in core file\n"
219 		"       -c: number of CPUs and/or topology specification\n"
220 		"       -D: destroy on power-off\n"
221 		"       -e: exit on unhandled I/O access\n"
222 		"       -G: start a debug server\n"
223 		"       -H: vmexit from the guest on HLT\n"
224 		"       -h: help\n"
225 		"       -k: key=value flat config file\n"
226 		"       -K: PS2 keyboard layout\n"
227 		"       -l: LPC device configuration\n"
228 		"       -m: memory size\n"
229 		"       -o: set config 'var' to 'value'\n"
230 		"       -P: vmexit from the guest on pause\n"
231 		"       -p: pin 'vcpu' to 'hostcpu'\n"
232 #ifdef BHYVE_SNAPSHOT
233 		"       -r: path to checkpoint file\n"
234 #endif
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 ",," as setting "cpus" to an
252  *     empty string.
253  *
254  * The acceptance of a null specification ('-c ""') is by design to match the
255  * manual page syntax specification, this results in a topology of 1 vCPU.
256  */
257 static int
258 topology_parse(const char *opt)
259 {
260 	char *cp, *str, *tofree;
261 
262 	if (*opt == '\0') {
263 		set_config_value("sockets", "1");
264 		set_config_value("cores", "1");
265 		set_config_value("threads", "1");
266 		set_config_value("cpus", "1");
267 		return (0);
268 	}
269 
270 	tofree = str = strdup(opt);
271 	if (str == NULL)
272 		errx(4, "Failed to allocate memory");
273 
274 	while ((cp = strsep(&str, ",")) != NULL) {
275 		if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
276 			set_config_value("cpus", cp + strlen("cpus="));
277 		else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
278 			set_config_value("sockets", cp + strlen("sockets="));
279 		else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
280 			set_config_value("cores", cp + strlen("cores="));
281 		else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
282 			set_config_value("threads", cp + strlen("threads="));
283 		else if (strchr(cp, '=') != NULL)
284 			goto out;
285 		else
286 			set_config_value("cpus", cp);
287 	}
288 	free(tofree);
289 	return (0);
290 
291 out:
292 	free(tofree);
293 	return (-1);
294 }
295 
296 static int
297 parse_int_value(const char *key, const char *value, int minval, int maxval)
298 {
299 	char *cp;
300 	long lval;
301 
302 	errno = 0;
303 	lval = strtol(value, &cp, 0);
304 	if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
305 	    lval > maxval)
306 		errx(4, "Invalid value for %s: '%s'", key, value);
307 	return (lval);
308 }
309 
310 /*
311  * Set the sockets, cores, threads, and guest_cpus variables based on
312  * the configured topology.
313  *
314  * The limits of UINT16_MAX are due to the types passed to
315  * vm_set_topology().  vmm.ko may enforce tighter limits.
316  */
317 static void
318 calc_topology(void)
319 {
320 	const char *value;
321 	bool explicit_cpus;
322 	uint64_t ncpus;
323 
324 	value = get_config_value("cpus");
325 	if (value != NULL) {
326 		guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
327 		explicit_cpus = true;
328 	} else {
329 		guest_ncpus = 1;
330 		explicit_cpus = false;
331 	}
332 	value = get_config_value("cores");
333 	if (value != NULL)
334 		cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
335 	else
336 		cpu_cores = 1;
337 	value = get_config_value("threads");
338 	if (value != NULL)
339 		cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
340 	else
341 		cpu_threads = 1;
342 	value = get_config_value("sockets");
343 	if (value != NULL)
344 		cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
345 	else
346 		cpu_sockets = guest_ncpus;
347 
348 	/*
349 	 * Compute sockets * cores * threads avoiding overflow.  The
350 	 * range check above insures these are 16 bit values.
351 	 */
352 	ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
353 	if (ncpus > UINT16_MAX)
354 		errx(4, "Computed number of vCPUs too high: %ju",
355 		    (uintmax_t)ncpus);
356 
357 	if (explicit_cpus) {
358 		if (guest_ncpus != (int)ncpus)
359 			errx(4, "Topology (%d sockets, %d cores, %d threads) "
360 			    "does not match %d vCPUs",
361 			    cpu_sockets, cpu_cores, cpu_threads,
362 			    guest_ncpus);
363 	} else
364 		guest_ncpus = ncpus;
365 }
366 
367 static int
368 pincpu_parse(const char *opt)
369 {
370 	const char *value;
371 	char *newval;
372 	char key[16];
373 	int vcpu, pcpu;
374 
375 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
376 		fprintf(stderr, "invalid format: %s\n", opt);
377 		return (-1);
378 	}
379 
380 	if (vcpu < 0) {
381 		fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
382 		return (-1);
383 	}
384 
385 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
386 		fprintf(stderr, "hostcpu '%d' outside valid range from "
387 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
388 		return (-1);
389 	}
390 
391 	snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
392 	value = get_config_value(key);
393 
394 	if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
395 	    value != NULL ? "," : "", pcpu) == -1) {
396 		perror("failed to build new cpuset string");
397 		return (-1);
398 	}
399 
400 	set_config_value(key, newval);
401 	free(newval);
402 	return (0);
403 }
404 
405 static void
406 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
407 {
408 	char *cp, *token;
409 	int pcpu, start;
410 
411 	CPU_ZERO(set);
412 	start = -1;
413 	token = __DECONST(char *, list);
414 	for (;;) {
415 		pcpu = strtoul(token, &cp, 0);
416 		if (cp == token)
417 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
418 		if (pcpu < 0 || pcpu >= CPU_SETSIZE)
419 			errx(4, "hostcpu '%d' outside valid range from 0 to %d",
420 			    pcpu, CPU_SETSIZE - 1);
421 		switch (*cp) {
422 		case ',':
423 		case '\0':
424 			if (start >= 0) {
425 				if (start > pcpu)
426 					errx(4, "Invalid hostcpu range %d-%d",
427 					    start, pcpu);
428 				while (start < pcpu) {
429 					CPU_SET(start, set);
430 					start++;
431 				}
432 				start = -1;
433 			}
434 			CPU_SET(pcpu, set);
435 			break;
436 		case '-':
437 			if (start >= 0)
438 				errx(4, "invalid cpuset for vcpu %d: '%s'",
439 				    vcpu, list);
440 			start = pcpu;
441 			break;
442 		default:
443 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
444 		}
445 		if (*cp == '\0')
446 			break;
447 		token = cp + 1;
448 	}
449 }
450 
451 static void
452 build_vcpumaps(void)
453 {
454 	char key[16];
455 	const char *value;
456 	int vcpu;
457 
458 	vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
459 	for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
460 		snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
461 		value = get_config_value(key);
462 		if (value == NULL)
463 			continue;
464 		vcpumap[vcpu] = malloc(sizeof(cpuset_t));
465 		if (vcpumap[vcpu] == NULL)
466 			err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
467 		parse_cpuset(vcpu, value, vcpumap[vcpu]);
468 	}
469 }
470 
471 void
472 vm_inject_fault(struct vcpu *vcpu, int vector, int errcode_valid,
473     int errcode)
474 {
475 	int error, restart_instruction;
476 
477 	restart_instruction = 1;
478 
479 	error = vm_inject_exception(vcpu, vector, errcode_valid, errcode,
480 	    restart_instruction);
481 	assert(error == 0);
482 }
483 
484 void *
485 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
486 {
487 
488 	return (vm_map_gpa(ctx, gaddr, len));
489 }
490 
491 #ifdef BHYVE_SNAPSHOT
492 uintptr_t
493 paddr_host2guest(struct vmctx *ctx, void *addr)
494 {
495 	return (vm_rev_map_gpa(ctx, addr));
496 }
497 #endif
498 
499 int
500 fbsdrun_virtio_msix(void)
501 {
502 
503 	return (get_config_bool_default("virtio_msix", true));
504 }
505 
506 static void *
507 fbsdrun_start_thread(void *param)
508 {
509 	char tname[MAXCOMLEN + 1];
510 	struct vcpu_info *vi = param;
511 	int error;
512 
513 	snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
514 	pthread_set_name_np(pthread_self(), tname);
515 
516 	if (vcpumap[vi->vcpuid] != NULL) {
517 		error = pthread_setaffinity_np(pthread_self(),
518 		    sizeof(cpuset_t), vcpumap[vi->vcpuid]);
519 		assert(error == 0);
520 	}
521 
522 #ifdef BHYVE_SNAPSHOT
523 	checkpoint_cpu_add(vi->vcpuid);
524 #endif
525 	gdb_cpu_add(vi->vcpu);
526 
527 	vm_loop(vi->ctx, vi->vcpu);
528 
529 	/* not reached */
530 	exit(1);
531 	return (NULL);
532 }
533 
534 static void
535 fbsdrun_addcpu(struct vcpu_info *vi)
536 {
537 	pthread_t thr;
538 	int error;
539 
540 	error = vm_activate_cpu(vi->vcpu);
541 	if (error != 0)
542 		err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
543 
544 	CPU_SET_ATOMIC(vi->vcpuid, &cpumask);
545 
546 	vm_suspend_cpu(vi->vcpu);
547 
548 	error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
549 	assert(error == 0);
550 }
551 
552 static void
553 fbsdrun_deletecpu(int vcpu)
554 {
555 	static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
556 	static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
557 
558 	pthread_mutex_lock(&resetcpu_mtx);
559 	if (!CPU_ISSET(vcpu, &cpumask)) {
560 		fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
561 		exit(4);
562 	}
563 
564 	CPU_CLR(vcpu, &cpumask);
565 
566 	if (vcpu != BSP) {
567 		pthread_cond_signal(&resetcpu_cond);
568 		pthread_mutex_unlock(&resetcpu_mtx);
569 		pthread_exit(NULL);
570 		/* NOTREACHED */
571 	}
572 
573 	while (!CPU_EMPTY(&cpumask)) {
574 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
575 	}
576 	pthread_mutex_unlock(&resetcpu_mtx);
577 }
578 
579 static int
580 vmexit_inout(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
581 {
582 	struct vm_exit *vme;
583 	int error;
584 	int bytes, port, in;
585 
586 	vme = vmrun->vm_exit;
587 	port = vme->u.inout.port;
588 	bytes = vme->u.inout.bytes;
589 	in = vme->u.inout.in;
590 
591 	error = emulate_inout(ctx, vcpu, vme);
592 	if (error) {
593 		fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
594 		    in ? "in" : "out",
595 		    bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
596 		    port, vme->rip);
597 		return (VMEXIT_ABORT);
598 	} else {
599 		return (VMEXIT_CONTINUE);
600 	}
601 }
602 
603 static int
604 vmexit_rdmsr(struct vmctx *ctx __unused, struct vcpu *vcpu,
605     struct vm_run *vmrun)
606 {
607 	struct vm_exit *vme;
608 	uint64_t val;
609 	uint32_t eax, edx;
610 	int error;
611 
612 	vme = vmrun->vm_exit;
613 
614 	val = 0;
615 	error = emulate_rdmsr(vcpu, vme->u.msr.code, &val);
616 	if (error != 0) {
617 		fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
618 		    vme->u.msr.code, vcpu_id(vcpu));
619 		if (get_config_bool("x86.strictmsr")) {
620 			vm_inject_gp(vcpu);
621 			return (VMEXIT_CONTINUE);
622 		}
623 	}
624 
625 	eax = val;
626 	error = vm_set_register(vcpu, VM_REG_GUEST_RAX, eax);
627 	assert(error == 0);
628 
629 	edx = val >> 32;
630 	error = vm_set_register(vcpu, VM_REG_GUEST_RDX, edx);
631 	assert(error == 0);
632 
633 	return (VMEXIT_CONTINUE);
634 }
635 
636 static int
637 vmexit_wrmsr(struct vmctx *ctx __unused, struct vcpu *vcpu,
638     struct vm_run *vmrun)
639 {
640 	struct vm_exit *vme;
641 	int error;
642 
643 	vme = vmrun->vm_exit;
644 
645 	error = emulate_wrmsr(vcpu, vme->u.msr.code, vme->u.msr.wval);
646 	if (error != 0) {
647 		fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
648 		    vme->u.msr.code, vme->u.msr.wval, vcpu_id(vcpu));
649 		if (get_config_bool("x86.strictmsr")) {
650 			vm_inject_gp(vcpu);
651 			return (VMEXIT_CONTINUE);
652 		}
653 	}
654 	return (VMEXIT_CONTINUE);
655 }
656 
657 #define	DEBUG_EPT_MISCONFIG
658 #ifdef DEBUG_EPT_MISCONFIG
659 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
660 
661 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
662 static int ept_misconfig_ptenum;
663 #endif
664 
665 static const char *
666 vmexit_vmx_desc(uint32_t exit_reason)
667 {
668 
669 	if (exit_reason >= nitems(vmx_exit_reason_desc) ||
670 	    vmx_exit_reason_desc[exit_reason] == NULL)
671 		return ("Unknown");
672 	return (vmx_exit_reason_desc[exit_reason]);
673 }
674 
675 static int
676 vmexit_vmx(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
677 {
678 	struct vm_exit *vme;
679 
680 	vme = vmrun->vm_exit;
681 
682 	fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
683 	fprintf(stderr, "\treason\t\tVMX\n");
684 	fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
685 	fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
686 	fprintf(stderr, "\tstatus\t\t%d\n", vme->u.vmx.status);
687 	fprintf(stderr, "\texit_reason\t%u (%s)\n", vme->u.vmx.exit_reason,
688 	    vmexit_vmx_desc(vme->u.vmx.exit_reason));
689 	fprintf(stderr, "\tqualification\t0x%016lx\n",
690 	    vme->u.vmx.exit_qualification);
691 	fprintf(stderr, "\tinst_type\t\t%d\n", vme->u.vmx.inst_type);
692 	fprintf(stderr, "\tinst_error\t\t%d\n", vme->u.vmx.inst_error);
693 #ifdef DEBUG_EPT_MISCONFIG
694 	if (vme->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
695 		vm_get_register(vcpu,
696 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
697 		    &ept_misconfig_gpa);
698 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
699 		    &ept_misconfig_ptenum);
700 		fprintf(stderr, "\tEPT misconfiguration:\n");
701 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
702 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
703 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
704 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
705 		    ept_misconfig_pte[3]);
706 	}
707 #endif	/* DEBUG_EPT_MISCONFIG */
708 	return (VMEXIT_ABORT);
709 }
710 
711 static int
712 vmexit_svm(struct vmctx *ctx __unused, struct vcpu *vcpu, struct vm_run *vmrun)
713 {
714 	struct vm_exit *vme;
715 
716 	vme = vmrun->vm_exit;
717 
718 	fprintf(stderr, "vm exit[%d]\n", vcpu_id(vcpu));
719 	fprintf(stderr, "\treason\t\tSVM\n");
720 	fprintf(stderr, "\trip\t\t0x%016lx\n", vme->rip);
721 	fprintf(stderr, "\tinst_length\t%d\n", vme->inst_length);
722 	fprintf(stderr, "\texitcode\t%#lx\n", vme->u.svm.exitcode);
723 	fprintf(stderr, "\texitinfo1\t%#lx\n", vme->u.svm.exitinfo1);
724 	fprintf(stderr, "\texitinfo2\t%#lx\n", vme->u.svm.exitinfo2);
725 	return (VMEXIT_ABORT);
726 }
727 
728 static int
729 vmexit_bogus(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
730     struct vm_run *vmrun)
731 {
732 	assert(vmrun->vm_exit->inst_length == 0);
733 
734 	return (VMEXIT_CONTINUE);
735 }
736 
737 static int
738 vmexit_reqidle(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
739     struct vm_run *vmrun)
740 {
741 	assert(vmrun->vm_exit->inst_length == 0);
742 
743 	return (VMEXIT_CONTINUE);
744 }
745 
746 static int
747 vmexit_hlt(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
748     struct vm_run *vmrun __unused)
749 {
750 	/*
751 	 * Just continue execution with the next instruction. We use
752 	 * the HLT VM exit as a way to be friendly with the host
753 	 * scheduler.
754 	 */
755 	return (VMEXIT_CONTINUE);
756 }
757 
758 static int
759 vmexit_pause(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
760     struct vm_run *vmrun __unused)
761 {
762 	return (VMEXIT_CONTINUE);
763 }
764 
765 static int
766 vmexit_mtrap(struct vmctx *ctx __unused, struct vcpu *vcpu,
767     struct vm_run *vmrun)
768 {
769 	assert(vmrun->vm_exit->inst_length == 0);
770 
771 #ifdef BHYVE_SNAPSHOT
772 	checkpoint_cpu_suspend(vcpu_id(vcpu));
773 #endif
774 	gdb_cpu_mtrap(vcpu);
775 #ifdef BHYVE_SNAPSHOT
776 	checkpoint_cpu_resume(vcpu_id(vcpu));
777 #endif
778 
779 	return (VMEXIT_CONTINUE);
780 }
781 
782 static int
783 vmexit_inst_emul(struct vmctx *ctx __unused, struct vcpu *vcpu,
784     struct vm_run *vmrun)
785 {
786 	struct vm_exit *vme;
787 	struct vie *vie;
788 	int err, i, cs_d;
789 	enum vm_cpu_mode mode;
790 
791 	vme = vmrun->vm_exit;
792 
793 	vie = &vme->u.inst_emul.vie;
794 	if (!vie->decoded) {
795 		/*
796 		 * Attempt to decode in userspace as a fallback.  This allows
797 		 * updating instruction decode in bhyve without rebooting the
798 		 * kernel (rapid prototyping), albeit with much slower
799 		 * emulation.
800 		 */
801 		vie_restart(vie);
802 		mode = vme->u.inst_emul.paging.cpu_mode;
803 		cs_d = vme->u.inst_emul.cs_d;
804 		if (vmm_decode_instruction(mode, cs_d, vie) != 0)
805 			goto fail;
806 		if (vm_set_register(vcpu, VM_REG_GUEST_RIP,
807 		    vme->rip + vie->num_processed) != 0)
808 			goto fail;
809 	}
810 
811 	err = emulate_mem(vcpu, vme->u.inst_emul.gpa, vie,
812 	    &vme->u.inst_emul.paging);
813 	if (err) {
814 		if (err == ESRCH) {
815 			EPRINTLN("Unhandled memory access to 0x%lx\n",
816 			    vme->u.inst_emul.gpa);
817 		}
818 		goto fail;
819 	}
820 
821 	return (VMEXIT_CONTINUE);
822 
823 fail:
824 	fprintf(stderr, "Failed to emulate instruction sequence [ ");
825 	for (i = 0; i < vie->num_valid; i++)
826 		fprintf(stderr, "%02x", vie->inst[i]);
827 	FPRINTLN(stderr, " ] at 0x%lx", vme->rip);
828 	return (VMEXIT_ABORT);
829 }
830 
831 static int
832 vmexit_suspend(struct vmctx *ctx, struct vcpu *vcpu, struct vm_run *vmrun)
833 {
834 	struct vm_exit *vme;
835 	enum vm_suspend_how how;
836 	int vcpuid = vcpu_id(vcpu);
837 
838 	vme = vmrun->vm_exit;
839 
840 	how = vme->u.suspended.how;
841 
842 	fbsdrun_deletecpu(vcpuid);
843 
844 	switch (how) {
845 	case VM_SUSPEND_RESET:
846 		exit(0);
847 	case VM_SUSPEND_POWEROFF:
848 		if (get_config_bool_default("destroy_on_poweroff", false))
849 			vm_destroy(ctx);
850 		exit(1);
851 	case VM_SUSPEND_HALT:
852 		exit(2);
853 	case VM_SUSPEND_TRIPLEFAULT:
854 		exit(3);
855 	default:
856 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
857 		exit(100);
858 	}
859 	return (0);	/* NOTREACHED */
860 }
861 
862 static int
863 vmexit_debug(struct vmctx *ctx __unused, struct vcpu *vcpu,
864     struct vm_run *vmrun __unused)
865 {
866 
867 #ifdef BHYVE_SNAPSHOT
868 	checkpoint_cpu_suspend(vcpu_id(vcpu));
869 #endif
870 	gdb_cpu_suspend(vcpu);
871 #ifdef BHYVE_SNAPSHOT
872 	checkpoint_cpu_resume(vcpu_id(vcpu));
873 #endif
874 	/*
875 	 * XXX-MJ sleep for a short period to avoid chewing up the CPU in the
876 	 * window between activation of the vCPU thread and the STARTUP IPI.
877 	 */
878 	usleep(1000);
879 	return (VMEXIT_CONTINUE);
880 }
881 
882 static int
883 vmexit_breakpoint(struct vmctx *ctx __unused, struct vcpu *vcpu,
884     struct vm_run *vmrun)
885 {
886 	gdb_cpu_breakpoint(vcpu, vmrun->vm_exit);
887 	return (VMEXIT_CONTINUE);
888 }
889 
890 static int
891 vmexit_ipi(struct vmctx *ctx __unused, struct vcpu *vcpu __unused,
892     struct vm_run *vmrun)
893 {
894 	struct vm_exit *vme;
895 	cpuset_t *dmask;
896 	int error = -1;
897 	int i;
898 
899 	dmask = vmrun->cpuset;
900 	vme = vmrun->vm_exit;
901 
902 	switch (vme->u.ipi.mode) {
903 	case APIC_DELMODE_INIT:
904 		CPU_FOREACH_ISSET(i, dmask) {
905 			error = vm_suspend_cpu(vcpu_info[i].vcpu);
906 			if (error) {
907 				warnx("%s: failed to suspend cpu %d\n",
908 				    __func__, i);
909 				break;
910 			}
911 		}
912 		break;
913 	case APIC_DELMODE_STARTUP:
914 		CPU_FOREACH_ISSET(i, dmask) {
915 			spinup_ap(vcpu_info[i].vcpu,
916 			    vme->u.ipi.vector << PAGE_SHIFT);
917 		}
918 		error = 0;
919 		break;
920 	default:
921 		break;
922 	}
923 
924 	return (error);
925 }
926 
927 static const vmexit_handler_t handler[VM_EXITCODE_MAX] = {
928 	[VM_EXITCODE_INOUT]  = vmexit_inout,
929 	[VM_EXITCODE_INOUT_STR]  = vmexit_inout,
930 	[VM_EXITCODE_VMX]    = vmexit_vmx,
931 	[VM_EXITCODE_SVM]    = vmexit_svm,
932 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
933 	[VM_EXITCODE_REQIDLE] = vmexit_reqidle,
934 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
935 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
936 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
937 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
938 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
939 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
940 	[VM_EXITCODE_DEBUG] = vmexit_debug,
941 	[VM_EXITCODE_BPT] = vmexit_breakpoint,
942 	[VM_EXITCODE_IPI] = vmexit_ipi,
943 	[VM_EXITCODE_HLT] = vmexit_hlt,
944 	[VM_EXITCODE_PAUSE] = vmexit_pause,
945 };
946 
947 static void
948 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
949 {
950 	struct vm_exit vme;
951 	struct vm_run vmrun;
952 	int error, rc;
953 	enum vm_exitcode exitcode;
954 	cpuset_t active_cpus, dmask;
955 
956 	error = vm_active_cpus(ctx, &active_cpus);
957 	assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
958 
959 	vmrun.vm_exit = &vme;
960 	vmrun.cpuset = &dmask;
961 	vmrun.cpusetsize = sizeof(dmask);
962 
963 	while (1) {
964 		error = vm_run(vcpu, &vmrun);
965 		if (error != 0)
966 			break;
967 
968 		exitcode = vme.exitcode;
969 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
970 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
971 			    exitcode);
972 			exit(4);
973 		}
974 
975 		rc = (*handler[exitcode])(ctx, vcpu, &vmrun);
976 
977 		switch (rc) {
978 		case VMEXIT_CONTINUE:
979 			break;
980 		case VMEXIT_ABORT:
981 			abort();
982 		default:
983 			exit(4);
984 		}
985 	}
986 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
987 }
988 
989 static int
990 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
991 {
992 	uint16_t sockets, cores, threads, maxcpus;
993 	int tmp, error;
994 
995 	/*
996 	 * The guest is allowed to spinup more than one processor only if the
997 	 * UNRESTRICTED_GUEST capability is available.
998 	 */
999 	error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1000 	if (error != 0)
1001 		return (1);
1002 
1003 	error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
1004 	if (error == 0)
1005 		return (maxcpus);
1006 	else
1007 		return (1);
1008 }
1009 
1010 static void
1011 fbsdrun_set_capabilities(struct vcpu *vcpu)
1012 {
1013 	int err, tmp;
1014 
1015 	if (get_config_bool_default("x86.vmexit_on_hlt", false)) {
1016 		err = vm_get_capability(vcpu, VM_CAP_HALT_EXIT, &tmp);
1017 		if (err < 0) {
1018 			fprintf(stderr, "VM exit on HLT not supported\n");
1019 			exit(4);
1020 		}
1021 		vm_set_capability(vcpu, VM_CAP_HALT_EXIT, 1);
1022 	}
1023 
1024 	if (get_config_bool_default("x86.vmexit_on_pause", false)) {
1025 		/*
1026 		 * pause exit support required for this mode
1027 		 */
1028 		err = vm_get_capability(vcpu, VM_CAP_PAUSE_EXIT, &tmp);
1029 		if (err < 0) {
1030 			fprintf(stderr,
1031 			    "SMP mux requested, no pause support\n");
1032 			exit(4);
1033 		}
1034 		vm_set_capability(vcpu, VM_CAP_PAUSE_EXIT, 1);
1035 	}
1036 
1037 	if (get_config_bool_default("x86.x2apic", false))
1038 		err = vm_set_x2apic_state(vcpu, X2APIC_ENABLED);
1039 	else
1040 		err = vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
1041 
1042 	if (err) {
1043 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1044 		exit(4);
1045 	}
1046 
1047 	vm_set_capability(vcpu, VM_CAP_ENABLE_INVPCID, 1);
1048 
1049 	err = vm_set_capability(vcpu, VM_CAP_IPI_EXIT, 1);
1050 	assert(err == 0);
1051 }
1052 
1053 static struct vmctx *
1054 do_open(const char *vmname)
1055 {
1056 	struct vmctx *ctx;
1057 	int error;
1058 	bool reinit, romboot;
1059 
1060 	reinit = romboot = false;
1061 
1062 	if (lpc_bootrom())
1063 		romboot = true;
1064 
1065 	error = vm_create(vmname);
1066 	if (error) {
1067 		if (errno == EEXIST) {
1068 			if (romboot) {
1069 				reinit = true;
1070 			} else {
1071 				/*
1072 				 * The virtual machine has been setup by the
1073 				 * userspace bootloader.
1074 				 */
1075 			}
1076 		} else {
1077 			perror("vm_create");
1078 			exit(4);
1079 		}
1080 	} else {
1081 		if (!romboot) {
1082 			/*
1083 			 * If the virtual machine was just created then a
1084 			 * bootrom must be configured to boot it.
1085 			 */
1086 			fprintf(stderr, "virtual machine cannot be booted\n");
1087 			exit(4);
1088 		}
1089 	}
1090 
1091 	ctx = vm_open(vmname);
1092 	if (ctx == NULL) {
1093 		perror("vm_open");
1094 		exit(4);
1095 	}
1096 
1097 #ifndef WITHOUT_CAPSICUM
1098 	if (vm_limit_rights(ctx) != 0)
1099 		err(EX_OSERR, "vm_limit_rights");
1100 #endif
1101 
1102 	if (reinit) {
1103 		error = vm_reinit(ctx);
1104 		if (error) {
1105 			perror("vm_reinit");
1106 			exit(4);
1107 		}
1108 	}
1109 	error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
1110 	if (error)
1111 		errx(EX_OSERR, "vm_set_topology");
1112 	return (ctx);
1113 }
1114 
1115 static void
1116 spinup_vcpu(struct vcpu_info *vi, bool bsp)
1117 {
1118 	int error;
1119 
1120 	if (!bsp) {
1121 		fbsdrun_set_capabilities(vi->vcpu);
1122 
1123 		/*
1124 		 * Enable the 'unrestricted guest' mode for APs.
1125 		 *
1126 		 * APs startup in power-on 16-bit mode.
1127 		 */
1128 		error = vm_set_capability(vi->vcpu, VM_CAP_UNRESTRICTED_GUEST, 1);
1129 		assert(error == 0);
1130 	}
1131 
1132 	fbsdrun_addcpu(vi);
1133 }
1134 
1135 static bool
1136 parse_config_option(const char *option)
1137 {
1138 	const char *value;
1139 	char *path;
1140 
1141 	value = strchr(option, '=');
1142 	if (value == NULL || value[1] == '\0')
1143 		return (false);
1144 	path = strndup(option, value - option);
1145 	if (path == NULL)
1146 		err(4, "Failed to allocate memory");
1147 	set_config_value(path, value + 1);
1148 	return (true);
1149 }
1150 
1151 static void
1152 parse_simple_config_file(const char *path)
1153 {
1154 	FILE *fp;
1155 	char *line, *cp;
1156 	size_t linecap;
1157 	unsigned int lineno;
1158 
1159 	fp = fopen(path, "r");
1160 	if (fp == NULL)
1161 		err(4, "Failed to open configuration file %s", path);
1162 	line = NULL;
1163 	linecap = 0;
1164 	lineno = 1;
1165 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
1166 		if (*line == '#' || *line == '\n')
1167 			continue;
1168 		cp = strchr(line, '\n');
1169 		if (cp != NULL)
1170 			*cp = '\0';
1171 		if (!parse_config_option(line))
1172 			errx(4, "%s line %u: invalid config option '%s'", path,
1173 			    lineno, line);
1174 	}
1175 	free(line);
1176 	fclose(fp);
1177 }
1178 
1179 static void
1180 parse_gdb_options(const char *opt)
1181 {
1182 	const char *sport;
1183 	char *colon;
1184 
1185 	if (opt[0] == 'w') {
1186 		set_config_bool("gdb.wait", true);
1187 		opt++;
1188 	}
1189 
1190 	colon = strrchr(opt, ':');
1191 	if (colon == NULL) {
1192 		sport = opt;
1193 	} else {
1194 		*colon = '\0';
1195 		colon++;
1196 		sport = colon;
1197 		set_config_value("gdb.address", opt);
1198 	}
1199 
1200 	set_config_value("gdb.port", sport);
1201 }
1202 
1203 static void
1204 set_defaults(void)
1205 {
1206 
1207 	set_config_bool("acpi_tables", false);
1208 	set_config_value("memory.size", "256M");
1209 	set_config_bool("x86.strictmsr", true);
1210 	set_config_value("lpc.fwcfg", "bhyve");
1211 }
1212 
1213 int
1214 main(int argc, char *argv[])
1215 {
1216 	int c, error;
1217 	int max_vcpus, memflags;
1218 	struct vcpu *bsp;
1219 	struct vmctx *ctx;
1220 	struct qemu_fwcfg_item *e820_fwcfg_item;
1221 	size_t memsize;
1222 	const char *optstr, *value, *vmname;
1223 #ifdef BHYVE_SNAPSHOT
1224 	char *restore_file;
1225 	struct restore_state rstate;
1226 
1227 	restore_file = NULL;
1228 #endif
1229 
1230 	init_config();
1231 	set_defaults();
1232 	progname = basename(argv[0]);
1233 
1234 #ifdef BHYVE_SNAPSHOT
1235 	optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:r:";
1236 #else
1237 	optstr = "aehuwxACDHIPSWYk:f:o:p:G:c:s:m:l:K:U:";
1238 #endif
1239 	while ((c = getopt(argc, argv, optstr)) != -1) {
1240 		switch (c) {
1241 		case 'a':
1242 			set_config_bool("x86.x2apic", false);
1243 			break;
1244 		case 'A':
1245 			set_config_bool("acpi_tables", true);
1246 			break;
1247 		case 'D':
1248 			set_config_bool("destroy_on_poweroff", true);
1249 			break;
1250 		case 'p':
1251 			if (pincpu_parse(optarg) != 0) {
1252 				errx(EX_USAGE, "invalid vcpu pinning "
1253 				    "configuration '%s'", optarg);
1254 			}
1255 			break;
1256 		case 'c':
1257 			if (topology_parse(optarg) != 0) {
1258 			    errx(EX_USAGE, "invalid cpu topology "
1259 				"'%s'", optarg);
1260 			}
1261 			break;
1262 		case 'C':
1263 			set_config_bool("memory.guest_in_core", true);
1264 			break;
1265 		case 'f':
1266 			if (qemu_fwcfg_parse_cmdline_arg(optarg) != 0) {
1267 			    errx(EX_USAGE, "invalid fwcfg item '%s'", optarg);
1268 			}
1269 			break;
1270 		case 'G':
1271 			parse_gdb_options(optarg);
1272 			break;
1273 		case 'k':
1274 			parse_simple_config_file(optarg);
1275 			break;
1276 		case 'K':
1277 			set_config_value("keyboard.layout", optarg);
1278 			break;
1279 		case 'l':
1280 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1281 				lpc_print_supported_devices();
1282 				exit(0);
1283 			} else if (lpc_device_parse(optarg) != 0) {
1284 				errx(EX_USAGE, "invalid lpc device "
1285 				    "configuration '%s'", optarg);
1286 			}
1287 			break;
1288 #ifdef BHYVE_SNAPSHOT
1289 		case 'r':
1290 			restore_file = optarg;
1291 			break;
1292 #endif
1293 		case 's':
1294 			if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1295 				pci_print_supported_devices();
1296 				exit(0);
1297 			} else if (pci_parse_slot(optarg) != 0)
1298 				exit(4);
1299 			else
1300 				break;
1301 		case 'S':
1302 			set_config_bool("memory.wired", true);
1303 			break;
1304 		case 'm':
1305 			set_config_value("memory.size", optarg);
1306 			break;
1307 		case 'o':
1308 			if (!parse_config_option(optarg))
1309 				errx(EX_USAGE, "invalid configuration option '%s'", optarg);
1310 			break;
1311 		case 'H':
1312 			set_config_bool("x86.vmexit_on_hlt", true);
1313 			break;
1314 		case 'I':
1315 			/*
1316 			 * The "-I" option was used to add an ioapic to the
1317 			 * virtual machine.
1318 			 *
1319 			 * An ioapic is now provided unconditionally for each
1320 			 * virtual machine and this option is now deprecated.
1321 			 */
1322 			break;
1323 		case 'P':
1324 			set_config_bool("x86.vmexit_on_pause", true);
1325 			break;
1326 		case 'e':
1327 			set_config_bool("x86.strictio", true);
1328 			break;
1329 		case 'u':
1330 			set_config_bool("rtc.use_localtime", false);
1331 			break;
1332 		case 'U':
1333 			set_config_value("uuid", optarg);
1334 			break;
1335 		case 'w':
1336 			set_config_bool("x86.strictmsr", false);
1337 			break;
1338 		case 'W':
1339 			set_config_bool("virtio_msix", false);
1340 			break;
1341 		case 'x':
1342 			set_config_bool("x86.x2apic", true);
1343 			break;
1344 		case 'Y':
1345 			set_config_bool("x86.mptable", false);
1346 			break;
1347 		case 'h':
1348 			usage(0);
1349 		default:
1350 			usage(1);
1351 		}
1352 	}
1353 	argc -= optind;
1354 	argv += optind;
1355 
1356 	if (argc > 1)
1357 		usage(1);
1358 
1359 #ifdef BHYVE_SNAPSHOT
1360 	if (restore_file != NULL) {
1361 		error = load_restore_file(restore_file, &rstate);
1362 		if (error) {
1363 			fprintf(stderr, "Failed to read checkpoint info from "
1364 					"file: '%s'.\n", restore_file);
1365 			exit(1);
1366 		}
1367 		vmname = lookup_vmname(&rstate);
1368 		if (vmname != NULL)
1369 			set_config_value("name", vmname);
1370 	}
1371 #endif
1372 
1373 	if (argc == 1)
1374 		set_config_value("name", argv[0]);
1375 
1376 	vmname = get_config_value("name");
1377 	if (vmname == NULL)
1378 		usage(1);
1379 
1380 	if (get_config_bool_default("config.dump", false)) {
1381 		dump_config();
1382 		exit(1);
1383 	}
1384 
1385 	calc_topology();
1386 	build_vcpumaps();
1387 
1388 	value = get_config_value("memory.size");
1389 	error = vm_parse_memsize(value, &memsize);
1390 	if (error)
1391 		errx(EX_USAGE, "invalid memsize '%s'", value);
1392 
1393 	ctx = do_open(vmname);
1394 
1395 #ifdef BHYVE_SNAPSHOT
1396 	if (restore_file != NULL) {
1397 		guest_ncpus = lookup_guest_ncpus(&rstate);
1398 		memflags = lookup_memflags(&rstate);
1399 		memsize = lookup_memsize(&rstate);
1400 	}
1401 
1402 	if (guest_ncpus < 1) {
1403 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
1404 		exit(1);
1405 	}
1406 #endif
1407 
1408 	bsp = vm_vcpu_open(ctx, BSP);
1409 	max_vcpus = num_vcpus_allowed(ctx, bsp);
1410 	if (guest_ncpus > max_vcpus) {
1411 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
1412 			guest_ncpus, max_vcpus);
1413 		exit(4);
1414 	}
1415 
1416 	fbsdrun_set_capabilities(bsp);
1417 
1418 	/* Allocate per-VCPU resources. */
1419 	vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
1420 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
1421 		vcpu_info[vcpuid].ctx = ctx;
1422 		vcpu_info[vcpuid].vcpuid = vcpuid;
1423 		if (vcpuid == BSP)
1424 			vcpu_info[vcpuid].vcpu = bsp;
1425 		else
1426 			vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
1427 	}
1428 
1429 	memflags = 0;
1430 	if (get_config_bool_default("memory.wired", false))
1431 		memflags |= VM_MEM_F_WIRED;
1432 	if (get_config_bool_default("memory.guest_in_core", false))
1433 		memflags |= VM_MEM_F_INCORE;
1434 	vm_set_memflags(ctx, memflags);
1435 	error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1436 	if (error) {
1437 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1438 		exit(4);
1439 	}
1440 
1441 	error = init_msr();
1442 	if (error) {
1443 		fprintf(stderr, "init_msr error %d", error);
1444 		exit(4);
1445 	}
1446 
1447 	init_mem(guest_ncpus);
1448 	init_inout();
1449 	kernemu_dev_init();
1450 	init_bootrom(ctx);
1451 	atkbdc_init(ctx);
1452 	pci_irq_init(ctx);
1453 	ioapic_init(ctx);
1454 
1455 	rtc_init(ctx);
1456 	sci_init(ctx);
1457 
1458 	if (qemu_fwcfg_init(ctx) != 0) {
1459 		fprintf(stderr, "qemu fwcfg initialization error");
1460 		exit(4);
1461 	}
1462 
1463 	if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
1464 	    &guest_ncpus) != 0) {
1465 		fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu");
1466 		exit(4);
1467 	}
1468 
1469 	if (e820_init(ctx) != 0) {
1470 		fprintf(stderr, "Unable to setup E820");
1471 		exit(4);
1472 	}
1473 
1474 	/*
1475 	 * Exit if a device emulation finds an error in its initialization
1476 	 */
1477 	if (init_pci(ctx) != 0) {
1478 		perror("device emulation initialization error");
1479 		exit(4);
1480 	}
1481 
1482 	/*
1483 	 * Initialize after PCI, to allow a bootrom file to reserve the high
1484 	 * region.
1485 	 */
1486 	if (get_config_bool("acpi_tables"))
1487 		vmgenc_init(ctx);
1488 
1489 	init_gdb(ctx);
1490 
1491 	if (lpc_bootrom()) {
1492 		if (vm_set_capability(bsp, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1493 			fprintf(stderr, "ROM boot failed: unrestricted guest "
1494 			    "capability not available\n");
1495 			exit(4);
1496 		}
1497 		error = vcpu_reset(bsp);
1498 		assert(error == 0);
1499 	}
1500 
1501 	/*
1502 	 * Add all vCPUs.
1503 	 */
1504 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1505 		spinup_vcpu(&vcpu_info[vcpuid], vcpuid == BSP);
1506 
1507 #ifdef BHYVE_SNAPSHOT
1508 	if (restore_file != NULL) {
1509 		fprintf(stdout, "Pausing pci devs...\r\n");
1510 		if (vm_pause_devices() != 0) {
1511 			fprintf(stderr, "Failed to pause PCI device state.\n");
1512 			exit(1);
1513 		}
1514 
1515 		fprintf(stdout, "Restoring vm mem...\r\n");
1516 		if (restore_vm_mem(ctx, &rstate) != 0) {
1517 			fprintf(stderr, "Failed to restore VM memory.\n");
1518 			exit(1);
1519 		}
1520 
1521 		fprintf(stdout, "Restoring pci devs...\r\n");
1522 		if (vm_restore_devices(&rstate) != 0) {
1523 			fprintf(stderr, "Failed to restore PCI device state.\n");
1524 			exit(1);
1525 		}
1526 
1527 		fprintf(stdout, "Restoring kernel structs...\r\n");
1528 		if (vm_restore_kern_structs(ctx, &rstate) != 0) {
1529 			fprintf(stderr, "Failed to restore kernel structs.\n");
1530 			exit(1);
1531 		}
1532 
1533 		fprintf(stdout, "Resuming pci devs...\r\n");
1534 		if (vm_resume_devices() != 0) {
1535 			fprintf(stderr, "Failed to resume PCI device state.\n");
1536 			exit(1);
1537 		}
1538 	}
1539 #endif
1540 
1541 	/*
1542 	 * build the guest tables, MP etc.
1543 	 */
1544 	if (get_config_bool_default("x86.mptable", true)) {
1545 		error = mptable_build(ctx, guest_ncpus);
1546 		if (error) {
1547 			perror("error to build the guest tables");
1548 			exit(4);
1549 		}
1550 	}
1551 
1552 	error = smbios_build(ctx);
1553 	if (error != 0)
1554 		exit(4);
1555 
1556 	if (get_config_bool("acpi_tables")) {
1557 		error = acpi_build(ctx, guest_ncpus);
1558 		assert(error == 0);
1559 	}
1560 
1561 	e820_fwcfg_item = e820_get_fwcfg_item();
1562 	if (e820_fwcfg_item == NULL) {
1563 	    fprintf(stderr, "invalid e820 table");
1564 		exit(4);
1565 	}
1566 	if (qemu_fwcfg_add_file("etc/e820", e820_fwcfg_item->size,
1567 		e820_fwcfg_item->data) != 0) {
1568 		fprintf(stderr, "could not add qemu fwcfg etc/e820");
1569 		exit(4);
1570 	}
1571 	free(e820_fwcfg_item);
1572 
1573 	if (lpc_bootrom() && strcmp(lpc_fwcfg(), "bhyve") == 0) {
1574 		fwctl_init();
1575 	}
1576 
1577 	/*
1578 	 * Change the proc title to include the VM name.
1579 	 */
1580 	setproctitle("%s", vmname);
1581 
1582 #ifdef BHYVE_SNAPSHOT
1583 	/* initialize mutex/cond variables */
1584 	init_snapshot();
1585 
1586 	/*
1587 	 * checkpointing thread for communication with bhyvectl
1588 	 */
1589 	if (init_checkpoint_thread(ctx) != 0)
1590 		errx(EX_OSERR, "Failed to start checkpoint thread");
1591 #endif
1592 
1593 #ifndef WITHOUT_CAPSICUM
1594 	caph_cache_catpages();
1595 
1596 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1597 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1598 
1599 	if (caph_enter() == -1)
1600 		errx(EX_OSERR, "cap_enter() failed");
1601 #endif
1602 
1603 #ifdef BHYVE_SNAPSHOT
1604 	if (restore_file != NULL) {
1605 		destroy_restore_state(&rstate);
1606 		if (vm_restore_time(ctx) < 0)
1607 			err(EX_OSERR, "Unable to restore time");
1608 
1609 		for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
1610 			vm_resume_cpu(vcpu_info[vcpuid].vcpu);
1611 	} else
1612 #endif
1613 		vm_resume_cpu(bsp);
1614 
1615 	/*
1616 	 * Head off to the main event dispatch loop
1617 	 */
1618 	mevent_dispatch();
1619 
1620 	exit(4);
1621 }
1622