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 * This file and its contents are supplied under the terms of the
32 * Common Development and Distribution License ("CDDL"), version 1.0.
33 * You may only use this file in accordance with the terms of version
34 * 1.0 of the CDDL.
35 *
36 * A full copy of the text of the CDDL should have accompanied this
37 * source. A copy of the CDDL is also available via the Internet at
38 * http://www.illumos.org/license/CDDL.
39 *
40 * Copyright 2015 Pluribus Networks Inc.
41 * Copyright 2018 Joyent, Inc.
42 * Copyright 2020 Oxide Computer Company
43 */
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/types.h>
49 #ifndef WITHOUT_CAPSICUM
50 #include <sys/capsicum.h>
51 #endif
52 #include <sys/mman.h>
53 #include <sys/time.h>
54 #include <sys/cpuset.h>
55
56 #ifdef __FreeBSD__
57 #include <amd64/vmm/intel/vmcs.h>
58 #else
59 #include <intel/vmcs.h>
60 #endif
61
62 #include <machine/atomic.h>
63 #include <machine/segments.h>
64
65 #ifndef WITHOUT_CAPSICUM
66 #include <capsicum_helpers.h>
67 #endif
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <libgen.h>
74 #include <unistd.h>
75 #include <assert.h>
76 #include <pthread.h>
77 #include <pthread_np.h>
78 #include <sysexits.h>
79 #include <stdbool.h>
80 #include <stdint.h>
81
82 #include <machine/vmm.h>
83 #ifndef WITHOUT_CAPSICUM
84 #include <machine/vmm_dev.h>
85 #endif
86 #include <vmmapi.h>
87
88 #ifndef __FreeBSD__
89 #include <sys/stat.h>
90 #endif
91
92 #include "bhyverun.h"
93 #include "acpi.h"
94 #include "atkbdc.h"
95 #include "console.h"
96 #include "bootrom.h"
97 #include "inout.h"
98 #include "dbgport.h"
99 #include "debug.h"
100 #include "fwctl.h"
101 #include "gdb.h"
102 #include "ioapic.h"
103 #include "kernemu_dev.h"
104 #include "mem.h"
105 #include "mevent.h"
106 #include "mptbl.h"
107 #include "pci_emul.h"
108 #include "pci_irq.h"
109 #include "pci_lpc.h"
110 #include "smbiostbl.h"
111 #include "xmsr.h"
112 #include "spinup_ap.h"
113 #include "rfb.h"
114 #include "rtc.h"
115 #include "vga.h"
116 #include "vmgenc.h"
117
118 #define GUEST_NIO_PORT 0x488 /* guest upcalls via i/o port */
119
120 #define MB (1024UL * 1024)
121 #define GB (1024UL * MB)
122
123 static const char * const vmx_exit_reason_desc[] = {
124 [EXIT_REASON_EXCEPTION] = "Exception or non-maskable interrupt (NMI)",
125 [EXIT_REASON_EXT_INTR] = "External interrupt",
126 [EXIT_REASON_TRIPLE_FAULT] = "Triple fault",
127 [EXIT_REASON_INIT] = "INIT signal",
128 [EXIT_REASON_SIPI] = "Start-up IPI (SIPI)",
129 [EXIT_REASON_IO_SMI] = "I/O system-management interrupt (SMI)",
130 [EXIT_REASON_SMI] = "Other SMI",
131 [EXIT_REASON_INTR_WINDOW] = "Interrupt window",
132 [EXIT_REASON_NMI_WINDOW] = "NMI window",
133 [EXIT_REASON_TASK_SWITCH] = "Task switch",
134 [EXIT_REASON_CPUID] = "CPUID",
135 [EXIT_REASON_GETSEC] = "GETSEC",
136 [EXIT_REASON_HLT] = "HLT",
137 [EXIT_REASON_INVD] = "INVD",
138 [EXIT_REASON_INVLPG] = "INVLPG",
139 [EXIT_REASON_RDPMC] = "RDPMC",
140 [EXIT_REASON_RDTSC] = "RDTSC",
141 [EXIT_REASON_RSM] = "RSM",
142 [EXIT_REASON_VMCALL] = "VMCALL",
143 [EXIT_REASON_VMCLEAR] = "VMCLEAR",
144 [EXIT_REASON_VMLAUNCH] = "VMLAUNCH",
145 [EXIT_REASON_VMPTRLD] = "VMPTRLD",
146 [EXIT_REASON_VMPTRST] = "VMPTRST",
147 [EXIT_REASON_VMREAD] = "VMREAD",
148 [EXIT_REASON_VMRESUME] = "VMRESUME",
149 [EXIT_REASON_VMWRITE] = "VMWRITE",
150 [EXIT_REASON_VMXOFF] = "VMXOFF",
151 [EXIT_REASON_VMXON] = "VMXON",
152 [EXIT_REASON_CR_ACCESS] = "Control-register accesses",
153 [EXIT_REASON_DR_ACCESS] = "MOV DR",
154 [EXIT_REASON_INOUT] = "I/O instruction",
155 [EXIT_REASON_RDMSR] = "RDMSR",
156 [EXIT_REASON_WRMSR] = "WRMSR",
157 [EXIT_REASON_INVAL_VMCS] =
158 "VM-entry failure due to invalid guest state",
159 [EXIT_REASON_INVAL_MSR] = "VM-entry failure due to MSR loading",
160 [EXIT_REASON_MWAIT] = "MWAIT",
161 [EXIT_REASON_MTF] = "Monitor trap flag",
162 [EXIT_REASON_MONITOR] = "MONITOR",
163 [EXIT_REASON_PAUSE] = "PAUSE",
164 [EXIT_REASON_MCE_DURING_ENTRY] =
165 "VM-entry failure due to machine-check event",
166 [EXIT_REASON_TPR] = "TPR below threshold",
167 [EXIT_REASON_APIC_ACCESS] = "APIC access",
168 [EXIT_REASON_VIRTUALIZED_EOI] = "Virtualized EOI",
169 [EXIT_REASON_GDTR_IDTR] = "Access to GDTR or IDTR",
170 [EXIT_REASON_LDTR_TR] = "Access to LDTR or TR",
171 [EXIT_REASON_EPT_FAULT] = "EPT violation",
172 [EXIT_REASON_EPT_MISCONFIG] = "EPT misconfiguration",
173 [EXIT_REASON_INVEPT] = "INVEPT",
174 [EXIT_REASON_RDTSCP] = "RDTSCP",
175 [EXIT_REASON_VMX_PREEMPT] = "VMX-preemption timer expired",
176 [EXIT_REASON_INVVPID] = "INVVPID",
177 [EXIT_REASON_WBINVD] = "WBINVD",
178 [EXIT_REASON_XSETBV] = "XSETBV",
179 [EXIT_REASON_APIC_WRITE] = "APIC write",
180 [EXIT_REASON_RDRAND] = "RDRAND",
181 [EXIT_REASON_INVPCID] = "INVPCID",
182 [EXIT_REASON_VMFUNC] = "VMFUNC",
183 [EXIT_REASON_ENCLS] = "ENCLS",
184 [EXIT_REASON_RDSEED] = "RDSEED",
185 [EXIT_REASON_PM_LOG_FULL] = "Page-modification log full",
186 [EXIT_REASON_XSAVES] = "XSAVES",
187 [EXIT_REASON_XRSTORS] = "XRSTORS"
188 };
189
190 typedef int (*vmexit_handler_t)(struct vmctx *, struct vm_exit *, int *vcpu);
191 extern int vmexit_task_switch(struct vmctx *, struct vm_exit *, int *vcpu);
192
193 char *vmname;
194
195 int guest_ncpus;
196 uint16_t cores, maxcpus, sockets, threads;
197
198 char *guest_uuid_str;
199
200 int raw_stdio = 0;
201
202 static int gdb_port = 0;
203 static int guest_vmexit_on_hlt, guest_vmexit_on_pause;
204 static int virtio_msix = 1;
205 static int x2apic_mode = 0; /* default is xAPIC */
206
207 static int strictio;
208 static int strictmsr = 1;
209
210 static int acpi;
211
212 static char *progname;
213 static const int BSP = 0;
214
215 static cpuset_t cpumask;
216
217 static void vm_loop(struct vmctx *ctx, int vcpu, uint64_t rip);
218
219 static struct vm_exit vmexit[VM_MAXCPU];
220 static struct vm_entry vmentry[VM_MAXCPU];
221
222 struct bhyvestats {
223 uint64_t vmexit_bogus;
224 uint64_t vmexit_reqidle;
225 uint64_t vmexit_hlt;
226 uint64_t vmexit_pause;
227 uint64_t vmexit_mtrap;
228 uint64_t vmexit_mmio;
229 uint64_t vmexit_inout;
230 uint64_t cpu_switch_rotate;
231 uint64_t cpu_switch_direct;
232 uint64_t mmio_unhandled;
233 } stats;
234
235 struct mt_vmm_info {
236 pthread_t mt_thr;
237 struct vmctx *mt_ctx;
238 int mt_vcpu;
239 uint64_t mt_startrip;
240 } mt_vmm_info[VM_MAXCPU];
241
242 #ifdef __FreeBSD__
243 static cpuset_t *vcpumap[VM_MAXCPU] = { NULL };
244 #endif
245
246 static void
247 usage(int code)
248 {
249
250 fprintf(stderr,
251 "Usage: %s [-abehuwxACHPSWY]\n"
252 " %*s [-c [[cpus=]numcpus][,sockets=n][,cores=n][,threads=n]]\n"
253 " %*s [-g <gdb port>] [-l <lpc>]\n"
254 #ifdef __FreeBSD__
255 " %*s [-m mem] [-p vcpu:hostcpu] [-s <pci>] [-U uuid] <vm>\n"
256 #else
257 " %*s [-m mem] [-s <pci>] [-U uuid] <vm>\n"
258 #endif
259 " -a: local apic is in xAPIC mode (deprecated)\n"
260 " -A: create ACPI tables\n"
261 " -c: number of cpus and/or topology specification\n"
262 " -C: include guest memory in core file\n"
263 #ifndef __FreeBSD__
264 " -d: suspend cpu at boot\n"
265 #endif
266 " -e: exit on unhandled I/O access\n"
267 " -g: gdb port\n"
268 " -h: help\n"
269 " -H: vmexit from the guest on hlt\n"
270 " -l: LPC device configuration\n"
271 " -m: memory size\n"
272 #ifdef __FreeBSD__
273 " -p: pin 'vcpu' to 'hostcpu'\n"
274 #endif
275 " -P: vmexit from the guest on pause\n"
276 " -s: <slot,driver,configinfo> PCI slot config\n"
277 " -S: guest memory cannot be swapped\n"
278 " -u: RTC keeps UTC time\n"
279 " -U: uuid\n"
280 " -w: ignore unimplemented MSRs\n"
281 " -W: force virtio to use single-vector MSI\n"
282 " -x: local apic is in x2APIC mode\n"
283 " -Y: disable MPtable generation\n",
284 progname, (int)strlen(progname), "", (int)strlen(progname), "",
285 (int)strlen(progname), "");
286
287 exit(code);
288 }
289
290 /*
291 * XXX This parser is known to have the following issues:
292 * 1. It accepts null key=value tokens ",,".
293 * 2. It accepts whitespace after = and before value.
294 * 3. Values out of range of INT are silently wrapped.
295 * 4. It doesn't check non-final values.
296 * 5. The apparently bogus limits of UINT16_MAX are for future expansion.
297 *
298 * The acceptance of a null specification ('-c ""') is by design to match the
299 * manual page syntax specification, this results in a topology of 1 vCPU.
300 */
301 static int
302 topology_parse(const char *opt)
303 {
304 uint64_t ncpus;
305 int c, chk, n, s, t, tmp;
306 char *cp, *str;
307 bool ns, scts;
308
309 c = 1, n = 1, s = 1, t = 1;
310 ns = false, scts = false;
311 str = strdup(opt);
312 if (str == NULL)
313 goto out;
314
315 while ((cp = strsep(&str, ",")) != NULL) {
316 if (sscanf(cp, "%i%n", &tmp, &chk) == 1) {
317 n = tmp;
318 ns = true;
319 } else if (sscanf(cp, "cpus=%i%n", &tmp, &chk) == 1) {
320 n = tmp;
321 ns = true;
322 } else if (sscanf(cp, "sockets=%i%n", &tmp, &chk) == 1) {
323 s = tmp;
324 scts = true;
325 } else if (sscanf(cp, "cores=%i%n", &tmp, &chk) == 1) {
326 c = tmp;
327 scts = true;
328 } else if (sscanf(cp, "threads=%i%n", &tmp, &chk) == 1) {
329 t = tmp;
330 scts = true;
331 #ifdef notyet /* Do not expose this until vmm.ko implements it */
332 } else if (sscanf(cp, "maxcpus=%i%n", &tmp, &chk) == 1) {
333 m = tmp;
334 #endif
335 /* Skip the empty argument case from -c "" */
336 } else if (cp[0] == '\0')
337 continue;
338 else
339 goto out;
340 /* Any trailing garbage causes an error */
341 if (cp[chk] != '\0')
342 goto out;
343 }
344 free(str);
345 str = NULL;
346
347 /*
348 * Range check 1 <= n <= UINT16_MAX all values
349 */
350 if (n < 1 || s < 1 || c < 1 || t < 1 ||
351 n > UINT16_MAX || s > UINT16_MAX || c > UINT16_MAX ||
352 t > UINT16_MAX)
353 return (-1);
354
355 /* If only the cpus was specified, use that as sockets */
356 if (!scts)
357 s = n;
358 /*
359 * Compute sockets * cores * threads avoiding overflow
360 * The range check above insures these are 16 bit values
361 * If n was specified check it against computed ncpus
362 */
363 ncpus = (uint64_t)s * c * t;
364 if (ncpus > UINT16_MAX || (ns && n != ncpus))
365 return (-1);
366
367 guest_ncpus = ncpus;
368 sockets = s;
369 cores = c;
370 threads = t;
371 return(0);
372
373 out:
374 free(str);
375 return (-1);
376 }
377
378 #ifndef WITHOUT_CAPSICUM
379 /*
380 * 11-stable capsicum helpers
381 */
382 static void
383 bhyve_caph_cache_catpages(void)
384 {
385
386 (void)catopen("libc", NL_CAT_LOCALE);
387 }
388
389 static int
390 bhyve_caph_limit_stdoe(void)
391 {
392 cap_rights_t rights;
393 unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ };
394 int i, fds[] = { STDOUT_FILENO, STDERR_FILENO };
395
396 cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL);
397 cap_rights_set(&rights, CAP_WRITE);
398
399 for (i = 0; i < nitems(fds); i++) {
400 if (cap_rights_limit(fds[i], &rights) < 0 && errno != ENOSYS)
401 return (-1);
402
403 if (cap_ioctls_limit(fds[i], cmds, nitems(cmds)) < 0 && errno != ENOSYS)
404 return (-1);
405
406 if (cap_fcntls_limit(fds[i], CAP_FCNTL_GETFL) < 0 && errno != ENOSYS)
407 return (-1);
408 }
409
410 return (0);
411 }
412
413 #endif
414
415 #ifdef __FreeBSD__
416 static int
417 pincpu_parse(const char *opt)
418 {
419 int vcpu, pcpu;
420
421 if (sscanf(opt, "%d:%d", &vcpu, &pcpu) != 2) {
422 fprintf(stderr, "invalid format: %s\n", opt);
423 return (-1);
424 }
425
426 if (vcpu < 0 || vcpu >= VM_MAXCPU) {
427 fprintf(stderr, "vcpu '%d' outside valid range from 0 to %d\n",
428 vcpu, VM_MAXCPU - 1);
429 return (-1);
430 }
431
432 if (pcpu < 0 || pcpu >= CPU_SETSIZE) {
433 fprintf(stderr, "hostcpu '%d' outside valid range from "
434 "0 to %d\n", pcpu, CPU_SETSIZE - 1);
435 return (-1);
436 }
437
438 if (vcpumap[vcpu] == NULL) {
439 if ((vcpumap[vcpu] = malloc(sizeof(cpuset_t))) == NULL) {
440 perror("malloc");
441 return (-1);
442 }
443 CPU_ZERO(vcpumap[vcpu]);
444 }
445 CPU_SET(pcpu, vcpumap[vcpu]);
446 return (0);
447 }
448
449 void
450 vm_inject_fault(void *arg, int vcpu, int vector, int errcode_valid,
451 int errcode)
452 {
453 struct vmctx *ctx;
454 int error, restart_instruction;
455
456 ctx = arg;
457 restart_instruction = 1;
458
459 error = vm_inject_exception(ctx, vcpu, vector, errcode_valid, errcode,
460 restart_instruction);
461 assert(error == 0);
462 }
463 #endif /* __FreeBSD__ */
464
465 void *
466 paddr_guest2host(struct vmctx *ctx, uintptr_t gaddr, size_t len)
467 {
468
469 return (vm_map_gpa(ctx, gaddr, len));
470 }
471
472 int
473 fbsdrun_vmexit_on_pause(void)
474 {
475
476 return (guest_vmexit_on_pause);
477 }
478
479 int
480 fbsdrun_vmexit_on_hlt(void)
481 {
482
483 return (guest_vmexit_on_hlt);
484 }
485
486 int
487 fbsdrun_virtio_msix(void)
488 {
489
490 return (virtio_msix);
491 }
492
493 static void *
494 fbsdrun_start_thread(void *param)
495 {
496 char tname[MAXCOMLEN + 1];
497 struct mt_vmm_info *mtp;
498 int vcpu;
499
500 mtp = param;
501 vcpu = mtp->mt_vcpu;
502
503 snprintf(tname, sizeof(tname), "vcpu %d", vcpu);
504 pthread_set_name_np(mtp->mt_thr, tname);
505
506 if (gdb_port != 0)
507 gdb_cpu_add(vcpu);
508
509 vm_loop(mtp->mt_ctx, vcpu, mtp->mt_startrip);
510
511 /* not reached */
512 exit(1);
513 return (NULL);
514 }
515
516 #ifdef __FreeBSD__
517 void
518 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip)
519 #else
520 void
521 fbsdrun_addcpu(struct vmctx *ctx, int fromcpu, int newcpu, uint64_t rip,
522 bool suspend)
523 #endif
524 {
525 int error;
526
527 assert(fromcpu == BSP);
528
529 /*
530 * The 'newcpu' must be activated in the context of 'fromcpu'. If
531 * vm_activate_cpu() is delayed until newcpu's pthread starts running
532 * then vmm.ko is out-of-sync with bhyve and this can create a race
533 * with vm_suspend().
534 */
535 error = vm_activate_cpu(ctx, newcpu);
536 if (error != 0)
537 err(EX_OSERR, "could not activate CPU %d", newcpu);
538
539 CPU_SET_ATOMIC(newcpu, &cpumask);
540
541 #ifndef __FreeBSD__
542 if (suspend)
543 (void) vm_suspend_cpu(ctx, newcpu);
544 #endif
545
546 /*
547 * Set up the vmexit struct to allow execution to start
548 * at the given RIP
549 */
550 mt_vmm_info[newcpu].mt_ctx = ctx;
551 mt_vmm_info[newcpu].mt_vcpu = newcpu;
552 mt_vmm_info[newcpu].mt_startrip = rip;
553
554 error = pthread_create(&mt_vmm_info[newcpu].mt_thr, NULL,
555 fbsdrun_start_thread, &mt_vmm_info[newcpu]);
556 assert(error == 0);
557 }
558
559 static int
560 fbsdrun_deletecpu(struct vmctx *ctx, int vcpu)
561 {
562
563 if (!CPU_ISSET(vcpu, &cpumask)) {
564 fprintf(stderr, "Attempting to delete unknown cpu %d\n", vcpu);
565 exit(4);
566 }
567
568 CPU_CLR_ATOMIC(vcpu, &cpumask);
569 return (CPU_EMPTY(&cpumask));
570 }
571
572 static void
573 vmentry_mmio_read(int vcpu, uint64_t gpa, uint8_t bytes, uint64_t data)
574 {
575 struct vm_entry *entry = &vmentry[vcpu];
576 struct vm_mmio *mmio = &entry->u.mmio;
577
578 assert(entry->cmd == VEC_DEFAULT);
579
580 entry->cmd = VEC_COMPLETE_MMIO;
581 mmio->bytes = bytes;
582 mmio->read = 1;
583 mmio->gpa = gpa;
584 mmio->data = data;
585 }
586
587 static void
588 vmentry_mmio_write(int vcpu, uint64_t gpa, uint8_t bytes)
589 {
590 struct vm_entry *entry = &vmentry[vcpu];
591 struct vm_mmio *mmio = &entry->u.mmio;
592
593 assert(entry->cmd == VEC_DEFAULT);
594
595 entry->cmd = VEC_COMPLETE_MMIO;
596 mmio->bytes = bytes;
597 mmio->read = 0;
598 mmio->gpa = gpa;
599 mmio->data = 0;
600 }
601
602 static void
603 vmentry_inout_read(int vcpu, uint16_t port, uint8_t bytes, uint32_t data)
604 {
605 struct vm_entry *entry = &vmentry[vcpu];
606 struct vm_inout *inout = &entry->u.inout;
607
608 assert(entry->cmd == VEC_DEFAULT);
609
610 entry->cmd = VEC_COMPLETE_INOUT;
611 inout->bytes = bytes;
612 inout->flags = INOUT_IN;
613 inout->port = port;
614 inout->eax = data;
615 }
616
617 static void
618 vmentry_inout_write(int vcpu, uint16_t port, uint8_t bytes)
619 {
620 struct vm_entry *entry = &vmentry[vcpu];
621 struct vm_inout *inout = &entry->u.inout;
622
623 assert(entry->cmd == VEC_DEFAULT);
624
625 entry->cmd = VEC_COMPLETE_INOUT;
626 inout->bytes = bytes;
627 inout->flags = 0;
628 inout->port = port;
629 inout->eax = 0;
630 }
631
632 static int
633 vmexit_handle_notify(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu,
634 uint32_t eax)
635 {
636 #if BHYVE_DEBUG
637 /*
638 * put guest-driven debug here
639 */
640 #endif
641 return (VMEXIT_CONTINUE);
642 }
643
644 static int
645 vmexit_inout(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
646 {
647 int error;
648 int vcpu;
649 struct vm_inout inout;
650 bool in;
651 uint8_t bytes;
652
653 stats.vmexit_inout++;
654
655 vcpu = *pvcpu;
656 inout = vme->u.inout;
657 in = (inout.flags & INOUT_IN) != 0;
658 bytes = inout.bytes;
659
660 /* Extra-special case of host notifications */
661 if (!in && inout.port == GUEST_NIO_PORT) {
662 error = vmexit_handle_notify(ctx, vme, pvcpu, inout.eax);
663 vmentry_inout_write(vcpu, inout.port, bytes);
664 return (error);
665 }
666
667 error = emulate_inout(ctx, vcpu, &inout, strictio != 0);
668 if (error) {
669 fprintf(stderr, "Unhandled %s%c 0x%04x at 0x%lx\n",
670 in ? "in" : "out",
671 bytes == 1 ? 'b' : (bytes == 2 ? 'w' : 'l'),
672 inout.port, vmexit->rip);
673 return (VMEXIT_ABORT);
674 } else {
675 /*
676 * Communicate the status of the inout operation back to the
677 * in-kernel instruction emulation.
678 */
679 if (in) {
680 vmentry_inout_read(vcpu, inout.port, bytes, inout.eax);
681 } else {
682 vmentry_inout_write(vcpu, inout.port, bytes);
683 }
684 return (VMEXIT_CONTINUE);
685 }
686 }
687
688 static int
689 vmexit_rdmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
690 {
691 uint64_t val;
692 uint32_t eax, edx;
693 int error;
694
695 val = 0;
696 error = emulate_rdmsr(ctx, *pvcpu, vme->u.msr.code, &val);
697 if (error != 0) {
698 fprintf(stderr, "rdmsr to register %#x on vcpu %d\n",
699 vme->u.msr.code, *pvcpu);
700 if (strictmsr) {
701 vm_inject_gp(ctx, *pvcpu);
702 return (VMEXIT_CONTINUE);
703 }
704 }
705
706 eax = val;
707 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RAX, eax);
708 assert(error == 0);
709
710 edx = val >> 32;
711 error = vm_set_register(ctx, *pvcpu, VM_REG_GUEST_RDX, edx);
712 assert(error == 0);
713
714 return (VMEXIT_CONTINUE);
715 }
716
717 static int
718 vmexit_wrmsr(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
719 {
720 int error;
721
722 error = emulate_wrmsr(ctx, *pvcpu, vme->u.msr.code, vme->u.msr.wval);
723 if (error != 0) {
724 fprintf(stderr, "wrmsr to register %#x(%#lx) on vcpu %d\n",
725 vme->u.msr.code, vme->u.msr.wval, *pvcpu);
726 if (strictmsr) {
727 vm_inject_gp(ctx, *pvcpu);
728 return (VMEXIT_CONTINUE);
729 }
730 }
731 return (VMEXIT_CONTINUE);
732 }
733
734 static int
735 vmexit_spinup_ap(struct vmctx *ctx, struct vm_exit *vme, int *pvcpu)
736 {
737
738 (void)spinup_ap(ctx, *pvcpu,
739 vme->u.spinup_ap.vcpu, vme->u.spinup_ap.rip);
740
741 return (VMEXIT_CONTINUE);
742 }
743
744 #ifdef __FreeBSD__
745 #define DEBUG_EPT_MISCONFIG
746 #else
747 /* EPT misconfig debugging not possible now that raw VMCS access is gone */
748 #endif
749
750 #ifdef DEBUG_EPT_MISCONFIG
751 #define VMCS_GUEST_PHYSICAL_ADDRESS 0x00002400
752
753 static uint64_t ept_misconfig_gpa, ept_misconfig_pte[4];
754 static int ept_misconfig_ptenum;
755 #endif
756
757 static const char *
758 vmexit_vmx_desc(uint32_t exit_reason)
759 {
760
761 if (exit_reason >= nitems(vmx_exit_reason_desc) ||
762 vmx_exit_reason_desc[exit_reason] == NULL)
763 return ("Unknown");
764 return (vmx_exit_reason_desc[exit_reason]);
765 }
766
767 static int
768 vmexit_vmx(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
769 {
770
771 fprintf(stderr, "vm exit[%d]\n", *pvcpu);
772 fprintf(stderr, "\treason\t\tVMX\n");
773 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
774 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
775 fprintf(stderr, "\tstatus\t\t%d\n", vmexit->u.vmx.status);
776 fprintf(stderr, "\texit_reason\t%u (%s)\n", vmexit->u.vmx.exit_reason,
777 vmexit_vmx_desc(vmexit->u.vmx.exit_reason));
778 fprintf(stderr, "\tqualification\t0x%016lx\n",
779 vmexit->u.vmx.exit_qualification);
780 fprintf(stderr, "\tinst_type\t\t%d\n", vmexit->u.vmx.inst_type);
781 fprintf(stderr, "\tinst_error\t\t%d\n", vmexit->u.vmx.inst_error);
782 #ifdef DEBUG_EPT_MISCONFIG
783 if (vmexit->u.vmx.exit_reason == EXIT_REASON_EPT_MISCONFIG) {
784 vm_get_register(ctx, *pvcpu,
785 VMCS_IDENT(VMCS_GUEST_PHYSICAL_ADDRESS),
786 &ept_misconfig_gpa);
787 vm_get_gpa_pmap(ctx, ept_misconfig_gpa, ept_misconfig_pte,
788 &ept_misconfig_ptenum);
789 fprintf(stderr, "\tEPT misconfiguration:\n");
790 fprintf(stderr, "\t\tGPA: %#lx\n", ept_misconfig_gpa);
791 fprintf(stderr, "\t\tPTE(%d): %#lx %#lx %#lx %#lx\n",
792 ept_misconfig_ptenum, ept_misconfig_pte[0],
793 ept_misconfig_pte[1], ept_misconfig_pte[2],
794 ept_misconfig_pte[3]);
795 }
796 #endif /* DEBUG_EPT_MISCONFIG */
797 return (VMEXIT_ABORT);
798 }
799
800 static int
801 vmexit_svm(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
802 {
803
804 fprintf(stderr, "vm exit[%d]\n", *pvcpu);
805 fprintf(stderr, "\treason\t\tSVM\n");
806 fprintf(stderr, "\trip\t\t0x%016lx\n", vmexit->rip);
807 fprintf(stderr, "\tinst_length\t%d\n", vmexit->inst_length);
808 fprintf(stderr, "\texitcode\t%#lx\n", vmexit->u.svm.exitcode);
809 fprintf(stderr, "\texitinfo1\t%#lx\n", vmexit->u.svm.exitinfo1);
810 fprintf(stderr, "\texitinfo2\t%#lx\n", vmexit->u.svm.exitinfo2);
811 return (VMEXIT_ABORT);
812 }
813
814 static int
815 vmexit_bogus(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
816 {
817
818 assert(vmexit->inst_length == 0);
819
820 stats.vmexit_bogus++;
821
822 return (VMEXIT_CONTINUE);
823 }
824
825 static int
826 vmexit_reqidle(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
827 {
828
829 assert(vmexit->inst_length == 0);
830
831 stats.vmexit_reqidle++;
832
833 return (VMEXIT_CONTINUE);
834 }
835
836 static int
837 vmexit_hlt(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
838 {
839
840 stats.vmexit_hlt++;
841
842 /*
843 * Just continue execution with the next instruction. We use
844 * the HLT VM exit as a way to be friendly with the host
845 * scheduler.
846 */
847 return (VMEXIT_CONTINUE);
848 }
849
850 static int
851 vmexit_pause(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
852 {
853
854 stats.vmexit_pause++;
855
856 return (VMEXIT_CONTINUE);
857 }
858
859 static int
860 vmexit_mtrap(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
861 {
862
863 assert(vmexit->inst_length == 0);
864
865 stats.vmexit_mtrap++;
866
867 if (gdb_port == 0) {
868 fprintf(stderr, "vm_loop: unexpected VMEXIT_MTRAP\n");
869 exit(4);
870 }
871 gdb_cpu_mtrap(*pvcpu);
872 return (VMEXIT_CONTINUE);
873 }
874
875 static int
876 vmexit_inst_emul(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
877 {
878 uint8_t i, valid;
879
880 fprintf(stderr, "Failed to emulate instruction sequence ");
881
882 valid = vmexit->u.inst_emul.num_valid;
883 if (valid != 0) {
884 assert(valid <= sizeof (vmexit->u.inst_emul.inst));
885 fprintf(stderr, "[");
886 for (i = 0; i < valid; i++) {
887 if (i == 0) {
888 fprintf(stderr, "%02x",
889 vmexit->u.inst_emul.inst[i]);
890 } else {
891 fprintf(stderr, ", %02x",
892 vmexit->u.inst_emul.inst[i]);
893 }
894 }
895 fprintf(stderr, "] ");
896 }
897 fprintf(stderr, "@ %rip = %x\n", vmexit->rip);
898
899 return (VMEXIT_ABORT);
900 }
901
902 static int
903 vmexit_mmio(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
904 {
905 int vcpu, err;
906 struct vm_mmio mmio;
907 bool is_read;
908
909 stats.vmexit_mmio++;
910
911 vcpu = *pvcpu;
912 mmio = vmexit->u.mmio;
913 is_read = (mmio.read != 0);
914
915 err = emulate_mem(ctx, vcpu, &mmio);
916
917 if (err == ESRCH) {
918 fprintf(stderr, "Unhandled memory access to 0x%lx\n", mmio.gpa);
919 stats.mmio_unhandled++;
920
921 /*
922 * Access to non-existent physical addresses is not likely to
923 * result in fatal errors on hardware machines, but rather reads
924 * of all-ones or discarded-but-acknowledged writes.
925 */
926 mmio.data = ~0UL;
927 err = 0;
928 }
929
930 if (err == 0) {
931 if (is_read) {
932 vmentry_mmio_read(vcpu, mmio.gpa, mmio.bytes,
933 mmio.data);
934 } else {
935 vmentry_mmio_write(vcpu, mmio.gpa, mmio.bytes);
936 }
937 return (VMEXIT_CONTINUE);
938 }
939
940 fprintf(stderr, "Unhandled mmio error to 0x%lx: %d\n", mmio.gpa, err);
941 return (VMEXIT_ABORT);
942 }
943
944 static pthread_mutex_t resetcpu_mtx = PTHREAD_MUTEX_INITIALIZER;
945 static pthread_cond_t resetcpu_cond = PTHREAD_COND_INITIALIZER;
946
947 static int
948 vmexit_suspend(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
949 {
950 enum vm_suspend_how how;
951
952 how = vmexit->u.suspended.how;
953
954 fbsdrun_deletecpu(ctx, *pvcpu);
955
956 if (*pvcpu != BSP) {
957 pthread_mutex_lock(&resetcpu_mtx);
958 pthread_cond_signal(&resetcpu_cond);
959 pthread_mutex_unlock(&resetcpu_mtx);
960 pthread_exit(NULL);
961 }
962
963 pthread_mutex_lock(&resetcpu_mtx);
964 while (!CPU_EMPTY(&cpumask)) {
965 pthread_cond_wait(&resetcpu_cond, &resetcpu_mtx);
966 }
967 pthread_mutex_unlock(&resetcpu_mtx);
968
969 switch (how) {
970 case VM_SUSPEND_RESET:
971 exit(0);
972 case VM_SUSPEND_POWEROFF:
973 exit(1);
974 case VM_SUSPEND_HALT:
975 exit(2);
976 case VM_SUSPEND_TRIPLEFAULT:
977 exit(3);
978 default:
979 fprintf(stderr, "vmexit_suspend: invalid reason %d\n", how);
980 exit(100);
981 }
982 return (0); /* NOTREACHED */
983 }
984
985 static int
986 vmexit_debug(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
987 {
988
989 if (gdb_port == 0) {
990 fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
991 exit(4);
992 }
993 gdb_cpu_suspend(*pvcpu);
994 return (VMEXIT_CONTINUE);
995 }
996
997 static int
998 vmexit_breakpoint(struct vmctx *ctx, struct vm_exit *vmexit, int *pvcpu)
999 {
1000
1001 if (gdb_port == 0) {
1002 fprintf(stderr, "vm_loop: unexpected VMEXIT_DEBUG\n");
1003 exit(4);
1004 }
1005 gdb_cpu_breakpoint(*pvcpu, vmexit);
1006 return (VMEXIT_CONTINUE);
1007 }
1008
1009 static vmexit_handler_t handler[VM_EXITCODE_MAX] = {
1010 [VM_EXITCODE_INOUT] = vmexit_inout,
1011 [VM_EXITCODE_MMIO] = vmexit_mmio,
1012 [VM_EXITCODE_VMX] = vmexit_vmx,
1013 [VM_EXITCODE_SVM] = vmexit_svm,
1014 [VM_EXITCODE_BOGUS] = vmexit_bogus,
1015 [VM_EXITCODE_REQIDLE] = vmexit_reqidle,
1016 [VM_EXITCODE_RDMSR] = vmexit_rdmsr,
1017 [VM_EXITCODE_WRMSR] = vmexit_wrmsr,
1018 [VM_EXITCODE_MTRAP] = vmexit_mtrap,
1019 [VM_EXITCODE_INST_EMUL] = vmexit_inst_emul,
1020 [VM_EXITCODE_SPINUP_AP] = vmexit_spinup_ap,
1021 [VM_EXITCODE_SUSPENDED] = vmexit_suspend,
1022 [VM_EXITCODE_TASK_SWITCH] = vmexit_task_switch,
1023 [VM_EXITCODE_DEBUG] = vmexit_debug,
1024 [VM_EXITCODE_BPT] = vmexit_breakpoint,
1025 };
1026
1027 static void
1028 vm_loop(struct vmctx *ctx, int vcpu, uint64_t startrip)
1029 {
1030 int error, rc;
1031 enum vm_exitcode exitcode;
1032 cpuset_t active_cpus;
1033 struct vm_exit *vexit;
1034 struct vm_entry *ventry;
1035
1036 #ifdef __FreeBSD__
1037 if (vcpumap[vcpu] != NULL) {
1038 error = pthread_setaffinity_np(pthread_self(),
1039 sizeof(cpuset_t), vcpumap[vcpu]);
1040 assert(error == 0);
1041 }
1042 #endif
1043 error = vm_active_cpus(ctx, &active_cpus);
1044 assert(CPU_ISSET(vcpu, &active_cpus));
1045
1046 error = vm_set_register(ctx, vcpu, VM_REG_GUEST_RIP, startrip);
1047 assert(error == 0);
1048
1049 ventry = &vmentry[vcpu];
1050 vexit = &vmexit[vcpu];
1051
1052 while (1) {
1053 error = vm_run(ctx, vcpu, ventry, vexit);
1054 if (error != 0)
1055 break;
1056
1057 if (ventry->cmd != VEC_DEFAULT) {
1058 /*
1059 * Discard any lingering entry state after it has been
1060 * submitted via vm_run().
1061 */
1062 bzero(ventry, sizeof (*ventry));
1063 }
1064
1065 exitcode = vexit->exitcode;
1066 if (exitcode >= VM_EXITCODE_MAX || handler[exitcode] == NULL) {
1067 fprintf(stderr, "vm_loop: unexpected exitcode 0x%x\n",
1068 exitcode);
1069 exit(4);
1070 }
1071
1072 rc = (*handler[exitcode])(ctx, vexit, &vcpu);
1073
1074 switch (rc) {
1075 case VMEXIT_CONTINUE:
1076 break;
1077 case VMEXIT_ABORT:
1078 abort();
1079 default:
1080 exit(4);
1081 }
1082 }
1083 fprintf(stderr, "vm_run error %d, errno %d\n", error, errno);
1084 }
1085
1086 static int
1087 num_vcpus_allowed(struct vmctx *ctx)
1088 {
1089 #ifdef __FreeBSD__
1090 int tmp, error;
1091
1092 error = vm_get_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, &tmp);
1093
1094 /*
1095 * The guest is allowed to spinup more than one processor only if the
1096 * UNRESTRICTED_GUEST capability is available.
1097 */
1098 if (error == 0)
1099 return (VM_MAXCPU);
1100 else
1101 return (1);
1102 #else
1103 /* Unrestricted Guest is always enabled on illumos */
1104 return (VM_MAXCPU);
1105 #endif /* __FreeBSD__ */
1106 }
1107
1108 void
1109 fbsdrun_set_capabilities(struct vmctx *ctx, int cpu)
1110 {
1111 int err, tmp;
1112
1113 if (fbsdrun_vmexit_on_hlt()) {
1114 err = vm_get_capability(ctx, cpu, VM_CAP_HALT_EXIT, &tmp);
1115 if (err < 0) {
1116 fprintf(stderr, "VM exit on HLT not supported\n");
1117 exit(4);
1118 }
1119 vm_set_capability(ctx, cpu, VM_CAP_HALT_EXIT, 1);
1120 if (cpu == BSP)
1121 handler[VM_EXITCODE_HLT] = vmexit_hlt;
1122 }
1123
1124 if (fbsdrun_vmexit_on_pause()) {
1125 /*
1126 * pause exit support required for this mode
1127 */
1128 err = vm_get_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, &tmp);
1129 if (err < 0) {
1130 fprintf(stderr,
1131 "SMP mux requested, no pause support\n");
1132 exit(4);
1133 }
1134 vm_set_capability(ctx, cpu, VM_CAP_PAUSE_EXIT, 1);
1135 if (cpu == BSP)
1136 handler[VM_EXITCODE_PAUSE] = vmexit_pause;
1137 }
1138
1139 if (x2apic_mode)
1140 err = vm_set_x2apic_state(ctx, cpu, X2APIC_ENABLED);
1141 else
1142 err = vm_set_x2apic_state(ctx, cpu, X2APIC_DISABLED);
1143
1144 if (err) {
1145 fprintf(stderr, "Unable to set x2apic state (%d)\n", err);
1146 exit(4);
1147 }
1148
1149 #ifdef __FreeBSD__
1150 vm_set_capability(ctx, cpu, VM_CAP_ENABLE_INVPCID, 1);
1151 #endif
1152 }
1153
1154 static struct vmctx *
1155 do_open(const char *vmname)
1156 {
1157 struct vmctx *ctx;
1158 int error;
1159 bool reinit, romboot;
1160 #ifndef WITHOUT_CAPSICUM
1161 cap_rights_t rights;
1162 const cap_ioctl_t *cmds;
1163 size_t ncmds;
1164 #endif
1165
1166 reinit = romboot = false;
1167
1168 if (lpc_bootrom())
1169 romboot = true;
1170
1171 error = vm_create(vmname);
1172 if (error) {
1173 if (errno == EEXIST) {
1174 if (romboot) {
1175 reinit = true;
1176 } else {
1177 /*
1178 * The virtual machine has been setup by the
1179 * userspace bootloader.
1180 */
1181 }
1182 } else {
1183 perror("vm_create");
1184 exit(4);
1185 }
1186 } else {
1187 if (!romboot) {
1188 /*
1189 * If the virtual machine was just created then a
1190 * bootrom must be configured to boot it.
1191 */
1192 fprintf(stderr, "virtual machine cannot be booted\n");
1193 exit(4);
1194 }
1195 }
1196
1197 ctx = vm_open(vmname);
1198 if (ctx == NULL) {
1199 perror("vm_open");
1200 exit(4);
1201 }
1202
1203 #ifndef WITHOUT_CAPSICUM
1204 cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
1205 if (caph_rights_limit(vm_get_device_fd(ctx), &rights) == -1)
1206 errx(EX_OSERR, "Unable to apply rights for sandbox");
1207 vm_get_ioctls(&ncmds);
1208 cmds = vm_get_ioctls(NULL);
1209 if (cmds == NULL)
1210 errx(EX_OSERR, "out of memory");
1211 if (caph_ioctls_limit(vm_get_device_fd(ctx), cmds, ncmds) == -1)
1212 errx(EX_OSERR, "Unable to apply rights for sandbox");
1213 free((cap_ioctl_t *)cmds);
1214 #endif
1215
1216 if (reinit) {
1217 error = vm_reinit(ctx);
1218 if (error) {
1219 perror("vm_reinit");
1220 exit(4);
1221 }
1222 }
1223 error = vm_set_topology(ctx, sockets, cores, threads, maxcpus);
1224 if (error)
1225 errx(EX_OSERR, "vm_set_topology");
1226 return (ctx);
1227 }
1228
1229 #ifndef __FreeBSD__
1230
1231 #define FILE_PROVISIONING "/var/svc/provisioning"
1232 #define FILE_PROVISION_SUCCESS "/var/svc/provision_success"
1233
1234 static void
1235 mark_provisioned(void)
1236 {
1237 struct stat stbuf;
1238
1239 if (lstat(FILE_PROVISIONING, &stbuf) != 0)
1240 return;
1241
1242 if (rename(FILE_PROVISIONING, FILE_PROVISION_SUCCESS) != 0) {
1243 (void) fprintf(stderr, "Cannot rename %s to %s: %s\n",
1244 FILE_PROVISIONING, FILE_PROVISION_SUCCESS,
1245 strerror(errno));
1246 }
1247 }
1248
1249 #endif
1250
1251 int
1252 main(int argc, char *argv[])
1253 {
1254 int c, error, dbg_port, err, bvmcons;
1255 int max_vcpus, mptgen, memflags;
1256 int rtc_localtime;
1257 bool gdb_stop;
1258 #ifndef __FreeBSD__
1259 bool suspend = false;
1260 #endif
1261 struct vmctx *ctx;
1262 uint64_t rip;
1263 size_t memsize;
1264 char *optstr;
1265
1266 bvmcons = 0;
1267 progname = basename(argv[0]);
1268 dbg_port = 0;
1269 gdb_stop = false;
1270 guest_ncpus = 1;
1271 sockets = cores = threads = 1;
1272 maxcpus = 0;
1273 memsize = 256 * MB;
1274 mptgen = 1;
1275 rtc_localtime = 1;
1276 memflags = 0;
1277
1278 #ifdef __FreeBSD__
1279 optstr = "abehuwxACHIPSWYp:g:G:c:s:m:l:B:U:";
1280 #else
1281 optstr = "abdehuwxACHIPSWYg:G:c:s:m:l:B:U:";
1282 #endif
1283 while ((c = getopt(argc, argv, optstr)) != -1) {
1284 switch (c) {
1285 case 'a':
1286 x2apic_mode = 0;
1287 break;
1288 case 'A':
1289 acpi = 1;
1290 break;
1291 case 'b':
1292 bvmcons = 1;
1293 break;
1294 case 'B':
1295 if (smbios_parse(optarg) != 0) {
1296 errx(EX_USAGE, "invalid SMBIOS "
1297 "configuration '%s'", optarg);
1298 }
1299 break;
1300 #ifndef __FreeBSD__
1301 case 'd':
1302 suspend = true;
1303 break;
1304 #else
1305 case 'p':
1306 if (pincpu_parse(optarg) != 0) {
1307 errx(EX_USAGE, "invalid vcpu pinning "
1308 "configuration '%s'", optarg);
1309 }
1310 break;
1311 #endif
1312 case 'c':
1313 if (topology_parse(optarg) != 0) {
1314 errx(EX_USAGE, "invalid cpu topology "
1315 "'%s'", optarg);
1316 }
1317 break;
1318 case 'C':
1319 memflags |= VM_MEM_F_INCORE;
1320 break;
1321 case 'g':
1322 dbg_port = atoi(optarg);
1323 break;
1324 case 'G':
1325 if (optarg[0] == 'w') {
1326 gdb_stop = true;
1327 optarg++;
1328 }
1329 gdb_port = atoi(optarg);
1330 break;
1331 case 'l':
1332 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1333 lpc_print_supported_devices();
1334 exit(0);
1335 } else if (lpc_device_parse(optarg) != 0) {
1336 errx(EX_USAGE, "invalid lpc device "
1337 "configuration '%s'", optarg);
1338 }
1339 break;
1340 case 's':
1341 if (strncmp(optarg, "help", strlen(optarg)) == 0) {
1342 pci_print_supported_devices();
1343 exit(0);
1344 } else if (pci_parse_slot(optarg) != 0)
1345 exit(4);
1346 else
1347 break;
1348 case 'S':
1349 memflags |= VM_MEM_F_WIRED;
1350 break;
1351 case 'm':
1352 error = vm_parse_memsize(optarg, &memsize);
1353 if (error)
1354 errx(EX_USAGE, "invalid memsize '%s'", optarg);
1355 break;
1356 case 'H':
1357 guest_vmexit_on_hlt = 1;
1358 break;
1359 case 'I':
1360 /*
1361 * The "-I" option was used to add an ioapic to the
1362 * virtual machine.
1363 *
1364 * An ioapic is now provided unconditionally for each
1365 * virtual machine and this option is now deprecated.
1366 */
1367 break;
1368 case 'P':
1369 guest_vmexit_on_pause = 1;
1370 break;
1371 case 'e':
1372 strictio = 1;
1373 break;
1374 case 'u':
1375 rtc_localtime = 0;
1376 break;
1377 case 'U':
1378 guest_uuid_str = optarg;
1379 break;
1380 case 'w':
1381 strictmsr = 0;
1382 break;
1383 case 'W':
1384 virtio_msix = 0;
1385 break;
1386 case 'x':
1387 x2apic_mode = 1;
1388 break;
1389 case 'Y':
1390 mptgen = 0;
1391 break;
1392 case 'h':
1393 usage(0);
1394 default:
1395 usage(1);
1396 }
1397 }
1398 argc -= optind;
1399 argv += optind;
1400
1401 if (argc != 1)
1402 usage(1);
1403
1404 vmname = argv[0];
1405 ctx = do_open(vmname);
1406
1407 max_vcpus = num_vcpus_allowed(ctx);
1408 if (guest_ncpus > max_vcpus) {
1409 fprintf(stderr, "%d vCPUs requested but only %d available\n",
1410 guest_ncpus, max_vcpus);
1411 exit(4);
1412 }
1413
1414 fbsdrun_set_capabilities(ctx, BSP);
1415
1416 vm_set_memflags(ctx, memflags);
1417 #ifdef __FreeBSD__
1418 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1419 #else
1420 do {
1421 errno = 0;
1422 err = vm_setup_memory(ctx, memsize, VM_MMAP_ALL);
1423 error = errno;
1424 if (err != 0 && error == ENOMEM) {
1425 (void) fprintf(stderr, "Unable to allocate memory "
1426 "(%llu), retrying in 1 second\n", memsize);
1427 sleep(1);
1428 }
1429 } while (error == ENOMEM);
1430 #endif
1431 if (err) {
1432 fprintf(stderr, "Unable to setup memory (%d)\n", errno);
1433 exit(4);
1434 }
1435
1436 error = init_msr();
1437 if (error) {
1438 fprintf(stderr, "init_msr error %d", error);
1439 exit(4);
1440 }
1441
1442 init_mem();
1443 init_inout();
1444 #ifdef __FreeBSD__
1445 kernemu_dev_init();
1446 #endif
1447 init_bootrom(ctx);
1448 atkbdc_init(ctx);
1449 pci_irq_init(ctx);
1450 ioapic_init(ctx);
1451
1452 rtc_init(ctx, rtc_localtime);
1453 sci_init(ctx);
1454 #ifndef __FreeBSD__
1455 pmtmr_init(ctx);
1456 #endif
1457
1458 /*
1459 * Exit if a device emulation finds an error in its initilization
1460 */
1461 if (init_pci(ctx) != 0) {
1462 perror("device emulation initialization error");
1463 exit(4);
1464 }
1465
1466 /*
1467 * Initialize after PCI, to allow a bootrom file to reserve the high
1468 * region.
1469 */
1470 if (acpi)
1471 vmgenc_init(ctx);
1472
1473 if (dbg_port != 0)
1474 init_dbgport(dbg_port);
1475
1476 #ifdef __FreeBSD__
1477 if (gdb_port != 0)
1478 init_gdb(ctx, gdb_port, gdb_stop);
1479 #else
1480 if (gdb_port < 0) {
1481 /*
1482 * Set up the internal gdb state needed for basic debugging, but
1483 * skip the step of listening on a port for the GDB server.
1484 */
1485 init_mdb(ctx, gdb_stop);
1486 } else if (gdb_port != 0) {
1487 init_gdb(ctx, gdb_port, gdb_stop);
1488 }
1489 #endif
1490
1491 if (bvmcons)
1492 init_bvmcons();
1493
1494 vga_init(1);
1495
1496 if (lpc_bootrom()) {
1497 #ifdef __FreeBSD__
1498 if (vm_set_capability(ctx, BSP, VM_CAP_UNRESTRICTED_GUEST, 1)) {
1499 fprintf(stderr, "ROM boot failed: unrestricted guest "
1500 "capability not available\n");
1501 exit(4);
1502 }
1503 #else
1504 /* Unrestricted Guest is always enabled on illumos */
1505 #endif
1506 error = vcpu_reset(ctx, BSP);
1507 assert(error == 0);
1508 }
1509
1510 error = vm_get_register(ctx, BSP, VM_REG_GUEST_RIP, &rip);
1511 assert(error == 0);
1512
1513 /*
1514 * build the guest tables, MP etc.
1515 */
1516 if (mptgen) {
1517 error = mptable_build(ctx, guest_ncpus);
1518 if (error) {
1519 perror("error to build the guest tables");
1520 exit(4);
1521 }
1522 }
1523
1524 error = smbios_build(ctx);
1525 assert(error == 0);
1526
1527 if (acpi) {
1528 error = acpi_build(ctx, guest_ncpus);
1529 assert(error == 0);
1530 }
1531
1532 if (lpc_bootrom())
1533 fwctl_init();
1534
1535 /*
1536 * Change the proc title to include the VM name.
1537 */
1538 setproctitle("%s", vmname);
1539
1540 #ifndef WITHOUT_CAPSICUM
1541 caph_cache_catpages();
1542
1543 if (caph_limit_stdout() == -1 || caph_limit_stderr() == -1)
1544 errx(EX_OSERR, "Unable to apply rights for sandbox");
1545
1546 if (caph_enter() == -1)
1547 errx(EX_OSERR, "cap_enter() failed");
1548 #endif
1549
1550 /*
1551 * Add CPU 0
1552 */
1553 #ifdef __FreeBSD__
1554 fbsdrun_addcpu(ctx, BSP, BSP, rip);
1555 #else
1556 fbsdrun_addcpu(ctx, BSP, BSP, rip, suspend);
1557
1558 mark_provisioned();
1559 #endif
1560
1561 /*
1562 * Head off to the main event dispatch loop
1563 */
1564 mevent_dispatch();
1565
1566 exit(4);
1567 }