bhyverun.c revision 261090
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: stable/10/usr.sbin/bhyve/bhyverun.c 261090 2014-01-23 20:35:32Z jhb $
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: stable/10/usr.sbin/bhyve/bhyverun.c 261090 2014-01-23 20:35:32Z jhb $");
31
32#include <sys/types.h>
33#include <sys/mman.h>
34#include <sys/time.h>
35
36#include <machine/segments.h>
37
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <err.h>
42#include <libgen.h>
43#include <unistd.h>
44#include <assert.h>
45#include <errno.h>
46#include <pthread.h>
47#include <pthread_np.h>
48#include <sysexits.h>
49
50#include <machine/vmm.h>
51#include <vmmapi.h>
52
53#include "bhyverun.h"
54#include "acpi.h"
55#include "inout.h"
56#include "dbgport.h"
57#include "legacy_irq.h"
58#include "mem.h"
59#include "mevent.h"
60#include "mptbl.h"
61#include "pci_emul.h"
62#include "pci_lpc.h"
63#include "xmsr.h"
64#include "spinup_ap.h"
65#include "rtc.h"
66
67#define GUEST_NIO_PORT		0x488	/* guest upcalls via i/o port */
68
69#define	VMEXIT_SWITCH		0	/* force vcpu switch in mux mode */
70#define	VMEXIT_CONTINUE		1	/* continue from next instruction */
71#define	VMEXIT_RESTART		2	/* restart current instruction */
72#define	VMEXIT_ABORT		3	/* abort the vm run loop */
73#define	VMEXIT_RESET		4	/* guest machine has reset */
74#define	VMEXIT_POWEROFF		5	/* guest machine has powered off */
75
76#define MB		(1024UL * 1024)
77#define GB		(1024UL * MB)
78
79typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
80
81char *vmname;
82
83int guest_ncpus;
84
85static int pincpu = -1;
86static int guest_vmexit_on_hlt, guest_vmexit_on_pause, disable_x2apic;
87static int virtio_msix = 1;
88
89static int foundcpus;
90
91static int strictio;
92
93static int acpi;
94
95static char *progname;
96static const int BSP = 0;
97
98static int cpumask;
99
100static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
101
102struct vm_exit vmexit[VM_MAXCPU];
103
104struct bhyvestats {
105        uint64_t        vmexit_bogus;
106        uint64_t        vmexit_bogus_switch;
107        uint64_t        vmexit_hlt;
108        uint64_t        vmexit_pause;
109        uint64_t        vmexit_mtrap;
110        uint64_t        vmexit_inst_emul;
111        uint64_t        cpu_switch_rotate;
112        uint64_t        cpu_switch_direct;
113        int             io_reset;
114} stats;
115
116struct mt_vmm_info {
117	pthread_t	mt_thr;
118	struct vmctx	*mt_ctx;
119	int		mt_vcpu;
120} mt_vmm_info[VM_MAXCPU];
121
122static void
123usage(int code)
124{
125
126        fprintf(stderr,
127                "Usage: %s [-aehAHIPW] [-g <gdb port>] [-s <pci>] [-S <pci>]\n"
128		"       %*s [-c vcpus] [-p pincpu] [-m mem] [-l <lpc>] <vm>\n"
129		"       -a: local apic is in XAPIC mode (default is X2APIC)\n"
130		"       -A: create an ACPI table\n"
131		"       -g: gdb port\n"
132		"       -c: # cpus (default 1)\n"
133		"       -p: pin vcpu 'n' to host cpu 'pincpu + n'\n"
134		"       -H: vmexit from the guest on hlt\n"
135		"       -P: vmexit from the guest on pause\n"
136		"       -W: force virtio to use single-vector MSI\n"
137		"       -e: exit on unhandled I/O access\n"
138		"       -h: help\n"
139		"       -s: <slot,driver,configinfo> PCI slot config\n"
140		"       -S: <slot,driver,configinfo> legacy PCI slot config\n"
141		"       -l: LPC device configuration\n"
142		"       -m: memory size in MB\n",
143		progname, (int)strlen(progname), "");
144
145	exit(code);
146}
147
148void *
149paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
150{
151
152	return (vm_map_gpa(ctx, gaddr, len));
153}
154
155int
156fbsdrun_disable_x2apic(void)
157{
158
159	return (disable_x2apic);
160}
161
162int
163fbsdrun_vmexit_on_pause(void)
164{
165
166	return (guest_vmexit_on_pause);
167}
168
169int
170fbsdrun_vmexit_on_hlt(void)
171{
172
173	return (guest_vmexit_on_hlt);
174}
175
176int
177fbsdrun_virtio_msix(void)
178{
179
180	return (virtio_msix);
181}
182
183static void *
184fbsdrun_start_thread(void *param)
185{
186	char tname[MAXCOMLEN + 1];
187	struct mt_vmm_info *mtp;
188	int vcpu;
189
190	mtp = param;
191	vcpu = mtp->mt_vcpu;
192
193	snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
194	pthread_set_name_np(mtp->mt_thr, tname);
195
196	vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
197
198	/* not reached */
199	exit(1);
200	return (NULL);
201}
202
203void
204fbsdrun_addcpu(struct vmctx *ctx, int vcpu, uint64_t rip)
205{
206	int error;
207
208	if (cpumask & (1 << vcpu)) {
209		fprintf(stderr, "addcpu: attempting to add existing cpu %d\n",
210		    vcpu);
211		exit(1);
212	}
213
214	cpumask |= 1 << vcpu;
215	foundcpus++;
216
217	/*
218	 * Set up the vmexit struct to allow execution to start
219	 * at the given RIP
220	 */
221	vmexit[vcpu].rip = rip;
222	vmexit[vcpu].inst_length = 0;
223
224	mt_vmm_info[vcpu].mt_ctx = ctx;
225	mt_vmm_info[vcpu].mt_vcpu = vcpu;
226
227	error = pthread_create(&mt_vmm_info[vcpu].mt_thr, NULL,
228	    fbsdrun_start_thread, &mt_vmm_info[vcpu]);
229	assert(error == 0);
230}
231
232static int
233vmexit_catch_reset(void)
234{
235        stats.io_reset++;
236        return (VMEXIT_RESET);
237}
238
239static int
240vmexit_catch_inout(void)
241{
242	return (VMEXIT_ABORT);
243}
244
245static int
246vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
247		     uint32_t eax)
248{
249#if BHYVE_DEBUG
250	/*
251	 * put guest-driven debug here
252	 */
253#endif
254        return (VMEXIT_CONTINUE);
255}
256
257static int
258vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
259{
260	int error;
261	int bytes, port, in, out;
262	uint32_t eax;
263	int vcpu;
264
265	vcpu = *pvcpu;
266
267	port = vme->u.inout.port;
268	bytes = vme->u.inout.bytes;
269	eax = vme->u.inout.eax;
270	in = vme->u.inout.in;
271	out = !in;
272
273	/* We don't deal with these */
274	if (vme->u.inout.string || vme->u.inout.rep)
275		return (VMEXIT_ABORT);
276
277	/* Special case of guest reset */
278	if (out && port == 0x64 && (uint8_t)eax == 0xFE)
279		return (vmexit_catch_reset());
280
281        /* Extra-special case of host notifications */
282        if (out && port == GUEST_NIO_PORT)
283                return (vmexit_handle_notify(ctx, vme, pvcpu, eax));
284
285	error = emulate_inout(ctx, vcpu, in, port, bytes, &eax, strictio);
286	if (error == INOUT_OK && in)
287		error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RAX, eax);
288
289	switch (error) {
290	case INOUT_OK:
291		return (VMEXIT_CONTINUE);
292	case INOUT_RESET:
293		return (VMEXIT_RESET);
294	case INOUT_POWEROFF:
295		return (VMEXIT_POWEROFF);
296	default:
297		fprintf(stderr, "Unhandled %s%c 0x%04x\n",
298			in ? "in" : "out",
299			bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'), port);
300		return (vmexit_catch_inout());
301	}
302}
303
304static int
305vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
306{
307	fprintf(stderr, "vm exit rdmsr 0x%x, cpu %d\n", vme->u.msr.code,
308	    *pvcpu);
309	return (VMEXIT_ABORT);
310}
311
312static int
313vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
314{
315	int newcpu;
316	int retval = VMEXIT_CONTINUE;
317
318	newcpu = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code,vme->u.msr.wval);
319
320        return (retval);
321}
322
323static int
324vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
325{
326	int newcpu;
327	int retval = VMEXIT_CONTINUE;
328
329	newcpu = spinup_ap(ctx, *pvcpu,
330			   vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
331
332	return (retval);
333}
334
335static int
336vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
337{
338
339	fprintf(stderr, "vm exit[%d]\n", *pvcpu);
340	fprintf(stderr, "\treason\t\tVMX\n");
341	fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
342	fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
343	fprintf(stderr, "\terror\t\t%d\n", vmexit->u.vmx.error);
344	fprintf(stderr, "\texit_reason\t%u\n", vmexit->u.vmx.exit_reason);
345	fprintf(stderr, "\tqualification\t0x%016lx\n",
346	    vmexit->u.vmx.exit_qualification);
347
348	return (VMEXIT_ABORT);
349}
350
351static int
352vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
353{
354
355	stats.vmexit_bogus++;
356
357	return (VMEXIT_RESTART);
358}
359
360static int
361vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
362{
363
364	stats.vmexit_hlt++;
365
366	/*
367	 * Just continue execution with the next instruction. We use
368	 * the HLT VM exit as a way to be friendly with the host
369	 * scheduler.
370	 */
371	return (VMEXIT_CONTINUE);
372}
373
374static int
375vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
376{
377
378	stats.vmexit_pause++;
379
380	return (VMEXIT_CONTINUE);
381}
382
383static int
384vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
385{
386
387	stats.vmexit_mtrap++;
388
389	return (VMEXIT_RESTART);
390}
391
392static int
393vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
394{
395	int err;
396	stats.vmexit_inst_emul++;
397
398	err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
399			  &vmexit->u.inst_emul.vie);
400
401	if (err) {
402		if (err == EINVAL) {
403			fprintf(stderr,
404			    "Failed to emulate instruction at 0x%lx\n",
405			    vmexit->rip);
406		} else if (err == ESRCH) {
407			fprintf(stderr, "Unhandled memory access to 0x%lx\n",
408			    vmexit->u.inst_emul.gpa);
409		}
410
411		return (VMEXIT_ABORT);
412	}
413
414	return (VMEXIT_CONTINUE);
415}
416
417static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
418	[VM_EXITCODE_INOUT]  = vmexit_inout,
419	[VM_EXITCODE_VMX]    = vmexit_vmx,
420	[VM_EXITCODE_BOGUS]  = vmexit_bogus,
421	[VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
422	[VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
423	[VM_EXITCODE_MTRAP]  = vmexit_mtrap,
424	[VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
425	[VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
426};
427
428static void
429vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip)
430{
431	cpuset_t mask;
432	int error, rc, prevcpu;
433	enum vm_exitcode exitcode;
434
435	if (pincpu >= 0) {
436		CPU_ZERO(&mask);
437		CPU_SET(pincpu + vcpu, &mask);
438		error = pthread_setaffinity_np(pthread_self(),
439					       sizeof(mask), &mask);
440		assert(error == 0);
441	}
442
443	while (1) {
444		error = vm_run(ctx, vcpu, rip, &vmexit[vcpu]);
445		if (error != 0) {
446			/*
447			 * It is possible that 'vmmctl' or some other process
448			 * has transitioned the vcpu to CANNOT_RUN state right
449			 * before we tried to transition it to RUNNING.
450			 *
451			 * This is expected to be temporary so just retry.
452			 */
453			if (errno == EBUSY)
454				continue;
455			else
456				break;
457		}
458
459		prevcpu = vcpu;
460
461		exitcode = vmexit[vcpu].exitcode;
462		if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
463			fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
464			    exitcode);
465			exit(1);
466		}
467
468                rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
469
470		switch (rc) {
471		case VMEXIT_CONTINUE:
472                        rip = vmexit[vcpu].rip + vmexit[vcpu].inst_length;
473			break;
474		case VMEXIT_RESTART:
475                        rip = vmexit[vcpu].rip;
476			break;
477		case VMEXIT_RESET:
478			exit(0);
479		default:
480			exit(1);
481		}
482	}
483	fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
484}
485
486static int
487num_vcpus_allowed(struct vmctx *ctx)
488{
489	int tmp, error;
490
491	error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
492
493	/*
494	 * The guest is allowed to spinup more than one processor only if the
495	 * UNRESTRICTED_GUEST capability is available.
496	 */
497	if (error == 0)
498		return (VM_MAXCPU);
499	else
500		return (1);
501}
502
503void
504fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
505{
506	int err, tmp;
507
508	if (fbsdrun_vmexit_on_hlt()) {
509		err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
510		if (err < 0) {
511			fprintf(stderr, "VM exit on HLT not supported\n");
512			exit(1);
513		}
514		vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
515		if (cpu == BSP)
516			handler[VM_EXITCODE_HLT] = vmexit_hlt;
517	}
518
519        if (fbsdrun_vmexit_on_pause()) {
520		/*
521		 * pause exit support required for this mode
522		 */
523		err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
524		if (err < 0) {
525			fprintf(stderr,
526			    "SMP mux requested, no pause support\n");
527			exit(1);
528		}
529		vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
530		if (cpu == BSP)
531			handler[VM_EXITCODE_PAUSE] = vmexit_pause;
532        }
533
534	if (fbsdrun_disable_x2apic())
535		err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
536	else
537		err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
538
539	if (err) {
540		fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
541		exit(1);
542	}
543
544	vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
545}
546
547int
548main(int argc, char *argv[])
549{
550	int c, error, gdb_port, err, bvmcons;
551	int max_vcpus;
552	struct vmctx *ctx;
553	uint64_t rip;
554	size_t memsize;
555
556	bvmcons = 0;
557	progname = basename(argv[0]);
558	gdb_port = 0;
559	guest_ncpus = 1;
560	memsize = 256 * MB;
561
562	while ((c = getopt(argc, argv, "abehAHIPWp:g:c:s:S:m:l:")) != -1) {
563		switch (c) {
564		case 'a':
565			disable_x2apic = 1;
566			break;
567		case 'A':
568			acpi = 1;
569			break;
570		case 'b':
571			bvmcons = 1;
572			break;
573		case 'p':
574			pincpu = atoi(optarg);
575			break;
576                case 'c':
577			guest_ncpus = atoi(optarg);
578			break;
579		case 'g':
580			gdb_port = atoi(optarg);
581			break;
582		case 'l':
583			if (lpc_device_parse(optarg) != 0) {
584				errx(EX_USAGE, "invalid lpc device "
585				    "configuration '%s'", optarg);
586			}
587			break;
588		case 's':
589			if (pci_parse_slot(optarg, 0) != 0)
590				exit(1);
591			else
592				break;
593		case 'S':
594			if (pci_parse_slot(optarg, 1) != 0)
595				exit(1);
596			else
597				break;
598                case 'm':
599			error = vm_parse_memsize(optarg, &memsize);
600			if (error)
601				errx(EX_USAGE, "invalid memsize '%s'", optarg);
602			break;
603		case 'H':
604			guest_vmexit_on_hlt = 1;
605			break;
606		case 'I':
607			/*
608			 * The "-I" option was used to add an ioapic to the
609			 * virtual machine.
610			 *
611			 * An ioapic is now provided unconditionally for each
612			 * virtual machine and this option is now deprecated.
613			 */
614			break;
615		case 'P':
616			guest_vmexit_on_pause = 1;
617			break;
618		case 'e':
619			strictio = 1;
620			break;
621		case 'W':
622			virtio_msix = 0;
623			break;
624		case 'h':
625			usage(0);
626		default:
627			usage(1);
628		}
629	}
630	argc -= optind;
631	argv += optind;
632
633	if (argc != 1)
634		usage(1);
635
636	vmname = argv[0];
637
638	ctx = vm_open(vmname);
639	if (ctx == NULL) {
640		perror("vm_open");
641		exit(1);
642	}
643
644	max_vcpus = num_vcpus_allowed(ctx);
645	if (guest_ncpus > max_vcpus) {
646		fprintf(stderr, "%d vCPUs requested but only %d available\n",
647			guest_ncpus, max_vcpus);
648		exit(1);
649	}
650
651	fbsdrun_set_capabilities(ctx, BSP);
652
653	err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
654	if (err) {
655		fprintf(stderr, "Unable to setup memory (%d)\n", err);
656		exit(1);
657	}
658
659	init_mem();
660	init_inout();
661	legacy_irq_init();
662
663	rtc_init(ctx);
664
665	/*
666	 * Exit if a device emulation finds an error in it's initilization
667	 */
668	if (init_pci(ctx) != 0)
669		exit(1);
670
671	if (gdb_port != 0)
672		init_dbgport(gdb_port);
673
674	if (bvmcons)
675		init_bvmcons();
676
677	error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
678	assert(error == 0);
679
680	/*
681	 * build the guest tables, MP etc.
682	 */
683	mptable_build(ctx, guest_ncpus);
684
685	if (acpi) {
686		error = acpi_build(ctx, guest_ncpus);
687		assert(error == 0);
688	}
689
690	/*
691	 * Change the proc title to include the VM name.
692	 */
693	setproctitle("%s", vmname);
694
695	/*
696	 * Add CPU 0
697	 */
698	fbsdrun_addcpu(ctx, BSP, rip);
699
700	/*
701	 * Head off to the main event dispatch loop
702	 */
703	mevent_dispatch();
704
705	exit(1);
706}
707