7 #define _LARGEFILE64_SOURCE
17 #include <sys/param.h>
18 #include <sys/types.h>
21 #include <sys/eventfd.h>
26 #include <sys/socket.h>
27 #include <sys/ioctl.h>
30 #include <netinet/in.h>
33 #include <linux/if_tun.h>
45 #include <linux/virtio_config.h>
48 #include <linux/virtio_console.h>
50 #include <linux/virtio_ring.h>
51 #include <asm/bootparam.h>
52 #include "../../include/linux/lguest_launcher.h"
62 typedef unsigned long long u64;
68 #define BRIDGE_PFX "bridge:"
70 #define SIOCBRADDIF 0x89a2
73 #define DEVICE_PAGES 256
75 #define VIRTQUEUE_NUM 256
82 #define verbose(args...) \
83 do { if (verbose) printf(args); } while(0)
87 static void *guest_base;
89 static unsigned long guest_limit, guest_max;
94 static unsigned int __thread
cpu_id;
169 static char **main_args;
172 static struct termios orig_term;
179 #define wmb() __asm__ __volatile__("" : : : "memory")
180 #define mb() __asm__ __volatile__("" : : : "memory")
192 #define convert(iov, type) \
193 ((type *)_convert((iov), sizeof(type), __alignof__(type), #type))
195 static void *_convert(
struct iovec *iov,
size_t size,
size_t align,
199 errx(1,
"Bad iovec size %zu for %s", iov->
iov_len, name);
200 if ((
unsigned long)iov->
iov_base % align != 0)
201 errx(1,
"Bad alignment %p for %s", iov->
iov_base, name);
206 #define lg_last_avail(vq) ((vq)->last_avail_idx)
212 #define cpu_to_le16(v16) (v16)
213 #define cpu_to_le32(v32) (v32)
214 #define cpu_to_le64(v64) (v64)
215 #define le16_to_cpu(v16) (v16)
216 #define le32_to_cpu(v32) (v32)
217 #define le64_to_cpu(v64) (v64)
220 static bool iov_empty(
const struct iovec iov[],
unsigned int num_iov)
224 for (i = 0; i < num_iov; i++)
231 static void iov_consume(
struct iovec iov[],
unsigned num_iov,
unsigned len)
235 for (i = 0; i < num_iov; i++) {
249 return (
u8 *)(dev->
desc + 1)
268 static void *from_guest_phys(
unsigned long addr)
270 return guest_base +
addr;
273 static unsigned long to_guest_phys(
const void *
addr)
275 return (addr - guest_base);
284 static int open_or_die(
const char *
name,
int flags)
286 int fd =
open(name, flags);
288 err(1,
"Failed to open %s", name);
293 static void *map_zeroed_pages(
unsigned int num)
295 int fd = open_or_die(
"/dev/zero",
O_RDONLY);
303 addr = mmap(
NULL, getpagesize() * (num+2),
306 if (addr == MAP_FAILED)
307 err(1,
"Mmapping %u pages of /dev/zero", num);
309 if (mprotect(addr + getpagesize(), getpagesize() * num,
311 err(1,
"mprotect rw %u pages failed", num);
320 return addr + getpagesize();
324 static void *get_pages(
unsigned int num)
326 void *addr = from_guest_phys(guest_limit);
328 guest_limit += num * getpagesize();
329 if (guest_limit > guest_max)
330 errx(1,
"Not enough memory for devices");
339 static void map_at(
int fd,
void *addr,
unsigned long offset,
unsigned long len)
357 r = pread(fd, addr, len, offset);
359 err(1,
"Reading offset %lu len %lu gave %zi", offset, len, r);
373 static unsigned long map_elf(
int elf_fd,
const Elf32_Ehdr *ehdr)
386 errx(1,
"Malformed elf header");
396 err(1,
"Seeking to program headers");
397 if (
read(elf_fd, phdr,
sizeof(phdr)) !=
sizeof(phdr))
398 err(1,
"Reading program headers");
404 for (i = 0; i < ehdr->
e_phnum; i++) {
409 verbose(
"Section %i: size %i addr %p\n",
410 i, phdr[i].p_memsz, (
void *)phdr[i].p_paddr);
413 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
414 phdr[i].p_offset, phdr[i].p_filesz);
430 static unsigned long load_bzimage(
int fd)
435 void *
p = from_guest_phys(0x100000);
442 read(fd, &boot,
sizeof(boot));
445 if (
memcmp(&boot.hdr.header,
"HdrS", 4) != 0)
446 errx(1,
"This doesn't look like a bzImage to me");
449 lseek(fd, (boot.hdr.setup_sects+1) * 512,
SEEK_SET);
452 while ((r =
read(fd, p, 65536)) > 0)
456 return boot.hdr.code32_start;
464 static unsigned long load_kernel(
int fd)
469 if (
read(fd, &hdr,
sizeof(hdr)) !=
sizeof(hdr))
470 err(1,
"Reading kernel");
474 return map_elf(fd, &hdr);
477 return load_bzimage(fd);
487 static inline unsigned long page_align(
unsigned long addr)
490 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
502 static unsigned long load_initrd(
const char *name,
unsigned long mem)
510 if (fstat(ifd, &
st) < 0)
511 err(1,
"fstat() on initrd '%s'", name);
517 len = page_align(
st.st_size);
518 map_at(ifd, from_guest_phys(mem - len), 0,
st.st_size);
524 verbose(
"mapped initrd %s size=%lu @ %p\n", name, len, (
void*)mem-len);
535 static void concat(
char *
dst,
char *args[])
537 unsigned int i, len = 0;
539 for (i = 0; args[
i]; i++) {
557 static void tell_kernel(
unsigned long start)
560 (
unsigned long)guest_base,
561 guest_limit / getpagesize(), start };
562 verbose(
"Guest: %p - %p (%#lx)\n",
563 guest_base, guest_base + guest_limit, guest_limit);
564 lguest_fd = open_or_die(
"/dev/lguest",
O_RDWR);
565 if (
write(lguest_fd, args,
sizeof(args)) < 0)
566 err(1,
"Writing to /dev/lguest");
578 static void *_check_pointer(
unsigned long addr,
unsigned int size,
585 if ((addr + size) > guest_limit || (addr + size) < addr)
586 errx(1,
"%s:%i: Invalid address %#lx", __FILE__, line, addr);
591 return from_guest_phys(addr);
594 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
602 unsigned int i,
unsigned int max)
616 errx(1,
"Desc next is %u", next);
625 static void trigger_irq(
struct virtqueue *vq)
640 if (
write(lguest_fd, buf,
sizeof(buf)) != 0)
641 err(1,
"Triggering irq %i", vq->
config.irq);
652 static unsigned wait_for_vq_desc(
struct virtqueue *vq,
654 unsigned int *out_num,
unsigned int *in_num)
661 while (last_avail == vq->
vring.avail->idx) {
678 if (last_avail != vq->
vring.avail->idx) {
684 if (
read(vq->
eventfd, &event,
sizeof(event)) !=
sizeof(event))
685 errx(1,
"Event read failed?");
692 if ((
u16)(vq->
vring.avail->idx - last_avail) > vq->
vring.num)
693 errx(1,
"Guest moved used index from %u to %u",
694 last_avail, vq->
vring.avail->idx);
700 head = vq->
vring.avail->ring[last_avail % vq->
vring.num];
704 if (head >= vq->
vring.num)
705 errx(1,
"Guest says index %u is available", head);
708 *out_num = *in_num = 0;
711 desc = vq->
vring.desc;
720 errx(1,
"Invalid size for indirect buffer table");
741 errx(1,
"Descriptor has out after in");
746 if (*out_num + *in_num > max)
747 errx(1,
"Looped descriptor");
748 }
while ((i =
next_desc(desc, i, max)) != max);
758 static void add_used(
struct virtqueue *vq,
unsigned int head,
int len)
771 vq->
vring.used->idx++;
776 static void add_used_and_trigger(
struct virtqueue *vq,
unsigned head,
int len)
778 add_used(vq, head, len);
795 static void console_input(
struct virtqueue *vq)
798 unsigned int head, in_num, out_num;
803 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
805 errx(1,
"Output buffers in console in queue?");
808 len = readv(STDIN_FILENO, iov, in_num);
811 warnx(
"Failed to get console input, ignoring console.");
821 add_used_and_trigger(vq, head, len);
831 if (len != 1 || ((
char *)iov[0].
iov_base)[0] != 3) {
837 if (abort->
count == 1)
839 else if (abort->
count == 3) {
843 if (now.tv_sec <= abort->
start.tv_sec+1)
850 static void console_output(
struct virtqueue *vq)
856 head = wait_for_vq_desc(vq, iov, &out, &in);
858 errx(1,
"Input buffers in console output queue?");
861 while (!iov_empty(iov, out)) {
862 int len = writev(STDOUT_FILENO, iov, out);
864 warn(
"Write to stdout gave %i (%d)", len, errno);
867 iov_consume(iov, out, len);
874 add_used(vq, head, 0);
887 static void net_output(
struct virtqueue *vq)
891 struct iovec iov[vq->vring.num];
894 head = wait_for_vq_desc(vq, iov, &out, &in);
896 errx(1,
"Input buffers in net output queue?");
901 if (writev(net_info->
tunfd, iov, out) < 0)
902 warnx(
"Write to tun failed (%d)?",
errno);
908 add_used(vq, head, 0);
917 static bool will_block(
int fd)
931 static void net_input(
struct virtqueue *vq)
942 head = wait_for_vq_desc(vq, iov, &out, &in);
944 errx(1,
"Output buffers in net input queue?");
957 len = readv(net_info->
tunfd, iov, in);
959 warn(
"Failed to read from tun (%d).", errno);
965 add_used(vq, head, len);
970 static int do_thread(
void *_vq)
983 static void kill_launcher(
int signal)
988 static void reset_device(
struct device *dev)
1001 for (vq = dev->
vq; vq; vq = vq->
next) {
1014 signal(
SIGCHLD, (
void *)kill_launcher);
1020 static void create_thread(
struct virtqueue *vq)
1028 vq->
config.pfn*getpagesize(), 0 };
1033 err(1,
"Creating eventfd");
1040 if (
write(lguest_fd, &args,
sizeof(args)) != 0)
1041 err(1,
"Attaching eventfd");
1049 err(1,
"Creating clone");
1055 static void start_device(
struct device *dev)
1062 verbose(
" %02x", get_feature_bits(dev)[i]);
1065 verbose(
" %02x", get_feature_bits(dev)
1068 for (vq = dev->
vq; vq; vq = vq->
next) {
1075 static void cleanup_devices(
void)
1084 tcsetattr(STDIN_FILENO,
TCSANOW, &orig_term);
1088 static void update_device_status(
struct device *dev)
1091 if (dev->
desc->status == 0)
1094 warnx(
"Device %s configuration FAILED", dev->
name);
1099 err(1,
"Device %s features finalized twice", dev->
name);
1108 static void handle_output(
unsigned long addr)
1120 if (from_guest_phys(addr) == i->
desc) {
1121 update_device_status(i);
1126 for (vq = i->
vq; vq; vq = vq->
next) {
1127 if (addr != vq->
config.pfn*getpagesize())
1129 errx(1,
"Notification on %s before setup!", i->
name);
1138 if (addr >= guest_limit)
1139 errx(1,
"Bad NOTIFY %#lx", addr);
1141 write(STDOUT_FILENO, from_guest_phys(addr),
1142 strnlen(from_guest_phys(addr), guest_limit - addr));
1159 static u8 *device_config(
const struct device *dev)
1161 return (
void *)(dev->
desc + 1)
1178 p = device_config(
devices.lastdev)
1179 +
devices.lastdev->desc->config_len;
1184 if (p +
sizeof(d) > (
void *)
devices.descpage + getpagesize())
1185 errx(1,
"Too many devices");
1188 return memcpy(p, &d,
sizeof(d));
1195 static void add_virtqueue(
struct device *dev,
unsigned int num_descs,
1205 p = get_pages(pages);
1220 vq->
config.num = num_descs;
1222 vq->
config.pfn = to_guest_phys(p) / getpagesize();
1233 assert(dev->
desc->config_len == 0 && dev->
desc->feature_len == 0);
1236 dev->
desc->num_vq++;
1238 verbose(
"Virtqueue page %#lx\n", to_guest_phys(p));
1244 for (i = &dev->
vq; *i; i = &(*i)->
next);
1252 static void add_feature(
struct device *dev,
unsigned bit)
1270 static void set_config(
struct device *dev,
unsigned len,
const void *conf)
1273 if (device_config(dev) + len >
devices.descpage + getpagesize())
1274 errx(1,
"Too many devices");
1277 memcpy(device_config(dev), conf, len);
1278 dev->
desc->config_len = len;
1291 static struct device *new_device(
const char *name,
u16 type)
1296 dev->
desc = new_dev_desc(type);
1323 static void setup_console(
void)
1328 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1329 struct termios term = orig_term;
1335 tcsetattr(STDIN_FILENO,
TCSANOW, &term);
1379 if (
sscanf(ipaddr,
"%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
1380 errx(1,
"Failed to parse IP address '%s'", ipaddr);
1381 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
1384 static void str2mac(
const char *
macaddr,
unsigned char mac[6])
1387 if (
sscanf(macaddr,
"%02x:%02x:%02x:%02x:%02x:%02x",
1388 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
1389 errx(1,
"Failed to parse mac address '%s'", macaddr);
1405 static void add_to_bridge(
int fd,
const char *if_name,
const char *br_name)
1411 errx(1,
"must specify bridge name");
1413 ifidx = if_nametoindex(if_name);
1415 errx(1,
"interface %s does not exist!", if_name);
1419 ifr.ifr_ifindex = ifidx;
1421 err(1,
"can't add %s to bridge %s", if_name, br_name);
1429 static void configure_device(
int fd,
const char *tapif,
u32 ipaddr)
1434 memset(&ifr, 0,
sizeof(ifr));
1435 strcpy(ifr.ifr_name, tapif);
1439 sin.sin_addr.s_addr =
htonl(ipaddr);
1440 memcpy(&ifr.ifr_addr, &sin,
sizeof(sin));
1442 err(1,
"Setting %s interface address", tapif);
1445 err(1,
"Bringing interface %s up", tapif);
1448 static int get_tun_device(
char tapif[
IFNAMSIZ])
1454 memset(&ifr, 0,
sizeof(ifr));
1462 netfd = open_or_die(
"/dev/net/tun",
O_RDWR);
1464 strcpy(ifr.ifr_name,
"tap%d");
1466 err(1,
"configuring /dev/net/tun");
1470 err(1,
"Could not set features for tun device");
1478 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
1488 static void setup_tun_net(
char *
arg)
1491 struct net_info *net_info =
malloc(
sizeof(*net_info));
1494 bool bridging =
false;
1498 net_info->
tunfd = get_tun_device(tapif);
1502 dev->
priv = net_info;
1514 err(1,
"opening IP socket");
1525 str2mac(p+1, conf.mac);
1532 add_to_bridge(ipfd, tapif, arg);
1537 configure_device(ipfd, tapif, ip);
1550 set_config(dev,
sizeof(conf), &conf);
1558 verbose(
"device %u: tun %s attached to bridge: %s\n",
1559 devices.device_num, tapif, arg);
1561 verbose(
"device %u: tun %s: %s\n",
1562 devices.device_num, tapif, arg);
1590 static void blk_request(
struct virtqueue *vq)
1593 unsigned int head, out_num, in_num, wlen;
1597 struct iovec iov[vq->vring.num];
1604 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
1611 if (out_num == 0 || in_num == 0)
1612 errx(1,
"Bad virtblk cmd %u out=%u in=%u",
1613 head, out_num, in_num);
1616 in =
convert(&iov[out_num+in_num-1],
u8);
1628 fprintf(stderr,
"Scsi commands unsupported\n");
1639 err(1,
"Bad seek to sector %llu", out->
sector);
1641 ret = writev(vblk->
fd, iov+1, out_num-1);
1649 if (ret > 0 && off + ret > vblk->
len) {
1651 ftruncate64(vblk->
fd, vblk->
len);
1653 errx(1,
"Write past end %llu+%u", off, ret);
1660 ret = fdatasync(vblk->
fd);
1661 verbose(
"FLUSH fdatasync: %i\n", ret);
1672 err(1,
"Bad seek to sector %llu", out->
sector);
1674 ret = readv(vblk->
fd, iov+1, in_num-1);
1677 wlen =
sizeof(*in) +
ret;
1686 add_used(vq, head, wlen);
1690 static void setup_block_file(
const char *
filename)
1703 vblk = dev->priv =
malloc(
sizeof(*vblk));
1725 verbose(
"device %u: virtblock %llu sectors\n",
1741 static void rng_input(
struct virtqueue *vq)
1744 unsigned int head, in_num, out_num,
totlen = 0;
1746 struct iovec iov[vq->vring.num];
1749 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
1751 errx(1,
"Output buffers in rng?");
1757 while (!iov_empty(iov, in_num)) {
1758 len = readv(rng_info->
rfd, iov, in_num);
1760 err(1,
"Read from /dev/random gave %i", len);
1761 iov_consume(iov, in_num, len);
1766 add_used(vq, head, totlen);
1772 static void setup_rng(
void)
1778 rng_info->
rfd = open_or_die(
"/dev/random",
O_RDONLY);
1782 dev->
priv = rng_info;
1800 for (i = 3; i < FD_SETSIZE; i++)
1806 execv(main_args[0], main_args);
1807 err(1,
"Could not exec %s", main_args[0]);
1817 unsigned long notify_addr;
1821 readval = pread(lguest_fd, ¬ify_addr,
1822 sizeof(notify_addr),
cpu_id);
1825 if (readval ==
sizeof(notify_addr)) {
1826 verbose(
"Notify on address %#lx\n", notify_addr);
1827 handle_output(notify_addr);
1829 }
else if (errno ==
ENOENT) {
1830 char reason[1024] = { 0 };
1831 pread(lguest_fd, reason,
sizeof(reason)-1,
cpu_id);
1832 errx(1,
"%s", reason);
1838 err(1,
"Running guest failed");
1851 {
"verbose", 0,
NULL,
'v' },
1852 {
"tunnet", 1,
NULL,
't' },
1853 {
"block", 1,
NULL,
'b' },
1854 {
"rng", 0,
NULL,
'r' },
1855 {
"initrd", 1,
NULL,
'i' },
1856 {
"username", 1,
NULL,
'u' },
1857 {
"chroot", 1,
NULL,
'c' },
1860 static void usage(
void)
1862 errx(1,
"Usage: lguest [--verbose] "
1863 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
1864 "|--block=<filename>|--initrd=<filename>]...\n"
1865 "<mem-in-mb> vmlinux [args...]");
1872 unsigned long mem = 0,
start, initrd_size = 0;
1878 const char *initrd_name =
NULL;
1881 struct passwd *user_details =
NULL;
1884 char *chroot_path =
NULL;
1906 for (i = 1; i <
argc; i++) {
1907 if (argv[i][0] !=
'-') {
1908 mem = atoi(argv[i]) * 1024 * 1024;
1915 guest_base = map_zeroed_pages(mem / getpagesize()
1919 devices.descpage = get_pages(1);
1925 while ((c = getopt_long(argc, argv,
"v", opts,
NULL)) !=
EOF) {
1931 setup_tun_net(optarg);
1934 setup_block_file(optarg);
1940 initrd_name = optarg;
1943 user_details = getpwnam(optarg);
1945 err(1,
"getpwnam failed, incorrect username?");
1948 chroot_path = optarg;
1951 warnx(
"Unknown argument %s", argv[optind]);
1959 if (optind + 2 > argc)
1962 verbose(
"Guest base is at %p\n", guest_base);
1968 start = load_kernel(open_or_die(argv[optind+1],
O_RDONLY));
1971 boot = from_guest_phys(0);
1975 initrd_size = load_initrd(initrd_name, mem);
1980 boot->
hdr.ramdisk_image = mem - initrd_size;
1981 boot->
hdr.ramdisk_size = initrd_size;
1983 boot->
hdr.type_of_loader = 0xFF;
1996 boot->
hdr.cmd_line_ptr = to_guest_phys(boot + 1);
1998 concat((
char *)(boot + 1), argv+optind+2);
2001 boot->
hdr.kernel_alignment = 0x1000000;
2004 boot->
hdr.version = 0x207;
2007 boot->
hdr.hardware_subarch = 1;
2016 signal(
SIGCHLD, kill_launcher);
2019 atexit(cleanup_devices);
2023 if (chroot(chroot_path) != 0)
2024 err(1,
"chroot(\"%s\") failed", chroot_path);
2026 if (chdir(
"/") != 0)
2027 err(1,
"chdir(\"/\") failed");
2037 u = user_details->pw_uid;
2038 g = user_details->pw_gid;
2040 if (initgroups(user_details->pw_name, g) != 0)
2041 err(1,
"initgroups failed");
2043 if (setresgid(g, g, g) != 0)
2044 err(1,
"setresgid failed");
2046 if (setresuid(u, u, u) != 0)
2047 err(1,
"setresuid failed");
2049 verbose(
"Dropping privileges completed\n");