xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision 4c5188bb)
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
bhyve_topology_parse(const char * opt)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
parse_int_value(const char * key,const char * value,int minval,int maxval)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
calc_topology(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
bhyve_pincpu_parse(const char * opt)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
parse_cpuset(int vcpu,const char * list,cpuset_t * set)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
build_vcpumaps(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 *
paddr_guest2host(struct vmctx * ctx,uintptr_t gaddr,size_t len)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
paddr_host2guest(struct vmctx * ctx,void * addr)352 paddr_host2guest(struct vmctx *ctx, void *addr)
353 {
354 	return (vm_rev_map_gpa(ctx, addr));
355 }
356 #endif
357 
358 int
fbsdrun_virtio_msix(void)359 fbsdrun_virtio_msix(void)
360 {
361 
362 	return (get_config_bool_default("virtio_msix", true));
363 }
364 
365 struct vcpu *
fbsdrun_vcpu(int vcpuid)366 fbsdrun_vcpu(int vcpuid)
367 {
368 	return (vcpu_info[vcpuid].vcpu);
369 }
370 
371 static void *
fbsdrun_start_thread(void * param)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
fbsdrun_addcpu(int vcpuid)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 	error = vm_suspend_cpu(vi->vcpu);
417 	assert(error == 0);
418 
419 	error = pthread_create(&thr, NULL, fbsdrun_start_thread, vi);
420 	assert(error == 0);
421 }
422 
423 void
fbsdrun_deletecpu(int vcpu)424 fbsdrun_deletecpu(int vcpu)
425 {
426 	static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
427 	static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
428 
429 	pthread_mutex_lock(&resetcpu_mtx);
430 	if (!CPU_ISSET(vcpu, &cpumask)) {
431 		EPRINTLN("Attempting to delete unknown cpu %d", vcpu);
432 		exit(4);
433 	}
434 
435 	CPU_CLR(vcpu, &cpumask);
436 
437 	if (vcpu != BSP) {
438 		pthread_cond_signal(&resetcpu_cond);
439 		pthread_mutex_unlock(&resetcpu_mtx);
440 		pthread_exit(NULL);
441 		/* NOTREACHED */
442 	}
443 
444 	while (!CPU_EMPTY(&cpumask)) {
445 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
446 	}
447 	pthread_mutex_unlock(&resetcpu_mtx);
448 }
449 
450 int
fbsdrun_suspendcpu(int vcpuid)451 fbsdrun_suspendcpu(int vcpuid)
452 {
453 	return (vm_suspend_cpu(vcpu_info[vcpuid].vcpu));
454 }
455 
456 static void
vm_loop(struct vmctx * ctx,struct vcpu * vcpu)457 vm_loop(struct vmctx *ctx, struct vcpu *vcpu)
458 {
459 	struct vm_exit vme;
460 	struct vm_run vmrun;
461 	int error, rc;
462 	enum vm_exitcode exitcode;
463 	cpuset_t active_cpus, dmask;
464 
465 	error = vm_active_cpus(ctx, &active_cpus);
466 	assert(CPU_ISSET(vcpu_id(vcpu), &active_cpus));
467 
468 	vmrun.vm_exit = &vme;
469 	vmrun.cpuset = &dmask;
470 	vmrun.cpusetsize = sizeof(dmask);
471 
472 	while (1) {
473 		error = vm_run(vcpu, &vmrun);
474 		if (error != 0)
475 			break;
476 
477 		exitcode = vme.exitcode;
478 		if (exitcode >= VM_EXITCODE_MAX ||
479 		    vmexit_handlers[exitcode] == NULL) {
480 			warnx("vm_loop: unexpected exitcode 0x%x", exitcode);
481 			exit(4);
482 		}
483 
484 		rc = (*vmexit_handlers[exitcode])(ctx, vcpu, &vmrun);
485 
486 		switch (rc) {
487 		case VMEXIT_CONTINUE:
488 			break;
489 		case VMEXIT_ABORT:
490 			abort();
491 		default:
492 			exit(4);
493 		}
494 	}
495 	EPRINTLN("vm_run error %d, errno %d", error, errno);
496 }
497 
498 static int
num_vcpus_allowed(struct vmctx * ctx,struct vcpu * vcpu)499 num_vcpus_allowed(struct vmctx *ctx, struct vcpu *vcpu)
500 {
501 	uint16_t sockets, cores, threads, maxcpus;
502 	int tmp, error;
503 
504 	/*
505 	 * The guest is allowed to spinup more than one processor only if the
506 	 * UNRESTRICTED_GUEST capability is available.
507 	 */
508 	error = vm_get_capability(vcpu, VM_CAP_UNRESTRICTED_GUEST, &tmp);
509 	if (error != 0)
510 		return (1);
511 
512 	error = vm_get_topology(ctx, &sockets, &cores, &threads, &maxcpus);
513 	if (error == 0)
514 		return (maxcpus);
515 	else
516 		return (1);
517 }
518 
519 static struct vmctx *
do_open(const char * vmname)520 do_open(const char *vmname)
521 {
522 	struct vmctx *ctx;
523 	int error;
524 	bool reinit, romboot;
525 
526 	reinit = false;
527 
528 #ifdef __amd64__
529 	romboot = lpc_bootrom() != NULL;
530 #else
531 	romboot = true;
532 #endif
533 
534 	error = vm_create(vmname);
535 	if (error) {
536 		if (errno == EEXIST) {
537 			if (romboot) {
538 				reinit = true;
539 			} else {
540 				/*
541 				 * The virtual machine has been setup by the
542 				 * userspace bootloader.
543 				 */
544 			}
545 		} else {
546 			perror("vm_create");
547 			exit(4);
548 		}
549 	} else {
550 		if (!romboot) {
551 			/*
552 			 * If the virtual machine was just created then a
553 			 * bootrom must be configured to boot it.
554 			 */
555 			fprintf(stderr, "virtual machine cannot be booted\n");
556 			exit(4);
557 		}
558 	}
559 
560 	ctx = vm_open(vmname);
561 	if (ctx == NULL) {
562 		perror("vm_open");
563 		exit(4);
564 	}
565 
566 #ifndef WITHOUT_CAPSICUM
567 	if (vm_limit_rights(ctx) != 0)
568 		err(EX_OSERR, "vm_limit_rights");
569 #endif
570 
571 	if (reinit) {
572 		error = vm_reinit(ctx);
573 		if (error) {
574 			perror("vm_reinit");
575 			exit(4);
576 		}
577 	}
578 	error = vm_set_topology(ctx, cpu_sockets, cpu_cores, cpu_threads, 0);
579 	if (error)
580 		errx(EX_OSERR, "vm_set_topology");
581 	return (ctx);
582 }
583 
584 bool
bhyve_parse_config_option(const char * option)585 bhyve_parse_config_option(const char *option)
586 {
587 	const char *value;
588 	char *path;
589 
590 	value = strchr(option, '=');
591 	if (value == NULL || value[1] == '\0')
592 		return (false);
593 	path = strndup(option, value - option);
594 	if (path == NULL)
595 		err(4, "Failed to allocate memory");
596 	set_config_value(path, value + 1);
597 	free(path);
598 	return (true);
599 }
600 
601 void
bhyve_parse_simple_config_file(const char * path)602 bhyve_parse_simple_config_file(const char *path)
603 {
604 	FILE *fp;
605 	char *line, *cp;
606 	size_t linecap;
607 	unsigned int lineno;
608 
609 	fp = fopen(path, "r");
610 	if (fp == NULL)
611 		err(4, "Failed to open configuration file %s", path);
612 	line = NULL;
613 	linecap = 0;
614 	lineno = 1;
615 	for (lineno = 1; getline(&line, &linecap, fp) > 0; lineno++) {
616 		if (*line == '#' || *line == '\n')
617 			continue;
618 		cp = strchr(line, '\n');
619 		if (cp != NULL)
620 			*cp = '\0';
621 		if (!bhyve_parse_config_option(line))
622 			errx(4, "%s line %u: invalid config option '%s'", path,
623 			    lineno, line);
624 	}
625 	free(line);
626 	fclose(fp);
627 }
628 
629 #ifdef BHYVE_GDB
630 void
bhyve_parse_gdb_options(const char * opt)631 bhyve_parse_gdb_options(const char *opt)
632 {
633 	const char *sport;
634 	char *colon;
635 
636 	if (opt[0] == 'w') {
637 		set_config_bool("gdb.wait", true);
638 		opt++;
639 	}
640 
641 	colon = strrchr(opt, ':');
642 	if (colon == NULL) {
643 		sport = opt;
644 	} else {
645 		*colon = '\0';
646 		colon++;
647 		sport = colon;
648 		set_config_value("gdb.address", opt);
649 	}
650 
651 	set_config_value("gdb.port", sport);
652 }
653 #endif
654 
655 int
main(int argc,char * argv[])656 main(int argc, char *argv[])
657 {
658 	int error;
659 	int max_vcpus, memflags;
660 	struct vcpu *bsp;
661 	struct vmctx *ctx;
662 	size_t memsize;
663 	const char *value, *vmname;
664 #ifdef BHYVE_SNAPSHOT
665 	struct restore_state rstate;
666 #endif
667 
668 	bhyve_init_config();
669 	bhyve_optparse(argc, argv);
670 	argc -= optind;
671 	argv += optind;
672 
673 	if (argc > 1)
674 		bhyve_usage(1);
675 
676 #ifdef BHYVE_SNAPSHOT
677 	if (restore_file != NULL) {
678 		error = load_restore_file(restore_file, &rstate);
679 		if (error) {
680 			fprintf(stderr, "Failed to read checkpoint info from "
681 					"file: '%s'.\n", restore_file);
682 			exit(1);
683 		}
684 		vmname = lookup_vmname(&rstate);
685 		if (vmname != NULL)
686 			set_config_value("name", vmname);
687 	}
688 #endif
689 
690 	if (argc == 1)
691 		set_config_value("name", argv[0]);
692 
693 	vmname = get_config_value("name");
694 	if (vmname == NULL)
695 		bhyve_usage(1);
696 
697 	if (get_config_bool_default("config.dump", false)) {
698 		dump_config();
699 		exit(1);
700 	}
701 
702 	calc_topology();
703 	build_vcpumaps();
704 
705 	value = get_config_value("memory.size");
706 	error = vm_parse_memsize(value, &memsize);
707 	if (error)
708 		errx(EX_USAGE, "invalid memsize '%s'", value);
709 
710 	ctx = do_open(vmname);
711 
712 #ifdef BHYVE_SNAPSHOT
713 	if (restore_file != NULL) {
714 		guest_ncpus = lookup_guest_ncpus(&rstate);
715 		memflags = lookup_memflags(&rstate);
716 		memsize = lookup_memsize(&rstate);
717 	}
718 
719 	if (guest_ncpus < 1) {
720 		fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
721 		exit(1);
722 	}
723 #endif
724 
725 	bsp = vm_vcpu_open(ctx, BSP);
726 	max_vcpus = num_vcpus_allowed(ctx, bsp);
727 	if (guest_ncpus > max_vcpus) {
728 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
729 			guest_ncpus, max_vcpus);
730 		exit(4);
731 	}
732 
733 	bhyve_init_vcpu(bsp);
734 
735 	/* Allocate per-VCPU resources. */
736 	vcpu_info = calloc(guest_ncpus, sizeof(*vcpu_info));
737 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++) {
738 		vcpu_info[vcpuid].ctx = ctx;
739 		vcpu_info[vcpuid].vcpuid = vcpuid;
740 		if (vcpuid == BSP)
741 			vcpu_info[vcpuid].vcpu = bsp;
742 		else
743 			vcpu_info[vcpuid].vcpu = vm_vcpu_open(ctx, vcpuid);
744 	}
745 
746 	memflags = 0;
747 	if (get_config_bool_default("memory.wired", false))
748 		memflags |= VM_MEM_F_WIRED;
749 	if (get_config_bool_default("memory.guest_in_core", false))
750 		memflags |= VM_MEM_F_INCORE;
751 	vm_set_memflags(ctx, memflags);
752 	error = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
753 	if (error) {
754 		fprintf(stderr, "Unable to setup memory (%d)\n", errno);
755 		exit(4);
756 	}
757 
758 	init_mem(guest_ncpus);
759 	init_bootrom(ctx);
760 	if (bhyve_init_platform(ctx, bsp) != 0)
761 		exit(4);
762 
763 	if (qemu_fwcfg_init(ctx) != 0) {
764 		fprintf(stderr, "qemu fwcfg initialization error\n");
765 		exit(4);
766 	}
767 
768 	if (qemu_fwcfg_add_file("opt/bhyve/hw.ncpu", sizeof(guest_ncpus),
769 	    &guest_ncpus) != 0) {
770 		fprintf(stderr, "Could not add qemu fwcfg opt/bhyve/hw.ncpu\n");
771 		exit(4);
772 	}
773 
774 	/*
775 	 * Exit if a device emulation finds an error in its initialization
776 	 */
777 	if (init_pci(ctx) != 0) {
778 		EPRINTLN("Device emulation initialization error: %s",
779 		    strerror(errno));
780 		exit(4);
781 	}
782 	if (init_tpm(ctx) != 0) {
783 		EPRINTLN("Failed to init TPM device");
784 		exit(4);
785 	}
786 
787 	/*
788 	 * Initialize after PCI, to allow a bootrom file to reserve the high
789 	 * region.
790 	 */
791 	if (get_config_bool("acpi_tables"))
792 		vmgenc_init(ctx);
793 
794 #ifdef BHYVE_GDB
795 	init_gdb(ctx);
796 #endif
797 
798 	/*
799 	 * Add all vCPUs.
800 	 */
801 	for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
802 		bhyve_start_vcpu(vcpu_info[vcpuid].vcpu, vcpuid == BSP);
803 
804 #ifdef BHYVE_SNAPSHOT
805 	if (restore_file != NULL) {
806 		FPRINTLN(stdout, "Pausing pci devs...");
807 		if (vm_pause_devices() != 0) {
808 			EPRINTLN("Failed to pause PCI device state.");
809 			exit(1);
810 		}
811 
812 		FPRINTLN(stdout, "Restoring vm mem...");
813 		if (restore_vm_mem(ctx, &rstate) != 0) {
814 			EPRINTLN("Failed to restore VM memory.");
815 			exit(1);
816 		}
817 
818 		FPRINTLN(stdout, "Restoring pci devs...");
819 		if (vm_restore_devices(&rstate) != 0) {
820 			EPRINTLN("Failed to restore PCI device state.");
821 			exit(1);
822 		}
823 
824 		FPRINTLN(stdout, "Restoring kernel structs...");
825 		if (vm_restore_kern_structs(ctx, &rstate) != 0) {
826 			EPRINTLN("Failed to restore kernel structs.");
827 			exit(1);
828 		}
829 
830 		FPRINTLN(stdout, "Resuming pci devs...");
831 		if (vm_resume_devices() != 0) {
832 			EPRINTLN("Failed to resume PCI device state.");
833 			exit(1);
834 		}
835 	}
836 #endif
837 
838 	if (bhyve_init_platform_late(ctx, bsp) != 0)
839 		exit(4);
840 
841 	/*
842 	 * Change the proc title to include the VM name.
843 	 */
844 	setproctitle("%s", vmname);
845 
846 #ifdef BHYVE_SNAPSHOT
847 	/*
848 	 * checkpointing thread for communication with bhyvectl
849 	 */
850 	if (init_checkpoint_thread(ctx) != 0)
851 		errx(EX_OSERR, "Failed to start checkpoint thread");
852 #endif
853 
854 #ifndef WITHOUT_CAPSICUM
855 	caph_cache_catpages();
856 
857 	if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
858 		errx(EX_OSERR, "Unable to apply rights for sandbox");
859 
860 	if (caph_enter() == -1)
861 		errx(EX_OSERR, "cap_enter() failed");
862 #endif
863 
864 #ifdef BHYVE_SNAPSHOT
865 	if (restore_file != NULL) {
866 		destroy_restore_state(&rstate);
867 		if (vm_restore_time(ctx) < 0)
868 			err(EX_OSERR, "Unable to restore time");
869 
870 		for (int vcpuid = 0; vcpuid < guest_ncpus; vcpuid++)
871 			vm_resume_cpu(vcpu_info[vcpuid].vcpu);
872 	} else
873 #endif
874 		vm_resume_cpu(bsp);
875 
876 	/*
877 	 * Head off to the main event dispatch loop
878 	 */
879 	mevent_dispatch();
880 
881 	exit(4);
882 }
883