xref: /freebsd/usr.sbin/bhyve/bhyverun.c (revision 2e5b60079b7d8c3ca68f1390cd90f305e651f8d3)
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/types.h>
33 #include <sys/mman.h>
34 #include <sys/time.h>
35 
36 #include <machine/atomic.h>
37 #include <machine/segments.h>
38 
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <err.h>
43 #include <libgen.h>
44 #include <unistd.h>
45 #include <assert.h>
46 #include <errno.h>
47 #include <pthread.h>
48 #include <pthread_np.h>
49 #include <sysexits.h>
50 
51 #include <machine/vmm.h>
52 #include <vmmapi.h>
53 
54 #include "bhyverun.h"
55 #include "acpi.h"
56 #include "inout.h"
57 #include "dbgport.h"
58 #include "ioapic.h"
59 #include "mem.h"
60 #include "mevent.h"
61 #include "mptbl.h"
62 #include "pci_emul.h"
63 #include "pci_irq.h"
64 #include "pci_lpc.h"
65 #include "smbiostbl.h"
66 #include "xmsr.h"
67 #include "spinup_ap.h"
68 #include "rtc.h"
69 
70 #define GUEST_NIO_PORT		0x488	/* guest upcalls via i/o port */
71 
72 #define MB		(1024UL * 1024)
73 #define GB		(1024UL * MB)
74 
75 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
76 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
77 
78 char *vmname;
79 
80 int guest_ncpus;
81 char *guest_uuid_str;
82 
83 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
84 static int virtio_msix = 1;
85 static int x2apic_mode = 0;	/* default is xAPIC */
86 
87 static int strictio;
88 static int strictmsr = 1;
89 
90 static int acpi;
91 
92 static char *progname;
93 static const int BSP = 0;
94 
95 static cpuset_t cpumask;
96 
97 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
98 
99 static struct vm_exit vmexit[VM_MAXCPU];
100 
101 struct bhyvestats {
102         uint64_t        vmexit_bogus;
103         uint64_t        vmexit_bogus_switch;
104         uint64_t        vmexit_hlt;
105         uint64_t        vmexit_pause;
106         uint64_t        vmexit_mtrap;
107         uint64_t        vmexit_inst_emul;
108         uint64_t        cpu_switch_rotate;
109         uint64_t        cpu_switch_direct;
110 } stats;
111 
112 struct mt_vmm_info {
113 	pthread_t	mt_thr;
114 	struct vmctx	*mt_ctx;
115 	int		mt_vcpu;
116 } mt_vmm_info[VM_MAXCPU];
117 
118 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
119 
120 static void
121 usage(int code)
122 {
123 
124         fprintf(stderr,
125                 "Usage: %s [-abehwxACHPWY] [-c vcpus] [-g <gdb port>] [-l <lpc>]\n"
126 		"       %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
127 		"       -a: local apic is in xAPIC mode (deprecated)\n"
128 		"       -A: create ACPI tables\n"
129 		"       -c: # cpus (default 1)\n"
130 		"       -C: include guest memory in core file\n"
131 		"       -e: exit on unhandled I/O access\n"
132 		"       -g: gdb port\n"
133 		"       -h: help\n"
134 		"       -H: vmexit from the guest on hlt\n"
135 		"       -l: LPC device configuration\n"
136 		"       -m: memory size in MB\n"
137 		"       -p: pin 'vcpu' to 'hostcpu'\n"
138 		"       -P: vmexit from the guest on pause\n"
139 		"       -s: <slot,driver,configinfo> PCI slot config\n"
140 		"       -U: uuid\n"
141 		"       -w: ignore unimplemented MSRs\n"
142 		"       -W: force virtio to use single-vector MSI\n"
143 		"       -x: local apic is in x2APIC mode\n"
144 		"       -Y: disable MPtable generation\n",
145 		progname, (int)strlen(progname), "");
146 
147 	exit(code);
148 }
149 
150 static int
151 pincpu_parse(const char *opt)
152 {
153 	int vcpu, pcpu;
154 
155 	if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
156 		fprintf(stderr, "invalid format: %s\n", opt);
157 		return (-1);
158 	}
159 
160 	if (vcpu < 0 || vcpu >= VM_MAXCPU) {
161 		fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
162 		    vcpu, VM_MAXCPU - 1);
163 		return (-1);
164 	}
165 
166 	if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
167 		fprintf(stderr, "hostcpu '%d' outside valid range from "
168 		    "0 to %d\n", pcpu, CPU_SETSIZE - 1);
169 		return (-1);
170 	}
171 
172 	if (vcpumap[vcpu] == NULL) {
173 		if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
174 			perror("malloc");
175 			return (-1);
176 		}
177 		CPU_ZERO(vcpumap[vcpu]);
178 	}
179 	CPU_SET(pcpu, vcpumap[vcpu]);
180 	return (0);
181 }
182 
183 void
184 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
185     int errcode)
186 {
187 	struct vmctx *ctx;
188 	int error, restart_instruction;
189 
190 	ctx = arg;
191 	restart_instruction = 1;
192 
193 	error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
194 	    restart_instruction);
195 	assert(error == 0);
196 }
197 
198 void *
199 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
200 {
201 
202 	return (vm_map_gpa(ctx, gaddr, len));
203 }
204 
205 int
206 fbsdrun_vmexit_on_pause(void)
207 {
208 
209 	return (guest_vmexit_on_pause);
210 }
211 
212 int
213 fbsdrun_vmexit_on_hlt(void)
214 {
215 
216 	return (guest_vmexit_on_hlt);
217 }
218 
219 int
220 fbsdrun_virtio_msix(void)
221 {
222 
223 	return (virtio_msix);
224 }
225 
226 static void *
227 fbsdrun_start_thread(void *param)
228 {
229 	char tname[MAXCOMLEN + 1];
230 	struct mt_vmm_info *mtp;
231 	int vcpu;
232 
233 	mtp = param;
234 	vcpu = mtp->mt_vcpu;
235 
236 	snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
237 	pthread_set_name_np(mtp->mt_thr, tname);
238 
239 	vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
240 
241 	/* not reached */
242 	exit(1);
243 	return (NULL);
244 }
245 
246 void
247 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
248 {
249 	int error;
250 
251 	assert(fromcpu == BSP);
252 
253 	/*
254 	 * The 'newcpu' must be activated in the context of 'fromcpu'. If
255 	 * vm_activate_cpu() is delayed until newcpu's pthread starts running
256 	 * then vmm.ko is out-of-sync with bhyve and this can create a race
257 	 * with vm_suspend().
258 	 */
259 	error = vm_activate_cpu(ctx, newcpu);
260 	assert(error == 0);
261 
262 	CPU_SET_ATOMIC(newcpu, &cpumask);
263 
264 	/*
265 	 * Set up the vmexit struct to allow execution to start
266 	 * at the given RIP
267 	 */
268 	vmexit[newcpu].rip = rip;
269 	vmexit[newcpu].inst_length = 0;
270 
271 	mt_vmm_info[newcpu].mt_ctx = ctx;
272 	mt_vmm_info[newcpu].mt_vcpu = newcpu;
273 
274 	error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
275 	    fbsdrun_start_thread, &mt_vmm_info[newcpu]);
276 	assert(error == 0);
277 }
278 
279 static int
280 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
281 {
282 
283 	if (!CPU_ISSET(vcpu, &cpumask)) {
284 		fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
285 		exit(1);
286 	}
287 
288 	CPU_CLR_ATOMIC(vcpu, &cpumask);
289 	return (CPU_EMPTY(&cpumask));
290 }
291 
292 static int
293 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
294 		     uint32_t eax)
295 {
296 #if BHYVE_DEBUG
297 	/*
298 	 * put guest-driven debug here
299 	 */
300 #endif
301         return (VMEXIT_CONTINUE);
302 }
303 
304 static int
305 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
306 {
307 	int error;
308 	int bytes, port, in, out, string;
309 	int vcpu;
310 
311 	vcpu = *pvcpu;
312 
313 	port = vme->u.inout.port;
314 	bytes = vme->u.inout.bytes;
315 	string = vme->u.inout.string;
316 	in = vme->u.inout.in;
317 	out = !in;
318 
319         /* Extra-special case of host notifications */
320         if (out && port == GUEST_NIO_PORT) {
321                 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax);
322 		return (error);
323 	}
324 
325 	error = emulate_inout(ctx, vcpu, vme, strictio);
326 	if (error) {
327 		fprintf(stderr, "Unhandled %s%c 0x%04x\n", in ? "in" : "out",
328 		    bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'), port);
329 		return (VMEXIT_ABORT);
330 	} else {
331 		return (VMEXIT_CONTINUE);
332 	}
333 }
334 
335 static int
336 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
337 {
338 	uint64_t val;
339 	uint32_t eax, edx;
340 	int error;
341 
342 	val = 0;
343 	error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
344 	if (error != 0) {
345 		fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
346 		    vme->u.msr.code, *pvcpu);
347 		if (strictmsr) {
348 			vm_inject_gp(ctx, *pvcpu);
349 			return (VMEXIT_CONTINUE);
350 		}
351 	}
352 
353 	eax = val;
354 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
355 	assert(error == 0);
356 
357 	edx = val >> 32;
358 	error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
359 	assert(error == 0);
360 
361 	return (VMEXIT_CONTINUE);
362 }
363 
364 static int
365 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
366 {
367 	int error;
368 
369 	error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
370 	if (error != 0) {
371 		fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
372 		    vme->u.msr.code, vme->u.msr.wval, *pvcpu);
373 		if (strictmsr) {
374 			vm_inject_gp(ctx, *pvcpu);
375 			return (VMEXIT_CONTINUE);
376 		}
377 	}
378 	return (VMEXIT_CONTINUE);
379 }
380 
381 static int
382 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
383 {
384 	int newcpu;
385 	int retval = VMEXIT_CONTINUE;
386 
387 	newcpu = spinup_ap(ctx, *pvcpu,
388 			   vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
389 
390 	return (retval);
391 }
392 
393 #define	DEBUG_EPT_MISCONFIG
394 #ifdef DEBUG_EPT_MISCONFIG
395 #define	EXIT_REASON_EPT_MISCONFIG	49
396 #define	VMCS_GUEST_PHYSICAL_ADDRESS	0x00002400
397 #define	VMCS_IDENT(x)			((x) | 0x80000000)
398 
399 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
400 static int ept_misconfig_ptenum;
401 #endif
402 
403 static int
404 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
405 {
406 
407 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
408 	fprintf(stderr, "\treason\t\tVMX\n");
409 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
410 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
411 	fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
412 	fprintf(stderr, "\texit_reason\t%u\n", vmexit->u.vmx.exit_reason);
413 	fprintf(stderr, "\tqualification\t0x%016lx\n",
414 	    vmexit->u.vmx.exit_qualification);
415 	fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
416 	fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
417 #ifdef DEBUG_EPT_MISCONFIG
418 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
419 		vm_get_register(ctx, *pvcpu,
420 		    VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
421 		    &ept_misconfig_gpa);
422 		vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
423 		    &ept_misconfig_ptenum);
424 		fprintf(stderr, "\tEPT misconfiguration:\n");
425 		fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
426 		fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
427 		    ept_misconfig_ptenum, ept_misconfig_pte[0],
428 		    ept_misconfig_pte[1], ept_misconfig_pte[2],
429 		    ept_misconfig_pte[3]);
430 	}
431 #endif	/* DEBUG_EPT_MISCONFIG */
432 	return (VMEXIT_ABORT);
433 }
434 
435 static int
436 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
437 {
438 
439 	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
440 	fprintf(stderr, "\treason\t\tSVM\n");
441 	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
442 	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
443 	fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
444 	fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
445 	fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
446 	return (VMEXIT_ABORT);
447 }
448 
449 static int
450 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
451 {
452 
453 	assert(vmexit->inst_length == 0);
454 
455 	stats.vmexit_bogus++;
456 
457 	return (VMEXIT_CONTINUE);
458 }
459 
460 static int
461 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
462 {
463 
464 	stats.vmexit_hlt++;
465 
466 	/*
467 	 * Just continue execution with the next instruction. We use
468 	 * the HLT VM exit as a way to be friendly with the host
469 	 * scheduler.
470 	 */
471 	return (VMEXIT_CONTINUE);
472 }
473 
474 static int
475 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
476 {
477 
478 	stats.vmexit_pause++;
479 
480 	return (VMEXIT_CONTINUE);
481 }
482 
483 static int
484 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
485 {
486 
487 	assert(vmexit->inst_length == 0);
488 
489 	stats.vmexit_mtrap++;
490 
491 	return (VMEXIT_CONTINUE);
492 }
493 
494 static int
495 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
496 {
497 	int err;
498 	stats.vmexit_inst_emul++;
499 
500 	err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
501 	    &vmexit->u.inst_emul.vie, &vmexit->u.inst_emul.paging);
502 
503 	if (err) {
504 		if (err == EINVAL) {
505 			fprintf(stderr,
506 			    "Failed to emulate instruction at 0x%lx\n",
507 			    vmexit->rip);
508 		} else if (err == ESRCH) {
509 			fprintf(stderr, "Unhandled memory access to 0x%lx\n",
510 			    vmexit->u.inst_emul.gpa);
511 		}
512 
513 		return (VMEXIT_ABORT);
514 	}
515 
516 	return (VMEXIT_CONTINUE);
517 }
518 
519 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
520 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
521 
522 static int
523 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
524 {
525 	enum vm_suspend_how how;
526 
527 	how = vmexit->u.suspended.how;
528 
529 	fbsdrun_deletecpu(ctx, *pvcpu);
530 
531 	if (*pvcpu != BSP) {
532 		pthread_mutex_lock(&resetcpu_mtx);
533 		pthread_cond_signal(&resetcpu_cond);
534 		pthread_mutex_unlock(&resetcpu_mtx);
535 		pthread_exit(NULL);
536 	}
537 
538 	pthread_mutex_lock(&resetcpu_mtx);
539 	while (!CPU_EMPTY(&cpumask)) {
540 		pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
541 	}
542 	pthread_mutex_unlock(&resetcpu_mtx);
543 
544 	switch (how) {
545 	case VM_SUSPEND_RESET:
546 		exit(0);
547 	case VM_SUSPEND_POWEROFF:
548 		exit(1);
549 	case VM_SUSPEND_HALT:
550 		exit(2);
551 	case VM_SUSPEND_TRIPLEFAULT:
552 		exit(3);
553 	default:
554 		fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
555 		exit(100);
556 	}
557 	return (0);	/* NOTREACHED */
558 }
559 
560 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
561 	[VM_EXITCODE_INOUT]  = vmexit_inout,
562 	[VM_EXITCODE_INOUT_STR]  = vmexit_inout,
563 	[VM_EXITCODE_VMX]    = vmexit_vmx,
564 	[VM_EXITCODE_SVM]    = vmexit_svm,
565 	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
566 	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
567 	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
568 	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
569 	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
570 	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
571 	[VM_EXITCODE_SUSPENDED] = vmexit_suspend,
572 	[VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
573 };
574 
575 static void
576 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
577 {
578 	int error, rc, prevcpu;
579 	enum vm_exitcode exitcode;
580 	cpuset_t active_cpus;
581 
582 	if (vcpumap[vcpu] != NULL) {
583 		error = pthread_setaffinity_np(pthread_self(),
584 		    sizeof(cpuset_t), vcpumap[vcpu]);
585 		assert(error == 0);
586 	}
587 
588 	error = vm_active_cpus(ctx, &active_cpus);
589 	assert(CPU_ISSET(vcpu, &active_cpus));
590 
591 	error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
592 	assert(error == 0);
593 
594 	while (1) {
595 		error = vm_run(ctx, vcpu, &vmexit[vcpu]);
596 		if (error != 0)
597 			break;
598 
599 		prevcpu = vcpu;
600 
601 		exitcode = vmexit[vcpu].exitcode;
602 		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
603 			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
604 			    exitcode);
605 			exit(1);
606 		}
607 
608                 rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
609 
610 		switch (rc) {
611 		case VMEXIT_CONTINUE:
612 			break;
613 		case VMEXIT_ABORT:
614 			abort();
615 		default:
616 			exit(1);
617 		}
618 	}
619 	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
620 }
621 
622 static int
623 num_vcpus_allowed(struct vmctx *ctx)
624 {
625 	int tmp, error;
626 
627 	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
628 
629 	/*
630 	 * The guest is allowed to spinup more than one processor only if the
631 	 * UNRESTRICTED_GUEST capability is available.
632 	 */
633 	if (error == 0)
634 		return (VM_MAXCPU);
635 	else
636 		return (1);
637 }
638 
639 void
640 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
641 {
642 	int err, tmp;
643 
644 	if (fbsdrun_vmexit_on_hlt()) {
645 		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
646 		if (err < 0) {
647 			fprintf(stderr, "VM exit on HLT not supported\n");
648 			exit(1);
649 		}
650 		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
651 		if (cpu == BSP)
652 			handler[VM_EXITCODE_HLT] = vmexit_hlt;
653 	}
654 
655         if (fbsdrun_vmexit_on_pause()) {
656 		/*
657 		 * pause exit support required for this mode
658 		 */
659 		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
660 		if (err < 0) {
661 			fprintf(stderr,
662 			    "SMP mux requested, no pause support\n");
663 			exit(1);
664 		}
665 		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
666 		if (cpu == BSP)
667 			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
668         }
669 
670 	if (x2apic_mode)
671 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
672 	else
673 		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
674 
675 	if (err) {
676 		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
677 		exit(1);
678 	}
679 
680 	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
681 }
682 
683 int
684 main(int argc, char *argv[])
685 {
686 	int c, error, gdb_port, err, bvmcons;
687 	int dump_guest_memory, max_vcpus, mptgen;
688 	struct vmctx *ctx;
689 	uint64_t rip;
690 	size_t memsize;
691 
692 	bvmcons = 0;
693 	dump_guest_memory = 0;
694 	progname = basename(argv[0]);
695 	gdb_port = 0;
696 	guest_ncpus = 1;
697 	memsize = 256 * MB;
698 	mptgen = 1;
699 
700 	while ((c = getopt(argc, argv, "abehwxACHIPWYp:g:c:s:m:l:U:")) != -1) {
701 		switch (c) {
702 		case 'a':
703 			x2apic_mode = 0;
704 			break;
705 		case 'A':
706 			acpi = 1;
707 			break;
708 		case 'b':
709 			bvmcons = 1;
710 			break;
711 		case 'p':
712                         if (pincpu_parse(optarg) != 0) {
713                             errx(EX_USAGE, "invalid vcpu pinning "
714                                  "configuration '%s'", optarg);
715                         }
716 			break;
717                 case 'c':
718 			guest_ncpus = atoi(optarg);
719 			break;
720 		case 'C':
721 			dump_guest_memory = 1;
722 			break;
723 		case 'g':
724 			gdb_port = atoi(optarg);
725 			break;
726 		case 'l':
727 			if (lpc_device_parse(optarg) != 0) {
728 				errx(EX_USAGE, "invalid lpc device "
729 				    "configuration '%s'", optarg);
730 			}
731 			break;
732 		case 's':
733 			if (pci_parse_slot(optarg) != 0)
734 				exit(1);
735 			else
736 				break;
737                 case 'm':
738 			error = vm_parse_memsize(optarg, &memsize);
739 			if (error)
740 				errx(EX_USAGE, "invalid memsize '%s'", optarg);
741 			break;
742 		case 'H':
743 			guest_vmexit_on_hlt = 1;
744 			break;
745 		case 'I':
746 			/*
747 			 * The "-I" option was used to add an ioapic to the
748 			 * virtual machine.
749 			 *
750 			 * An ioapic is now provided unconditionally for each
751 			 * virtual machine and this option is now deprecated.
752 			 */
753 			break;
754 		case 'P':
755 			guest_vmexit_on_pause = 1;
756 			break;
757 		case 'e':
758 			strictio = 1;
759 			break;
760 		case 'U':
761 			guest_uuid_str = optarg;
762 			break;
763 		case 'w':
764 			strictmsr = 0;
765 			break;
766 		case 'W':
767 			virtio_msix = 0;
768 			break;
769 		case 'x':
770 			x2apic_mode = 1;
771 			break;
772 		case 'Y':
773 			mptgen = 0;
774 			break;
775 		case 'h':
776 			usage(0);
777 		default:
778 			usage(1);
779 		}
780 	}
781 	argc -= optind;
782 	argv += optind;
783 
784 	if (argc != 1)
785 		usage(1);
786 
787 	vmname = argv[0];
788 
789 	ctx = vm_open(vmname);
790 	if (ctx == NULL) {
791 		perror("vm_open");
792 		exit(1);
793 	}
794 
795 	max_vcpus = num_vcpus_allowed(ctx);
796 	if (guest_ncpus > max_vcpus) {
797 		fprintf(stderr, "%d vCPUs requested but only %d available\n",
798 			guest_ncpus, max_vcpus);
799 		exit(1);
800 	}
801 
802 	fbsdrun_set_capabilities(ctx, BSP);
803 
804 	if (dump_guest_memory)
805 		vm_set_memflags(ctx, VM_MEM_F_INCORE);
806 	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
807 	if (err) {
808 		fprintf(stderr, "Unable to setup memory (%d)\n", err);
809 		exit(1);
810 	}
811 
812 	error = init_msr();
813 	if (error) {
814 		fprintf(stderr, "init_msr error %d", error);
815 		exit(1);
816 	}
817 
818 	init_mem();
819 	init_inout();
820 	pci_irq_init(ctx);
821 	ioapic_init(ctx);
822 
823 	rtc_init(ctx);
824 	sci_init(ctx);
825 
826 	/*
827 	 * Exit if a device emulation finds an error in it's initilization
828 	 */
829 	if (init_pci(ctx) != 0)
830 		exit(1);
831 
832 	if (gdb_port != 0)
833 		init_dbgport(gdb_port);
834 
835 	if (bvmcons)
836 		init_bvmcons();
837 
838 	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
839 	assert(error == 0);
840 
841 	/*
842 	 * build the guest tables, MP etc.
843 	 */
844 	if (mptgen) {
845 		error = mptable_build(ctx, guest_ncpus);
846 		if (error)
847 			exit(1);
848 	}
849 
850 	error = smbios_build(ctx);
851 	assert(error == 0);
852 
853 	if (acpi) {
854 		error = acpi_build(ctx, guest_ncpus);
855 		assert(error == 0);
856 	}
857 
858 	/*
859 	 * Change the proc title to include the VM name.
860 	 */
861 	setproctitle("%s", vmname);
862 
863 	/*
864 	 * Add CPU 0
865 	 */
866 	fbsdrun_addcpu(ctx, BSP, BSP, rip);
867 
868 	/*
869 	 * Head off to the main event dispatch loop
870 	 */
871 	mevent_dispatch();
872 
873 	exit(1);
874 }
875