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 /* PCI configuration */
175 struct pci_config config
;
176 u32 config_words
[sizeof(struct pci_config
) / sizeof(u32
)];
179 /* Features we offer, and those accepted. */
180 u64 features
, features_accepted
;
182 /* Device-specific config hangs off the end of this. */
183 struct virtio_pci_mmio
*mmio
;
185 /* PCI MMIO resources (all in BAR0) */
189 /* Device-specific data. */
193 /* The virtqueue structure describes a queue attached to a device. */
195 struct virtqueue
*next
;
197 /* Which device owns me. */
200 /* The actual ring of buffers. */
203 /* The information about this virtqueue (we only use queue_size on) */
204 struct virtio_pci_common_cfg pci_config
;
206 /* Last available index we saw. */
209 /* How many are used since we sent last irq? */
210 unsigned int pending_used
;
212 /* Eventfd where Guest notifications arrive. */
215 /* Function for the thread which is servicing this virtqueue. */
216 void (*service
)(struct virtqueue
*vq
);
220 /* Remember the arguments to the program so we can "reboot" */
221 static char **main_args
;
223 /* The original tty settings to restore on exit. */
224 static struct termios orig_term
;
227 * We have to be careful with barriers: our devices are all run in separate
228 * threads and so we need to make sure that changes visible to the Guest happen
231 #define wmb() __asm__ __volatile__("" : : : "memory")
232 #define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
233 #define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
235 /* Wrapper for the last available index. Makes it easier to change. */
236 #define lg_last_avail(vq) ((vq)->last_avail_idx)
239 * The virtio configuration space is defined to be little-endian. x86 is
240 * little-endian too, but it's nice to be explicit so we have these helpers.
242 #define cpu_to_le16(v16) (v16)
243 #define cpu_to_le32(v32) (v32)
244 #define cpu_to_le64(v64) (v64)
245 #define le16_to_cpu(v16) (v16)
246 #define le32_to_cpu(v32) (v32)
247 #define le64_to_cpu(v64) (v64)
249 /* Is this iovec empty? */
250 static bool iov_empty(const struct iovec iov
[], unsigned int num_iov
)
254 for (i
= 0; i
< num_iov
; i
++)
260 /* Take len bytes from the front of this iovec. */
261 static void iov_consume(struct iovec iov
[], unsigned num_iov
,
262 void *dest
, unsigned len
)
266 for (i
= 0; i
< num_iov
; i
++) {
269 used
= iov
[i
].iov_len
< len
? iov
[i
].iov_len
: len
;
271 memcpy(dest
, iov
[i
].iov_base
, used
);
274 iov
[i
].iov_base
+= used
;
275 iov
[i
].iov_len
-= used
;
279 errx(1, "iovec too short!");
283 * The Launcher code itself takes us out into userspace, that scary place where
284 * pointers run wild and free! Unfortunately, like most userspace programs,
285 * it's quite boring (which is why everyone likes to hack on the kernel!).
286 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
287 * you through this section. Or, maybe not.
289 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
290 * memory and stores it in "guest_base". In other words, Guest physical ==
291 * Launcher virtual with an offset.
293 * This can be tough to get your head around, but usually it just means that we
294 * use these trivial conversion functions when the Guest gives us its
295 * "physical" addresses:
297 static void *from_guest_phys(unsigned long addr
)
299 return guest_base
+ addr
;
302 static unsigned long to_guest_phys(const void *addr
)
304 return (addr
- guest_base
);
308 * Loading the Kernel.
310 * We start with couple of simple helper routines. open_or_die() avoids
311 * error-checking code cluttering the callers:
313 static int open_or_die(const char *name
, int flags
)
315 int fd
= open(name
, flags
);
317 err(1, "Failed to open %s", name
);
321 /* map_zeroed_pages() takes a number of pages. */
322 static void *map_zeroed_pages(unsigned int num
)
324 int fd
= open_or_die("/dev/zero", O_RDONLY
);
328 * We use a private mapping (ie. if we write to the page, it will be
329 * copied). We allocate an extra two pages PROT_NONE to act as guard
330 * pages against read/write attempts that exceed allocated space.
332 addr
= mmap(NULL
, getpagesize() * (num
+2),
333 PROT_NONE
, MAP_PRIVATE
, fd
, 0);
335 if (addr
== MAP_FAILED
)
336 err(1, "Mmapping %u pages of /dev/zero", num
);
338 if (mprotect(addr
+ getpagesize(), getpagesize() * num
,
339 PROT_READ
|PROT_WRITE
) == -1)
340 err(1, "mprotect rw %u pages failed", num
);
343 * One neat mmap feature is that you can close the fd, and it
348 /* Return address after PROT_NONE page */
349 return addr
+ getpagesize();
352 /* Get some bytes which won't be mapped into the guest. */
353 static unsigned long get_mmio_region(size_t size
)
355 unsigned long addr
= guest_mmio
;
361 /* Size has to be a power of 2 (and multiple of 16) */
362 for (i
= 1; i
< size
; i
<<= 1);
370 * This routine is used to load the kernel or initrd. It tries mmap, but if
371 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
372 * it falls back to reading the memory in.
374 static void map_at(int fd
, void *addr
, unsigned long offset
, unsigned long len
)
379 * We map writable even though for some segments are marked read-only.
380 * The kernel really wants to be writable: it patches its own
383 * MAP_PRIVATE means that the page won't be copied until a write is
384 * done to it. This allows us to share untouched memory between
387 if (mmap(addr
, len
, PROT_READ
|PROT_WRITE
,
388 MAP_FIXED
|MAP_PRIVATE
, fd
, offset
) != MAP_FAILED
)
391 /* pread does a seek and a read in one shot: saves a few lines. */
392 r
= pread(fd
, addr
, len
, offset
);
394 err(1, "Reading offset %lu len %lu gave %zi", offset
, len
, r
);
398 * This routine takes an open vmlinux image, which is in ELF, and maps it into
399 * the Guest memory. ELF = Embedded Linking Format, which is the format used
400 * by all modern binaries on Linux including the kernel.
402 * The ELF headers give *two* addresses: a physical address, and a virtual
403 * address. We use the physical address; the Guest will map itself to the
406 * We return the starting address.
408 static unsigned long map_elf(int elf_fd
, const Elf32_Ehdr
*ehdr
)
410 Elf32_Phdr phdr
[ehdr
->e_phnum
];
414 * Sanity checks on the main ELF header: an x86 executable with a
415 * reasonable number of correctly-sized program headers.
417 if (ehdr
->e_type
!= ET_EXEC
418 || ehdr
->e_machine
!= EM_386
419 || ehdr
->e_phentsize
!= sizeof(Elf32_Phdr
)
420 || ehdr
->e_phnum
< 1 || ehdr
->e_phnum
> 65536U/sizeof(Elf32_Phdr
))
421 errx(1, "Malformed elf header");
424 * An ELF executable contains an ELF header and a number of "program"
425 * headers which indicate which parts ("segments") of the program to
429 /* We read in all the program headers at once: */
430 if (lseek(elf_fd
, ehdr
->e_phoff
, SEEK_SET
) < 0)
431 err(1, "Seeking to program headers");
432 if (read(elf_fd
, phdr
, sizeof(phdr
)) != sizeof(phdr
))
433 err(1, "Reading program headers");
436 * Try all the headers: there are usually only three. A read-only one,
437 * a read-write one, and a "note" section which we don't load.
439 for (i
= 0; i
< ehdr
->e_phnum
; i
++) {
440 /* If this isn't a loadable segment, we ignore it */
441 if (phdr
[i
].p_type
!= PT_LOAD
)
444 verbose("Section %i: size %i addr %p\n",
445 i
, phdr
[i
].p_memsz
, (void *)phdr
[i
].p_paddr
);
447 /* We map this section of the file at its physical address. */
448 map_at(elf_fd
, from_guest_phys(phdr
[i
].p_paddr
),
449 phdr
[i
].p_offset
, phdr
[i
].p_filesz
);
452 /* The entry point is given in the ELF header. */
453 return ehdr
->e_entry
;
457 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
458 * to jump into it and it will unpack itself. We used to have to perform some
459 * hairy magic because the unpacking code scared me.
461 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
462 * a small patch to jump over the tricky bits in the Guest, so now we just read
463 * the funky header so we know where in the file to load, and away we go!
465 static unsigned long load_bzimage(int fd
)
467 struct boot_params boot
;
469 /* Modern bzImages get loaded at 1M. */
470 void *p
= from_guest_phys(0x100000);
473 * Go back to the start of the file and read the header. It should be
474 * a Linux boot header (see Documentation/x86/boot.txt)
476 lseek(fd
, 0, SEEK_SET
);
477 read(fd
, &boot
, sizeof(boot
));
479 /* Inside the setup_hdr, we expect the magic "HdrS" */
480 if (memcmp(&boot
.hdr
.header
, "HdrS", 4) != 0)
481 errx(1, "This doesn't look like a bzImage to me");
483 /* Skip over the extra sectors of the header. */
484 lseek(fd
, (boot
.hdr
.setup_sects
+1) * 512, SEEK_SET
);
486 /* Now read everything into memory. in nice big chunks. */
487 while ((r
= read(fd
, p
, 65536)) > 0)
490 /* Finally, code32_start tells us where to enter the kernel. */
491 return boot
.hdr
.code32_start
;
495 * Loading the kernel is easy when it's a "vmlinux", but most kernels
496 * come wrapped up in the self-decompressing "bzImage" format. With a little
497 * work, we can load those, too.
499 static unsigned long load_kernel(int fd
)
503 /* Read in the first few bytes. */
504 if (read(fd
, &hdr
, sizeof(hdr
)) != sizeof(hdr
))
505 err(1, "Reading kernel");
507 /* If it's an ELF file, it starts with "\177ELF" */
508 if (memcmp(hdr
.e_ident
, ELFMAG
, SELFMAG
) == 0)
509 return map_elf(fd
, &hdr
);
511 /* Otherwise we assume it's a bzImage, and try to load it. */
512 return load_bzimage(fd
);
516 * This is a trivial little helper to align pages. Andi Kleen hated it because
517 * it calls getpagesize() twice: "it's dumb code."
519 * Kernel guys get really het up about optimization, even when it's not
520 * necessary. I leave this code as a reaction against that.
522 static inline unsigned long page_align(unsigned long addr
)
524 /* Add upwards and truncate downwards. */
525 return ((addr
+ getpagesize()-1) & ~(getpagesize()-1));
529 * An "initial ram disk" is a disk image loaded into memory along with the
530 * kernel which the kernel can use to boot from without needing any drivers.
531 * Most distributions now use this as standard: the initrd contains the code to
532 * load the appropriate driver modules for the current machine.
534 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
535 * kernels. He sent me this (and tells me when I break it).
537 static unsigned long load_initrd(const char *name
, unsigned long mem
)
543 ifd
= open_or_die(name
, O_RDONLY
);
544 /* fstat() is needed to get the file size. */
545 if (fstat(ifd
, &st
) < 0)
546 err(1, "fstat() on initrd '%s'", name
);
549 * We map the initrd at the top of memory, but mmap wants it to be
550 * page-aligned, so we round the size up for that.
552 len
= page_align(st
.st_size
);
553 map_at(ifd
, from_guest_phys(mem
- len
), 0, st
.st_size
);
555 * Once a file is mapped, you can close the file descriptor. It's a
556 * little odd, but quite useful.
559 verbose("mapped initrd %s size=%lu @ %p\n", name
, len
, (void*)mem
-len
);
561 /* We return the initrd size. */
567 * Simple routine to roll all the commandline arguments together with spaces
570 static void concat(char *dst
, char *args
[])
572 unsigned int i
, len
= 0;
574 for (i
= 0; args
[i
]; i
++) {
576 strcat(dst
+len
, " ");
579 strcpy(dst
+len
, args
[i
]);
580 len
+= strlen(args
[i
]);
582 /* In case it's empty. */
587 * This is where we actually tell the kernel to initialize the Guest. We
588 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
589 * the base of Guest "physical" memory, the top physical page to allow and the
590 * entry point for the Guest.
592 static void tell_kernel(unsigned long start
)
594 unsigned long args
[] = { LHREQ_INITIALIZE
,
595 (unsigned long)guest_base
,
596 guest_limit
/ getpagesize(), start
,
597 (guest_mmio
+getpagesize()-1) / getpagesize() };
598 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
599 guest_base
, guest_base
+ guest_limit
,
600 guest_limit
, guest_mmio
);
601 lguest_fd
= open_or_die("/dev/lguest", O_RDWR
);
602 if (write(lguest_fd
, args
, sizeof(args
)) < 0)
603 err(1, "Writing to /dev/lguest");
610 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
611 * We need to make sure it's not trying to reach into the Launcher itself, so
612 * we have a convenient routine which checks it and exits with an error message
613 * if something funny is going on:
615 static void *_check_pointer(unsigned long addr
, unsigned int size
,
619 * Check if the requested address and size exceeds the allocated memory,
620 * or addr + size wraps around.
622 if ((addr
+ size
) > guest_limit
|| (addr
+ size
) < addr
)
623 errx(1, "%s:%i: Invalid address %#lx", __FILE__
, line
, addr
);
625 * We return a pointer for the caller's convenience, now we know it's
628 return from_guest_phys(addr
);
630 /* A macro which transparently hands the line number to the real function. */
631 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
634 * Each buffer in the virtqueues is actually a chain of descriptors. This
635 * function returns the next descriptor in the chain, or vq->vring.num if we're
638 static unsigned next_desc(struct vring_desc
*desc
,
639 unsigned int i
, unsigned int max
)
643 /* If this descriptor says it doesn't chain, we're done. */
644 if (!(desc
[i
].flags
& VRING_DESC_F_NEXT
))
647 /* Check they're not leading us off end of descriptors. */
649 /* Make sure compiler knows to grab that: we don't want it changing! */
653 errx(1, "Desc next is %u", next
);
659 * This actually sends the interrupt for this virtqueue, if we've used a
662 static void trigger_irq(struct virtqueue
*vq
)
664 unsigned long buf
[] = { LHREQ_IRQ
, vq
->dev
->config
.irq_line
};
666 /* Don't inform them if nothing used. */
667 if (!vq
->pending_used
)
669 vq
->pending_used
= 0;
671 /* If they don't want an interrupt, don't send one... */
672 if (vq
->vring
.avail
->flags
& VRING_AVAIL_F_NO_INTERRUPT
) {
676 /* Set isr to 1 (queue interrupt pending) */
677 vq
->dev
->mmio
->isr
= 0x1;
679 /* Send the Guest an interrupt tell them we used something up. */
680 if (write(lguest_fd
, buf
, sizeof(buf
)) != 0)
681 err(1, "Triggering irq %i", vq
->dev
->config
.irq_line
);
685 * This looks in the virtqueue for the first available buffer, and converts
686 * it to an iovec for convenient access. Since descriptors consist of some
687 * number of output then some number of input descriptors, it's actually two
688 * iovecs, but we pack them into one and note how many of each there were.
690 * This function waits if necessary, and returns the descriptor number found.
692 static unsigned wait_for_vq_desc(struct virtqueue
*vq
,
694 unsigned int *out_num
, unsigned int *in_num
)
696 unsigned int i
, head
, max
;
697 struct vring_desc
*desc
;
698 u16 last_avail
= lg_last_avail(vq
);
700 /* There's nothing available? */
701 while (last_avail
== vq
->vring
.avail
->idx
) {
705 * Since we're about to sleep, now is a good time to tell the
706 * Guest about what we've used up to now.
710 /* OK, now we need to know about added descriptors. */
711 vq
->vring
.used
->flags
&= ~VRING_USED_F_NO_NOTIFY
;
714 * They could have slipped one in as we were doing that: make
715 * sure it's written, then check again.
718 if (last_avail
!= vq
->vring
.avail
->idx
) {
719 vq
->vring
.used
->flags
|= VRING_USED_F_NO_NOTIFY
;
723 /* Nothing new? Wait for eventfd to tell us they refilled. */
724 if (read(vq
->eventfd
, &event
, sizeof(event
)) != sizeof(event
))
725 errx(1, "Event read failed?");
727 /* We don't need to be notified again. */
728 vq
->vring
.used
->flags
|= VRING_USED_F_NO_NOTIFY
;
731 /* Check it isn't doing very strange things with descriptor numbers. */
732 if ((u16
)(vq
->vring
.avail
->idx
- last_avail
) > vq
->vring
.num
)
733 errx(1, "Guest moved used index from %u to %u",
734 last_avail
, vq
->vring
.avail
->idx
);
737 * Make sure we read the descriptor number *after* we read the ring
738 * update; don't let the cpu or compiler change the order.
743 * Grab the next descriptor number they're advertising, and increment
744 * the index we've seen.
746 head
= vq
->vring
.avail
->ring
[last_avail
% vq
->vring
.num
];
749 /* If their number is silly, that's a fatal mistake. */
750 if (head
>= vq
->vring
.num
)
751 errx(1, "Guest says index %u is available", head
);
753 /* When we start there are none of either input nor output. */
754 *out_num
= *in_num
= 0;
757 desc
= vq
->vring
.desc
;
761 * We have to read the descriptor after we read the descriptor number,
762 * but there's a data dependency there so the CPU shouldn't reorder
763 * that: no rmb() required.
767 * If this is an indirect entry, then this buffer contains a descriptor
768 * table which we handle as if it's any normal descriptor chain.
770 if (desc
[i
].flags
& VRING_DESC_F_INDIRECT
) {
771 if (desc
[i
].len
% sizeof(struct vring_desc
))
772 errx(1, "Invalid size for indirect buffer table");
774 max
= desc
[i
].len
/ sizeof(struct vring_desc
);
775 desc
= check_pointer(desc
[i
].addr
, desc
[i
].len
);
780 /* Grab the first descriptor, and check it's OK. */
781 iov
[*out_num
+ *in_num
].iov_len
= desc
[i
].len
;
782 iov
[*out_num
+ *in_num
].iov_base
783 = check_pointer(desc
[i
].addr
, desc
[i
].len
);
784 /* If this is an input descriptor, increment that count. */
785 if (desc
[i
].flags
& VRING_DESC_F_WRITE
)
789 * If it's an output descriptor, they're all supposed
790 * to come before any input descriptors.
793 errx(1, "Descriptor has out after in");
797 /* If we've got too many, that implies a descriptor loop. */
798 if (*out_num
+ *in_num
> max
)
799 errx(1, "Looped descriptor");
800 } while ((i
= next_desc(desc
, i
, max
)) != max
);
806 * After we've used one of their buffers, we tell the Guest about it. Sometime
807 * later we'll want to send them an interrupt using trigger_irq(); note that
808 * wait_for_vq_desc() does that for us if it has to wait.
810 static void add_used(struct virtqueue
*vq
, unsigned int head
, int len
)
812 struct vring_used_elem
*used
;
815 * The virtqueue contains a ring of used buffers. Get a pointer to the
816 * next entry in that used ring.
818 used
= &vq
->vring
.used
->ring
[vq
->vring
.used
->idx
% vq
->vring
.num
];
821 /* Make sure buffer is written before we update index. */
823 vq
->vring
.used
->idx
++;
827 /* And here's the combo meal deal. Supersize me! */
828 static void add_used_and_trigger(struct virtqueue
*vq
, unsigned head
, int len
)
830 add_used(vq
, head
, len
);
837 * We associate some data with the console for our exit hack.
839 struct console_abort
{
840 /* How many times have they hit ^C? */
842 /* When did they start? */
843 struct timeval start
;
846 /* This is the routine which handles console input (ie. stdin). */
847 static void console_input(struct virtqueue
*vq
)
850 unsigned int head
, in_num
, out_num
;
851 struct console_abort
*abort
= vq
->dev
->priv
;
852 struct iovec iov
[vq
->vring
.num
];
854 /* Make sure there's a descriptor available. */
855 head
= wait_for_vq_desc(vq
, iov
, &out_num
, &in_num
);
857 errx(1, "Output buffers in console in queue?");
859 /* Read into it. This is where we usually wait. */
860 len
= readv(STDIN_FILENO
, iov
, in_num
);
862 /* Ran out of input? */
863 warnx("Failed to get console input, ignoring console.");
865 * For simplicity, dying threads kill the whole Launcher. So
872 /* Tell the Guest we used a buffer. */
873 add_used_and_trigger(vq
, head
, len
);
876 * Three ^C within one second? Exit.
878 * This is such a hack, but works surprisingly well. Each ^C has to
879 * be in a buffer by itself, so they can't be too fast. But we check
880 * that we get three within about a second, so they can't be too
883 if (len
!= 1 || ((char *)iov
[0].iov_base
)[0] != 3) {
889 if (abort
->count
== 1)
890 gettimeofday(&abort
->start
, NULL
);
891 else if (abort
->count
== 3) {
893 gettimeofday(&now
, NULL
);
894 /* Kill all Launcher processes with SIGINT, like normal ^C */
895 if (now
.tv_sec
<= abort
->start
.tv_sec
+1)
901 /* This is the routine which handles console output (ie. stdout). */
902 static void console_output(struct virtqueue
*vq
)
904 unsigned int head
, out
, in
;
905 struct iovec iov
[vq
->vring
.num
];
907 /* We usually wait in here, for the Guest to give us something. */
908 head
= wait_for_vq_desc(vq
, iov
, &out
, &in
);
910 errx(1, "Input buffers in console output queue?");
912 /* writev can return a partial write, so we loop here. */
913 while (!iov_empty(iov
, out
)) {
914 int len
= writev(STDOUT_FILENO
, iov
, out
);
916 warn("Write to stdout gave %i (%d)", len
, errno
);
919 iov_consume(iov
, out
, NULL
, len
);
923 * We're finished with that buffer: if we're going to sleep,
924 * wait_for_vq_desc() will prod the Guest with an interrupt.
926 add_used(vq
, head
, 0);
932 * Handling output for network is also simple: we get all the output buffers
933 * and write them to /dev/net/tun.
939 static void net_output(struct virtqueue
*vq
)
941 struct net_info
*net_info
= vq
->dev
->priv
;
942 unsigned int head
, out
, in
;
943 struct iovec iov
[vq
->vring
.num
];
945 /* We usually wait in here for the Guest to give us a packet. */
946 head
= wait_for_vq_desc(vq
, iov
, &out
, &in
);
948 errx(1, "Input buffers in net output queue?");
950 * Send the whole thing through to /dev/net/tun. It expects the exact
951 * same format: what a coincidence!
953 if (writev(net_info
->tunfd
, iov
, out
) < 0)
954 warnx("Write to tun failed (%d)?", errno
);
957 * Done with that one; wait_for_vq_desc() will send the interrupt if
958 * all packets are processed.
960 add_used(vq
, head
, 0);
964 * Handling network input is a bit trickier, because I've tried to optimize it.
966 * First we have a helper routine which tells is if from this file descriptor
967 * (ie. the /dev/net/tun device) will block:
969 static bool will_block(int fd
)
972 struct timeval zero
= { 0, 0 };
975 return select(fd
+1, &fdset
, NULL
, NULL
, &zero
) != 1;
979 * This handles packets coming in from the tun device to our Guest. Like all
980 * service routines, it gets called again as soon as it returns, so you don't
981 * see a while(1) loop here.
983 static void net_input(struct virtqueue
*vq
)
986 unsigned int head
, out
, in
;
987 struct iovec iov
[vq
->vring
.num
];
988 struct net_info
*net_info
= vq
->dev
->priv
;
991 * Get a descriptor to write an incoming packet into. This will also
992 * send an interrupt if they're out of descriptors.
994 head
= wait_for_vq_desc(vq
, iov
, &out
, &in
);
996 errx(1, "Output buffers in net input queue?");
999 * If it looks like we'll block reading from the tun device, send them
1002 if (vq
->pending_used
&& will_block(net_info
->tunfd
))
1006 * Read in the packet. This is where we normally wait (when there's no
1007 * incoming network traffic).
1009 len
= readv(net_info
->tunfd
, iov
, in
);
1011 warn("Failed to read from tun (%d).", errno
);
1014 * Mark that packet buffer as used, but don't interrupt here. We want
1015 * to wait until we've done as much work as we can.
1017 add_used(vq
, head
, len
);
1021 /* This is the helper to create threads: run the service routine in a loop. */
1022 static int do_thread(void *_vq
)
1024 struct virtqueue
*vq
= _vq
;
1032 * When a child dies, we kill our entire process group with SIGTERM. This
1033 * also has the side effect that the shell restores the console for us!
1035 static void kill_launcher(int signal
)
1040 static void reset_vq_pci_config(struct virtqueue
*vq
)
1042 vq
->pci_config
.queue_size
= VIRTQUEUE_NUM
;
1043 vq
->pci_config
.queue_enable
= 0;
1046 static void reset_device(struct device
*dev
)
1048 struct virtqueue
*vq
;
1050 verbose("Resetting device %s\n", dev
->name
);
1052 /* Clear any features they've acked. */
1053 dev
->features_accepted
= 0;
1055 /* We're going to be explicitly killing threads, so ignore them. */
1056 signal(SIGCHLD
, SIG_IGN
);
1061 * The device MUST present a 0 in queue_enable on reset.
1063 * This means we set it here, and reset the saved ones in every vq.
1065 dev
->mmio
->cfg
.queue_enable
= 0;
1067 /* Get rid of the virtqueue threads */
1068 for (vq
= dev
->vq
; vq
; vq
= vq
->next
) {
1069 vq
->last_avail_idx
= 0;
1070 reset_vq_pci_config(vq
);
1071 if (vq
->thread
!= (pid_t
)-1) {
1072 kill(vq
->thread
, SIGTERM
);
1073 waitpid(vq
->thread
, NULL
, 0);
1074 vq
->thread
= (pid_t
)-1;
1077 dev
->running
= false;
1079 /* Now we care if threads die. */
1080 signal(SIGCHLD
, (void *)kill_launcher
);
1083 static void cleanup_devices(void)
1087 for (i
= 1; i
< MAX_PCI_DEVICES
; i
++) {
1088 struct device
*d
= devices
.pci
[i
];
1094 /* If we saved off the original terminal settings, restore them now. */
1095 if (orig_term
.c_lflag
& (ISIG
|ICANON
|ECHO
))
1096 tcsetattr(STDIN_FILENO
, TCSANOW
, &orig_term
);
1100 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1104 /* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1105 static struct device pci_host_bridge
;
1107 static void init_pci_host_bridge(void)
1109 pci_host_bridge
.name
= "PCI Host Bridge";
1110 pci_host_bridge
.config
.class = 0x06; /* bridge */
1111 pci_host_bridge
.config
.subclass
= 0; /* host bridge */
1112 devices
.pci
[0] = &pci_host_bridge
;
1115 /* The IO ports used to read the PCI config space. */
1116 #define PCI_CONFIG_ADDR 0xCF8
1117 #define PCI_CONFIG_DATA 0xCFC
1120 * Not really portable, but does help readability: this is what the Guest
1121 * writes to the PCI_CONFIG_ADDR IO port.
1123 union pci_config_addr
{
1127 unsigned funcnum
: 3;
1130 unsigned reserved
: 7;
1131 unsigned enabled
: 1;
1137 * We cache what they wrote to the address port, so we know what they're
1138 * talking about when they access the data port.
1140 static union pci_config_addr pci_config_addr
;
1142 static struct device
*find_pci_device(unsigned int index
)
1144 return devices
.pci
[index
];
1147 /* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1148 static void ioread(u16 off
, u32 v
, u32 mask
, u32
*val
)
1151 assert(mask
== 0xFF || mask
== 0xFFFF || mask
== 0xFFFFFFFF);
1152 *val
= (v
>> (off
* 8)) & mask
;
1155 /* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1156 static void iowrite(u16 off
, u32 v
, u32 mask
, u32
*dst
)
1159 assert(mask
== 0xFF || mask
== 0xFFFF || mask
== 0xFFFFFFFF);
1160 *dst
&= ~(mask
<< (off
* 8));
1161 *dst
|= (v
& mask
) << (off
* 8);
1165 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1168 static struct device
*dev_and_reg(u32
*reg
)
1170 if (!pci_config_addr
.bits
.enabled
)
1173 if (pci_config_addr
.bits
.funcnum
!= 0)
1176 if (pci_config_addr
.bits
.busnum
!= 0)
1179 if (pci_config_addr
.bits
.offset
* 4 >= sizeof(struct pci_config
))
1182 *reg
= pci_config_addr
.bits
.offset
;
1183 return find_pci_device(pci_config_addr
.bits
.devnum
);
1187 * We can get invalid combinations of values while they're writing, so we
1188 * only fault if they try to write with some invalid bar/offset/length.
1190 static bool valid_bar_access(struct device
*d
,
1191 struct virtio_pci_cfg_cap
*cfg_access
)
1193 /* We only have 1 bar (BAR0) */
1194 if (cfg_access
->cap
.bar
!= 0)
1197 /* Check it's within BAR0. */
1198 if (cfg_access
->cap
.offset
>= d
->mmio_size
1199 || cfg_access
->cap
.offset
+ cfg_access
->cap
.length
> d
->mmio_size
)
1202 /* Check length is 1, 2 or 4. */
1203 if (cfg_access
->cap
.length
!= 1
1204 && cfg_access
->cap
.length
!= 2
1205 && cfg_access
->cap
.length
!= 4)
1208 /* Offset must be multiple of length */
1209 if (cfg_access
->cap
.offset
% cfg_access
->cap
.length
!= 0)
1212 /* Return pointer into word in BAR0. */
1216 /* Is this accessing the PCI config address port?. */
1217 static bool is_pci_addr_port(u16 port
)
1219 return port
>= PCI_CONFIG_ADDR
&& port
< PCI_CONFIG_ADDR
+ 4;
1222 static bool pci_addr_iowrite(u16 port
, u32 mask
, u32 val
)
1224 iowrite(port
- PCI_CONFIG_ADDR
, val
, mask
,
1225 &pci_config_addr
.val
);
1226 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1227 pci_config_addr
.bits
.enabled
? "" : " DISABLED",
1229 pci_config_addr
.bits
.busnum
,
1230 pci_config_addr
.bits
.devnum
,
1231 pci_config_addr
.bits
.funcnum
,
1232 pci_config_addr
.bits
.offset
);
1236 static void pci_addr_ioread(u16 port
, u32 mask
, u32
*val
)
1238 ioread(port
- PCI_CONFIG_ADDR
, pci_config_addr
.val
, mask
, val
);
1241 /* Is this accessing the PCI config data port?. */
1242 static bool is_pci_data_port(u16 port
)
1244 return port
>= PCI_CONFIG_DATA
&& port
< PCI_CONFIG_DATA
+ 4;
1247 static void emulate_mmio_write(struct device
*d
, u32 off
, u32 val
, u32 mask
);
1249 static bool pci_data_iowrite(u16 port
, u32 mask
, u32 val
)
1252 struct device
*d
= dev_and_reg(®
);
1254 /* Complain if they don't belong to a device. */
1258 /* They can do 1 byte writes, etc. */
1259 portoff
= port
- PCI_CONFIG_DATA
;
1262 * PCI uses a weird way to determine the BAR size: the OS
1263 * writes all 1's, and sees which ones stick.
1265 if (&d
->config_words
[reg
] == &d
->config
.bar
[0]) {
1268 iowrite(portoff
, val
, mask
, &d
->config
.bar
[0]);
1269 for (i
= 0; (1 << i
) < d
->mmio_size
; i
++)
1270 d
->config
.bar
[0] &= ~(1 << i
);
1272 } else if ((&d
->config_words
[reg
] > &d
->config
.bar
[0]
1273 && &d
->config_words
[reg
] <= &d
->config
.bar
[6])
1274 || &d
->config_words
[reg
] == &d
->config
.expansion_rom_addr
) {
1275 /* Allow writing to any other BAR, or expansion ROM */
1276 iowrite(portoff
, val
, mask
, &d
->config_words
[reg
]);
1278 /* We let them overide latency timer and cacheline size */
1279 } else if (&d
->config_words
[reg
] == (void *)&d
->config
.cacheline_size
) {
1280 /* Only let them change the first two fields. */
1281 if (mask
== 0xFFFFFFFF)
1283 iowrite(portoff
, val
, mask
, &d
->config_words
[reg
]);
1285 } else if (&d
->config_words
[reg
] == (void *)&d
->config
.command
1286 && mask
== 0xFFFF) {
1287 /* Ignore command writes. */
1289 } else if (&d
->config_words
[reg
]
1290 == (void *)&d
->config
.cfg_access
.cap
.bar
1291 || &d
->config_words
[reg
]
1292 == &d
->config
.cfg_access
.cap
.length
1293 || &d
->config_words
[reg
]
1294 == &d
->config
.cfg_access
.cap
.offset
) {
1297 * The VIRTIO_PCI_CAP_PCI_CFG capability
1298 * provides a backdoor to access the MMIO
1299 * regions without mapping them. Weird, but
1302 iowrite(portoff
, val
, mask
, &d
->config_words
[reg
]);
1304 } else if (&d
->config_words
[reg
] == &d
->config
.cfg_access
.pci_cfg_data
) {
1308 if (!valid_bar_access(d
, &d
->config
.cfg_access
))
1311 /* First copy what they wrote into the window */
1312 iowrite(portoff
, val
, mask
, &d
->config
.cfg_access
.pci_cfg_data
);
1315 * Now emulate a write. The mask we use is set by
1316 * len, *not* this write!
1318 write_mask
= (1ULL<<(8*d
->config
.cfg_access
.cap
.length
)) - 1;
1319 verbose("Window writing %#x/%#x to bar %u, offset %u len %u\n",
1320 d
->config
.cfg_access
.pci_cfg_data
, write_mask
,
1321 d
->config
.cfg_access
.cap
.bar
,
1322 d
->config
.cfg_access
.cap
.offset
,
1323 d
->config
.cfg_access
.cap
.length
);
1325 emulate_mmio_write(d
, d
->config
.cfg_access
.cap
.offset
,
1326 d
->config
.cfg_access
.pci_cfg_data
,
1331 /* Complain about other writes. */
1335 static u32
emulate_mmio_read(struct device
*d
, u32 off
, u32 mask
);
1337 static void pci_data_ioread(u16 port
, u32 mask
, u32
*val
)
1340 struct device
*d
= dev_and_reg(®
);
1345 /* Read through the PCI MMIO access window is special */
1346 if (&d
->config_words
[reg
] == &d
->config
.cfg_access
.pci_cfg_data
) {
1350 if (!valid_bar_access(d
, &d
->config
.cfg_access
))
1351 errx(1, "Invalid cfg_access to bar%u, offset %u len %u",
1352 d
->config
.cfg_access
.cap
.bar
,
1353 d
->config
.cfg_access
.cap
.offset
,
1354 d
->config
.cfg_access
.cap
.length
);
1357 * Read into the window. The mask we use is set by
1358 * len, *not* this read!
1360 read_mask
= (1ULL<<(8*d
->config
.cfg_access
.cap
.length
))-1;
1361 d
->config
.cfg_access
.pci_cfg_data
1362 = emulate_mmio_read(d
,
1363 d
->config
.cfg_access
.cap
.offset
,
1365 verbose("Window read %#x/%#x from bar %u, offset %u len %u\n",
1366 d
->config
.cfg_access
.pci_cfg_data
, read_mask
,
1367 d
->config
.cfg_access
.cap
.bar
,
1368 d
->config
.cfg_access
.cap
.offset
,
1369 d
->config
.cfg_access
.cap
.length
);
1371 ioread(port
- PCI_CONFIG_DATA
, d
->config_words
[reg
], mask
, val
);
1375 * This is where we emulate a handful of Guest instructions. It's ugly
1376 * and we used to do it in the kernel but it grew over time.
1380 * We use the ptrace syscall's pt_regs struct to talk about registers
1381 * to lguest: these macros convert the names to the offsets.
1383 #define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1384 #define setreg(name, val) \
1385 setreg_off(offsetof(struct user_regs_struct, name), (val))
1387 static u32
getreg_off(size_t offset
)
1390 unsigned long args
[] = { LHREQ_GETREG
, offset
};
1392 if (pwrite(lguest_fd
, args
, sizeof(args
), cpu_id
) < 0)
1393 err(1, "Getting register %u", offset
);
1394 if (pread(lguest_fd
, &r
, sizeof(r
), cpu_id
) != sizeof(r
))
1395 err(1, "Reading register %u", offset
);
1400 static void setreg_off(size_t offset
, u32 val
)
1402 unsigned long args
[] = { LHREQ_SETREG
, offset
, val
};
1404 if (pwrite(lguest_fd
, args
, sizeof(args
), cpu_id
) < 0)
1405 err(1, "Setting register %u", offset
);
1408 /* Get register by instruction encoding */
1409 static u32
getreg_num(unsigned regnum
, u32 mask
)
1411 /* 8 bit ops use regnums 4-7 for high parts of word */
1412 if (mask
== 0xFF && (regnum
& 0x4))
1413 return getreg_num(regnum
& 0x3, 0xFFFF) >> 8;
1416 case 0: return getreg(eax
) & mask
;
1417 case 1: return getreg(ecx
) & mask
;
1418 case 2: return getreg(edx
) & mask
;
1419 case 3: return getreg(ebx
) & mask
;
1420 case 4: return getreg(esp
) & mask
;
1421 case 5: return getreg(ebp
) & mask
;
1422 case 6: return getreg(esi
) & mask
;
1423 case 7: return getreg(edi
) & mask
;
1428 /* Set register by instruction encoding */
1429 static void setreg_num(unsigned regnum
, u32 val
, u32 mask
)
1431 /* Don't try to set bits out of range */
1432 assert(~(val
& ~mask
));
1434 /* 8 bit ops use regnums 4-7 for high parts of word */
1435 if (mask
== 0xFF && (regnum
& 0x4)) {
1436 /* Construct the 16 bits we want. */
1437 val
= (val
<< 8) | getreg_num(regnum
& 0x3, 0xFF);
1438 setreg_num(regnum
& 0x3, val
, 0xFFFF);
1443 case 0: setreg(eax
, val
| (getreg(eax
) & ~mask
)); return;
1444 case 1: setreg(ecx
, val
| (getreg(ecx
) & ~mask
)); return;
1445 case 2: setreg(edx
, val
| (getreg(edx
) & ~mask
)); return;
1446 case 3: setreg(ebx
, val
| (getreg(ebx
) & ~mask
)); return;
1447 case 4: setreg(esp
, val
| (getreg(esp
) & ~mask
)); return;
1448 case 5: setreg(ebp
, val
| (getreg(ebp
) & ~mask
)); return;
1449 case 6: setreg(esi
, val
| (getreg(esi
) & ~mask
)); return;
1450 case 7: setreg(edi
, val
| (getreg(edi
) & ~mask
)); return;
1455 /* Get bytes of displacement appended to instruction, from r/m encoding */
1456 static u32
insn_displacement_len(u8 mod_reg_rm
)
1458 /* Switch on the mod bits */
1459 switch (mod_reg_rm
>> 6) {
1461 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1462 if ((mod_reg_rm
& 0x7) == 0x5)
1464 /* Normally, mod == 0 means no literal displacement */
1467 /* One byte displacement */
1470 /* Four byte displacement */
1479 static void emulate_insn(const u8 insn
[])
1481 unsigned long args
[] = { LHREQ_TRAP
, 13 };
1482 unsigned int insnlen
= 0, in
= 0, small_operand
= 0, byte_access
;
1483 unsigned int eax
, port
, mask
;
1485 * Default is to return all-ones on IO port reads, which traditionally
1486 * means "there's nothing there".
1488 u32 val
= 0xFFFFFFFF;
1491 * This must be the Guest kernel trying to do something, not userspace!
1492 * The bottom two bits of the CS segment register are the privilege
1495 if ((getreg(xcs
) & 3) != 0x1)
1498 /* Decoding x86 instructions is icky. */
1501 * Around 2.6.33, the kernel started using an emulation for the
1502 * cmpxchg8b instruction in early boot on many configurations. This
1503 * code isn't paravirtualized, and it tries to disable interrupts.
1504 * Ignore it, which will Mostly Work.
1506 if (insn
[insnlen
] == 0xfa) {
1507 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1513 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1515 if (insn
[insnlen
] == 0x66) {
1517 /* The instruction is 1 byte so far, read the next byte. */
1521 /* If the lower bit isn't set, it's a single byte access */
1522 byte_access
= !(insn
[insnlen
] & 1);
1525 * Now we can ignore the lower bit and decode the 4 opcodes
1526 * we need to emulate.
1528 switch (insn
[insnlen
] & 0xFE) {
1529 case 0xE4: /* in <next byte>,%al */
1530 port
= insn
[insnlen
+1];
1534 case 0xEC: /* in (%dx),%al */
1535 port
= getreg(edx
) & 0xFFFF;
1539 case 0xE6: /* out %al,<next byte> */
1540 port
= insn
[insnlen
+1];
1543 case 0xEE: /* out %al,(%dx) */
1544 port
= getreg(edx
) & 0xFFFF;
1548 /* OK, we don't know what this is, can't emulate. */
1552 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1555 else if (small_operand
)
1561 * If it was an "IN" instruction, they expect the result to be read
1562 * into %eax, so we change %eax.
1567 /* This is the PS/2 keyboard status; 1 means ready for output */
1570 else if (is_pci_addr_port(port
))
1571 pci_addr_ioread(port
, mask
, &val
);
1572 else if (is_pci_data_port(port
))
1573 pci_data_ioread(port
, mask
, &val
);
1575 /* Clear the bits we're about to read */
1577 /* Copy bits in from val. */
1579 /* Now update the register. */
1582 if (is_pci_addr_port(port
)) {
1583 if (!pci_addr_iowrite(port
, mask
, eax
))
1585 } else if (is_pci_data_port(port
)) {
1586 if (!pci_data_iowrite(port
, mask
, eax
))
1589 /* There are many other ports, eg. CMOS clock, serial
1590 * and parallel ports, so we ignore them all. */
1593 verbose("IO %s of %x to %u: %#08x\n",
1594 in
? "IN" : "OUT", mask
, port
, eax
);
1596 /* Finally, we've "done" the instruction, so move past it. */
1597 setreg(eip
, getreg(eip
) + insnlen
);
1601 warnx("Attempt to %s port %u (%#x mask)",
1602 in
? "read from" : "write to", port
, mask
);
1605 /* Inject trap into Guest. */
1606 if (write(lguest_fd
, args
, sizeof(args
)) < 0)
1607 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip
));
1610 static struct device
*find_mmio_region(unsigned long paddr
, u32
*off
)
1614 for (i
= 1; i
< MAX_PCI_DEVICES
; i
++) {
1615 struct device
*d
= devices
.pci
[i
];
1619 if (paddr
< d
->mmio_addr
)
1621 if (paddr
>= d
->mmio_addr
+ d
->mmio_size
)
1623 *off
= paddr
- d
->mmio_addr
;
1629 /* FIXME: Use vq array. */
1630 static struct virtqueue
*vq_by_num(struct device
*d
, u32 num
)
1632 struct virtqueue
*vq
= d
->vq
;
1640 static void save_vq_config(const struct virtio_pci_common_cfg
*cfg
,
1641 struct virtqueue
*vq
)
1643 vq
->pci_config
= *cfg
;
1646 static void restore_vq_config(struct virtio_pci_common_cfg
*cfg
,
1647 struct virtqueue
*vq
)
1649 /* Only restore the per-vq part */
1650 size_t off
= offsetof(struct virtio_pci_common_cfg
, queue_size
);
1652 memcpy((void *)cfg
+ off
, (void *)&vq
->pci_config
+ off
,
1653 sizeof(*cfg
) - off
);
1657 * When they enable the virtqueue, we check that their setup is valid.
1659 static void enable_virtqueue(struct device
*d
, struct virtqueue
*vq
)
1662 * Create stack for thread. Since the stack grows upwards, we point
1663 * the stack pointer to the end of this region.
1665 char *stack
= malloc(32768);
1667 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1668 if (vq
->pci_config
.queue_desc_hi
1669 || vq
->pci_config
.queue_avail_hi
1670 || vq
->pci_config
.queue_used_hi
)
1671 errx(1, "%s: invalid 64-bit queue address", d
->name
);
1673 /* Initialize the virtqueue and check they're all in range. */
1674 vq
->vring
.num
= vq
->pci_config
.queue_size
;
1675 vq
->vring
.desc
= check_pointer(vq
->pci_config
.queue_desc_lo
,
1676 sizeof(*vq
->vring
.desc
) * vq
->vring
.num
);
1677 vq
->vring
.avail
= check_pointer(vq
->pci_config
.queue_avail_lo
,
1678 sizeof(*vq
->vring
.avail
)
1679 + (sizeof(vq
->vring
.avail
->ring
[0])
1681 vq
->vring
.used
= check_pointer(vq
->pci_config
.queue_used_lo
,
1682 sizeof(*vq
->vring
.used
)
1683 + (sizeof(vq
->vring
.used
->ring
[0])
1687 /* Create a zero-initialized eventfd. */
1688 vq
->eventfd
= eventfd(0, 0);
1689 if (vq
->eventfd
< 0)
1690 err(1, "Creating eventfd");
1693 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1694 * we get a signal if it dies.
1696 vq
->thread
= clone(do_thread
, stack
+ 32768, CLONE_VM
| SIGCHLD
, vq
);
1697 if (vq
->thread
== (pid_t
)-1)
1698 err(1, "Creating clone");
1701 static void emulate_mmio_write(struct device
*d
, u32 off
, u32 val
, u32 mask
)
1703 struct virtqueue
*vq
;
1706 case offsetof(struct virtio_pci_mmio
, cfg
.device_feature_select
):
1708 d
->mmio
->cfg
.device_feature
= d
->features
;
1710 d
->mmio
->cfg
.device_feature
= (d
->features
>> 32);
1712 d
->mmio
->cfg
.device_feature
= 0;
1713 goto write_through32
;
1714 case offsetof(struct virtio_pci_mmio
, cfg
.guest_feature_select
):
1716 errx(1, "%s: Unexpected driver select %u",
1718 goto write_through32
;
1719 case offsetof(struct virtio_pci_mmio
, cfg
.guest_feature
):
1720 if (d
->mmio
->cfg
.guest_feature_select
== 0) {
1721 d
->features_accepted
&= ~((u64
)0xFFFFFFFF);
1722 d
->features_accepted
|= val
;
1724 assert(d
->mmio
->cfg
.guest_feature_select
== 1);
1725 d
->features_accepted
&= 0xFFFFFFFF;
1726 d
->features_accepted
|= ((u64
)val
) << 32;
1728 if (d
->features_accepted
& ~d
->features
)
1729 errx(1, "%s: over-accepted features %#llx of %#llx",
1730 d
->name
, d
->features_accepted
, d
->features
);
1731 goto write_through32
;
1732 case offsetof(struct virtio_pci_mmio
, cfg
.device_status
):
1733 verbose("%s: device status -> %#x\n", d
->name
, val
);
1736 goto write_through8
;
1737 case offsetof(struct virtio_pci_mmio
, cfg
.queue_select
):
1738 vq
= vq_by_num(d
, val
);
1739 /* Out of range? Return size 0 */
1741 d
->mmio
->cfg
.queue_size
= 0;
1742 goto write_through16
;
1744 /* Save registers for old vq, if it was a valid vq */
1745 if (d
->mmio
->cfg
.queue_size
)
1746 save_vq_config(&d
->mmio
->cfg
,
1747 vq_by_num(d
, d
->mmio
->cfg
.queue_select
));
1748 /* Restore the registers for the queue they asked for */
1749 restore_vq_config(&d
->mmio
->cfg
, vq
);
1750 goto write_through16
;
1751 case offsetof(struct virtio_pci_mmio
, cfg
.queue_size
):
1753 errx(1, "%s: invalid queue size %u\n", d
->name
, val
);
1754 if (d
->mmio
->cfg
.queue_enable
)
1755 errx(1, "%s: changing queue size on live device",
1757 goto write_through16
;
1758 case offsetof(struct virtio_pci_mmio
, cfg
.queue_msix_vector
):
1759 errx(1, "%s: attempt to set MSIX vector to %u",
1761 case offsetof(struct virtio_pci_mmio
, cfg
.queue_enable
):
1763 errx(1, "%s: setting queue_enable to %u", d
->name
, val
);
1764 d
->mmio
->cfg
.queue_enable
= val
;
1765 save_vq_config(&d
->mmio
->cfg
,
1766 vq_by_num(d
, d
->mmio
->cfg
.queue_select
));
1767 enable_virtqueue(d
, vq_by_num(d
, d
->mmio
->cfg
.queue_select
));
1768 goto write_through16
;
1769 case offsetof(struct virtio_pci_mmio
, cfg
.queue_notify_off
):
1770 errx(1, "%s: attempt to write to queue_notify_off", d
->name
);
1771 case offsetof(struct virtio_pci_mmio
, cfg
.queue_desc_lo
):
1772 case offsetof(struct virtio_pci_mmio
, cfg
.queue_desc_hi
):
1773 case offsetof(struct virtio_pci_mmio
, cfg
.queue_avail_lo
):
1774 case offsetof(struct virtio_pci_mmio
, cfg
.queue_avail_hi
):
1775 case offsetof(struct virtio_pci_mmio
, cfg
.queue_used_lo
):
1776 case offsetof(struct virtio_pci_mmio
, cfg
.queue_used_hi
):
1777 if (d
->mmio
->cfg
.queue_enable
)
1778 errx(1, "%s: changing queue on live device",
1780 goto write_through32
;
1781 case offsetof(struct virtio_pci_mmio
, notify
):
1782 vq
= vq_by_num(d
, val
);
1784 errx(1, "Invalid vq notification on %u", val
);
1785 /* Notify the process handling this vq by adding 1 to eventfd */
1786 write(vq
->eventfd
, "\1\0\0\0\0\0\0\0", 8);
1787 goto write_through16
;
1788 case offsetof(struct virtio_pci_mmio
, isr
):
1789 errx(1, "%s: Unexpected write to isr", d
->name
);
1790 /* Weird corner case: write to emerg_wr of console */
1791 case sizeof(struct virtio_pci_mmio
)
1792 + offsetof(struct virtio_console_config
, emerg_wr
):
1793 if (strcmp(d
->name
, "console") == 0) {
1795 write(STDOUT_FILENO
, &c
, 1);
1796 goto write_through32
;
1798 /* Fall through... */
1800 errx(1, "%s: Unexpected write to offset %u", d
->name
, off
);
1804 if (mask
!= 0xFFFFFFFF) {
1805 errx(1, "%s: non-32-bit write to offset %u (%#x)",
1806 d
->name
, off
, getreg(eip
));
1809 memcpy((char *)d
->mmio
+ off
, &val
, 4);
1814 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
1815 d
->name
, mask
, off
, getreg(eip
));
1816 memcpy((char *)d
->mmio
+ off
, &val
, 2);
1821 errx(1, "%s: non-8-bit write to offset %u (%#x)",
1822 d
->name
, off
, getreg(eip
));
1823 memcpy((char *)d
->mmio
+ off
, &val
, 1);
1827 static u32
emulate_mmio_read(struct device
*d
, u32 off
, u32 mask
)
1833 case offsetof(struct virtio_pci_mmio
, cfg
.device_feature_select
):
1834 case offsetof(struct virtio_pci_mmio
, cfg
.device_feature
):
1835 case offsetof(struct virtio_pci_mmio
, cfg
.guest_feature_select
):
1836 case offsetof(struct virtio_pci_mmio
, cfg
.guest_feature
):
1837 goto read_through32
;
1838 case offsetof(struct virtio_pci_mmio
, cfg
.msix_config
):
1839 errx(1, "%s: read of msix_config", d
->name
);
1840 case offsetof(struct virtio_pci_mmio
, cfg
.num_queues
):
1841 goto read_through16
;
1842 case offsetof(struct virtio_pci_mmio
, cfg
.device_status
):
1843 case offsetof(struct virtio_pci_mmio
, cfg
.config_generation
):
1845 case offsetof(struct virtio_pci_mmio
, notify
):
1846 goto read_through16
;
1847 case offsetof(struct virtio_pci_mmio
, isr
):
1849 errx(1, "%s: non-8-bit read from offset %u (%#x)",
1850 d
->name
, off
, getreg(eip
));
1851 /* Read resets the isr */
1855 case offsetof(struct virtio_pci_mmio
, padding
):
1856 errx(1, "%s: read from padding (%#x)",
1857 d
->name
, getreg(eip
));
1859 /* Read from device config space, beware unaligned overflow */
1860 if (off
> d
->mmio_size
- 4)
1861 errx(1, "%s: read past end (%#x)",
1862 d
->name
, getreg(eip
));
1863 if (mask
== 0xFFFFFFFF)
1864 goto read_through32
;
1865 else if (mask
== 0xFFFF)
1866 goto read_through16
;
1872 if (mask
!= 0xFFFFFFFF)
1873 errx(1, "%s: non-32-bit read to offset %u (%#x)",
1874 d
->name
, off
, getreg(eip
));
1875 memcpy(&val
, (char *)d
->mmio
+ off
, 4);
1880 errx(1, "%s: non-16-bit read to offset %u (%#x)",
1881 d
->name
, off
, getreg(eip
));
1882 memcpy(&val
, (char *)d
->mmio
+ off
, 2);
1887 errx(1, "%s: non-8-bit read to offset %u (%#x)",
1888 d
->name
, off
, getreg(eip
));
1889 memcpy(&val
, (char *)d
->mmio
+ off
, 1);
1893 static void emulate_mmio(unsigned long paddr
, const u8
*insn
)
1895 u32 val
, off
, mask
= 0xFFFFFFFF, insnlen
= 0;
1896 struct device
*d
= find_mmio_region(paddr
, &off
);
1897 unsigned long args
[] = { LHREQ_TRAP
, 14 };
1900 warnx("MMIO touching %#08lx (not a device)", paddr
);
1904 /* Prefix makes it a 16 bit op */
1905 if (insn
[0] == 0x66) {
1911 if (insn
[insnlen
] == 0x89) {
1912 /* Next byte is r/m byte: bits 3-5 are register. */
1913 val
= getreg_num((insn
[insnlen
+1] >> 3) & 0x7, mask
);
1914 emulate_mmio_write(d
, off
, val
, mask
);
1915 insnlen
+= 2 + insn_displacement_len(insn
[insnlen
+1]);
1916 } else if (insn
[insnlen
] == 0x8b) { /* ioread */
1917 /* Next byte is r/m byte: bits 3-5 are register. */
1918 val
= emulate_mmio_read(d
, off
, mask
);
1919 setreg_num((insn
[insnlen
+1] >> 3) & 0x7, val
, mask
);
1920 insnlen
+= 2 + insn_displacement_len(insn
[insnlen
+1]);
1921 } else if (insn
[0] == 0x88) { /* 8-bit iowrite */
1923 /* Next byte is r/m byte: bits 3-5 are register. */
1924 val
= getreg_num((insn
[1] >> 3) & 0x7, mask
);
1925 emulate_mmio_write(d
, off
, val
, mask
);
1926 insnlen
= 2 + insn_displacement_len(insn
[1]);
1927 } else if (insn
[0] == 0x8a) { /* 8-bit ioread */
1929 val
= emulate_mmio_read(d
, off
, mask
);
1930 setreg_num((insn
[1] >> 3) & 0x7, val
, mask
);
1931 insnlen
= 2 + insn_displacement_len(insn
[1]);
1933 warnx("Unknown MMIO instruction touching %#08lx:"
1934 " %02x %02x %02x %02x at %u",
1935 paddr
, insn
[0], insn
[1], insn
[2], insn
[3], getreg(eip
));
1937 /* Inject trap into Guest. */
1938 if (write(lguest_fd
, args
, sizeof(args
)) < 0)
1939 err(1, "Reinjecting trap 14 for fault at %#x",
1944 /* Finally, we've "done" the instruction, so move past it. */
1945 setreg(eip
, getreg(eip
) + insnlen
);
1951 * All devices need a descriptor so the Guest knows it exists, and a "struct
1952 * device" so the Launcher can keep track of it. We have common helper
1953 * routines to allocate and manage them.
1955 static void add_pci_virtqueue(struct device
*dev
,
1956 void (*service
)(struct virtqueue
*))
1958 struct virtqueue
**i
, *vq
= malloc(sizeof(*vq
));
1960 /* Initialize the virtqueue */
1962 vq
->last_avail_idx
= 0;
1966 * This is the routine the service thread will run, and its Process ID
1967 * once it's running.
1969 vq
->service
= service
;
1970 vq
->thread
= (pid_t
)-1;
1972 /* Initialize the configuration. */
1973 reset_vq_pci_config(vq
);
1974 vq
->pci_config
.queue_notify_off
= 0;
1976 /* Add one to the number of queues */
1977 vq
->dev
->mmio
->cfg
.num_queues
++;
1980 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
1983 for (i
= &dev
->vq
; *i
; i
= &(*i
)->next
);
1987 /* The Guest accesses the feature bits via the PCI common config MMIO region */
1988 static void add_pci_feature(struct device
*dev
, unsigned bit
)
1990 dev
->features
|= (1ULL << bit
);
1993 /* For devices with no config. */
1994 static void no_device_config(struct device
*dev
)
1996 dev
->mmio_addr
= get_mmio_region(dev
->mmio_size
);
1998 dev
->config
.bar
[0] = dev
->mmio_addr
;
1999 /* Bottom 4 bits must be zero */
2000 assert(~(dev
->config
.bar
[0] & 0xF));
2003 /* This puts the device config into BAR0 */
2004 static void set_device_config(struct device
*dev
, const void *conf
, size_t len
)
2007 dev
->mmio_size
+= len
;
2008 dev
->mmio
= realloc(dev
->mmio
, dev
->mmio_size
);
2009 memcpy(dev
->mmio
+ 1, conf
, len
);
2011 /* Hook up device cfg */
2012 dev
->config
.cfg_access
.cap
.cap_next
2013 = offsetof(struct pci_config
, device
);
2015 /* Fix up device cfg field length. */
2016 dev
->config
.device
.length
= len
;
2018 /* The rest is the same as the no-config case */
2019 no_device_config(dev
);
2022 static void init_cap(struct virtio_pci_cap
*cap
, size_t caplen
, int type
,
2023 size_t bar_offset
, size_t bar_bytes
, u8 next
)
2025 cap
->cap_vndr
= PCI_CAP_ID_VNDR
;
2026 cap
->cap_next
= next
;
2027 cap
->cap_len
= caplen
;
2028 cap
->cfg_type
= type
;
2030 memset(cap
->padding
, 0, sizeof(cap
->padding
));
2031 cap
->offset
= bar_offset
;
2032 cap
->length
= bar_bytes
;
2036 * This sets up the pci_config structure, as defined in the virtio 1.0
2037 * standard (and PCI standard).
2039 static void init_pci_config(struct pci_config
*pci
, u16 type
,
2040 u8
class, u8 subclass
)
2042 size_t bar_offset
, bar_len
;
2044 /* Save typing: most thing are happy being zero. */
2045 memset(pci
, 0, sizeof(*pci
));
2047 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2048 pci
->vendor_id
= 0x1AF4;
2049 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2050 pci
->device_id
= 0x1040 + type
;
2053 * PCI have specific codes for different types of devices.
2054 * Linux doesn't care, but it's a good clue for people looking
2058 pci
->subclass
= subclass
;
2061 * 4.1.2.1 Non-transitional devices SHOULD have a PCI Revision
2067 * 4.1.2.1 Non-transitional devices SHOULD have a PCI
2068 * Subsystem Device ID of 0x40 or higher.
2070 pci
->subsystem_device_id
= 0x40;
2072 /* We use our dummy interrupt controller, and irq_line is the irq */
2073 pci
->irq_line
= devices
.next_irq
++;
2076 /* Support for extended capabilities. */
2077 pci
->status
= (1 << 4);
2080 pci
->capabilities
= offsetof(struct pci_config
, common
);
2082 bar_offset
= offsetof(struct virtio_pci_mmio
, cfg
);
2083 bar_len
= sizeof(((struct virtio_pci_mmio
*)0)->cfg
);
2084 init_cap(&pci
->common
, sizeof(pci
->common
), VIRTIO_PCI_CAP_COMMON_CFG
,
2085 bar_offset
, bar_len
,
2086 offsetof(struct pci_config
, notify
));
2088 bar_offset
+= bar_len
;
2089 bar_len
= sizeof(((struct virtio_pci_mmio
*)0)->notify
);
2090 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2091 init_cap(&pci
->notify
.cap
, sizeof(pci
->notify
),
2092 VIRTIO_PCI_CAP_NOTIFY_CFG
,
2093 bar_offset
, bar_len
,
2094 offsetof(struct pci_config
, isr
));
2096 bar_offset
+= bar_len
;
2097 bar_len
= sizeof(((struct virtio_pci_mmio
*)0)->isr
);
2098 init_cap(&pci
->isr
, sizeof(pci
->isr
),
2099 VIRTIO_PCI_CAP_ISR_CFG
,
2100 bar_offset
, bar_len
,
2101 offsetof(struct pci_config
, cfg_access
));
2103 /* This doesn't have any presence in the BAR */
2104 init_cap(&pci
->cfg_access
.cap
, sizeof(pci
->cfg_access
),
2105 VIRTIO_PCI_CAP_PCI_CFG
,
2108 bar_offset
+= bar_len
+ sizeof(((struct virtio_pci_mmio
*)0)->padding
);
2109 assert(bar_offset
== sizeof(struct virtio_pci_mmio
));
2112 * This gets sewn in and length set in set_device_config().
2113 * Some devices don't have a device configuration interface, so
2114 * we never expose this if we don't call set_device_config().
2116 init_cap(&pci
->device
, sizeof(pci
->device
), VIRTIO_PCI_CAP_DEVICE_CFG
,
2121 * This routine does all the creation and setup of a new device, but we don't
2122 * actually place the MMIO region until we know the size (if any) of the
2123 * device-specific config. And we don't actually start the service threads
2126 * See what I mean about userspace being boring?
2128 static struct device
*new_pci_device(const char *name
, u16 type
,
2129 u8
class, u8 subclass
)
2131 struct device
*dev
= malloc(sizeof(*dev
));
2133 /* Now we populate the fields one at a time. */
2136 dev
->running
= false;
2137 dev
->mmio_size
= sizeof(struct virtio_pci_mmio
);
2138 dev
->mmio
= calloc(1, dev
->mmio_size
);
2139 dev
->features
= (u64
)1 << VIRTIO_F_VERSION_1
;
2140 dev
->features_accepted
= 0;
2142 if (devices
.device_num
+ 1 >= MAX_PCI_DEVICES
)
2143 errx(1, "Can only handle 31 PCI devices");
2145 init_pci_config(&dev
->config
, type
, class, subclass
);
2146 assert(!devices
.pci
[devices
.device_num
+1]);
2147 devices
.pci
[++devices
.device_num
] = dev
;
2153 * Our first setup routine is the console. It's a fairly simple device, but
2154 * UNIX tty handling makes it uglier than it could be.
2156 static void setup_console(void)
2159 struct virtio_console_config conf
;
2161 /* If we can save the initial standard input settings... */
2162 if (tcgetattr(STDIN_FILENO
, &orig_term
) == 0) {
2163 struct termios term
= orig_term
;
2165 * Then we turn off echo, line buffering and ^C etc: We want a
2166 * raw input stream to the Guest.
2168 term
.c_lflag
&= ~(ISIG
|ICANON
|ECHO
);
2169 tcsetattr(STDIN_FILENO
, TCSANOW
, &term
);
2172 dev
= new_pci_device("console", VIRTIO_ID_CONSOLE
, 0x07, 0x00);
2174 /* We store the console state in dev->priv, and initialize it. */
2175 dev
->priv
= malloc(sizeof(struct console_abort
));
2176 ((struct console_abort
*)dev
->priv
)->count
= 0;
2179 * The console needs two virtqueues: the input then the output. When
2180 * they put something the input queue, we make sure we're listening to
2181 * stdin. When they put something in the output queue, we write it to
2184 add_pci_virtqueue(dev
, console_input
);
2185 add_pci_virtqueue(dev
, console_output
);
2187 /* We need a configuration area for the emerg_wr early writes. */
2188 add_pci_feature(dev
, VIRTIO_CONSOLE_F_EMERG_WRITE
);
2189 set_device_config(dev
, &conf
, sizeof(conf
));
2191 verbose("device %u: console\n", devices
.device_num
);
2196 * Inter-guest networking is an interesting area. Simplest is to have a
2197 * --sharenet=<name> option which opens or creates a named pipe. This can be
2198 * used to send packets to another guest in a 1:1 manner.
2200 * More sophisticated is to use one of the tools developed for project like UML
2203 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2204 * completely generic ("here's my vring, attach to your vring") and would work
2205 * for any traffic. Of course, namespace and permissions issues need to be
2206 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2207 * multiple inter-guest channels behind one interface, although it would
2208 * require some manner of hotplugging new virtio channels.
2210 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
2213 static u32
str2ip(const char *ipaddr
)
2217 if (sscanf(ipaddr
, "%u.%u.%u.%u", &b
[0], &b
[1], &b
[2], &b
[3]) != 4)
2218 errx(1, "Failed to parse IP address '%s'", ipaddr
);
2219 return (b
[0] << 24) | (b
[1] << 16) | (b
[2] << 8) | b
[3];
2222 static void str2mac(const char *macaddr
, unsigned char mac
[6])
2225 if (sscanf(macaddr
, "%02x:%02x:%02x:%02x:%02x:%02x",
2226 &m
[0], &m
[1], &m
[2], &m
[3], &m
[4], &m
[5]) != 6)
2227 errx(1, "Failed to parse mac address '%s'", macaddr
);
2237 * This code is "adapted" from libbridge: it attaches the Host end of the
2238 * network device to the bridge device specified by the command line.
2240 * This is yet another James Morris contribution (I'm an IP-level guy, so I
2241 * dislike bridging), and I just try not to break it.
2243 static void add_to_bridge(int fd
, const char *if_name
, const char *br_name
)
2249 errx(1, "must specify bridge name");
2251 ifidx
= if_nametoindex(if_name
);
2253 errx(1, "interface %s does not exist!", if_name
);
2255 strncpy(ifr
.ifr_name
, br_name
, IFNAMSIZ
);
2256 ifr
.ifr_name
[IFNAMSIZ
-1] = '\0';
2257 ifr
.ifr_ifindex
= ifidx
;
2258 if (ioctl(fd
, SIOCBRADDIF
, &ifr
) < 0)
2259 err(1, "can't add %s to bridge %s", if_name
, br_name
);
2263 * This sets up the Host end of the network device with an IP address, brings
2264 * it up so packets will flow, the copies the MAC address into the hwaddr
2267 static void configure_device(int fd
, const char *tapif
, u32 ipaddr
)
2270 struct sockaddr_in sin
;
2272 memset(&ifr
, 0, sizeof(ifr
));
2273 strcpy(ifr
.ifr_name
, tapif
);
2275 /* Don't read these incantations. Just cut & paste them like I did! */
2276 sin
.sin_family
= AF_INET
;
2277 sin
.sin_addr
.s_addr
= htonl(ipaddr
);
2278 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(sin
));
2279 if (ioctl(fd
, SIOCSIFADDR
, &ifr
) != 0)
2280 err(1, "Setting %s interface address", tapif
);
2281 ifr
.ifr_flags
= IFF_UP
;
2282 if (ioctl(fd
, SIOCSIFFLAGS
, &ifr
) != 0)
2283 err(1, "Bringing interface %s up", tapif
);
2286 static int get_tun_device(char tapif
[IFNAMSIZ
])
2292 /* Start with this zeroed. Messy but sure. */
2293 memset(&ifr
, 0, sizeof(ifr
));
2296 * We open the /dev/net/tun device and tell it we want a tap device. A
2297 * tap device is like a tun device, only somehow different. To tell
2298 * the truth, I completely blundered my way through this code, but it
2301 netfd
= open_or_die("/dev/net/tun", O_RDWR
);
2302 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
| IFF_VNET_HDR
;
2303 strcpy(ifr
.ifr_name
, "tap%d");
2304 if (ioctl(netfd
, TUNSETIFF
, &ifr
) != 0)
2305 err(1, "configuring /dev/net/tun");
2307 if (ioctl(netfd
, TUNSETOFFLOAD
,
2308 TUN_F_CSUM
|TUN_F_TSO4
|TUN_F_TSO6
|TUN_F_TSO_ECN
) != 0)
2309 err(1, "Could not set features for tun device");
2312 * We don't need checksums calculated for packets coming in this
2315 ioctl(netfd
, TUNSETNOCSUM
, 1);
2318 * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2319 * field at the end of the network header iff
2320 * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
2321 * that became the norm, but we need to tell the tun device
2322 * about our expanded header (which is called
2323 * virtio_net_hdr_mrg_rxbuf in the legacy system).
2325 vnet_hdr_sz
= sizeof(struct virtio_net_hdr_mrg_rxbuf
);
2326 if (ioctl(netfd
, TUNSETVNETHDRSZ
, &vnet_hdr_sz
) != 0)
2327 err(1, "Setting tun header size to %u", vnet_hdr_sz
);
2329 memcpy(tapif
, ifr
.ifr_name
, IFNAMSIZ
);
2334 * Our network is a Host<->Guest network. This can either use bridging or
2335 * routing, but the principle is the same: it uses the "tun" device to inject
2336 * packets into the Host as if they came in from a normal network card. We
2337 * just shunt packets between the Guest and the tun device.
2339 static void setup_tun_net(char *arg
)
2342 struct net_info
*net_info
= malloc(sizeof(*net_info
));
2344 u32 ip
= INADDR_ANY
;
2345 bool bridging
= false;
2346 char tapif
[IFNAMSIZ
], *p
;
2347 struct virtio_net_config conf
;
2349 net_info
->tunfd
= get_tun_device(tapif
);
2351 /* First we create a new network device. */
2352 dev
= new_pci_device("net", VIRTIO_ID_NET
, 0x02, 0x00);
2353 dev
->priv
= net_info
;
2355 /* Network devices need a recv and a send queue, just like console. */
2356 add_pci_virtqueue(dev
, net_input
);
2357 add_pci_virtqueue(dev
, net_output
);
2360 * We need a socket to perform the magic network ioctls to bring up the
2361 * tap interface, connect to the bridge etc. Any socket will do!
2363 ipfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
2365 err(1, "opening IP socket");
2367 /* If the command line was --tunnet=bridge:<name> do bridging. */
2368 if (!strncmp(BRIDGE_PFX
, arg
, strlen(BRIDGE_PFX
))) {
2369 arg
+= strlen(BRIDGE_PFX
);
2373 /* A mac address may follow the bridge name or IP address */
2374 p
= strchr(arg
, ':');
2376 str2mac(p
+1, conf
.mac
);
2377 add_pci_feature(dev
, VIRTIO_NET_F_MAC
);
2381 /* arg is now either an IP address or a bridge name */
2383 add_to_bridge(ipfd
, tapif
, arg
);
2387 /* Set up the tun device. */
2388 configure_device(ipfd
, tapif
, ip
);
2390 /* Expect Guest to handle everything except UFO */
2391 add_pci_feature(dev
, VIRTIO_NET_F_CSUM
);
2392 add_pci_feature(dev
, VIRTIO_NET_F_GUEST_CSUM
);
2393 add_pci_feature(dev
, VIRTIO_NET_F_GUEST_TSO4
);
2394 add_pci_feature(dev
, VIRTIO_NET_F_GUEST_TSO6
);
2395 add_pci_feature(dev
, VIRTIO_NET_F_GUEST_ECN
);
2396 add_pci_feature(dev
, VIRTIO_NET_F_HOST_TSO4
);
2397 add_pci_feature(dev
, VIRTIO_NET_F_HOST_TSO6
);
2398 add_pci_feature(dev
, VIRTIO_NET_F_HOST_ECN
);
2399 /* We handle indirect ring entries */
2400 add_pci_feature(dev
, VIRTIO_RING_F_INDIRECT_DESC
);
2401 set_device_config(dev
, &conf
, sizeof(conf
));
2403 /* We don't need the socket any more; setup is done. */
2407 verbose("device %u: tun %s attached to bridge: %s\n",
2408 devices
.device_num
, tapif
, arg
);
2410 verbose("device %u: tun %s: %s\n",
2411 devices
.device_num
, tapif
, arg
);
2415 /* This hangs off device->priv. */
2417 /* The size of the file. */
2420 /* The file descriptor for the file. */
2428 * The disk only has one virtqueue, so it only has one thread. It is really
2429 * simple: the Guest asks for a block number and we read or write that position
2432 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2433 * slow: the Guest waits until the read is finished before running anything
2434 * else, even if it could have been doing useful work.
2436 * We could have used async I/O, except it's reputed to suck so hard that
2437 * characters actually go missing from your code when you try to use it.
2439 static void blk_request(struct virtqueue
*vq
)
2441 struct vblk_info
*vblk
= vq
->dev
->priv
;
2442 unsigned int head
, out_num
, in_num
, wlen
;
2445 struct virtio_blk_outhdr out
;
2446 struct iovec iov
[vq
->vring
.num
];
2450 * Get the next request, where we normally wait. It triggers the
2451 * interrupt to acknowledge previously serviced requests (if any).
2453 head
= wait_for_vq_desc(vq
, iov
, &out_num
, &in_num
);
2455 /* Copy the output header from the front of the iov (adjusts iov) */
2456 iov_consume(iov
, out_num
, &out
, sizeof(out
));
2458 /* Find and trim end of iov input array, for our status byte. */
2460 for (i
= out_num
+ in_num
- 1; i
>= out_num
; i
--) {
2461 if (iov
[i
].iov_len
> 0) {
2462 in
= iov
[i
].iov_base
+ iov
[i
].iov_len
- 1;
2468 errx(1, "Bad virtblk cmd with no room for status");
2471 * For historical reasons, block operations are expressed in 512 byte
2474 off
= out
.sector
* 512;
2476 if (out
.type
& VIRTIO_BLK_T_OUT
) {
2480 * Move to the right location in the block file. This can fail
2481 * if they try to write past end.
2483 if (lseek64(vblk
->fd
, off
, SEEK_SET
) != off
)
2484 err(1, "Bad seek to sector %llu", out
.sector
);
2486 ret
= writev(vblk
->fd
, iov
, out_num
);
2487 verbose("WRITE to sector %llu: %i\n", out
.sector
, ret
);
2490 * Grr... Now we know how long the descriptor they sent was, we
2491 * make sure they didn't try to write over the end of the block
2492 * file (possibly extending it).
2494 if (ret
> 0 && off
+ ret
> vblk
->len
) {
2495 /* Trim it back to the correct length */
2496 ftruncate64(vblk
->fd
, vblk
->len
);
2497 /* Die, bad Guest, die. */
2498 errx(1, "Write past end %llu+%u", off
, ret
);
2502 *in
= (ret
>= 0 ? VIRTIO_BLK_S_OK
: VIRTIO_BLK_S_IOERR
);
2503 } else if (out
.type
& VIRTIO_BLK_T_FLUSH
) {
2505 ret
= fdatasync(vblk
->fd
);
2506 verbose("FLUSH fdatasync: %i\n", ret
);
2508 *in
= (ret
>= 0 ? VIRTIO_BLK_S_OK
: VIRTIO_BLK_S_IOERR
);
2513 * Move to the right location in the block file. This can fail
2514 * if they try to read past end.
2516 if (lseek64(vblk
->fd
, off
, SEEK_SET
) != off
)
2517 err(1, "Bad seek to sector %llu", out
.sector
);
2519 ret
= readv(vblk
->fd
, iov
+ out_num
, in_num
);
2521 wlen
= sizeof(*in
) + ret
;
2522 *in
= VIRTIO_BLK_S_OK
;
2525 *in
= VIRTIO_BLK_S_IOERR
;
2529 /* Finished that request. */
2530 add_used(vq
, head
, wlen
);
2533 /*L:198 This actually sets up a virtual block device. */
2534 static void setup_block_file(const char *filename
)
2537 struct vblk_info
*vblk
;
2538 struct virtio_blk_config conf
;
2540 /* Create the device. */
2541 dev
= new_pci_device("block", VIRTIO_ID_BLOCK
, 0x01, 0x80);
2543 /* The device has one virtqueue, where the Guest places requests. */
2544 add_pci_virtqueue(dev
, blk_request
);
2546 /* Allocate the room for our own bookkeeping */
2547 vblk
= dev
->priv
= malloc(sizeof(*vblk
));
2549 /* First we open the file and store the length. */
2550 vblk
->fd
= open_or_die(filename
, O_RDWR
|O_LARGEFILE
);
2551 vblk
->len
= lseek64(vblk
->fd
, 0, SEEK_END
);
2553 /* Tell Guest how many sectors this device has. */
2554 conf
.capacity
= cpu_to_le64(vblk
->len
/ 512);
2557 * Tell Guest not to put in too many descriptors at once: two are used
2558 * for the in and out elements.
2560 add_pci_feature(dev
, VIRTIO_BLK_F_SEG_MAX
);
2561 conf
.seg_max
= cpu_to_le32(VIRTQUEUE_NUM
- 2);
2563 set_device_config(dev
, &conf
, sizeof(struct virtio_blk_config
));
2565 verbose("device %u: virtblock %llu sectors\n",
2566 devices
.device_num
, le64_to_cpu(conf
.capacity
));
2570 * Our random number generator device reads from /dev/urandom into the Guest's
2571 * input buffers. The usual case is that the Guest doesn't want random numbers
2572 * and so has no buffers although /dev/urandom is still readable, whereas
2573 * console is the reverse.
2575 * The same logic applies, however.
2581 static void rng_input(struct virtqueue
*vq
)
2584 unsigned int head
, in_num
, out_num
, totlen
= 0;
2585 struct rng_info
*rng_info
= vq
->dev
->priv
;
2586 struct iovec iov
[vq
->vring
.num
];
2588 /* First we need a buffer from the Guests's virtqueue. */
2589 head
= wait_for_vq_desc(vq
, iov
, &out_num
, &in_num
);
2591 errx(1, "Output buffers in rng?");
2594 * Just like the console write, we loop to cover the whole iovec.
2595 * In this case, short reads actually happen quite a bit.
2597 while (!iov_empty(iov
, in_num
)) {
2598 len
= readv(rng_info
->rfd
, iov
, in_num
);
2600 err(1, "Read from /dev/urandom gave %i", len
);
2601 iov_consume(iov
, in_num
, NULL
, len
);
2605 /* Tell the Guest about the new input. */
2606 add_used(vq
, head
, totlen
);
2610 * This creates a "hardware" random number device for the Guest.
2612 static void setup_rng(void)
2615 struct rng_info
*rng_info
= malloc(sizeof(*rng_info
));
2617 /* Our device's private info simply contains the /dev/urandom fd. */
2618 rng_info
->rfd
= open_or_die("/dev/urandom", O_RDONLY
);
2620 /* Create the new device. */
2621 dev
= new_pci_device("rng", VIRTIO_ID_RNG
, 0xff, 0);
2622 dev
->priv
= rng_info
;
2624 /* The device has one virtqueue, where the Guest places inbufs. */
2625 add_pci_virtqueue(dev
, rng_input
);
2627 /* We don't have any configuration space */
2628 no_device_config(dev
);
2630 verbose("device %u: rng\n", devices
.device_num
);
2632 /* That's the end of device setup. */
2634 /*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
2635 static void __attribute__((noreturn
)) restart_guest(void)
2640 * Since we don't track all open fds, we simply close everything beyond
2643 for (i
= 3; i
< FD_SETSIZE
; i
++)
2646 /* Reset all the devices (kills all threads). */
2649 execv(main_args
[0], main_args
);
2650 err(1, "Could not exec %s", main_args
[0]);
2654 * Finally we reach the core of the Launcher which runs the Guest, serves
2655 * its input and output, and finally, lays it to rest.
2657 static void __attribute__((noreturn
)) run_guest(void)
2660 struct lguest_pending notify
;
2663 /* We read from the /dev/lguest device to run the Guest. */
2664 readval
= pread(lguest_fd
, ¬ify
, sizeof(notify
), cpu_id
);
2665 if (readval
== sizeof(notify
)) {
2666 if (notify
.trap
== 13) {
2667 verbose("Emulating instruction at %#x\n",
2669 emulate_insn(notify
.insn
);
2670 } else if (notify
.trap
== 14) {
2671 verbose("Emulating MMIO at %#x\n",
2673 emulate_mmio(notify
.addr
, notify
.insn
);
2675 errx(1, "Unknown trap %i addr %#08x\n",
2676 notify
.trap
, notify
.addr
);
2677 /* ENOENT means the Guest died. Reading tells us why. */
2678 } else if (errno
== ENOENT
) {
2679 char reason
[1024] = { 0 };
2680 pread(lguest_fd
, reason
, sizeof(reason
)-1, cpu_id
);
2681 errx(1, "%s", reason
);
2682 /* ERESTART means that we need to reboot the guest */
2683 } else if (errno
== ERESTART
) {
2685 /* Anything else means a bug or incompatible change. */
2687 err(1, "Running guest failed");
2691 * This is the end of the Launcher. The good news: we are over halfway
2692 * through! The bad news: the most fiendish part of the code still lies ahead
2695 * Are you ready? Take a deep breath and join me in the core of the Host, in
2699 static struct option opts
[] = {
2700 { "verbose", 0, NULL
, 'v' },
2701 { "tunnet", 1, NULL
, 't' },
2702 { "block", 1, NULL
, 'b' },
2703 { "rng", 0, NULL
, 'r' },
2704 { "initrd", 1, NULL
, 'i' },
2705 { "username", 1, NULL
, 'u' },
2706 { "chroot", 1, NULL
, 'c' },
2709 static void usage(void)
2711 errx(1, "Usage: lguest [--verbose] "
2712 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
2713 "|--block=<filename>|--initrd=<filename>]...\n"
2714 "<mem-in-mb> vmlinux [args...]");
2717 /*L:105 The main routine is where the real work begins: */
2718 int main(int argc
, char *argv
[])
2720 /* Memory, code startpoint and size of the (optional) initrd. */
2721 unsigned long mem
= 0, start
, initrd_size
= 0;
2722 /* Two temporaries. */
2724 /* The boot information for the Guest. */
2725 struct boot_params
*boot
;
2726 /* If they specify an initrd file to load. */
2727 const char *initrd_name
= NULL
;
2729 /* Password structure for initgroups/setres[gu]id */
2730 struct passwd
*user_details
= NULL
;
2732 /* Directory to chroot to */
2733 char *chroot_path
= NULL
;
2735 /* Save the args: we "reboot" by execing ourselves again. */
2739 * First we initialize the device list. We remember next interrupt
2740 * number to use for devices (1: remember that 0 is used by the timer).
2742 devices
.next_irq
= 1;
2744 /* We're CPU 0. In fact, that's the only CPU possible right now. */
2748 * We need to know how much memory so we can set up the device
2749 * descriptor and memory pages for the devices as we parse the command
2750 * line. So we quickly look through the arguments to find the amount
2753 for (i
= 1; i
< argc
; i
++) {
2754 if (argv
[i
][0] != '-') {
2755 mem
= atoi(argv
[i
]) * 1024 * 1024;
2757 * We start by mapping anonymous pages over all of
2758 * guest-physical memory range. This fills it with 0,
2759 * and ensures that the Guest won't be killed when it
2760 * tries to access it.
2762 guest_base
= map_zeroed_pages(mem
/ getpagesize()
2765 guest_max
= guest_mmio
= mem
+ DEVICE_PAGES
*getpagesize();
2770 /* We always have a console device, and it's always device 1. */
2773 /* The options are fairly straight-forward */
2774 while ((c
= getopt_long(argc
, argv
, "v", opts
, NULL
)) != EOF
) {
2780 setup_tun_net(optarg
);
2783 setup_block_file(optarg
);
2789 initrd_name
= optarg
;
2792 user_details
= getpwnam(optarg
);
2794 err(1, "getpwnam failed, incorrect username?");
2797 chroot_path
= optarg
;
2800 warnx("Unknown argument %s", argv
[optind
]);
2805 * After the other arguments we expect memory and kernel image name,
2806 * followed by command line arguments for the kernel.
2808 if (optind
+ 2 > argc
)
2811 verbose("Guest base is at %p\n", guest_base
);
2813 /* Initialize the (fake) PCI host bridge device. */
2814 init_pci_host_bridge();
2816 /* Now we load the kernel */
2817 start
= load_kernel(open_or_die(argv
[optind
+1], O_RDONLY
));
2819 /* Boot information is stashed at physical address 0 */
2820 boot
= from_guest_phys(0);
2822 /* Map the initrd image if requested (at top of physical memory) */
2824 initrd_size
= load_initrd(initrd_name
, mem
);
2826 * These are the location in the Linux boot header where the
2827 * start and size of the initrd are expected to be found.
2829 boot
->hdr
.ramdisk_image
= mem
- initrd_size
;
2830 boot
->hdr
.ramdisk_size
= initrd_size
;
2831 /* The bootloader type 0xFF means "unknown"; that's OK. */
2832 boot
->hdr
.type_of_loader
= 0xFF;
2836 * The Linux boot header contains an "E820" memory map: ours is a
2837 * simple, single region.
2839 boot
->e820_entries
= 1;
2840 boot
->e820_map
[0] = ((struct e820entry
) { 0, mem
, E820_RAM
});
2842 * The boot header contains a command line pointer: we put the command
2843 * line after the boot header.
2845 boot
->hdr
.cmd_line_ptr
= to_guest_phys(boot
+ 1);
2846 /* We use a simple helper to copy the arguments separated by spaces. */
2847 concat((char *)(boot
+ 1), argv
+optind
+2);
2849 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
2850 boot
->hdr
.kernel_alignment
= 0x1000000;
2852 /* Boot protocol version: 2.07 supports the fields for lguest. */
2853 boot
->hdr
.version
= 0x207;
2855 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
2856 boot
->hdr
.hardware_subarch
= 1;
2858 /* Tell the entry path not to try to reload segment registers. */
2859 boot
->hdr
.loadflags
|= KEEP_SEGMENTS
;
2861 /* We tell the kernel to initialize the Guest. */
2864 /* Ensure that we terminate if a device-servicing child dies. */
2865 signal(SIGCHLD
, kill_launcher
);
2867 /* If we exit via err(), this kills all the threads, restores tty. */
2868 atexit(cleanup_devices
);
2870 /* If requested, chroot to a directory */
2872 if (chroot(chroot_path
) != 0)
2873 err(1, "chroot(\"%s\") failed", chroot_path
);
2875 if (chdir("/") != 0)
2876 err(1, "chdir(\"/\") failed");
2878 verbose("chroot done\n");
2881 /* If requested, drop privileges */
2886 u
= user_details
->pw_uid
;
2887 g
= user_details
->pw_gid
;
2889 if (initgroups(user_details
->pw_name
, g
) != 0)
2890 err(1, "initgroups failed");
2892 if (setresgid(g
, g
, g
) != 0)
2893 err(1, "setresgid failed");
2895 if (setresuid(u
, u
, u
) != 0)
2896 err(1, "setresuid failed");
2898 verbose("Dropping privileges completed\n");
2901 /* Finally, run the Guest. This doesn't return. */
2907 * Mastery is done: you now know everything I do.
2909 * But surely you have seen code, features and bugs in your wanderings which
2910 * you now yearn to attack? That is the real game, and I look forward to you
2911 * patching and forking lguest into the Your-Name-Here-visor.
2913 * Farewell, and good coding!