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