2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2011 NetApp, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
30 * Copyright (c) 2011 Google, Inc.
31 * All rights reserved.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
42 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 #include <sys/cdefs.h>
56 #include <sys/ioctl.h>
59 #include <sys/queue.h>
61 #include <machine/specialreg.h>
62 #include <machine/vmm.h>
81 #include <capsicum_helpers.h>
86 #define MB (1024 * 1024UL)
87 #define GB (1024 * 1024 * 1024UL)
93 * Reason for our loader reload and reentry, though these aren't really used
97 /* 0 cannot be allocated; setjmp(3) return. */
98 JMP_SWAPLOADER = 0x01,
102 static struct termios term, oldterm;
103 static int disk_fd[NDISKS];
105 static int consin_fd, consout_fd;
106 static int hostbase_fd = -1;
108 static void *loader_hdl;
110 static int explicit_loader_fd = -1;
113 static char *vmname, *progname;
114 static struct vmctx *ctx;
115 static struct vcpu *vcpu;
117 static uint64_t gdtbase, cr3, rsp;
119 static void cb_exit(void *arg, int v);
122 * Console i/o callbacks
126 cb_putc(void *arg __unused, int ch)
130 (void) write(consout_fd, &c, 1);
134 cb_getc(void *arg __unused)
138 if (read(consin_fd, &c, 1) == 1)
144 cb_poll(void *arg __unused)
148 if (ioctl(consin_fd, FIONREAD, &n) >= 0)
154 * Host filesystem i/o callbacks
168 cb_open(void *arg __unused, const char *filename, void **hp)
176 flags = O_RDONLY | O_RESOLVE_BENEATH;
177 if (hostbase_fd == -1)
180 /* Absolute paths are relative to our hostbase, chop off leading /. */
181 if (filename[0] == '/')
184 /* Lookup of /, use . instead. */
185 if (filename[0] == '\0')
188 if (fstatat(hostbase_fd, filename, &sb, AT_RESOLVE_BENEATH) < 0)
191 if (!S_ISDIR(sb.st_mode) && !S_ISREG(sb.st_mode))
194 if (S_ISDIR(sb.st_mode))
195 flags |= O_DIRECTORY;
197 /* May be opening the root dir */
198 fd = openat(hostbase_fd, filename, flags);
202 cf = malloc(sizeof(struct cb_file));
209 cf->cf_size = cf->cf_stat.st_size;
211 if (S_ISDIR(cf->cf_stat.st_mode)) {
213 cf->cf_u.dir = fdopendir(fd);
214 if (cf->cf_u.dir == NULL) {
220 assert(S_ISREG(cf->cf_stat.st_mode));
229 cb_close(void *arg __unused, void *h)
231 struct cb_file *cf = h;
234 closedir(cf->cf_u.dir);
243 cb_isdir(void *arg __unused, void *h)
245 struct cb_file *cf = h;
247 return (cf->cf_isdir);
251 cb_read(void *arg __unused, void *h, void *buf, size_t size, size_t *resid)
253 struct cb_file *cf = h;
258 sz = read(cf->cf_u.fd, buf, size);
266 cb_readdir(void *arg __unused, void *h, uint32_t *fileno_return,
267 uint8_t *type_return, size_t *namelen_return, char *name)
269 struct cb_file *cf = h;
275 dp = readdir(cf->cf_u.dir);
280 * Note: d_namlen is in the range 0..255 and therefore less
281 * than PATH_MAX so we don't need to test before copying.
283 *fileno_return = dp->d_fileno;
284 *type_return = dp->d_type;
285 *namelen_return = dp->d_namlen;
286 memcpy(name, dp->d_name, dp->d_namlen);
287 name[dp->d_namlen] = 0;
293 cb_seek(void *arg __unused, void *h, uint64_t offset, int whence)
295 struct cb_file *cf = h;
299 if (lseek(cf->cf_u.fd, offset, whence) < 0)
305 cb_stat(void *arg __unused, void *h, struct stat *sbp)
307 struct cb_file *cf = h;
309 memset(sbp, 0, sizeof(struct stat));
310 sbp->st_mode = cf->cf_stat.st_mode;
311 sbp->st_uid = cf->cf_stat.st_uid;
312 sbp->st_gid = cf->cf_stat.st_gid;
313 sbp->st_size = cf->cf_stat.st_size;
314 sbp->st_mtime = cf->cf_stat.st_mtime;
315 sbp->st_dev = cf->cf_stat.st_dev;
316 sbp->st_ino = cf->cf_stat.st_ino;
322 * Disk image i/o callbacks
326 cb_diskread(void *arg __unused, int unit, uint64_t from, void *to, size_t size,
331 if (unit < 0 || unit >= ndisks)
333 n = pread(disk_fd[unit], to, size, from);
341 cb_diskwrite(void *arg __unused, int unit, uint64_t offset, void *src,
342 size_t size, size_t *resid)
346 if (unit < 0 || unit >= ndisks)
348 n = pwrite(disk_fd[unit], src, size, offset);
356 cb_diskioctl(void *arg __unused, int unit, u_long cmd, void *data)
360 if (unit < 0 || unit >= ndisks)
364 case DIOCGSECTORSIZE:
365 *(u_int *)data = 512;
368 if (fstat(disk_fd[unit], &sb) != 0)
370 if (S_ISCHR(sb.st_mode) &&
371 ioctl(disk_fd[unit], DIOCGMEDIASIZE, &sb.st_size) != 0)
373 *(off_t *)data = sb.st_size;
383 * Guest virtual machine i/o callbacks
386 cb_copyin(void *arg __unused, const void *from, uint64_t to, size_t size)
392 ptr = vm_map_gpa(ctx, to, size);
396 memcpy(ptr, from, size);
401 cb_copyout(void *arg __unused, uint64_t from, void *to, size_t size)
407 ptr = vm_map_gpa(ctx, from, size);
411 memcpy(to, ptr, size);
416 cb_setreg(void *arg __unused, int r, uint64_t v)
419 enum vm_reg_name vmreg;
425 vmreg = VM_REG_GUEST_RSP;
432 if (vmreg == VM_REG_LAST) {
433 printf("test_setreg(%d): not implemented\n", r);
434 cb_exit(NULL, USERBOOT_EXIT_QUIT);
437 error = vm_set_register(vcpu, vmreg, v);
439 perror("vm_set_register");
440 cb_exit(NULL, USERBOOT_EXIT_QUIT);
445 cb_setmsr(void *arg __unused, int r, uint64_t v)
448 enum vm_reg_name vmreg;
454 vmreg = VM_REG_GUEST_EFER;
460 if (vmreg == VM_REG_LAST) {
461 printf("test_setmsr(%d): not implemented\n", r);
462 cb_exit(NULL, USERBOOT_EXIT_QUIT);
465 error = vm_set_register(vcpu, vmreg, v);
467 perror("vm_set_msr");
468 cb_exit(NULL, USERBOOT_EXIT_QUIT);
473 cb_setcr(void *arg __unused, int r, uint64_t v)
476 enum vm_reg_name vmreg;
482 vmreg = VM_REG_GUEST_CR0;
485 vmreg = VM_REG_GUEST_CR3;
489 vmreg = VM_REG_GUEST_CR4;
495 if (vmreg == VM_REG_LAST) {
496 printf("test_setcr(%d): not implemented\n", r);
497 cb_exit(NULL, USERBOOT_EXIT_QUIT);
500 error = vm_set_register(vcpu, vmreg, v);
503 cb_exit(NULL, USERBOOT_EXIT_QUIT);
508 cb_setgdt(void *arg __unused, uint64_t base, size_t size)
512 error = vm_set_desc(vcpu, VM_REG_GUEST_GDTR, base, size - 1, 0);
514 perror("vm_set_desc(gdt)");
515 cb_exit(NULL, USERBOOT_EXIT_QUIT);
522 cb_exec(void *arg __unused, uint64_t rip)
527 error = vm_setup_freebsd_registers_i386(vcpu, rip, gdtbase,
530 error = vm_setup_freebsd_registers(vcpu, rip, cr3, gdtbase,
533 perror("vm_setup_freebsd_registers");
534 cb_exit(NULL, USERBOOT_EXIT_QUIT);
545 cb_delay(void *arg __unused, int usec)
552 cb_exit(void *arg __unused, int v)
555 tcsetattr(consout_fd, TCSAFLUSH, &oldterm);
556 if (v == USERBOOT_EXIT_REBOOT)
557 longjmp(jb, JMP_REBOOT);
562 cb_getmem(void *arg __unused, uint64_t *ret_lowmem, uint64_t *ret_highmem)
565 *ret_lowmem = vm_get_lowmem_size(ctx);
566 *ret_highmem = vm_get_highmem_size(ctx);
570 char *str; /* name=value */
571 SLIST_ENTRY(env) next;
574 static SLIST_HEAD(envhead, env) envhead;
577 addenv(const char *str)
581 env = malloc(sizeof(struct env));
583 err(EX_OSERR, "malloc");
584 env->str = strdup(str);
585 if (env->str == NULL)
586 err(EX_OSERR, "strdup");
587 SLIST_INSERT_HEAD(&envhead, env, next);
591 cb_getenv(void *arg __unused, int num)
597 SLIST_FOREACH(env, &envhead, next) {
607 cb_vm_set_register(void *arg __unused, int vcpuid, int reg, uint64_t val)
610 assert(vcpuid == BSP);
611 return (vm_set_register(vcpu, reg, val));
615 cb_vm_set_desc(void *arg __unused, int vcpuid, int reg, uint64_t base,
616 u_int limit, u_int access)
619 assert(vcpuid == BSP);
620 return (vm_set_desc(vcpu, reg, base, limit, access));
624 cb_swap_interpreter(void *arg __unused, const char *interp_req)
628 * If the user specified a loader but we detected a mismatch, we should
629 * not try to pivot to a different loader on them.
632 if (explicit_loader_fd != -1) {
633 perror("requested loader interpreter does not match guest userboot");
636 if (interp_req == NULL || *interp_req == '\0') {
637 perror("guest failed to request an interpreter");
641 if (asprintf(&loader, "userboot_%s.so", interp_req) == -1)
642 err(EX_OSERR, "malloc");
643 longjmp(jb, JMP_SWAPLOADER);
646 static struct loader_callbacks cb = {
655 .readdir = cb_readdir,
659 .diskread = cb_diskread,
660 .diskwrite = cb_diskwrite,
661 .diskioctl = cb_diskioctl,
664 .copyout = cb_copyout,
677 /* Version 4 additions */
678 .vm_set_register = cb_vm_set_register,
679 .vm_set_desc = cb_vm_set_desc,
681 /* Version 5 additions */
682 .swap_interpreter = cb_swap_interpreter,
686 altcons_open(char *path)
693 * Allow stdio to be passed in so that the same string
694 * can be used for the bhyveload console and bhyve com-port
697 if (!strcmp(path, "stdio"))
700 err = stat(path, &sb);
702 if (!S_ISCHR(sb.st_mode))
705 fd = open(path, O_RDWR | O_NONBLOCK);
709 consin_fd = consout_fd = fd;
717 disk_open(char *path)
721 if (ndisks >= NDISKS)
724 fd = open(path, O_RDWR);
728 disk_fd[ndisks] = fd;
739 "usage: %s [-S][-c <console-device>] [-d <disk-path>] [-e <name=value>]\n"
740 " %*s [-h <host-path>] [-m memsize[K|k|M|m|G|g|T|t]] <vmname>\n",
742 (int)strlen(progname), "");
747 hostbase_open(const char *base)
751 if (hostbase_fd != -1)
753 hostbase_fd = open(base, O_DIRECTORY | O_PATH);
754 if (hostbase_fd == -1)
755 err(EX_OSERR, "open");
757 if (caph_rights_limit(hostbase_fd, cap_rights_init(&rights, CAP_FSTATAT,
758 CAP_LOOKUP, CAP_PREAD)) < 0)
759 err(EX_OSERR, "caph_rights_limit");
763 loader_open(int bootfd)
767 if (loader == NULL) {
768 loader = strdup("userboot.so");
770 err(EX_OSERR, "malloc");
773 assert(bootfd >= 0 || explicit_loader_fd >= 0);
774 if (explicit_loader_fd >= 0)
775 fd = explicit_loader_fd;
777 fd = openat(bootfd, loader, O_RDONLY | O_RESOLVE_BENEATH);
779 err(EX_OSERR, "openat");
781 loader_hdl = fdlopen(fd, RTLD_LOCAL);
783 errx(EX_OSERR, "dlopen: %s", dlerror());
784 if (fd != explicit_loader_fd)
789 main(int argc, char** argv)
791 void (*func)(struct loader_callbacks *, void *, int, int);
793 int bootfd, opt, error, memflags, need_reinit;
796 progname = basename(argv[0]);
801 consin_fd = STDIN_FILENO;
802 consout_fd = STDOUT_FILENO;
804 while ((opt = getopt(argc, argv, "CSc:d:e:h:l:m:")) != -1) {
807 error = altcons_open(optarg);
809 errx(EX_USAGE, "Could not open '%s'", optarg);
813 error = disk_open(optarg);
815 errx(EX_USAGE, "Could not open '%s'", optarg);
823 hostbase_open(optarg);
828 errx(EX_USAGE, "-l can only be given once");
829 loader = strdup(optarg);
831 err(EX_OSERR, "malloc");
832 explicit_loader_fd = open(loader, O_RDONLY);
833 if (explicit_loader_fd == -1)
834 err(EX_OSERR, "%s", loader);
838 error = vm_parse_memsize(optarg, &mem_size);
840 errx(EX_USAGE, "Invalid memsize '%s'", optarg);
843 memflags |= VM_MEM_F_INCORE;
846 memflags |= VM_MEM_F_WIRED;
862 error = vm_create(vmname);
869 ctx = vm_open(vmname);
874 * If we weren't given an explicit loader to use, we need to support the
875 * guest requesting a different one.
877 if (explicit_loader_fd == -1) {
880 bootfd = open("/boot", O_DIRECTORY | O_PATH);
885 * bootfd will be used to do a lookup of our loader and do an
886 * fdlopen(3) on the loader; thus, we need mmap(2) in addition
887 * to the more usual lookup rights.
889 if (caph_rights_limit(bootfd, cap_rights_init(&rights,
890 CAP_FSTATAT, CAP_LOOKUP, CAP_MMAP_RX, CAP_PREAD)) < 0)
891 err(1, "caph_rights_limit");
894 vcpu = vm_vcpu_open(ctx, BSP);
896 caph_cache_catpages();
897 if (caph_enter() < 0)
898 err(1, "caph_enter");
901 * setjmp in the case the guest wants to swap out interpreter,
902 * cb_swap_interpreter will swap out loader as appropriate and set
903 * need_reinit so that we end up in a clean state once again.
905 if (setjmp(jb) != 0) {
913 error = vm_reinit(ctx);
918 vm_set_memflags(ctx, memflags);
919 error = vm_setup_memory(ctx, mem_size, VM_MMAP_ALL);
921 err(1, "vm_setup_memory");
924 func = dlsym(loader_hdl, "loader_main");
926 errx(1, "dlsym: %s", dlerror());
928 tcgetattr(consout_fd, &term);
931 term.c_cflag |= CLOCAL;
933 tcsetattr(consout_fd, TCSAFLUSH, &term);
935 addenv("smbios.bios.vendor=BHYVE");
936 addenv("boot_serial=1");
938 func(&cb, NULL, USERBOOT_VERSION_5, ndisks);