xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision aa1a8ff2d6dbc51ef058f46f3db5a8bb77967145)
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 
29 #include <sys/types.h>
30 #ifndef WITHOUT_CAPSICUM
31 #include <sys/capsicum.h>
32 #endif
33 #include <sys/mman.h>
34 #ifdef BHYVE_SNAPSHOT
35 #include <sys/socket.h>
36 #include <sys/stat.h>
37 #endif
38 #include <sys/time.h>
39 #ifdef BHYVE_SNAPSHOT
40 #include <sys/un.h>
41 #endif
42 
43 #include <machine/atomic.h>
44 
45 #ifndef WITHOUT_CAPSICUM
46 #include <capsicum_helpers.h>
47 #endif
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <err.h>
52 #include <errno.h>
53 #ifdef BHYVE_SNAPSHOT
54 #include <fcntl.h>
55 #endif
56 #include <libgen.h>
57 #include <unistd.h>
58 #include <assert.h>
59 #include <pthread.h>
60 #include <pthread_np.h>
61 #include <sysexits.h>
62 #include <stdbool.h>
63 #include <stdint.h>
64 #ifdef BHYVE_SNAPSHOT
65 #include <ucl.h>
66 #include <unistd.h>
67 
68 #include <libxo/xo.h>
69 #endif
70 
71 #include <vmmapi.h>
72 
73 #include "acpi.h"
74 #include "bhyverun.h"
75 #include "bootrom.h"
76 #include "config.h"
77 #include "debug.h"
78 #ifdef BHYVE_GDB
79 #include "gdb.h"
80 #endif
81 #include "mem.h"
82 #include "mevent.h"
83 #include "pci_emul.h"
84 #ifdef __amd64__
85 #include "amd64/pci_lpc.h"
86 #endif
87 #include "qemu_fwcfg.h"
88 #ifdef BHYVE_SNAPSHOT
89 #include "snapshot.h"
90 #endif
91 #include "tpm_device.h"
92 #include "vmgenc.h"
93 #include "vmexit.h"
94 
95 #define MB		(1024UL * 1024)
96 #define GB		(1024UL * MB)
97 
98 int guest_ncpus;
99 uint16_t cpu_cores, cpu_sockets, cpu_threads;
100 
101 int raw_stdio = 0;
102 
103 #ifdef BHYVE_SNAPSHOT
104 char *restore_file;
105 #endif
106 
107 static const int BSP = 0;
108 
109 static cpuset_t cpumask;
110 
111 static void vm_loop(struct vmctx *ctx, struct vcpu *vcpu);
112 
113 static struct vcpu_info {
114 	struct vmctx	*ctx;
115 	struct vcpu	*vcpu;
116 	int		vcpuid;
117 } *vcpu_info;
118 
119 static cpuset_t **vcpumap;
120 
121 /*
122  * XXX This parser is known to have the following issues:
123  * 1.  It accepts null key=value tokens ",," as setting "cpus" to an
124  *     empty string.
125  *
126  * The acceptance of a null specification ('-c ""') is by design to match the
127  * manual page syntax specification, this results in a topology of 1 vCPU.
128  */
129 int
130 bhyve_topology_parse(const char *opt)
131 {
132 	char *cp, *str, *tofree;
133 
134 	if (*opt == '\0') {
135 		set_config_value("sockets", "1");
136 		set_config_value("cores", "1");
137 		set_config_value("threads", "1");
138 		set_config_value("cpus", "1");
139 		return (0);
140 	}
141 
142 	tofree = str = strdup(opt);
143 	if (str == NULL)
144 		errx(4, "Failed to allocate memory");
145 
146 	while ((cp = strsep(&str, ",")) != NULL) {
147 		if (strncmp(cp, "cpus=", strlen("cpus=")) == 0)
148 			set_config_value("cpus", cp + strlen("cpus="));
149 		else if (strncmp(cp, "sockets=", strlen("sockets=")) == 0)
150 			set_config_value("sockets", cp + strlen("sockets="));
151 		else if (strncmp(cp, "cores=", strlen("cores=")) == 0)
152 			set_config_value("cores", cp + strlen("cores="));
153 		else if (strncmp(cp, "threads=", strlen("threads=")) == 0)
154 			set_config_value("threads", cp + strlen("threads="));
155 		else if (strchr(cp, '=') != NULL)
156 			goto out;
157 		else
158 			set_config_value("cpus", cp);
159 	}
160 	free(tofree);
161 	return (0);
162 
163 out:
164 	free(tofree);
165 	return (-1);
166 }
167 
168 static int
169 parse_int_value(const char *key, const char *value, int minval, int maxval)
170 {
171 	char *cp;
172 	long lval;
173 
174 	errno = 0;
175 	lval = strtol(value, &cp, 0);
176 	if (errno != 0 || *cp != '\0' || cp == value || lval < minval ||
177 	    lval > maxval)
178 		errx(4, "Invalid value for %s: '%s'", key, value);
179 	return (lval);
180 }
181 
182 /*
183  * Set the sockets, cores, threads, and guest_cpus variables based on
184  * the configured topology.
185  *
186  * The limits of UINT16_MAX are due to the types passed to
187  * vm_set_topology().  vmm.ko may enforce tighter limits.
188  */
189 static void
190 calc_topology(void)
191 {
192 	const char *value;
193 	bool explicit_cpus;
194 	uint64_t ncpus;
195 
196 	value = get_config_value("cpus");
197 	if (value != NULL) {
198 		guest_ncpus = parse_int_value("cpus", value, 1, UINT16_MAX);
199 		explicit_cpus = true;
200 	} else {
201 		guest_ncpus = 1;
202 		explicit_cpus = false;
203 	}
204 	value = get_config_value("cores");
205 	if (value != NULL)
206 		cpu_cores = parse_int_value("cores", value, 1, UINT16_MAX);
207 	else
208 		cpu_cores = 1;
209 	value = get_config_value("threads");
210 	if (value != NULL)
211 		cpu_threads = parse_int_value("threads", value, 1, UINT16_MAX);
212 	else
213 		cpu_threads = 1;
214 	value = get_config_value("sockets");
215 	if (value != NULL)
216 		cpu_sockets = parse_int_value("sockets", value, 1, UINT16_MAX);
217 	else
218 		cpu_sockets = guest_ncpus;
219 
220 	/*
221 	 * Compute sockets * cores * threads avoiding overflow.  The
222 	 * range check above insures these are 16 bit values.
223 	 */
224 	ncpus = (uint64_t)cpu_sockets * cpu_cores * cpu_threads;
225 	if (ncpus > UINT16_MAX)
226 		errx(4, "Computed number of vCPUs too high: %ju",
227 		    (uintmax_t)ncpus);
228 
229 	if (explicit_cpus) {
230 		if (guest_ncpus != (int)ncpus)
231 			errx(4, "Topology (%d sockets, %d cores, %d threads) "
232 			    "does not match %d vCPUs",
233 			    cpu_sockets, cpu_cores, cpu_threads,
234 			    guest_ncpus);
235 	} else
236 		guest_ncpus = ncpus;
237 }
238 
239 int
240 bhyve_pincpu_parse(const char *opt)
241 {
242 	const char *value;
243 	char *newval;
244 	char key[16];
245 	int vcpu, pcpu;
246 
247 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
248 		fprintf(stderr, "invalid format: %s\n", opt);
249 		return (-1);
250 	}
251 
252 	if (vcpu < 0) {
253 		fprintf(stderr, "invalid vcpu '%d'\n", vcpu);
254 		return (-1);
255 	}
256 
257 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
258 		fprintf(stderr, "hostcpu '%d' outside valid range from "
259 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
260 		return (-1);
261 	}
262 
263 	snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
264 	value = get_config_value(key);
265 
266 	if (asprintf(&newval, "%s%s%d", value != NULL ? value : "",
267 	    value != NULL ? "," : "", pcpu) == -1) {
268 		perror("failed to build new cpuset string");
269 		return (-1);
270 	}
271 
272 	set_config_value(key, newval);
273 	free(newval);
274 	return (0);
275 }
276 
277 static void
278 parse_cpuset(int vcpu, const char *list, cpuset_t *set)
279 {
280 	char *cp, *token;
281 	int pcpu, start;
282 
283 	CPU_ZERO(set);
284 	start = -1;
285 	token = __DECONST(char *, list);
286 	for (;;) {
287 		pcpu = strtoul(token, &cp, 0);
288 		if (cp == token)
289 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
290 		if (pcpu < 0 || pcpu >= CPU_SETSIZE)
291 			errx(4, "hostcpu '%d' outside valid range from 0 to %d",
292 			    pcpu, CPU_SETSIZE - 1);
293 		switch (*cp) {
294 		case ',':
295 		case '\0':
296 			if (start >= 0) {
297 				if (start > pcpu)
298 					errx(4, "Invalid hostcpu range %d-%d",
299 					    start, pcpu);
300 				while (start < pcpu) {
301 					CPU_SET(start, set);
302 					start++;
303 				}
304 				start = -1;
305 			}
306 			CPU_SET(pcpu, set);
307 			break;
308 		case '-':
309 			if (start >= 0)
310 				errx(4, "invalid cpuset for vcpu %d: '%s'",
311 				    vcpu, list);
312 			start = pcpu;
313 			break;
314 		default:
315 			errx(4, "invalid cpuset for vcpu %d: '%s'", vcpu, list);
316 		}
317 		if (*cp == '\0')
318 			break;
319 		token = cp + 1;
320 	}
321 }
322 
323 static void
324 build_vcpumaps(void)
325 {
326 	char key[16];
327 	const char *value;
328 	int vcpu;
329 
330 	vcpumap = calloc(guest_ncpus, sizeof(*vcpumap));
331 	for (vcpu = 0; vcpu < guest_ncpus; vcpu++) {
332 		snprintf(key, sizeof(key), "vcpu.%d.cpuset", vcpu);
333 		value = get_config_value(key);
334 		if (value == NULL)
335 			continue;
336 		vcpumap[vcpu] = malloc(sizeof(cpuset_t));
337 		if (vcpumap[vcpu] == NULL)
338 			err(4, "Failed to allocate cpuset for vcpu %d", vcpu);
339 		parse_cpuset(vcpu, value, vcpumap[vcpu]);
340 	}
341 }
342 
343 void *
344 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
345 {
346 
347 	return (vm_map_gpa(ctx, gaddr, len));
348 }
349 
350 #ifdef BHYVE_SNAPSHOT
351 uintptr_t
352 paddr_host2guest(struct vmctx *ctx, void *addr)
353 {
354 	return (vm_rev_map_gpa(ctx, addr));
355 }
356 #endif
357 
358 int
359 fbsdrun_virtio_msix(void)
360 {
361 
362 	return (get_config_bool_default("virtio_msix", true));
363 }
364 
365 struct vcpu *
366 fbsdrun_vcpu(int vcpuid)
367 {
368 	return (vcpu_info[vcpuid].vcpu);
369 }
370 
371 static void *
372 fbsdrun_start_thread(void *param)
373 {
374 	char tname[MAXCOMLEN + 1];
375 	struct vcpu_info *vi = param;
376 	int error;
377 
378 	snprintf(tname, sizeof(tname), "vcpu %d", vi->vcpuid);
379 	pthread_set_name_np(pthread_self(), tname);
380 
381 	if (vcpumap[vi->vcpuid] != NULL) {
382 		error = pthread_setaffinity_np(pthread_self(),
383 		    sizeof(cpuset_t), vcpumap[vi->vcpuid]);
384 		assert(error == 0);
385 	}
386 
387 #ifdef BHYVE_SNAPSHOT
388 	checkpoint_cpu_add(vi->vcpuid);
389 #endif
390 #ifdef BHYVE_GDB
391 	gdb_cpu_add(vi->vcpu);
392 #endif
393 
394 	vm_loop(vi->ctx, vi->vcpu);
395 
396 	/* not reached */
397 	exit(1);
398 	return (NULL);
399 }
400 
401 void
402 fbsdrun_addcpu(int vcpuid)
403 {
404 	struct vcpu_info *vi;
405 	pthread_t thr;
406 	int error;
407 
408 	vi = &vcpu_info[vcpuid];
409 
410 	error = vm_activate_cpu(vi->vcpu);
411 	if (error != 0)
412 		err(EX_OSERR, "could not activate CPU %d", vi->vcpuid);
413 
414 	CPU_SET_ATOMIC(vcpuid, &cpumask);
415 
416 	vm_suspend_cpu(vi->vcpu);
417 
418 	error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
419 	assert(error == 0);
420 }
421 
422 void
423 fbsdrun_deletecpu(int vcpu)
424 {
425 	static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
426 	static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
427 
428 	pthread_mutex_lock(&resetcpu_mtx);
429 	if (!CPU_ISSET(vcpu, &cpumask)) {
430 		EPRINTLN("Attempting to delete unknown cpu %d", vcpu);
431 		exit(4);
432 	}
433 
434 	CPU_CLR(vcpu, &cpumask);
435 
436 	if (vcpu != BSP) {
437 		pthread_cond_signal(&resetcpu_cond);
438 		pthread_mutex_unlock(&resetcpu_mtx);
439 		pthread_exit(NULL);
440 		/* NOTREACHED */
441 	}
442 
443 	while (!CPU_EMPTY(&cpumask)) {
444 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
445 	}
446 	pthread_mutex_unlock(&resetcpu_mtx);
447 }
448 
449 int
450 fbsdrun_suspendcpu(int vcpuid)
451 {
452 	return (vm_suspend_cpu(vcpu_info[vcpuid].vcpu));
453 }
454 
455 static void
456 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
457 {
458 	struct vm_exit vme;
459 	struct vm_run vmrun;
460 	int error, rc;
461 	enum vm_exitcode exitcode;
462 	cpuset_t active_cpus, dmask;
463 
464 	error = vm_active_cpus(ctx, &active_cpus);
465 	assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
466 
467 	vmrun.vm_exit = &vme;
468 	vmrun.cpuset = &dmask;
469 	vmrun.cpusetsize = sizeof(dmask);
470 
471 	while (1) {
472 		error = vm_run(vcpu, &vmrun);
473 		if (error != 0)
474 			break;
475 
476 		exitcode = vme.exitcode;
477 		if (exitcode >= VM_EXITCODE_MAX ||
478 		    vmexit_handlers[exitcode] == NULL) {
479 			warnx("vm_loop: unexpected exitcode 0x%x", exitcode);
480 			exit(4);
481 		}
482 
483 		rc = (*vmexit_handlers[exitcode])(ctx, vcpu, &vmrun);
484 
485 		switch (rc) {
486 		case VMEXIT_CONTINUE:
487 			break;
488 		case VMEXIT_ABORT:
489 			abort();
490 		default:
491 			exit(4);
492 		}
493 	}
494 	EPRINTLN("vm_run error %d, errno %d", error, errno);
495 }
496 
497 static int
498 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
499 {
500 	uint16_t sockets, cores, threads, maxcpus;
501 	int tmp, error;
502 
503 	/*
504 	 * The guest is allowed to spinup more than one processor only if the
505 	 * UNRESTRICTED_GUEST capability is available.
506 	 */
507 	error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
508 	if (error != 0)
509 		return (1);
510 
511 	error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
512 	if (error == 0)
513 		return (maxcpus);
514 	else
515 		return (1);
516 }
517 
518 static struct vmctx *
519 do_open(const char *vmname)
520 {
521 	struct vmctx *ctx;
522 	int error;
523 	bool reinit, romboot;
524 
525 	reinit = false;
526 
527 #ifdef __amd64__
528 	romboot = lpc_bootrom() != NULL;
529 #else
530 	romboot = true;
531 #endif
532 
533 	error = vm_create(vmname);
534 	if (error) {
535 		if (errno == EEXIST) {
536 			if (romboot) {
537 				reinit = true;
538 			} else {
539 				/*
540 				 * The virtual machine has been setup by the
541 				 * userspace bootloader.
542 				 */
543 			}
544 		} else {
545 			perror("vm_create");
546 			exit(4);
547 		}
548 	} else {
549 		if (!romboot) {
550 			/*
551 			 * If the virtual machine was just created then a
552 			 * bootrom must be configured to boot it.
553 			 */
554 			fprintf(stderr, "virtual machine cannot be booted\n");
555 			exit(4);
556 		}
557 	}
558 
559 	ctx = vm_open(vmname);
560 	if (ctx == NULL) {
561 		perror("vm_open");
562 		exit(4);
563 	}
564 
565 #ifndef WITHOUT_CAPSICUM
566 	if (vm_limit_rights(ctx) != 0)
567 		err(EX_OSERR, "vm_limit_rights");
568 #endif
569 
570 	if (reinit) {
571 		error = vm_reinit(ctx);
572 		if (error) {
573 			perror("vm_reinit");
574 			exit(4);
575 		}
576 	}
577 	error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
578 	if (error)
579 		errx(EX_OSERR, "vm_set_topology");
580 	return (ctx);
581 }
582 
583 bool
584 bhyve_parse_config_option(const char *option)
585 {
586 	const char *value;
587 	char *path;
588 
589 	value = strchr(option, '=');
590 	if (value == NULL || value[1] == '\0')
591 		return (false);
592 	path = strndup(option, value - option);
593 	if (path == NULL)
594 		err(4, "Failed to allocate memory");
595 	set_config_value(path, value + 1);
596 	return (true);
597 }
598 
599 void
600 bhyve_parse_simple_config_file(const char *path)
601 {
602 	FILE *fp;
603 	char *line, *cp;
604 	size_t linecap;
605 	unsigned int lineno;
606 
607 	fp = fopen(path, "r");
608 	if (fp == NULL)
609 		err(4, "Failed to open configuration file %s", path);
610 	line = NULL;
611 	linecap = 0;
612 	lineno = 1;
613 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
614 		if (*line == '#' || *line == '\n')
615 			continue;
616 		cp = strchr(line, '\n');
617 		if (cp != NULL)
618 			*cp = '\0';
619 		if (!bhyve_parse_config_option(line))
620 			errx(4, "%s line %u: invalid config option '%s'", path,
621 			    lineno, line);
622 	}
623 	free(line);
624 	fclose(fp);
625 }
626 
627 #ifdef BHYVE_GDB
628 void
629 bhyve_parse_gdb_options(const char *opt)
630 {
631 	const char *sport;
632 	char *colon;
633 
634 	if (opt[0] == 'w') {
635 		set_config_bool("gdb.wait", true);
636 		opt++;
637 	}
638 
639 	colon = strrchr(opt, ':');
640 	if (colon == NULL) {
641 		sport = opt;
642 	} else {
643 		*colon = '\0';
644 		colon++;
645 		sport = colon;
646 		set_config_value("gdb.address", opt);
647 	}
648 
649 	set_config_value("gdb.port", sport);
650 }
651 #endif
652 
653 int
654 main(int argc, char *argv[])
655 {
656 	int error;
657 	int max_vcpus, memflags;
658 	struct vcpu *bsp;
659 	struct vmctx *ctx;
660 	size_t memsize;
661 	const char *value, *vmname;
662 #ifdef BHYVE_SNAPSHOT
663 	struct restore_state rstate;
664 #endif
665 
666 	bhyve_init_config();
667 	bhyve_optparse(argc, argv);
668 	argc -= optind;
669 	argv += optind;
670 
671 	if (argc > 1)
672 		bhyve_usage(1);
673 
674 #ifdef BHYVE_SNAPSHOT
675 	if (restore_file != NULL) {
676 		error = load_restore_file(restore_file, &rstate);
677 		if (error) {
678 			fprintf(stderr, "Failed to read checkpoint info from "
679 					"file: '%s'.\n", restore_file);
680 			exit(1);
681 		}
682 		vmname = lookup_vmname(&rstate);
683 		if (vmname != NULL)
684 			set_config_value("name", vmname);
685 	}
686 #endif
687 
688 	if (argc == 1)
689 		set_config_value("name", argv[0]);
690 
691 	vmname = get_config_value("name");
692 	if (vmname == NULL)
693 		bhyve_usage(1);
694 
695 	if (get_config_bool_default("config.dump", false)) {
696 		dump_config();
697 		exit(1);
698 	}
699 
700 	calc_topology();
701 	build_vcpumaps();
702 
703 	value = get_config_value("memory.size");
704 	error = vm_parse_memsize(value, &memsize);
705 	if (error)
706 		errx(EX_USAGE, "invalid memsize '%s'", value);
707 
708 	ctx = do_open(vmname);
709 
710 #ifdef BHYVE_SNAPSHOT
711 	if (restore_file != NULL) {
712 		guest_ncpus = lookup_guest_ncpus(&rstate);
713 		memflags = lookup_memflags(&rstate);
714 		memsize = lookup_memsize(&rstate);
715 	}
716 
717 	if (guest_ncpus < 1) {
718 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
719 		exit(1);
720 	}
721 #endif
722 
723 	bsp = vm_vcpu_open(ctx, BSP);
724 	max_vcpus = num_vcpus_allowed(ctx, bsp);
725 	if (guest_ncpus > max_vcpus) {
726 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
727 			guest_ncpus, max_vcpus);
728 		exit(4);
729 	}
730 
731 	bhyve_init_vcpu(bsp);
732 
733 	/* Allocate per-VCPU resources. */
734 	vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
735 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
736 		vcpu_info[vcpuid].ctx = ctx;
737 		vcpu_info[vcpuid].vcpuid = vcpuid;
738 		if (vcpuid == BSP)
739 			vcpu_info[vcpuid].vcpu = bsp;
740 		else
741 			vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
742 	}
743 
744 	memflags = 0;
745 	if (get_config_bool_default("memory.wired", false))
746 		memflags |= VM_MEM_F_WIRED;
747 	if (get_config_bool_default("memory.guest_in_core", false))
748 		memflags |= VM_MEM_F_INCORE;
749 	vm_set_memflags(ctx, memflags);
750 	error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
751 	if (error) {
752 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
753 		exit(4);
754 	}
755 
756 	init_mem(guest_ncpus);
757 	init_bootrom(ctx);
758 	if (bhyve_init_platform(ctx, bsp) != 0)
759 		exit(4);
760 
761 	if (qemu_fwcfg_init(ctx) != 0) {
762 		fprintf(stderr, "qemu fwcfg initialization error\n");
763 		exit(4);
764 	}
765 
766 	if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
767 	    &guest_ncpus) != 0) {
768 		fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu\n");
769 		exit(4);
770 	}
771 
772 	/*
773 	 * Exit if a device emulation finds an error in its initialization
774 	 */
775 	if (init_pci(ctx) != 0) {
776 		EPRINTLN("Device emulation initialization error: %s",
777 		    strerror(errno));
778 		exit(4);
779 	}
780 	if (init_tpm(ctx) != 0) {
781 		EPRINTLN("Failed to init TPM device");
782 		exit(4);
783 	}
784 
785 	/*
786 	 * Initialize after PCI, to allow a bootrom file to reserve the high
787 	 * region.
788 	 */
789 	if (get_config_bool("acpi_tables"))
790 		vmgenc_init(ctx);
791 
792 #ifdef BHYVE_GDB
793 	init_gdb(ctx);
794 #endif
795 
796 	/*
797 	 * Add all vCPUs.
798 	 */
799 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
800 		bhyve_start_vcpu(vcpu_info[vcpuid].vcpu, vcpuid == BSP);
801 
802 #ifdef BHYVE_SNAPSHOT
803 	if (restore_file != NULL) {
804 		FPRINTLN(stdout, "Pausing pci devs...");
805 		if (vm_pause_devices() != 0) {
806 			EPRINTLN("Failed to pause PCI device state.");
807 			exit(1);
808 		}
809 
810 		FPRINTLN(stdout, "Restoring vm mem...");
811 		if (restore_vm_mem(ctx, &rstate) != 0) {
812 			EPRINTLN("Failed to restore VM memory.");
813 			exit(1);
814 		}
815 
816 		FPRINTLN(stdout, "Restoring pci devs...");
817 		if (vm_restore_devices(&rstate) != 0) {
818 			EPRINTLN("Failed to restore PCI device state.");
819 			exit(1);
820 		}
821 
822 		FPRINTLN(stdout, "Restoring kernel structs...");
823 		if (vm_restore_kern_structs(ctx, &rstate) != 0) {
824 			EPRINTLN("Failed to restore kernel structs.");
825 			exit(1);
826 		}
827 
828 		FPRINTLN(stdout, "Resuming pci devs...");
829 		if (vm_resume_devices() != 0) {
830 			EPRINTLN("Failed to resume PCI device state.");
831 			exit(1);
832 		}
833 	}
834 #endif
835 
836 	if (bhyve_init_platform_late(ctx, bsp) != 0)
837 		exit(4);
838 
839 	/*
840 	 * Change the proc title to include the VM name.
841 	 */
842 	setproctitle("%s", vmname);
843 
844 #ifdef BHYVE_SNAPSHOT
845 	/*
846 	 * checkpointing thread for communication with bhyvectl
847 	 */
848 	if (init_checkpoint_thread(ctx) != 0)
849 		errx(EX_OSERR, "Failed to start checkpoint thread");
850 #endif
851 
852 #ifndef WITHOUT_CAPSICUM
853 	caph_cache_catpages();
854 
855 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
856 		errx(EX_OSERR, "Unable to apply rights for sandbox");
857 
858 	if (caph_enter() == -1)
859 		errx(EX_OSERR, "cap_enter() failed");
860 #endif
861 
862 #ifdef BHYVE_SNAPSHOT
863 	if (restore_file != NULL) {
864 		destroy_restore_state(&rstate);
865 		if (vm_restore_time(ctx) < 0)
866 			err(EX_OSERR, "Unable to restore time");
867 
868 		for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
869 			vm_resume_cpu(vcpu_info[vcpuid].vcpu);
870 	} else
871 #endif
872 		vm_resume_cpu(bsp);
873 
874 	/*
875 	 * Head off to the main event dispatch loop
876 	 */
877 	mevent_dispatch();
878 
879 	exit(4);
880 }
881