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