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