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 /* Name for printing errors. */
206 /* The actual ring of buffers. */
209 /* The information about this virtqueue (we only use queue_size on) */
210 struct virtio_pci_common_cfg pci_config;
212 /* Last available index we saw. */
215 /* How many are used since we sent last irq? */
216 unsigned int pending_used;
218 /* Eventfd where Guest notifications arrive. */
221 /* Function for the thread which is servicing this virtqueue. */
222 void (*service)(struct virtqueue *vq);
226 /* Remember the arguments to the program so we can "reboot" */
227 static char **main_args;
229 /* The original tty settings to restore on exit. */
230 static struct termios orig_term;
233 * We have to be careful with barriers: our devices are all run in separate
234 * threads and so we need to make sure that changes visible to the Guest happen
237 #define wmb() __asm__ __volatile__("" : : : "memory")
238 #define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
239 #define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
241 /* Wrapper for the last available index. Makes it easier to change. */
242 #define lg_last_avail(vq) ((vq)->last_avail_idx)
245 * The virtio configuration space is defined to be little-endian. x86 is
246 * little-endian too, but it's nice to be explicit so we have these helpers.
248 #define cpu_to_le16(v16) (v16)
249 #define cpu_to_le32(v32) (v32)
250 #define cpu_to_le64(v64) (v64)
251 #define le16_to_cpu(v16) (v16)
252 #define le32_to_cpu(v32) (v32)
253 #define le64_to_cpu(v64) (v64)
255 /* Is this iovec empty? */
256 static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
260 for (i = 0; i < num_iov; i++)
266 /* Take len bytes from the front of this iovec. */
267 static void iov_consume(struct iovec iov[], unsigned num_iov,
268 void *dest, unsigned len)
272 for (i = 0; i < num_iov; i++) {
275 used = iov[i].iov_len < len ? iov[i].iov_len : len;
277 memcpy(dest, iov[i].iov_base, used);
280 iov[i].iov_base += used;
281 iov[i].iov_len -= used;
285 errx(1, "iovec too short!");
289 * The Launcher code itself takes us out into userspace, that scary place where
290 * pointers run wild and free! Unfortunately, like most userspace programs,
291 * it's quite boring (which is why everyone likes to hack on the kernel!).
292 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
293 * you through this section. Or, maybe not.
295 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
296 * memory and stores it in "guest_base". In other words, Guest physical ==
297 * Launcher virtual with an offset.
299 * This can be tough to get your head around, but usually it just means that we
300 * use these trivial conversion functions when the Guest gives us its
301 * "physical" addresses:
303 static void *from_guest_phys(unsigned long addr)
305 return guest_base + addr;
308 static unsigned long to_guest_phys(const void *addr)
310 return (addr - guest_base);
314 * Loading the Kernel.
316 * We start with couple of simple helper routines. open_or_die() avoids
317 * error-checking code cluttering the callers:
319 static int open_or_die(const char *name, int flags)
321 int fd = open(name, flags);
323 err(1, "Failed to open %s", name);
327 /* map_zeroed_pages() takes a number of pages. */
328 static void *map_zeroed_pages(unsigned int num)
330 int fd = open_or_die("/dev/zero", O_RDONLY);
334 * We use a private mapping (ie. if we write to the page, it will be
335 * copied). We allocate an extra two pages PROT_NONE to act as guard
336 * pages against read/write attempts that exceed allocated space.
338 addr = mmap(NULL, getpagesize() * (num+2),
339 PROT_NONE, MAP_PRIVATE, fd, 0);
341 if (addr == MAP_FAILED)
342 err(1, "Mmapping %u pages of /dev/zero", num);
344 if (mprotect(addr + getpagesize(), getpagesize() * num,
345 PROT_READ|PROT_WRITE) == -1)
346 err(1, "mprotect rw %u pages failed", num);
349 * One neat mmap feature is that you can close the fd, and it
354 /* Return address after PROT_NONE page */
355 return addr + getpagesize();
358 /* Get some bytes which won't be mapped into the guest. */
359 static unsigned long get_mmio_region(size_t size)
361 unsigned long addr = guest_mmio;
367 /* Size has to be a power of 2 (and multiple of 16) */
368 for (i = 1; i < size; i <<= 1);
376 * This routine is used to load the kernel or initrd. It tries mmap, but if
377 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
378 * it falls back to reading the memory in.
380 static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
385 * We map writable even though for some segments are marked read-only.
386 * The kernel really wants to be writable: it patches its own
389 * MAP_PRIVATE means that the page won't be copied until a write is
390 * done to it. This allows us to share untouched memory between
393 if (mmap(addr, len, PROT_READ|PROT_WRITE,
394 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
397 /* pread does a seek and a read in one shot: saves a few lines. */
398 r = pread(fd, addr, len, offset);
400 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
404 * This routine takes an open vmlinux image, which is in ELF, and maps it into
405 * the Guest memory. ELF = Embedded Linking Format, which is the format used
406 * by all modern binaries on Linux including the kernel.
408 * The ELF headers give *two* addresses: a physical address, and a virtual
409 * address. We use the physical address; the Guest will map itself to the
412 * We return the starting address.
414 static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
416 Elf32_Phdr phdr[ehdr->e_phnum];
420 * Sanity checks on the main ELF header: an x86 executable with a
421 * reasonable number of correctly-sized program headers.
423 if (ehdr->e_type != ET_EXEC
424 || ehdr->e_machine != EM_386
425 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
426 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
427 errx(1, "Malformed elf header");
430 * An ELF executable contains an ELF header and a number of "program"
431 * headers which indicate which parts ("segments") of the program to
435 /* We read in all the program headers at once: */
436 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
437 err(1, "Seeking to program headers");
438 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
439 err(1, "Reading program headers");
442 * Try all the headers: there are usually only three. A read-only one,
443 * a read-write one, and a "note" section which we don't load.
445 for (i = 0; i < ehdr->e_phnum; i++) {
446 /* If this isn't a loadable segment, we ignore it */
447 if (phdr[i].p_type != PT_LOAD)
450 verbose("Section %i: size %i addr %p\n",
451 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
453 /* We map this section of the file at its physical address. */
454 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
455 phdr[i].p_offset, phdr[i].p_filesz);
458 /* The entry point is given in the ELF header. */
459 return ehdr->e_entry;
463 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
464 * to jump into it and it will unpack itself. We used to have to perform some
465 * hairy magic because the unpacking code scared me.
467 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
468 * a small patch to jump over the tricky bits in the Guest, so now we just read
469 * the funky header so we know where in the file to load, and away we go!
471 static unsigned long load_bzimage(int fd)
473 struct boot_params boot;
475 /* Modern bzImages get loaded at 1M. */
476 void *p = from_guest_phys(0x100000);
479 * Go back to the start of the file and read the header. It should be
480 * a Linux boot header (see Documentation/x86/boot.txt)
482 lseek(fd, 0, SEEK_SET);
483 read(fd, &boot, sizeof(boot));
485 /* Inside the setup_hdr, we expect the magic "HdrS" */
486 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
487 errx(1, "This doesn't look like a bzImage to me");
489 /* Skip over the extra sectors of the header. */
490 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
492 /* Now read everything into memory. in nice big chunks. */
493 while ((r = read(fd, p, 65536)) > 0)
496 /* Finally, code32_start tells us where to enter the kernel. */
497 return boot.hdr.code32_start;
501 * Loading the kernel is easy when it's a "vmlinux", but most kernels
502 * come wrapped up in the self-decompressing "bzImage" format. With a little
503 * work, we can load those, too.
505 static unsigned long load_kernel(int fd)
509 /* Read in the first few bytes. */
510 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
511 err(1, "Reading kernel");
513 /* If it's an ELF file, it starts with "\177ELF" */
514 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
515 return map_elf(fd, &hdr);
517 /* Otherwise we assume it's a bzImage, and try to load it. */
518 return load_bzimage(fd);
522 * This is a trivial little helper to align pages. Andi Kleen hated it because
523 * it calls getpagesize() twice: "it's dumb code."
525 * Kernel guys get really het up about optimization, even when it's not
526 * necessary. I leave this code as a reaction against that.
528 static inline unsigned long page_align(unsigned long addr)
530 /* Add upwards and truncate downwards. */
531 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
535 * An "initial ram disk" is a disk image loaded into memory along with the
536 * kernel which the kernel can use to boot from without needing any drivers.
537 * Most distributions now use this as standard: the initrd contains the code to
538 * load the appropriate driver modules for the current machine.
540 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
541 * kernels. He sent me this (and tells me when I break it).
543 static unsigned long load_initrd(const char *name, unsigned long mem)
549 ifd = open_or_die(name, O_RDONLY);
550 /* fstat() is needed to get the file size. */
551 if (fstat(ifd, &st) < 0)
552 err(1, "fstat() on initrd '%s'", name);
555 * We map the initrd at the top of memory, but mmap wants it to be
556 * page-aligned, so we round the size up for that.
558 len = page_align(st.st_size);
559 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
561 * Once a file is mapped, you can close the file descriptor. It's a
562 * little odd, but quite useful.
565 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
567 /* We return the initrd size. */
573 * Simple routine to roll all the commandline arguments together with spaces
576 static void concat(char *dst, char *args[])
578 unsigned int i, len = 0;
580 for (i = 0; args[i]; i++) {
582 strcat(dst+len, " ");
585 strcpy(dst+len, args[i]);
586 len += strlen(args[i]);
588 /* In case it's empty. */
593 * This is where we actually tell the kernel to initialize the Guest. We
594 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
595 * the base of Guest "physical" memory, the top physical page to allow and the
596 * entry point for the Guest.
598 static void tell_kernel(unsigned long start)
600 unsigned long args[] = { LHREQ_INITIALIZE,
601 (unsigned long)guest_base,
602 guest_limit / getpagesize(), start,
603 (guest_mmio+getpagesize()-1) / getpagesize() };
604 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
605 guest_base, guest_base + guest_limit,
606 guest_limit, guest_mmio);
607 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
608 if (write(lguest_fd, args, sizeof(args)) < 0)
609 err(1, "Writing to /dev/lguest");
616 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
617 * We need to make sure it's not trying to reach into the Launcher itself, so
618 * we have a convenient routine which checks it and exits with an error message
619 * if something funny is going on:
621 static void *_check_pointer(unsigned long addr, unsigned int size,
625 * Check if the requested address and size exceeds the allocated memory,
626 * or addr + size wraps around.
628 if ((addr + size) > guest_limit || (addr + size) < addr)
629 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
631 * We return a pointer for the caller's convenience, now we know it's
634 return from_guest_phys(addr);
636 /* A macro which transparently hands the line number to the real function. */
637 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
640 * Each buffer in the virtqueues is actually a chain of descriptors. This
641 * function returns the next descriptor in the chain, or vq->vring.num if we're
644 static unsigned next_desc(struct vring_desc *desc,
645 unsigned int i, unsigned int max)
649 /* If this descriptor says it doesn't chain, we're done. */
650 if (!(desc[i].flags & VRING_DESC_F_NEXT))
653 /* Check they're not leading us off end of descriptors. */
655 /* Make sure compiler knows to grab that: we don't want it changing! */
659 errx(1, "Desc next is %u", next);
665 * This actually sends the interrupt for this virtqueue, if we've used a
668 static void trigger_irq(struct virtqueue *vq)
670 unsigned long buf[] = { LHREQ_IRQ, vq->dev->config.irq_line };
672 /* Don't inform them if nothing used. */
673 if (!vq->pending_used)
675 vq->pending_used = 0;
680 * If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
681 * The driver MUST set flags to 0 or 1.
683 if (vq->vring.avail->flags > 1)
684 errx(1, "%s: avail->flags = %u\n",
685 vq->dev->name, vq->vring.avail->flags);
690 * If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
692 * - The device MUST ignore the used_event value.
693 * - After the device writes a descriptor index into the used ring:
694 * - If flags is 1, the device SHOULD NOT send an interrupt.
695 * - If flags is 0, the device MUST send an interrupt.
697 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
704 * If MSI-X capability is disabled, the device MUST set the Queue
705 * Interrupt bit in ISR status before sending a virtqueue notification
708 vq->dev->mmio->isr = 0x1;
710 /* Send the Guest an interrupt tell them we used something up. */
711 if (write(lguest_fd, buf, sizeof(buf)) != 0)
712 err(1, "Triggering irq %i", vq->dev->config.irq_line);
716 * This looks in the virtqueue for the first available buffer, and converts
717 * it to an iovec for convenient access. Since descriptors consist of some
718 * number of output then some number of input descriptors, it's actually two
719 * iovecs, but we pack them into one and note how many of each there were.
721 * This function waits if necessary, and returns the descriptor number found.
723 static unsigned wait_for_vq_desc(struct virtqueue *vq,
725 unsigned int *out_num, unsigned int *in_num)
727 unsigned int i, head, max;
728 struct vring_desc *desc;
729 u16 last_avail = lg_last_avail(vq);
734 * The driver MUST handle spurious interrupts from the device.
736 * That's why this is a while loop.
739 /* There's nothing available? */
740 while (last_avail == vq->vring.avail->idx) {
744 * Since we're about to sleep, now is a good time to tell the
745 * Guest about what we've used up to now.
749 /* OK, now we need to know about added descriptors. */
750 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
753 * They could have slipped one in as we were doing that: make
754 * sure it's written, then check again.
757 if (last_avail != vq->vring.avail->idx) {
758 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
762 /* Nothing new? Wait for eventfd to tell us they refilled. */
763 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
764 errx(1, "Event read failed?");
766 /* We don't need to be notified again. */
767 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
770 /* Check it isn't doing very strange things with descriptor numbers. */
771 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
772 errx(1, "Guest moved used index from %u to %u",
773 last_avail, vq->vring.avail->idx);
776 * Make sure we read the descriptor number *after* we read the ring
777 * update; don't let the cpu or compiler change the order.
782 * Grab the next descriptor number they're advertising, and increment
783 * the index we've seen.
785 head = vq->vring.avail->ring[last_avail % vq->vring.num];
788 /* If their number is silly, that's a fatal mistake. */
789 if (head >= vq->vring.num)
790 errx(1, "Guest says index %u is available", head);
792 /* When we start there are none of either input nor output. */
793 *out_num = *in_num = 0;
796 desc = vq->vring.desc;
800 * We have to read the descriptor after we read the descriptor number,
801 * but there's a data dependency there so the CPU shouldn't reorder
802 * that: no rmb() required.
807 * If this is an indirect entry, then this buffer contains a
808 * descriptor table which we handle as if it's any normal
811 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
814 * The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
815 * flag unless the VIRTIO_F_INDIRECT_DESC feature was
818 if (!(vq->dev->features_accepted &
819 (1<<VIRTIO_RING_F_INDIRECT_DESC)))
820 errx(1, "%s: vq indirect not negotiated",
826 * The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
827 * flag within an indirect descriptor (ie. only one
828 * table per descriptor).
830 if (desc != vq->vring.desc)
831 errx(1, "%s: Indirect within indirect",
835 * Proposed update VIRTIO-134 spells this out:
837 * A driver MUST NOT set both VIRTQ_DESC_F_INDIRECT
838 * and VIRTQ_DESC_F_NEXT in flags.
840 if (desc[i].flags & VRING_DESC_F_NEXT)
841 errx(1, "%s: indirect and next together",
844 if (desc[i].len % sizeof(struct vring_desc))
845 errx(1, "Invalid size for indirect buffer table");
849 * The device MUST ignore the write-only flag
850 * (flags&VIRTQ_DESC_F_WRITE) in the descriptor that
851 * refers to an indirect table.
853 * We ignore it here: :)
856 max = desc[i].len / sizeof(struct vring_desc);
857 desc = check_pointer(desc[i].addr, desc[i].len);
862 * A driver MUST NOT create a descriptor chain longer
863 * than the Queue Size of the device.
865 if (max > vq->pci_config.queue_size)
866 errx(1, "%s: indirect has too many entries",
870 /* Grab the first descriptor, and check it's OK. */
871 iov[*out_num + *in_num].iov_len = desc[i].len;
872 iov[*out_num + *in_num].iov_base
873 = check_pointer(desc[i].addr, desc[i].len);
874 /* If this is an input descriptor, increment that count. */
875 if (desc[i].flags & VRING_DESC_F_WRITE)
879 * If it's an output descriptor, they're all supposed
880 * to come before any input descriptors.
883 errx(1, "Descriptor has out after in");
887 /* If we've got too many, that implies a descriptor loop. */
888 if (*out_num + *in_num > max)
889 errx(1, "Looped descriptor");
890 } while ((i = next_desc(desc, i, max)) != max);
896 * After we've used one of their buffers, we tell the Guest about it. Sometime
897 * later we'll want to send them an interrupt using trigger_irq(); note that
898 * wait_for_vq_desc() does that for us if it has to wait.
900 static void add_used(struct virtqueue *vq, unsigned int head, int len)
902 struct vring_used_elem *used;
905 * The virtqueue contains a ring of used buffers. Get a pointer to the
906 * next entry in that used ring.
908 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
911 /* Make sure buffer is written before we update index. */
913 vq->vring.used->idx++;
917 /* And here's the combo meal deal. Supersize me! */
918 static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
920 add_used(vq, head, len);
927 * We associate some data with the console for our exit hack.
929 struct console_abort {
930 /* How many times have they hit ^C? */
932 /* When did they start? */
933 struct timeval start;
936 /* This is the routine which handles console input (ie. stdin). */
937 static void console_input(struct virtqueue *vq)
940 unsigned int head, in_num, out_num;
941 struct console_abort *abort = vq->dev->priv;
942 struct iovec iov[vq->vring.num];
944 /* Make sure there's a descriptor available. */
945 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
947 errx(1, "Output buffers in console in queue?");
949 /* Read into it. This is where we usually wait. */
950 len = readv(STDIN_FILENO, iov, in_num);
952 /* Ran out of input? */
953 warnx("Failed to get console input, ignoring console.");
955 * For simplicity, dying threads kill the whole Launcher. So
962 /* Tell the Guest we used a buffer. */
963 add_used_and_trigger(vq, head, len);
966 * Three ^C within one second? Exit.
968 * This is such a hack, but works surprisingly well. Each ^C has to
969 * be in a buffer by itself, so they can't be too fast. But we check
970 * that we get three within about a second, so they can't be too
973 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
979 if (abort->count == 1)
980 gettimeofday(&abort->start, NULL);
981 else if (abort->count == 3) {
983 gettimeofday(&now, NULL);
984 /* Kill all Launcher processes with SIGINT, like normal ^C */
985 if (now.tv_sec <= abort->start.tv_sec+1)
991 /* This is the routine which handles console output (ie. stdout). */
992 static void console_output(struct virtqueue *vq)
994 unsigned int head, out, in;
995 struct iovec iov[vq->vring.num];
997 /* We usually wait in here, for the Guest to give us something. */
998 head = wait_for_vq_desc(vq, iov, &out, &in);
1000 errx(1, "Input buffers in console output queue?");
1002 /* writev can return a partial write, so we loop here. */
1003 while (!iov_empty(iov, out)) {
1004 int len = writev(STDOUT_FILENO, iov, out);
1006 warn("Write to stdout gave %i (%d)", len, errno);
1009 iov_consume(iov, out, NULL, len);
1013 * We're finished with that buffer: if we're going to sleep,
1014 * wait_for_vq_desc() will prod the Guest with an interrupt.
1016 add_used(vq, head, 0);
1022 * Handling output for network is also simple: we get all the output buffers
1023 * and write them to /dev/net/tun.
1029 static void net_output(struct virtqueue *vq)
1031 struct net_info *net_info = vq->dev->priv;
1032 unsigned int head, out, in;
1033 struct iovec iov[vq->vring.num];
1035 /* We usually wait in here for the Guest to give us a packet. */
1036 head = wait_for_vq_desc(vq, iov, &out, &in);
1038 errx(1, "Input buffers in net output queue?");
1040 * Send the whole thing through to /dev/net/tun. It expects the exact
1041 * same format: what a coincidence!
1043 if (writev(net_info->tunfd, iov, out) < 0)
1044 warnx("Write to tun failed (%d)?", errno);
1047 * Done with that one; wait_for_vq_desc() will send the interrupt if
1048 * all packets are processed.
1050 add_used(vq, head, 0);
1054 * Handling network input is a bit trickier, because I've tried to optimize it.
1056 * First we have a helper routine which tells is if from this file descriptor
1057 * (ie. the /dev/net/tun device) will block:
1059 static bool will_block(int fd)
1062 struct timeval zero = { 0, 0 };
1065 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
1069 * This handles packets coming in from the tun device to our Guest. Like all
1070 * service routines, it gets called again as soon as it returns, so you don't
1071 * see a while(1) loop here.
1073 static void net_input(struct virtqueue *vq)
1076 unsigned int head, out, in;
1077 struct iovec iov[vq->vring.num];
1078 struct net_info *net_info = vq->dev->priv;
1081 * Get a descriptor to write an incoming packet into. This will also
1082 * send an interrupt if they're out of descriptors.
1084 head = wait_for_vq_desc(vq, iov, &out, &in);
1086 errx(1, "Output buffers in net input queue?");
1089 * If it looks like we'll block reading from the tun device, send them
1092 if (vq->pending_used && will_block(net_info->tunfd))
1096 * Read in the packet. This is where we normally wait (when there's no
1097 * incoming network traffic).
1099 len = readv(net_info->tunfd, iov, in);
1101 warn("Failed to read from tun (%d).", errno);
1104 * Mark that packet buffer as used, but don't interrupt here. We want
1105 * to wait until we've done as much work as we can.
1107 add_used(vq, head, len);
1111 /* This is the helper to create threads: run the service routine in a loop. */
1112 static int do_thread(void *_vq)
1114 struct virtqueue *vq = _vq;
1122 * When a child dies, we kill our entire process group with SIGTERM. This
1123 * also has the side effect that the shell restores the console for us!
1125 static void kill_launcher(int signal)
1130 static void reset_vq_pci_config(struct virtqueue *vq)
1132 vq->pci_config.queue_size = VIRTQUEUE_NUM;
1133 vq->pci_config.queue_enable = 0;
1136 static void reset_device(struct device *dev)
1138 struct virtqueue *vq;
1140 verbose("Resetting device %s\n", dev->name);
1142 /* Clear any features they've acked. */
1143 dev->features_accepted = 0;
1145 /* We're going to be explicitly killing threads, so ignore them. */
1146 signal(SIGCHLD, SIG_IGN);
1151 * The device MUST present a 0 in queue_enable on reset.
1153 * This means we set it here, and reset the saved ones in every vq.
1155 dev->mmio->cfg.queue_enable = 0;
1157 /* Get rid of the virtqueue threads */
1158 for (vq = dev->vq; vq; vq = vq->next) {
1159 vq->last_avail_idx = 0;
1160 reset_vq_pci_config(vq);
1161 if (vq->thread != (pid_t)-1) {
1162 kill(vq->thread, SIGTERM);
1163 waitpid(vq->thread, NULL, 0);
1164 vq->thread = (pid_t)-1;
1167 dev->running = false;
1168 dev->wrote_features_ok = false;
1170 /* Now we care if threads die. */
1171 signal(SIGCHLD, (void *)kill_launcher);
1174 static void cleanup_devices(void)
1178 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1179 struct device *d = devices.pci[i];
1185 /* If we saved off the original terminal settings, restore them now. */
1186 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1187 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
1191 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1195 /* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1196 static struct device pci_host_bridge;
1198 static void init_pci_host_bridge(void)
1200 pci_host_bridge.name = "PCI Host Bridge";
1201 pci_host_bridge.config.class = 0x06; /* bridge */
1202 pci_host_bridge.config.subclass = 0; /* host bridge */
1203 devices.pci[0] = &pci_host_bridge;
1206 /* The IO ports used to read the PCI config space. */
1207 #define PCI_CONFIG_ADDR 0xCF8
1208 #define PCI_CONFIG_DATA 0xCFC
1211 * Not really portable, but does help readability: this is what the Guest
1212 * writes to the PCI_CONFIG_ADDR IO port.
1214 union pci_config_addr {
1218 unsigned funcnum: 3;
1221 unsigned reserved: 7;
1222 unsigned enabled : 1;
1228 * We cache what they wrote to the address port, so we know what they're
1229 * talking about when they access the data port.
1231 static union pci_config_addr pci_config_addr;
1233 static struct device *find_pci_device(unsigned int index)
1235 return devices.pci[index];
1238 /* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1239 static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1242 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1243 *val = (v >> (off * 8)) & mask;
1246 /* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1247 static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1250 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1251 *dst &= ~(mask << (off * 8));
1252 *dst |= (v & mask) << (off * 8);
1256 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1259 static struct device *dev_and_reg(u32 *reg)
1261 if (!pci_config_addr.bits.enabled)
1264 if (pci_config_addr.bits.funcnum != 0)
1267 if (pci_config_addr.bits.busnum != 0)
1270 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1273 *reg = pci_config_addr.bits.offset;
1274 return find_pci_device(pci_config_addr.bits.devnum);
1278 * We can get invalid combinations of values while they're writing, so we
1279 * only fault if they try to write with some invalid bar/offset/length.
1281 static bool valid_bar_access(struct device *d,
1282 struct virtio_pci_cfg_cap *cfg_access)
1284 /* We only have 1 bar (BAR0) */
1285 if (cfg_access->cap.bar != 0)
1288 /* Check it's within BAR0. */
1289 if (cfg_access->cap.offset >= d->mmio_size
1290 || cfg_access->cap.offset + cfg_access->cap.length > d->mmio_size)
1293 /* Check length is 1, 2 or 4. */
1294 if (cfg_access->cap.length != 1
1295 && cfg_access->cap.length != 2
1296 && cfg_access->cap.length != 4)
1302 * The driver MUST NOT write a cap.offset which is not a multiple of
1303 * cap.length (ie. all accesses MUST be aligned).
1305 if (cfg_access->cap.offset % cfg_access->cap.length != 0)
1308 /* Return pointer into word in BAR0. */
1312 /* Is this accessing the PCI config address port?. */
1313 static bool is_pci_addr_port(u16 port)
1315 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1318 static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1320 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1321 &pci_config_addr.val);
1322 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1323 pci_config_addr.bits.enabled ? "" : " DISABLED",
1325 pci_config_addr.bits.busnum,
1326 pci_config_addr.bits.devnum,
1327 pci_config_addr.bits.funcnum,
1328 pci_config_addr.bits.offset);
1332 static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1334 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1337 /* Is this accessing the PCI config data port?. */
1338 static bool is_pci_data_port(u16 port)
1340 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1343 static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask);
1345 static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1348 struct device *d = dev_and_reg(®);
1350 /* Complain if they don't belong to a device. */
1354 /* They can do 1 byte writes, etc. */
1355 portoff = port - PCI_CONFIG_DATA;
1358 * PCI uses a weird way to determine the BAR size: the OS
1359 * writes all 1's, and sees which ones stick.
1361 if (&d->config_words[reg] == &d->config.bar[0]) {
1364 iowrite(portoff, val, mask, &d->config.bar[0]);
1365 for (i = 0; (1 << i) < d->mmio_size; i++)
1366 d->config.bar[0] &= ~(1 << i);
1368 } else if ((&d->config_words[reg] > &d->config.bar[0]
1369 && &d->config_words[reg] <= &d->config.bar[6])
1370 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1371 /* Allow writing to any other BAR, or expansion ROM */
1372 iowrite(portoff, val, mask, &d->config_words[reg]);
1374 /* We let them overide latency timer and cacheline size */
1375 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1376 /* Only let them change the first two fields. */
1377 if (mask == 0xFFFFFFFF)
1379 iowrite(portoff, val, mask, &d->config_words[reg]);
1381 } else if (&d->config_words[reg] == (void *)&d->config.command
1382 && mask == 0xFFFF) {
1383 /* Ignore command writes. */
1385 } else if (&d->config_words[reg]
1386 == (void *)&d->config.cfg_access.cap.bar
1387 || &d->config_words[reg]
1388 == &d->config.cfg_access.cap.length
1389 || &d->config_words[reg]
1390 == &d->config.cfg_access.cap.offset) {
1393 * The VIRTIO_PCI_CAP_PCI_CFG capability
1394 * provides a backdoor to access the MMIO
1395 * regions without mapping them. Weird, but
1398 iowrite(portoff, val, mask, &d->config_words[reg]);
1400 } else if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
1406 * Upon detecting driver write access to pci_cfg_data, the
1407 * device MUST execute a write access at offset cap.offset at
1408 * BAR selected by cap.bar using the first cap.length bytes
1409 * from pci_cfg_data.
1413 if (!valid_bar_access(d, &d->config.cfg_access))
1416 iowrite(portoff, val, mask, &d->config.cfg_access.pci_cfg_data);
1419 * Now emulate a write. The mask we use is set by
1420 * len, *not* this write!
1422 write_mask = (1ULL<<(8*d->config.cfg_access.cap.length)) - 1;
1423 verbose("Window writing %#x/%#x to bar %u, offset %u len %u\n",
1424 d->config.cfg_access.pci_cfg_data, write_mask,
1425 d->config.cfg_access.cap.bar,
1426 d->config.cfg_access.cap.offset,
1427 d->config.cfg_access.cap.length);
1429 emulate_mmio_write(d, d->config.cfg_access.cap.offset,
1430 d->config.cfg_access.pci_cfg_data,
1438 * The driver MUST NOT write into any field of the capability
1439 * structure, with the exception of those with cap_type
1440 * VIRTIO_PCI_CAP_PCI_CFG...
1445 static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask);
1447 static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1450 struct device *d = dev_and_reg(®);
1455 /* Read through the PCI MMIO access window is special */
1456 if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
1462 * Upon detecting driver read access to pci_cfg_data, the
1463 * device MUST execute a read access of length cap.length at
1464 * offset cap.offset at BAR selected by cap.bar and store the
1465 * first cap.length bytes in pci_cfg_data.
1468 if (!valid_bar_access(d, &d->config.cfg_access))
1469 errx(1, "Invalid cfg_access to bar%u, offset %u len %u",
1470 d->config.cfg_access.cap.bar,
1471 d->config.cfg_access.cap.offset,
1472 d->config.cfg_access.cap.length);
1475 * Read into the window. The mask we use is set by
1476 * len, *not* this read!
1478 read_mask = (1ULL<<(8*d->config.cfg_access.cap.length))-1;
1479 d->config.cfg_access.pci_cfg_data
1480 = emulate_mmio_read(d,
1481 d->config.cfg_access.cap.offset,
1483 verbose("Window read %#x/%#x from bar %u, offset %u len %u\n",
1484 d->config.cfg_access.pci_cfg_data, read_mask,
1485 d->config.cfg_access.cap.bar,
1486 d->config.cfg_access.cap.offset,
1487 d->config.cfg_access.cap.length);
1489 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1493 * This is where we emulate a handful of Guest instructions. It's ugly
1494 * and we used to do it in the kernel but it grew over time.
1498 * We use the ptrace syscall's pt_regs struct to talk about registers
1499 * to lguest: these macros convert the names to the offsets.
1501 #define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1502 #define setreg(name, val) \
1503 setreg_off(offsetof(struct user_regs_struct, name), (val))
1505 static u32 getreg_off(size_t offset)
1508 unsigned long args[] = { LHREQ_GETREG, offset };
1510 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1511 err(1, "Getting register %u", offset);
1512 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1513 err(1, "Reading register %u", offset);
1518 static void setreg_off(size_t offset, u32 val)
1520 unsigned long args[] = { LHREQ_SETREG, offset, val };
1522 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1523 err(1, "Setting register %u", offset);
1526 /* Get register by instruction encoding */
1527 static u32 getreg_num(unsigned regnum, u32 mask)
1529 /* 8 bit ops use regnums 4-7 for high parts of word */
1530 if (mask == 0xFF && (regnum & 0x4))
1531 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1534 case 0: return getreg(eax) & mask;
1535 case 1: return getreg(ecx) & mask;
1536 case 2: return getreg(edx) & mask;
1537 case 3: return getreg(ebx) & mask;
1538 case 4: return getreg(esp) & mask;
1539 case 5: return getreg(ebp) & mask;
1540 case 6: return getreg(esi) & mask;
1541 case 7: return getreg(edi) & mask;
1546 /* Set register by instruction encoding */
1547 static void setreg_num(unsigned regnum, u32 val, u32 mask)
1549 /* Don't try to set bits out of range */
1550 assert(~(val & ~mask));
1552 /* 8 bit ops use regnums 4-7 for high parts of word */
1553 if (mask == 0xFF && (regnum & 0x4)) {
1554 /* Construct the 16 bits we want. */
1555 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1556 setreg_num(regnum & 0x3, val, 0xFFFF);
1561 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1562 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1563 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1564 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1565 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1566 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1567 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1568 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1573 /* Get bytes of displacement appended to instruction, from r/m encoding */
1574 static u32 insn_displacement_len(u8 mod_reg_rm)
1576 /* Switch on the mod bits */
1577 switch (mod_reg_rm >> 6) {
1579 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1580 if ((mod_reg_rm & 0x7) == 0x5)
1582 /* Normally, mod == 0 means no literal displacement */
1585 /* One byte displacement */
1588 /* Four byte displacement */
1597 static void emulate_insn(const u8 insn[])
1599 unsigned long args[] = { LHREQ_TRAP, 13 };
1600 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1601 unsigned int eax, port, mask;
1603 * Default is to return all-ones on IO port reads, which traditionally
1604 * means "there's nothing there".
1606 u32 val = 0xFFFFFFFF;
1609 * This must be the Guest kernel trying to do something, not userspace!
1610 * The bottom two bits of the CS segment register are the privilege
1613 if ((getreg(xcs) & 3) != 0x1)
1616 /* Decoding x86 instructions is icky. */
1619 * Around 2.6.33, the kernel started using an emulation for the
1620 * cmpxchg8b instruction in early boot on many configurations. This
1621 * code isn't paravirtualized, and it tries to disable interrupts.
1622 * Ignore it, which will Mostly Work.
1624 if (insn[insnlen] == 0xfa) {
1625 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1631 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1633 if (insn[insnlen] == 0x66) {
1635 /* The instruction is 1 byte so far, read the next byte. */
1639 /* If the lower bit isn't set, it's a single byte access */
1640 byte_access = !(insn[insnlen] & 1);
1643 * Now we can ignore the lower bit and decode the 4 opcodes
1644 * we need to emulate.
1646 switch (insn[insnlen] & 0xFE) {
1647 case 0xE4: /* in <next byte>,%al */
1648 port = insn[insnlen+1];
1652 case 0xEC: /* in (%dx),%al */
1653 port = getreg(edx) & 0xFFFF;
1657 case 0xE6: /* out %al,<next byte> */
1658 port = insn[insnlen+1];
1661 case 0xEE: /* out %al,(%dx) */
1662 port = getreg(edx) & 0xFFFF;
1666 /* OK, we don't know what this is, can't emulate. */
1670 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1673 else if (small_operand)
1679 * If it was an "IN" instruction, they expect the result to be read
1680 * into %eax, so we change %eax.
1685 /* This is the PS/2 keyboard status; 1 means ready for output */
1688 else if (is_pci_addr_port(port))
1689 pci_addr_ioread(port, mask, &val);
1690 else if (is_pci_data_port(port))
1691 pci_data_ioread(port, mask, &val);
1693 /* Clear the bits we're about to read */
1695 /* Copy bits in from val. */
1697 /* Now update the register. */
1700 if (is_pci_addr_port(port)) {
1701 if (!pci_addr_iowrite(port, mask, eax))
1703 } else if (is_pci_data_port(port)) {
1704 if (!pci_data_iowrite(port, mask, eax))
1707 /* There are many other ports, eg. CMOS clock, serial
1708 * and parallel ports, so we ignore them all. */
1711 verbose("IO %s of %x to %u: %#08x\n",
1712 in ? "IN" : "OUT", mask, port, eax);
1714 /* Finally, we've "done" the instruction, so move past it. */
1715 setreg(eip, getreg(eip) + insnlen);
1719 warnx("Attempt to %s port %u (%#x mask)",
1720 in ? "read from" : "write to", port, mask);
1723 /* Inject trap into Guest. */
1724 if (write(lguest_fd, args, sizeof(args)) < 0)
1725 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1728 static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1732 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1733 struct device *d = devices.pci[i];
1737 if (paddr < d->mmio_addr)
1739 if (paddr >= d->mmio_addr + d->mmio_size)
1741 *off = paddr - d->mmio_addr;
1747 /* FIXME: Use vq array. */
1748 static struct virtqueue *vq_by_num(struct device *d, u32 num)
1750 struct virtqueue *vq = d->vq;
1758 static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1759 struct virtqueue *vq)
1761 vq->pci_config = *cfg;
1764 static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1765 struct virtqueue *vq)
1767 /* Only restore the per-vq part */
1768 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1770 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1771 sizeof(*cfg) - off);
1777 * The driver MUST configure the other virtqueue fields before
1778 * enabling the virtqueue with queue_enable.
1780 * When they enable the virtqueue, we check that their setup is valid.
1782 static void check_virtqueue(struct device *d, struct virtqueue *vq)
1784 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1785 if (vq->pci_config.queue_desc_hi
1786 || vq->pci_config.queue_avail_hi
1787 || vq->pci_config.queue_used_hi)
1788 errx(1, "%s: invalid 64-bit queue address", d->name);
1793 * The driver MUST ensure that the physical address of the first byte
1794 * of each virtqueue part is a multiple of the specified alignment
1795 * value in the above table.
1797 if (vq->pci_config.queue_desc_lo % 16
1798 || vq->pci_config.queue_avail_lo % 2
1799 || vq->pci_config.queue_used_lo % 4)
1800 errx(1, "%s: invalid alignment in queue addresses", d->name);
1802 /* Initialize the virtqueue and check they're all in range. */
1803 vq->vring.num = vq->pci_config.queue_size;
1804 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1805 sizeof(*vq->vring.desc) * vq->vring.num);
1806 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1807 sizeof(*vq->vring.avail)
1808 + (sizeof(vq->vring.avail->ring[0])
1810 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1811 sizeof(*vq->vring.used)
1812 + (sizeof(vq->vring.used->ring[0])
1818 * The driver MUST initialize flags in the used ring to 0
1819 * when allocating the used ring.
1821 if (vq->vring.used->flags != 0)
1822 errx(1, "%s: invalid initial used.flags %#x",
1823 d->name, vq->vring.used->flags);
1826 static void start_virtqueue(struct virtqueue *vq)
1829 * Create stack for thread. Since the stack grows upwards, we point
1830 * the stack pointer to the end of this region.
1832 char *stack = malloc(32768);
1834 /* Create a zero-initialized eventfd. */
1835 vq->eventfd = eventfd(0, 0);
1836 if (vq->eventfd < 0)
1837 err(1, "Creating eventfd");
1840 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1841 * we get a signal if it dies.
1843 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1844 if (vq->thread == (pid_t)-1)
1845 err(1, "Creating clone");
1848 static void start_virtqueues(struct device *d)
1850 struct virtqueue *vq;
1852 for (vq = d->vq; vq; vq = vq->next) {
1853 if (vq->pci_config.queue_enable)
1854 start_virtqueue(vq);
1858 static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1860 struct virtqueue *vq;
1863 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1867 * The device MUST present the feature bits it is offering in
1868 * device_feature, starting at bit device_feature_select ∗ 32
1869 * for any device_feature_select written by the driver
1872 d->mmio->cfg.device_feature = d->features;
1874 d->mmio->cfg.device_feature = (d->features >> 32);
1876 d->mmio->cfg.device_feature = 0;
1877 goto feature_write_through32;
1878 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1880 errx(1, "%s: Unexpected driver select %u",
1882 goto feature_write_through32;
1883 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1884 if (d->mmio->cfg.guest_feature_select == 0) {
1885 d->features_accepted &= ~((u64)0xFFFFFFFF);
1886 d->features_accepted |= val;
1888 assert(d->mmio->cfg.guest_feature_select == 1);
1889 d->features_accepted &= 0xFFFFFFFF;
1890 d->features_accepted |= ((u64)val) << 32;
1895 * The driver MUST NOT accept a feature which the device did
1898 if (d->features_accepted & ~d->features)
1899 errx(1, "%s: over-accepted features %#llx of %#llx",
1900 d->name, d->features_accepted, d->features);
1901 goto feature_write_through32;
1902 case offsetof(struct virtio_pci_mmio, cfg.device_status): {
1905 verbose("%s: device status -> %#x\n", d->name, val);
1909 * The device MUST reset when 0 is written to device_status,
1910 * and present a 0 in device_status once that is done.
1914 goto write_through8;
1917 /* 2.1.1: The driver MUST NOT clear a device status bit. */
1918 if (d->mmio->cfg.device_status & ~val)
1919 errx(1, "%s: unset of device status bit %#x -> %#x",
1920 d->name, d->mmio->cfg.device_status, val);
1925 * The device MUST NOT consume buffers or notify the driver
1928 if (val & VIRTIO_CONFIG_S_DRIVER_OK
1929 && !(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
1930 start_virtqueues(d);
1935 * The driver MUST follow this sequence to initialize a device:
1936 * - Reset the device.
1937 * - Set the ACKNOWLEDGE status bit: the guest OS has
1938 * notice the device.
1939 * - Set the DRIVER status bit: the guest OS knows how
1940 * to drive the device.
1941 * - Read device feature bits, and write the subset
1942 * of feature bits understood by the OS and driver
1943 * to the device. During this step the driver MAY
1944 * read (but MUST NOT write) the device-specific
1945 * configuration fields to check that it can
1946 * support the device before accepting it.
1947 * - Set the FEATURES_OK status bit. The driver
1948 * MUST not accept new feature bits after this
1950 * - Re-read device status to ensure the FEATURES_OK
1951 * bit is still set: otherwise, the device does
1952 * not support our subset of features and the
1953 * device is unusable.
1954 * - Perform device-specific setup, including
1955 * discovery of virtqueues for the device,
1956 * optional per-bus setup, reading and possibly
1957 * writing the device’s virtio configuration
1958 * space, and population of virtqueues.
1959 * - Set the DRIVER_OK status bit. At this point the
1963 switch (val & ~d->mmio->cfg.device_status) {
1964 case VIRTIO_CONFIG_S_DRIVER_OK:
1965 prev |= VIRTIO_CONFIG_S_FEATURES_OK; /* fall thru */
1966 case VIRTIO_CONFIG_S_FEATURES_OK:
1967 prev |= VIRTIO_CONFIG_S_DRIVER; /* fall thru */
1968 case VIRTIO_CONFIG_S_DRIVER:
1969 prev |= VIRTIO_CONFIG_S_ACKNOWLEDGE; /* fall thru */
1970 case VIRTIO_CONFIG_S_ACKNOWLEDGE:
1973 errx(1, "%s: unknown device status bit %#x -> %#x",
1974 d->name, d->mmio->cfg.device_status, val);
1976 if (d->mmio->cfg.device_status != prev)
1977 errx(1, "%s: unexpected status transition %#x -> %#x",
1978 d->name, d->mmio->cfg.device_status, val);
1980 /* If they just wrote FEATURES_OK, we make sure they read */
1981 switch (val & ~d->mmio->cfg.device_status) {
1982 case VIRTIO_CONFIG_S_FEATURES_OK:
1983 d->wrote_features_ok = true;
1985 case VIRTIO_CONFIG_S_DRIVER_OK:
1986 if (d->wrote_features_ok)
1987 errx(1, "%s: did not re-read FEATURES_OK",
1991 goto write_through8;
1993 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1994 vq = vq_by_num(d, val);
1998 * The device MUST present a 0 in queue_size if the virtqueue
1999 * corresponding to the current queue_select is unavailable.
2002 d->mmio->cfg.queue_size = 0;
2003 goto write_through16;
2005 /* Save registers for old vq, if it was a valid vq */
2006 if (d->mmio->cfg.queue_size)
2007 save_vq_config(&d->mmio->cfg,
2008 vq_by_num(d, d->mmio->cfg.queue_select));
2009 /* Restore the registers for the queue they asked for */
2010 restore_vq_config(&d->mmio->cfg, vq);
2011 goto write_through16;
2012 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
2016 * The driver MUST NOT write a value which is not a power of 2
2020 errx(1, "%s: invalid queue size %u\n", d->name, val);
2021 if (d->mmio->cfg.queue_enable)
2022 errx(1, "%s: changing queue size on live device",
2024 goto write_through16;
2025 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
2026 errx(1, "%s: attempt to set MSIX vector to %u",
2028 case offsetof(struct virtio_pci_mmio, cfg.queue_enable): {
2029 struct virtqueue *vq = vq_by_num(d, d->mmio->cfg.queue_select);
2034 * The driver MUST NOT write a 0 to queue_enable.
2037 errx(1, "%s: setting queue_enable to %u", d->name, val);
2042 * 7. Perform device-specific setup, including discovery of
2043 * virtqueues for the device, optional per-bus setup,
2044 * reading and possibly writing the device’s virtio
2045 * configuration space, and population of virtqueues.
2046 * 8. Set the DRIVER_OK status bit.
2048 * All our devices require all virtqueues to be enabled, so
2049 * they should have done that before setting DRIVER_OK.
2051 if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK)
2052 errx(1, "%s: enabling vs after DRIVER_OK", d->name);
2054 d->mmio->cfg.queue_enable = val;
2055 save_vq_config(&d->mmio->cfg, vq);
2056 check_virtqueue(d, vq);
2057 goto write_through16;
2059 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
2060 errx(1, "%s: attempt to write to queue_notify_off", d->name);
2061 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
2062 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
2063 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
2064 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
2065 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
2066 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
2070 * The driver MUST configure the other virtqueue fields before
2071 * enabling the virtqueue with queue_enable.
2073 if (d->mmio->cfg.queue_enable)
2074 errx(1, "%s: changing queue on live device",
2080 * The driver MUST follow this sequence to initialize a device:
2082 * 5. Set the FEATURES_OK status bit. The driver MUST not
2083 * accept new feature bits after this step.
2085 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK))
2086 errx(1, "%s: enabling vs before FEATURES_OK", d->name);
2089 * 6. Re-read device status to ensure the FEATURES_OK bit is
2092 if (d->wrote_features_ok)
2093 errx(1, "%s: didn't re-read FEATURES_OK before setup",
2096 goto write_through32;
2097 case offsetof(struct virtio_pci_mmio, notify):
2098 vq = vq_by_num(d, val);
2100 errx(1, "Invalid vq notification on %u", val);
2101 /* Notify the process handling this vq by adding 1 to eventfd */
2102 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
2103 goto write_through16;
2104 case offsetof(struct virtio_pci_mmio, isr):
2105 errx(1, "%s: Unexpected write to isr", d->name);
2106 /* Weird corner case: write to emerg_wr of console */
2107 case sizeof(struct virtio_pci_mmio)
2108 + offsetof(struct virtio_console_config, emerg_wr):
2109 if (strcmp(d->name, "console") == 0) {
2111 write(STDOUT_FILENO, &c, 1);
2112 goto write_through32;
2114 /* Fall through... */
2119 * The driver MUST NOT write to device_feature, num_queues,
2120 * config_generation or queue_notify_off.
2122 errx(1, "%s: Unexpected write to offset %u", d->name, off);
2125 feature_write_through32:
2129 * The driver MUST follow this sequence to initialize a device:
2131 * - Set the DRIVER status bit: the guest OS knows how
2132 * to drive the device.
2133 * - Read device feature bits, and write the subset
2134 * of feature bits understood by the OS and driver
2137 * - Set the FEATURES_OK status bit. The driver MUST not
2138 * accept new feature bits after this step.
2140 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2141 errx(1, "%s: feature write before VIRTIO_CONFIG_S_DRIVER",
2143 if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK)
2144 errx(1, "%s: feature write after VIRTIO_CONFIG_S_FEATURES_OK",
2150 * The driver MUST access each field using the “natural” access
2151 * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
2152 * 16-bit fields and 8-bit accesses for 8-bit fields.
2155 if (mask != 0xFFFFFFFF) {
2156 errx(1, "%s: non-32-bit write to offset %u (%#x)",
2157 d->name, off, getreg(eip));
2160 memcpy((char *)d->mmio + off, &val, 4);
2165 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
2166 d->name, mask, off, getreg(eip));
2167 memcpy((char *)d->mmio + off, &val, 2);
2172 errx(1, "%s: non-8-bit write to offset %u (%#x)",
2173 d->name, off, getreg(eip));
2174 memcpy((char *)d->mmio + off, &val, 1);
2178 static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
2184 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
2185 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
2186 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
2187 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
2191 * The driver MUST follow this sequence to initialize a device:
2193 * - Set the DRIVER status bit: the guest OS knows how
2194 * to drive the device.
2195 * - Read device feature bits, and write the subset
2196 * of feature bits understood by the OS and driver
2199 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2200 errx(1, "%s: feature read before VIRTIO_CONFIG_S_DRIVER",
2202 goto read_through32;
2203 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
2204 errx(1, "%s: read of msix_config", d->name);
2205 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
2206 goto read_through16;
2207 case offsetof(struct virtio_pci_mmio, cfg.device_status):
2208 /* As they did read, any write of FEATURES_OK is now fine. */
2209 d->wrote_features_ok = false;
2211 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
2215 * The device MUST present a changed config_generation after
2216 * the driver has read a device-specific configuration value
2217 * which has changed since any part of the device-specific
2218 * configuration was last read.
2220 * This is simple: none of our devices change config, so this
2224 case offsetof(struct virtio_pci_mmio, notify):
2228 * The driver MUST NOT notify the device before setting
2231 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
2232 errx(1, "%s: notify before VIRTIO_CONFIG_S_DRIVER_OK",
2234 goto read_through16;
2235 case offsetof(struct virtio_pci_mmio, isr):
2237 errx(1, "%s: non-8-bit read from offset %u (%#x)",
2238 d->name, off, getreg(eip));
2243 * The device MUST reset ISR status to 0 on driver read.
2247 case offsetof(struct virtio_pci_mmio, padding):
2248 errx(1, "%s: read from padding (%#x)",
2249 d->name, getreg(eip));
2251 /* Read from device config space, beware unaligned overflow */
2252 if (off > d->mmio_size - 4)
2253 errx(1, "%s: read past end (%#x)",
2254 d->name, getreg(eip));
2258 * The driver MUST follow this sequence to initialize a device:
2260 * 3. Set the DRIVER status bit: the guest OS knows how to
2262 * 4. Read device feature bits, and write the subset of
2263 * feature bits understood by the OS and driver to the
2264 * device. During this step the driver MAY read (but MUST NOT
2265 * write) the device-specific configuration fields to check
2266 * that it can support the device before accepting it.
2268 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2269 errx(1, "%s: config read before VIRTIO_CONFIG_S_DRIVER",
2272 if (mask == 0xFFFFFFFF)
2273 goto read_through32;
2274 else if (mask == 0xFFFF)
2275 goto read_through16;
2283 * The driver MUST access each field using the “natural” access
2284 * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
2285 * 16-bit fields and 8-bit accesses for 8-bit fields.
2288 if (mask != 0xFFFFFFFF)
2289 errx(1, "%s: non-32-bit read to offset %u (%#x)",
2290 d->name, off, getreg(eip));
2291 memcpy(&val, (char *)d->mmio + off, 4);
2296 errx(1, "%s: non-16-bit read to offset %u (%#x)",
2297 d->name, off, getreg(eip));
2298 memcpy(&val, (char *)d->mmio + off, 2);
2303 errx(1, "%s: non-8-bit read to offset %u (%#x)",
2304 d->name, off, getreg(eip));
2305 memcpy(&val, (char *)d->mmio + off, 1);
2309 static void emulate_mmio(unsigned long paddr, const u8 *insn)
2311 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
2312 struct device *d = find_mmio_region(paddr, &off);
2313 unsigned long args[] = { LHREQ_TRAP, 14 };
2316 warnx("MMIO touching %#08lx (not a device)", paddr);
2320 /* Prefix makes it a 16 bit op */
2321 if (insn[0] == 0x66) {
2327 if (insn[insnlen] == 0x89) {
2328 /* Next byte is r/m byte: bits 3-5 are register. */
2329 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
2330 emulate_mmio_write(d, off, val, mask);
2331 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2332 } else if (insn[insnlen] == 0x8b) { /* ioread */
2333 /* Next byte is r/m byte: bits 3-5 are register. */
2334 val = emulate_mmio_read(d, off, mask);
2335 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
2336 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2337 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
2339 /* Next byte is r/m byte: bits 3-5 are register. */
2340 val = getreg_num((insn[1] >> 3) & 0x7, mask);
2341 emulate_mmio_write(d, off, val, mask);
2342 insnlen = 2 + insn_displacement_len(insn[1]);
2343 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
2345 val = emulate_mmio_read(d, off, mask);
2346 setreg_num((insn[1] >> 3) & 0x7, val, mask);
2347 insnlen = 2 + insn_displacement_len(insn[1]);
2349 warnx("Unknown MMIO instruction touching %#08lx:"
2350 " %02x %02x %02x %02x at %u",
2351 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
2353 /* Inject trap into Guest. */
2354 if (write(lguest_fd, args, sizeof(args)) < 0)
2355 err(1, "Reinjecting trap 14 for fault at %#x",
2360 /* Finally, we've "done" the instruction, so move past it. */
2361 setreg(eip, getreg(eip) + insnlen);
2367 * All devices need a descriptor so the Guest knows it exists, and a "struct
2368 * device" so the Launcher can keep track of it. We have common helper
2369 * routines to allocate and manage them.
2371 static void add_pci_virtqueue(struct device *dev,
2372 void (*service)(struct virtqueue *),
2375 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2377 /* Initialize the virtqueue */
2379 vq->last_avail_idx = 0;
2384 * This is the routine the service thread will run, and its Process ID
2385 * once it's running.
2387 vq->service = service;
2388 vq->thread = (pid_t)-1;
2390 /* Initialize the configuration. */
2391 reset_vq_pci_config(vq);
2392 vq->pci_config.queue_notify_off = 0;
2394 /* Add one to the number of queues */
2395 vq->dev->mmio->cfg.num_queues++;
2398 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2401 for (i = &dev->vq; *i; i = &(*i)->next);
2405 /* The Guest accesses the feature bits via the PCI common config MMIO region */
2406 static void add_pci_feature(struct device *dev, unsigned bit)
2408 dev->features |= (1ULL << bit);
2411 /* For devices with no config. */
2412 static void no_device_config(struct device *dev)
2414 dev->mmio_addr = get_mmio_region(dev->mmio_size);
2416 dev->config.bar[0] = dev->mmio_addr;
2417 /* Bottom 4 bits must be zero */
2418 assert(~(dev->config.bar[0] & 0xF));
2421 /* This puts the device config into BAR0 */
2422 static void set_device_config(struct device *dev, const void *conf, size_t len)
2425 dev->mmio_size += len;
2426 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2427 memcpy(dev->mmio + 1, conf, len);
2432 * The device MUST present at least one VIRTIO_PCI_CAP_DEVICE_CFG
2433 * capability for any device type which has a device-specific
2436 /* Hook up device cfg */
2437 dev->config.cfg_access.cap.cap_next
2438 = offsetof(struct pci_config, device);
2443 * The offset for the device-specific configuration MUST be 4-byte
2446 assert(dev->config.cfg_access.cap.cap_next % 4 == 0);
2448 /* Fix up device cfg field length. */
2449 dev->config.device.length = len;
2451 /* The rest is the same as the no-config case */
2452 no_device_config(dev);
2455 static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2456 size_t bar_offset, size_t bar_bytes, u8 next)
2458 cap->cap_vndr = PCI_CAP_ID_VNDR;
2459 cap->cap_next = next;
2460 cap->cap_len = caplen;
2461 cap->cfg_type = type;
2463 memset(cap->padding, 0, sizeof(cap->padding));
2464 cap->offset = bar_offset;
2465 cap->length = bar_bytes;
2469 * This sets up the pci_config structure, as defined in the virtio 1.0
2470 * standard (and PCI standard).
2472 static void init_pci_config(struct pci_config *pci, u16 type,
2473 u8 class, u8 subclass)
2475 size_t bar_offset, bar_len;
2480 * The device MUST either present notify_off_multiplier as an even
2481 * power of 2, or present notify_off_multiplier as 0.
2485 * The device MUST initialize device status to 0 upon reset.
2487 memset(pci, 0, sizeof(*pci));
2489 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2490 pci->vendor_id = 0x1AF4;
2491 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2492 pci->device_id = 0x1040 + type;
2495 * PCI have specific codes for different types of devices.
2496 * Linux doesn't care, but it's a good clue for people looking
2500 pci->subclass = subclass;
2505 * Non-transitional devices SHOULD have a PCI Revision ID of 1 or
2513 * Non-transitional devices SHOULD have a PCI Subsystem Device ID of
2516 pci->subsystem_device_id = 0x40;
2518 /* We use our dummy interrupt controller, and irq_line is the irq */
2519 pci->irq_line = devices.next_irq++;
2522 /* Support for extended capabilities. */
2523 pci->status = (1 << 4);
2529 * The device MUST present at least one common configuration
2532 pci->capabilities = offsetof(struct pci_config, common);
2534 /* 4.1.4.3.1 ... offset MUST be 4-byte aligned. */
2535 assert(pci->capabilities % 4 == 0);
2537 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2538 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2539 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2540 bar_offset, bar_len,
2541 offsetof(struct pci_config, notify));
2546 * The device MUST present at least one notification capability.
2548 bar_offset += bar_len;
2549 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2554 * The cap.offset MUST be 2-byte aligned.
2556 assert(pci->common.cap_next % 2 == 0);
2558 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2562 * The value cap.length presented by the device MUST be at least 2 and
2563 * MUST be large enough to support queue notification offsets for all
2564 * supported queues in all possible configurations.
2566 assert(bar_len >= 2);
2568 init_cap(&pci->notify.cap, sizeof(pci->notify),
2569 VIRTIO_PCI_CAP_NOTIFY_CFG,
2570 bar_offset, bar_len,
2571 offsetof(struct pci_config, isr));
2573 bar_offset += bar_len;
2574 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2578 * The device MUST present at least one VIRTIO_PCI_CAP_ISR_CFG
2581 init_cap(&pci->isr, sizeof(pci->isr),
2582 VIRTIO_PCI_CAP_ISR_CFG,
2583 bar_offset, bar_len,
2584 offsetof(struct pci_config, cfg_access));
2589 * The device MUST present at least one VIRTIO_PCI_CAP_PCI_CFG
2592 /* This doesn't have any presence in the BAR */
2593 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2594 VIRTIO_PCI_CAP_PCI_CFG,
2597 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2598 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2601 * This gets sewn in and length set in set_device_config().
2602 * Some devices don't have a device configuration interface, so
2603 * we never expose this if we don't call set_device_config().
2605 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2610 * This routine does all the creation and setup of a new device, but we don't
2611 * actually place the MMIO region until we know the size (if any) of the
2612 * device-specific config. And we don't actually start the service threads
2615 * See what I mean about userspace being boring?
2617 static struct device *new_pci_device(const char *name, u16 type,
2618 u8 class, u8 subclass)
2620 struct device *dev = malloc(sizeof(*dev));
2622 /* Now we populate the fields one at a time. */
2625 dev->running = false;
2626 dev->wrote_features_ok = false;
2627 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2628 dev->mmio = calloc(1, dev->mmio_size);
2629 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2630 dev->features_accepted = 0;
2632 if (devices.device_num + 1 >= MAX_PCI_DEVICES)
2633 errx(1, "Can only handle 31 PCI devices");
2635 init_pci_config(&dev->config, type, class, subclass);
2636 assert(!devices.pci[devices.device_num+1]);
2637 devices.pci[++devices.device_num] = dev;
2643 * Our first setup routine is the console. It's a fairly simple device, but
2644 * UNIX tty handling makes it uglier than it could be.
2646 static void setup_console(void)
2649 struct virtio_console_config conf;
2651 /* If we can save the initial standard input settings... */
2652 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2653 struct termios term = orig_term;
2655 * Then we turn off echo, line buffering and ^C etc: We want a
2656 * raw input stream to the Guest.
2658 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2659 tcsetattr(STDIN_FILENO, TCSANOW, &term);
2662 dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
2664 /* We store the console state in dev->priv, and initialize it. */
2665 dev->priv = malloc(sizeof(struct console_abort));
2666 ((struct console_abort *)dev->priv)->count = 0;
2669 * The console needs two virtqueues: the input then the output. When
2670 * they put something the input queue, we make sure we're listening to
2671 * stdin. When they put something in the output queue, we write it to
2674 add_pci_virtqueue(dev, console_input, "input");
2675 add_pci_virtqueue(dev, console_output, "output");
2677 /* We need a configuration area for the emerg_wr early writes. */
2678 add_pci_feature(dev, VIRTIO_CONSOLE_F_EMERG_WRITE);
2679 set_device_config(dev, &conf, sizeof(conf));
2681 verbose("device %u: console\n", devices.device_num);
2686 * Inter-guest networking is an interesting area. Simplest is to have a
2687 * --sharenet=<name> option which opens or creates a named pipe. This can be
2688 * used to send packets to another guest in a 1:1 manner.
2690 * More sophisticated is to use one of the tools developed for project like UML
2693 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2694 * completely generic ("here's my vring, attach to your vring") and would work
2695 * for any traffic. Of course, namespace and permissions issues need to be
2696 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2697 * multiple inter-guest channels behind one interface, although it would
2698 * require some manner of hotplugging new virtio channels.
2700 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
2703 static u32 str2ip(const char *ipaddr)
2707 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2708 errx(1, "Failed to parse IP address '%s'", ipaddr);
2709 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2712 static void str2mac(const char *macaddr, unsigned char mac[6])
2715 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2716 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2717 errx(1, "Failed to parse mac address '%s'", macaddr);
2727 * This code is "adapted" from libbridge: it attaches the Host end of the
2728 * network device to the bridge device specified by the command line.
2730 * This is yet another James Morris contribution (I'm an IP-level guy, so I
2731 * dislike bridging), and I just try not to break it.
2733 static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2739 errx(1, "must specify bridge name");
2741 ifidx = if_nametoindex(if_name);
2743 errx(1, "interface %s does not exist!", if_name);
2745 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
2746 ifr.ifr_name[IFNAMSIZ-1] = '\0';
2747 ifr.ifr_ifindex = ifidx;
2748 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2749 err(1, "can't add %s to bridge %s", if_name, br_name);
2753 * This sets up the Host end of the network device with an IP address, brings
2754 * it up so packets will flow, the copies the MAC address into the hwaddr
2757 static void configure_device(int fd, const char *tapif, u32 ipaddr)
2760 struct sockaddr_in sin;
2762 memset(&ifr, 0, sizeof(ifr));
2763 strcpy(ifr.ifr_name, tapif);
2765 /* Don't read these incantations. Just cut & paste them like I did! */
2766 sin.sin_family = AF_INET;
2767 sin.sin_addr.s_addr = htonl(ipaddr);
2768 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
2769 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
2770 err(1, "Setting %s interface address", tapif);
2771 ifr.ifr_flags = IFF_UP;
2772 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
2773 err(1, "Bringing interface %s up", tapif);
2776 static int get_tun_device(char tapif[IFNAMSIZ])
2782 /* Start with this zeroed. Messy but sure. */
2783 memset(&ifr, 0, sizeof(ifr));
2786 * We open the /dev/net/tun device and tell it we want a tap device. A
2787 * tap device is like a tun device, only somehow different. To tell
2788 * the truth, I completely blundered my way through this code, but it
2791 netfd = open_or_die("/dev/net/tun", O_RDWR);
2792 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
2793 strcpy(ifr.ifr_name, "tap%d");
2794 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2795 err(1, "configuring /dev/net/tun");
2797 if (ioctl(netfd, TUNSETOFFLOAD,
2798 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2799 err(1, "Could not set features for tun device");
2802 * We don't need checksums calculated for packets coming in this
2805 ioctl(netfd, TUNSETNOCSUM, 1);
2808 * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2809 * field at the end of the network header iff
2810 * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
2811 * that became the norm, but we need to tell the tun device
2812 * about our expanded header (which is called
2813 * virtio_net_hdr_mrg_rxbuf in the legacy system).
2815 vnet_hdr_sz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2816 if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
2817 err(1, "Setting tun header size to %u", vnet_hdr_sz);
2819 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2824 * Our network is a Host<->Guest network. This can either use bridging or
2825 * routing, but the principle is the same: it uses the "tun" device to inject
2826 * packets into the Host as if they came in from a normal network card. We
2827 * just shunt packets between the Guest and the tun device.
2829 static void setup_tun_net(char *arg)
2832 struct net_info *net_info = malloc(sizeof(*net_info));
2834 u32 ip = INADDR_ANY;
2835 bool bridging = false;
2836 char tapif[IFNAMSIZ], *p;
2837 struct virtio_net_config conf;
2839 net_info->tunfd = get_tun_device(tapif);
2841 /* First we create a new network device. */
2842 dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
2843 dev->priv = net_info;
2845 /* Network devices need a recv and a send queue, just like console. */
2846 add_pci_virtqueue(dev, net_input, "rx");
2847 add_pci_virtqueue(dev, net_output, "tx");
2850 * We need a socket to perform the magic network ioctls to bring up the
2851 * tap interface, connect to the bridge etc. Any socket will do!
2853 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2855 err(1, "opening IP socket");
2857 /* If the command line was --tunnet=bridge:<name> do bridging. */
2858 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
2859 arg += strlen(BRIDGE_PFX);
2863 /* A mac address may follow the bridge name or IP address */
2864 p = strchr(arg, ':');
2866 str2mac(p+1, conf.mac);
2867 add_pci_feature(dev, VIRTIO_NET_F_MAC);
2871 /* arg is now either an IP address or a bridge name */
2873 add_to_bridge(ipfd, tapif, arg);
2877 /* Set up the tun device. */
2878 configure_device(ipfd, tapif, ip);
2880 /* Expect Guest to handle everything except UFO */
2881 add_pci_feature(dev, VIRTIO_NET_F_CSUM);
2882 add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2883 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2884 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2885 add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2886 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2887 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2888 add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
2889 /* We handle indirect ring entries */
2890 add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2891 set_device_config(dev, &conf, sizeof(conf));
2893 /* We don't need the socket any more; setup is done. */
2897 verbose("device %u: tun %s attached to bridge: %s\n",
2898 devices.device_num, tapif, arg);
2900 verbose("device %u: tun %s: %s\n",
2901 devices.device_num, tapif, arg);
2905 /* This hangs off device->priv. */
2907 /* The size of the file. */
2910 /* The file descriptor for the file. */
2918 * The disk only has one virtqueue, so it only has one thread. It is really
2919 * simple: the Guest asks for a block number and we read or write that position
2922 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2923 * slow: the Guest waits until the read is finished before running anything
2924 * else, even if it could have been doing useful work.
2926 * We could have used async I/O, except it's reputed to suck so hard that
2927 * characters actually go missing from your code when you try to use it.
2929 static void blk_request(struct virtqueue *vq)
2931 struct vblk_info *vblk = vq->dev->priv;
2932 unsigned int head, out_num, in_num, wlen;
2935 struct virtio_blk_outhdr out;
2936 struct iovec iov[vq->vring.num];
2940 * Get the next request, where we normally wait. It triggers the
2941 * interrupt to acknowledge previously serviced requests (if any).
2943 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
2945 /* Copy the output header from the front of the iov (adjusts iov) */
2946 iov_consume(iov, out_num, &out, sizeof(out));
2948 /* Find and trim end of iov input array, for our status byte. */
2950 for (i = out_num + in_num - 1; i >= out_num; i--) {
2951 if (iov[i].iov_len > 0) {
2952 in = iov[i].iov_base + iov[i].iov_len - 1;
2958 errx(1, "Bad virtblk cmd with no room for status");
2961 * For historical reasons, block operations are expressed in 512 byte
2964 off = out.sector * 512;
2966 if (out.type & VIRTIO_BLK_T_OUT) {
2970 * Move to the right location in the block file. This can fail
2971 * if they try to write past end.
2973 if (lseek64(vblk->fd, off, SEEK_SET) != off)
2974 err(1, "Bad seek to sector %llu", out.sector);
2976 ret = writev(vblk->fd, iov, out_num);
2977 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
2980 * Grr... Now we know how long the descriptor they sent was, we
2981 * make sure they didn't try to write over the end of the block
2982 * file (possibly extending it).
2984 if (ret > 0 && off + ret > vblk->len) {
2985 /* Trim it back to the correct length */
2986 ftruncate64(vblk->fd, vblk->len);
2987 /* Die, bad Guest, die. */
2988 errx(1, "Write past end %llu+%u", off, ret);
2992 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
2993 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
2995 ret = fdatasync(vblk->fd);
2996 verbose("FLUSH fdatasync: %i\n", ret);
2998 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
3003 * Move to the right location in the block file. This can fail
3004 * if they try to read past end.
3006 if (lseek64(vblk->fd, off, SEEK_SET) != off)
3007 err(1, "Bad seek to sector %llu", out.sector);
3009 ret = readv(vblk->fd, iov + out_num, in_num);
3011 wlen = sizeof(*in) + ret;
3012 *in = VIRTIO_BLK_S_OK;
3015 *in = VIRTIO_BLK_S_IOERR;
3019 /* Finished that request. */
3020 add_used(vq, head, wlen);
3023 /*L:198 This actually sets up a virtual block device. */
3024 static void setup_block_file(const char *filename)
3027 struct vblk_info *vblk;
3028 struct virtio_blk_config conf;
3030 /* Create the device. */
3031 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
3033 /* The device has one virtqueue, where the Guest places requests. */
3034 add_pci_virtqueue(dev, blk_request, "request");
3036 /* Allocate the room for our own bookkeeping */
3037 vblk = dev->priv = malloc(sizeof(*vblk));
3039 /* First we open the file and store the length. */
3040 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
3041 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
3043 /* Tell Guest how many sectors this device has. */
3044 conf.capacity = cpu_to_le64(vblk->len / 512);
3047 * Tell Guest not to put in too many descriptors at once: two are used
3048 * for the in and out elements.
3050 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
3051 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
3053 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
3055 verbose("device %u: virtblock %llu sectors\n",
3056 devices.device_num, le64_to_cpu(conf.capacity));
3060 * Our random number generator device reads from /dev/urandom into the Guest's
3061 * input buffers. The usual case is that the Guest doesn't want random numbers
3062 * and so has no buffers although /dev/urandom is still readable, whereas
3063 * console is the reverse.
3065 * The same logic applies, however.
3071 static void rng_input(struct virtqueue *vq)
3074 unsigned int head, in_num, out_num, totlen = 0;
3075 struct rng_info *rng_info = vq->dev->priv;
3076 struct iovec iov[vq->vring.num];
3078 /* First we need a buffer from the Guests's virtqueue. */
3079 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
3081 errx(1, "Output buffers in rng?");
3084 * Just like the console write, we loop to cover the whole iovec.
3085 * In this case, short reads actually happen quite a bit.
3087 while (!iov_empty(iov, in_num)) {
3088 len = readv(rng_info->rfd, iov, in_num);
3090 err(1, "Read from /dev/urandom gave %i", len);
3091 iov_consume(iov, in_num, NULL, len);
3095 /* Tell the Guest about the new input. */
3096 add_used(vq, head, totlen);
3100 * This creates a "hardware" random number device for the Guest.
3102 static void setup_rng(void)
3105 struct rng_info *rng_info = malloc(sizeof(*rng_info));
3107 /* Our device's private info simply contains the /dev/urandom fd. */
3108 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
3110 /* Create the new device. */
3111 dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
3112 dev->priv = rng_info;
3114 /* The device has one virtqueue, where the Guest places inbufs. */
3115 add_pci_virtqueue(dev, rng_input, "input");
3117 /* We don't have any configuration space */
3118 no_device_config(dev);
3120 verbose("device %u: rng\n", devices.device_num);
3122 /* That's the end of device setup. */
3124 /*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
3125 static void __attribute__((noreturn)) restart_guest(void)
3130 * Since we don't track all open fds, we simply close everything beyond
3133 for (i = 3; i < FD_SETSIZE; i++)
3136 /* Reset all the devices (kills all threads). */
3139 execv(main_args[0], main_args);
3140 err(1, "Could not exec %s", main_args[0]);
3144 * Finally we reach the core of the Launcher which runs the Guest, serves
3145 * its input and output, and finally, lays it to rest.
3147 static void __attribute__((noreturn)) run_guest(void)
3150 struct lguest_pending notify;
3153 /* We read from the /dev/lguest device to run the Guest. */
3154 readval = pread(lguest_fd, ¬ify, sizeof(notify), cpu_id);
3155 if (readval == sizeof(notify)) {
3156 if (notify.trap == 13) {
3157 verbose("Emulating instruction at %#x\n",
3159 emulate_insn(notify.insn);
3160 } else if (notify.trap == 14) {
3161 verbose("Emulating MMIO at %#x\n",
3163 emulate_mmio(notify.addr, notify.insn);
3165 errx(1, "Unknown trap %i addr %#08x\n",
3166 notify.trap, notify.addr);
3167 /* ENOENT means the Guest died. Reading tells us why. */
3168 } else if (errno == ENOENT) {
3169 char reason[1024] = { 0 };
3170 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
3171 errx(1, "%s", reason);
3172 /* ERESTART means that we need to reboot the guest */
3173 } else if (errno == ERESTART) {
3175 /* Anything else means a bug or incompatible change. */
3177 err(1, "Running guest failed");
3181 * This is the end of the Launcher. The good news: we are over halfway
3182 * through! The bad news: the most fiendish part of the code still lies ahead
3185 * Are you ready? Take a deep breath and join me in the core of the Host, in
3189 static struct option opts[] = {
3190 { "verbose", 0, NULL, 'v' },
3191 { "tunnet", 1, NULL, 't' },
3192 { "block", 1, NULL, 'b' },
3193 { "rng", 0, NULL, 'r' },
3194 { "initrd", 1, NULL, 'i' },
3195 { "username", 1, NULL, 'u' },
3196 { "chroot", 1, NULL, 'c' },
3199 static void usage(void)
3201 errx(1, "Usage: lguest [--verbose] "
3202 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
3203 "|--block=<filename>|--initrd=<filename>]...\n"
3204 "<mem-in-mb> vmlinux [args...]");
3207 /*L:105 The main routine is where the real work begins: */
3208 int main(int argc, char *argv[])
3210 /* Memory, code startpoint and size of the (optional) initrd. */
3211 unsigned long mem = 0, start, initrd_size = 0;
3212 /* Two temporaries. */
3214 /* The boot information for the Guest. */
3215 struct boot_params *boot;
3216 /* If they specify an initrd file to load. */
3217 const char *initrd_name = NULL;
3219 /* Password structure for initgroups/setres[gu]id */
3220 struct passwd *user_details = NULL;
3222 /* Directory to chroot to */
3223 char *chroot_path = NULL;
3225 /* Save the args: we "reboot" by execing ourselves again. */
3229 * First we initialize the device list. We remember next interrupt
3230 * number to use for devices (1: remember that 0 is used by the timer).
3232 devices.next_irq = 1;
3234 /* We're CPU 0. In fact, that's the only CPU possible right now. */
3238 * We need to know how much memory so we can set up the device
3239 * descriptor and memory pages for the devices as we parse the command
3240 * line. So we quickly look through the arguments to find the amount
3243 for (i = 1; i < argc; i++) {
3244 if (argv[i][0] != '-') {
3245 mem = atoi(argv[i]) * 1024 * 1024;
3247 * We start by mapping anonymous pages over all of
3248 * guest-physical memory range. This fills it with 0,
3249 * and ensures that the Guest won't be killed when it
3250 * tries to access it.
3252 guest_base = map_zeroed_pages(mem / getpagesize()
3255 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
3260 /* We always have a console device, and it's always device 1. */
3263 /* The options are fairly straight-forward */
3264 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
3270 setup_tun_net(optarg);
3273 setup_block_file(optarg);
3279 initrd_name = optarg;
3282 user_details = getpwnam(optarg);
3284 err(1, "getpwnam failed, incorrect username?");
3287 chroot_path = optarg;
3290 warnx("Unknown argument %s", argv[optind]);
3295 * After the other arguments we expect memory and kernel image name,
3296 * followed by command line arguments for the kernel.
3298 if (optind + 2 > argc)
3301 verbose("Guest base is at %p\n", guest_base);
3303 /* Initialize the (fake) PCI host bridge device. */
3304 init_pci_host_bridge();
3306 /* Now we load the kernel */
3307 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
3309 /* Boot information is stashed at physical address 0 */
3310 boot = from_guest_phys(0);
3312 /* Map the initrd image if requested (at top of physical memory) */
3314 initrd_size = load_initrd(initrd_name, mem);
3316 * These are the location in the Linux boot header where the
3317 * start and size of the initrd are expected to be found.
3319 boot->hdr.ramdisk_image = mem - initrd_size;
3320 boot->hdr.ramdisk_size = initrd_size;
3321 /* The bootloader type 0xFF means "unknown"; that's OK. */
3322 boot->hdr.type_of_loader = 0xFF;
3326 * The Linux boot header contains an "E820" memory map: ours is a
3327 * simple, single region.
3329 boot->e820_entries = 1;
3330 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
3332 * The boot header contains a command line pointer: we put the command
3333 * line after the boot header.
3335 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
3336 /* We use a simple helper to copy the arguments separated by spaces. */
3337 concat((char *)(boot + 1), argv+optind+2);
3339 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3340 boot->hdr.kernel_alignment = 0x1000000;
3342 /* Boot protocol version: 2.07 supports the fields for lguest. */
3343 boot->hdr.version = 0x207;
3345 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
3346 boot->hdr.hardware_subarch = 1;
3348 /* Tell the entry path not to try to reload segment registers. */
3349 boot->hdr.loadflags |= KEEP_SEGMENTS;
3351 /* We tell the kernel to initialize the Guest. */
3354 /* Ensure that we terminate if a device-servicing child dies. */
3355 signal(SIGCHLD, kill_launcher);
3357 /* If we exit via err(), this kills all the threads, restores tty. */
3358 atexit(cleanup_devices);
3360 /* If requested, chroot to a directory */
3362 if (chroot(chroot_path) != 0)
3363 err(1, "chroot(\"%s\") failed", chroot_path);
3365 if (chdir("/") != 0)
3366 err(1, "chdir(\"/\") failed");
3368 verbose("chroot done\n");
3371 /* If requested, drop privileges */
3376 u = user_details->pw_uid;
3377 g = user_details->pw_gid;
3379 if (initgroups(user_details->pw_name, g) != 0)
3380 err(1, "initgroups failed");
3382 if (setresgid(g, g, g) != 0)
3383 err(1, "setresgid failed");
3385 if (setresuid(u, u, u) != 0)
3386 err(1, "setresuid failed");
3388 verbose("Dropping privileges completed\n");
3391 /* Finally, run the Guest. This doesn't return. */
3397 * Mastery is done: you now know everything I do.
3399 * But surely you have seen code, features and bugs in your wanderings which
3400 * you now yearn to attack? That is the real game, and I look forward to you
3401 * patching and forking lguest into the Your-Name-Here-visor.
3403 * Farewell, and good coding!