]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bhyve/bhyverun.c
MFC r34505: freebsd-update: restore old exit code when no updates are available
[FreeBSD/FreeBSD.git] / usr.sbin / bhyve / bhyverun.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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  * $FreeBSD$
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include <sys/types.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
37 #endif
38 #include <sys/mman.h>
39 #include <sys/time.h>
40
41 #include <machine/atomic.h>
42 #include <machine/segments.h>
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <libgen.h>
50 #include <unistd.h>
51 #include <assert.h>
52 #include <errno.h>
53 #include <pthread.h>
54 #include <pthread_np.h>
55 #include <sysexits.h>
56 #include <stdbool.h>
57 #ifndef WITHOUT_CAPSICUM
58 #include <nl_types.h>
59 #include <termios.h>
60 #endif
61
62 #include <machine/vmm.h>
63 #ifndef WITHOUT_CAPSICUM
64 #include <machine/vmm_dev.h>
65 #endif
66 #include <vmmapi.h>
67
68 #include "bhyverun.h"
69 #include "acpi.h"
70 #include "atkbdc.h"
71 #include "inout.h"
72 #include "dbgport.h"
73 #include "fwctl.h"
74 #include "ioapic.h"
75 #include "mem.h"
76 #include "mevent.h"
77 #include "mptbl.h"
78 #include "pci_emul.h"
79 #include "pci_irq.h"
80 #include "pci_lpc.h"
81 #include "smbiostbl.h"
82 #include "xmsr.h"
83 #include "spinup_ap.h"
84 #include "rtc.h"
85
86 #define GUEST_NIO_PORT          0x488   /* guest upcalls via i/o port */
87
88 #define MB              (1024UL * 1024)
89 #define GB              (1024UL * MB)
90
91 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
92 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
93
94 char *vmname;
95
96 int guest_ncpus;
97 char *guest_uuid_str;
98
99 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
100 static int virtio_msix = 1;
101 static int x2apic_mode = 0;     /* default is xAPIC */
102
103 static int strictio;
104 static int strictmsr = 1;
105
106 static int acpi;
107
108 static char *progname;
109 static const int BSP = 0;
110
111 static cpuset_t cpumask;
112
113 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
114
115 static struct vm_exit vmexit[VM_MAXCPU];
116
117 struct bhyvestats {
118         uint64_t        vmexit_bogus;
119         uint64_t        vmexit_reqidle;
120         uint64_t        vmexit_hlt;
121         uint64_t        vmexit_pause;
122         uint64_t        vmexit_mtrap;
123         uint64_t        vmexit_inst_emul;
124         uint64_t        cpu_switch_rotate;
125         uint64_t        cpu_switch_direct;
126 } stats;
127
128 struct mt_vmm_info {
129         pthread_t       mt_thr;
130         struct vmctx    *mt_ctx;
131         int             mt_vcpu;        
132 } mt_vmm_info[VM_MAXCPU];
133
134 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
135
136 static void
137 usage(int code)
138 {
139
140         fprintf(stderr,
141                 "Usage: %s [-abehuwxACHPSWY] [-c vcpus] [-g <gdb port>] [-l <lpc>]\n"
142                 "       %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
143                 "       -a: local apic is in xAPIC mode (deprecated)\n"
144                 "       -A: create ACPI tables\n"
145                 "       -c: # cpus (default 1)\n"
146                 "       -C: include guest memory in core file\n"
147                 "       -e: exit on unhandled I/O access\n"
148                 "       -g: gdb port\n"
149                 "       -h: help\n"
150                 "       -H: vmexit from the guest on hlt\n"
151                 "       -l: LPC device configuration\n"
152                 "       -m: memory size in MB\n"
153                 "       -p: pin 'vcpu' to 'hostcpu'\n"
154                 "       -P: vmexit from the guest on pause\n"
155                 "       -s: <slot,driver,configinfo> PCI slot config\n"
156                 "       -S: guest memory cannot be swapped\n"
157                 "       -u: RTC keeps UTC time\n"
158                 "       -U: uuid\n"
159                 "       -w: ignore unimplemented MSRs\n"
160                 "       -W: force virtio to use single-vector MSI\n"
161                 "       -x: local apic is in x2APIC mode\n"
162                 "       -Y: disable MPtable generation\n",
163                 progname, (int)strlen(progname), "");
164
165         exit(code);
166 }
167
168 #ifndef WITHOUT_CAPSICUM
169 /*
170  * 11-stable capsicum helpers
171  */
172 static void
173 bhyve_caph_cache_catpages(void)
174 {
175
176         (void)catopen("libc", NL_CAT_LOCALE);
177 }
178
179 static int
180 bhyve_caph_limit_stdoe(void)
181 {
182         cap_rights_t rights;
183         unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ };
184         int i, fds[] = { STDOUT_FILENO, STDERR_FILENO };
185
186         cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL);
187         cap_rights_set(&rights, CAP_WRITE);
188
189         for (i = 0; i < nitems(fds); i++) {
190                 if (cap_rights_limit(fds[i], &rights) < 0 && errno != ENOSYS)
191                         return (-1);
192
193                 if (cap_ioctls_limit(fds[i], cmds, nitems(cmds)) < 0 && errno != ENOSYS)
194                         return (-1);
195
196                 if (cap_fcntls_limit(fds[i], CAP_FCNTL_GETFL) < 0 && errno != ENOSYS)
197                         return (-1);
198         }
199
200         return (0);
201 }
202
203 #endif
204
205 static int
206 pincpu_parse(const char *opt)
207 {
208         int vcpu, pcpu;
209
210         if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
211                 fprintf(stderr, "invalid format: %s\n", opt);
212                 return (-1);
213         }
214
215         if (vcpu < 0 || vcpu >= VM_MAXCPU) {
216                 fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
217                     vcpu, VM_MAXCPU - 1);
218                 return (-1);
219         }
220
221         if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
222                 fprintf(stderr, "hostcpu '%d' outside valid range from "
223                     "0 to %d\n", pcpu, CPU_SETSIZE - 1);
224                 return (-1);
225         }
226
227         if (vcpumap[vcpu] == NULL) {
228                 if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
229                         perror("malloc");
230                         return (-1);
231                 }
232                 CPU_ZERO(vcpumap[vcpu]);
233         }
234         CPU_SET(pcpu, vcpumap[vcpu]);
235         return (0);
236 }
237
238 void
239 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
240     int errcode)
241 {
242         struct vmctx *ctx;
243         int error, restart_instruction;
244
245         ctx = arg;
246         restart_instruction = 1;
247
248         error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
249             restart_instruction);
250         assert(error == 0);
251 }
252
253 void *
254 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
255 {
256
257         return (vm_map_gpa(ctx, gaddr, len));
258 }
259
260 int
261 fbsdrun_vmexit_on_pause(void)
262 {
263
264         return (guest_vmexit_on_pause);
265 }
266
267 int
268 fbsdrun_vmexit_on_hlt(void)
269 {
270
271         return (guest_vmexit_on_hlt);
272 }
273
274 int
275 fbsdrun_virtio_msix(void)
276 {
277
278         return (virtio_msix);
279 }
280
281 static void *
282 fbsdrun_start_thread(void *param)
283 {
284         char tname[MAXCOMLEN + 1];
285         struct mt_vmm_info *mtp;
286         int vcpu;
287
288         mtp = param;
289         vcpu = mtp->mt_vcpu;
290
291         snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
292         pthread_set_name_np(mtp->mt_thr, tname);
293
294         vm_loop(mtp->mt_ctx, vcpu, vmexit[vcpu].rip);
295
296         /* not reached */
297         exit(1);
298         return (NULL);
299 }
300
301 void
302 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
303 {
304         int error;
305
306         assert(fromcpu == BSP);
307
308         /*
309          * The 'newcpu' must be activated in the context of 'fromcpu'. If
310          * vm_activate_cpu() is delayed until newcpu's pthread starts running
311          * then vmm.ko is out-of-sync with bhyve and this can create a race
312          * with vm_suspend().
313          */
314         error = vm_activate_cpu(ctx, newcpu);
315         if (error != 0)
316                 err(EX_OSERR, "could not activate CPU %d", newcpu);
317
318         CPU_SET_ATOMIC(newcpu, &cpumask);
319
320         /*
321          * Set up the vmexit struct to allow execution to start
322          * at the given RIP
323          */
324         vmexit[newcpu].rip = rip;
325         vmexit[newcpu].inst_length = 0;
326
327         mt_vmm_info[newcpu].mt_ctx = ctx;
328         mt_vmm_info[newcpu].mt_vcpu = newcpu;
329
330         error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
331             fbsdrun_start_thread, &mt_vmm_info[newcpu]);
332         assert(error == 0);
333 }
334
335 static int
336 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
337 {
338
339         if (!CPU_ISSET(vcpu, &cpumask)) {
340                 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
341                 exit(4);
342         }
343
344         CPU_CLR_ATOMIC(vcpu, &cpumask);
345         return (CPU_EMPTY(&cpumask));
346 }
347
348 static int
349 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
350                      uint32_t eax)
351 {
352 #if BHYVE_DEBUG
353         /*
354          * put guest-driven debug here
355          */
356 #endif
357         return (VMEXIT_CONTINUE);
358 }
359
360 static int
361 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
362 {
363         int error;
364         int bytes, port, in, out;
365         int vcpu;
366
367         vcpu = *pvcpu;
368
369         port = vme->u.inout.port;
370         bytes = vme->u.inout.bytes;
371         in = vme->u.inout.in;
372         out = !in;
373
374         /* Extra-special case of host notifications */
375         if (out && port == GUEST_NIO_PORT) {
376                 error = vmexit_handle_notify(ctx, vme, pvcpu, vme->u.inout.eax);
377                 return (error);
378         }
379
380         error = emulate_inout(ctx, vcpu, vme, strictio);
381         if (error) {
382                 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
383                     in ? "in" : "out",
384                     bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
385                     port, vmexit->rip);
386                 return (VMEXIT_ABORT);
387         } else {
388                 return (VMEXIT_CONTINUE);
389         }
390 }
391
392 static int
393 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
394 {
395         uint64_t val;
396         uint32_t eax, edx;
397         int error;
398
399         val = 0;
400         error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
401         if (error != 0) {
402                 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
403                     vme->u.msr.code, *pvcpu);
404                 if (strictmsr) {
405                         vm_inject_gp(ctx, *pvcpu);
406                         return (VMEXIT_CONTINUE);
407                 }
408         }
409
410         eax = val;
411         error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
412         assert(error == 0);
413
414         edx = val >> 32;
415         error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
416         assert(error == 0);
417
418         return (VMEXIT_CONTINUE);
419 }
420
421 static int
422 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
423 {
424         int error;
425
426         error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
427         if (error != 0) {
428                 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
429                     vme->u.msr.code, vme->u.msr.wval, *pvcpu);
430                 if (strictmsr) {
431                         vm_inject_gp(ctx, *pvcpu);
432                         return (VMEXIT_CONTINUE);
433                 }
434         }
435         return (VMEXIT_CONTINUE);
436 }
437
438 static int
439 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
440 {
441
442         (void)spinup_ap(ctx, *pvcpu,
443                     vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
444
445         return (VMEXIT_CONTINUE);
446 }
447
448 #define DEBUG_EPT_MISCONFIG
449 #ifdef DEBUG_EPT_MISCONFIG
450 #define EXIT_REASON_EPT_MISCONFIG       49
451 #define VMCS_GUEST_PHYSICAL_ADDRESS     0x00002400
452 #define VMCS_IDENT(x)                   ((x) | 0x80000000)
453
454 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
455 static int ept_misconfig_ptenum;
456 #endif
457
458 static int
459 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
460 {
461
462         fprintf(stderr, "vm exit[%d]\n", *pvcpu);
463         fprintf(stderr, "\treason\t\tVMX\n");
464         fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
465         fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
466         fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
467         fprintf(stderr, "\texit_reason\t%u\n", vmexit->u.vmx.exit_reason);
468         fprintf(stderr, "\tqualification\t0x%016lx\n",
469             vmexit->u.vmx.exit_qualification);
470         fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
471         fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
472 #ifdef DEBUG_EPT_MISCONFIG
473         if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
474                 vm_get_register(ctx, *pvcpu,
475                     VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
476                     &ept_misconfig_gpa);
477                 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
478                     &ept_misconfig_ptenum);
479                 fprintf(stderr, "\tEPT misconfiguration:\n");
480                 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
481                 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
482                     ept_misconfig_ptenum, ept_misconfig_pte[0],
483                     ept_misconfig_pte[1], ept_misconfig_pte[2],
484                     ept_misconfig_pte[3]);
485         }
486 #endif  /* DEBUG_EPT_MISCONFIG */
487         return (VMEXIT_ABORT);
488 }
489
490 static int
491 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
492 {
493
494         fprintf(stderr, "vm exit[%d]\n", *pvcpu);
495         fprintf(stderr, "\treason\t\tSVM\n");
496         fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
497         fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
498         fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
499         fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
500         fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
501         return (VMEXIT_ABORT);
502 }
503
504 static int
505 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
506 {
507
508         assert(vmexit->inst_length == 0);
509
510         stats.vmexit_bogus++;
511
512         return (VMEXIT_CONTINUE);
513 }
514
515 static int
516 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
517 {
518
519         assert(vmexit->inst_length == 0);
520
521         stats.vmexit_reqidle++;
522
523         return (VMEXIT_CONTINUE);
524 }
525
526 static int
527 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
528 {
529
530         stats.vmexit_hlt++;
531
532         /*
533          * Just continue execution with the next instruction. We use
534          * the HLT VM exit as a way to be friendly with the host
535          * scheduler.
536          */
537         return (VMEXIT_CONTINUE);
538 }
539
540 static int
541 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
542 {
543
544         stats.vmexit_pause++;
545
546         return (VMEXIT_CONTINUE);
547 }
548
549 static int
550 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
551 {
552
553         assert(vmexit->inst_length == 0);
554
555         stats.vmexit_mtrap++;
556
557         return (VMEXIT_CONTINUE);
558 }
559
560 static int
561 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
562 {
563         int err, i;
564         struct vie *vie;
565
566         stats.vmexit_inst_emul++;
567
568         vie = &vmexit->u.inst_emul.vie;
569         err = emulate_mem(ctx, *pvcpu, vmexit->u.inst_emul.gpa,
570             vie, &vmexit->u.inst_emul.paging);
571
572         if (err) {
573                 if (err == ESRCH) {
574                         fprintf(stderr, "Unhandled memory access to 0x%lx\n",
575                             vmexit->u.inst_emul.gpa);
576                 }
577
578                 fprintf(stderr, "Failed to emulate instruction [");
579                 for (i = 0; i < vie->num_valid; i++) {
580                         fprintf(stderr, "0x%02x%s", vie->inst[i],
581                             i != (vie->num_valid - 1) ? " " : "");
582                 }
583                 fprintf(stderr, "] at 0x%lx\n", vmexit->rip);
584                 return (VMEXIT_ABORT);
585         }
586
587         return (VMEXIT_CONTINUE);
588 }
589
590 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
591 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
592
593 static int
594 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
595 {
596         enum vm_suspend_how how;
597
598         how = vmexit->u.suspended.how;
599
600         fbsdrun_deletecpu(ctx, *pvcpu);
601
602         if (*pvcpu != BSP) {
603                 pthread_mutex_lock(&resetcpu_mtx);
604                 pthread_cond_signal(&resetcpu_cond);
605                 pthread_mutex_unlock(&resetcpu_mtx);
606                 pthread_exit(NULL);
607         }
608
609         pthread_mutex_lock(&resetcpu_mtx);
610         while (!CPU_EMPTY(&cpumask)) {
611                 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
612         }
613         pthread_mutex_unlock(&resetcpu_mtx);
614
615         switch (how) {
616         case VM_SUSPEND_RESET:
617                 exit(0);
618         case VM_SUSPEND_POWEROFF:
619                 exit(1);
620         case VM_SUSPEND_HALT:
621                 exit(2);
622         case VM_SUSPEND_TRIPLEFAULT:
623                 exit(3);
624         default:
625                 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
626                 exit(100);
627         }
628         return (0);     /* NOTREACHED */
629 }
630
631 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
632         [VM_EXITCODE_INOUT]  = vmexit_inout,
633         [VM_EXITCODE_INOUT_STR]  = vmexit_inout,
634         [VM_EXITCODE_VMX]    = vmexit_vmx,
635         [VM_EXITCODE_SVM]    = vmexit_svm,
636         [VM_EXITCODE_BOGUS]  = vmexit_bogus,
637         [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
638         [VM_EXITCODE_RDMSR]  = vmexit_rdmsr,
639         [VM_EXITCODE_WRMSR]  = vmexit_wrmsr,
640         [VM_EXITCODE_MTRAP]  = vmexit_mtrap,
641         [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
642         [VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
643         [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
644         [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
645 };
646
647 static void
648 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
649 {
650         int error, rc;
651         enum vm_exitcode exitcode;
652         cpuset_t active_cpus;
653
654         if (vcpumap[vcpu] != NULL) {
655                 error = pthread_setaffinity_np(pthread_self(),
656                     sizeof(cpuset_t), vcpumap[vcpu]);
657                 assert(error == 0);
658         }
659
660         error = vm_active_cpus(ctx, &active_cpus);
661         assert(CPU_ISSET(vcpu, &active_cpus));
662
663         error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
664         assert(error == 0);
665
666         while (1) {
667                 error = vm_run(ctx, vcpu, &vmexit[vcpu]);
668                 if (error != 0)
669                         break;
670
671                 exitcode = vmexit[vcpu].exitcode;
672                 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
673                         fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
674                             exitcode);
675                         exit(4);
676                 }
677
678                 rc = (*handler[exitcode])(ctx, &vmexit[vcpu], &vcpu);
679
680                 switch (rc) {
681                 case VMEXIT_CONTINUE:
682                         break;
683                 case VMEXIT_ABORT:
684                         abort();
685                 default:
686                         exit(4);
687                 }
688         }
689         fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
690 }
691
692 static int
693 num_vcpus_allowed(struct vmctx *ctx)
694 {
695         int tmp, error;
696
697         error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
698
699         /*
700          * The guest is allowed to spinup more than one processor only if the
701          * UNRESTRICTED_GUEST capability is available.
702          */
703         if (error == 0)
704                 return (VM_MAXCPU);
705         else
706                 return (1);
707 }
708
709 void
710 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
711 {
712         int err, tmp;
713
714         if (fbsdrun_vmexit_on_hlt()) {
715                 err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
716                 if (err < 0) {
717                         fprintf(stderr, "VM exit on HLT not supported\n");
718                         exit(4);
719                 }
720                 vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
721                 if (cpu == BSP)
722                         handler[VM_EXITCODE_HLT] = vmexit_hlt;
723         }
724
725         if (fbsdrun_vmexit_on_pause()) {
726                 /*
727                  * pause exit support required for this mode
728                  */
729                 err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
730                 if (err < 0) {
731                         fprintf(stderr,
732                             "SMP mux requested, no pause support\n");
733                         exit(4);
734                 }
735                 vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
736                 if (cpu == BSP)
737                         handler[VM_EXITCODE_PAUSE] = vmexit_pause;
738         }
739
740         if (x2apic_mode)
741                 err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
742         else
743                 err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
744
745         if (err) {
746                 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
747                 exit(4);
748         }
749
750         vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
751 }
752
753 static struct vmctx *
754 do_open(const char *vmname)
755 {
756         struct vmctx *ctx;
757         int error;
758         bool reinit, romboot;
759 #ifndef WITHOUT_CAPSICUM
760         cap_rights_t rights;
761         const cap_ioctl_t *cmds;        
762         size_t ncmds;
763 #endif
764
765         reinit = romboot = false;
766
767         if (lpc_bootrom())
768                 romboot = true;
769
770         error = vm_create(vmname);
771         if (error) {
772                 if (errno == EEXIST) {
773                         if (romboot) {
774                                 reinit = true;
775                         } else {
776                                 /*
777                                  * The virtual machine has been setup by the
778                                  * userspace bootloader.
779                                  */
780                         }
781                 } else {
782                         perror("vm_create");
783                         exit(4);
784                 }
785         } else {
786                 if (!romboot) {
787                         /*
788                          * If the virtual machine was just created then a
789                          * bootrom must be configured to boot it.
790                          */
791                         fprintf(stderr, "virtual machine cannot be booted\n");
792                         exit(4);
793                 }
794         }
795
796         ctx = vm_open(vmname);
797         if (ctx == NULL) {
798                 perror("vm_open");
799                 exit(4);
800         }
801
802 #ifndef WITHOUT_CAPSICUM
803         cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
804         if (cap_rights_limit(vm_get_device_fd(ctx), &rights) == -1 &&
805             errno != ENOSYS)
806                 errx(EX_OSERR, "Unable to apply rights for sandbox");
807         vm_get_ioctls(&ncmds);
808         cmds = vm_get_ioctls(NULL);
809         if (cmds == NULL)
810                 errx(EX_OSERR, "out of memory");
811         if (cap_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1 &&
812             errno != ENOSYS)
813                 errx(EX_OSERR, "Unable to apply rights for sandbox");
814         free((cap_ioctl_t *)cmds);
815 #endif
816  
817         if (reinit) {
818                 error = vm_reinit(ctx);
819                 if (error) {
820                         perror("vm_reinit");
821                         exit(4);
822                 }
823         }
824         return (ctx);
825 }
826
827 int
828 main(int argc, char *argv[])
829 {
830         int c, error, gdb_port, err, bvmcons;
831         int max_vcpus, mptgen, memflags;
832         int rtc_localtime;
833         struct vmctx *ctx;
834         uint64_t rip;
835         size_t memsize;
836         char *optstr;
837
838         bvmcons = 0;
839         progname = basename(argv[0]);
840         gdb_port = 0;
841         guest_ncpus = 1;
842         memsize = 256 * MB;
843         mptgen = 1;
844         rtc_localtime = 1;
845         memflags = 0;
846
847         optstr = "abehuwxACHIPSWYp:g:c:s:m:l:U:";
848         while ((c = getopt(argc, argv, optstr)) != -1) {
849                 switch (c) {
850                 case 'a':
851                         x2apic_mode = 0;
852                         break;
853                 case 'A':
854                         acpi = 1;
855                         break;
856                 case 'b':
857                         bvmcons = 1;
858                         break;
859                 case 'p':
860                         if (pincpu_parse(optarg) != 0) {
861                             errx(EX_USAGE, "invalid vcpu pinning "
862                                  "configuration '%s'", optarg);
863                         }
864                         break;
865                 case 'c':
866                         guest_ncpus = atoi(optarg);
867                         break;
868                 case 'C':
869                         memflags |= VM_MEM_F_INCORE;
870                         break;
871                 case 'g':
872                         gdb_port = atoi(optarg);
873                         break;
874                 case 'l':
875                         if (lpc_device_parse(optarg) != 0) {
876                                 errx(EX_USAGE, "invalid lpc device "
877                                     "configuration '%s'", optarg);
878                         }
879                         break;
880                 case 's':
881                         if (pci_parse_slot(optarg) != 0)
882                                 exit(4);
883                         else
884                                 break;
885                 case 'S':
886                         memflags |= VM_MEM_F_WIRED;
887                         break;
888                 case 'm':
889                         error = vm_parse_memsize(optarg, &memsize);
890                         if (error)
891                                 errx(EX_USAGE, "invalid memsize '%s'", optarg);
892                         break;
893                 case 'H':
894                         guest_vmexit_on_hlt = 1;
895                         break;
896                 case 'I':
897                         /*
898                          * The "-I" option was used to add an ioapic to the
899                          * virtual machine.
900                          *
901                          * An ioapic is now provided unconditionally for each
902                          * virtual machine and this option is now deprecated.
903                          */
904                         break;
905                 case 'P':
906                         guest_vmexit_on_pause = 1;
907                         break;
908                 case 'e':
909                         strictio = 1;
910                         break;
911                 case 'u':
912                         rtc_localtime = 0;
913                         break;
914                 case 'U':
915                         guest_uuid_str = optarg;
916                         break;
917                 case 'w':
918                         strictmsr = 0;
919                         break;
920                 case 'W':
921                         virtio_msix = 0;
922                         break;
923                 case 'x':
924                         x2apic_mode = 1;
925                         break;
926                 case 'Y':
927                         mptgen = 0;
928                         break;
929                 case 'h':
930                         usage(0);                       
931                 default:
932                         usage(1);
933                 }
934         }
935         argc -= optind;
936         argv += optind;
937
938         if (argc != 1)
939                 usage(1);
940
941         vmname = argv[0];
942         ctx = do_open(vmname);
943
944         if (guest_ncpus < 1) {
945                 fprintf(stderr, "Invalid guest vCPUs (%d)\n", guest_ncpus);
946                 exit(1);
947         }
948
949         max_vcpus = num_vcpus_allowed(ctx);
950         if (guest_ncpus > max_vcpus) {
951                 fprintf(stderr, "%d vCPUs requested but only %d available\n",
952                         guest_ncpus, max_vcpus);
953                 exit(4);
954         }
955
956         fbsdrun_set_capabilities(ctx, BSP);
957
958         vm_set_memflags(ctx, memflags);
959         err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
960         if (err) {
961                 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
962                 exit(4);
963         }
964
965         error = init_msr();
966         if (error) {
967                 fprintf(stderr, "init_msr error %d", error);
968                 exit(4);
969         }
970
971         init_mem();
972         init_inout();
973         atkbdc_init(ctx);
974         pci_irq_init(ctx);
975         ioapic_init(ctx);
976
977         rtc_init(ctx, rtc_localtime);
978         sci_init(ctx);
979
980         /*
981          * Exit if a device emulation finds an error in it's initilization
982          */
983         if (init_pci(ctx) != 0) {
984                 perror("device emulation initialization error");
985                 exit(4);
986         }
987
988         if (gdb_port != 0)
989                 init_dbgport(gdb_port);
990
991         if (bvmcons)
992                 init_bvmcons();
993
994         if (lpc_bootrom()) {
995                 if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
996                         fprintf(stderr, "ROM boot failed: unrestricted guest "
997                             "capability not available\n");
998                         exit(4);
999                 }
1000                 error = vcpu_reset(ctx, BSP);
1001                 assert(error == 0);
1002         }
1003
1004         error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1005         assert(error == 0);
1006
1007         /*
1008          * build the guest tables, MP etc.
1009          */
1010         if (mptgen) {
1011                 error = mptable_build(ctx, guest_ncpus);
1012                 if (error) {
1013                         perror("error to build the guest tables");
1014                         exit(4);
1015                 }
1016         }
1017
1018         error = smbios_build(ctx);
1019         assert(error == 0);
1020
1021         if (acpi) {
1022                 error = acpi_build(ctx, guest_ncpus);
1023                 assert(error == 0);
1024         }
1025
1026         if (lpc_bootrom())
1027                 fwctl_init();
1028
1029         /*
1030          * Change the proc title to include the VM name.
1031          */
1032         setproctitle("%s", vmname);
1033
1034 #ifndef WITHOUT_CAPSICUM
1035         bhyve_caph_cache_catpages();
1036
1037         if (bhyve_caph_limit_stdoe() == -1)
1038                 errx(EX_OSERR, "Unable to apply rights for sandbox");
1039
1040         if (cap_enter() == -1 && errno != ENOSYS)
1041                 errx(EX_OSERR, "cap_enter() failed");
1042 #endif
1043
1044         /*
1045          * Add CPU 0
1046          */
1047         fbsdrun_addcpu(ctx, BSP, BSP, rip);
1048
1049         /*
1050          * Head off to the main event dispatch loop
1051          */
1052         mevent_dispatch();
1053
1054         exit(4);
1055 }