tools/lguest: more documentation and checking of virtio 1.0 compliance.
[linux-2.6-block.git] / tools / lguest / lguest.c
1 /*P:100
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
5  * control it.
6 :*/
7 #define _LARGEFILE64_SOURCE
8 #define _GNU_SOURCE
9 #include <stdio.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <err.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <elf.h>
16 #include <sys/mman.h>
17 #include <sys/param.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/wait.h>
21 #include <sys/eventfd.h>
22 #include <fcntl.h>
23 #include <stdbool.h>
24 #include <errno.h>
25 #include <ctype.h>
26 #include <sys/socket.h>
27 #include <sys/ioctl.h>
28 #include <sys/time.h>
29 #include <time.h>
30 #include <netinet/in.h>
31 #include <net/if.h>
32 #include <linux/sockios.h>
33 #include <linux/if_tun.h>
34 #include <sys/uio.h>
35 #include <termios.h>
36 #include <getopt.h>
37 #include <assert.h>
38 #include <sched.h>
39 #include <limits.h>
40 #include <stddef.h>
41 #include <signal.h>
42 #include <pwd.h>
43 #include <grp.h>
44 #include <sys/user.h>
45 #include <linux/pci_regs.h>
46
47 #ifndef VIRTIO_F_ANY_LAYOUT
48 #define VIRTIO_F_ANY_LAYOUT             27
49 #endif
50
51 /*L:110
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.
54  *
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.
59  */
60 typedef unsigned long long u64;
61 typedef uint32_t u32;
62 typedef uint16_t u16;
63 typedef uint8_t u8;
64 /*:*/
65
66 #define VIRTIO_CONFIG_NO_LEGACY
67 #define VIRTIO_PCI_NO_LEGACY
68 #define VIRTIO_BLK_NO_LEGACY
69
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"
80
81 #define BRIDGE_PFX "bridge:"
82 #ifndef SIOCBRADDIF
83 #define SIOCBRADDIF     0x89a2          /* add interface to bridge      */
84 #endif
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
89
90 /*L:120
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.
93  */
94 static bool verbose;
95 #define verbose(args...) \
96         do { if (verbose) printf(args); } while(0)
97 /*:*/
98
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;
105
106 /* a per-cpu variable indicating whose vcpu is currently running */
107 static unsigned int __thread cpu_id;
108
109 /* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
110 #define MAX_PCI_DEVICES 32
111
112 /* This is our list of devices. */
113 struct device_list {
114         /* Counter to assign interrupt numbers. */
115         unsigned int next_irq;
116
117         /* Counter to print out convenient device numbers. */
118         unsigned int device_num;
119
120         /* PCI devices. */
121         struct device *pci[MAX_PCI_DEVICES];
122 };
123
124 /* The list of Guest devices, based on command line arguments. */
125 static struct device_list devices;
126
127 struct virtio_pci_cfg_cap {
128         struct virtio_pci_cap cap;
129         u32 pci_cfg_data; /* Data for BAR access. */
130 };
131
132 struct virtio_pci_mmio {
133         struct virtio_pci_common_cfg cfg;
134         u16 notify;
135         u8 isr;
136         u8 padding;
137         /* Device-specific configuration follows this. */
138 };
139
140 /* This is the layout (little-endian) of the PCI config space. */
141 struct pci_config {
142         u16 vendor_id, device_id;
143         u16 command, status;
144         u8 revid, prog_if, subclass, class;
145         u8 cacheline_size, lat_timer, header_type, bist;
146         u32 bar[6];
147         u32 cardbus_cis_ptr;
148         u16 subsystem_vendor_id, subsystem_device_id;
149         u32 expansion_rom_addr;
150         u8 capabilities, reserved1[3];
151         u32 reserved2;
152         u8 irq_line, irq_pin, min_grant, max_latency;
153
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;
160 };
161
162 /* The device structure describes a single device. */
163 struct device {
164         /* The name of this device, for --verbose. */
165         const char *name;
166
167         /* Any queues attached to this device */
168         struct virtqueue *vq;
169
170         /* Is it operational */
171         bool running;
172
173         /* Has it written FEATURES_OK but not re-checked it? */
174         bool wrote_features_ok;
175
176         /* PCI configuration */
177         union {
178                 struct pci_config config;
179                 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
180         };
181
182         /* Features we offer, and those accepted. */
183         u64 features, features_accepted;
184
185         /* Device-specific config hangs off the end of this. */
186         struct virtio_pci_mmio *mmio;
187
188         /* PCI MMIO resources (all in BAR0) */
189         size_t mmio_size;
190         u32 mmio_addr;
191
192         /* Device-specific data. */
193         void *priv;
194 };
195
196 /* The virtqueue structure describes a queue attached to a device. */
197 struct virtqueue {
198         struct virtqueue *next;
199
200         /* Which device owns me. */
201         struct device *dev;
202
203         /* The actual ring of buffers. */
204         struct vring vring;
205
206         /* The information about this virtqueue (we only use queue_size on) */
207         struct virtio_pci_common_cfg pci_config;
208
209         /* Last available index we saw. */
210         u16 last_avail_idx;
211
212         /* How many are used since we sent last irq? */
213         unsigned int pending_used;
214
215         /* Eventfd where Guest notifications arrive. */
216         int eventfd;
217
218         /* Function for the thread which is servicing this virtqueue. */
219         void (*service)(struct virtqueue *vq);
220         pid_t thread;
221 };
222
223 /* Remember the arguments to the program so we can "reboot" */
224 static char **main_args;
225
226 /* The original tty settings to restore on exit. */
227 static struct termios orig_term;
228
229 /*
230  * We have to be careful with barriers: our devices are all run in separate
231  * threads and so we need to make sure that changes visible to the Guest happen
232  * in precise order.
233  */
234 #define wmb() __asm__ __volatile__("" : : : "memory")
235 #define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
236 #define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
237
238 /* Wrapper for the last available index.  Makes it easier to change. */
239 #define lg_last_avail(vq)       ((vq)->last_avail_idx)
240
241 /*
242  * The virtio configuration space is defined to be little-endian.  x86 is
243  * little-endian too, but it's nice to be explicit so we have these helpers.
244  */
245 #define cpu_to_le16(v16) (v16)
246 #define cpu_to_le32(v32) (v32)
247 #define cpu_to_le64(v64) (v64)
248 #define le16_to_cpu(v16) (v16)
249 #define le32_to_cpu(v32) (v32)
250 #define le64_to_cpu(v64) (v64)
251
252 /* Is this iovec empty? */
253 static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
254 {
255         unsigned int i;
256
257         for (i = 0; i < num_iov; i++)
258                 if (iov[i].iov_len)
259                         return false;
260         return true;
261 }
262
263 /* Take len bytes from the front of this iovec. */
264 static void iov_consume(struct iovec iov[], unsigned num_iov,
265                         void *dest, unsigned len)
266 {
267         unsigned int i;
268
269         for (i = 0; i < num_iov; i++) {
270                 unsigned int used;
271
272                 used = iov[i].iov_len < len ? iov[i].iov_len : len;
273                 if (dest) {
274                         memcpy(dest, iov[i].iov_base, used);
275                         dest += used;
276                 }
277                 iov[i].iov_base += used;
278                 iov[i].iov_len -= used;
279                 len -= used;
280         }
281         if (len != 0)
282                 errx(1, "iovec too short!");
283 }
284
285 /*L:100
286  * The Launcher code itself takes us out into userspace, that scary place where
287  * pointers run wild and free!  Unfortunately, like most userspace programs,
288  * it's quite boring (which is why everyone likes to hack on the kernel!).
289  * Perhaps if you make up an Lguest Drinking Game at this point, it will get
290  * you through this section.  Or, maybe not.
291  *
292  * The Launcher sets up a big chunk of memory to be the Guest's "physical"
293  * memory and stores it in "guest_base".  In other words, Guest physical ==
294  * Launcher virtual with an offset.
295  *
296  * This can be tough to get your head around, but usually it just means that we
297  * use these trivial conversion functions when the Guest gives us its
298  * "physical" addresses:
299  */
300 static void *from_guest_phys(unsigned long addr)
301 {
302         return guest_base + addr;
303 }
304
305 static unsigned long to_guest_phys(const void *addr)
306 {
307         return (addr - guest_base);
308 }
309
310 /*L:130
311  * Loading the Kernel.
312  *
313  * We start with couple of simple helper routines.  open_or_die() avoids
314  * error-checking code cluttering the callers:
315  */
316 static int open_or_die(const char *name, int flags)
317 {
318         int fd = open(name, flags);
319         if (fd < 0)
320                 err(1, "Failed to open %s", name);
321         return fd;
322 }
323
324 /* map_zeroed_pages() takes a number of pages. */
325 static void *map_zeroed_pages(unsigned int num)
326 {
327         int fd = open_or_die("/dev/zero", O_RDONLY);
328         void *addr;
329
330         /*
331          * We use a private mapping (ie. if we write to the page, it will be
332          * copied). We allocate an extra two pages PROT_NONE to act as guard
333          * pages against read/write attempts that exceed allocated space.
334          */
335         addr = mmap(NULL, getpagesize() * (num+2),
336                     PROT_NONE, MAP_PRIVATE, fd, 0);
337
338         if (addr == MAP_FAILED)
339                 err(1, "Mmapping %u pages of /dev/zero", num);
340
341         if (mprotect(addr + getpagesize(), getpagesize() * num,
342                      PROT_READ|PROT_WRITE) == -1)
343                 err(1, "mprotect rw %u pages failed", num);
344
345         /*
346          * One neat mmap feature is that you can close the fd, and it
347          * stays mapped.
348          */
349         close(fd);
350
351         /* Return address after PROT_NONE page */
352         return addr + getpagesize();
353 }
354
355 /* Get some bytes which won't be mapped into the guest. */
356 static unsigned long get_mmio_region(size_t size)
357 {
358         unsigned long addr = guest_mmio;
359         size_t i;
360
361         if (!size)
362                 return addr;
363
364         /* Size has to be a power of 2 (and multiple of 16) */
365         for (i = 1; i < size; i <<= 1);
366
367         guest_mmio += i;
368
369         return addr;
370 }
371
372 /*
373  * This routine is used to load the kernel or initrd.  It tries mmap, but if
374  * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
375  * it falls back to reading the memory in.
376  */
377 static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
378 {
379         ssize_t r;
380
381         /*
382          * We map writable even though for some segments are marked read-only.
383          * The kernel really wants to be writable: it patches its own
384          * instructions.
385          *
386          * MAP_PRIVATE means that the page won't be copied until a write is
387          * done to it.  This allows us to share untouched memory between
388          * Guests.
389          */
390         if (mmap(addr, len, PROT_READ|PROT_WRITE,
391                  MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
392                 return;
393
394         /* pread does a seek and a read in one shot: saves a few lines. */
395         r = pread(fd, addr, len, offset);
396         if (r != len)
397                 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
398 }
399
400 /*
401  * This routine takes an open vmlinux image, which is in ELF, and maps it into
402  * the Guest memory.  ELF = Embedded Linking Format, which is the format used
403  * by all modern binaries on Linux including the kernel.
404  *
405  * The ELF headers give *two* addresses: a physical address, and a virtual
406  * address.  We use the physical address; the Guest will map itself to the
407  * virtual address.
408  *
409  * We return the starting address.
410  */
411 static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
412 {
413         Elf32_Phdr phdr[ehdr->e_phnum];
414         unsigned int i;
415
416         /*
417          * Sanity checks on the main ELF header: an x86 executable with a
418          * reasonable number of correctly-sized program headers.
419          */
420         if (ehdr->e_type != ET_EXEC
421             || ehdr->e_machine != EM_386
422             || ehdr->e_phentsize != sizeof(Elf32_Phdr)
423             || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
424                 errx(1, "Malformed elf header");
425
426         /*
427          * An ELF executable contains an ELF header and a number of "program"
428          * headers which indicate which parts ("segments") of the program to
429          * load where.
430          */
431
432         /* We read in all the program headers at once: */
433         if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
434                 err(1, "Seeking to program headers");
435         if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
436                 err(1, "Reading program headers");
437
438         /*
439          * Try all the headers: there are usually only three.  A read-only one,
440          * a read-write one, and a "note" section which we don't load.
441          */
442         for (i = 0; i < ehdr->e_phnum; i++) {
443                 /* If this isn't a loadable segment, we ignore it */
444                 if (phdr[i].p_type != PT_LOAD)
445                         continue;
446
447                 verbose("Section %i: size %i addr %p\n",
448                         i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
449
450                 /* We map this section of the file at its physical address. */
451                 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
452                        phdr[i].p_offset, phdr[i].p_filesz);
453         }
454
455         /* The entry point is given in the ELF header. */
456         return ehdr->e_entry;
457 }
458
459 /*L:150
460  * A bzImage, unlike an ELF file, is not meant to be loaded.  You're supposed
461  * to jump into it and it will unpack itself.  We used to have to perform some
462  * hairy magic because the unpacking code scared me.
463  *
464  * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
465  * a small patch to jump over the tricky bits in the Guest, so now we just read
466  * the funky header so we know where in the file to load, and away we go!
467  */
468 static unsigned long load_bzimage(int fd)
469 {
470         struct boot_params boot;
471         int r;
472         /* Modern bzImages get loaded at 1M. */
473         void *p = from_guest_phys(0x100000);
474
475         /*
476          * Go back to the start of the file and read the header.  It should be
477          * a Linux boot header (see Documentation/x86/boot.txt)
478          */
479         lseek(fd, 0, SEEK_SET);
480         read(fd, &boot, sizeof(boot));
481
482         /* Inside the setup_hdr, we expect the magic "HdrS" */
483         if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
484                 errx(1, "This doesn't look like a bzImage to me");
485
486         /* Skip over the extra sectors of the header. */
487         lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
488
489         /* Now read everything into memory. in nice big chunks. */
490         while ((r = read(fd, p, 65536)) > 0)
491                 p += r;
492
493         /* Finally, code32_start tells us where to enter the kernel. */
494         return boot.hdr.code32_start;
495 }
496
497 /*L:140
498  * Loading the kernel is easy when it's a "vmlinux", but most kernels
499  * come wrapped up in the self-decompressing "bzImage" format.  With a little
500  * work, we can load those, too.
501  */
502 static unsigned long load_kernel(int fd)
503 {
504         Elf32_Ehdr hdr;
505
506         /* Read in the first few bytes. */
507         if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
508                 err(1, "Reading kernel");
509
510         /* If it's an ELF file, it starts with "\177ELF" */
511         if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
512                 return map_elf(fd, &hdr);
513
514         /* Otherwise we assume it's a bzImage, and try to load it. */
515         return load_bzimage(fd);
516 }
517
518 /*
519  * This is a trivial little helper to align pages.  Andi Kleen hated it because
520  * it calls getpagesize() twice: "it's dumb code."
521  *
522  * Kernel guys get really het up about optimization, even when it's not
523  * necessary.  I leave this code as a reaction against that.
524  */
525 static inline unsigned long page_align(unsigned long addr)
526 {
527         /* Add upwards and truncate downwards. */
528         return ((addr + getpagesize()-1) & ~(getpagesize()-1));
529 }
530
531 /*L:180
532  * An "initial ram disk" is a disk image loaded into memory along with the
533  * kernel which the kernel can use to boot from without needing any drivers.
534  * Most distributions now use this as standard: the initrd contains the code to
535  * load the appropriate driver modules for the current machine.
536  *
537  * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
538  * kernels.  He sent me this (and tells me when I break it).
539  */
540 static unsigned long load_initrd(const char *name, unsigned long mem)
541 {
542         int ifd;
543         struct stat st;
544         unsigned long len;
545
546         ifd = open_or_die(name, O_RDONLY);
547         /* fstat() is needed to get the file size. */
548         if (fstat(ifd, &st) < 0)
549                 err(1, "fstat() on initrd '%s'", name);
550
551         /*
552          * We map the initrd at the top of memory, but mmap wants it to be
553          * page-aligned, so we round the size up for that.
554          */
555         len = page_align(st.st_size);
556         map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
557         /*
558          * Once a file is mapped, you can close the file descriptor.  It's a
559          * little odd, but quite useful.
560          */
561         close(ifd);
562         verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
563
564         /* We return the initrd size. */
565         return len;
566 }
567 /*:*/
568
569 /*
570  * Simple routine to roll all the commandline arguments together with spaces
571  * between them.
572  */
573 static void concat(char *dst, char *args[])
574 {
575         unsigned int i, len = 0;
576
577         for (i = 0; args[i]; i++) {
578                 if (i) {
579                         strcat(dst+len, " ");
580                         len++;
581                 }
582                 strcpy(dst+len, args[i]);
583                 len += strlen(args[i]);
584         }
585         /* In case it's empty. */
586         dst[len] = '\0';
587 }
588
589 /*L:185
590  * This is where we actually tell the kernel to initialize the Guest.  We
591  * saw the arguments it expects when we looked at initialize() in lguest_user.c:
592  * the base of Guest "physical" memory, the top physical page to allow and the
593  * entry point for the Guest.
594  */
595 static void tell_kernel(unsigned long start)
596 {
597         unsigned long args[] = { LHREQ_INITIALIZE,
598                                  (unsigned long)guest_base,
599                                  guest_limit / getpagesize(), start,
600                                  (guest_mmio+getpagesize()-1) / getpagesize() };
601         verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
602                 guest_base, guest_base + guest_limit,
603                 guest_limit, guest_mmio);
604         lguest_fd = open_or_die("/dev/lguest", O_RDWR);
605         if (write(lguest_fd, args, sizeof(args)) < 0)
606                 err(1, "Writing to /dev/lguest");
607 }
608 /*:*/
609
610 /*L:200
611  * Device Handling.
612  *
613  * When the Guest gives us a buffer, it sends an array of addresses and sizes.
614  * We need to make sure it's not trying to reach into the Launcher itself, so
615  * we have a convenient routine which checks it and exits with an error message
616  * if something funny is going on:
617  */
618 static void *_check_pointer(unsigned long addr, unsigned int size,
619                             unsigned int line)
620 {
621         /*
622          * Check if the requested address and size exceeds the allocated memory,
623          * or addr + size wraps around.
624          */
625         if ((addr + size) > guest_limit || (addr + size) < addr)
626                 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
627         /*
628          * We return a pointer for the caller's convenience, now we know it's
629          * safe to use.
630          */
631         return from_guest_phys(addr);
632 }
633 /* A macro which transparently hands the line number to the real function. */
634 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
635
636 /*
637  * Each buffer in the virtqueues is actually a chain of descriptors.  This
638  * function returns the next descriptor in the chain, or vq->vring.num if we're
639  * at the end.
640  */
641 static unsigned next_desc(struct vring_desc *desc,
642                           unsigned int i, unsigned int max)
643 {
644         unsigned int next;
645
646         /* If this descriptor says it doesn't chain, we're done. */
647         if (!(desc[i].flags & VRING_DESC_F_NEXT))
648                 return max;
649
650         /* Check they're not leading us off end of descriptors. */
651         next = desc[i].next;
652         /* Make sure compiler knows to grab that: we don't want it changing! */
653         wmb();
654
655         if (next >= max)
656                 errx(1, "Desc next is %u", next);
657
658         return next;
659 }
660
661 /*
662  * This actually sends the interrupt for this virtqueue, if we've used a
663  * buffer.
664  */
665 static void trigger_irq(struct virtqueue *vq)
666 {
667         unsigned long buf[] = { LHREQ_IRQ, vq->dev->config.irq_line };
668
669         /* Don't inform them if nothing used. */
670         if (!vq->pending_used)
671                 return;
672         vq->pending_used = 0;
673
674         /*
675          * 2.4.7.1:
676          *
677          *  If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
678          *    The driver MUST set flags to 0 or 1. 
679          */
680         if (vq->vring.avail->flags > 1)
681                 errx(1, "%s: avail->flags = %u\n",
682                      vq->dev->name, vq->vring.avail->flags);
683
684         /*
685          * 2.4.7.2:
686          *
687          *  If the VIRTIO_F_EVENT_IDX feature bit is not negotiated:
688          *
689          *     - The device MUST ignore the used_event value.
690          *     - After the device writes a descriptor index into the used ring:
691          *         - If flags is 1, the device SHOULD NOT send an interrupt.
692          *         - If flags is 0, the device MUST send an interrupt.
693          */
694         if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
695                 return;
696         }
697
698         /*
699          * 4.1.4.5.1:
700          *
701          *  If MSI-X capability is disabled, the device MUST set the Queue
702          *  Interrupt bit in ISR status before sending a virtqueue notification
703          *  to the driver.
704          */
705         vq->dev->mmio->isr = 0x1;
706
707         /* Send the Guest an interrupt tell them we used something up. */
708         if (write(lguest_fd, buf, sizeof(buf)) != 0)
709                 err(1, "Triggering irq %i", vq->dev->config.irq_line);
710 }
711
712 /*
713  * This looks in the virtqueue for the first available buffer, and converts
714  * it to an iovec for convenient access.  Since descriptors consist of some
715  * number of output then some number of input descriptors, it's actually two
716  * iovecs, but we pack them into one and note how many of each there were.
717  *
718  * This function waits if necessary, and returns the descriptor number found.
719  */
720 static unsigned wait_for_vq_desc(struct virtqueue *vq,
721                                  struct iovec iov[],
722                                  unsigned int *out_num, unsigned int *in_num)
723 {
724         unsigned int i, head, max;
725         struct vring_desc *desc;
726         u16 last_avail = lg_last_avail(vq);
727
728         /*
729          * 2.4.7.1:
730          *
731          *   The driver MUST handle spurious interrupts from the device.
732          *
733          * That's why this is a while loop.
734          */
735
736         /* There's nothing available? */
737         while (last_avail == vq->vring.avail->idx) {
738                 u64 event;
739
740                 /*
741                  * Since we're about to sleep, now is a good time to tell the
742                  * Guest about what we've used up to now.
743                  */
744                 trigger_irq(vq);
745
746                 /* OK, now we need to know about added descriptors. */
747                 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
748
749                 /*
750                  * They could have slipped one in as we were doing that: make
751                  * sure it's written, then check again.
752                  */
753                 mb();
754                 if (last_avail != vq->vring.avail->idx) {
755                         vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
756                         break;
757                 }
758
759                 /* Nothing new?  Wait for eventfd to tell us they refilled. */
760                 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
761                         errx(1, "Event read failed?");
762
763                 /* We don't need to be notified again. */
764                 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
765         }
766
767         /* Check it isn't doing very strange things with descriptor numbers. */
768         if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
769                 errx(1, "Guest moved used index from %u to %u",
770                      last_avail, vq->vring.avail->idx);
771
772         /* 
773          * Make sure we read the descriptor number *after* we read the ring
774          * update; don't let the cpu or compiler change the order.
775          */
776         rmb();
777
778         /*
779          * Grab the next descriptor number they're advertising, and increment
780          * the index we've seen.
781          */
782         head = vq->vring.avail->ring[last_avail % vq->vring.num];
783         lg_last_avail(vq)++;
784
785         /* If their number is silly, that's a fatal mistake. */
786         if (head >= vq->vring.num)
787                 errx(1, "Guest says index %u is available", head);
788
789         /* When we start there are none of either input nor output. */
790         *out_num = *in_num = 0;
791
792         max = vq->vring.num;
793         desc = vq->vring.desc;
794         i = head;
795
796         /*
797          * We have to read the descriptor after we read the descriptor number,
798          * but there's a data dependency there so the CPU shouldn't reorder
799          * that: no rmb() required.
800          */
801
802         do {
803                 /*
804                  * If this is an indirect entry, then this buffer contains a
805                  * descriptor table which we handle as if it's any normal
806                  * descriptor chain.
807                  */
808                 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
809                         /* 2.4.5.3.1:
810                          *
811                          *  The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
812                          *  flag unless the VIRTIO_F_INDIRECT_DESC feature was
813                          *  negotiated.
814                          */
815                         if (!(vq->dev->features_accepted &
816                               (1<<VIRTIO_RING_F_INDIRECT_DESC)))
817                                 errx(1, "%s: vq indirect not negotiated",
818                                      vq->dev->name);
819
820                         /*
821                          * 2.4.5.3.1:
822                          *
823                          *   The driver MUST NOT set the VIRTQ_DESC_F_INDIRECT
824                          *   flag within an indirect descriptor (ie. only one
825                          *   table per descriptor).
826                          */
827                         if (desc != vq->vring.desc)
828                                 errx(1, "%s: Indirect within indirect",
829                                      vq->dev->name);
830
831                         /*
832                          * Proposed update VIRTIO-134 spells this out:
833                          *
834                          *   A driver MUST NOT set both VIRTQ_DESC_F_INDIRECT
835                          *   and VIRTQ_DESC_F_NEXT in flags.
836                          */
837                         if (desc[i].flags & VRING_DESC_F_NEXT)
838                                 errx(1, "%s: indirect and next together",
839                                      vq->dev->name);
840
841                         if (desc[i].len % sizeof(struct vring_desc))
842                                 errx(1, "Invalid size for indirect buffer table");
843                         /*
844                          * 2.4.5.3.2:
845                          *
846                          *  The device MUST ignore the write-only flag
847                          *  (flags&VIRTQ_DESC_F_WRITE) in the descriptor that
848                          *  refers to an indirect table.
849                          *
850                          * We ignore it here: :)
851                          */
852
853                         max = desc[i].len / sizeof(struct vring_desc);
854                         desc = check_pointer(desc[i].addr, desc[i].len);
855                         i = 0;
856
857                         /* 2.4.5.3.1:
858                          *
859                          *  A driver MUST NOT create a descriptor chain longer
860                          *  than the Queue Size of the device.
861                          */
862                         if (max > vq->pci_config.queue_size)
863                                 errx(1, "%s: indirect has too many entries",
864                                      vq->dev->name);
865                 }
866
867                 /* Grab the first descriptor, and check it's OK. */
868                 iov[*out_num + *in_num].iov_len = desc[i].len;
869                 iov[*out_num + *in_num].iov_base
870                         = check_pointer(desc[i].addr, desc[i].len);
871                 /* If this is an input descriptor, increment that count. */
872                 if (desc[i].flags & VRING_DESC_F_WRITE)
873                         (*in_num)++;
874                 else {
875                         /*
876                          * If it's an output descriptor, they're all supposed
877                          * to come before any input descriptors.
878                          */
879                         if (*in_num)
880                                 errx(1, "Descriptor has out after in");
881                         (*out_num)++;
882                 }
883
884                 /* If we've got too many, that implies a descriptor loop. */
885                 if (*out_num + *in_num > max)
886                         errx(1, "Looped descriptor");
887         } while ((i = next_desc(desc, i, max)) != max);
888
889         return head;
890 }
891
892 /*
893  * After we've used one of their buffers, we tell the Guest about it.  Sometime
894  * later we'll want to send them an interrupt using trigger_irq(); note that
895  * wait_for_vq_desc() does that for us if it has to wait.
896  */
897 static void add_used(struct virtqueue *vq, unsigned int head, int len)
898 {
899         struct vring_used_elem *used;
900
901         /*
902          * The virtqueue contains a ring of used buffers.  Get a pointer to the
903          * next entry in that used ring.
904          */
905         used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
906         used->id = head;
907         used->len = len;
908         /* Make sure buffer is written before we update index. */
909         wmb();
910         vq->vring.used->idx++;
911         vq->pending_used++;
912 }
913
914 /* And here's the combo meal deal.  Supersize me! */
915 static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
916 {
917         add_used(vq, head, len);
918         trigger_irq(vq);
919 }
920
921 /*
922  * The Console
923  *
924  * We associate some data with the console for our exit hack.
925  */
926 struct console_abort {
927         /* How many times have they hit ^C? */
928         int count;
929         /* When did they start? */
930         struct timeval start;
931 };
932
933 /* This is the routine which handles console input (ie. stdin). */
934 static void console_input(struct virtqueue *vq)
935 {
936         int len;
937         unsigned int head, in_num, out_num;
938         struct console_abort *abort = vq->dev->priv;
939         struct iovec iov[vq->vring.num];
940
941         /* Make sure there's a descriptor available. */
942         head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
943         if (out_num)
944                 errx(1, "Output buffers in console in queue?");
945
946         /* Read into it.  This is where we usually wait. */
947         len = readv(STDIN_FILENO, iov, in_num);
948         if (len <= 0) {
949                 /* Ran out of input? */
950                 warnx("Failed to get console input, ignoring console.");
951                 /*
952                  * For simplicity, dying threads kill the whole Launcher.  So
953                  * just nap here.
954                  */
955                 for (;;)
956                         pause();
957         }
958
959         /* Tell the Guest we used a buffer. */
960         add_used_and_trigger(vq, head, len);
961
962         /*
963          * Three ^C within one second?  Exit.
964          *
965          * This is such a hack, but works surprisingly well.  Each ^C has to
966          * be in a buffer by itself, so they can't be too fast.  But we check
967          * that we get three within about a second, so they can't be too
968          * slow.
969          */
970         if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
971                 abort->count = 0;
972                 return;
973         }
974
975         abort->count++;
976         if (abort->count == 1)
977                 gettimeofday(&abort->start, NULL);
978         else if (abort->count == 3) {
979                 struct timeval now;
980                 gettimeofday(&now, NULL);
981                 /* Kill all Launcher processes with SIGINT, like normal ^C */
982                 if (now.tv_sec <= abort->start.tv_sec+1)
983                         kill(0, SIGINT);
984                 abort->count = 0;
985         }
986 }
987
988 /* This is the routine which handles console output (ie. stdout). */
989 static void console_output(struct virtqueue *vq)
990 {
991         unsigned int head, out, in;
992         struct iovec iov[vq->vring.num];
993
994         /* We usually wait in here, for the Guest to give us something. */
995         head = wait_for_vq_desc(vq, iov, &out, &in);
996         if (in)
997                 errx(1, "Input buffers in console output queue?");
998
999         /* writev can return a partial write, so we loop here. */
1000         while (!iov_empty(iov, out)) {
1001                 int len = writev(STDOUT_FILENO, iov, out);
1002                 if (len <= 0) {
1003                         warn("Write to stdout gave %i (%d)", len, errno);
1004                         break;
1005                 }
1006                 iov_consume(iov, out, NULL, len);
1007         }
1008
1009         /*
1010          * We're finished with that buffer: if we're going to sleep,
1011          * wait_for_vq_desc() will prod the Guest with an interrupt.
1012          */
1013         add_used(vq, head, 0);
1014 }
1015
1016 /*
1017  * The Network
1018  *
1019  * Handling output for network is also simple: we get all the output buffers
1020  * and write them to /dev/net/tun.
1021  */
1022 struct net_info {
1023         int tunfd;
1024 };
1025
1026 static void net_output(struct virtqueue *vq)
1027 {
1028         struct net_info *net_info = vq->dev->priv;
1029         unsigned int head, out, in;
1030         struct iovec iov[vq->vring.num];
1031
1032         /* We usually wait in here for the Guest to give us a packet. */
1033         head = wait_for_vq_desc(vq, iov, &out, &in);
1034         if (in)
1035                 errx(1, "Input buffers in net output queue?");
1036         /*
1037          * Send the whole thing through to /dev/net/tun.  It expects the exact
1038          * same format: what a coincidence!
1039          */
1040         if (writev(net_info->tunfd, iov, out) < 0)
1041                 warnx("Write to tun failed (%d)?", errno);
1042
1043         /*
1044          * Done with that one; wait_for_vq_desc() will send the interrupt if
1045          * all packets are processed.
1046          */
1047         add_used(vq, head, 0);
1048 }
1049
1050 /*
1051  * Handling network input is a bit trickier, because I've tried to optimize it.
1052  *
1053  * First we have a helper routine which tells is if from this file descriptor
1054  * (ie. the /dev/net/tun device) will block:
1055  */
1056 static bool will_block(int fd)
1057 {
1058         fd_set fdset;
1059         struct timeval zero = { 0, 0 };
1060         FD_ZERO(&fdset);
1061         FD_SET(fd, &fdset);
1062         return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
1063 }
1064
1065 /*
1066  * This handles packets coming in from the tun device to our Guest.  Like all
1067  * service routines, it gets called again as soon as it returns, so you don't
1068  * see a while(1) loop here.
1069  */
1070 static void net_input(struct virtqueue *vq)
1071 {
1072         int len;
1073         unsigned int head, out, in;
1074         struct iovec iov[vq->vring.num];
1075         struct net_info *net_info = vq->dev->priv;
1076
1077         /*
1078          * Get a descriptor to write an incoming packet into.  This will also
1079          * send an interrupt if they're out of descriptors.
1080          */
1081         head = wait_for_vq_desc(vq, iov, &out, &in);
1082         if (out)
1083                 errx(1, "Output buffers in net input queue?");
1084
1085         /*
1086          * If it looks like we'll block reading from the tun device, send them
1087          * an interrupt.
1088          */
1089         if (vq->pending_used && will_block(net_info->tunfd))
1090                 trigger_irq(vq);
1091
1092         /*
1093          * Read in the packet.  This is where we normally wait (when there's no
1094          * incoming network traffic).
1095          */
1096         len = readv(net_info->tunfd, iov, in);
1097         if (len <= 0)
1098                 warn("Failed to read from tun (%d).", errno);
1099
1100         /*
1101          * Mark that packet buffer as used, but don't interrupt here.  We want
1102          * to wait until we've done as much work as we can.
1103          */
1104         add_used(vq, head, len);
1105 }
1106 /*:*/
1107
1108 /* This is the helper to create threads: run the service routine in a loop. */
1109 static int do_thread(void *_vq)
1110 {
1111         struct virtqueue *vq = _vq;
1112
1113         for (;;)
1114                 vq->service(vq);
1115         return 0;
1116 }
1117
1118 /*
1119  * When a child dies, we kill our entire process group with SIGTERM.  This
1120  * also has the side effect that the shell restores the console for us!
1121  */
1122 static void kill_launcher(int signal)
1123 {
1124         kill(0, SIGTERM);
1125 }
1126
1127 static void reset_vq_pci_config(struct virtqueue *vq)
1128 {
1129         vq->pci_config.queue_size = VIRTQUEUE_NUM;
1130         vq->pci_config.queue_enable = 0;
1131 }
1132
1133 static void reset_device(struct device *dev)
1134 {
1135         struct virtqueue *vq;
1136
1137         verbose("Resetting device %s\n", dev->name);
1138
1139         /* Clear any features they've acked. */
1140         dev->features_accepted = 0;
1141
1142         /* We're going to be explicitly killing threads, so ignore them. */
1143         signal(SIGCHLD, SIG_IGN);
1144
1145         /*
1146          * 4.1.4.3.1:
1147          *
1148          *   The device MUST present a 0 in queue_enable on reset. 
1149          *
1150          * This means we set it here, and reset the saved ones in every vq.
1151          */
1152         dev->mmio->cfg.queue_enable = 0;
1153
1154         /* Get rid of the virtqueue threads */
1155         for (vq = dev->vq; vq; vq = vq->next) {
1156                 vq->last_avail_idx = 0;
1157                 reset_vq_pci_config(vq);
1158                 if (vq->thread != (pid_t)-1) {
1159                         kill(vq->thread, SIGTERM);
1160                         waitpid(vq->thread, NULL, 0);
1161                         vq->thread = (pid_t)-1;
1162                 }
1163         }
1164         dev->running = false;
1165         dev->wrote_features_ok = false;
1166
1167         /* Now we care if threads die. */
1168         signal(SIGCHLD, (void *)kill_launcher);
1169 }
1170
1171 static void cleanup_devices(void)
1172 {
1173         unsigned int i;
1174
1175         for (i = 1; i < MAX_PCI_DEVICES; i++) {
1176                 struct device *d = devices.pci[i];
1177                 if (!d)
1178                         continue;
1179                 reset_device(d);
1180         }
1181
1182         /* If we saved off the original terminal settings, restore them now. */
1183         if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1184                 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
1185 }
1186
1187 /*L:217
1188  * We do PCI.  This is mainly done to let us test the kernel virtio PCI
1189  * code.
1190  */
1191
1192 /* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1193 static struct device pci_host_bridge;
1194
1195 static void init_pci_host_bridge(void)
1196 {
1197         pci_host_bridge.name = "PCI Host Bridge";
1198         pci_host_bridge.config.class = 0x06; /* bridge */
1199         pci_host_bridge.config.subclass = 0; /* host bridge */
1200         devices.pci[0] = &pci_host_bridge;
1201 }
1202
1203 /* The IO ports used to read the PCI config space. */
1204 #define PCI_CONFIG_ADDR 0xCF8
1205 #define PCI_CONFIG_DATA 0xCFC
1206
1207 /*
1208  * Not really portable, but does help readability: this is what the Guest
1209  * writes to the PCI_CONFIG_ADDR IO port.
1210  */
1211 union pci_config_addr {
1212         struct {
1213                 unsigned mbz: 2;
1214                 unsigned offset: 6;
1215                 unsigned funcnum: 3;
1216                 unsigned devnum: 5;
1217                 unsigned busnum: 8;
1218                 unsigned reserved: 7;
1219                 unsigned enabled : 1;
1220         } bits;
1221         u32 val;
1222 };
1223
1224 /*
1225  * We cache what they wrote to the address port, so we know what they're
1226  * talking about when they access the data port.
1227  */
1228 static union pci_config_addr pci_config_addr;
1229
1230 static struct device *find_pci_device(unsigned int index)
1231 {
1232         return devices.pci[index];
1233 }
1234
1235 /* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1236 static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1237 {
1238         assert(off < 4);
1239         assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1240         *val = (v >> (off * 8)) & mask;
1241 }
1242
1243 /* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1244 static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1245 {
1246         assert(off < 4);
1247         assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1248         *dst &= ~(mask << (off * 8));
1249         *dst |= (v & mask) << (off * 8);
1250 }
1251
1252 /*
1253  * Where PCI_CONFIG_DATA accesses depends on the previous write to
1254  * PCI_CONFIG_ADDR.
1255  */
1256 static struct device *dev_and_reg(u32 *reg)
1257 {
1258         if (!pci_config_addr.bits.enabled)
1259                 return NULL;
1260
1261         if (pci_config_addr.bits.funcnum != 0)
1262                 return NULL;
1263
1264         if (pci_config_addr.bits.busnum != 0)
1265                 return NULL;
1266
1267         if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1268                 return NULL;
1269
1270         *reg = pci_config_addr.bits.offset;
1271         return find_pci_device(pci_config_addr.bits.devnum);
1272 }
1273
1274 /*
1275  * We can get invalid combinations of values while they're writing, so we
1276  * only fault if they try to write with some invalid bar/offset/length.
1277  */
1278 static bool valid_bar_access(struct device *d,
1279                              struct virtio_pci_cfg_cap *cfg_access)
1280 {
1281         /* We only have 1 bar (BAR0) */
1282         if (cfg_access->cap.bar != 0)
1283                 return false;
1284
1285         /* Check it's within BAR0. */
1286         if (cfg_access->cap.offset >= d->mmio_size
1287             || cfg_access->cap.offset + cfg_access->cap.length > d->mmio_size)
1288                 return false;
1289
1290         /* Check length is 1, 2 or 4. */
1291         if (cfg_access->cap.length != 1
1292             && cfg_access->cap.length != 2
1293             && cfg_access->cap.length != 4)
1294                 return false;
1295
1296         /*
1297          * 4.1.4.7.2:
1298          *
1299          *  The driver MUST NOT write a cap.offset which is not a multiple of
1300          *  cap.length (ie. all accesses MUST be aligned).
1301          */
1302         if (cfg_access->cap.offset % cfg_access->cap.length != 0)
1303                 return false;
1304
1305         /* Return pointer into word in BAR0. */
1306         return true;
1307 }
1308
1309 /* Is this accessing the PCI config address port?. */
1310 static bool is_pci_addr_port(u16 port)
1311 {
1312         return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1313 }
1314
1315 static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1316 {
1317         iowrite(port - PCI_CONFIG_ADDR, val, mask,
1318                 &pci_config_addr.val);
1319         verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1320                 pci_config_addr.bits.enabled ? "" : " DISABLED",
1321                 val, mask,
1322                 pci_config_addr.bits.busnum,
1323                 pci_config_addr.bits.devnum,
1324                 pci_config_addr.bits.funcnum,
1325                 pci_config_addr.bits.offset);
1326         return true;
1327 }
1328
1329 static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1330 {
1331         ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1332 }
1333
1334 /* Is this accessing the PCI config data port?. */
1335 static bool is_pci_data_port(u16 port)
1336 {
1337         return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1338 }
1339
1340 static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask);
1341
1342 static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1343 {
1344         u32 reg, portoff;
1345         struct device *d = dev_and_reg(&reg);
1346
1347         /* Complain if they don't belong to a device. */
1348         if (!d)
1349                 return false;
1350
1351         /* They can do 1 byte writes, etc. */
1352         portoff = port - PCI_CONFIG_DATA;
1353
1354         /*
1355          * PCI uses a weird way to determine the BAR size: the OS
1356          * writes all 1's, and sees which ones stick.
1357          */
1358         if (&d->config_words[reg] == &d->config.bar[0]) {
1359                 int i;
1360
1361                 iowrite(portoff, val, mask, &d->config.bar[0]);
1362                 for (i = 0; (1 << i) < d->mmio_size; i++)
1363                         d->config.bar[0] &= ~(1 << i);
1364                 return true;
1365         } else if ((&d->config_words[reg] > &d->config.bar[0]
1366                     && &d->config_words[reg] <= &d->config.bar[6])
1367                    || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1368                 /* Allow writing to any other BAR, or expansion ROM */
1369                 iowrite(portoff, val, mask, &d->config_words[reg]);
1370                 return true;
1371                 /* We let them overide latency timer and cacheline size */
1372         } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1373                 /* Only let them change the first two fields. */
1374                 if (mask == 0xFFFFFFFF)
1375                         mask = 0xFFFF;
1376                 iowrite(portoff, val, mask, &d->config_words[reg]);
1377                 return true;
1378         } else if (&d->config_words[reg] == (void *)&d->config.command
1379                    && mask == 0xFFFF) {
1380                 /* Ignore command writes. */
1381                 return true;
1382         } else if (&d->config_words[reg]
1383                    == (void *)&d->config.cfg_access.cap.bar
1384                    || &d->config_words[reg]
1385                    == &d->config.cfg_access.cap.length
1386                    || &d->config_words[reg]
1387                    == &d->config.cfg_access.cap.offset) {
1388
1389                 /*
1390                  * The VIRTIO_PCI_CAP_PCI_CFG capability
1391                  * provides a backdoor to access the MMIO
1392                  * regions without mapping them.  Weird, but
1393                  * useful.
1394                  */
1395                 iowrite(portoff, val, mask, &d->config_words[reg]);
1396                 return true;
1397         } else if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
1398                 u32 write_mask;
1399
1400                 /*
1401                  * 4.1.4.7.1:
1402                  *
1403                  *  Upon detecting driver write access to pci_cfg_data, the
1404                  *  device MUST execute a write access at offset cap.offset at
1405                  *  BAR selected by cap.bar using the first cap.length bytes
1406                  *  from pci_cfg_data.
1407                  */
1408
1409                 /* Must be bar 0 */
1410                 if (!valid_bar_access(d, &d->config.cfg_access))
1411                         return false;
1412
1413                 iowrite(portoff, val, mask, &d->config.cfg_access.pci_cfg_data);
1414
1415                 /*
1416                  * Now emulate a write.  The mask we use is set by
1417                  * len, *not* this write!
1418                  */
1419                 write_mask = (1ULL<<(8*d->config.cfg_access.cap.length)) - 1;
1420                 verbose("Window writing %#x/%#x to bar %u, offset %u len %u\n",
1421                         d->config.cfg_access.pci_cfg_data, write_mask,
1422                         d->config.cfg_access.cap.bar,
1423                         d->config.cfg_access.cap.offset,
1424                         d->config.cfg_access.cap.length);
1425
1426                 emulate_mmio_write(d, d->config.cfg_access.cap.offset,
1427                                    d->config.cfg_access.pci_cfg_data,
1428                                    write_mask);
1429                 return true;
1430         }
1431
1432         /*
1433          * 4.1.4.1:
1434          *
1435          *  The driver MUST NOT write into any field of the capability
1436          *  structure, with the exception of those with cap_type
1437          *  VIRTIO_PCI_CAP_PCI_CFG...
1438          */
1439         return false;
1440 }
1441
1442 static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask);
1443
1444 static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1445 {
1446         u32 reg;
1447         struct device *d = dev_and_reg(&reg);
1448
1449         if (!d)
1450                 return;
1451
1452         /* Read through the PCI MMIO access window is special */
1453         if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
1454                 u32 read_mask;
1455
1456                 /*
1457                  * 4.1.4.7.1:
1458                  *
1459                  *  Upon detecting driver read access to pci_cfg_data, the
1460                  *  device MUST execute a read access of length cap.length at
1461                  *  offset cap.offset at BAR selected by cap.bar and store the
1462                  *  first cap.length bytes in pci_cfg_data.
1463                  */
1464                 /* Must be bar 0 */
1465                 if (!valid_bar_access(d, &d->config.cfg_access))
1466                         errx(1, "Invalid cfg_access to bar%u, offset %u len %u",
1467                              d->config.cfg_access.cap.bar,
1468                              d->config.cfg_access.cap.offset,
1469                              d->config.cfg_access.cap.length);
1470
1471                 /*
1472                  * Read into the window.  The mask we use is set by
1473                  * len, *not* this read!
1474                  */
1475                 read_mask = (1ULL<<(8*d->config.cfg_access.cap.length))-1;
1476                 d->config.cfg_access.pci_cfg_data
1477                         = emulate_mmio_read(d,
1478                                             d->config.cfg_access.cap.offset,
1479                                             read_mask);
1480                 verbose("Window read %#x/%#x from bar %u, offset %u len %u\n",
1481                         d->config.cfg_access.pci_cfg_data, read_mask,
1482                         d->config.cfg_access.cap.bar,
1483                         d->config.cfg_access.cap.offset,
1484                         d->config.cfg_access.cap.length);
1485         }
1486         ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1487 }
1488
1489 /*L:216
1490  * This is where we emulate a handful of Guest instructions.  It's ugly
1491  * and we used to do it in the kernel but it grew over time.
1492  */
1493
1494 /*
1495  * We use the ptrace syscall's pt_regs struct to talk about registers
1496  * to lguest: these macros convert the names to the offsets.
1497  */
1498 #define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1499 #define setreg(name, val) \
1500         setreg_off(offsetof(struct user_regs_struct, name), (val))
1501
1502 static u32 getreg_off(size_t offset)
1503 {
1504         u32 r;
1505         unsigned long args[] = { LHREQ_GETREG, offset };
1506
1507         if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1508                 err(1, "Getting register %u", offset);
1509         if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1510                 err(1, "Reading register %u", offset);
1511
1512         return r;
1513 }
1514
1515 static void setreg_off(size_t offset, u32 val)
1516 {
1517         unsigned long args[] = { LHREQ_SETREG, offset, val };
1518
1519         if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1520                 err(1, "Setting register %u", offset);
1521 }
1522
1523 /* Get register by instruction encoding */
1524 static u32 getreg_num(unsigned regnum, u32 mask)
1525 {
1526         /* 8 bit ops use regnums 4-7 for high parts of word */
1527         if (mask == 0xFF && (regnum & 0x4))
1528                 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1529
1530         switch (regnum) {
1531         case 0: return getreg(eax) & mask;
1532         case 1: return getreg(ecx) & mask;
1533         case 2: return getreg(edx) & mask;
1534         case 3: return getreg(ebx) & mask;
1535         case 4: return getreg(esp) & mask;
1536         case 5: return getreg(ebp) & mask;
1537         case 6: return getreg(esi) & mask;
1538         case 7: return getreg(edi) & mask;
1539         }
1540         abort();
1541 }
1542
1543 /* Set register by instruction encoding */
1544 static void setreg_num(unsigned regnum, u32 val, u32 mask)
1545 {
1546         /* Don't try to set bits out of range */
1547         assert(~(val & ~mask));
1548
1549         /* 8 bit ops use regnums 4-7 for high parts of word */
1550         if (mask == 0xFF && (regnum & 0x4)) {
1551                 /* Construct the 16 bits we want. */
1552                 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1553                 setreg_num(regnum & 0x3, val, 0xFFFF);
1554                 return;
1555         }
1556
1557         switch (regnum) {
1558         case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1559         case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1560         case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1561         case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1562         case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1563         case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1564         case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1565         case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1566         }
1567         abort();
1568 }
1569
1570 /* Get bytes of displacement appended to instruction, from r/m encoding */
1571 static u32 insn_displacement_len(u8 mod_reg_rm)
1572 {
1573         /* Switch on the mod bits */
1574         switch (mod_reg_rm >> 6) {
1575         case 0:
1576                 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1577                 if ((mod_reg_rm & 0x7) == 0x5)
1578                         return 2;
1579                 /* Normally, mod == 0 means no literal displacement */
1580                 return 0;
1581         case 1:
1582                 /* One byte displacement */
1583                 return 1;
1584         case 2:
1585                 /* Four byte displacement */
1586                 return 4;
1587         case 3:
1588                 /* Register mode */
1589                 return 0;
1590         }
1591         abort();
1592 }
1593
1594 static void emulate_insn(const u8 insn[])
1595 {
1596         unsigned long args[] = { LHREQ_TRAP, 13 };
1597         unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1598         unsigned int eax, port, mask;
1599         /*
1600          * Default is to return all-ones on IO port reads, which traditionally
1601          * means "there's nothing there".
1602          */
1603         u32 val = 0xFFFFFFFF;
1604
1605         /*
1606          * This must be the Guest kernel trying to do something, not userspace!
1607          * The bottom two bits of the CS segment register are the privilege
1608          * level.
1609          */
1610         if ((getreg(xcs) & 3) != 0x1)
1611                 goto no_emulate;
1612
1613         /* Decoding x86 instructions is icky. */
1614
1615         /*
1616          * Around 2.6.33, the kernel started using an emulation for the
1617          * cmpxchg8b instruction in early boot on many configurations.  This
1618          * code isn't paravirtualized, and it tries to disable interrupts.
1619          * Ignore it, which will Mostly Work.
1620          */
1621         if (insn[insnlen] == 0xfa) {
1622                 /* "cli", or Clear Interrupt Enable instruction.  Skip it. */
1623                 insnlen = 1;
1624                 goto skip_insn;
1625         }
1626
1627         /*
1628          * 0x66 is an "operand prefix".  It means a 16, not 32 bit in/out.
1629          */
1630         if (insn[insnlen] == 0x66) {
1631                 small_operand = 1;
1632                 /* The instruction is 1 byte so far, read the next byte. */
1633                 insnlen = 1;
1634         }
1635
1636         /* If the lower bit isn't set, it's a single byte access */
1637         byte_access = !(insn[insnlen] & 1);
1638
1639         /*
1640          * Now we can ignore the lower bit and decode the 4 opcodes
1641          * we need to emulate.
1642          */
1643         switch (insn[insnlen] & 0xFE) {
1644         case 0xE4: /* in     <next byte>,%al */
1645                 port = insn[insnlen+1];
1646                 insnlen += 2;
1647                 in = 1;
1648                 break;
1649         case 0xEC: /* in     (%dx),%al */
1650                 port = getreg(edx) & 0xFFFF;
1651                 insnlen += 1;
1652                 in = 1;
1653                 break;
1654         case 0xE6: /* out    %al,<next byte> */
1655                 port = insn[insnlen+1];
1656                 insnlen += 2;
1657                 break;
1658         case 0xEE: /* out    %al,(%dx) */
1659                 port = getreg(edx) & 0xFFFF;
1660                 insnlen += 1;
1661                 break;
1662         default:
1663                 /* OK, we don't know what this is, can't emulate. */
1664                 goto no_emulate;
1665         }
1666
1667         /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1668         if (byte_access)
1669                 mask = 0xFF;
1670         else if (small_operand)
1671                 mask = 0xFFFF;
1672         else
1673                 mask = 0xFFFFFFFF;
1674
1675         /*
1676          * If it was an "IN" instruction, they expect the result to be read
1677          * into %eax, so we change %eax.
1678          */
1679         eax = getreg(eax);
1680
1681         if (in) {
1682                 /* This is the PS/2 keyboard status; 1 means ready for output */
1683                 if (port == 0x64)
1684                         val = 1;
1685                 else if (is_pci_addr_port(port))
1686                         pci_addr_ioread(port, mask, &val);
1687                 else if (is_pci_data_port(port))
1688                         pci_data_ioread(port, mask, &val);
1689
1690                 /* Clear the bits we're about to read */
1691                 eax &= ~mask;
1692                 /* Copy bits in from val. */
1693                 eax |= val & mask;
1694                 /* Now update the register. */
1695                 setreg(eax, eax);
1696         } else {
1697                 if (is_pci_addr_port(port)) {
1698                         if (!pci_addr_iowrite(port, mask, eax))
1699                                 goto bad_io;
1700                 } else if (is_pci_data_port(port)) {
1701                         if (!pci_data_iowrite(port, mask, eax))
1702                                 goto bad_io;
1703                 }
1704                 /* There are many other ports, eg. CMOS clock, serial
1705                  * and parallel ports, so we ignore them all. */
1706         }
1707
1708         verbose("IO %s of %x to %u: %#08x\n",
1709                 in ? "IN" : "OUT", mask, port, eax);
1710 skip_insn:
1711         /* Finally, we've "done" the instruction, so move past it. */
1712         setreg(eip, getreg(eip) + insnlen);
1713         return;
1714
1715 bad_io:
1716         warnx("Attempt to %s port %u (%#x mask)",
1717               in ? "read from" : "write to", port, mask);
1718
1719 no_emulate:
1720         /* Inject trap into Guest. */
1721         if (write(lguest_fd, args, sizeof(args)) < 0)
1722                 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1723 }
1724
1725 static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1726 {
1727         unsigned int i;
1728
1729         for (i = 1; i < MAX_PCI_DEVICES; i++) {
1730                 struct device *d = devices.pci[i];
1731
1732                 if (!d)
1733                         continue;
1734                 if (paddr < d->mmio_addr)
1735                         continue;
1736                 if (paddr >= d->mmio_addr + d->mmio_size)
1737                         continue;
1738                 *off = paddr - d->mmio_addr;
1739                 return d;
1740         }
1741         return NULL;
1742 }
1743
1744 /* FIXME: Use vq array. */
1745 static struct virtqueue *vq_by_num(struct device *d, u32 num)
1746 {
1747         struct virtqueue *vq = d->vq;
1748
1749         while (num-- && vq)
1750                 vq = vq->next;
1751
1752         return vq;
1753 }
1754
1755 static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1756                            struct virtqueue *vq)
1757 {
1758         vq->pci_config = *cfg;
1759 }
1760
1761 static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1762                               struct virtqueue *vq)
1763 {
1764         /* Only restore the per-vq part */
1765         size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1766
1767         memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1768                sizeof(*cfg) - off);
1769 }
1770
1771 /*
1772  * 4.1.4.3.2:
1773  *
1774  *  The driver MUST configure the other virtqueue fields before
1775  *  enabling the virtqueue with queue_enable.
1776  *
1777  * When they enable the virtqueue, we check that their setup is valid.
1778  */
1779 static void check_virtqueue(struct device *d, struct virtqueue *vq)
1780 {
1781         /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1782         if (vq->pci_config.queue_desc_hi
1783             || vq->pci_config.queue_avail_hi
1784             || vq->pci_config.queue_used_hi)
1785                 errx(1, "%s: invalid 64-bit queue address", d->name);
1786
1787         /*
1788          * 2.4.1:
1789          *
1790          *  The driver MUST ensure that the physical address of the first byte
1791          *  of each virtqueue part is a multiple of the specified alignment
1792          *  value in the above table.
1793          */
1794         if (vq->pci_config.queue_desc_lo % 16
1795             || vq->pci_config.queue_avail_lo % 2
1796             || vq->pci_config.queue_used_lo % 4)
1797                 errx(1, "%s: invalid alignment in queue addresses", d->name);
1798
1799         /* Initialize the virtqueue and check they're all in range. */
1800         vq->vring.num = vq->pci_config.queue_size;
1801         vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1802                                        sizeof(*vq->vring.desc) * vq->vring.num);
1803         vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1804                                         sizeof(*vq->vring.avail)
1805                                         + (sizeof(vq->vring.avail->ring[0])
1806                                            * vq->vring.num));
1807         vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1808                                        sizeof(*vq->vring.used)
1809                                        + (sizeof(vq->vring.used->ring[0])
1810                                           * vq->vring.num));
1811
1812         /*
1813          * 2.4.9.1:
1814          *
1815          *   The driver MUST initialize flags in the used ring to 0
1816          *   when allocating the used ring.
1817          */
1818         if (vq->vring.used->flags != 0)
1819                 errx(1, "%s: invalid initial used.flags %#x",
1820                      d->name, vq->vring.used->flags);
1821 }
1822
1823 static void start_virtqueue(struct virtqueue *vq)
1824 {
1825         /*
1826          * Create stack for thread.  Since the stack grows upwards, we point
1827          * the stack pointer to the end of this region.
1828          */
1829         char *stack = malloc(32768);
1830
1831         /* Create a zero-initialized eventfd. */
1832         vq->eventfd = eventfd(0, 0);
1833         if (vq->eventfd < 0)
1834                 err(1, "Creating eventfd");
1835
1836         /*
1837          * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1838          * we get a signal if it dies.
1839          */
1840         vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1841         if (vq->thread == (pid_t)-1)
1842                 err(1, "Creating clone");
1843 }
1844
1845 static void start_virtqueues(struct device *d)
1846 {
1847         struct virtqueue *vq;
1848
1849         for (vq = d->vq; vq; vq = vq->next) {
1850                 if (vq->pci_config.queue_enable)
1851                         start_virtqueue(vq);
1852         }
1853 }
1854
1855 static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1856 {
1857         struct virtqueue *vq;
1858
1859         switch (off) {
1860         case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1861                 /*
1862                  * 4.1.4.3.1:
1863                  *
1864                  * The device MUST present the feature bits it is offering in
1865                  * device_feature, starting at bit device_feature_select ∗ 32
1866                  * for any device_feature_select written by the driver
1867                  */
1868                 if (val == 0)
1869                         d->mmio->cfg.device_feature = d->features;
1870                 else if (val == 1)
1871                         d->mmio->cfg.device_feature = (d->features >> 32);
1872                 else
1873                         d->mmio->cfg.device_feature = 0;
1874                 goto feature_write_through32;
1875         case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1876                 if (val > 1)
1877                         errx(1, "%s: Unexpected driver select %u",
1878                              d->name, val);
1879                 goto feature_write_through32;
1880         case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1881                 if (d->mmio->cfg.guest_feature_select == 0) {
1882                         d->features_accepted &= ~((u64)0xFFFFFFFF);
1883                         d->features_accepted |= val;
1884                 } else {
1885                         assert(d->mmio->cfg.guest_feature_select == 1);
1886                         d->features_accepted &= 0xFFFFFFFF;
1887                         d->features_accepted |= ((u64)val) << 32;
1888                 }
1889                 /*
1890                  * 2.2.1:
1891                  *
1892                  *   The driver MUST NOT accept a feature which the device did
1893                  *   not offer
1894                  */
1895                 if (d->features_accepted & ~d->features)
1896                         errx(1, "%s: over-accepted features %#llx of %#llx",
1897                              d->name, d->features_accepted, d->features);
1898                 goto feature_write_through32;
1899         case offsetof(struct virtio_pci_mmio, cfg.device_status): {
1900                 u8 prev;
1901
1902                 verbose("%s: device status -> %#x\n", d->name, val);
1903                 /*
1904                  * 4.1.4.3.1:
1905                  * 
1906                  *  The device MUST reset when 0 is written to device_status,
1907                  *  and present a 0 in device_status once that is done.
1908                  */
1909                 if (val == 0) {
1910                         reset_device(d);
1911                         goto write_through8;
1912                 }
1913
1914                 /* 2.1.1: The driver MUST NOT clear a device status bit. */
1915                 if (d->mmio->cfg.device_status & ~val)
1916                         errx(1, "%s: unset of device status bit %#x -> %#x",
1917                              d->name, d->mmio->cfg.device_status, val);
1918
1919                 /*
1920                  * 2.1.2:
1921                  *
1922                  *  The device MUST NOT consume buffers or notify the driver
1923                  *  before DRIVER_OK.
1924                  */
1925                 if (val & VIRTIO_CONFIG_S_DRIVER_OK
1926                     && !(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
1927                         start_virtqueues(d);
1928
1929                 /*
1930                  * 3.1.1:
1931                  *
1932                  *   The driver MUST follow this sequence to initialize a device:
1933                  *   - Reset the device.
1934                  *   - Set the ACKNOWLEDGE status bit: the guest OS has
1935                  *     notice the device.
1936                  *   - Set the DRIVER status bit: the guest OS knows how
1937                  *     to drive the device.
1938                  *   - Read device feature bits, and write the subset
1939                  *     of feature bits understood by the OS and driver
1940                  *     to the device. During this step the driver MAY
1941                  *     read (but MUST NOT write) the device-specific
1942                  *     configuration fields to check that it can
1943                  *     support the device before accepting it.
1944                  *   - Set the FEATURES_OK status bit.  The driver
1945                  *     MUST not accept new feature bits after this
1946                  *     step.
1947                  *   - Re-read device status to ensure the FEATURES_OK
1948                  *     bit is still set: otherwise, the device does
1949                  *     not support our subset of features and the
1950                  *     device is unusable.
1951                  *   - Perform device-specific setup, including
1952                  *     discovery of virtqueues for the device,
1953                  *     optional per-bus setup, reading and possibly
1954                  *     writing the device’s virtio configuration
1955                  *     space, and population of virtqueues.
1956                  *   - Set the DRIVER_OK status bit. At this point the
1957                  *     device is “live”.
1958                  */
1959                 prev = 0;
1960                 switch (val & ~d->mmio->cfg.device_status) {
1961                 case VIRTIO_CONFIG_S_DRIVER_OK:
1962                         prev |= VIRTIO_CONFIG_S_FEATURES_OK; /* fall thru */
1963                 case VIRTIO_CONFIG_S_FEATURES_OK:
1964                         prev |= VIRTIO_CONFIG_S_DRIVER; /* fall thru */
1965                 case VIRTIO_CONFIG_S_DRIVER:
1966                         prev |= VIRTIO_CONFIG_S_ACKNOWLEDGE; /* fall thru */
1967                 case VIRTIO_CONFIG_S_ACKNOWLEDGE:
1968                         break;
1969                 default:
1970                         errx(1, "%s: unknown device status bit %#x -> %#x",
1971                              d->name, d->mmio->cfg.device_status, val);
1972                 }
1973                 if (d->mmio->cfg.device_status != prev)
1974                         errx(1, "%s: unexpected status transition %#x -> %#x",
1975                              d->name, d->mmio->cfg.device_status, val);
1976
1977                 /* If they just wrote FEATURES_OK, we make sure they read */
1978                 switch (val & ~d->mmio->cfg.device_status) {
1979                 case VIRTIO_CONFIG_S_FEATURES_OK:
1980                         d->wrote_features_ok = true;
1981                         break;
1982                 case VIRTIO_CONFIG_S_DRIVER_OK:
1983                         if (d->wrote_features_ok)
1984                                 errx(1, "%s: did not re-read FEATURES_OK",
1985                                      d->name);
1986                         break;
1987                 }
1988                 goto write_through8;
1989         }
1990         case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1991                 vq = vq_by_num(d, val);
1992                 /*
1993                  * 4.1.4.3.1:
1994                  *
1995                  *  The device MUST present a 0 in queue_size if the virtqueue
1996                  *  corresponding to the current queue_select is unavailable.
1997                  */
1998                 if (!vq) {
1999                         d->mmio->cfg.queue_size = 0;
2000                         goto write_through16;
2001                 }
2002                 /* Save registers for old vq, if it was a valid vq */
2003                 if (d->mmio->cfg.queue_size)
2004                         save_vq_config(&d->mmio->cfg,
2005                                        vq_by_num(d, d->mmio->cfg.queue_select));
2006                 /* Restore the registers for the queue they asked for */
2007                 restore_vq_config(&d->mmio->cfg, vq);
2008                 goto write_through16;
2009         case offsetof(struct virtio_pci_mmio, cfg.queue_size):
2010                 /*
2011                  * 4.1.4.3.2:
2012                  *
2013                  *  The driver MUST NOT write a value which is not a power of 2
2014                  *  to queue_size.
2015                  */
2016                 if (val & (val-1))
2017                         errx(1, "%s: invalid queue size %u\n", d->name, val);
2018                 if (d->mmio->cfg.queue_enable)
2019                         errx(1, "%s: changing queue size on live device",
2020                              d->name);
2021                 goto write_through16;
2022         case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
2023                 errx(1, "%s: attempt to set MSIX vector to %u",
2024                      d->name, val);
2025         case offsetof(struct virtio_pci_mmio, cfg.queue_enable): {
2026                 struct virtqueue *vq = vq_by_num(d, d->mmio->cfg.queue_select);
2027
2028                 /*
2029                  * 4.1.4.3.2:
2030                  *
2031                  *  The driver MUST NOT write a 0 to queue_enable.
2032                  */
2033                 if (val != 1)
2034                         errx(1, "%s: setting queue_enable to %u", d->name, val);
2035
2036                 /*
2037                  * 3.1.1:
2038                  *
2039                  *  7. Perform device-specific setup, including discovery of
2040                  *     virtqueues for the device, optional per-bus setup,
2041                  *     reading and possibly writing the device’s virtio
2042                  *     configuration space, and population of virtqueues.
2043                  *  8. Set the DRIVER_OK status bit.
2044                  *
2045                  * All our devices require all virtqueues to be enabled, so
2046                  * they should have done that before setting DRIVER_OK.
2047                  */
2048                 if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK)
2049                         errx(1, "%s: enabling vs after DRIVER_OK", d->name);
2050
2051                 d->mmio->cfg.queue_enable = val;
2052                 save_vq_config(&d->mmio->cfg, vq);
2053                 check_virtqueue(d, vq);
2054                 goto write_through16;
2055         }
2056         case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
2057                 errx(1, "%s: attempt to write to queue_notify_off", d->name);
2058         case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
2059         case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
2060         case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
2061         case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
2062         case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
2063         case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
2064                 /*
2065                  * 4.1.4.3.2:
2066                  *
2067                  *  The driver MUST configure the other virtqueue fields before
2068                  *  enabling the virtqueue with queue_enable.
2069                  */
2070                 if (d->mmio->cfg.queue_enable)
2071                         errx(1, "%s: changing queue on live device",
2072                              d->name);
2073
2074                 /*
2075                  * 3.1.1:
2076                  *
2077                  *  The driver MUST follow this sequence to initialize a device:
2078                  *...
2079                  *  5. Set the FEATURES_OK status bit. The driver MUST not
2080                  *  accept new feature bits after this step.
2081                  */
2082                 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK))
2083                         errx(1, "%s: enabling vs before FEATURES_OK", d->name);
2084
2085                 /*
2086                  *  6. Re-read device status to ensure the FEATURES_OK bit is
2087                  *     still set...
2088                  */
2089                 if (d->wrote_features_ok)
2090                         errx(1, "%s: didn't re-read FEATURES_OK before setup",
2091                              d->name);
2092
2093                 goto write_through32;
2094         case offsetof(struct virtio_pci_mmio, notify):
2095                 vq = vq_by_num(d, val);
2096                 if (!vq)
2097                         errx(1, "Invalid vq notification on %u", val);
2098                 /* Notify the process handling this vq by adding 1 to eventfd */
2099                 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
2100                 goto write_through16;
2101         case offsetof(struct virtio_pci_mmio, isr):
2102                 errx(1, "%s: Unexpected write to isr", d->name);
2103         /* Weird corner case: write to emerg_wr of console */
2104         case sizeof(struct virtio_pci_mmio)
2105                 + offsetof(struct virtio_console_config, emerg_wr):
2106                 if (strcmp(d->name, "console") == 0) {
2107                         char c = val;
2108                         write(STDOUT_FILENO, &c, 1);
2109                         goto write_through32;
2110                 }
2111                 /* Fall through... */
2112         default:
2113                 /*
2114                  * 4.1.4.3.2:
2115                  *
2116                  *   The driver MUST NOT write to device_feature, num_queues,
2117                  *   config_generation or queue_notify_off.
2118                  */
2119                 errx(1, "%s: Unexpected write to offset %u", d->name, off);
2120         }
2121
2122 feature_write_through32:
2123         /*
2124          * 3.1.1:
2125          *
2126          *   The driver MUST follow this sequence to initialize a device:
2127          *...
2128          *   - Set the DRIVER status bit: the guest OS knows how
2129          *     to drive the device.
2130          *   - Read device feature bits, and write the subset
2131          *     of feature bits understood by the OS and driver
2132          *     to the device.
2133          *...
2134          *   - Set the FEATURES_OK status bit. The driver MUST not
2135          *     accept new feature bits after this step.
2136          */
2137         if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2138                 errx(1, "%s: feature write before VIRTIO_CONFIG_S_DRIVER",
2139                      d->name);
2140         if (d->mmio->cfg.device_status & VIRTIO_CONFIG_S_FEATURES_OK)
2141                 errx(1, "%s: feature write after VIRTIO_CONFIG_S_FEATURES_OK",
2142                      d->name);
2143
2144         /*
2145          * 4.1.3.1:
2146          *
2147          *  The driver MUST access each field using the “natural” access
2148          *  method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
2149          *  16-bit fields and 8-bit accesses for 8-bit fields.
2150          */
2151 write_through32:
2152         if (mask != 0xFFFFFFFF) {
2153                 errx(1, "%s: non-32-bit write to offset %u (%#x)",
2154                      d->name, off, getreg(eip));
2155                 return;
2156         }
2157         memcpy((char *)d->mmio + off, &val, 4);
2158         return;
2159
2160 write_through16:
2161         if (mask != 0xFFFF)
2162                 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
2163                      d->name, mask, off, getreg(eip));
2164         memcpy((char *)d->mmio + off, &val, 2);
2165         return;
2166
2167 write_through8:
2168         if (mask != 0xFF)
2169                 errx(1, "%s: non-8-bit write to offset %u (%#x)",
2170                      d->name, off, getreg(eip));
2171         memcpy((char *)d->mmio + off, &val, 1);
2172         return;
2173 }
2174
2175 static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
2176 {
2177         u8 isr;
2178         u32 val = 0;
2179
2180         switch (off) {
2181         case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
2182         case offsetof(struct virtio_pci_mmio, cfg.device_feature):
2183         case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
2184         case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
2185                 /*
2186                  * 3.1.1:
2187                  *
2188                  *   The driver MUST follow this sequence to initialize a device:
2189                  *...
2190                  *   - Set the DRIVER status bit: the guest OS knows how
2191                  *     to drive the device.
2192                  *   - Read device feature bits, and write the subset
2193                  *     of feature bits understood by the OS and driver
2194                  *     to the device.
2195                  */
2196                 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2197                         errx(1, "%s: feature read before VIRTIO_CONFIG_S_DRIVER",
2198                              d->name);
2199                 goto read_through32;
2200         case offsetof(struct virtio_pci_mmio, cfg.msix_config):
2201                 errx(1, "%s: read of msix_config", d->name);
2202         case offsetof(struct virtio_pci_mmio, cfg.num_queues):
2203                 goto read_through16;
2204         case offsetof(struct virtio_pci_mmio, cfg.device_status):
2205                 /* As they did read, any write of FEATURES_OK is now fine. */
2206                 d->wrote_features_ok = false;
2207                 goto read_through8;
2208         case offsetof(struct virtio_pci_mmio, cfg.config_generation):
2209                 /*
2210                  * 4.1.4.3.1:
2211                  *
2212                  *  The device MUST present a changed config_generation after
2213                  *  the driver has read a device-specific configuration value
2214                  *  which has changed since any part of the device-specific
2215                  *  configuration was last read.
2216                  *
2217                  * This is simple: none of our devices change config, so this
2218                  * is always 0.
2219                  */
2220                 goto read_through8;
2221         case offsetof(struct virtio_pci_mmio, notify):
2222                 /*
2223                  * 3.1.1:
2224                  *
2225                  *   The driver MUST NOT notify the device before setting
2226                  *   DRIVER_OK.
2227                  */
2228                 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER_OK))
2229                         errx(1, "%s: notify before VIRTIO_CONFIG_S_DRIVER_OK",
2230                              d->name);
2231                 goto read_through16;
2232         case offsetof(struct virtio_pci_mmio, isr):
2233                 if (mask != 0xFF)
2234                         errx(1, "%s: non-8-bit read from offset %u (%#x)",
2235                              d->name, off, getreg(eip));
2236                 isr = d->mmio->isr;
2237                 /*
2238                  * 4.1.4.5.1:
2239                  *
2240                  *  The device MUST reset ISR status to 0 on driver read. 
2241                  */
2242                 d->mmio->isr = 0;
2243                 return isr;
2244         case offsetof(struct virtio_pci_mmio, padding):
2245                 errx(1, "%s: read from padding (%#x)",
2246                      d->name, getreg(eip));
2247         default:
2248                 /* Read from device config space, beware unaligned overflow */
2249                 if (off > d->mmio_size - 4)
2250                         errx(1, "%s: read past end (%#x)",
2251                              d->name, getreg(eip));
2252
2253                 /*
2254                  * 3.1.1:
2255                  *  The driver MUST follow this sequence to initialize a device:
2256                  *...
2257                  *  3. Set the DRIVER status bit: the guest OS knows how to
2258                  *  drive the device.
2259                  *  4. Read device feature bits, and write the subset of
2260                  *  feature bits understood by the OS and driver to the
2261                  *  device. During this step the driver MAY read (but MUST NOT
2262                  *  write) the device-specific configuration fields to check
2263                  *  that it can support the device before accepting it.
2264                  */
2265                 if (!(d->mmio->cfg.device_status & VIRTIO_CONFIG_S_DRIVER))
2266                         errx(1, "%s: config read before VIRTIO_CONFIG_S_DRIVER",
2267                              d->name);
2268
2269                 if (mask == 0xFFFFFFFF)
2270                         goto read_through32;
2271                 else if (mask == 0xFFFF)
2272                         goto read_through16;
2273                 else
2274                         goto read_through8;
2275         }
2276
2277         /*
2278          * 4.1.3.1:
2279          *
2280          *  The driver MUST access each field using the “natural” access
2281          *  method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
2282          *  16-bit fields and 8-bit accesses for 8-bit fields.
2283          */
2284 read_through32:
2285         if (mask != 0xFFFFFFFF)
2286                 errx(1, "%s: non-32-bit read to offset %u (%#x)",
2287                      d->name, off, getreg(eip));
2288         memcpy(&val, (char *)d->mmio + off, 4);
2289         return val;
2290
2291 read_through16:
2292         if (mask != 0xFFFF)
2293                 errx(1, "%s: non-16-bit read to offset %u (%#x)",
2294                      d->name, off, getreg(eip));
2295         memcpy(&val, (char *)d->mmio + off, 2);
2296         return val;
2297
2298 read_through8:
2299         if (mask != 0xFF)
2300                 errx(1, "%s: non-8-bit read to offset %u (%#x)",
2301                      d->name, off, getreg(eip));
2302         memcpy(&val, (char *)d->mmio + off, 1);
2303         return val;
2304 }
2305
2306 static void emulate_mmio(unsigned long paddr, const u8 *insn)
2307 {
2308         u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
2309         struct device *d = find_mmio_region(paddr, &off);
2310         unsigned long args[] = { LHREQ_TRAP, 14 };
2311
2312         if (!d) {
2313                 warnx("MMIO touching %#08lx (not a device)", paddr);
2314                 goto reinject;
2315         }
2316
2317         /* Prefix makes it a 16 bit op */
2318         if (insn[0] == 0x66) {
2319                 mask = 0xFFFF;
2320                 insnlen++;
2321         }
2322
2323         /* iowrite */
2324         if (insn[insnlen] == 0x89) {
2325                 /* Next byte is r/m byte: bits 3-5 are register. */
2326                 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
2327                 emulate_mmio_write(d, off, val, mask);
2328                 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2329         } else if (insn[insnlen] == 0x8b) { /* ioread */
2330                 /* Next byte is r/m byte: bits 3-5 are register. */
2331                 val = emulate_mmio_read(d, off, mask);
2332                 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
2333                 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2334         } else if (insn[0] == 0x88) { /* 8-bit iowrite */
2335                 mask = 0xff;
2336                 /* Next byte is r/m byte: bits 3-5 are register. */
2337                 val = getreg_num((insn[1] >> 3) & 0x7, mask);
2338                 emulate_mmio_write(d, off, val, mask);
2339                 insnlen = 2 + insn_displacement_len(insn[1]);
2340         } else if (insn[0] == 0x8a) { /* 8-bit ioread */
2341                 mask = 0xff;
2342                 val = emulate_mmio_read(d, off, mask);
2343                 setreg_num((insn[1] >> 3) & 0x7, val, mask);
2344                 insnlen = 2 + insn_displacement_len(insn[1]);
2345         } else {
2346                 warnx("Unknown MMIO instruction touching %#08lx:"
2347                      " %02x %02x %02x %02x at %u",
2348                      paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
2349         reinject:
2350                 /* Inject trap into Guest. */
2351                 if (write(lguest_fd, args, sizeof(args)) < 0)
2352                         err(1, "Reinjecting trap 14 for fault at %#x",
2353                             getreg(eip));
2354                 return;
2355         }
2356
2357         /* Finally, we've "done" the instruction, so move past it. */
2358         setreg(eip, getreg(eip) + insnlen);
2359 }
2360
2361 /*L:190
2362  * Device Setup
2363  *
2364  * All devices need a descriptor so the Guest knows it exists, and a "struct
2365  * device" so the Launcher can keep track of it.  We have common helper
2366  * routines to allocate and manage them.
2367  */
2368 static void add_pci_virtqueue(struct device *dev,
2369                               void (*service)(struct virtqueue *))
2370 {
2371         struct virtqueue **i, *vq = malloc(sizeof(*vq));
2372
2373         /* Initialize the virtqueue */
2374         vq->next = NULL;
2375         vq->last_avail_idx = 0;
2376         vq->dev = dev;
2377
2378         /*
2379          * This is the routine the service thread will run, and its Process ID
2380          * once it's running.
2381          */
2382         vq->service = service;
2383         vq->thread = (pid_t)-1;
2384
2385         /* Initialize the configuration. */
2386         reset_vq_pci_config(vq);
2387         vq->pci_config.queue_notify_off = 0;
2388
2389         /* Add one to the number of queues */
2390         vq->dev->mmio->cfg.num_queues++;
2391
2392         /*
2393          * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2394          * second.
2395          */
2396         for (i = &dev->vq; *i; i = &(*i)->next);
2397         *i = vq;
2398 }
2399
2400 /* The Guest accesses the feature bits via the PCI common config MMIO region */
2401 static void add_pci_feature(struct device *dev, unsigned bit)
2402 {
2403         dev->features |= (1ULL << bit);
2404 }
2405
2406 /* For devices with no config. */
2407 static void no_device_config(struct device *dev)
2408 {
2409         dev->mmio_addr = get_mmio_region(dev->mmio_size);
2410
2411         dev->config.bar[0] = dev->mmio_addr;
2412         /* Bottom 4 bits must be zero */
2413         assert(~(dev->config.bar[0] & 0xF));
2414 }
2415
2416 /* This puts the device config into BAR0 */
2417 static void set_device_config(struct device *dev, const void *conf, size_t len)
2418 {
2419         /* Set up BAR 0 */
2420         dev->mmio_size += len;
2421         dev->mmio = realloc(dev->mmio, dev->mmio_size);
2422         memcpy(dev->mmio + 1, conf, len);
2423
2424         /*
2425          * 4.1.4.6:
2426          *
2427          *  The device MUST present at least one VIRTIO_PCI_CAP_DEVICE_CFG
2428          *  capability for any device type which has a device-specific
2429          *  configuration.
2430          */
2431         /* Hook up device cfg */
2432         dev->config.cfg_access.cap.cap_next
2433                 = offsetof(struct pci_config, device);
2434
2435         /*
2436          * 4.1.4.6.1:
2437          *
2438          *  The offset for the device-specific configuration MUST be 4-byte
2439          *  aligned.
2440          */
2441         assert(dev->config.cfg_access.cap.cap_next % 4 == 0);
2442
2443         /* Fix up device cfg field length. */
2444         dev->config.device.length = len;
2445
2446         /* The rest is the same as the no-config case */
2447         no_device_config(dev);
2448 }
2449
2450 static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2451                      size_t bar_offset, size_t bar_bytes, u8 next)
2452 {
2453         cap->cap_vndr = PCI_CAP_ID_VNDR;
2454         cap->cap_next = next;
2455         cap->cap_len = caplen;
2456         cap->cfg_type = type;
2457         cap->bar = 0;
2458         memset(cap->padding, 0, sizeof(cap->padding));
2459         cap->offset = bar_offset;
2460         cap->length = bar_bytes;
2461 }
2462
2463 /*
2464  * This sets up the pci_config structure, as defined in the virtio 1.0
2465  * standard (and PCI standard).
2466  */
2467 static void init_pci_config(struct pci_config *pci, u16 type,
2468                             u8 class, u8 subclass)
2469 {
2470         size_t bar_offset, bar_len;
2471
2472         /*
2473          * 4.1.4.4.1:
2474          *
2475          *  The device MUST either present notify_off_multiplier as an even
2476          *  power of 2, or present notify_off_multiplier as 0.
2477          *
2478          * 2.1.2:
2479          *
2480          *   The device MUST initialize device status to 0 upon reset. 
2481          */
2482         memset(pci, 0, sizeof(*pci));
2483
2484         /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2485         pci->vendor_id = 0x1AF4;
2486         /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2487         pci->device_id = 0x1040 + type;
2488
2489         /*
2490          * PCI have specific codes for different types of devices.
2491          * Linux doesn't care, but it's a good clue for people looking
2492          * at the device.
2493          */
2494         pci->class = class;
2495         pci->subclass = subclass;
2496
2497         /*
2498          * 4.1.2.1:
2499          *
2500          *  Non-transitional devices SHOULD have a PCI Revision ID of 1 or
2501          *  higher
2502          */
2503         pci->revid = 1;
2504
2505         /*
2506          * 4.1.2.1:
2507          *
2508          *  Non-transitional devices SHOULD have a PCI Subsystem Device ID of
2509          *  0x40 or higher.
2510          */
2511         pci->subsystem_device_id = 0x40;
2512
2513         /* We use our dummy interrupt controller, and irq_line is the irq */
2514         pci->irq_line = devices.next_irq++;
2515         pci->irq_pin = 0;
2516
2517         /* Support for extended capabilities. */
2518         pci->status = (1 << 4);
2519
2520         /* Link them in. */
2521         /*
2522          * 4.1.4.3.1:
2523          *
2524          *  The device MUST present at least one common configuration
2525          *  capability.
2526          */
2527         pci->capabilities = offsetof(struct pci_config, common);
2528
2529         /* 4.1.4.3.1 ... offset MUST be 4-byte aligned. */
2530         assert(pci->capabilities % 4 == 0);
2531
2532         bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2533         bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2534         init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2535                  bar_offset, bar_len,
2536                  offsetof(struct pci_config, notify));
2537
2538         /*
2539          * 4.1.4.4.1:
2540          *
2541          *  The device MUST present at least one notification capability.
2542          */
2543         bar_offset += bar_len;
2544         bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2545
2546         /*
2547          * 4.1.4.4.1:
2548          *
2549          *  The cap.offset MUST be 2-byte aligned.
2550          */
2551         assert(pci->common.cap_next % 2 == 0);
2552
2553         /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2554         /*
2555          * 4.1.4.4.1:
2556          *
2557          *  The value cap.length presented by the device MUST be at least 2 and
2558          *  MUST be large enough to support queue notification offsets for all
2559          *  supported queues in all possible configurations.
2560          */
2561         assert(bar_len >= 2);
2562
2563         init_cap(&pci->notify.cap, sizeof(pci->notify),
2564                  VIRTIO_PCI_CAP_NOTIFY_CFG,
2565                  bar_offset, bar_len,
2566                  offsetof(struct pci_config, isr));
2567
2568         bar_offset += bar_len;
2569         bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2570         /*
2571          * 4.1.4.5.1:
2572          *
2573          *  The device MUST present at least one VIRTIO_PCI_CAP_ISR_CFG
2574          *  capability.
2575          */
2576         init_cap(&pci->isr, sizeof(pci->isr),
2577                  VIRTIO_PCI_CAP_ISR_CFG,
2578                  bar_offset, bar_len,
2579                  offsetof(struct pci_config, cfg_access));
2580
2581         /*
2582          * 4.1.4.7.1:
2583          *
2584          * The device MUST present at least one VIRTIO_PCI_CAP_PCI_CFG
2585          * capability.
2586          */
2587         /* This doesn't have any presence in the BAR */
2588         init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2589                  VIRTIO_PCI_CAP_PCI_CFG,
2590                  0, 0, 0);
2591
2592         bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2593         assert(bar_offset == sizeof(struct virtio_pci_mmio));
2594
2595         /*
2596          * This gets sewn in and length set in set_device_config().
2597          * Some devices don't have a device configuration interface, so
2598          * we never expose this if we don't call set_device_config().
2599          */
2600         init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2601                  bar_offset, 0, 0);
2602 }
2603
2604 /*
2605  * This routine does all the creation and setup of a new device, but we don't
2606  * actually place the MMIO region until we know the size (if any) of the
2607  * device-specific config.  And we don't actually start the service threads
2608  * until later.
2609  *
2610  * See what I mean about userspace being boring?
2611  */
2612 static struct device *new_pci_device(const char *name, u16 type,
2613                                      u8 class, u8 subclass)
2614 {
2615         struct device *dev = malloc(sizeof(*dev));
2616
2617         /* Now we populate the fields one at a time. */
2618         dev->name = name;
2619         dev->vq = NULL;
2620         dev->running = false;
2621         dev->wrote_features_ok = false;
2622         dev->mmio_size = sizeof(struct virtio_pci_mmio);
2623         dev->mmio = calloc(1, dev->mmio_size);
2624         dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2625         dev->features_accepted = 0;
2626
2627         if (devices.device_num + 1 >= MAX_PCI_DEVICES)
2628                 errx(1, "Can only handle 31 PCI devices");
2629
2630         init_pci_config(&dev->config, type, class, subclass);
2631         assert(!devices.pci[devices.device_num+1]);
2632         devices.pci[++devices.device_num] = dev;
2633
2634         return dev;
2635 }
2636
2637 /*
2638  * Our first setup routine is the console.  It's a fairly simple device, but
2639  * UNIX tty handling makes it uglier than it could be.
2640  */
2641 static void setup_console(void)
2642 {
2643         struct device *dev;
2644         struct virtio_console_config conf;
2645
2646         /* If we can save the initial standard input settings... */
2647         if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2648                 struct termios term = orig_term;
2649                 /*
2650                  * Then we turn off echo, line buffering and ^C etc: We want a
2651                  * raw input stream to the Guest.
2652                  */
2653                 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2654                 tcsetattr(STDIN_FILENO, TCSANOW, &term);
2655         }
2656
2657         dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
2658
2659         /* We store the console state in dev->priv, and initialize it. */
2660         dev->priv = malloc(sizeof(struct console_abort));
2661         ((struct console_abort *)dev->priv)->count = 0;
2662
2663         /*
2664          * The console needs two virtqueues: the input then the output.  When
2665          * they put something the input queue, we make sure we're listening to
2666          * stdin.  When they put something in the output queue, we write it to
2667          * stdout.
2668          */
2669         add_pci_virtqueue(dev, console_input);
2670         add_pci_virtqueue(dev, console_output);
2671
2672         /* We need a configuration area for the emerg_wr early writes. */
2673         add_pci_feature(dev, VIRTIO_CONSOLE_F_EMERG_WRITE);
2674         set_device_config(dev, &conf, sizeof(conf));
2675
2676         verbose("device %u: console\n", devices.device_num);
2677 }
2678 /*:*/
2679
2680 /*M:010
2681  * Inter-guest networking is an interesting area.  Simplest is to have a
2682  * --sharenet=<name> option which opens or creates a named pipe.  This can be
2683  * used to send packets to another guest in a 1:1 manner.
2684  *
2685  * More sophisticated is to use one of the tools developed for project like UML
2686  * to do networking.
2687  *
2688  * Faster is to do virtio bonding in kernel.  Doing this 1:1 would be
2689  * completely generic ("here's my vring, attach to your vring") and would work
2690  * for any traffic.  Of course, namespace and permissions issues need to be
2691  * dealt with.  A more sophisticated "multi-channel" virtio_net.c could hide
2692  * multiple inter-guest channels behind one interface, although it would
2693  * require some manner of hotplugging new virtio channels.
2694  *
2695  * Finally, we could use a virtio network switch in the kernel, ie. vhost.
2696 :*/
2697
2698 static u32 str2ip(const char *ipaddr)
2699 {
2700         unsigned int b[4];
2701
2702         if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2703                 errx(1, "Failed to parse IP address '%s'", ipaddr);
2704         return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2705 }
2706
2707 static void str2mac(const char *macaddr, unsigned char mac[6])
2708 {
2709         unsigned int m[6];
2710         if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2711                    &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2712                 errx(1, "Failed to parse mac address '%s'", macaddr);
2713         mac[0] = m[0];
2714         mac[1] = m[1];
2715         mac[2] = m[2];
2716         mac[3] = m[3];
2717         mac[4] = m[4];
2718         mac[5] = m[5];
2719 }
2720
2721 /*
2722  * This code is "adapted" from libbridge: it attaches the Host end of the
2723  * network device to the bridge device specified by the command line.
2724  *
2725  * This is yet another James Morris contribution (I'm an IP-level guy, so I
2726  * dislike bridging), and I just try not to break it.
2727  */
2728 static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2729 {
2730         int ifidx;
2731         struct ifreq ifr;
2732
2733         if (!*br_name)
2734                 errx(1, "must specify bridge name");
2735
2736         ifidx = if_nametoindex(if_name);
2737         if (!ifidx)
2738                 errx(1, "interface %s does not exist!", if_name);
2739
2740         strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
2741         ifr.ifr_name[IFNAMSIZ-1] = '\0';
2742         ifr.ifr_ifindex = ifidx;
2743         if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2744                 err(1, "can't add %s to bridge %s", if_name, br_name);
2745 }
2746
2747 /*
2748  * This sets up the Host end of the network device with an IP address, brings
2749  * it up so packets will flow, the copies the MAC address into the hwaddr
2750  * pointer.
2751  */
2752 static void configure_device(int fd, const char *tapif, u32 ipaddr)
2753 {
2754         struct ifreq ifr;
2755         struct sockaddr_in sin;
2756
2757         memset(&ifr, 0, sizeof(ifr));
2758         strcpy(ifr.ifr_name, tapif);
2759
2760         /* Don't read these incantations.  Just cut & paste them like I did! */
2761         sin.sin_family = AF_INET;
2762         sin.sin_addr.s_addr = htonl(ipaddr);
2763         memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
2764         if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
2765                 err(1, "Setting %s interface address", tapif);
2766         ifr.ifr_flags = IFF_UP;
2767         if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
2768                 err(1, "Bringing interface %s up", tapif);
2769 }
2770
2771 static int get_tun_device(char tapif[IFNAMSIZ])
2772 {
2773         struct ifreq ifr;
2774         int vnet_hdr_sz;
2775         int netfd;
2776
2777         /* Start with this zeroed.  Messy but sure. */
2778         memset(&ifr, 0, sizeof(ifr));
2779
2780         /*
2781          * We open the /dev/net/tun device and tell it we want a tap device.  A
2782          * tap device is like a tun device, only somehow different.  To tell
2783          * the truth, I completely blundered my way through this code, but it
2784          * works now!
2785          */
2786         netfd = open_or_die("/dev/net/tun", O_RDWR);
2787         ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
2788         strcpy(ifr.ifr_name, "tap%d");
2789         if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2790                 err(1, "configuring /dev/net/tun");
2791
2792         if (ioctl(netfd, TUNSETOFFLOAD,
2793                   TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2794                 err(1, "Could not set features for tun device");
2795
2796         /*
2797          * We don't need checksums calculated for packets coming in this
2798          * device: trust us!
2799          */
2800         ioctl(netfd, TUNSETNOCSUM, 1);
2801
2802         /*
2803          * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2804          * field at the end of the network header iff
2805          * VIRTIO_NET_F_MRG_RXBUF was negotiated.  For virtio 1.0,
2806          * that became the norm, but we need to tell the tun device
2807          * about our expanded header (which is called
2808          * virtio_net_hdr_mrg_rxbuf in the legacy system).
2809          */
2810         vnet_hdr_sz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2811         if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
2812                 err(1, "Setting tun header size to %u", vnet_hdr_sz);
2813
2814         memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2815         return netfd;
2816 }
2817
2818 /*L:195
2819  * Our network is a Host<->Guest network.  This can either use bridging or
2820  * routing, but the principle is the same: it uses the "tun" device to inject
2821  * packets into the Host as if they came in from a normal network card.  We
2822  * just shunt packets between the Guest and the tun device.
2823  */
2824 static void setup_tun_net(char *arg)
2825 {
2826         struct device *dev;
2827         struct net_info *net_info = malloc(sizeof(*net_info));
2828         int ipfd;
2829         u32 ip = INADDR_ANY;
2830         bool bridging = false;
2831         char tapif[IFNAMSIZ], *p;
2832         struct virtio_net_config conf;
2833
2834         net_info->tunfd = get_tun_device(tapif);
2835
2836         /* First we create a new network device. */
2837         dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
2838         dev->priv = net_info;
2839
2840         /* Network devices need a recv and a send queue, just like console. */
2841         add_pci_virtqueue(dev, net_input);
2842         add_pci_virtqueue(dev, net_output);
2843
2844         /*
2845          * We need a socket to perform the magic network ioctls to bring up the
2846          * tap interface, connect to the bridge etc.  Any socket will do!
2847          */
2848         ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2849         if (ipfd < 0)
2850                 err(1, "opening IP socket");
2851
2852         /* If the command line was --tunnet=bridge:<name> do bridging. */
2853         if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
2854                 arg += strlen(BRIDGE_PFX);
2855                 bridging = true;
2856         }
2857
2858         /* A mac address may follow the bridge name or IP address */
2859         p = strchr(arg, ':');
2860         if (p) {
2861                 str2mac(p+1, conf.mac);
2862                 add_pci_feature(dev, VIRTIO_NET_F_MAC);
2863                 *p = '\0';
2864         }
2865
2866         /* arg is now either an IP address or a bridge name */
2867         if (bridging)
2868                 add_to_bridge(ipfd, tapif, arg);
2869         else
2870                 ip = str2ip(arg);
2871
2872         /* Set up the tun device. */
2873         configure_device(ipfd, tapif, ip);
2874
2875         /* Expect Guest to handle everything except UFO */
2876         add_pci_feature(dev, VIRTIO_NET_F_CSUM);
2877         add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2878         add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2879         add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2880         add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2881         add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2882         add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2883         add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
2884         /* We handle indirect ring entries */
2885         add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2886         set_device_config(dev, &conf, sizeof(conf));
2887
2888         /* We don't need the socket any more; setup is done. */
2889         close(ipfd);
2890
2891         if (bridging)
2892                 verbose("device %u: tun %s attached to bridge: %s\n",
2893                         devices.device_num, tapif, arg);
2894         else
2895                 verbose("device %u: tun %s: %s\n",
2896                         devices.device_num, tapif, arg);
2897 }
2898 /*:*/
2899
2900 /* This hangs off device->priv. */
2901 struct vblk_info {
2902         /* The size of the file. */
2903         off64_t len;
2904
2905         /* The file descriptor for the file. */
2906         int fd;
2907
2908 };
2909
2910 /*L:210
2911  * The Disk
2912  *
2913  * The disk only has one virtqueue, so it only has one thread.  It is really
2914  * simple: the Guest asks for a block number and we read or write that position
2915  * in the file.
2916  *
2917  * Before we serviced each virtqueue in a separate thread, that was unacceptably
2918  * slow: the Guest waits until the read is finished before running anything
2919  * else, even if it could have been doing useful work.
2920  *
2921  * We could have used async I/O, except it's reputed to suck so hard that
2922  * characters actually go missing from your code when you try to use it.
2923  */
2924 static void blk_request(struct virtqueue *vq)
2925 {
2926         struct vblk_info *vblk = vq->dev->priv;
2927         unsigned int head, out_num, in_num, wlen;
2928         int ret, i;
2929         u8 *in;
2930         struct virtio_blk_outhdr out;
2931         struct iovec iov[vq->vring.num];
2932         off64_t off;
2933
2934         /*
2935          * Get the next request, where we normally wait.  It triggers the
2936          * interrupt to acknowledge previously serviced requests (if any).
2937          */
2938         head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
2939
2940         /* Copy the output header from the front of the iov (adjusts iov) */
2941         iov_consume(iov, out_num, &out, sizeof(out));
2942
2943         /* Find and trim end of iov input array, for our status byte. */
2944         in = NULL;
2945         for (i = out_num + in_num - 1; i >= out_num; i--) {
2946                 if (iov[i].iov_len > 0) {
2947                         in = iov[i].iov_base + iov[i].iov_len - 1;
2948                         iov[i].iov_len--;
2949                         break;
2950                 }
2951         }
2952         if (!in)
2953                 errx(1, "Bad virtblk cmd with no room for status");
2954
2955         /*
2956          * For historical reasons, block operations are expressed in 512 byte
2957          * "sectors".
2958          */
2959         off = out.sector * 512;
2960
2961         if (out.type & VIRTIO_BLK_T_OUT) {
2962                 /*
2963                  * Write
2964                  *
2965                  * Move to the right location in the block file.  This can fail
2966                  * if they try to write past end.
2967                  */
2968                 if (lseek64(vblk->fd, off, SEEK_SET) != off)
2969                         err(1, "Bad seek to sector %llu", out.sector);
2970
2971                 ret = writev(vblk->fd, iov, out_num);
2972                 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
2973
2974                 /*
2975                  * Grr... Now we know how long the descriptor they sent was, we
2976                  * make sure they didn't try to write over the end of the block
2977                  * file (possibly extending it).
2978                  */
2979                 if (ret > 0 && off + ret > vblk->len) {
2980                         /* Trim it back to the correct length */
2981                         ftruncate64(vblk->fd, vblk->len);
2982                         /* Die, bad Guest, die. */
2983                         errx(1, "Write past end %llu+%u", off, ret);
2984                 }
2985
2986                 wlen = sizeof(*in);
2987                 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
2988         } else if (out.type & VIRTIO_BLK_T_FLUSH) {
2989                 /* Flush */
2990                 ret = fdatasync(vblk->fd);
2991                 verbose("FLUSH fdatasync: %i\n", ret);
2992                 wlen = sizeof(*in);
2993                 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
2994         } else {
2995                 /*
2996                  * Read
2997                  *
2998                  * Move to the right location in the block file.  This can fail
2999                  * if they try to read past end.
3000                  */
3001                 if (lseek64(vblk->fd, off, SEEK_SET) != off)
3002                         err(1, "Bad seek to sector %llu", out.sector);
3003
3004                 ret = readv(vblk->fd, iov + out_num, in_num);
3005                 if (ret >= 0) {
3006                         wlen = sizeof(*in) + ret;
3007                         *in = VIRTIO_BLK_S_OK;
3008                 } else {
3009                         wlen = sizeof(*in);
3010                         *in = VIRTIO_BLK_S_IOERR;
3011                 }
3012         }
3013
3014         /* Finished that request. */
3015         add_used(vq, head, wlen);
3016 }
3017
3018 /*L:198 This actually sets up a virtual block device. */
3019 static void setup_block_file(const char *filename)
3020 {
3021         struct device *dev;
3022         struct vblk_info *vblk;
3023         struct virtio_blk_config conf;
3024
3025         /* Create the device. */
3026         dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
3027
3028         /* The device has one virtqueue, where the Guest places requests. */
3029         add_pci_virtqueue(dev, blk_request);
3030
3031         /* Allocate the room for our own bookkeeping */
3032         vblk = dev->priv = malloc(sizeof(*vblk));
3033
3034         /* First we open the file and store the length. */
3035         vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
3036         vblk->len = lseek64(vblk->fd, 0, SEEK_END);
3037
3038         /* Tell Guest how many sectors this device has. */
3039         conf.capacity = cpu_to_le64(vblk->len / 512);
3040
3041         /*
3042          * Tell Guest not to put in too many descriptors at once: two are used
3043          * for the in and out elements.
3044          */
3045         add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
3046         conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
3047
3048         set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
3049
3050         verbose("device %u: virtblock %llu sectors\n",
3051                 devices.device_num, le64_to_cpu(conf.capacity));
3052 }
3053
3054 /*L:211
3055  * Our random number generator device reads from /dev/urandom into the Guest's
3056  * input buffers.  The usual case is that the Guest doesn't want random numbers
3057  * and so has no buffers although /dev/urandom is still readable, whereas
3058  * console is the reverse.
3059  *
3060  * The same logic applies, however.
3061  */
3062 struct rng_info {
3063         int rfd;
3064 };
3065
3066 static void rng_input(struct virtqueue *vq)
3067 {
3068         int len;
3069         unsigned int head, in_num, out_num, totlen = 0;
3070         struct rng_info *rng_info = vq->dev->priv;
3071         struct iovec iov[vq->vring.num];
3072
3073         /* First we need a buffer from the Guests's virtqueue. */
3074         head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
3075         if (out_num)
3076                 errx(1, "Output buffers in rng?");
3077
3078         /*
3079          * Just like the console write, we loop to cover the whole iovec.
3080          * In this case, short reads actually happen quite a bit.
3081          */
3082         while (!iov_empty(iov, in_num)) {
3083                 len = readv(rng_info->rfd, iov, in_num);
3084                 if (len <= 0)
3085                         err(1, "Read from /dev/urandom gave %i", len);
3086                 iov_consume(iov, in_num, NULL, len);
3087                 totlen += len;
3088         }
3089
3090         /* Tell the Guest about the new input. */
3091         add_used(vq, head, totlen);
3092 }
3093
3094 /*L:199
3095  * This creates a "hardware" random number device for the Guest.
3096  */
3097 static void setup_rng(void)
3098 {
3099         struct device *dev;
3100         struct rng_info *rng_info = malloc(sizeof(*rng_info));
3101
3102         /* Our device's private info simply contains the /dev/urandom fd. */
3103         rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
3104
3105         /* Create the new device. */
3106         dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
3107         dev->priv = rng_info;
3108
3109         /* The device has one virtqueue, where the Guest places inbufs. */
3110         add_pci_virtqueue(dev, rng_input);
3111
3112         /* We don't have any configuration space */
3113         no_device_config(dev);
3114
3115         verbose("device %u: rng\n", devices.device_num);
3116 }
3117 /* That's the end of device setup. */
3118
3119 /*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
3120 static void __attribute__((noreturn)) restart_guest(void)
3121 {
3122         unsigned int i;
3123
3124         /*
3125          * Since we don't track all open fds, we simply close everything beyond
3126          * stderr.
3127          */
3128         for (i = 3; i < FD_SETSIZE; i++)
3129                 close(i);
3130
3131         /* Reset all the devices (kills all threads). */
3132         cleanup_devices();
3133
3134         execv(main_args[0], main_args);
3135         err(1, "Could not exec %s", main_args[0]);
3136 }
3137
3138 /*L:220
3139  * Finally we reach the core of the Launcher which runs the Guest, serves
3140  * its input and output, and finally, lays it to rest.
3141  */
3142 static void __attribute__((noreturn)) run_guest(void)
3143 {
3144         for (;;) {
3145                 struct lguest_pending notify;
3146                 int readval;
3147
3148                 /* We read from the /dev/lguest device to run the Guest. */
3149                 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
3150                 if (readval == sizeof(notify)) {
3151                         if (notify.trap == 13) {
3152                                 verbose("Emulating instruction at %#x\n",
3153                                         getreg(eip));
3154                                 emulate_insn(notify.insn);
3155                         } else if (notify.trap == 14) {
3156                                 verbose("Emulating MMIO at %#x\n",
3157                                         getreg(eip));
3158                                 emulate_mmio(notify.addr, notify.insn);
3159                         } else
3160                                 errx(1, "Unknown trap %i addr %#08x\n",
3161                                      notify.trap, notify.addr);
3162                 /* ENOENT means the Guest died.  Reading tells us why. */
3163                 } else if (errno == ENOENT) {
3164                         char reason[1024] = { 0 };
3165                         pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
3166                         errx(1, "%s", reason);
3167                 /* ERESTART means that we need to reboot the guest */
3168                 } else if (errno == ERESTART) {
3169                         restart_guest();
3170                 /* Anything else means a bug or incompatible change. */
3171                 } else
3172                         err(1, "Running guest failed");
3173         }
3174 }
3175 /*L:240
3176  * This is the end of the Launcher.  The good news: we are over halfway
3177  * through!  The bad news: the most fiendish part of the code still lies ahead
3178  * of us.
3179  *
3180  * Are you ready?  Take a deep breath and join me in the core of the Host, in
3181  * "make Host".
3182 :*/
3183
3184 static struct option opts[] = {
3185         { "verbose", 0, NULL, 'v' },
3186         { "tunnet", 1, NULL, 't' },
3187         { "block", 1, NULL, 'b' },
3188         { "rng", 0, NULL, 'r' },
3189         { "initrd", 1, NULL, 'i' },
3190         { "username", 1, NULL, 'u' },
3191         { "chroot", 1, NULL, 'c' },
3192         { NULL },
3193 };
3194 static void usage(void)
3195 {
3196         errx(1, "Usage: lguest [--verbose] "
3197              "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
3198              "|--block=<filename>|--initrd=<filename>]...\n"
3199              "<mem-in-mb> vmlinux [args...]");
3200 }
3201
3202 /*L:105 The main routine is where the real work begins: */
3203 int main(int argc, char *argv[])
3204 {
3205         /* Memory, code startpoint and size of the (optional) initrd. */
3206         unsigned long mem = 0, start, initrd_size = 0;
3207         /* Two temporaries. */
3208         int i, c;
3209         /* The boot information for the Guest. */
3210         struct boot_params *boot;
3211         /* If they specify an initrd file to load. */
3212         const char *initrd_name = NULL;
3213
3214         /* Password structure for initgroups/setres[gu]id */
3215         struct passwd *user_details = NULL;
3216
3217         /* Directory to chroot to */
3218         char *chroot_path = NULL;
3219
3220         /* Save the args: we "reboot" by execing ourselves again. */
3221         main_args = argv;
3222
3223         /*
3224          * First we initialize the device list.  We remember next interrupt
3225          * number to use for devices (1: remember that 0 is used by the timer).
3226          */
3227         devices.next_irq = 1;
3228
3229         /* We're CPU 0.  In fact, that's the only CPU possible right now. */
3230         cpu_id = 0;
3231
3232         /*
3233          * We need to know how much memory so we can set up the device
3234          * descriptor and memory pages for the devices as we parse the command
3235          * line.  So we quickly look through the arguments to find the amount
3236          * of memory now.
3237          */
3238         for (i = 1; i < argc; i++) {
3239                 if (argv[i][0] != '-') {
3240                         mem = atoi(argv[i]) * 1024 * 1024;
3241                         /*
3242                          * We start by mapping anonymous pages over all of
3243                          * guest-physical memory range.  This fills it with 0,
3244                          * and ensures that the Guest won't be killed when it
3245                          * tries to access it.
3246                          */
3247                         guest_base = map_zeroed_pages(mem / getpagesize()
3248                                                       + DEVICE_PAGES);
3249                         guest_limit = mem;
3250                         guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
3251                         break;
3252                 }
3253         }
3254
3255         /* We always have a console device, and it's always device 1. */
3256         setup_console();
3257
3258         /* The options are fairly straight-forward */
3259         while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
3260                 switch (c) {
3261                 case 'v':
3262                         verbose = true;
3263                         break;
3264                 case 't':
3265                         setup_tun_net(optarg);
3266                         break;
3267                 case 'b':
3268                         setup_block_file(optarg);
3269                         break;
3270                 case 'r':
3271                         setup_rng();
3272                         break;
3273                 case 'i':
3274                         initrd_name = optarg;
3275                         break;
3276                 case 'u':
3277                         user_details = getpwnam(optarg);
3278                         if (!user_details)
3279                                 err(1, "getpwnam failed, incorrect username?");
3280                         break;
3281                 case 'c':
3282                         chroot_path = optarg;
3283                         break;
3284                 default:
3285                         warnx("Unknown argument %s", argv[optind]);
3286                         usage();
3287                 }
3288         }
3289         /*
3290          * After the other arguments we expect memory and kernel image name,
3291          * followed by command line arguments for the kernel.
3292          */
3293         if (optind + 2 > argc)
3294                 usage();
3295
3296         verbose("Guest base is at %p\n", guest_base);
3297
3298         /* Initialize the (fake) PCI host bridge device. */
3299         init_pci_host_bridge();
3300
3301         /* Now we load the kernel */
3302         start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
3303
3304         /* Boot information is stashed at physical address 0 */
3305         boot = from_guest_phys(0);
3306
3307         /* Map the initrd image if requested (at top of physical memory) */
3308         if (initrd_name) {
3309                 initrd_size = load_initrd(initrd_name, mem);
3310                 /*
3311                  * These are the location in the Linux boot header where the
3312                  * start and size of the initrd are expected to be found.
3313                  */
3314                 boot->hdr.ramdisk_image = mem - initrd_size;
3315                 boot->hdr.ramdisk_size = initrd_size;
3316                 /* The bootloader type 0xFF means "unknown"; that's OK. */
3317                 boot->hdr.type_of_loader = 0xFF;
3318         }
3319
3320         /*
3321          * The Linux boot header contains an "E820" memory map: ours is a
3322          * simple, single region.
3323          */
3324         boot->e820_entries = 1;
3325         boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
3326         /*
3327          * The boot header contains a command line pointer: we put the command
3328          * line after the boot header.
3329          */
3330         boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
3331         /* We use a simple helper to copy the arguments separated by spaces. */
3332         concat((char *)(boot + 1), argv+optind+2);
3333
3334         /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3335         boot->hdr.kernel_alignment = 0x1000000;
3336
3337         /* Boot protocol version: 2.07 supports the fields for lguest. */
3338         boot->hdr.version = 0x207;
3339
3340         /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
3341         boot->hdr.hardware_subarch = 1;
3342
3343         /* Tell the entry path not to try to reload segment registers. */
3344         boot->hdr.loadflags |= KEEP_SEGMENTS;
3345
3346         /* We tell the kernel to initialize the Guest. */
3347         tell_kernel(start);
3348
3349         /* Ensure that we terminate if a device-servicing child dies. */
3350         signal(SIGCHLD, kill_launcher);
3351
3352         /* If we exit via err(), this kills all the threads, restores tty. */
3353         atexit(cleanup_devices);
3354
3355         /* If requested, chroot to a directory */
3356         if (chroot_path) {
3357                 if (chroot(chroot_path) != 0)
3358                         err(1, "chroot(\"%s\") failed", chroot_path);
3359
3360                 if (chdir("/") != 0)
3361                         err(1, "chdir(\"/\") failed");
3362
3363                 verbose("chroot done\n");
3364         }
3365
3366         /* If requested, drop privileges */
3367         if (user_details) {
3368                 uid_t u;
3369                 gid_t g;
3370
3371                 u = user_details->pw_uid;
3372                 g = user_details->pw_gid;
3373
3374                 if (initgroups(user_details->pw_name, g) != 0)
3375                         err(1, "initgroups failed");
3376
3377                 if (setresgid(g, g, g) != 0)
3378                         err(1, "setresgid failed");
3379
3380                 if (setresuid(u, u, u) != 0)
3381                         err(1, "setresuid failed");
3382
3383                 verbose("Dropping privileges completed\n");
3384         }
3385
3386         /* Finally, run the Guest.  This doesn't return. */
3387         run_guest();
3388 }
3389 /*:*/
3390
3391 /*M:999
3392  * Mastery is done: you now know everything I do.
3393  *
3394  * But surely you have seen code, features and bugs in your wanderings which
3395  * you now yearn to attack?  That is the real game, and I look forward to you
3396  * patching and forking lguest into the Your-Name-Here-visor.
3397  *
3398  * Farewell, and good coding!
3399  * Rusty Russell.
3400  */