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