2 * This is the Launcher code, a simple program which lays out the "physical"
3 * memory for the new Guest by mapping the kernel image and the virtual
4 * devices, then opens /dev/lguest to tell the kernel about the Guest and
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>
32 #include <linux/sockios.h>
33 #include <linux/if_tun.h>
45 #include <linux/pci_regs.h>
47 #ifndef VIRTIO_F_ANY_LAYOUT
48 #define VIRTIO_F_ANY_LAYOUT 27
52 * We can ignore the 43 include files we need for this program, but I do want
53 * to draw attention to the use of kernel-style types.
55 * As Linus said, "C is a Spartan language, and so should your naming be." I
56 * like these abbreviations, so we define them here. Note that u64 is always
57 * unsigned long long, which works on all Linux systems: this means that we can
58 * use %llu in printf for any u64.
60 typedef unsigned long long u64;
66 #define VIRTIO_PCI_NO_LEGACY
67 #define VIRTIO_BLK_NO_LEGACY
69 /* Use in-kernel ones, which defines VIRTIO_F_VERSION_1 */
70 #include "../../include/uapi/linux/virtio_config.h"
71 #include <linux/virtio_net.h>
72 #include "../../include/uapi/linux/virtio_blk.h"
73 #include <linux/virtio_console.h>
74 #include <linux/virtio_rng.h>
75 #include <linux/virtio_ring.h>
76 #include "../../include/uapi/linux/virtio_pci.h"
77 #include <asm/bootparam.h>
78 #include "../../include/linux/lguest_launcher.h"
80 #define BRIDGE_PFX "bridge:"
82 #define SIOCBRADDIF 0x89a2 /* add interface to bridge */
84 /* We can have up to 256 pages for devices. */
85 #define DEVICE_PAGES 256
86 /* This will occupy 3 pages: it must be a power of 2. */
87 #define VIRTQUEUE_NUM 256
90 * verbose is both a global flag and a macro. The C preprocessor allows
91 * this, and although I wouldn't recommend it, it works quite nicely here.
94 #define verbose(args...) \
95 do { if (verbose) printf(args); } while(0)
98 /* The pointer to the start of guest memory. */
99 static void *guest_base;
100 /* The maximum guest physical address allowed, and maximum possible. */
101 static unsigned long guest_limit, guest_max, guest_mmio;
102 /* The /dev/lguest file descriptor. */
103 static int lguest_fd;
105 /* a per-cpu variable indicating whose vcpu is currently running */
106 static unsigned int __thread cpu_id;
108 /* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
109 #define MAX_PCI_DEVICES 32
111 /* This is our list of devices. */
113 /* Counter to assign interrupt numbers. */
114 unsigned int next_irq;
116 /* Counter to print out convenient device numbers. */
117 unsigned int device_num;
119 /* The descriptor page for the devices. */
122 /* A single linked list of devices. */
124 /* And a pointer to the last device for easy append. */
125 struct device *lastdev;
128 struct device *pci[MAX_PCI_DEVICES];
131 /* The list of Guest devices, based on command line arguments. */
132 static struct device_list devices;
134 struct virtio_pci_cfg_cap {
135 struct virtio_pci_cap cap;
136 u32 window; /* Data for BAR access. */
139 struct virtio_pci_mmio {
140 struct virtio_pci_common_cfg cfg;
144 /* Device-specific configuration follows this. */
147 /* This is the layout (little-endian) of the PCI config space. */
149 u16 vendor_id, device_id;
151 u8 revid, prog_if, subclass, class;
152 u8 cacheline_size, lat_timer, header_type, bist;
155 u16 subsystem_vendor_id, subsystem_device_id;
156 u32 expansion_rom_addr;
157 u8 capabilities, reserved1[3];
159 u8 irq_line, irq_pin, min_grant, max_latency;
161 /* Now, this is the linked capability list. */
162 struct virtio_pci_cap common;
163 struct virtio_pci_notify_cap notify;
164 struct virtio_pci_cap isr;
165 struct virtio_pci_cap device;
166 /* FIXME: Implement this! */
167 struct virtio_pci_cfg_cap cfg_access;
170 /* The device structure describes a single device. */
172 /* The linked-list pointer. */
175 /* The device's descriptor, as mapped into the Guest. */
176 struct lguest_device_desc *desc;
178 /* We can't trust desc values once Guest has booted: we use these. */
179 unsigned int feature_len;
182 /* The name of this device, for --verbose. */
185 /* Any queues attached to this device */
186 struct virtqueue *vq;
188 /* Is it operational */
191 /* PCI configuration */
193 struct pci_config config;
194 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
197 /* Features we offer, and those accepted. */
198 u64 features, features_accepted;
200 /* Device-specific config hangs off the end of this. */
201 struct virtio_pci_mmio *mmio;
203 /* PCI MMIO resources (all in BAR0) */
207 /* Device-specific data. */
211 /* The virtqueue structure describes a queue attached to a device. */
213 struct virtqueue *next;
215 /* Which device owns me. */
218 /* The configuration for this queue. */
219 struct lguest_vqconfig config;
221 /* The actual ring of buffers. */
224 /* The information about this virtqueue (we only use queue_size on) */
225 struct virtio_pci_common_cfg pci_config;
227 /* Last available index we saw. */
230 /* How many are used since we sent last irq? */
231 unsigned int pending_used;
233 /* Eventfd where Guest notifications arrive. */
236 /* Function for the thread which is servicing this virtqueue. */
237 void (*service)(struct virtqueue *vq);
241 /* Remember the arguments to the program so we can "reboot" */
242 static char **main_args;
244 /* The original tty settings to restore on exit. */
245 static struct termios orig_term;
248 * We have to be careful with barriers: our devices are all run in separate
249 * threads and so we need to make sure that changes visible to the Guest happen
252 #define wmb() __asm__ __volatile__("" : : : "memory")
253 #define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
254 #define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
256 /* Wrapper for the last available index. Makes it easier to change. */
257 #define lg_last_avail(vq) ((vq)->last_avail_idx)
260 * The virtio configuration space is defined to be little-endian. x86 is
261 * little-endian too, but it's nice to be explicit so we have these helpers.
263 #define cpu_to_le16(v16) (v16)
264 #define cpu_to_le32(v32) (v32)
265 #define cpu_to_le64(v64) (v64)
266 #define le16_to_cpu(v16) (v16)
267 #define le32_to_cpu(v32) (v32)
268 #define le64_to_cpu(v64) (v64)
270 /* Is this iovec empty? */
271 static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
275 for (i = 0; i < num_iov; i++)
281 /* Take len bytes from the front of this iovec. */
282 static void iov_consume(struct iovec iov[], unsigned num_iov,
283 void *dest, unsigned len)
287 for (i = 0; i < num_iov; i++) {
290 used = iov[i].iov_len < len ? iov[i].iov_len : len;
292 memcpy(dest, iov[i].iov_base, used);
295 iov[i].iov_base += used;
296 iov[i].iov_len -= used;
300 errx(1, "iovec too short!");
303 /* The device virtqueue descriptors are followed by feature bitmasks. */
304 static u8 *get_feature_bits(struct device *dev)
306 return (u8 *)(dev->desc + 1)
307 + dev->num_vq * sizeof(struct lguest_vqconfig);
311 * The Launcher code itself takes us out into userspace, that scary place where
312 * pointers run wild and free! Unfortunately, like most userspace programs,
313 * it's quite boring (which is why everyone likes to hack on the kernel!).
314 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
315 * you through this section. Or, maybe not.
317 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
318 * memory and stores it in "guest_base". In other words, Guest physical ==
319 * Launcher virtual with an offset.
321 * This can be tough to get your head around, but usually it just means that we
322 * use these trivial conversion functions when the Guest gives us its
323 * "physical" addresses:
325 static void *from_guest_phys(unsigned long addr)
327 return guest_base + addr;
330 static unsigned long to_guest_phys(const void *addr)
332 return (addr - guest_base);
336 * Loading the Kernel.
338 * We start with couple of simple helper routines. open_or_die() avoids
339 * error-checking code cluttering the callers:
341 static int open_or_die(const char *name, int flags)
343 int fd = open(name, flags);
345 err(1, "Failed to open %s", name);
349 /* map_zeroed_pages() takes a number of pages. */
350 static void *map_zeroed_pages(unsigned int num)
352 int fd = open_or_die("/dev/zero", O_RDONLY);
356 * We use a private mapping (ie. if we write to the page, it will be
357 * copied). We allocate an extra two pages PROT_NONE to act as guard
358 * pages against read/write attempts that exceed allocated space.
360 addr = mmap(NULL, getpagesize() * (num+2),
361 PROT_NONE, MAP_PRIVATE, fd, 0);
363 if (addr == MAP_FAILED)
364 err(1, "Mmapping %u pages of /dev/zero", num);
366 if (mprotect(addr + getpagesize(), getpagesize() * num,
367 PROT_READ|PROT_WRITE) == -1)
368 err(1, "mprotect rw %u pages failed", num);
371 * One neat mmap feature is that you can close the fd, and it
376 /* Return address after PROT_NONE page */
377 return addr + getpagesize();
380 /* Get some more pages for a device. */
381 static void *get_pages(unsigned int num)
383 void *addr = from_guest_phys(guest_limit);
385 guest_limit += num * getpagesize();
386 if (guest_limit > guest_max)
387 errx(1, "Not enough memory for devices");
391 /* Get some bytes which won't be mapped into the guest. */
392 static unsigned long get_mmio_region(size_t size)
394 unsigned long addr = guest_mmio;
400 /* Size has to be a power of 2 (and multiple of 16) */
401 for (i = 1; i < size; i <<= 1);
409 * This routine is used to load the kernel or initrd. It tries mmap, but if
410 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
411 * it falls back to reading the memory in.
413 static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
418 * We map writable even though for some segments are marked read-only.
419 * The kernel really wants to be writable: it patches its own
422 * MAP_PRIVATE means that the page won't be copied until a write is
423 * done to it. This allows us to share untouched memory between
426 if (mmap(addr, len, PROT_READ|PROT_WRITE,
427 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
430 /* pread does a seek and a read in one shot: saves a few lines. */
431 r = pread(fd, addr, len, offset);
433 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
437 * This routine takes an open vmlinux image, which is in ELF, and maps it into
438 * the Guest memory. ELF = Embedded Linking Format, which is the format used
439 * by all modern binaries on Linux including the kernel.
441 * The ELF headers give *two* addresses: a physical address, and a virtual
442 * address. We use the physical address; the Guest will map itself to the
445 * We return the starting address.
447 static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
449 Elf32_Phdr phdr[ehdr->e_phnum];
453 * Sanity checks on the main ELF header: an x86 executable with a
454 * reasonable number of correctly-sized program headers.
456 if (ehdr->e_type != ET_EXEC
457 || ehdr->e_machine != EM_386
458 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
459 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
460 errx(1, "Malformed elf header");
463 * An ELF executable contains an ELF header and a number of "program"
464 * headers which indicate which parts ("segments") of the program to
468 /* We read in all the program headers at once: */
469 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
470 err(1, "Seeking to program headers");
471 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
472 err(1, "Reading program headers");
475 * Try all the headers: there are usually only three. A read-only one,
476 * a read-write one, and a "note" section which we don't load.
478 for (i = 0; i < ehdr->e_phnum; i++) {
479 /* If this isn't a loadable segment, we ignore it */
480 if (phdr[i].p_type != PT_LOAD)
483 verbose("Section %i: size %i addr %p\n",
484 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
486 /* We map this section of the file at its physical address. */
487 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
488 phdr[i].p_offset, phdr[i].p_filesz);
491 /* The entry point is given in the ELF header. */
492 return ehdr->e_entry;
496 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
497 * to jump into it and it will unpack itself. We used to have to perform some
498 * hairy magic because the unpacking code scared me.
500 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
501 * a small patch to jump over the tricky bits in the Guest, so now we just read
502 * the funky header so we know where in the file to load, and away we go!
504 static unsigned long load_bzimage(int fd)
506 struct boot_params boot;
508 /* Modern bzImages get loaded at 1M. */
509 void *p = from_guest_phys(0x100000);
512 * Go back to the start of the file and read the header. It should be
513 * a Linux boot header (see Documentation/x86/boot.txt)
515 lseek(fd, 0, SEEK_SET);
516 read(fd, &boot, sizeof(boot));
518 /* Inside the setup_hdr, we expect the magic "HdrS" */
519 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
520 errx(1, "This doesn't look like a bzImage to me");
522 /* Skip over the extra sectors of the header. */
523 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
525 /* Now read everything into memory. in nice big chunks. */
526 while ((r = read(fd, p, 65536)) > 0)
529 /* Finally, code32_start tells us where to enter the kernel. */
530 return boot.hdr.code32_start;
534 * Loading the kernel is easy when it's a "vmlinux", but most kernels
535 * come wrapped up in the self-decompressing "bzImage" format. With a little
536 * work, we can load those, too.
538 static unsigned long load_kernel(int fd)
542 /* Read in the first few bytes. */
543 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
544 err(1, "Reading kernel");
546 /* If it's an ELF file, it starts with "\177ELF" */
547 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
548 return map_elf(fd, &hdr);
550 /* Otherwise we assume it's a bzImage, and try to load it. */
551 return load_bzimage(fd);
555 * This is a trivial little helper to align pages. Andi Kleen hated it because
556 * it calls getpagesize() twice: "it's dumb code."
558 * Kernel guys get really het up about optimization, even when it's not
559 * necessary. I leave this code as a reaction against that.
561 static inline unsigned long page_align(unsigned long addr)
563 /* Add upwards and truncate downwards. */
564 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
568 * An "initial ram disk" is a disk image loaded into memory along with the
569 * kernel which the kernel can use to boot from without needing any drivers.
570 * Most distributions now use this as standard: the initrd contains the code to
571 * load the appropriate driver modules for the current machine.
573 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
574 * kernels. He sent me this (and tells me when I break it).
576 static unsigned long load_initrd(const char *name, unsigned long mem)
582 ifd = open_or_die(name, O_RDONLY);
583 /* fstat() is needed to get the file size. */
584 if (fstat(ifd, &st) < 0)
585 err(1, "fstat() on initrd '%s'", name);
588 * We map the initrd at the top of memory, but mmap wants it to be
589 * page-aligned, so we round the size up for that.
591 len = page_align(st.st_size);
592 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
594 * Once a file is mapped, you can close the file descriptor. It's a
595 * little odd, but quite useful.
598 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
600 /* We return the initrd size. */
606 * Simple routine to roll all the commandline arguments together with spaces
609 static void concat(char *dst, char *args[])
611 unsigned int i, len = 0;
613 for (i = 0; args[i]; i++) {
615 strcat(dst+len, " ");
618 strcpy(dst+len, args[i]);
619 len += strlen(args[i]);
621 /* In case it's empty. */
626 * This is where we actually tell the kernel to initialize the Guest. We
627 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
628 * the base of Guest "physical" memory, the top physical page to allow and the
629 * entry point for the Guest.
631 static void tell_kernel(unsigned long start)
633 unsigned long args[] = { LHREQ_INITIALIZE,
634 (unsigned long)guest_base,
635 guest_limit / getpagesize(), start,
636 (guest_mmio+getpagesize()-1) / getpagesize() };
637 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
638 guest_base, guest_base + guest_limit,
639 guest_limit, guest_mmio);
640 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
641 if (write(lguest_fd, args, sizeof(args)) < 0)
642 err(1, "Writing to /dev/lguest");
649 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
650 * We need to make sure it's not trying to reach into the Launcher itself, so
651 * we have a convenient routine which checks it and exits with an error message
652 * if something funny is going on:
654 static void *_check_pointer(unsigned long addr, unsigned int size,
658 * Check if the requested address and size exceeds the allocated memory,
659 * or addr + size wraps around.
661 if ((addr + size) > guest_limit || (addr + size) < addr)
662 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
664 * We return a pointer for the caller's convenience, now we know it's
667 return from_guest_phys(addr);
669 /* A macro which transparently hands the line number to the real function. */
670 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
673 * Each buffer in the virtqueues is actually a chain of descriptors. This
674 * function returns the next descriptor in the chain, or vq->vring.num if we're
677 static unsigned next_desc(struct vring_desc *desc,
678 unsigned int i, unsigned int max)
682 /* If this descriptor says it doesn't chain, we're done. */
683 if (!(desc[i].flags & VRING_DESC_F_NEXT))
686 /* Check they're not leading us off end of descriptors. */
688 /* Make sure compiler knows to grab that: we don't want it changing! */
692 errx(1, "Desc next is %u", next);
698 * This actually sends the interrupt for this virtqueue, if we've used a
701 static void trigger_irq(struct virtqueue *vq)
703 unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
705 /* Don't inform them if nothing used. */
706 if (!vq->pending_used)
708 vq->pending_used = 0;
710 /* If they don't want an interrupt, don't send one... */
711 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
715 /* For a PCI device, set isr to 1 (queue interrupt pending) */
717 vq->dev->mmio->isr = 0x1;
719 /* Send the Guest an interrupt tell them we used something up. */
720 if (write(lguest_fd, buf, sizeof(buf)) != 0)
721 err(1, "Triggering irq %i", vq->config.irq);
725 * This looks in the virtqueue for the first available buffer, and converts
726 * it to an iovec for convenient access. Since descriptors consist of some
727 * number of output then some number of input descriptors, it's actually two
728 * iovecs, but we pack them into one and note how many of each there were.
730 * This function waits if necessary, and returns the descriptor number found.
732 static unsigned wait_for_vq_desc(struct virtqueue *vq,
734 unsigned int *out_num, unsigned int *in_num)
736 unsigned int i, head, max;
737 struct vring_desc *desc;
738 u16 last_avail = lg_last_avail(vq);
740 /* There's nothing available? */
741 while (last_avail == vq->vring.avail->idx) {
745 * Since we're about to sleep, now is a good time to tell the
746 * Guest about what we've used up to now.
750 /* OK, now we need to know about added descriptors. */
751 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
754 * They could have slipped one in as we were doing that: make
755 * sure it's written, then check again.
758 if (last_avail != vq->vring.avail->idx) {
759 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
763 /* Nothing new? Wait for eventfd to tell us they refilled. */
764 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
765 errx(1, "Event read failed?");
767 /* We don't need to be notified again. */
768 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
771 /* Check it isn't doing very strange things with descriptor numbers. */
772 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
773 errx(1, "Guest moved used index from %u to %u",
774 last_avail, vq->vring.avail->idx);
777 * Make sure we read the descriptor number *after* we read the ring
778 * update; don't let the cpu or compiler change the order.
783 * Grab the next descriptor number they're advertising, and increment
784 * the index we've seen.
786 head = vq->vring.avail->ring[last_avail % vq->vring.num];
789 /* If their number is silly, that's a fatal mistake. */
790 if (head >= vq->vring.num)
791 errx(1, "Guest says index %u is available", head);
793 /* When we start there are none of either input nor output. */
794 *out_num = *in_num = 0;
797 desc = vq->vring.desc;
801 * We have to read the descriptor after we read the descriptor number,
802 * but there's a data dependency there so the CPU shouldn't reorder
803 * that: no rmb() required.
807 * If this is an indirect entry, then this buffer contains a descriptor
808 * table which we handle as if it's any normal descriptor chain.
810 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
811 if (desc[i].len % sizeof(struct vring_desc))
812 errx(1, "Invalid size for indirect buffer table");
814 max = desc[i].len / sizeof(struct vring_desc);
815 desc = check_pointer(desc[i].addr, desc[i].len);
820 /* Grab the first descriptor, and check it's OK. */
821 iov[*out_num + *in_num].iov_len = desc[i].len;
822 iov[*out_num + *in_num].iov_base
823 = check_pointer(desc[i].addr, desc[i].len);
824 /* If this is an input descriptor, increment that count. */
825 if (desc[i].flags & VRING_DESC_F_WRITE)
829 * If it's an output descriptor, they're all supposed
830 * to come before any input descriptors.
833 errx(1, "Descriptor has out after in");
837 /* If we've got too many, that implies a descriptor loop. */
838 if (*out_num + *in_num > max)
839 errx(1, "Looped descriptor");
840 } while ((i = next_desc(desc, i, max)) != max);
846 * After we've used one of their buffers, we tell the Guest about it. Sometime
847 * later we'll want to send them an interrupt using trigger_irq(); note that
848 * wait_for_vq_desc() does that for us if it has to wait.
850 static void add_used(struct virtqueue *vq, unsigned int head, int len)
852 struct vring_used_elem *used;
855 * The virtqueue contains a ring of used buffers. Get a pointer to the
856 * next entry in that used ring.
858 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
861 /* Make sure buffer is written before we update index. */
863 vq->vring.used->idx++;
867 /* And here's the combo meal deal. Supersize me! */
868 static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
870 add_used(vq, head, len);
877 * We associate some data with the console for our exit hack.
879 struct console_abort {
880 /* How many times have they hit ^C? */
882 /* When did they start? */
883 struct timeval start;
886 /* This is the routine which handles console input (ie. stdin). */
887 static void console_input(struct virtqueue *vq)
890 unsigned int head, in_num, out_num;
891 struct console_abort *abort = vq->dev->priv;
892 struct iovec iov[vq->vring.num];
894 /* Make sure there's a descriptor available. */
895 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
897 errx(1, "Output buffers in console in queue?");
899 /* Read into it. This is where we usually wait. */
900 len = readv(STDIN_FILENO, iov, in_num);
902 /* Ran out of input? */
903 warnx("Failed to get console input, ignoring console.");
905 * For simplicity, dying threads kill the whole Launcher. So
912 /* Tell the Guest we used a buffer. */
913 add_used_and_trigger(vq, head, len);
916 * Three ^C within one second? Exit.
918 * This is such a hack, but works surprisingly well. Each ^C has to
919 * be in a buffer by itself, so they can't be too fast. But we check
920 * that we get three within about a second, so they can't be too
923 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
929 if (abort->count == 1)
930 gettimeofday(&abort->start, NULL);
931 else if (abort->count == 3) {
933 gettimeofday(&now, NULL);
934 /* Kill all Launcher processes with SIGINT, like normal ^C */
935 if (now.tv_sec <= abort->start.tv_sec+1)
941 /* This is the routine which handles console output (ie. stdout). */
942 static void console_output(struct virtqueue *vq)
944 unsigned int head, out, in;
945 struct iovec iov[vq->vring.num];
947 /* We usually wait in here, for the Guest to give us something. */
948 head = wait_for_vq_desc(vq, iov, &out, &in);
950 errx(1, "Input buffers in console output queue?");
952 /* writev can return a partial write, so we loop here. */
953 while (!iov_empty(iov, out)) {
954 int len = writev(STDOUT_FILENO, iov, out);
956 warn("Write to stdout gave %i (%d)", len, errno);
959 iov_consume(iov, out, NULL, len);
963 * We're finished with that buffer: if we're going to sleep,
964 * wait_for_vq_desc() will prod the Guest with an interrupt.
966 add_used(vq, head, 0);
972 * Handling output for network is also simple: we get all the output buffers
973 * and write them to /dev/net/tun.
979 static void net_output(struct virtqueue *vq)
981 struct net_info *net_info = vq->dev->priv;
982 unsigned int head, out, in;
983 struct iovec iov[vq->vring.num];
985 /* We usually wait in here for the Guest to give us a packet. */
986 head = wait_for_vq_desc(vq, iov, &out, &in);
988 errx(1, "Input buffers in net output queue?");
990 * Send the whole thing through to /dev/net/tun. It expects the exact
991 * same format: what a coincidence!
993 if (writev(net_info->tunfd, iov, out) < 0)
994 warnx("Write to tun failed (%d)?", errno);
997 * Done with that one; wait_for_vq_desc() will send the interrupt if
998 * all packets are processed.
1000 add_used(vq, head, 0);
1004 * Handling network input is a bit trickier, because I've tried to optimize it.
1006 * First we have a helper routine which tells is if from this file descriptor
1007 * (ie. the /dev/net/tun device) will block:
1009 static bool will_block(int fd)
1012 struct timeval zero = { 0, 0 };
1015 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
1019 * This handles packets coming in from the tun device to our Guest. Like all
1020 * service routines, it gets called again as soon as it returns, so you don't
1021 * see a while(1) loop here.
1023 static void net_input(struct virtqueue *vq)
1026 unsigned int head, out, in;
1027 struct iovec iov[vq->vring.num];
1028 struct net_info *net_info = vq->dev->priv;
1031 * Get a descriptor to write an incoming packet into. This will also
1032 * send an interrupt if they're out of descriptors.
1034 head = wait_for_vq_desc(vq, iov, &out, &in);
1036 errx(1, "Output buffers in net input queue?");
1039 * If it looks like we'll block reading from the tun device, send them
1042 if (vq->pending_used && will_block(net_info->tunfd))
1046 * Read in the packet. This is where we normally wait (when there's no
1047 * incoming network traffic).
1049 len = readv(net_info->tunfd, iov, in);
1051 warn("Failed to read from tun (%d).", errno);
1054 * Mark that packet buffer as used, but don't interrupt here. We want
1055 * to wait until we've done as much work as we can.
1057 add_used(vq, head, len);
1061 /* This is the helper to create threads: run the service routine in a loop. */
1062 static int do_thread(void *_vq)
1064 struct virtqueue *vq = _vq;
1072 * When a child dies, we kill our entire process group with SIGTERM. This
1073 * also has the side effect that the shell restores the console for us!
1075 static void kill_launcher(int signal)
1080 static void reset_device(struct device *dev)
1082 struct virtqueue *vq;
1084 verbose("Resetting device %s\n", dev->name);
1086 /* Clear any features they've acked. */
1087 memset(get_feature_bits(dev) + dev->feature_len, 0, dev->feature_len);
1089 /* We're going to be explicitly killing threads, so ignore them. */
1090 signal(SIGCHLD, SIG_IGN);
1092 /* Zero out the virtqueues, get rid of their threads */
1093 for (vq = dev->vq; vq; vq = vq->next) {
1094 if (vq->thread != (pid_t)-1) {
1095 kill(vq->thread, SIGTERM);
1096 waitpid(vq->thread, NULL, 0);
1097 vq->thread = (pid_t)-1;
1099 memset(vq->vring.desc, 0,
1100 vring_size(vq->config.num, LGUEST_VRING_ALIGN));
1101 lg_last_avail(vq) = 0;
1103 dev->running = false;
1105 /* Now we care if threads die. */
1106 signal(SIGCHLD, (void *)kill_launcher);
1110 * This actually creates the thread which services the virtqueue for a device.
1112 static void create_thread(struct virtqueue *vq)
1115 * Create stack for thread. Since the stack grows upwards, we point
1116 * the stack pointer to the end of this region.
1118 char *stack = malloc(32768);
1119 unsigned long args[] = { LHREQ_EVENTFD,
1120 vq->config.pfn*getpagesize(), 0 };
1122 /* Create a zero-initialized eventfd. */
1123 vq->eventfd = eventfd(0, 0);
1124 if (vq->eventfd < 0)
1125 err(1, "Creating eventfd");
1126 args[2] = vq->eventfd;
1129 * Attach an eventfd to this virtqueue: it will go off when the Guest
1130 * does an LHCALL_NOTIFY for this vq.
1132 if (write(lguest_fd, &args, sizeof(args)) != 0)
1133 err(1, "Attaching eventfd");
1136 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1137 * we get a signal if it dies.
1139 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1140 if (vq->thread == (pid_t)-1)
1141 err(1, "Creating clone");
1143 /* We close our local copy now the child has it. */
1147 static void start_device(struct device *dev)
1150 struct virtqueue *vq;
1152 verbose("Device %s OK: offered", dev->name);
1153 for (i = 0; i < dev->feature_len; i++)
1154 verbose(" %02x", get_feature_bits(dev)[i]);
1155 verbose(", accepted");
1156 for (i = 0; i < dev->feature_len; i++)
1157 verbose(" %02x", get_feature_bits(dev)
1158 [dev->feature_len+i]);
1160 for (vq = dev->vq; vq; vq = vq->next) {
1164 dev->running = true;
1167 static void cleanup_devices(void)
1171 for (dev = devices.dev; dev; dev = dev->next)
1174 /* If we saved off the original terminal settings, restore them now. */
1175 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1176 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
1179 /* When the Guest tells us they updated the status field, we handle it. */
1180 static void update_device_status(struct device *dev)
1182 /* A zero status is a reset, otherwise it's a set of flags. */
1183 if (dev->desc->status == 0)
1185 else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
1186 warnx("Device %s configuration FAILED", dev->name);
1191 err(1, "Device %s features finalized twice", dev->name);
1197 * This is the generic routine we call when the Guest uses LHCALL_NOTIFY. In
1198 * particular, it's used to notify us of device status changes during boot.
1200 static void handle_output(unsigned long addr)
1204 /* Check each device. */
1205 for (i = devices.dev; i; i = i->next) {
1206 struct virtqueue *vq;
1209 * Notifications to device descriptors mean they updated the
1212 if (from_guest_phys(addr) == i->desc) {
1213 update_device_status(i);
1217 /* Devices should not be used before features are finalized. */
1218 for (vq = i->vq; vq; vq = vq->next) {
1219 if (addr != vq->config.pfn*getpagesize())
1221 errx(1, "Notification on %s before setup!", i->name);
1226 * Early console write is done using notify on a nul-terminated string
1227 * in Guest memory. It's also great for hacking debugging messages
1230 if (addr >= guest_limit)
1231 errx(1, "Bad NOTIFY %#lx", addr);
1233 write(STDOUT_FILENO, from_guest_phys(addr),
1234 strnlen(from_guest_phys(addr), guest_limit - addr));
1238 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1242 /* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1243 static struct device pci_host_bridge;
1245 static void init_pci_host_bridge(void)
1247 pci_host_bridge.name = "PCI Host Bridge";
1248 pci_host_bridge.config.class = 0x06; /* bridge */
1249 pci_host_bridge.config.subclass = 0; /* host bridge */
1250 devices.pci[0] = &pci_host_bridge;
1253 /* The IO ports used to read the PCI config space. */
1254 #define PCI_CONFIG_ADDR 0xCF8
1255 #define PCI_CONFIG_DATA 0xCFC
1258 * Not really portable, but does help readability: this is what the Guest
1259 * writes to the PCI_CONFIG_ADDR IO port.
1261 union pci_config_addr {
1265 unsigned funcnum: 3;
1268 unsigned reserved: 7;
1269 unsigned enabled : 1;
1275 * We cache what they wrote to the address port, so we know what they're
1276 * talking about when they access the data port.
1278 static union pci_config_addr pci_config_addr;
1280 static struct device *find_pci_device(unsigned int index)
1282 return devices.pci[index];
1285 /* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1286 static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1289 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1290 *val = (v >> (off * 8)) & mask;
1293 /* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1294 static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1297 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1298 *dst &= ~(mask << (off * 8));
1299 *dst |= (v & mask) << (off * 8);
1303 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1306 static struct device *dev_and_reg(u32 *reg)
1308 if (!pci_config_addr.bits.enabled)
1311 if (pci_config_addr.bits.funcnum != 0)
1314 if (pci_config_addr.bits.busnum != 0)
1317 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1320 *reg = pci_config_addr.bits.offset;
1321 return find_pci_device(pci_config_addr.bits.devnum);
1324 /* Is this accessing the PCI config address port?. */
1325 static bool is_pci_addr_port(u16 port)
1327 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1330 static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1332 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1333 &pci_config_addr.val);
1334 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1335 pci_config_addr.bits.enabled ? "" : " DISABLED",
1337 pci_config_addr.bits.busnum,
1338 pci_config_addr.bits.devnum,
1339 pci_config_addr.bits.funcnum,
1340 pci_config_addr.bits.offset);
1344 static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1346 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1349 /* Is this accessing the PCI config data port?. */
1350 static bool is_pci_data_port(u16 port)
1352 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1355 static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1358 struct device *d = dev_and_reg(®);
1360 /* Complain if they don't belong to a device. */
1364 /* They can do 1 byte writes, etc. */
1365 portoff = port - PCI_CONFIG_DATA;
1368 * PCI uses a weird way to determine the BAR size: the OS
1369 * writes all 1's, and sees which ones stick.
1371 if (&d->config_words[reg] == &d->config.bar[0]) {
1374 iowrite(portoff, val, mask, &d->config.bar[0]);
1375 for (i = 0; (1 << i) < d->mmio_size; i++)
1376 d->config.bar[0] &= ~(1 << i);
1378 } else if ((&d->config_words[reg] > &d->config.bar[0]
1379 && &d->config_words[reg] <= &d->config.bar[6])
1380 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1381 /* Allow writing to any other BAR, or expansion ROM */
1382 iowrite(portoff, val, mask, &d->config_words[reg]);
1384 /* We let them overide latency timer and cacheline size */
1385 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1386 /* Only let them change the first two fields. */
1387 if (mask == 0xFFFFFFFF)
1389 iowrite(portoff, val, mask, &d->config_words[reg]);
1391 } else if (&d->config_words[reg] == (void *)&d->config.command
1392 && mask == 0xFFFF) {
1393 /* Ignore command writes. */
1397 /* Complain about other writes. */
1401 static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1404 struct device *d = dev_and_reg(®);
1408 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1412 * This is where we emulate a handful of Guest instructions. It's ugly
1413 * and we used to do it in the kernel but it grew over time.
1417 * We use the ptrace syscall's pt_regs struct to talk about registers
1418 * to lguest: these macros convert the names to the offsets.
1420 #define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1421 #define setreg(name, val) \
1422 setreg_off(offsetof(struct user_regs_struct, name), (val))
1424 static u32 getreg_off(size_t offset)
1427 unsigned long args[] = { LHREQ_GETREG, offset };
1429 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1430 err(1, "Getting register %u", offset);
1431 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1432 err(1, "Reading register %u", offset);
1437 static void setreg_off(size_t offset, u32 val)
1439 unsigned long args[] = { LHREQ_SETREG, offset, val };
1441 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1442 err(1, "Setting register %u", offset);
1445 /* Get register by instruction encoding */
1446 static u32 getreg_num(unsigned regnum, u32 mask)
1448 /* 8 bit ops use regnums 4-7 for high parts of word */
1449 if (mask == 0xFF && (regnum & 0x4))
1450 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1453 case 0: return getreg(eax) & mask;
1454 case 1: return getreg(ecx) & mask;
1455 case 2: return getreg(edx) & mask;
1456 case 3: return getreg(ebx) & mask;
1457 case 4: return getreg(esp) & mask;
1458 case 5: return getreg(ebp) & mask;
1459 case 6: return getreg(esi) & mask;
1460 case 7: return getreg(edi) & mask;
1465 /* Set register by instruction encoding */
1466 static void setreg_num(unsigned regnum, u32 val, u32 mask)
1468 /* Don't try to set bits out of range */
1469 assert(~(val & ~mask));
1471 /* 8 bit ops use regnums 4-7 for high parts of word */
1472 if (mask == 0xFF && (regnum & 0x4)) {
1473 /* Construct the 16 bits we want. */
1474 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1475 setreg_num(regnum & 0x3, val, 0xFFFF);
1480 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1481 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1482 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1483 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1484 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1485 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1486 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1487 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1492 /* Get bytes of displacement appended to instruction, from r/m encoding */
1493 static u32 insn_displacement_len(u8 mod_reg_rm)
1495 /* Switch on the mod bits */
1496 switch (mod_reg_rm >> 6) {
1498 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1499 if ((mod_reg_rm & 0x7) == 0x5)
1501 /* Normally, mod == 0 means no literal displacement */
1504 /* One byte displacement */
1507 /* Four byte displacement */
1516 static void emulate_insn(const u8 insn[])
1518 unsigned long args[] = { LHREQ_TRAP, 13 };
1519 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1520 unsigned int eax, port, mask;
1522 * Default is to return all-ones on IO port reads, which traditionally
1523 * means "there's nothing there".
1525 u32 val = 0xFFFFFFFF;
1528 * This must be the Guest kernel trying to do something, not userspace!
1529 * The bottom two bits of the CS segment register are the privilege
1532 if ((getreg(xcs) & 3) != 0x1)
1535 /* Decoding x86 instructions is icky. */
1538 * Around 2.6.33, the kernel started using an emulation for the
1539 * cmpxchg8b instruction in early boot on many configurations. This
1540 * code isn't paravirtualized, and it tries to disable interrupts.
1541 * Ignore it, which will Mostly Work.
1543 if (insn[insnlen] == 0xfa) {
1544 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1550 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1552 if (insn[insnlen] == 0x66) {
1554 /* The instruction is 1 byte so far, read the next byte. */
1558 /* If the lower bit isn't set, it's a single byte access */
1559 byte_access = !(insn[insnlen] & 1);
1562 * Now we can ignore the lower bit and decode the 4 opcodes
1563 * we need to emulate.
1565 switch (insn[insnlen] & 0xFE) {
1566 case 0xE4: /* in <next byte>,%al */
1567 port = insn[insnlen+1];
1571 case 0xEC: /* in (%dx),%al */
1572 port = getreg(edx) & 0xFFFF;
1576 case 0xE6: /* out %al,<next byte> */
1577 port = insn[insnlen+1];
1580 case 0xEE: /* out %al,(%dx) */
1581 port = getreg(edx) & 0xFFFF;
1585 /* OK, we don't know what this is, can't emulate. */
1589 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1592 else if (small_operand)
1598 * If it was an "IN" instruction, they expect the result to be read
1599 * into %eax, so we change %eax.
1604 /* This is the PS/2 keyboard status; 1 means ready for output */
1607 else if (is_pci_addr_port(port))
1608 pci_addr_ioread(port, mask, &val);
1609 else if (is_pci_data_port(port))
1610 pci_data_ioread(port, mask, &val);
1612 /* Clear the bits we're about to read */
1614 /* Copy bits in from val. */
1616 /* Now update the register. */
1619 if (is_pci_addr_port(port)) {
1620 if (!pci_addr_iowrite(port, mask, eax))
1622 } else if (is_pci_data_port(port)) {
1623 if (!pci_data_iowrite(port, mask, eax))
1626 /* There are many other ports, eg. CMOS clock, serial
1627 * and parallel ports, so we ignore them all. */
1630 verbose("IO %s of %x to %u: %#08x\n",
1631 in ? "IN" : "OUT", mask, port, eax);
1633 /* Finally, we've "done" the instruction, so move past it. */
1634 setreg(eip, getreg(eip) + insnlen);
1638 warnx("Attempt to %s port %u (%#x mask)",
1639 in ? "read from" : "write to", port, mask);
1642 /* Inject trap into Guest. */
1643 if (write(lguest_fd, args, sizeof(args)) < 0)
1644 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1647 static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1651 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1652 struct device *d = devices.pci[i];
1656 if (paddr < d->mmio_addr)
1658 if (paddr >= d->mmio_addr + d->mmio_size)
1660 *off = paddr - d->mmio_addr;
1666 /* FIXME: Use vq array. */
1667 static struct virtqueue *vq_by_num(struct device *d, u32 num)
1669 struct virtqueue *vq = d->vq;
1677 static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1678 struct virtqueue *vq)
1680 vq->pci_config = *cfg;
1683 static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1684 struct virtqueue *vq)
1686 /* Only restore the per-vq part */
1687 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1689 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1690 sizeof(*cfg) - off);
1694 * When they enable the virtqueue, we check that their setup is valid.
1696 static void enable_virtqueue(struct device *d, struct virtqueue *vq)
1699 * Create stack for thread. Since the stack grows upwards, we point
1700 * the stack pointer to the end of this region.
1702 char *stack = malloc(32768);
1704 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1705 if (vq->pci_config.queue_desc_hi
1706 || vq->pci_config.queue_avail_hi
1707 || vq->pci_config.queue_used_hi)
1708 errx(1, "%s: invalid 64-bit queue address", d->name);
1710 /* Initialize the virtqueue and check they're all in range. */
1711 vq->vring.num = vq->pci_config.queue_size;
1712 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1713 sizeof(*vq->vring.desc) * vq->vring.num);
1714 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1715 sizeof(*vq->vring.avail)
1716 + (sizeof(vq->vring.avail->ring[0])
1718 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1719 sizeof(*vq->vring.used)
1720 + (sizeof(vq->vring.used->ring[0])
1724 /* Create a zero-initialized eventfd. */
1725 vq->eventfd = eventfd(0, 0);
1726 if (vq->eventfd < 0)
1727 err(1, "Creating eventfd");
1730 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1731 * we get a signal if it dies.
1733 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1734 if (vq->thread == (pid_t)-1)
1735 err(1, "Creating clone");
1738 static void reset_pci_device(struct device *dev)
1743 static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1745 struct virtqueue *vq;
1748 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1750 d->mmio->cfg.device_feature = d->features;
1752 d->mmio->cfg.device_feature = (d->features >> 32);
1754 d->mmio->cfg.device_feature = 0;
1755 goto write_through32;
1756 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1758 errx(1, "%s: Unexpected driver select %u",
1760 goto write_through32;
1761 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1762 if (d->mmio->cfg.guest_feature_select == 0) {
1763 d->features_accepted &= ~((u64)0xFFFFFFFF);
1764 d->features_accepted |= val;
1766 assert(d->mmio->cfg.guest_feature_select == 1);
1767 d->features_accepted &= ((u64)0xFFFFFFFF << 32);
1768 d->features_accepted |= ((u64)val) << 32;
1770 if (d->features_accepted & ~d->features)
1771 errx(1, "%s: over-accepted features %#llx of %#llx",
1772 d->name, d->features_accepted, d->features);
1773 goto write_through32;
1774 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1775 verbose("%s: device status -> %#x\n", d->name, val);
1777 reset_pci_device(d);
1778 goto write_through8;
1779 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1780 vq = vq_by_num(d, val);
1781 /* Out of range? Return size 0 */
1783 d->mmio->cfg.queue_size = 0;
1784 goto write_through16;
1786 /* Save registers for old vq, if it was a valid vq */
1787 if (d->mmio->cfg.queue_size)
1788 save_vq_config(&d->mmio->cfg,
1789 vq_by_num(d, d->mmio->cfg.queue_select));
1790 /* Restore the registers for the queue they asked for */
1791 restore_vq_config(&d->mmio->cfg, vq);
1792 goto write_through16;
1793 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
1795 errx(1, "%s: invalid queue size %u\n", d->name, val);
1796 if (d->mmio->cfg.queue_enable)
1797 errx(1, "%s: changing queue size on live device",
1799 goto write_through16;
1800 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
1801 errx(1, "%s: attempt to set MSIX vector to %u",
1803 case offsetof(struct virtio_pci_mmio, cfg.queue_enable):
1805 errx(1, "%s: setting queue_enable to %u", d->name, val);
1806 d->mmio->cfg.queue_enable = val;
1807 save_vq_config(&d->mmio->cfg,
1808 vq_by_num(d, d->mmio->cfg.queue_select));
1809 enable_virtqueue(d, vq_by_num(d, d->mmio->cfg.queue_select));
1810 goto write_through16;
1811 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
1812 errx(1, "%s: attempt to write to queue_notify_off", d->name);
1813 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
1814 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
1815 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
1816 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
1817 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
1818 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
1819 if (d->mmio->cfg.queue_enable)
1820 errx(1, "%s: changing queue on live device",
1822 goto write_through32;
1823 case offsetof(struct virtio_pci_mmio, notify):
1824 vq = vq_by_num(d, val);
1826 errx(1, "Invalid vq notification on %u", val);
1827 /* Notify the process handling this vq by adding 1 to eventfd */
1828 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
1829 goto write_through16;
1830 case offsetof(struct virtio_pci_mmio, isr):
1831 errx(1, "%s: Unexpected write to isr", d->name);
1833 errx(1, "%s: Unexpected write to offset %u", d->name, off);
1837 if (mask != 0xFFFFFFFF) {
1838 errx(1, "%s: non-32-bit write to offset %u (%#x)",
1839 d->name, off, getreg(eip));
1842 memcpy((char *)d->mmio + off, &val, 4);
1847 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
1848 d->name, mask, off, getreg(eip));
1849 memcpy((char *)d->mmio + off, &val, 2);
1854 errx(1, "%s: non-8-bit write to offset %u (%#x)",
1855 d->name, off, getreg(eip));
1856 memcpy((char *)d->mmio + off, &val, 1);
1860 static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
1866 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1867 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
1868 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1869 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1870 goto read_through32;
1871 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
1872 errx(1, "%s: read of msix_config", d->name);
1873 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
1874 goto read_through16;
1875 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1876 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
1878 case offsetof(struct virtio_pci_mmio, notify):
1879 goto read_through16;
1880 case offsetof(struct virtio_pci_mmio, isr):
1882 errx(1, "%s: non-8-bit read from offset %u (%#x)",
1883 d->name, off, getreg(eip));
1884 /* Read resets the isr */
1888 case offsetof(struct virtio_pci_mmio, padding):
1889 errx(1, "%s: read from padding (%#x)",
1890 d->name, getreg(eip));
1892 /* Read from device config space, beware unaligned overflow */
1893 if (off > d->mmio_size - 4)
1894 errx(1, "%s: read past end (%#x)",
1895 d->name, getreg(eip));
1896 if (mask == 0xFFFFFFFF)
1897 goto read_through32;
1898 else if (mask == 0xFFFF)
1899 goto read_through16;
1905 if (mask != 0xFFFFFFFF)
1906 errx(1, "%s: non-32-bit read to offset %u (%#x)",
1907 d->name, off, getreg(eip));
1908 memcpy(&val, (char *)d->mmio + off, 4);
1913 errx(1, "%s: non-16-bit read to offset %u (%#x)",
1914 d->name, off, getreg(eip));
1915 memcpy(&val, (char *)d->mmio + off, 2);
1920 errx(1, "%s: non-8-bit read to offset %u (%#x)",
1921 d->name, off, getreg(eip));
1922 memcpy(&val, (char *)d->mmio + off, 1);
1926 static void emulate_mmio(unsigned long paddr, const u8 *insn)
1928 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
1929 struct device *d = find_mmio_region(paddr, &off);
1930 unsigned long args[] = { LHREQ_TRAP, 14 };
1933 warnx("MMIO touching %#08lx (not a device)", paddr);
1937 /* Prefix makes it a 16 bit op */
1938 if (insn[0] == 0x66) {
1944 if (insn[insnlen] == 0x89) {
1945 /* Next byte is r/m byte: bits 3-5 are register. */
1946 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
1947 emulate_mmio_write(d, off, val, mask);
1948 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1949 } else if (insn[insnlen] == 0x8b) { /* ioread */
1950 /* Next byte is r/m byte: bits 3-5 are register. */
1951 val = emulate_mmio_read(d, off, mask);
1952 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
1953 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1954 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
1956 /* Next byte is r/m byte: bits 3-5 are register. */
1957 val = getreg_num((insn[1] >> 3) & 0x7, mask);
1958 emulate_mmio_write(d, off, val, mask);
1959 insnlen = 2 + insn_displacement_len(insn[1]);
1960 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
1962 val = emulate_mmio_read(d, off, mask);
1963 setreg_num((insn[1] >> 3) & 0x7, val, mask);
1964 insnlen = 2 + insn_displacement_len(insn[1]);
1966 warnx("Unknown MMIO instruction touching %#08lx:"
1967 " %02x %02x %02x %02x at %u",
1968 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
1970 /* Inject trap into Guest. */
1971 if (write(lguest_fd, args, sizeof(args)) < 0)
1972 err(1, "Reinjecting trap 14 for fault at %#x",
1977 /* Finally, we've "done" the instruction, so move past it. */
1978 setreg(eip, getreg(eip) + insnlen);
1984 * All devices need a descriptor so the Guest knows it exists, and a "struct
1985 * device" so the Launcher can keep track of it. We have common helper
1986 * routines to allocate and manage them.
1990 * The layout of the device page is a "struct lguest_device_desc" followed by a
1991 * number of virtqueue descriptors, then two sets of feature bits, then an
1992 * array of configuration bytes. This routine returns the configuration
1995 static u8 *device_config(const struct device *dev)
1997 return (void *)(dev->desc + 1)
1998 + dev->num_vq * sizeof(struct lguest_vqconfig)
1999 + dev->feature_len * 2;
2003 * This routine allocates a new "struct lguest_device_desc" from descriptor
2004 * table page just above the Guest's normal memory. It returns a pointer to
2007 static struct lguest_device_desc *new_dev_desc(u16 type)
2009 struct lguest_device_desc d = { .type = type };
2012 /* Figure out where the next device config is, based on the last one. */
2013 if (devices.lastdev)
2014 p = device_config(devices.lastdev)
2015 + devices.lastdev->desc->config_len;
2017 p = devices.descpage;
2019 /* We only have one page for all the descriptors. */
2020 if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
2021 errx(1, "Too many devices");
2023 /* p might not be aligned, so we memcpy in. */
2024 return memcpy(p, &d, sizeof(d));
2028 * Each device descriptor is followed by the description of its virtqueues. We
2029 * specify how many descriptors the virtqueue is to have.
2031 static void add_virtqueue(struct device *dev, unsigned int num_descs,
2032 void (*service)(struct virtqueue *))
2035 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2038 /* First we need some memory for this virtqueue. */
2039 pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
2041 p = get_pages(pages);
2043 /* Initialize the virtqueue */
2045 vq->last_avail_idx = 0;
2049 * This is the routine the service thread will run, and its Process ID
2050 * once it's running.
2052 vq->service = service;
2053 vq->thread = (pid_t)-1;
2055 /* Initialize the configuration. */
2056 vq->config.num = num_descs;
2057 vq->config.irq = devices.next_irq++;
2058 vq->config.pfn = to_guest_phys(p) / getpagesize();
2060 /* Initialize the vring. */
2061 vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
2064 * Append virtqueue to this device's descriptor. We use
2065 * device_config() to get the end of the device's current virtqueues;
2066 * we check that we haven't added any config or feature information
2067 * yet, otherwise we'd be overwriting them.
2069 assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
2070 memcpy(device_config(dev), &vq->config, sizeof(vq->config));
2072 dev->desc->num_vq++;
2074 verbose("Virtqueue page %#lx\n", to_guest_phys(p));
2077 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2080 for (i = &dev->vq; *i; i = &(*i)->next);
2084 static void add_pci_virtqueue(struct device *dev,
2085 void (*service)(struct virtqueue *))
2087 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2089 /* Initialize the virtqueue */
2091 vq->last_avail_idx = 0;
2095 * This is the routine the service thread will run, and its Process ID
2096 * once it's running.
2098 vq->service = service;
2099 vq->thread = (pid_t)-1;
2101 /* Initialize the configuration. */
2102 vq->pci_config.queue_size = VIRTQUEUE_NUM;
2103 vq->pci_config.queue_enable = 0;
2104 vq->pci_config.queue_notify_off = 0;
2106 /* Add one to the number of queues */
2107 vq->dev->mmio->cfg.num_queues++;
2109 /* FIXME: Do irq per virtqueue, not per device. */
2110 vq->config.irq = vq->dev->config.irq_line;
2113 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2116 for (i = &dev->vq; *i; i = &(*i)->next);
2121 * The first half of the feature bitmask is for us to advertise features. The
2122 * second half is for the Guest to accept features.
2124 static void add_feature(struct device *dev, unsigned bit)
2126 u8 *features = get_feature_bits(dev);
2128 /* We can't extend the feature bits once we've added config bytes */
2129 if (dev->desc->feature_len <= bit / CHAR_BIT) {
2130 assert(dev->desc->config_len == 0);
2131 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
2134 features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
2137 static void add_pci_feature(struct device *dev, unsigned bit)
2139 dev->features |= (1ULL << bit);
2143 * This routine sets the configuration fields for an existing device's
2144 * descriptor. It only works for the last device, but that's OK because that's
2147 static void set_config(struct device *dev, unsigned len, const void *conf)
2149 /* Check we haven't overflowed our single page. */
2150 if (device_config(dev) + len > devices.descpage + getpagesize())
2151 errx(1, "Too many devices");
2153 /* Copy in the config information, and store the length. */
2154 memcpy(device_config(dev), conf, len);
2155 dev->desc->config_len = len;
2157 /* Size must fit in config_len field (8 bits)! */
2158 assert(dev->desc->config_len == len);
2161 /* For devices with no config. */
2162 static void no_device_config(struct device *dev)
2164 dev->mmio_addr = get_mmio_region(dev->mmio_size);
2166 dev->config.bar[0] = dev->mmio_addr;
2167 /* Bottom 4 bits must be zero */
2168 assert(~(dev->config.bar[0] & 0xF));
2171 /* This puts the device config into BAR0 */
2172 static void set_device_config(struct device *dev, const void *conf, size_t len)
2175 dev->mmio_size += len;
2176 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2177 memcpy(dev->mmio + 1, conf, len);
2179 /* Hook up device cfg */
2180 dev->config.cfg_access.cap.cap_next
2181 = offsetof(struct pci_config, device);
2183 /* Fix up device cfg field length. */
2184 dev->config.device.length = len;
2186 /* The rest is the same as the no-config case */
2187 no_device_config(dev);
2190 static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2191 size_t bar_offset, size_t bar_bytes, u8 next)
2193 cap->cap_vndr = PCI_CAP_ID_VNDR;
2194 cap->cap_next = next;
2195 cap->cap_len = caplen;
2196 cap->cfg_type = type;
2198 memset(cap->padding, 0, sizeof(cap->padding));
2199 cap->offset = bar_offset;
2200 cap->length = bar_bytes;
2204 * This sets up the pci_config structure, as defined in the virtio 1.0
2205 * standard (and PCI standard).
2207 static void init_pci_config(struct pci_config *pci, u16 type,
2208 u8 class, u8 subclass)
2210 size_t bar_offset, bar_len;
2212 /* Save typing: most thing are happy being zero. */
2213 memset(pci, 0, sizeof(*pci));
2215 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2216 pci->vendor_id = 0x1AF4;
2217 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2218 pci->device_id = 0x1040 + type;
2221 * PCI have specific codes for different types of devices.
2222 * Linux doesn't care, but it's a good clue for people looking
2226 * VIRTIO_ID_CONSOLE: class = 0x07, subclass = 0x00
2227 * VIRTIO_ID_NET: class = 0x02, subclass = 0x00
2228 * VIRTIO_ID_RNG: class = 0xff, subclass = 0
2231 pci->subclass = subclass;
2234 * 4.1.2.1 Non-transitional devices SHOULD have a PCI Revision
2240 * 4.1.2.1 Non-transitional devices SHOULD have a PCI
2241 * Subsystem Device ID of 0x40 or higher.
2243 pci->subsystem_device_id = 0x40;
2245 /* We use our dummy interrupt controller, and irq_line is the irq */
2246 pci->irq_line = devices.next_irq++;
2249 /* Support for extended capabilities. */
2250 pci->status = (1 << 4);
2253 pci->capabilities = offsetof(struct pci_config, common);
2255 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2256 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2257 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2258 bar_offset, bar_len,
2259 offsetof(struct pci_config, notify));
2261 bar_offset += bar_len;
2262 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2263 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2264 init_cap(&pci->notify.cap, sizeof(pci->notify),
2265 VIRTIO_PCI_CAP_NOTIFY_CFG,
2266 bar_offset, bar_len,
2267 offsetof(struct pci_config, isr));
2269 bar_offset += bar_len;
2270 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2271 init_cap(&pci->isr, sizeof(pci->isr),
2272 VIRTIO_PCI_CAP_ISR_CFG,
2273 bar_offset, bar_len,
2274 offsetof(struct pci_config, cfg_access));
2276 /* This doesn't have any presence in the BAR */
2277 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2278 VIRTIO_PCI_CAP_PCI_CFG,
2281 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2282 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2285 * This gets sewn in and length set in set_device_config().
2286 * Some devices don't have a device configuration interface, so
2287 * we never expose this if we don't call set_device_config().
2289 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2294 * This routine does all the creation and setup of a new device, including
2295 * calling new_dev_desc() to allocate the descriptor and device memory. We
2296 * don't actually start the service threads until later.
2298 * See what I mean about userspace being boring?
2300 static struct device *new_device(const char *name, u16 type)
2302 struct device *dev = malloc(sizeof(*dev));
2304 /* Now we populate the fields one at a time. */
2305 dev->desc = new_dev_desc(type);
2308 dev->feature_len = 0;
2310 dev->running = false;
2314 * Append to device list. Prepending to a single-linked list is
2315 * easier, but the user expects the devices to be arranged on the bus
2316 * in command-line order. The first network device on the command line
2317 * is eth0, the first block device /dev/vda, etc.
2319 if (devices.lastdev)
2320 devices.lastdev->next = dev;
2323 devices.lastdev = dev;
2328 static struct device *new_pci_device(const char *name, u16 type,
2329 u8 class, u8 subclass)
2331 struct device *dev = malloc(sizeof(*dev));
2333 /* Now we populate the fields one at a time. */
2337 dev->feature_len = 0;
2339 dev->running = false;
2341 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2342 dev->mmio = calloc(1, dev->mmio_size);
2343 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2344 dev->features_accepted = 0;
2346 if (devices.device_num + 1 >= 32)
2347 errx(1, "Can only handle 31 PCI devices");
2349 init_pci_config(&dev->config, type, class, subclass);
2350 assert(!devices.pci[devices.device_num+1]);
2351 devices.pci[++devices.device_num] = dev;
2357 * Our first setup routine is the console. It's a fairly simple device, but
2358 * UNIX tty handling makes it uglier than it could be.
2360 static void setup_console(void)
2364 /* If we can save the initial standard input settings... */
2365 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2366 struct termios term = orig_term;
2368 * Then we turn off echo, line buffering and ^C etc: We want a
2369 * raw input stream to the Guest.
2371 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2372 tcsetattr(STDIN_FILENO, TCSANOW, &term);
2375 dev = new_device("console", VIRTIO_ID_CONSOLE);
2377 /* We store the console state in dev->priv, and initialize it. */
2378 dev->priv = malloc(sizeof(struct console_abort));
2379 ((struct console_abort *)dev->priv)->count = 0;
2382 * The console needs two virtqueues: the input then the output. When
2383 * they put something the input queue, we make sure we're listening to
2384 * stdin. When they put something in the output queue, we write it to
2387 add_virtqueue(dev, VIRTQUEUE_NUM, console_input);
2388 add_virtqueue(dev, VIRTQUEUE_NUM, console_output);
2390 verbose("device %u: console\n", ++devices.device_num);
2395 * Inter-guest networking is an interesting area. Simplest is to have a
2396 * --sharenet=<name> option which opens or creates a named pipe. This can be
2397 * used to send packets to another guest in a 1:1 manner.
2399 * More sophisticated is to use one of the tools developed for project like UML
2402 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2403 * completely generic ("here's my vring, attach to your vring") and would work
2404 * for any traffic. Of course, namespace and permissions issues need to be
2405 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2406 * multiple inter-guest channels behind one interface, although it would
2407 * require some manner of hotplugging new virtio channels.
2409 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
2412 static u32 str2ip(const char *ipaddr)
2416 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2417 errx(1, "Failed to parse IP address '%s'", ipaddr);
2418 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2421 static void str2mac(const char *macaddr, unsigned char mac[6])
2424 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2425 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2426 errx(1, "Failed to parse mac address '%s'", macaddr);
2436 * This code is "adapted" from libbridge: it attaches the Host end of the
2437 * network device to the bridge device specified by the command line.
2439 * This is yet another James Morris contribution (I'm an IP-level guy, so I
2440 * dislike bridging), and I just try not to break it.
2442 static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2448 errx(1, "must specify bridge name");
2450 ifidx = if_nametoindex(if_name);
2452 errx(1, "interface %s does not exist!", if_name);
2454 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
2455 ifr.ifr_name[IFNAMSIZ-1] = '\0';
2456 ifr.ifr_ifindex = ifidx;
2457 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2458 err(1, "can't add %s to bridge %s", if_name, br_name);
2462 * This sets up the Host end of the network device with an IP address, brings
2463 * it up so packets will flow, the copies the MAC address into the hwaddr
2466 static void configure_device(int fd, const char *tapif, u32 ipaddr)
2469 struct sockaddr_in sin;
2471 memset(&ifr, 0, sizeof(ifr));
2472 strcpy(ifr.ifr_name, tapif);
2474 /* Don't read these incantations. Just cut & paste them like I did! */
2475 sin.sin_family = AF_INET;
2476 sin.sin_addr.s_addr = htonl(ipaddr);
2477 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
2478 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
2479 err(1, "Setting %s interface address", tapif);
2480 ifr.ifr_flags = IFF_UP;
2481 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
2482 err(1, "Bringing interface %s up", tapif);
2485 static int get_tun_device(char tapif[IFNAMSIZ])
2490 /* Start with this zeroed. Messy but sure. */
2491 memset(&ifr, 0, sizeof(ifr));
2494 * We open the /dev/net/tun device and tell it we want a tap device. A
2495 * tap device is like a tun device, only somehow different. To tell
2496 * the truth, I completely blundered my way through this code, but it
2499 netfd = open_or_die("/dev/net/tun", O_RDWR);
2500 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
2501 strcpy(ifr.ifr_name, "tap%d");
2502 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2503 err(1, "configuring /dev/net/tun");
2505 if (ioctl(netfd, TUNSETOFFLOAD,
2506 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2507 err(1, "Could not set features for tun device");
2510 * We don't need checksums calculated for packets coming in this
2513 ioctl(netfd, TUNSETNOCSUM, 1);
2515 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2520 * Our network is a Host<->Guest network. This can either use bridging or
2521 * routing, but the principle is the same: it uses the "tun" device to inject
2522 * packets into the Host as if they came in from a normal network card. We
2523 * just shunt packets between the Guest and the tun device.
2525 static void setup_tun_net(char *arg)
2528 struct net_info *net_info = malloc(sizeof(*net_info));
2530 u32 ip = INADDR_ANY;
2531 bool bridging = false;
2532 char tapif[IFNAMSIZ], *p;
2533 struct virtio_net_config conf;
2535 net_info->tunfd = get_tun_device(tapif);
2537 /* First we create a new network device. */
2538 dev = new_device("net", VIRTIO_ID_NET);
2539 dev->priv = net_info;
2541 /* Network devices need a recv and a send queue, just like console. */
2542 add_virtqueue(dev, VIRTQUEUE_NUM, net_input);
2543 add_virtqueue(dev, VIRTQUEUE_NUM, net_output);
2546 * We need a socket to perform the magic network ioctls to bring up the
2547 * tap interface, connect to the bridge etc. Any socket will do!
2549 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2551 err(1, "opening IP socket");
2553 /* If the command line was --tunnet=bridge:<name> do bridging. */
2554 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
2555 arg += strlen(BRIDGE_PFX);
2559 /* A mac address may follow the bridge name or IP address */
2560 p = strchr(arg, ':');
2562 str2mac(p+1, conf.mac);
2563 add_feature(dev, VIRTIO_NET_F_MAC);
2567 /* arg is now either an IP address or a bridge name */
2569 add_to_bridge(ipfd, tapif, arg);
2573 /* Set up the tun device. */
2574 configure_device(ipfd, tapif, ip);
2576 /* Expect Guest to handle everything except UFO */
2577 add_feature(dev, VIRTIO_NET_F_CSUM);
2578 add_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2579 add_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2580 add_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2581 add_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2582 add_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2583 add_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2584 add_feature(dev, VIRTIO_NET_F_HOST_ECN);
2585 /* We handle indirect ring entries */
2586 add_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2587 /* We're compliant with the damn spec. */
2588 add_feature(dev, VIRTIO_F_ANY_LAYOUT);
2589 set_config(dev, sizeof(conf), &conf);
2591 /* We don't need the socket any more; setup is done. */
2594 devices.device_num++;
2597 verbose("device %u: tun %s attached to bridge: %s\n",
2598 devices.device_num, tapif, arg);
2600 verbose("device %u: tun %s: %s\n",
2601 devices.device_num, tapif, arg);
2605 /* This hangs off device->priv. */
2607 /* The size of the file. */
2610 /* The file descriptor for the file. */
2618 * The disk only has one virtqueue, so it only has one thread. It is really
2619 * simple: the Guest asks for a block number and we read or write that position
2622 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2623 * slow: the Guest waits until the read is finished before running anything
2624 * else, even if it could have been doing useful work.
2626 * We could have used async I/O, except it's reputed to suck so hard that
2627 * characters actually go missing from your code when you try to use it.
2629 static void blk_request(struct virtqueue *vq)
2631 struct vblk_info *vblk = vq->dev->priv;
2632 unsigned int head, out_num, in_num, wlen;
2635 struct virtio_blk_outhdr out;
2636 struct iovec iov[vq->vring.num];
2640 * Get the next request, where we normally wait. It triggers the
2641 * interrupt to acknowledge previously serviced requests (if any).
2643 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
2645 /* Copy the output header from the front of the iov (adjusts iov) */
2646 iov_consume(iov, out_num, &out, sizeof(out));
2648 /* Find and trim end of iov input array, for our status byte. */
2650 for (i = out_num + in_num - 1; i >= out_num; i--) {
2651 if (iov[i].iov_len > 0) {
2652 in = iov[i].iov_base + iov[i].iov_len - 1;
2658 errx(1, "Bad virtblk cmd with no room for status");
2661 * For historical reasons, block operations are expressed in 512 byte
2664 off = out.sector * 512;
2666 if (out.type & VIRTIO_BLK_T_OUT) {
2670 * Move to the right location in the block file. This can fail
2671 * if they try to write past end.
2673 if (lseek64(vblk->fd, off, SEEK_SET) != off)
2674 err(1, "Bad seek to sector %llu", out.sector);
2676 ret = writev(vblk->fd, iov, out_num);
2677 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
2680 * Grr... Now we know how long the descriptor they sent was, we
2681 * make sure they didn't try to write over the end of the block
2682 * file (possibly extending it).
2684 if (ret > 0 && off + ret > vblk->len) {
2685 /* Trim it back to the correct length */
2686 ftruncate64(vblk->fd, vblk->len);
2687 /* Die, bad Guest, die. */
2688 errx(1, "Write past end %llu+%u", off, ret);
2692 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
2693 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
2695 ret = fdatasync(vblk->fd);
2696 verbose("FLUSH fdatasync: %i\n", ret);
2698 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
2703 * Move to the right location in the block file. This can fail
2704 * if they try to read past end.
2706 if (lseek64(vblk->fd, off, SEEK_SET) != off)
2707 err(1, "Bad seek to sector %llu", out.sector);
2709 ret = readv(vblk->fd, iov + out_num, in_num);
2711 wlen = sizeof(*in) + ret;
2712 *in = VIRTIO_BLK_S_OK;
2715 *in = VIRTIO_BLK_S_IOERR;
2719 /* Finished that request. */
2720 add_used(vq, head, wlen);
2723 /*L:198 This actually sets up a virtual block device. */
2724 static void setup_block_file(const char *filename)
2727 struct vblk_info *vblk;
2728 struct virtio_blk_config conf;
2730 /* Create the device. */
2731 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
2733 /* The device has one virtqueue, where the Guest places requests. */
2734 add_pci_virtqueue(dev, blk_request);
2736 /* Allocate the room for our own bookkeeping */
2737 vblk = dev->priv = malloc(sizeof(*vblk));
2739 /* First we open the file and store the length. */
2740 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
2741 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
2743 /* Tell Guest how many sectors this device has. */
2744 conf.capacity = cpu_to_le64(vblk->len / 512);
2747 * Tell Guest not to put in too many descriptors at once: two are used
2748 * for the in and out elements.
2750 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
2751 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2753 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
2755 verbose("device %u: virtblock %llu sectors\n",
2756 devices.device_num, le64_to_cpu(conf.capacity));
2760 * Our random number generator device reads from /dev/urandom into the Guest's
2761 * input buffers. The usual case is that the Guest doesn't want random numbers
2762 * and so has no buffers although /dev/urandom is still readable, whereas
2763 * console is the reverse.
2765 * The same logic applies, however.
2771 static void rng_input(struct virtqueue *vq)
2774 unsigned int head, in_num, out_num, totlen = 0;
2775 struct rng_info *rng_info = vq->dev->priv;
2776 struct iovec iov[vq->vring.num];
2778 /* First we need a buffer from the Guests's virtqueue. */
2779 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
2781 errx(1, "Output buffers in rng?");
2784 * Just like the console write, we loop to cover the whole iovec.
2785 * In this case, short reads actually happen quite a bit.
2787 while (!iov_empty(iov, in_num)) {
2788 len = readv(rng_info->rfd, iov, in_num);
2790 err(1, "Read from /dev/urandom gave %i", len);
2791 iov_consume(iov, in_num, NULL, len);
2795 /* Tell the Guest about the new input. */
2796 add_used(vq, head, totlen);
2800 * This creates a "hardware" random number device for the Guest.
2802 static void setup_rng(void)
2805 struct rng_info *rng_info = malloc(sizeof(*rng_info));
2807 /* Our device's private info simply contains the /dev/urandom fd. */
2808 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
2810 /* Create the new device. */
2811 dev = new_device("rng", VIRTIO_ID_RNG);
2812 dev->priv = rng_info;
2814 /* The device has one virtqueue, where the Guest places inbufs. */
2815 add_virtqueue(dev, VIRTQUEUE_NUM, rng_input);
2817 verbose("device %u: rng\n", devices.device_num++);
2819 /* That's the end of device setup. */
2821 /*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
2822 static void __attribute__((noreturn)) restart_guest(void)
2827 * Since we don't track all open fds, we simply close everything beyond
2830 for (i = 3; i < FD_SETSIZE; i++)
2833 /* Reset all the devices (kills all threads). */
2836 execv(main_args[0], main_args);
2837 err(1, "Could not exec %s", main_args[0]);
2841 * Finally we reach the core of the Launcher which runs the Guest, serves
2842 * its input and output, and finally, lays it to rest.
2844 static void __attribute__((noreturn)) run_guest(void)
2847 struct lguest_pending notify;
2850 /* We read from the /dev/lguest device to run the Guest. */
2851 readval = pread(lguest_fd, ¬ify, sizeof(notify), cpu_id);
2853 /* One unsigned long means the Guest did HCALL_NOTIFY */
2854 if (readval == sizeof(notify)) {
2855 if (notify.trap == 0x1F) {
2856 verbose("Notify on address %#08x\n",
2858 handle_output(notify.addr);
2859 } else if (notify.trap == 13) {
2860 verbose("Emulating instruction at %#x\n",
2862 emulate_insn(notify.insn);
2863 } else if (notify.trap == 14) {
2864 verbose("Emulating MMIO at %#x\n",
2866 emulate_mmio(notify.addr, notify.insn);
2868 errx(1, "Unknown trap %i addr %#08x\n",
2869 notify.trap, notify.addr);
2870 /* ENOENT means the Guest died. Reading tells us why. */
2871 } else if (errno == ENOENT) {
2872 char reason[1024] = { 0 };
2873 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
2874 errx(1, "%s", reason);
2875 /* ERESTART means that we need to reboot the guest */
2876 } else if (errno == ERESTART) {
2878 /* Anything else means a bug or incompatible change. */
2880 err(1, "Running guest failed");
2884 * This is the end of the Launcher. The good news: we are over halfway
2885 * through! The bad news: the most fiendish part of the code still lies ahead
2888 * Are you ready? Take a deep breath and join me in the core of the Host, in
2892 static struct option opts[] = {
2893 { "verbose", 0, NULL, 'v' },
2894 { "tunnet", 1, NULL, 't' },
2895 { "block", 1, NULL, 'b' },
2896 { "rng", 0, NULL, 'r' },
2897 { "initrd", 1, NULL, 'i' },
2898 { "username", 1, NULL, 'u' },
2899 { "chroot", 1, NULL, 'c' },
2902 static void usage(void)
2904 errx(1, "Usage: lguest [--verbose] "
2905 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
2906 "|--block=<filename>|--initrd=<filename>]...\n"
2907 "<mem-in-mb> vmlinux [args...]");
2910 /*L:105 The main routine is where the real work begins: */
2911 int main(int argc, char *argv[])
2913 /* Memory, code startpoint and size of the (optional) initrd. */
2914 unsigned long mem = 0, start, initrd_size = 0;
2915 /* Two temporaries. */
2917 /* The boot information for the Guest. */
2918 struct boot_params *boot;
2919 /* If they specify an initrd file to load. */
2920 const char *initrd_name = NULL;
2922 /* Password structure for initgroups/setres[gu]id */
2923 struct passwd *user_details = NULL;
2925 /* Directory to chroot to */
2926 char *chroot_path = NULL;
2928 /* Save the args: we "reboot" by execing ourselves again. */
2932 * First we initialize the device list. We keep a pointer to the last
2933 * device, and the next interrupt number to use for devices (1:
2934 * remember that 0 is used by the timer).
2936 devices.lastdev = NULL;
2937 devices.next_irq = 1;
2939 /* We're CPU 0. In fact, that's the only CPU possible right now. */
2943 * We need to know how much memory so we can set up the device
2944 * descriptor and memory pages for the devices as we parse the command
2945 * line. So we quickly look through the arguments to find the amount
2948 for (i = 1; i < argc; i++) {
2949 if (argv[i][0] != '-') {
2950 mem = atoi(argv[i]) * 1024 * 1024;
2952 * We start by mapping anonymous pages over all of
2953 * guest-physical memory range. This fills it with 0,
2954 * and ensures that the Guest won't be killed when it
2955 * tries to access it.
2957 guest_base = map_zeroed_pages(mem / getpagesize()
2960 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
2961 devices.descpage = get_pages(1);
2966 /* The options are fairly straight-forward */
2967 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2973 setup_tun_net(optarg);
2976 setup_block_file(optarg);
2982 initrd_name = optarg;
2985 user_details = getpwnam(optarg);
2987 err(1, "getpwnam failed, incorrect username?");
2990 chroot_path = optarg;
2993 warnx("Unknown argument %s", argv[optind]);
2998 * After the other arguments we expect memory and kernel image name,
2999 * followed by command line arguments for the kernel.
3001 if (optind + 2 > argc)
3004 verbose("Guest base is at %p\n", guest_base);
3006 /* We always have a console device */
3009 /* Initialize the (fake) PCI host bridge device. */
3010 init_pci_host_bridge();
3012 /* Now we load the kernel */
3013 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
3015 /* Boot information is stashed at physical address 0 */
3016 boot = from_guest_phys(0);
3018 /* Map the initrd image if requested (at top of physical memory) */
3020 initrd_size = load_initrd(initrd_name, mem);
3022 * These are the location in the Linux boot header where the
3023 * start and size of the initrd are expected to be found.
3025 boot->hdr.ramdisk_image = mem - initrd_size;
3026 boot->hdr.ramdisk_size = initrd_size;
3027 /* The bootloader type 0xFF means "unknown"; that's OK. */
3028 boot->hdr.type_of_loader = 0xFF;
3032 * The Linux boot header contains an "E820" memory map: ours is a
3033 * simple, single region.
3035 boot->e820_entries = 1;
3036 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
3038 * The boot header contains a command line pointer: we put the command
3039 * line after the boot header.
3041 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
3042 /* We use a simple helper to copy the arguments separated by spaces. */
3043 concat((char *)(boot + 1), argv+optind+2);
3045 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3046 boot->hdr.kernel_alignment = 0x1000000;
3048 /* Boot protocol version: 2.07 supports the fields for lguest. */
3049 boot->hdr.version = 0x207;
3051 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
3052 boot->hdr.hardware_subarch = 1;
3054 /* Tell the entry path not to try to reload segment registers. */
3055 boot->hdr.loadflags |= KEEP_SEGMENTS;
3057 /* We tell the kernel to initialize the Guest. */
3060 /* Ensure that we terminate if a device-servicing child dies. */
3061 signal(SIGCHLD, kill_launcher);
3063 /* If we exit via err(), this kills all the threads, restores tty. */
3064 atexit(cleanup_devices);
3066 /* If requested, chroot to a directory */
3068 if (chroot(chroot_path) != 0)
3069 err(1, "chroot(\"%s\") failed", chroot_path);
3071 if (chdir("/") != 0)
3072 err(1, "chdir(\"/\") failed");
3074 verbose("chroot done\n");
3077 /* If requested, drop privileges */
3082 u = user_details->pw_uid;
3083 g = user_details->pw_gid;
3085 if (initgroups(user_details->pw_name, g) != 0)
3086 err(1, "initgroups failed");
3088 if (setresgid(g, g, g) != 0)
3089 err(1, "setresgid failed");
3091 if (setresuid(u, u, u) != 0)
3092 err(1, "setresuid failed");
3094 verbose("Dropping privileges completed\n");
3097 /* Finally, run the Guest. This doesn't return. */
3103 * Mastery is done: you now know everything I do.
3105 * But surely you have seen code, features and bugs in your wanderings which
3106 * you now yearn to attack? That is the real game, and I look forward to you
3107 * patching and forking lguest into the Your-Name-Here-visor.
3109 * Farewell, and good coding!