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_CONFIG_NO_LEGACY
67 #define VIRTIO_PCI_NO_LEGACY
68 #define VIRTIO_BLK_NO_LEGACY
70 /* Use in-kernel ones, which defines VIRTIO_F_VERSION_1 */
71 #include "../../include/uapi/linux/virtio_config.h"
72 #include "../../include/uapi/linux/virtio_net.h"
73 #include "../../include/uapi/linux/virtio_blk.h"
74 #include "../../include/uapi/linux/virtio_console.h"
75 #include "../../include/uapi/linux/virtio_rng.h"
76 #include <linux/virtio_ring.h>
77 #include "../../include/uapi/linux/virtio_pci.h"
78 #include <asm/bootparam.h>
79 #include "../../include/linux/lguest_launcher.h"
81 #define BRIDGE_PFX "bridge:"
83 #define SIOCBRADDIF 0x89a2 /* add interface to bridge */
85 /* We can have up to 256 pages for devices. */
86 #define DEVICE_PAGES 256
87 /* This will occupy 3 pages: it must be a power of 2. */
88 #define VIRTQUEUE_NUM 256
91 * verbose is both a global flag and a macro. The C preprocessor allows
92 * this, and although I wouldn't recommend it, it works quite nicely here.
95 #define verbose(args...) \
96 do { if (verbose) printf(args); } while(0)
99 /* The pointer to the start of guest memory. */
100 static void *guest_base;
101 /* The maximum guest physical address allowed, and maximum possible. */
102 static unsigned long guest_limit, guest_max, guest_mmio;
103 /* The /dev/lguest file descriptor. */
104 static int lguest_fd;
106 /* a per-cpu variable indicating whose vcpu is currently running */
107 static unsigned int __thread cpu_id;
109 /* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
110 #define MAX_PCI_DEVICES 32
112 /* This is our list of devices. */
114 /* Counter to assign interrupt numbers. */
115 unsigned int next_irq;
117 /* Counter to print out convenient device numbers. */
118 unsigned int device_num;
121 struct device *pci[MAX_PCI_DEVICES];
124 /* The list of Guest devices, based on command line arguments. */
125 static struct device_list devices;
127 struct virtio_pci_cfg_cap {
128 struct virtio_pci_cap cap;
129 u32 pci_cfg_data; /* Data for BAR access. */
132 struct virtio_pci_mmio {
133 struct virtio_pci_common_cfg cfg;
137 /* Device-specific configuration follows this. */
140 /* This is the layout (little-endian) of the PCI config space. */
142 u16 vendor_id, device_id;
144 u8 revid, prog_if, subclass, class;
145 u8 cacheline_size, lat_timer, header_type, bist;
148 u16 subsystem_vendor_id, subsystem_device_id;
149 u32 expansion_rom_addr;
150 u8 capabilities, reserved1[3];
152 u8 irq_line, irq_pin, min_grant, max_latency;
154 /* Now, this is the linked capability list. */
155 struct virtio_pci_cap common;
156 struct virtio_pci_notify_cap notify;
157 struct virtio_pci_cap isr;
158 struct virtio_pci_cap device;
159 struct virtio_pci_cfg_cap cfg_access;
162 /* The device structure describes a single device. */
164 /* The name of this device, for --verbose. */
167 /* Any queues attached to this device */
168 struct virtqueue *vq;
170 /* Is it operational */
173 /* Has it written FEATURES_OK but not re-checked it? */
174 bool wrote_features_ok;
176 /* PCI configuration */
178 struct pci_config config;
179 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
182 /* Features we offer, and those accepted. */
183 u64 features, features_accepted;
185 /* Device-specific config hangs off the end of this. */
186 struct virtio_pci_mmio *mmio;
188 /* PCI MMIO resources (all in BAR0) */
192 /* Device-specific data. */
196 /* The virtqueue structure describes a queue attached to a device. */
198 struct virtqueue *next;
200 /* Which device owns me. */
203 /* The actual ring of buffers. */
206 /* The information about this virtqueue (we only use queue_size on) */
207 struct virtio_pci_common_cfg pci_config;
209 /* Last available index we saw. */
212 /* How many are used since we sent last irq? */
213 unsigned int pending_used;
215 /* Eventfd where Guest notifications arrive. */
218 /* Function for the thread which is servicing this virtqueue. */
219 void (*service)(struct virtqueue *vq);
223 /* Remember the arguments to the program so we can "reboot" */
224 static char **main_args;
226 /* The original tty settings to restore on exit. */
227 static struct termios orig_term;
230 * We have to be careful with barriers: our devices are all run in separate
231 * threads and so we need to make sure that changes visible to the Guest happen
234 #define wmb() __asm__ __volatile__("" : : : "memory")
235 #define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
236 #define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
238 /* Wrapper for the last available index. Makes it easier to change. */
239 #define lg_last_avail(vq) ((vq)->last_avail_idx)
242 * The virtio configuration space is defined to be little-endian. x86 is
243 * little-endian too, but it's nice to be explicit so we have these helpers.
245 #define cpu_to_le16(v16) (v16)
246 #define cpu_to_le32(v32) (v32)
247 #define cpu_to_le64(v64) (v64)
248 #define le16_to_cpu(v16) (v16)
249 #define le32_to_cpu(v32) (v32)
250 #define le64_to_cpu(v64) (v64)
252 /* Is this iovec empty? */
253 static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
257 for (i = 0; i < num_iov; i++)
263 /* Take len bytes from the front of this iovec. */
264 static void iov_consume(struct iovec iov[], unsigned num_iov,
265 void *dest, unsigned len)
269 for (i = 0; i < num_iov; i++) {
272 used = iov[i].iov_len < len ? iov[i].iov_len : len;
274 memcpy(dest, iov[i].iov_base, used);
277 iov[i].iov_base += used;
278 iov[i].iov_len -= used;
282 errx(1, "iovec too short!");
286 * The Launcher code itself takes us out into userspace, that scary place where
287 * pointers run wild and free! Unfortunately, like most userspace programs,
288 * it's quite boring (which is why everyone likes to hack on the kernel!).
289 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
290 * you through this section. Or, maybe not.
292 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
293 * memory and stores it in "guest_base". In other words, Guest physical ==
294 * Launcher virtual with an offset.
296 * This can be tough to get your head around, but usually it just means that we
297 * use these trivial conversion functions when the Guest gives us its
298 * "physical" addresses:
300 static void *from_guest_phys(unsigned long addr)
302 return guest_base + addr;
305 static unsigned long to_guest_phys(const void *addr)
307 return (addr - guest_base);
311 * Loading the Kernel.
313 * We start with couple of simple helper routines. open_or_die() avoids
314 * error-checking code cluttering the callers:
316 static int open_or_die(const char *name, int flags)
318 int fd = open(name, flags);
320 err(1, "Failed to open %s", name);
324 /* map_zeroed_pages() takes a number of pages. */
325 static void *map_zeroed_pages(unsigned int num)
327 int fd = open_or_die("/dev/zero", O_RDONLY);
331 * We use a private mapping (ie. if we write to the page, it will be
332 * copied). We allocate an extra two pages PROT_NONE to act as guard
333 * pages against read/write attempts that exceed allocated space.
335 addr = mmap(NULL, getpagesize() * (num+2),
336 PROT_NONE, MAP_PRIVATE, fd, 0);
338 if (addr == MAP_FAILED)
339 err(1, "Mmapping %u pages of /dev/zero", num);
341 if (mprotect(addr + getpagesize(), getpagesize() * num,
342 PROT_READ|PROT_WRITE) == -1)
343 err(1, "mprotect rw %u pages failed", num);
346 * One neat mmap feature is that you can close the fd, and it
351 /* Return address after PROT_NONE page */
352 return addr + getpagesize();
355 /* Get some bytes which won't be mapped into the guest. */
356 static unsigned long get_mmio_region(size_t size)
358 unsigned long addr = guest_mmio;
364 /* Size has to be a power of 2 (and multiple of 16) */
365 for (i = 1; i < size; i <<= 1);
373 * This routine is used to load the kernel or initrd. It tries mmap, but if
374 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
375 * it falls back to reading the memory in.
377 static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
382 * We map writable even though for some segments are marked read-only.
383 * The kernel really wants to be writable: it patches its own
386 * MAP_PRIVATE means that the page won't be copied until a write is
387 * done to it. This allows us to share untouched memory between
390 if (mmap(addr, len, PROT_READ|PROT_WRITE,
391 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
394 /* pread does a seek and a read in one shot: saves a few lines. */
395 r = pread(fd, addr, len, offset);
397 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
401 * This routine takes an open vmlinux image, which is in ELF, and maps it into
402 * the Guest memory. ELF = Embedded Linking Format, which is the format used
403 * by all modern binaries on Linux including the kernel.
405 * The ELF headers give *two* addresses: a physical address, and a virtual
406 * address. We use the physical address; the Guest will map itself to the
409 * We return the starting address.
411 static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
413 Elf32_Phdr phdr[ehdr->e_phnum];
417 * Sanity checks on the main ELF header: an x86 executable with a
418 * reasonable number of correctly-sized program headers.
420 if (ehdr->e_type != ET_EXEC
421 || ehdr->e_machine != EM_386
422 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
423 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
424 errx(1, "Malformed elf header");
427 * An ELF executable contains an ELF header and a number of "program"
428 * headers which indicate which parts ("segments") of the program to
432 /* We read in all the program headers at once: */
433 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
434 err(1, "Seeking to program headers");
435 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
436 err(1, "Reading program headers");
439 * Try all the headers: there are usually only three. A read-only one,
440 * a read-write one, and a "note" section which we don't load.
442 for (i = 0; i < ehdr->e_phnum; i++) {
443 /* If this isn't a loadable segment, we ignore it */
444 if (phdr[i].p_type != PT_LOAD)
447 verbose("Section %i: size %i addr %p\n",
448 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
450 /* We map this section of the file at its physical address. */
451 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
452 phdr[i].p_offset, phdr[i].p_filesz);
455 /* The entry point is given in the ELF header. */
456 return ehdr->e_entry;
460 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
461 * to jump into it and it will unpack itself. We used to have to perform some
462 * hairy magic because the unpacking code scared me.
464 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
465 * a small patch to jump over the tricky bits in the Guest, so now we just read
466 * the funky header so we know where in the file to load, and away we go!
468 static unsigned long load_bzimage(int fd)
470 struct boot_params boot;
472 /* Modern bzImages get loaded at 1M. */
473 void *p = from_guest_phys(0x100000);
476 * Go back to the start of the file and read the header. It should be
477 * a Linux boot header (see Documentation/x86/boot.txt)
479 lseek(fd, 0, SEEK_SET);
480 read(fd, &boot, sizeof(boot));
482 /* Inside the setup_hdr, we expect the magic "HdrS" */
483 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
484 errx(1, "This doesn't look like a bzImage to me");
486 /* Skip over the extra sectors of the header. */
487 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
489 /* Now read everything into memory. in nice big chunks. */
490 while ((r = read(fd, p, 65536)) > 0)
493 /* Finally, code32_start tells us where to enter the kernel. */
494 return boot.hdr.code32_start;
498 * Loading the kernel is easy when it's a "vmlinux", but most kernels
499 * come wrapped up in the self-decompressing "bzImage" format. With a little
500 * work, we can load those, too.
502 static unsigned long load_kernel(int fd)
506 /* Read in the first few bytes. */
507 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
508 err(1, "Reading kernel");
510 /* If it's an ELF file, it starts with "\177ELF" */
511 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
512 return map_elf(fd, &hdr);
514 /* Otherwise we assume it's a bzImage, and try to load it. */
515 return load_bzimage(fd);
519 * This is a trivial little helper to align pages. Andi Kleen hated it because
520 * it calls getpagesize() twice: "it's dumb code."
522 * Kernel guys get really het up about optimization, even when it's not
523 * necessary. I leave this code as a reaction against that.
525 static inline unsigned long page_align(unsigned long addr)
527 /* Add upwards and truncate downwards. */
528 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
532 * An "initial ram disk" is a disk image loaded into memory along with the
533 * kernel which the kernel can use to boot from without needing any drivers.
534 * Most distributions now use this as standard: the initrd contains the code to
535 * load the appropriate driver modules for the current machine.
537 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
538 * kernels. He sent me this (and tells me when I break it).
540 static unsigned long load_initrd(const char *name, unsigned long mem)
546 ifd = open_or_die(name, O_RDONLY);
547 /* fstat() is needed to get the file size. */
548 if (fstat(ifd, &st) < 0)
549 err(1, "fstat() on initrd '%s'", name);
552 * We map the initrd at the top of memory, but mmap wants it to be
553 * page-aligned, so we round the size up for that.
555 len = page_align(st.st_size);
556 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
558 * Once a file is mapped, you can close the file descriptor. It's a
559 * little odd, but quite useful.
562 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
564 /* We return the initrd size. */
570 * Simple routine to roll all the commandline arguments together with spaces
573 static void concat(char *dst, char *args[])
575 unsigned int i, len = 0;
577 for (i = 0; args[i]; i++) {
579 strcat(dst+len, " ");
582 strcpy(dst+len, args[i]);
583 len += strlen(args[i]);
585 /* In case it's empty. */
590 * This is where we actually tell the kernel to initialize the Guest. We
591 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
592 * the base of Guest "physical" memory, the top physical page to allow and the
593 * entry point for the Guest.
595 static void tell_kernel(unsigned long start)
597 unsigned long args[] = { LHREQ_INITIALIZE,
598 (unsigned long)guest_base,
599 guest_limit / getpagesize(), start,
600 (guest_mmio+getpagesize()-1) / getpagesize() };
601 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
602 guest_base, guest_base + guest_limit,
603 guest_limit, guest_mmio);
604 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
605 if (write(lguest_fd, args, sizeof(args)) < 0)
606 err(1, "Writing to /dev/lguest");
613 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
614 * We need to make sure it's not trying to reach into the Launcher itself, so
615 * we have a convenient routine which checks it and exits with an error message
616 * if something funny is going on:
618 static void *_check_pointer(unsigned long addr, unsigned int size,
622 * Check if the requested address and size exceeds the allocated memory,
623 * or addr + size wraps around.
625 if ((addr + size) > guest_limit || (addr + size) < addr)
626 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
628 * We return a pointer for the caller's convenience, now we know it's
631 return from_guest_phys(addr);
633 /* A macro which transparently hands the line number to the real function. */
634 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
637 * Each buffer in the virtqueues is actually a chain of descriptors. This
638 * function returns the next descriptor in the chain, or vq->vring.num if we're
641 static unsigned next_desc(struct vring_desc *desc,
642 unsigned int i, unsigned int max)
646 /* If this descriptor says it doesn't chain, we're done. */
647 if (!(desc[i].flags & VRING_DESC_F_NEXT))
650 /* Check they're not leading us off end of descriptors. */
652 /* Make sure compiler knows to grab that: we don't want it changing! */
656 errx(1, "Desc next is %u", next);
662 * This actually sends the interrupt for this virtqueue, if we've used a
665 static void trigger_irq(struct virtqueue *vq)
667 unsigned long buf[] = { LHREQ_IRQ, vq->dev->config.irq_line };
669 /* Don't inform them if nothing used. */
670 if (!vq->pending_used)
672 vq->pending_used = 0;
677 * If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
678 * The driver MUST set flags to 0 or 1.
680 if (vq->vring.avail->flags > 1)
681 errx(1, "%s: avail->flags = %u\n",
682 vq->dev->name, vq->vring.avail->flags);
687 * If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
689 * - The device MUST ignore the used_event value.
690 * - After the device writes a descriptor index into the used ring:
691 * - If flags is 1, the device SHOULD NOT send an interrupt.
692 * - If flags is 0, the device MUST send an interrupt.
694 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
701 * If MSI-X capability is disabled, the device MUST set the Queue
702 * Interrupt bit in ISR status before sending a virtqueue notification
705 vq->dev->mmio->isr = 0x1;
707 /* Send the Guest an interrupt tell them we used something up. */
708 if (write(lguest_fd, buf, sizeof(buf)) != 0)
709 err(1, "Triggering irq %i", vq->dev->config.irq_line);
713 * This looks in the virtqueue for the first available buffer, and converts
714 * it to an iovec for convenient access. Since descriptors consist of some
715 * number of output then some number of input descriptors, it's actually two
716 * iovecs, but we pack them into one and note how many of each there were.
718 * This function waits if necessary, and returns the descriptor number found.
720 static unsigned wait_for_vq_desc(struct virtqueue *vq,
722 unsigned int *out_num, unsigned int *in_num)
724 unsigned int i, head, max;
725 struct vring_desc *desc;
726 u16 last_avail = lg_last_avail(vq);
731 * The driver MUST handle spurious interrupts from the device.
733 * That's why this is a while loop.
736 /* There's nothing available? */
737 while (last_avail == vq->vring.avail->idx) {
741 * Since we're about to sleep, now is a good time to tell the
742 * Guest about what we've used up to now.
746 /* OK, now we need to know about added descriptors. */
747 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
750 * They could have slipped one in as we were doing that: make
751 * sure it's written, then check again.
754 if (last_avail != vq->vring.avail->idx) {
755 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
759 /* Nothing new? Wait for eventfd to tell us they refilled. */
760 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
761 errx(1, "Event read failed?");
763 /* We don't need to be notified again. */
764 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
767 /* Check it isn't doing very strange things with descriptor numbers. */
768 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
769 errx(1, "Guest moved used index from %u to %u",
770 last_avail, vq->vring.avail->idx);
773 * Make sure we read the descriptor number *after* we read the ring
774 * update; don't let the cpu or compiler change the order.
779 * Grab the next descriptor number they're advertising, and increment
780 * the index we've seen.
782 head = vq->vring.avail->ring[last_avail % vq->vring.num];
785 /* If their number is silly, that's a fatal mistake. */
786 if (head >= vq->vring.num)
787 errx(1, "Guest says index %u is available", head);
789 /* When we start there are none of either input nor output. */
790 *out_num = *in_num = 0;
793 desc = vq->vring.desc;
797 * We have to read the descriptor after we read the descriptor number,
798 * but there's a data dependency there so the CPU shouldn't reorder
799 * that: no rmb() required.
804 * If this is an indirect entry, then this buffer contains a
805 * descriptor table which we handle as if it's any normal
808 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
811 * The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
812 * flag unless the VIRTIO_F_INDIRECT_DESC feature was
815 if (!(vq->dev->features_accepted &
816 (1<<VIRTIO_RING_F_INDIRECT_DESC)))
817 errx(1, "%s: vq indirect not negotiated",
823 * The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
824 * flag within an indirect descriptor (ie. only one
825 * table per descriptor).
827 if (desc != vq->vring.desc)
828 errx(1, "%s: Indirect within indirect",
832 * Proposed update VIRTIO-134 spells this out:
834 * A driver MUST NOT set both VIRTQ_DESC_F_INDIRECT
835 * and VIRTQ_DESC_F_NEXT in flags.
837 if (desc[i].flags & VRING_DESC_F_NEXT)
838 errx(1, "%s: indirect and next together",
841 if (desc[i].len % sizeof(struct vring_desc))
842 errx(1, "Invalid size for indirect buffer table");
846 * The device MUST ignore the write-only flag
847 * (flags&VIRTQ_DESC_F_WRITE) in the descriptor that
848 * refers to an indirect table.
850 * We ignore it here: :)
853 max = desc[i].len / sizeof(struct vring_desc);
854 desc = check_pointer(desc[i].addr, desc[i].len);
859 * A driver MUST NOT create a descriptor chain longer
860 * than the Queue Size of the device.
862 if (max > vq->pci_config.queue_size)
863 errx(1, "%s: indirect has too many entries",
867 /* Grab the first descriptor, and check it's OK. */
868 iov[*out_num + *in_num].iov_len = desc[i].len;
869 iov[*out_num + *in_num].iov_base
870 = check_pointer(desc[i].addr, desc[i].len);
871 /* If this is an input descriptor, increment that count. */
872 if (desc[i].flags & VRING_DESC_F_WRITE)
876 * If it's an output descriptor, they're all supposed
877 * to come before any input descriptors.
880 errx(1, "Descriptor has out after in");
884 /* If we've got too many, that implies a descriptor loop. */
885 if (*out_num + *in_num > max)
886 errx(1, "Looped descriptor");
887 } while ((i = next_desc(desc, i, max)) != max);
893 * After we've used one of their buffers, we tell the Guest about it. Sometime
894 * later we'll want to send them an interrupt using trigger_irq(); note that
895 * wait_for_vq_desc() does that for us if it has to wait.
897 static void add_used(struct virtqueue *vq, unsigned int head, int len)
899 struct vring_used_elem *used;
902 * The virtqueue contains a ring of used buffers. Get a pointer to the
903 * next entry in that used ring.
905 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
908 /* Make sure buffer is written before we update index. */
910 vq->vring.used->idx++;
914 /* And here's the combo meal deal. Supersize me! */
915 static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
917 add_used(vq, head, len);
924 * We associate some data with the console for our exit hack.
926 struct console_abort {
927 /* How many times have they hit ^C? */
929 /* When did they start? */
930 struct timeval start;
933 /* This is the routine which handles console input (ie. stdin). */
934 static void console_input(struct virtqueue *vq)
937 unsigned int head, in_num, out_num;
938 struct console_abort *abort = vq->dev->priv;
939 struct iovec iov[vq->vring.num];
941 /* Make sure there's a descriptor available. */
942 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
944 errx(1, "Output buffers in console in queue?");
946 /* Read into it. This is where we usually wait. */
947 len = readv(STDIN_FILENO, iov, in_num);
949 /* Ran out of input? */
950 warnx("Failed to get console input, ignoring console.");
952 * For simplicity, dying threads kill the whole Launcher. So
959 /* Tell the Guest we used a buffer. */
960 add_used_and_trigger(vq, head, len);
963 * Three ^C within one second? Exit.
965 * This is such a hack, but works surprisingly well. Each ^C has to
966 * be in a buffer by itself, so they can't be too fast. But we check
967 * that we get three within about a second, so they can't be too
970 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
976 if (abort->count == 1)
977 gettimeofday(&abort->start, NULL);
978 else if (abort->count == 3) {
980 gettimeofday(&now, NULL);
981 /* Kill all Launcher processes with SIGINT, like normal ^C */
982 if (now.tv_sec <= abort->start.tv_sec+1)
988 /* This is the routine which handles console output (ie. stdout). */
989 static void console_output(struct virtqueue *vq)
991 unsigned int head, out, in;
992 struct iovec iov[vq->vring.num];
994 /* We usually wait in here, for the Guest to give us something. */
995 head = wait_for_vq_desc(vq, iov, &out, &in);
997 errx(1, "Input buffers in console output queue?");
999 /* writev can return a partial write, so we loop here. */
1000 while (!iov_empty(iov, out)) {
1001 int len = writev(STDOUT_FILENO, iov, out);
1003 warn("Write to stdout gave %i (%d)", len, errno);
1006 iov_consume(iov, out, NULL, len);
1010 * We're finished with that buffer: if we're going to sleep,
1011 * wait_for_vq_desc() will prod the Guest with an interrupt.
1013 add_used(vq, head, 0);
1019 * Handling output for network is also simple: we get all the output buffers
1020 * and write them to /dev/net/tun.
1026 static void net_output(struct virtqueue *vq)
1028 struct net_info *net_info = vq->dev->priv;
1029 unsigned int head, out, in;
1030 struct iovec iov[vq->vring.num];
1032 /* We usually wait in here for the Guest to give us a packet. */
1033 head = wait_for_vq_desc(vq, iov, &out, &in);
1035 errx(1, "Input buffers in net output queue?");
1037 * Send the whole thing through to /dev/net/tun. It expects the exact
1038 * same format: what a coincidence!
1040 if (writev(net_info->tunfd, iov, out) < 0)
1041 warnx("Write to tun failed (%d)?", errno);
1044 * Done with that one; wait_for_vq_desc() will send the interrupt if
1045 * all packets are processed.
1047 add_used(vq, head, 0);
1051 * Handling network input is a bit trickier, because I've tried to optimize it.
1053 * First we have a helper routine which tells is if from this file descriptor
1054 * (ie. the /dev/net/tun device) will block:
1056 static bool will_block(int fd)
1059 struct timeval zero = { 0, 0 };
1062 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
1066 * This handles packets coming in from the tun device to our Guest. Like all
1067 * service routines, it gets called again as soon as it returns, so you don't
1068 * see a while(1) loop here.
1070 static void net_input(struct virtqueue *vq)
1073 unsigned int head, out, in;
1074 struct iovec iov[vq->vring.num];
1075 struct net_info *net_info = vq->dev->priv;
1078 * Get a descriptor to write an incoming packet into. This will also
1079 * send an interrupt if they're out of descriptors.
1081 head = wait_for_vq_desc(vq, iov, &out, &in);
1083 errx(1, "Output buffers in net input queue?");
1086 * If it looks like we'll block reading from the tun device, send them
1089 if (vq->pending_used && will_block(net_info->tunfd))
1093 * Read in the packet. This is where we normally wait (when there's no
1094 * incoming network traffic).
1096 len = readv(net_info->tunfd, iov, in);
1098 warn("Failed to read from tun (%d).", errno);
1101 * Mark that packet buffer as used, but don't interrupt here. We want
1102 * to wait until we've done as much work as we can.
1104 add_used(vq, head, len);
1108 /* This is the helper to create threads: run the service routine in a loop. */
1109 static int do_thread(void *_vq)
1111 struct virtqueue *vq = _vq;
1119 * When a child dies, we kill our entire process group with SIGTERM. This
1120 * also has the side effect that the shell restores the console for us!
1122 static void kill_launcher(int signal)
1127 static void reset_vq_pci_config(struct virtqueue *vq)
1129 vq->pci_config.queue_size = VIRTQUEUE_NUM;
1130 vq->pci_config.queue_enable = 0;
1133 static void reset_device(struct device *dev)
1135 struct virtqueue *vq;
1137 verbose("Resetting device %s\n", dev->name);
1139 /* Clear any features they've acked. */
1140 dev->features_accepted = 0;
1142 /* We're going to be explicitly killing threads, so ignore them. */
1143 signal(SIGCHLD, SIG_IGN);
1148 * The device MUST present a 0 in queue_enable on reset.
1150 * This means we set it here, and reset the saved ones in every vq.
1152 dev->mmio->cfg.queue_enable = 0;
1154 /* Get rid of the virtqueue threads */
1155 for (vq = dev->vq; vq; vq = vq->next) {
1156 vq->last_avail_idx = 0;
1157 reset_vq_pci_config(vq);
1158 if (vq->thread != (pid_t)-1) {
1159 kill(vq->thread, SIGTERM);
1160 waitpid(vq->thread, NULL, 0);
1161 vq->thread = (pid_t)-1;
1164 dev->running = false;
1165 dev->wrote_features_ok = false;
1167 /* Now we care if threads die. */
1168 signal(SIGCHLD, (void *)kill_launcher);
1171 static void cleanup_devices(void)
1175 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1176 struct device *d = devices.pci[i];
1182 /* If we saved off the original terminal settings, restore them now. */
1183 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1184 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
1188 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1192 /* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1193 static struct device pci_host_bridge;
1195 static void init_pci_host_bridge(void)
1197 pci_host_bridge.name = "PCI Host Bridge";
1198 pci_host_bridge.config.class = 0x06; /* bridge */
1199 pci_host_bridge.config.subclass = 0; /* host bridge */
1200 devices.pci[0] = &pci_host_bridge;
1203 /* The IO ports used to read the PCI config space. */
1204 #define PCI_CONFIG_ADDR 0xCF8
1205 #define PCI_CONFIG_DATA 0xCFC
1208 * Not really portable, but does help readability: this is what the Guest
1209 * writes to the PCI_CONFIG_ADDR IO port.
1211 union pci_config_addr {
1215 unsigned funcnum: 3;
1218 unsigned reserved: 7;
1219 unsigned enabled : 1;
1225 * We cache what they wrote to the address port, so we know what they're
1226 * talking about when they access the data port.
1228 static union pci_config_addr pci_config_addr;
1230 static struct device *find_pci_device(unsigned int index)
1232 return devices.pci[index];
1235 /* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1236 static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1239 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1240 *val = (v >> (off * 8)) & mask;
1243 /* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1244 static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1247 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1248 *dst &= ~(mask << (off * 8));
1249 *dst |= (v & mask) << (off * 8);
1253 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1256 static struct device *dev_and_reg(u32 *reg)
1258 if (!pci_config_addr.bits.enabled)
1261 if (pci_config_addr.bits.funcnum != 0)
1264 if (pci_config_addr.bits.busnum != 0)
1267 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1270 *reg = pci_config_addr.bits.offset;
1271 return find_pci_device(pci_config_addr.bits.devnum);
1275 * We can get invalid combinations of values while they're writing, so we
1276 * only fault if they try to write with some invalid bar/offset/length.
1278 static bool valid_bar_access(struct device *d,
1279 struct virtio_pci_cfg_cap *cfg_access)
1281 /* We only have 1 bar (BAR0) */
1282 if (cfg_access->cap.bar != 0)
1285 /* Check it's within BAR0. */
1286 if (cfg_access->cap.offset >= d->mmio_size
1287 || cfg_access->cap.offset + cfg_access->cap.length > d->mmio_size)
1290 /* Check length is 1, 2 or 4. */
1291 if (cfg_access->cap.length != 1
1292 && cfg_access->cap.length != 2
1293 && cfg_access->cap.length != 4)
1299 * The driver MUST NOT write a cap.offset which is not a multiple of
1300 * cap.length (ie. all accesses MUST be aligned).
1302 if (cfg_access->cap.offset % cfg_access->cap.length != 0)
1305 /* Return pointer into word in BAR0. */
1309 /* Is this accessing the PCI config address port?. */
1310 static bool is_pci_addr_port(u16 port)
1312 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1315 static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1317 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1318 &pci_config_addr.val);
1319 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1320 pci_config_addr.bits.enabled ? "" : " DISABLED",
1322 pci_config_addr.bits.busnum,
1323 pci_config_addr.bits.devnum,
1324 pci_config_addr.bits.funcnum,
1325 pci_config_addr.bits.offset);
1329 static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1331 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1334 /* Is this accessing the PCI config data port?. */
1335 static bool is_pci_data_port(u16 port)
1337 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1340 static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask);
1342 static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1345 struct device *d = dev_and_reg(®);
1347 /* Complain if they don't belong to a device. */
1351 /* They can do 1 byte writes, etc. */
1352 portoff = port - PCI_CONFIG_DATA;
1355 * PCI uses a weird way to determine the BAR size: the OS
1356 * writes all 1's, and sees which ones stick.
1358 if (&d->config_words[reg] == &d->config.bar[0]) {
1361 iowrite(portoff, val, mask, &d->config.bar[0]);
1362 for (i = 0; (1 << i) < d->mmio_size; i++)
1363 d->config.bar[0] &= ~(1 << i);
1365 } else if ((&d->config_words[reg] > &d->config.bar[0]
1366 && &d->config_words[reg] <= &d->config.bar[6])
1367 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1368 /* Allow writing to any other BAR, or expansion ROM */
1369 iowrite(portoff, val, mask, &d->config_words[reg]);
1371 /* We let them overide latency timer and cacheline size */
1372 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1373 /* Only let them change the first two fields. */
1374 if (mask == 0xFFFFFFFF)
1376 iowrite(portoff, val, mask, &d->config_words[reg]);
1378 } else if (&d->config_words[reg] == (void *)&d->config.command
1379 && mask == 0xFFFF) {
1380 /* Ignore command writes. */
1382 } else if (&d->config_words[reg]
1383 == (void *)&d->config.cfg_access.cap.bar
1384 || &d->config_words[reg]
1385 == &d->config.cfg_access.cap.length
1386 || &d->config_words[reg]
1387 == &d->config.cfg_access.cap.offset) {
1390 * The VIRTIO_PCI_CAP_PCI_CFG capability
1391 * provides a backdoor to access the MMIO
1392 * regions without mapping them. Weird, but
1395 iowrite(portoff, val, mask, &d->config_words[reg]);
1397 } else if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
1403 * Upon detecting driver write access to pci_cfg_data, the
1404 * device MUST execute a write access at offset cap.offset at
1405 * BAR selected by cap.bar using the first cap.length bytes
1406 * from pci_cfg_data.
1410 if (!valid_bar_access(d, &d->config.cfg_access))
1413 iowrite(portoff, val, mask, &d->config.cfg_access.pci_cfg_data);
1416 * Now emulate a write. The mask we use is set by
1417 * len, *not* this write!
1419 write_mask = (1ULL<<(8*d->config.cfg_access.cap.length)) - 1;
1420 verbose("Window writing %#x/%#x to bar %u, offset %u len %u\n",
1421 d->config.cfg_access.pci_cfg_data, write_mask,
1422 d->config.cfg_access.cap.bar,
1423 d->config.cfg_access.cap.offset,
1424 d->config.cfg_access.cap.length);
1426 emulate_mmio_write(d, d->config.cfg_access.cap.offset,
1427 d->config.cfg_access.pci_cfg_data,
1435 * The driver MUST NOT write into any field of the capability
1436 * structure, with the exception of those with cap_type
1437 * VIRTIO_PCI_CAP_PCI_CFG...
1442 static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask);
1444 static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1447 struct device *d = dev_and_reg(®);
1452 /* Read through the PCI MMIO access window is special */
1453 if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
1459 * Upon detecting driver read access to pci_cfg_data, the
1460 * device MUST execute a read access of length cap.length at
1461 * offset cap.offset at BAR selected by cap.bar and store the
1462 * first cap.length bytes in pci_cfg_data.
1465 if (!valid_bar_access(d, &d->config.cfg_access))
1466 errx(1, "Invalid cfg_access to bar%u, offset %u len %u",
1467 d->config.cfg_access.cap.bar,
1468 d->config.cfg_access.cap.offset,
1469 d->config.cfg_access.cap.length);
1472 * Read into the window. The mask we use is set by
1473 * len, *not* this read!
1475 read_mask = (1ULL<<(8*d->config.cfg_access.cap.length))-1;
1476 d->config.cfg_access.pci_cfg_data
1477 = emulate_mmio_read(d,
1478 d->config.cfg_access.cap.offset,
1480 verbose("Window read %#x/%#x from bar %u, offset %u len %u\n",
1481 d->config.cfg_access.pci_cfg_data, read_mask,
1482 d->config.cfg_access.cap.bar,
1483 d->config.cfg_access.cap.offset,
1484 d->config.cfg_access.cap.length);
1486 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1490 * This is where we emulate a handful of Guest instructions. It's ugly
1491 * and we used to do it in the kernel but it grew over time.
1495 * We use the ptrace syscall's pt_regs struct to talk about registers
1496 * to lguest: these macros convert the names to the offsets.
1498 #define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1499 #define setreg(name, val) \
1500 setreg_off(offsetof(struct user_regs_struct, name), (val))
1502 static u32 getreg_off(size_t offset)
1505 unsigned long args[] = { LHREQ_GETREG, offset };
1507 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1508 err(1, "Getting register %u", offset);
1509 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1510 err(1, "Reading register %u", offset);
1515 static void setreg_off(size_t offset, u32 val)
1517 unsigned long args[] = { LHREQ_SETREG, offset, val };
1519 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1520 err(1, "Setting register %u", offset);
1523 /* Get register by instruction encoding */
1524 static u32 getreg_num(unsigned regnum, u32 mask)
1526 /* 8 bit ops use regnums 4-7 for high parts of word */
1527 if (mask == 0xFF && (regnum & 0x4))
1528 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1531 case 0: return getreg(eax) & mask;
1532 case 1: return getreg(ecx) & mask;
1533 case 2: return getreg(edx) & mask;
1534 case 3: return getreg(ebx) & mask;
1535 case 4: return getreg(esp) & mask;
1536 case 5: return getreg(ebp) & mask;
1537 case 6: return getreg(esi) & mask;
1538 case 7: return getreg(edi) & mask;
1543 /* Set register by instruction encoding */
1544 static void setreg_num(unsigned regnum, u32 val, u32 mask)
1546 /* Don't try to set bits out of range */
1547 assert(~(val & ~mask));
1549 /* 8 bit ops use regnums 4-7 for high parts of word */
1550 if (mask == 0xFF && (regnum & 0x4)) {
1551 /* Construct the 16 bits we want. */
1552 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1553 setreg_num(regnum & 0x3, val, 0xFFFF);
1558 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1559 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1560 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1561 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1562 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1563 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1564 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1565 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1570 /* Get bytes of displacement appended to instruction, from r/m encoding */
1571 static u32 insn_displacement_len(u8 mod_reg_rm)
1573 /* Switch on the mod bits */
1574 switch (mod_reg_rm >> 6) {
1576 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1577 if ((mod_reg_rm & 0x7) == 0x5)
1579 /* Normally, mod == 0 means no literal displacement */
1582 /* One byte displacement */
1585 /* Four byte displacement */
1594 static void emulate_insn(const u8 insn[])
1596 unsigned long args[] = { LHREQ_TRAP, 13 };
1597 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1598 unsigned int eax, port, mask;
1600 * Default is to return all-ones on IO port reads, which traditionally
1601 * means "there's nothing there".
1603 u32 val = 0xFFFFFFFF;
1606 * This must be the Guest kernel trying to do something, not userspace!
1607 * The bottom two bits of the CS segment register are the privilege
1610 if ((getreg(xcs) & 3) != 0x1)
1613 /* Decoding x86 instructions is icky. */
1616 * Around 2.6.33, the kernel started using an emulation for the
1617 * cmpxchg8b instruction in early boot on many configurations. This
1618 * code isn't paravirtualized, and it tries to disable interrupts.
1619 * Ignore it, which will Mostly Work.
1621 if (insn[insnlen] == 0xfa) {
1622 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1628 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1630 if (insn[insnlen] == 0x66) {
1632 /* The instruction is 1 byte so far, read the next byte. */
1636 /* If the lower bit isn't set, it's a single byte access */
1637 byte_access = !(insn[insnlen] & 1);
1640 * Now we can ignore the lower bit and decode the 4 opcodes
1641 * we need to emulate.
1643 switch (insn[insnlen] & 0xFE) {
1644 case 0xE4: /* in <next byte>,%al */
1645 port = insn[insnlen+1];
1649 case 0xEC: /* in (%dx),%al */
1650 port = getreg(edx) & 0xFFFF;
1654 case 0xE6: /* out %al,<next byte> */
1655 port = insn[insnlen+1];
1658 case 0xEE: /* out %al,(%dx) */
1659 port = getreg(edx) & 0xFFFF;
1663 /* OK, we don't know what this is, can't emulate. */
1667 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1670 else if (small_operand)
1676 * If it was an "IN" instruction, they expect the result to be read
1677 * into %eax, so we change %eax.
1682 /* This is the PS/2 keyboard status; 1 means ready for output */
1685 else if (is_pci_addr_port(port))
1686 pci_addr_ioread(port, mask, &val);
1687 else if (is_pci_data_port(port))
1688 pci_data_ioread(port, mask, &val);
1690 /* Clear the bits we're about to read */
1692 /* Copy bits in from val. */
1694 /* Now update the register. */
1697 if (is_pci_addr_port(port)) {
1698 if (!pci_addr_iowrite(port, mask, eax))
1700 } else if (is_pci_data_port(port)) {
1701 if (!pci_data_iowrite(port, mask, eax))
1704 /* There are many other ports, eg. CMOS clock, serial
1705 * and parallel ports, so we ignore them all. */
1708 verbose("IO %s of %x to %u: %#08x\n",
1709 in ? "IN" : "OUT", mask, port, eax);
1711 /* Finally, we've "done" the instruction, so move past it. */
1712 setreg(eip, getreg(eip) + insnlen);
1716 warnx("Attempt to %s port %u (%#x mask)",
1717 in ? "read from" : "write to", port, mask);
1720 /* Inject trap into Guest. */
1721 if (write(lguest_fd, args, sizeof(args)) < 0)
1722 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1725 static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1729 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1730 struct device *d = devices.pci[i];
1734 if (paddr < d->mmio_addr)
1736 if (paddr >= d->mmio_addr + d->mmio_size)
1738 *off = paddr - d->mmio_addr;
1744 /* FIXME: Use vq array. */
1745 static struct virtqueue *vq_by_num(struct device *d, u32 num)
1747 struct virtqueue *vq = d->vq;
1755 static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1756 struct virtqueue *vq)
1758 vq->pci_config = *cfg;
1761 static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1762 struct virtqueue *vq)
1764 /* Only restore the per-vq part */
1765 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1767 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1768 sizeof(*cfg) - off);
1774 * The driver MUST configure the other virtqueue fields before
1775 * enabling the virtqueue with queue_enable.
1777 * When they enable the virtqueue, we check that their setup is valid.
1779 static void check_virtqueue(struct device *d, struct virtqueue *vq)
1781 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1782 if (vq->pci_config.queue_desc_hi
1783 || vq->pci_config.queue_avail_hi
1784 || vq->pci_config.queue_used_hi)
1785 errx(1, "%s: invalid 64-bit queue address", d->name);
1790 * The driver MUST ensure that the physical address of the first byte
1791 * of each virtqueue part is a multiple of the specified alignment
1792 * value in the above table.
1794 if (vq->pci_config.queue_desc_lo % 16
1795 || vq->pci_config.queue_avail_lo % 2
1796 || vq->pci_config.queue_used_lo % 4)
1797 errx(1, "%s: invalid alignment in queue addresses", d->name);
1799 /* Initialize the virtqueue and check they're all in range. */
1800 vq->vring.num = vq->pci_config.queue_size;
1801 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1802 sizeof(*vq->vring.desc) * vq->vring.num);
1803 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1804 sizeof(*vq->vring.avail)
1805 + (sizeof(vq->vring.avail->ring[0])
1807 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1808 sizeof(*vq->vring.used)
1809 + (sizeof(vq->vring.used->ring[0])
1815 * The driver MUST initialize flags in the used ring to 0
1816 * when allocating the used ring.
1818 if (vq->vring.used->flags != 0)
1819 errx(1, "%s: invalid initial used.flags %#x",
1820 d->name, vq->vring.used->flags);
1823 static void start_virtqueue(struct virtqueue *vq)
1826 * Create stack for thread. Since the stack grows upwards, we point
1827 * the stack pointer to the end of this region.
1829 char *stack = malloc(32768);
1831 /* Create a zero-initialized eventfd. */
1832 vq->eventfd = eventfd(0, 0);
1833 if (vq->eventfd < 0)
1834 err(1, "Creating eventfd");
1837 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1838 * we get a signal if it dies.
1840 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1841 if (vq->thread == (pid_t)-1)
1842 err(1, "Creating clone");
1845 static void start_virtqueues(struct device *d)
1847 struct virtqueue *vq;
1849 for (vq = d->vq; vq; vq = vq->next) {
1850 if (vq->pci_config.queue_enable)
1851 start_virtqueue(vq);
1855 static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1857 struct virtqueue *vq;
1860 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1864 * The device MUST present the feature bits it is offering in
1865 * device_feature, starting at bit device_feature_select ∗ 32
1866 * for any device_feature_select written by the driver
1869 d->mmio->cfg.device_feature = d->features;
1871 d->mmio->cfg.device_feature = (d->features >> 32);
1873 d->mmio->cfg.device_feature = 0;
1874 goto feature_write_through32;
1875 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1877 errx(1, "%s: Unexpected driver select %u",
1879 goto feature_write_through32;
1880 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1881 if (d->mmio->cfg.guest_feature_select == 0) {
1882 d->features_accepted &= ~((u64)0xFFFFFFFF);
1883 d->features_accepted |= val;
1885 assert(d->mmio->cfg.guest_feature_select == 1);
1886 d->features_accepted &= 0xFFFFFFFF;
1887 d->features_accepted |= ((u64)val) << 32;
1892 * The driver MUST NOT accept a feature which the device did
1895 if (d->features_accepted & ~d->features)
1896 errx(1, "%s: over-accepted features %#llx of %#llx",
1897 d->name, d->features_accepted, d->features);
1898 goto feature_write_through32;
1899 case offsetof(struct virtio_pci_mmio, cfg.device_status): {
1902 verbose("%s: device status -> %#x\n", d->name, val);
1906 * The device MUST reset when 0 is written to device_status,
1907 * and present a 0 in device_status once that is done.
1911 goto write_through8;
1914 /* 2.1.1: The driver MUST NOT clear a device status bit. */
1915 if (d->mmio->cfg.device_status & ~val)
1916 errx(1, "%s: unset of device status bit %#x -> %#x",
1917 d->name, d->mmio->cfg.device_status, val);
1922 * The device MUST NOT consume buffers or notify the driver
1925 if (val & VIRTIO_CONFIG_S_DRIVER_OK
1926 && !(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
1927 start_virtqueues(d);
1932 * The driver MUST follow this sequence to initialize a device:
1933 * - Reset the device.
1934 * - Set the ACKNOWLEDGE status bit: the guest OS has
1935 * notice the device.
1936 * - Set the DRIVER status bit: the guest OS knows how
1937 * to drive the device.
1938 * - Read device feature bits, and write the subset
1939 * of feature bits understood by the OS and driver
1940 * to the device. During this step the driver MAY
1941 * read (but MUST NOT write) the device-specific
1942 * configuration fields to check that it can
1943 * support the device before accepting it.
1944 * - Set the FEATURES_OK status bit. The driver
1945 * MUST not accept new feature bits after this
1947 * - Re-read device status to ensure the FEATURES_OK
1948 * bit is still set: otherwise, the device does
1949 * not support our subset of features and the
1950 * device is unusable.
1951 * - Perform device-specific setup, including
1952 * discovery of virtqueues for the device,
1953 * optional per-bus setup, reading and possibly
1954 * writing the device’s virtio configuration
1955 * space, and population of virtqueues.
1956 * - Set the DRIVER_OK status bit. At this point the
1960 switch (val & ~d->mmio->cfg.device_status) {
1961 case VIRTIO_CONFIG_S_DRIVER_OK:
1962 prev |= VIRTIO_CONFIG_S_FEATURES_OK; /* fall thru */
1963 case VIRTIO_CONFIG_S_FEATURES_OK:
1964 prev |= VIRTIO_CONFIG_S_DRIVER; /* fall thru */
1965 case VIRTIO_CONFIG_S_DRIVER:
1966 prev |= VIRTIO_CONFIG_S_ACKNOWLEDGE; /* fall thru */
1967 case VIRTIO_CONFIG_S_ACKNOWLEDGE:
1970 errx(1, "%s: unknown device status bit %#x -> %#x",
1971 d->name, d->mmio->cfg.device_status, val);
1973 if (d->mmio->cfg.device_status != prev)
1974 errx(1, "%s: unexpected status transition %#x -> %#x",
1975 d->name, d->mmio->cfg.device_status, val);
1977 /* If they just wrote FEATURES_OK, we make sure they read */
1978 switch (val & ~d->mmio->cfg.device_status) {
1979 case VIRTIO_CONFIG_S_FEATURES_OK:
1980 d->wrote_features_ok = true;
1982 case VIRTIO_CONFIG_S_DRIVER_OK:
1983 if (d->wrote_features_ok)
1984 errx(1, "%s: did not re-read FEATURES_OK",
1988 goto write_through8;
1990 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1991 vq = vq_by_num(d, val);
1995 * The device MUST present a 0 in queue_size if the virtqueue
1996 * corresponding to the current queue_select is unavailable.
1999 d->mmio->cfg.queue_size = 0;
2000 goto write_through16;
2002 /* Save registers for old vq, if it was a valid vq */
2003 if (d->mmio->cfg.queue_size)
2004 save_vq_config(&d->mmio->cfg,
2005 vq_by_num(d, d->mmio->cfg.queue_select));
2006 /* Restore the registers for the queue they asked for */
2007 restore_vq_config(&d->mmio->cfg, vq);
2008 goto write_through16;
2009 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
2013 * The driver MUST NOT write a value which is not a power of 2
2017 errx(1, "%s: invalid queue size %u\n", d->name, val);
2018 if (d->mmio->cfg.queue_enable)
2019 errx(1, "%s: changing queue size on live device",
2021 goto write_through16;
2022 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
2023 errx(1, "%s: attempt to set MSIX vector to %u",
2025 case offsetof(struct virtio_pci_mmio, cfg.queue_enable): {
2026 struct virtqueue *vq = vq_by_num(d, d->mmio->cfg.queue_select);
2031 * The driver MUST NOT write a 0 to queue_enable.
2034 errx(1, "%s: setting queue_enable to %u", d->name, val);
2039 * 7. Perform device-specific setup, including discovery of
2040 * virtqueues for the device, optional per-bus setup,
2041 * reading and possibly writing the device’s virtio
2042 * configuration space, and population of virtqueues.
2043 * 8. Set the DRIVER_OK status bit.
2045 * All our devices require all virtqueues to be enabled, so
2046 * they should have done that before setting DRIVER_OK.
2048 if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK)
2049 errx(1, "%s: enabling vs after DRIVER_OK", d->name);
2051 d->mmio->cfg.queue_enable = val;
2052 save_vq_config(&d->mmio->cfg, vq);
2053 check_virtqueue(d, vq);
2054 goto write_through16;
2056 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
2057 errx(1, "%s: attempt to write to queue_notify_off", d->name);
2058 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
2059 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
2060 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
2061 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
2062 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
2063 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
2067 * The driver MUST configure the other virtqueue fields before
2068 * enabling the virtqueue with queue_enable.
2070 if (d->mmio->cfg.queue_enable)
2071 errx(1, "%s: changing queue on live device",
2077 * The driver MUST follow this sequence to initialize a device:
2079 * 5. Set the FEATURES_OK status bit. The driver MUST not
2080 * accept new feature bits after this step.
2082 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK))
2083 errx(1, "%s: enabling vs before FEATURES_OK", d->name);
2086 * 6. Re-read device status to ensure the FEATURES_OK bit is
2089 if (d->wrote_features_ok)
2090 errx(1, "%s: didn't re-read FEATURES_OK before setup",
2093 goto write_through32;
2094 case offsetof(struct virtio_pci_mmio, notify):
2095 vq = vq_by_num(d, val);
2097 errx(1, "Invalid vq notification on %u", val);
2098 /* Notify the process handling this vq by adding 1 to eventfd */
2099 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
2100 goto write_through16;
2101 case offsetof(struct virtio_pci_mmio, isr):
2102 errx(1, "%s: Unexpected write to isr", d->name);
2103 /* Weird corner case: write to emerg_wr of console */
2104 case sizeof(struct virtio_pci_mmio)
2105 + offsetof(struct virtio_console_config, emerg_wr):
2106 if (strcmp(d->name, "console") == 0) {
2108 write(STDOUT_FILENO, &c, 1);
2109 goto write_through32;
2111 /* Fall through... */
2116 * The driver MUST NOT write to device_feature, num_queues,
2117 * config_generation or queue_notify_off.
2119 errx(1, "%s: Unexpected write to offset %u", d->name, off);
2122 feature_write_through32:
2126 * The driver MUST follow this sequence to initialize a device:
2128 * - Set the DRIVER status bit: the guest OS knows how
2129 * to drive the device.
2130 * - Read device feature bits, and write the subset
2131 * of feature bits understood by the OS and driver
2134 * - Set the FEATURES_OK status bit. The driver MUST not
2135 * accept new feature bits after this step.
2137 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2138 errx(1, "%s: feature write before VIRTIO_CONFIG_S_DRIVER",
2140 if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK)
2141 errx(1, "%s: feature write after VIRTIO_CONFIG_S_FEATURES_OK",
2147 * The driver MUST access each field using the “natural” access
2148 * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
2149 * 16-bit fields and 8-bit accesses for 8-bit fields.
2152 if (mask != 0xFFFFFFFF) {
2153 errx(1, "%s: non-32-bit write to offset %u (%#x)",
2154 d->name, off, getreg(eip));
2157 memcpy((char *)d->mmio + off, &val, 4);
2162 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
2163 d->name, mask, off, getreg(eip));
2164 memcpy((char *)d->mmio + off, &val, 2);
2169 errx(1, "%s: non-8-bit write to offset %u (%#x)",
2170 d->name, off, getreg(eip));
2171 memcpy((char *)d->mmio + off, &val, 1);
2175 static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
2181 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
2182 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
2183 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
2184 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
2188 * The driver MUST follow this sequence to initialize a device:
2190 * - Set the DRIVER status bit: the guest OS knows how
2191 * to drive the device.
2192 * - Read device feature bits, and write the subset
2193 * of feature bits understood by the OS and driver
2196 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2197 errx(1, "%s: feature read before VIRTIO_CONFIG_S_DRIVER",
2199 goto read_through32;
2200 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
2201 errx(1, "%s: read of msix_config", d->name);
2202 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
2203 goto read_through16;
2204 case offsetof(struct virtio_pci_mmio, cfg.device_status):
2205 /* As they did read, any write of FEATURES_OK is now fine. */
2206 d->wrote_features_ok = false;
2208 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
2212 * The device MUST present a changed config_generation after
2213 * the driver has read a device-specific configuration value
2214 * which has changed since any part of the device-specific
2215 * configuration was last read.
2217 * This is simple: none of our devices change config, so this
2221 case offsetof(struct virtio_pci_mmio, notify):
2225 * The driver MUST NOT notify the device before setting
2228 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
2229 errx(1, "%s: notify before VIRTIO_CONFIG_S_DRIVER_OK",
2231 goto read_through16;
2232 case offsetof(struct virtio_pci_mmio, isr):
2234 errx(1, "%s: non-8-bit read from offset %u (%#x)",
2235 d->name, off, getreg(eip));
2240 * The device MUST reset ISR status to 0 on driver read.
2244 case offsetof(struct virtio_pci_mmio, padding):
2245 errx(1, "%s: read from padding (%#x)",
2246 d->name, getreg(eip));
2248 /* Read from device config space, beware unaligned overflow */
2249 if (off > d->mmio_size - 4)
2250 errx(1, "%s: read past end (%#x)",
2251 d->name, getreg(eip));
2255 * The driver MUST follow this sequence to initialize a device:
2257 * 3. Set the DRIVER status bit: the guest OS knows how to
2259 * 4. Read device feature bits, and write the subset of
2260 * feature bits understood by the OS and driver to the
2261 * device. During this step the driver MAY read (but MUST NOT
2262 * write) the device-specific configuration fields to check
2263 * that it can support the device before accepting it.
2265 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2266 errx(1, "%s: config read before VIRTIO_CONFIG_S_DRIVER",
2269 if (mask == 0xFFFFFFFF)
2270 goto read_through32;
2271 else if (mask == 0xFFFF)
2272 goto read_through16;
2280 * The driver MUST access each field using the “natural” access
2281 * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
2282 * 16-bit fields and 8-bit accesses for 8-bit fields.
2285 if (mask != 0xFFFFFFFF)
2286 errx(1, "%s: non-32-bit read to offset %u (%#x)",
2287 d->name, off, getreg(eip));
2288 memcpy(&val, (char *)d->mmio + off, 4);
2293 errx(1, "%s: non-16-bit read to offset %u (%#x)",
2294 d->name, off, getreg(eip));
2295 memcpy(&val, (char *)d->mmio + off, 2);
2300 errx(1, "%s: non-8-bit read to offset %u (%#x)",
2301 d->name, off, getreg(eip));
2302 memcpy(&val, (char *)d->mmio + off, 1);
2306 static void emulate_mmio(unsigned long paddr, const u8 *insn)
2308 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
2309 struct device *d = find_mmio_region(paddr, &off);
2310 unsigned long args[] = { LHREQ_TRAP, 14 };
2313 warnx("MMIO touching %#08lx (not a device)", paddr);
2317 /* Prefix makes it a 16 bit op */
2318 if (insn[0] == 0x66) {
2324 if (insn[insnlen] == 0x89) {
2325 /* Next byte is r/m byte: bits 3-5 are register. */
2326 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
2327 emulate_mmio_write(d, off, val, mask);
2328 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2329 } else if (insn[insnlen] == 0x8b) { /* ioread */
2330 /* Next byte is r/m byte: bits 3-5 are register. */
2331 val = emulate_mmio_read(d, off, mask);
2332 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
2333 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2334 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
2336 /* Next byte is r/m byte: bits 3-5 are register. */
2337 val = getreg_num((insn[1] >> 3) & 0x7, mask);
2338 emulate_mmio_write(d, off, val, mask);
2339 insnlen = 2 + insn_displacement_len(insn[1]);
2340 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
2342 val = emulate_mmio_read(d, off, mask);
2343 setreg_num((insn[1] >> 3) & 0x7, val, mask);
2344 insnlen = 2 + insn_displacement_len(insn[1]);
2346 warnx("Unknown MMIO instruction touching %#08lx:"
2347 " %02x %02x %02x %02x at %u",
2348 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
2350 /* Inject trap into Guest. */
2351 if (write(lguest_fd, args, sizeof(args)) < 0)
2352 err(1, "Reinjecting trap 14 for fault at %#x",
2357 /* Finally, we've "done" the instruction, so move past it. */
2358 setreg(eip, getreg(eip) + insnlen);
2364 * All devices need a descriptor so the Guest knows it exists, and a "struct
2365 * device" so the Launcher can keep track of it. We have common helper
2366 * routines to allocate and manage them.
2368 static void add_pci_virtqueue(struct device *dev,
2369 void (*service)(struct virtqueue *))
2371 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2373 /* Initialize the virtqueue */
2375 vq->last_avail_idx = 0;
2379 * This is the routine the service thread will run, and its Process ID
2380 * once it's running.
2382 vq->service = service;
2383 vq->thread = (pid_t)-1;
2385 /* Initialize the configuration. */
2386 reset_vq_pci_config(vq);
2387 vq->pci_config.queue_notify_off = 0;
2389 /* Add one to the number of queues */
2390 vq->dev->mmio->cfg.num_queues++;
2393 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2396 for (i = &dev->vq; *i; i = &(*i)->next);
2400 /* The Guest accesses the feature bits via the PCI common config MMIO region */
2401 static void add_pci_feature(struct device *dev, unsigned bit)
2403 dev->features |= (1ULL << bit);
2406 /* For devices with no config. */
2407 static void no_device_config(struct device *dev)
2409 dev->mmio_addr = get_mmio_region(dev->mmio_size);
2411 dev->config.bar[0] = dev->mmio_addr;
2412 /* Bottom 4 bits must be zero */
2413 assert(~(dev->config.bar[0] & 0xF));
2416 /* This puts the device config into BAR0 */
2417 static void set_device_config(struct device *dev, const void *conf, size_t len)
2420 dev->mmio_size += len;
2421 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2422 memcpy(dev->mmio + 1, conf, len);
2427 * The device MUST present at least one VIRTIO_PCI_CAP_DEVICE_CFG
2428 * capability for any device type which has a device-specific
2431 /* Hook up device cfg */
2432 dev->config.cfg_access.cap.cap_next
2433 = offsetof(struct pci_config, device);
2438 * The offset for the device-specific configuration MUST be 4-byte
2441 assert(dev->config.cfg_access.cap.cap_next % 4 == 0);
2443 /* Fix up device cfg field length. */
2444 dev->config.device.length = len;
2446 /* The rest is the same as the no-config case */
2447 no_device_config(dev);
2450 static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2451 size_t bar_offset, size_t bar_bytes, u8 next)
2453 cap->cap_vndr = PCI_CAP_ID_VNDR;
2454 cap->cap_next = next;
2455 cap->cap_len = caplen;
2456 cap->cfg_type = type;
2458 memset(cap->padding, 0, sizeof(cap->padding));
2459 cap->offset = bar_offset;
2460 cap->length = bar_bytes;
2464 * This sets up the pci_config structure, as defined in the virtio 1.0
2465 * standard (and PCI standard).
2467 static void init_pci_config(struct pci_config *pci, u16 type,
2468 u8 class, u8 subclass)
2470 size_t bar_offset, bar_len;
2475 * The device MUST either present notify_off_multiplier as an even
2476 * power of 2, or present notify_off_multiplier as 0.
2480 * The device MUST initialize device status to 0 upon reset.
2482 memset(pci, 0, sizeof(*pci));
2484 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2485 pci->vendor_id = 0x1AF4;
2486 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2487 pci->device_id = 0x1040 + type;
2490 * PCI have specific codes for different types of devices.
2491 * Linux doesn't care, but it's a good clue for people looking
2495 pci->subclass = subclass;
2500 * Non-transitional devices SHOULD have a PCI Revision ID of 1 or
2508 * Non-transitional devices SHOULD have a PCI Subsystem Device ID of
2511 pci->subsystem_device_id = 0x40;
2513 /* We use our dummy interrupt controller, and irq_line is the irq */
2514 pci->irq_line = devices.next_irq++;
2517 /* Support for extended capabilities. */
2518 pci->status = (1 << 4);
2524 * The device MUST present at least one common configuration
2527 pci->capabilities = offsetof(struct pci_config, common);
2529 /* 4.1.4.3.1 ... offset MUST be 4-byte aligned. */
2530 assert(pci->capabilities % 4 == 0);
2532 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2533 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2534 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2535 bar_offset, bar_len,
2536 offsetof(struct pci_config, notify));
2541 * The device MUST present at least one notification capability.
2543 bar_offset += bar_len;
2544 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2549 * The cap.offset MUST be 2-byte aligned.
2551 assert(pci->common.cap_next % 2 == 0);
2553 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2557 * The value cap.length presented by the device MUST be at least 2 and
2558 * MUST be large enough to support queue notification offsets for all
2559 * supported queues in all possible configurations.
2561 assert(bar_len >= 2);
2563 init_cap(&pci->notify.cap, sizeof(pci->notify),
2564 VIRTIO_PCI_CAP_NOTIFY_CFG,
2565 bar_offset, bar_len,
2566 offsetof(struct pci_config, isr));
2568 bar_offset += bar_len;
2569 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2573 * The device MUST present at least one VIRTIO_PCI_CAP_ISR_CFG
2576 init_cap(&pci->isr, sizeof(pci->isr),
2577 VIRTIO_PCI_CAP_ISR_CFG,
2578 bar_offset, bar_len,
2579 offsetof(struct pci_config, cfg_access));
2584 * The device MUST present at least one VIRTIO_PCI_CAP_PCI_CFG
2587 /* This doesn't have any presence in the BAR */
2588 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2589 VIRTIO_PCI_CAP_PCI_CFG,
2592 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2593 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2596 * This gets sewn in and length set in set_device_config().
2597 * Some devices don't have a device configuration interface, so
2598 * we never expose this if we don't call set_device_config().
2600 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2605 * This routine does all the creation and setup of a new device, but we don't
2606 * actually place the MMIO region until we know the size (if any) of the
2607 * device-specific config. And we don't actually start the service threads
2610 * See what I mean about userspace being boring?
2612 static struct device *new_pci_device(const char *name, u16 type,
2613 u8 class, u8 subclass)
2615 struct device *dev = malloc(sizeof(*dev));
2617 /* Now we populate the fields one at a time. */
2620 dev->running = false;
2621 dev->wrote_features_ok = false;
2622 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2623 dev->mmio = calloc(1, dev->mmio_size);
2624 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2625 dev->features_accepted = 0;
2627 if (devices.device_num + 1 >= MAX_PCI_DEVICES)
2628 errx(1, "Can only handle 31 PCI devices");
2630 init_pci_config(&dev->config, type, class, subclass);
2631 assert(!devices.pci[devices.device_num+1]);
2632 devices.pci[++devices.device_num] = dev;
2638 * Our first setup routine is the console. It's a fairly simple device, but
2639 * UNIX tty handling makes it uglier than it could be.
2641 static void setup_console(void)
2644 struct virtio_console_config conf;
2646 /* If we can save the initial standard input settings... */
2647 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2648 struct termios term = orig_term;
2650 * Then we turn off echo, line buffering and ^C etc: We want a
2651 * raw input stream to the Guest.
2653 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2654 tcsetattr(STDIN_FILENO, TCSANOW, &term);
2657 dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
2659 /* We store the console state in dev->priv, and initialize it. */
2660 dev->priv = malloc(sizeof(struct console_abort));
2661 ((struct console_abort *)dev->priv)->count = 0;
2664 * The console needs two virtqueues: the input then the output. When
2665 * they put something the input queue, we make sure we're listening to
2666 * stdin. When they put something in the output queue, we write it to
2669 add_pci_virtqueue(dev, console_input);
2670 add_pci_virtqueue(dev, console_output);
2672 /* We need a configuration area for the emerg_wr early writes. */
2673 add_pci_feature(dev, VIRTIO_CONSOLE_F_EMERG_WRITE);
2674 set_device_config(dev, &conf, sizeof(conf));
2676 verbose("device %u: console\n", devices.device_num);
2681 * Inter-guest networking is an interesting area. Simplest is to have a
2682 * --sharenet=<name> option which opens or creates a named pipe. This can be
2683 * used to send packets to another guest in a 1:1 manner.
2685 * More sophisticated is to use one of the tools developed for project like UML
2688 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2689 * completely generic ("here's my vring, attach to your vring") and would work
2690 * for any traffic. Of course, namespace and permissions issues need to be
2691 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2692 * multiple inter-guest channels behind one interface, although it would
2693 * require some manner of hotplugging new virtio channels.
2695 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
2698 static u32 str2ip(const char *ipaddr)
2702 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2703 errx(1, "Failed to parse IP address '%s'", ipaddr);
2704 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2707 static void str2mac(const char *macaddr, unsigned char mac[6])
2710 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2711 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2712 errx(1, "Failed to parse mac address '%s'", macaddr);
2722 * This code is "adapted" from libbridge: it attaches the Host end of the
2723 * network device to the bridge device specified by the command line.
2725 * This is yet another James Morris contribution (I'm an IP-level guy, so I
2726 * dislike bridging), and I just try not to break it.
2728 static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2734 errx(1, "must specify bridge name");
2736 ifidx = if_nametoindex(if_name);
2738 errx(1, "interface %s does not exist!", if_name);
2740 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
2741 ifr.ifr_name[IFNAMSIZ-1] = '\0';
2742 ifr.ifr_ifindex = ifidx;
2743 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2744 err(1, "can't add %s to bridge %s", if_name, br_name);
2748 * This sets up the Host end of the network device with an IP address, brings
2749 * it up so packets will flow, the copies the MAC address into the hwaddr
2752 static void configure_device(int fd, const char *tapif, u32 ipaddr)
2755 struct sockaddr_in sin;
2757 memset(&ifr, 0, sizeof(ifr));
2758 strcpy(ifr.ifr_name, tapif);
2760 /* Don't read these incantations. Just cut & paste them like I did! */
2761 sin.sin_family = AF_INET;
2762 sin.sin_addr.s_addr = htonl(ipaddr);
2763 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
2764 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
2765 err(1, "Setting %s interface address", tapif);
2766 ifr.ifr_flags = IFF_UP;
2767 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
2768 err(1, "Bringing interface %s up", tapif);
2771 static int get_tun_device(char tapif[IFNAMSIZ])
2777 /* Start with this zeroed. Messy but sure. */
2778 memset(&ifr, 0, sizeof(ifr));
2781 * We open the /dev/net/tun device and tell it we want a tap device. A
2782 * tap device is like a tun device, only somehow different. To tell
2783 * the truth, I completely blundered my way through this code, but it
2786 netfd = open_or_die("/dev/net/tun", O_RDWR);
2787 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
2788 strcpy(ifr.ifr_name, "tap%d");
2789 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2790 err(1, "configuring /dev/net/tun");
2792 if (ioctl(netfd, TUNSETOFFLOAD,
2793 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2794 err(1, "Could not set features for tun device");
2797 * We don't need checksums calculated for packets coming in this
2800 ioctl(netfd, TUNSETNOCSUM, 1);
2803 * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2804 * field at the end of the network header iff
2805 * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
2806 * that became the norm, but we need to tell the tun device
2807 * about our expanded header (which is called
2808 * virtio_net_hdr_mrg_rxbuf in the legacy system).
2810 vnet_hdr_sz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2811 if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
2812 err(1, "Setting tun header size to %u", vnet_hdr_sz);
2814 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2819 * Our network is a Host<->Guest network. This can either use bridging or
2820 * routing, but the principle is the same: it uses the "tun" device to inject
2821 * packets into the Host as if they came in from a normal network card. We
2822 * just shunt packets between the Guest and the tun device.
2824 static void setup_tun_net(char *arg)
2827 struct net_info *net_info = malloc(sizeof(*net_info));
2829 u32 ip = INADDR_ANY;
2830 bool bridging = false;
2831 char tapif[IFNAMSIZ], *p;
2832 struct virtio_net_config conf;
2834 net_info->tunfd = get_tun_device(tapif);
2836 /* First we create a new network device. */
2837 dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
2838 dev->priv = net_info;
2840 /* Network devices need a recv and a send queue, just like console. */
2841 add_pci_virtqueue(dev, net_input);
2842 add_pci_virtqueue(dev, net_output);
2845 * We need a socket to perform the magic network ioctls to bring up the
2846 * tap interface, connect to the bridge etc. Any socket will do!
2848 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2850 err(1, "opening IP socket");
2852 /* If the command line was --tunnet=bridge:<name> do bridging. */
2853 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
2854 arg += strlen(BRIDGE_PFX);
2858 /* A mac address may follow the bridge name or IP address */
2859 p = strchr(arg, ':');
2861 str2mac(p+1, conf.mac);
2862 add_pci_feature(dev, VIRTIO_NET_F_MAC);
2866 /* arg is now either an IP address or a bridge name */
2868 add_to_bridge(ipfd, tapif, arg);
2872 /* Set up the tun device. */
2873 configure_device(ipfd, tapif, ip);
2875 /* Expect Guest to handle everything except UFO */
2876 add_pci_feature(dev, VIRTIO_NET_F_CSUM);
2877 add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2878 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2879 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2880 add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2881 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2882 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2883 add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
2884 /* We handle indirect ring entries */
2885 add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2886 set_device_config(dev, &conf, sizeof(conf));
2888 /* We don't need the socket any more; setup is done. */
2892 verbose("device %u: tun %s attached to bridge: %s\n",
2893 devices.device_num, tapif, arg);
2895 verbose("device %u: tun %s: %s\n",
2896 devices.device_num, tapif, arg);
2900 /* This hangs off device->priv. */
2902 /* The size of the file. */
2905 /* The file descriptor for the file. */
2913 * The disk only has one virtqueue, so it only has one thread. It is really
2914 * simple: the Guest asks for a block number and we read or write that position
2917 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2918 * slow: the Guest waits until the read is finished before running anything
2919 * else, even if it could have been doing useful work.
2921 * We could have used async I/O, except it's reputed to suck so hard that
2922 * characters actually go missing from your code when you try to use it.
2924 static void blk_request(struct virtqueue *vq)
2926 struct vblk_info *vblk = vq->dev->priv;
2927 unsigned int head, out_num, in_num, wlen;
2930 struct virtio_blk_outhdr out;
2931 struct iovec iov[vq->vring.num];
2935 * Get the next request, where we normally wait. It triggers the
2936 * interrupt to acknowledge previously serviced requests (if any).
2938 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
2940 /* Copy the output header from the front of the iov (adjusts iov) */
2941 iov_consume(iov, out_num, &out, sizeof(out));
2943 /* Find and trim end of iov input array, for our status byte. */
2945 for (i = out_num + in_num - 1; i >= out_num; i--) {
2946 if (iov[i].iov_len > 0) {
2947 in = iov[i].iov_base + iov[i].iov_len - 1;
2953 errx(1, "Bad virtblk cmd with no room for status");
2956 * For historical reasons, block operations are expressed in 512 byte
2959 off = out.sector * 512;
2961 if (out.type & VIRTIO_BLK_T_OUT) {
2965 * Move to the right location in the block file. This can fail
2966 * if they try to write past end.
2968 if (lseek64(vblk->fd, off, SEEK_SET) != off)
2969 err(1, "Bad seek to sector %llu", out.sector);
2971 ret = writev(vblk->fd, iov, out_num);
2972 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
2975 * Grr... Now we know how long the descriptor they sent was, we
2976 * make sure they didn't try to write over the end of the block
2977 * file (possibly extending it).
2979 if (ret > 0 && off + ret > vblk->len) {
2980 /* Trim it back to the correct length */
2981 ftruncate64(vblk->fd, vblk->len);
2982 /* Die, bad Guest, die. */
2983 errx(1, "Write past end %llu+%u", off, ret);
2987 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
2988 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
2990 ret = fdatasync(vblk->fd);
2991 verbose("FLUSH fdatasync: %i\n", ret);
2993 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
2998 * Move to the right location in the block file. This can fail
2999 * if they try to read past end.
3001 if (lseek64(vblk->fd, off, SEEK_SET) != off)
3002 err(1, "Bad seek to sector %llu", out.sector);
3004 ret = readv(vblk->fd, iov + out_num, in_num);
3006 wlen = sizeof(*in) + ret;
3007 *in = VIRTIO_BLK_S_OK;
3010 *in = VIRTIO_BLK_S_IOERR;
3014 /* Finished that request. */
3015 add_used(vq, head, wlen);
3018 /*L:198 This actually sets up a virtual block device. */
3019 static void setup_block_file(const char *filename)
3022 struct vblk_info *vblk;
3023 struct virtio_blk_config conf;
3025 /* Create the device. */
3026 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
3028 /* The device has one virtqueue, where the Guest places requests. */
3029 add_pci_virtqueue(dev, blk_request);
3031 /* Allocate the room for our own bookkeeping */
3032 vblk = dev->priv = malloc(sizeof(*vblk));
3034 /* First we open the file and store the length. */
3035 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
3036 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
3038 /* Tell Guest how many sectors this device has. */
3039 conf.capacity = cpu_to_le64(vblk->len / 512);
3042 * Tell Guest not to put in too many descriptors at once: two are used
3043 * for the in and out elements.
3045 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
3046 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
3048 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
3050 verbose("device %u: virtblock %llu sectors\n",
3051 devices.device_num, le64_to_cpu(conf.capacity));
3055 * Our random number generator device reads from /dev/urandom into the Guest's
3056 * input buffers. The usual case is that the Guest doesn't want random numbers
3057 * and so has no buffers although /dev/urandom is still readable, whereas
3058 * console is the reverse.
3060 * The same logic applies, however.
3066 static void rng_input(struct virtqueue *vq)
3069 unsigned int head, in_num, out_num, totlen = 0;
3070 struct rng_info *rng_info = vq->dev->priv;
3071 struct iovec iov[vq->vring.num];
3073 /* First we need a buffer from the Guests's virtqueue. */
3074 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
3076 errx(1, "Output buffers in rng?");
3079 * Just like the console write, we loop to cover the whole iovec.
3080 * In this case, short reads actually happen quite a bit.
3082 while (!iov_empty(iov, in_num)) {
3083 len = readv(rng_info->rfd, iov, in_num);
3085 err(1, "Read from /dev/urandom gave %i", len);
3086 iov_consume(iov, in_num, NULL, len);
3090 /* Tell the Guest about the new input. */
3091 add_used(vq, head, totlen);
3095 * This creates a "hardware" random number device for the Guest.
3097 static void setup_rng(void)
3100 struct rng_info *rng_info = malloc(sizeof(*rng_info));
3102 /* Our device's private info simply contains the /dev/urandom fd. */
3103 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
3105 /* Create the new device. */
3106 dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
3107 dev->priv = rng_info;
3109 /* The device has one virtqueue, where the Guest places inbufs. */
3110 add_pci_virtqueue(dev, rng_input);
3112 /* We don't have any configuration space */
3113 no_device_config(dev);
3115 verbose("device %u: rng\n", devices.device_num);
3117 /* That's the end of device setup. */
3119 /*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
3120 static void __attribute__((noreturn)) restart_guest(void)
3125 * Since we don't track all open fds, we simply close everything beyond
3128 for (i = 3; i < FD_SETSIZE; i++)
3131 /* Reset all the devices (kills all threads). */
3134 execv(main_args[0], main_args);
3135 err(1, "Could not exec %s", main_args[0]);
3139 * Finally we reach the core of the Launcher which runs the Guest, serves
3140 * its input and output, and finally, lays it to rest.
3142 static void __attribute__((noreturn)) run_guest(void)
3145 struct lguest_pending notify;
3148 /* We read from the /dev/lguest device to run the Guest. */
3149 readval = pread(lguest_fd, ¬ify, sizeof(notify), cpu_id);
3150 if (readval == sizeof(notify)) {
3151 if (notify.trap == 13) {
3152 verbose("Emulating instruction at %#x\n",
3154 emulate_insn(notify.insn);
3155 } else if (notify.trap == 14) {
3156 verbose("Emulating MMIO at %#x\n",
3158 emulate_mmio(notify.addr, notify.insn);
3160 errx(1, "Unknown trap %i addr %#08x\n",
3161 notify.trap, notify.addr);
3162 /* ENOENT means the Guest died. Reading tells us why. */
3163 } else if (errno == ENOENT) {
3164 char reason[1024] = { 0 };
3165 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
3166 errx(1, "%s", reason);
3167 /* ERESTART means that we need to reboot the guest */
3168 } else if (errno == ERESTART) {
3170 /* Anything else means a bug or incompatible change. */
3172 err(1, "Running guest failed");
3176 * This is the end of the Launcher. The good news: we are over halfway
3177 * through! The bad news: the most fiendish part of the code still lies ahead
3180 * Are you ready? Take a deep breath and join me in the core of the Host, in
3184 static struct option opts[] = {
3185 { "verbose", 0, NULL, 'v' },
3186 { "tunnet", 1, NULL, 't' },
3187 { "block", 1, NULL, 'b' },
3188 { "rng", 0, NULL, 'r' },
3189 { "initrd", 1, NULL, 'i' },
3190 { "username", 1, NULL, 'u' },
3191 { "chroot", 1, NULL, 'c' },
3194 static void usage(void)
3196 errx(1, "Usage: lguest [--verbose] "
3197 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
3198 "|--block=<filename>|--initrd=<filename>]...\n"
3199 "<mem-in-mb> vmlinux [args...]");
3202 /*L:105 The main routine is where the real work begins: */
3203 int main(int argc, char *argv[])
3205 /* Memory, code startpoint and size of the (optional) initrd. */
3206 unsigned long mem = 0, start, initrd_size = 0;
3207 /* Two temporaries. */
3209 /* The boot information for the Guest. */
3210 struct boot_params *boot;
3211 /* If they specify an initrd file to load. */
3212 const char *initrd_name = NULL;
3214 /* Password structure for initgroups/setres[gu]id */
3215 struct passwd *user_details = NULL;
3217 /* Directory to chroot to */
3218 char *chroot_path = NULL;
3220 /* Save the args: we "reboot" by execing ourselves again. */
3224 * First we initialize the device list. We remember next interrupt
3225 * number to use for devices (1: remember that 0 is used by the timer).
3227 devices.next_irq = 1;
3229 /* We're CPU 0. In fact, that's the only CPU possible right now. */
3233 * We need to know how much memory so we can set up the device
3234 * descriptor and memory pages for the devices as we parse the command
3235 * line. So we quickly look through the arguments to find the amount
3238 for (i = 1; i < argc; i++) {
3239 if (argv[i][0] != '-') {
3240 mem = atoi(argv[i]) * 1024 * 1024;
3242 * We start by mapping anonymous pages over all of
3243 * guest-physical memory range. This fills it with 0,
3244 * and ensures that the Guest won't be killed when it
3245 * tries to access it.
3247 guest_base = map_zeroed_pages(mem / getpagesize()
3250 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
3255 /* We always have a console device, and it's always device 1. */
3258 /* The options are fairly straight-forward */
3259 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
3265 setup_tun_net(optarg);
3268 setup_block_file(optarg);
3274 initrd_name = optarg;
3277 user_details = getpwnam(optarg);
3279 err(1, "getpwnam failed, incorrect username?");
3282 chroot_path = optarg;
3285 warnx("Unknown argument %s", argv[optind]);
3290 * After the other arguments we expect memory and kernel image name,
3291 * followed by command line arguments for the kernel.
3293 if (optind + 2 > argc)
3296 verbose("Guest base is at %p\n", guest_base);
3298 /* Initialize the (fake) PCI host bridge device. */
3299 init_pci_host_bridge();
3301 /* Now we load the kernel */
3302 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
3304 /* Boot information is stashed at physical address 0 */
3305 boot = from_guest_phys(0);
3307 /* Map the initrd image if requested (at top of physical memory) */
3309 initrd_size = load_initrd(initrd_name, mem);
3311 * These are the location in the Linux boot header where the
3312 * start and size of the initrd are expected to be found.
3314 boot->hdr.ramdisk_image = mem - initrd_size;
3315 boot->hdr.ramdisk_size = initrd_size;
3316 /* The bootloader type 0xFF means "unknown"; that's OK. */
3317 boot->hdr.type_of_loader = 0xFF;
3321 * The Linux boot header contains an "E820" memory map: ours is a
3322 * simple, single region.
3324 boot->e820_entries = 1;
3325 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
3327 * The boot header contains a command line pointer: we put the command
3328 * line after the boot header.
3330 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
3331 /* We use a simple helper to copy the arguments separated by spaces. */
3332 concat((char *)(boot + 1), argv+optind+2);
3334 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3335 boot->hdr.kernel_alignment = 0x1000000;
3337 /* Boot protocol version: 2.07 supports the fields for lguest. */
3338 boot->hdr.version = 0x207;
3340 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
3341 boot->hdr.hardware_subarch = 1;
3343 /* Tell the entry path not to try to reload segment registers. */
3344 boot->hdr.loadflags |= KEEP_SEGMENTS;
3346 /* We tell the kernel to initialize the Guest. */
3349 /* Ensure that we terminate if a device-servicing child dies. */
3350 signal(SIGCHLD, kill_launcher);
3352 /* If we exit via err(), this kills all the threads, restores tty. */
3353 atexit(cleanup_devices);
3355 /* If requested, chroot to a directory */
3357 if (chroot(chroot_path) != 0)
3358 err(1, "chroot(\"%s\") failed", chroot_path);
3360 if (chdir("/") != 0)
3361 err(1, "chdir(\"/\") failed");
3363 verbose("chroot done\n");
3366 /* If requested, drop privileges */
3371 u = user_details->pw_uid;
3372 g = user_details->pw_gid;
3374 if (initgroups(user_details->pw_name, g) != 0)
3375 err(1, "initgroups failed");
3377 if (setresgid(g, g, g) != 0)
3378 err(1, "setresgid failed");
3380 if (setresuid(u, u, u) != 0)
3381 err(1, "setresuid failed");
3383 verbose("Dropping privileges completed\n");
3386 /* Finally, run the Guest. This doesn't return. */
3392 * Mastery is done: you now know everything I do.
3394 * But surely you have seen code, features and bugs in your wanderings which
3395 * you now yearn to attack? That is the real game, and I look forward to you
3396 * patching and forking lguest into the Your-Name-Here-visor.
3398 * Farewell, and good coding!