lguest: cleanup passing of /dev/lguest fd around example launcher.
[safe/jmp/linux-2.6] / Documentation / lguest / lguest.c
1 /*P:100 This is the Launcher code, a simple program which lays out the
2  * "physical" memory for the new Guest by mapping the kernel image and
3  * the virtual devices, then opens /dev/lguest to tell the kernel
4  * about the Guest and control it. :*/
5 #define _LARGEFILE64_SOURCE
6 #define _GNU_SOURCE
7 #include <stdio.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <err.h>
11 #include <stdint.h>
12 #include <stdlib.h>
13 #include <elf.h>
14 #include <sys/mman.h>
15 #include <sys/param.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/wait.h>
19 #include <fcntl.h>
20 #include <stdbool.h>
21 #include <errno.h>
22 #include <ctype.h>
23 #include <sys/socket.h>
24 #include <sys/ioctl.h>
25 #include <sys/time.h>
26 #include <time.h>
27 #include <netinet/in.h>
28 #include <net/if.h>
29 #include <linux/sockios.h>
30 #include <linux/if_tun.h>
31 #include <sys/uio.h>
32 #include <termios.h>
33 #include <getopt.h>
34 #include <zlib.h>
35 #include <assert.h>
36 #include <sched.h>
37 #include <limits.h>
38 #include <stddef.h>
39 #include <signal.h>
40 #include "linux/lguest_launcher.h"
41 #include "linux/virtio_config.h"
42 #include "linux/virtio_net.h"
43 #include "linux/virtio_blk.h"
44 #include "linux/virtio_console.h"
45 #include "linux/virtio_rng.h"
46 #include "linux/virtio_ring.h"
47 #include "asm/bootparam.h"
48 /*L:110 We can ignore the 39 include files we need for this program, but I do
49  * want to draw attention to the use of kernel-style types.
50  *
51  * As Linus said, "C is a Spartan language, and so should your naming be."  I
52  * like these abbreviations, so we define them here.  Note that u64 is always
53  * unsigned long long, which works on all Linux systems: this means that we can
54  * use %llu in printf for any u64. */
55 typedef unsigned long long u64;
56 typedef uint32_t u32;
57 typedef uint16_t u16;
58 typedef uint8_t u8;
59 /*:*/
60
61 #define PAGE_PRESENT 0x7        /* Present, RW, Execute */
62 #define NET_PEERNUM 1
63 #define BRIDGE_PFX "bridge:"
64 #ifndef SIOCBRADDIF
65 #define SIOCBRADDIF     0x89a2          /* add interface to bridge      */
66 #endif
67 /* We can have up to 256 pages for devices. */
68 #define DEVICE_PAGES 256
69 /* This will occupy 3 pages: it must be a power of 2. */
70 #define VIRTQUEUE_NUM 256
71
72 /*L:120 verbose is both a global flag and a macro.  The C preprocessor allows
73  * this, and although I wouldn't recommend it, it works quite nicely here. */
74 static bool verbose;
75 #define verbose(args...) \
76         do { if (verbose) printf(args); } while(0)
77 /*:*/
78
79 /* File descriptors for the Waker. */
80 struct {
81         int pipe[2];
82 } waker_fds;
83
84 /* The pointer to the start of guest memory. */
85 static void *guest_base;
86 /* The maximum guest physical address allowed, and maximum possible. */
87 static unsigned long guest_limit, guest_max;
88 /* The pipe for signal hander to write to. */
89 static int timeoutpipe[2];
90 static unsigned int timeout_usec = 500;
91 /* The /dev/lguest file descriptor. */
92 static int lguest_fd;
93
94 /* a per-cpu variable indicating whose vcpu is currently running */
95 static unsigned int __thread cpu_id;
96
97 /* This is our list of devices. */
98 struct device_list
99 {
100         /* Summary information about the devices in our list: ready to pass to
101          * select() to ask which need servicing.*/
102         fd_set infds;
103         int max_infd;
104
105         /* Counter to assign interrupt numbers. */
106         unsigned int next_irq;
107
108         /* Counter to print out convenient device numbers. */
109         unsigned int device_num;
110
111         /* The descriptor page for the devices. */
112         u8 *descpage;
113
114         /* A single linked list of devices. */
115         struct device *dev;
116         /* And a pointer to the last device for easy append and also for
117          * configuration appending. */
118         struct device *lastdev;
119 };
120
121 /* The list of Guest devices, based on command line arguments. */
122 static struct device_list devices;
123
124 /* The device structure describes a single device. */
125 struct device
126 {
127         /* The linked-list pointer. */
128         struct device *next;
129
130         /* The device's descriptor, as mapped into the Guest. */
131         struct lguest_device_desc *desc;
132
133         /* We can't trust desc values once Guest has booted: we use these. */
134         unsigned int feature_len;
135         unsigned int num_vq;
136
137         /* The name of this device, for --verbose. */
138         const char *name;
139
140         /* If handle_input is set, it wants to be called when this file
141          * descriptor is ready. */
142         int fd;
143         bool (*handle_input)(struct device *me);
144
145         /* Any queues attached to this device */
146         struct virtqueue *vq;
147
148         /* Handle status being finalized (ie. feature bits stable). */
149         void (*ready)(struct device *me);
150
151         /* Device-specific data. */
152         void *priv;
153 };
154
155 /* The virtqueue structure describes a queue attached to a device. */
156 struct virtqueue
157 {
158         struct virtqueue *next;
159
160         /* Which device owns me. */
161         struct device *dev;
162
163         /* The configuration for this queue. */
164         struct lguest_vqconfig config;
165
166         /* The actual ring of buffers. */
167         struct vring vring;
168
169         /* Last available index we saw. */
170         u16 last_avail_idx;
171
172         /* The routine to call when the Guest pings us, or timeout. */
173         void (*handle_output)(struct virtqueue *me, bool timeout);
174
175         /* Outstanding buffers */
176         unsigned int inflight;
177
178         /* Is this blocked awaiting a timer? */
179         bool blocked;
180 };
181
182 /* Remember the arguments to the program so we can "reboot" */
183 static char **main_args;
184
185 /* Since guest is UP and we don't run at the same time, we don't need barriers.
186  * But I include them in the code in case others copy it. */
187 #define wmb()
188
189 /* Convert an iovec element to the given type.
190  *
191  * This is a fairly ugly trick: we need to know the size of the type and
192  * alignment requirement to check the pointer is kosher.  It's also nice to
193  * have the name of the type in case we report failure.
194  *
195  * Typing those three things all the time is cumbersome and error prone, so we
196  * have a macro which sets them all up and passes to the real function. */
197 #define convert(iov, type) \
198         ((type *)_convert((iov), sizeof(type), __alignof__(type), #type))
199
200 static void *_convert(struct iovec *iov, size_t size, size_t align,
201                       const char *name)
202 {
203         if (iov->iov_len != size)
204                 errx(1, "Bad iovec size %zu for %s", iov->iov_len, name);
205         if ((unsigned long)iov->iov_base % align != 0)
206                 errx(1, "Bad alignment %p for %s", iov->iov_base, name);
207         return iov->iov_base;
208 }
209
210 /* Wrapper for the last available index.  Makes it easier to change. */
211 #define lg_last_avail(vq)       ((vq)->last_avail_idx)
212
213 /* The virtio configuration space is defined to be little-endian.  x86 is
214  * little-endian too, but it's nice to be explicit so we have these helpers. */
215 #define cpu_to_le16(v16) (v16)
216 #define cpu_to_le32(v32) (v32)
217 #define cpu_to_le64(v64) (v64)
218 #define le16_to_cpu(v16) (v16)
219 #define le32_to_cpu(v32) (v32)
220 #define le64_to_cpu(v64) (v64)
221
222 /* Is this iovec empty? */
223 static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
224 {
225         unsigned int i;
226
227         for (i = 0; i < num_iov; i++)
228                 if (iov[i].iov_len)
229                         return false;
230         return true;
231 }
232
233 /* Take len bytes from the front of this iovec. */
234 static void iov_consume(struct iovec iov[], unsigned num_iov, unsigned len)
235 {
236         unsigned int i;
237
238         for (i = 0; i < num_iov; i++) {
239                 unsigned int used;
240
241                 used = iov[i].iov_len < len ? iov[i].iov_len : len;
242                 iov[i].iov_base += used;
243                 iov[i].iov_len -= used;
244                 len -= used;
245         }
246         assert(len == 0);
247 }
248
249 /* The device virtqueue descriptors are followed by feature bitmasks. */
250 static u8 *get_feature_bits(struct device *dev)
251 {
252         return (u8 *)(dev->desc + 1)
253                 + dev->num_vq * sizeof(struct lguest_vqconfig);
254 }
255
256 /*L:100 The Launcher code itself takes us out into userspace, that scary place
257  * where pointers run wild and free!  Unfortunately, like most userspace
258  * programs, it's quite boring (which is why everyone likes to hack on the
259  * kernel!).  Perhaps if you make up an Lguest Drinking Game at this point, it
260  * will get you through this section.  Or, maybe not.
261  *
262  * The Launcher sets up a big chunk of memory to be the Guest's "physical"
263  * memory and stores it in "guest_base".  In other words, Guest physical ==
264  * Launcher virtual with an offset.
265  *
266  * This can be tough to get your head around, but usually it just means that we
267  * use these trivial conversion functions when the Guest gives us it's
268  * "physical" addresses: */
269 static void *from_guest_phys(unsigned long addr)
270 {
271         return guest_base + addr;
272 }
273
274 static unsigned long to_guest_phys(const void *addr)
275 {
276         return (addr - guest_base);
277 }
278
279 /*L:130
280  * Loading the Kernel.
281  *
282  * We start with couple of simple helper routines.  open_or_die() avoids
283  * error-checking code cluttering the callers: */
284 static int open_or_die(const char *name, int flags)
285 {
286         int fd = open(name, flags);
287         if (fd < 0)
288                 err(1, "Failed to open %s", name);
289         return fd;
290 }
291
292 /* map_zeroed_pages() takes a number of pages. */
293 static void *map_zeroed_pages(unsigned int num)
294 {
295         int fd = open_or_die("/dev/zero", O_RDONLY);
296         void *addr;
297
298         /* We use a private mapping (ie. if we write to the page, it will be
299          * copied). */
300         addr = mmap(NULL, getpagesize() * num,
301                     PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE, fd, 0);
302         if (addr == MAP_FAILED)
303                 err(1, "Mmaping %u pages of /dev/zero", num);
304         close(fd);
305
306         return addr;
307 }
308
309 /* Get some more pages for a device. */
310 static void *get_pages(unsigned int num)
311 {
312         void *addr = from_guest_phys(guest_limit);
313
314         guest_limit += num * getpagesize();
315         if (guest_limit > guest_max)
316                 errx(1, "Not enough memory for devices");
317         return addr;
318 }
319
320 /* This routine is used to load the kernel or initrd.  It tries mmap, but if
321  * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
322  * it falls back to reading the memory in. */
323 static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
324 {
325         ssize_t r;
326
327         /* We map writable even though for some segments are marked read-only.
328          * The kernel really wants to be writable: it patches its own
329          * instructions.
330          *
331          * MAP_PRIVATE means that the page won't be copied until a write is
332          * done to it.  This allows us to share untouched memory between
333          * Guests. */
334         if (mmap(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC,
335                  MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
336                 return;
337
338         /* pread does a seek and a read in one shot: saves a few lines. */
339         r = pread(fd, addr, len, offset);
340         if (r != len)
341                 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
342 }
343
344 /* This routine takes an open vmlinux image, which is in ELF, and maps it into
345  * the Guest memory.  ELF = Embedded Linking Format, which is the format used
346  * by all modern binaries on Linux including the kernel.
347  *
348  * The ELF headers give *two* addresses: a physical address, and a virtual
349  * address.  We use the physical address; the Guest will map itself to the
350  * virtual address.
351  *
352  * We return the starting address. */
353 static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
354 {
355         Elf32_Phdr phdr[ehdr->e_phnum];
356         unsigned int i;
357
358         /* Sanity checks on the main ELF header: an x86 executable with a
359          * reasonable number of correctly-sized program headers. */
360         if (ehdr->e_type != ET_EXEC
361             || ehdr->e_machine != EM_386
362             || ehdr->e_phentsize != sizeof(Elf32_Phdr)
363             || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
364                 errx(1, "Malformed elf header");
365
366         /* An ELF executable contains an ELF header and a number of "program"
367          * headers which indicate which parts ("segments") of the program to
368          * load where. */
369
370         /* We read in all the program headers at once: */
371         if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
372                 err(1, "Seeking to program headers");
373         if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
374                 err(1, "Reading program headers");
375
376         /* Try all the headers: there are usually only three.  A read-only one,
377          * a read-write one, and a "note" section which we don't load. */
378         for (i = 0; i < ehdr->e_phnum; i++) {
379                 /* If this isn't a loadable segment, we ignore it */
380                 if (phdr[i].p_type != PT_LOAD)
381                         continue;
382
383                 verbose("Section %i: size %i addr %p\n",
384                         i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
385
386                 /* We map this section of the file at its physical address. */
387                 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
388                        phdr[i].p_offset, phdr[i].p_filesz);
389         }
390
391         /* The entry point is given in the ELF header. */
392         return ehdr->e_entry;
393 }
394
395 /*L:150 A bzImage, unlike an ELF file, is not meant to be loaded.  You're
396  * supposed to jump into it and it will unpack itself.  We used to have to
397  * perform some hairy magic because the unpacking code scared me.
398  *
399  * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
400  * a small patch to jump over the tricky bits in the Guest, so now we just read
401  * the funky header so we know where in the file to load, and away we go! */
402 static unsigned long load_bzimage(int fd)
403 {
404         struct boot_params boot;
405         int r;
406         /* Modern bzImages get loaded at 1M. */
407         void *p = from_guest_phys(0x100000);
408
409         /* Go back to the start of the file and read the header.  It should be
410          * a Linux boot header (see Documentation/x86/i386/boot.txt) */
411         lseek(fd, 0, SEEK_SET);
412         read(fd, &boot, sizeof(boot));
413
414         /* Inside the setup_hdr, we expect the magic "HdrS" */
415         if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
416                 errx(1, "This doesn't look like a bzImage to me");
417
418         /* Skip over the extra sectors of the header. */
419         lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
420
421         /* Now read everything into memory. in nice big chunks. */
422         while ((r = read(fd, p, 65536)) > 0)
423                 p += r;
424
425         /* Finally, code32_start tells us where to enter the kernel. */
426         return boot.hdr.code32_start;
427 }
428
429 /*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels
430  * come wrapped up in the self-decompressing "bzImage" format.  With a little
431  * work, we can load those, too. */
432 static unsigned long load_kernel(int fd)
433 {
434         Elf32_Ehdr hdr;
435
436         /* Read in the first few bytes. */
437         if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
438                 err(1, "Reading kernel");
439
440         /* If it's an ELF file, it starts with "\177ELF" */
441         if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
442                 return map_elf(fd, &hdr);
443
444         /* Otherwise we assume it's a bzImage, and try to load it. */
445         return load_bzimage(fd);
446 }
447
448 /* This is a trivial little helper to align pages.  Andi Kleen hated it because
449  * it calls getpagesize() twice: "it's dumb code."
450  *
451  * Kernel guys get really het up about optimization, even when it's not
452  * necessary.  I leave this code as a reaction against that. */
453 static inline unsigned long page_align(unsigned long addr)
454 {
455         /* Add upwards and truncate downwards. */
456         return ((addr + getpagesize()-1) & ~(getpagesize()-1));
457 }
458
459 /*L:180 An "initial ram disk" is a disk image loaded into memory along with
460  * the kernel which the kernel can use to boot from without needing any
461  * drivers.  Most distributions now use this as standard: the initrd contains
462  * the code to load the appropriate driver modules for the current machine.
463  *
464  * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
465  * kernels.  He sent me this (and tells me when I break it). */
466 static unsigned long load_initrd(const char *name, unsigned long mem)
467 {
468         int ifd;
469         struct stat st;
470         unsigned long len;
471
472         ifd = open_or_die(name, O_RDONLY);
473         /* fstat() is needed to get the file size. */
474         if (fstat(ifd, &st) < 0)
475                 err(1, "fstat() on initrd '%s'", name);
476
477         /* We map the initrd at the top of memory, but mmap wants it to be
478          * page-aligned, so we round the size up for that. */
479         len = page_align(st.st_size);
480         map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
481         /* Once a file is mapped, you can close the file descriptor.  It's a
482          * little odd, but quite useful. */
483         close(ifd);
484         verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
485
486         /* We return the initrd size. */
487         return len;
488 }
489 /*:*/
490
491 /* Simple routine to roll all the commandline arguments together with spaces
492  * between them. */
493 static void concat(char *dst, char *args[])
494 {
495         unsigned int i, len = 0;
496
497         for (i = 0; args[i]; i++) {
498                 if (i) {
499                         strcat(dst+len, " ");
500                         len++;
501                 }
502                 strcpy(dst+len, args[i]);
503                 len += strlen(args[i]);
504         }
505         /* In case it's empty. */
506         dst[len] = '\0';
507 }
508
509 /*L:185 This is where we actually tell the kernel to initialize the Guest.  We
510  * saw the arguments it expects when we looked at initialize() in lguest_user.c:
511  * the base of Guest "physical" memory, the top physical page to allow and the
512  * entry point for the Guest. */
513 static void tell_kernel(unsigned long start)
514 {
515         unsigned long args[] = { LHREQ_INITIALIZE,
516                                  (unsigned long)guest_base,
517                                  guest_limit / getpagesize(), start };
518         verbose("Guest: %p - %p (%#lx)\n",
519                 guest_base, guest_base + guest_limit, guest_limit);
520         lguest_fd = open_or_die("/dev/lguest", O_RDWR);
521         if (write(lguest_fd, args, sizeof(args)) < 0)
522                 err(1, "Writing to /dev/lguest");
523 }
524 /*:*/
525
526 static void add_device_fd(int fd)
527 {
528         FD_SET(fd, &devices.infds);
529         if (fd > devices.max_infd)
530                 devices.max_infd = fd;
531 }
532
533 /*L:200
534  * The Waker.
535  *
536  * With console, block and network devices, we can have lots of input which we
537  * need to process.  We could try to tell the kernel what file descriptors to
538  * watch, but handing a file descriptor mask through to the kernel is fairly
539  * icky.
540  *
541  * Instead, we clone off a thread which watches the file descriptors and writes
542  * the LHREQ_BREAK command to the /dev/lguest file descriptor to tell the Host
543  * stop running the Guest.  This causes the Launcher to return from the
544  * /dev/lguest read with -EAGAIN, where it will write to /dev/lguest to reset
545  * the LHREQ_BREAK and wake us up again.
546  *
547  * This, of course, is merely a different *kind* of icky.
548  *
549  * Given my well-known antipathy to threads, I'd prefer to use processes.  But
550  * it's easier to share Guest memory with threads, and trivial to share the
551  * devices.infds as the Launcher changes it.
552  */
553 static int waker(void *unused)
554 {
555         /* Close the write end of the pipe: only the Launcher has it open. */
556         close(waker_fds.pipe[1]);
557
558         for (;;) {
559                 fd_set rfds = devices.infds;
560                 unsigned long args[] = { LHREQ_BREAK, 1 };
561                 unsigned int maxfd = devices.max_infd;
562
563                 /* We also listen to the pipe from the Launcher. */
564                 FD_SET(waker_fds.pipe[0], &rfds);
565                 if (waker_fds.pipe[0] > maxfd)
566                         maxfd = waker_fds.pipe[0];
567
568                 /* Wait until input is ready from one of the devices. */
569                 select(maxfd+1, &rfds, NULL, NULL, NULL);
570
571                 /* Message from Launcher? */
572                 if (FD_ISSET(waker_fds.pipe[0], &rfds)) {
573                         char c;
574                         /* If this fails, then assume Launcher has exited.
575                          * Don't do anything on exit: we're just a thread! */
576                         if (read(waker_fds.pipe[0], &c, 1) != 1)
577                                 _exit(0);
578                         continue;
579                 }
580
581                 /* Send LHREQ_BREAK command to snap the Launcher out of it. */
582                 pwrite(lguest_fd, args, sizeof(args), cpu_id);
583         }
584         return 0;
585 }
586
587 /* This routine just sets up a pipe to the Waker process. */
588 static void setup_waker(void)
589 {
590         /* This pipe is closed when Launcher dies, telling Waker. */
591         if (pipe(waker_fds.pipe) != 0)
592                 err(1, "Creating pipe for Waker");
593
594         if (clone(waker, malloc(4096) + 4096, CLONE_VM | SIGCHLD, NULL) == -1)
595                 err(1, "Creating Waker");
596 }
597
598 /*
599  * Device Handling.
600  *
601  * When the Guest gives us a buffer, it sends an array of addresses and sizes.
602  * We need to make sure it's not trying to reach into the Launcher itself, so
603  * we have a convenient routine which checks it and exits with an error message
604  * if something funny is going on:
605  */
606 static void *_check_pointer(unsigned long addr, unsigned int size,
607                             unsigned int line)
608 {
609         /* We have to separately check addr and addr+size, because size could
610          * be huge and addr + size might wrap around. */
611         if (addr >= guest_limit || addr + size >= guest_limit)
612                 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
613         /* We return a pointer for the caller's convenience, now we know it's
614          * safe to use. */
615         return from_guest_phys(addr);
616 }
617 /* A macro which transparently hands the line number to the real function. */
618 #define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
619
620 /* Each buffer in the virtqueues is actually a chain of descriptors.  This
621  * function returns the next descriptor in the chain, or vq->vring.num if we're
622  * at the end. */
623 static unsigned next_desc(struct virtqueue *vq, unsigned int i)
624 {
625         unsigned int next;
626
627         /* If this descriptor says it doesn't chain, we're done. */
628         if (!(vq->vring.desc[i].flags & VRING_DESC_F_NEXT))
629                 return vq->vring.num;
630
631         /* Check they're not leading us off end of descriptors. */
632         next = vq->vring.desc[i].next;
633         /* Make sure compiler knows to grab that: we don't want it changing! */
634         wmb();
635
636         if (next >= vq->vring.num)
637                 errx(1, "Desc next is %u", next);
638
639         return next;
640 }
641
642 /* This looks in the virtqueue and for the first available buffer, and converts
643  * it to an iovec for convenient access.  Since descriptors consist of some
644  * number of output then some number of input descriptors, it's actually two
645  * iovecs, but we pack them into one and note how many of each there were.
646  *
647  * This function returns the descriptor number found, or vq->vring.num (which
648  * is never a valid descriptor number) if none was found. */
649 static unsigned get_vq_desc(struct virtqueue *vq,
650                             struct iovec iov[],
651                             unsigned int *out_num, unsigned int *in_num)
652 {
653         unsigned int i, head;
654         u16 last_avail;
655
656         /* Check it isn't doing very strange things with descriptor numbers. */
657         last_avail = lg_last_avail(vq);
658         if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
659                 errx(1, "Guest moved used index from %u to %u",
660                      last_avail, vq->vring.avail->idx);
661
662         /* If there's nothing new since last we looked, return invalid. */
663         if (vq->vring.avail->idx == last_avail)
664                 return vq->vring.num;
665
666         /* Grab the next descriptor number they're advertising, and increment
667          * the index we've seen. */
668         head = vq->vring.avail->ring[last_avail % vq->vring.num];
669         lg_last_avail(vq)++;
670
671         /* If their number is silly, that's a fatal mistake. */
672         if (head >= vq->vring.num)
673                 errx(1, "Guest says index %u is available", head);
674
675         /* When we start there are none of either input nor output. */
676         *out_num = *in_num = 0;
677
678         i = head;
679         do {
680                 /* Grab the first descriptor, and check it's OK. */
681                 iov[*out_num + *in_num].iov_len = vq->vring.desc[i].len;
682                 iov[*out_num + *in_num].iov_base
683                         = check_pointer(vq->vring.desc[i].addr,
684                                         vq->vring.desc[i].len);
685                 /* If this is an input descriptor, increment that count. */
686                 if (vq->vring.desc[i].flags & VRING_DESC_F_WRITE)
687                         (*in_num)++;
688                 else {
689                         /* If it's an output descriptor, they're all supposed
690                          * to come before any input descriptors. */
691                         if (*in_num)
692                                 errx(1, "Descriptor has out after in");
693                         (*out_num)++;
694                 }
695
696                 /* If we've got too many, that implies a descriptor loop. */
697                 if (*out_num + *in_num > vq->vring.num)
698                         errx(1, "Looped descriptor");
699         } while ((i = next_desc(vq, i)) != vq->vring.num);
700
701         vq->inflight++;
702         return head;
703 }
704
705 /* After we've used one of their buffers, we tell them about it.  We'll then
706  * want to send them an interrupt, using trigger_irq(). */
707 static void add_used(struct virtqueue *vq, unsigned int head, int len)
708 {
709         struct vring_used_elem *used;
710
711         /* The virtqueue contains a ring of used buffers.  Get a pointer to the
712          * next entry in that used ring. */
713         used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
714         used->id = head;
715         used->len = len;
716         /* Make sure buffer is written before we update index. */
717         wmb();
718         vq->vring.used->idx++;
719         vq->inflight--;
720 }
721
722 /* This actually sends the interrupt for this virtqueue */
723 static void trigger_irq(struct virtqueue *vq)
724 {
725         unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
726
727         /* If they don't want an interrupt, don't send one, unless empty. */
728         if ((vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)
729             && vq->inflight)
730                 return;
731
732         /* Send the Guest an interrupt tell them we used something up. */
733         if (write(lguest_fd, buf, sizeof(buf)) != 0)
734                 err(1, "Triggering irq %i", vq->config.irq);
735 }
736
737 /* And here's the combo meal deal.  Supersize me! */
738 static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
739 {
740         add_used(vq, head, len);
741         trigger_irq(vq);
742 }
743
744 /*
745  * The Console
746  *
747  * Here is the input terminal setting we save, and the routine to restore them
748  * on exit so the user gets their terminal back. */
749 static struct termios orig_term;
750 static void restore_term(void)
751 {
752         tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
753 }
754
755 /* We associate some data with the console for our exit hack. */
756 struct console_abort
757 {
758         /* How many times have they hit ^C? */
759         int count;
760         /* When did they start? */
761         struct timeval start;
762 };
763
764 /* This is the routine which handles console input (ie. stdin). */
765 static bool handle_console_input(struct device *dev)
766 {
767         int len;
768         unsigned int head, in_num, out_num;
769         struct iovec iov[dev->vq->vring.num];
770         struct console_abort *abort = dev->priv;
771
772         /* First we need a console buffer from the Guests's input virtqueue. */
773         head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
774
775         /* If they're not ready for input, stop listening to this file
776          * descriptor.  We'll start again once they add an input buffer. */
777         if (head == dev->vq->vring.num)
778                 return false;
779
780         if (out_num)
781                 errx(1, "Output buffers in console in queue?");
782
783         /* This is why we convert to iovecs: the readv() call uses them, and so
784          * it reads straight into the Guest's buffer. */
785         len = readv(dev->fd, iov, in_num);
786         if (len <= 0) {
787                 /* This implies that the console is closed, is /dev/null, or
788                  * something went terribly wrong. */
789                 warnx("Failed to get console input, ignoring console.");
790                 /* Put the input terminal back. */
791                 restore_term();
792                 /* Remove callback from input vq, so it doesn't restart us. */
793                 dev->vq->handle_output = NULL;
794                 /* Stop listening to this fd: don't call us again. */
795                 return false;
796         }
797
798         /* Tell the Guest about the new input. */
799         add_used_and_trigger(dev->vq, head, len);
800
801         /* Three ^C within one second?  Exit.
802          *
803          * This is such a hack, but works surprisingly well.  Each ^C has to be
804          * in a buffer by itself, so they can't be too fast.  But we check that
805          * we get three within about a second, so they can't be too slow. */
806         if (len == 1 && ((char *)iov[0].iov_base)[0] == 3) {
807                 if (!abort->count++)
808                         gettimeofday(&abort->start, NULL);
809                 else if (abort->count == 3) {
810                         struct timeval now;
811                         gettimeofday(&now, NULL);
812                         if (now.tv_sec <= abort->start.tv_sec+1) {
813                                 unsigned long args[] = { LHREQ_BREAK, 0 };
814                                 /* Close the fd so Waker will know it has to
815                                  * exit. */
816                                 close(waker_fds.pipe[1]);
817                                 /* Just in case Waker is blocked in BREAK, send
818                                  * unbreak now. */
819                                 write(lguest_fd, args, sizeof(args));
820                                 exit(2);
821                         }
822                         abort->count = 0;
823                 }
824         } else
825                 /* Any other key resets the abort counter. */
826                 abort->count = 0;
827
828         /* Everything went OK! */
829         return true;
830 }
831
832 /* Handling output for console is simple: we just get all the output buffers
833  * and write them to stdout. */
834 static void handle_console_output(struct virtqueue *vq, bool timeout)
835 {
836         unsigned int head, out, in;
837         int len;
838         struct iovec iov[vq->vring.num];
839
840         /* Keep getting output buffers from the Guest until we run out. */
841         while ((head = get_vq_desc(vq, iov, &out, &in)) != vq->vring.num) {
842                 if (in)
843                         errx(1, "Input buffers in output queue?");
844                 len = writev(STDOUT_FILENO, iov, out);
845                 add_used_and_trigger(vq, head, len);
846         }
847 }
848
849 /* This is called when we no longer want to hear about Guest changes to a
850  * virtqueue.  This is more efficient in high-traffic cases, but it means we
851  * have to set a timer to check if any more changes have occurred. */
852 static void block_vq(struct virtqueue *vq)
853 {
854         struct itimerval itm;
855
856         vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
857         vq->blocked = true;
858
859         itm.it_interval.tv_sec = 0;
860         itm.it_interval.tv_usec = 0;
861         itm.it_value.tv_sec = 0;
862         itm.it_value.tv_usec = timeout_usec;
863
864         setitimer(ITIMER_REAL, &itm, NULL);
865 }
866
867 /*
868  * The Network
869  *
870  * Handling output for network is also simple: we get all the output buffers
871  * and write them (ignoring the first element) to this device's file descriptor
872  * (/dev/net/tun).
873  */
874 static void handle_net_output(struct virtqueue *vq, bool timeout)
875 {
876         unsigned int head, out, in, num = 0;
877         int len;
878         struct iovec iov[vq->vring.num];
879         static int last_timeout_num;
880
881         /* Keep getting output buffers from the Guest until we run out. */
882         while ((head = get_vq_desc(vq, iov, &out, &in)) != vq->vring.num) {
883                 if (in)
884                         errx(1, "Input buffers in output queue?");
885                 len = writev(vq->dev->fd, iov, out);
886                 if (len < 0)
887                         err(1, "Writing network packet to tun");
888                 add_used_and_trigger(vq, head, len);
889                 num++;
890         }
891
892         /* Block further kicks and set up a timer if we saw anything. */
893         if (!timeout && num)
894                 block_vq(vq);
895
896         /* We never quite know how long should we wait before we check the
897          * queue again for more packets.  We start at 500 microseconds, and if
898          * we get fewer packets than last time, we assume we made the timeout
899          * too small and increase it by 10 microseconds.  Otherwise, we drop it
900          * by one microsecond every time.  It seems to work well enough. */
901         if (timeout) {
902                 if (num < last_timeout_num)
903                         timeout_usec += 10;
904                 else if (timeout_usec > 1)
905                         timeout_usec--;
906                 last_timeout_num = num;
907         }
908 }
909
910 /* This is where we handle a packet coming in from the tun device to our
911  * Guest. */
912 static bool handle_tun_input(struct device *dev)
913 {
914         unsigned int head, in_num, out_num;
915         int len;
916         struct iovec iov[dev->vq->vring.num];
917
918         /* First we need a network buffer from the Guests's recv virtqueue. */
919         head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
920         if (head == dev->vq->vring.num) {
921                 /* Now, it's expected that if we try to send a packet too
922                  * early, the Guest won't be ready yet.  Wait until the device
923                  * status says it's ready. */
924                 /* FIXME: Actually want DRIVER_ACTIVE here. */
925
926                 /* Now tell it we want to know if new things appear. */
927                 dev->vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
928                 wmb();
929
930                 /* We'll turn this back on if input buffers are registered. */
931                 return false;
932         } else if (out_num)
933                 errx(1, "Output buffers in network recv queue?");
934
935         /* Read the packet from the device directly into the Guest's buffer. */
936         len = readv(dev->fd, iov, in_num);
937         if (len <= 0)
938                 err(1, "reading network");
939
940         /* Tell the Guest about the new packet. */
941         add_used_and_trigger(dev->vq, head, len);
942
943         verbose("tun input packet len %i [%02x %02x] (%s)\n", len,
944                 ((u8 *)iov[1].iov_base)[0], ((u8 *)iov[1].iov_base)[1],
945                 head != dev->vq->vring.num ? "sent" : "discarded");
946
947         /* All good. */
948         return true;
949 }
950
951 /*L:215 This is the callback attached to the network and console input
952  * virtqueues: it ensures we try again, in case we stopped console or net
953  * delivery because Guest didn't have any buffers. */
954 static void enable_fd(struct virtqueue *vq, bool timeout)
955 {
956         add_device_fd(vq->dev->fd);
957         /* Snap the Waker out of its select loop. */
958         write(waker_fds.pipe[1], "", 1);
959 }
960
961 static void net_enable_fd(struct virtqueue *vq, bool timeout)
962 {
963         /* We don't need to know again when Guest refills receive buffer. */
964         vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
965         enable_fd(vq, timeout);
966 }
967
968 /* When the Guest tells us they updated the status field, we handle it. */
969 static void update_device_status(struct device *dev)
970 {
971         struct virtqueue *vq;
972
973         /* This is a reset. */
974         if (dev->desc->status == 0) {
975                 verbose("Resetting device %s\n", dev->name);
976
977                 /* Clear any features they've acked. */
978                 memset(get_feature_bits(dev) + dev->feature_len, 0,
979                        dev->feature_len);
980
981                 /* Zero out the virtqueues. */
982                 for (vq = dev->vq; vq; vq = vq->next) {
983                         memset(vq->vring.desc, 0,
984                                vring_size(vq->config.num, LGUEST_VRING_ALIGN));
985                         lg_last_avail(vq) = 0;
986                 }
987         } else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
988                 warnx("Device %s configuration FAILED", dev->name);
989         } else if (dev->desc->status & VIRTIO_CONFIG_S_DRIVER_OK) {
990                 unsigned int i;
991
992                 verbose("Device %s OK: offered", dev->name);
993                 for (i = 0; i < dev->feature_len; i++)
994                         verbose(" %02x", get_feature_bits(dev)[i]);
995                 verbose(", accepted");
996                 for (i = 0; i < dev->feature_len; i++)
997                         verbose(" %02x", get_feature_bits(dev)
998                                 [dev->feature_len+i]);
999
1000                 if (dev->ready)
1001                         dev->ready(dev);
1002         }
1003 }
1004
1005 /* This is the generic routine we call when the Guest uses LHCALL_NOTIFY. */
1006 static void handle_output(unsigned long addr)
1007 {
1008         struct device *i;
1009         struct virtqueue *vq;
1010
1011         /* Check each device and virtqueue. */
1012         for (i = devices.dev; i; i = i->next) {
1013                 /* Notifications to device descriptors update device status. */
1014                 if (from_guest_phys(addr) == i->desc) {
1015                         update_device_status(i);
1016                         return;
1017                 }
1018
1019                 /* Notifications to virtqueues mean output has occurred. */
1020                 for (vq = i->vq; vq; vq = vq->next) {
1021                         if (vq->config.pfn != addr/getpagesize())
1022                                 continue;
1023
1024                         /* Guest should acknowledge (and set features!)  before
1025                          * using the device. */
1026                         if (i->desc->status == 0) {
1027                                 warnx("%s gave early output", i->name);
1028                                 return;
1029                         }
1030
1031                         if (strcmp(vq->dev->name, "console") != 0)
1032                                 verbose("Output to %s\n", vq->dev->name);
1033                         if (vq->handle_output)
1034                                 vq->handle_output(vq, false);
1035                         return;
1036                 }
1037         }
1038
1039         /* Early console write is done using notify on a nul-terminated string
1040          * in Guest memory. */
1041         if (addr >= guest_limit)
1042                 errx(1, "Bad NOTIFY %#lx", addr);
1043
1044         write(STDOUT_FILENO, from_guest_phys(addr),
1045               strnlen(from_guest_phys(addr), guest_limit - addr));
1046 }
1047
1048 static void handle_timeout(void)
1049 {
1050         char buf[32];
1051         struct device *i;
1052         struct virtqueue *vq;
1053
1054         /* Clear the pipe */
1055         read(timeoutpipe[0], buf, sizeof(buf));
1056
1057         /* Check each device and virtqueue: flush blocked ones. */
1058         for (i = devices.dev; i; i = i->next) {
1059                 for (vq = i->vq; vq; vq = vq->next) {
1060                         if (!vq->blocked)
1061                                 continue;
1062
1063                         vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
1064                         vq->blocked = false;
1065                         if (vq->handle_output)
1066                                 vq->handle_output(vq, true);
1067                 }
1068         }
1069 }
1070
1071 /* This is called when the Waker wakes us up: check for incoming file
1072  * descriptors. */
1073 static void handle_input(void)
1074 {
1075         /* select() wants a zeroed timeval to mean "don't wait". */
1076         struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
1077
1078         for (;;) {
1079                 struct device *i;
1080                 fd_set fds = devices.infds;
1081                 int num;
1082
1083                 num = select(devices.max_infd+1, &fds, NULL, NULL, &poll);
1084                 /* Could get interrupted */
1085                 if (num < 0)
1086                         continue;
1087                 /* If nothing is ready, we're done. */
1088                 if (num == 0)
1089                         break;
1090
1091                 /* Otherwise, call the device(s) which have readable file
1092                  * descriptors and a method of handling them.  */
1093                 for (i = devices.dev; i; i = i->next) {
1094                         if (i->handle_input && FD_ISSET(i->fd, &fds)) {
1095                                 if (i->handle_input(i))
1096                                         continue;
1097
1098                                 /* If handle_input() returns false, it means we
1099                                  * should no longer service it.  Networking and
1100                                  * console do this when there's no input
1101                                  * buffers to deliver into.  Console also uses
1102                                  * it when it discovers that stdin is closed. */
1103                                 FD_CLR(i->fd, &devices.infds);
1104                         }
1105                 }
1106
1107                 /* Is this the timeout fd? */
1108                 if (FD_ISSET(timeoutpipe[0], &fds))
1109                         handle_timeout();
1110         }
1111 }
1112
1113 /*L:190
1114  * Device Setup
1115  *
1116  * All devices need a descriptor so the Guest knows it exists, and a "struct
1117  * device" so the Launcher can keep track of it.  We have common helper
1118  * routines to allocate and manage them.
1119  */
1120
1121 /* The layout of the device page is a "struct lguest_device_desc" followed by a
1122  * number of virtqueue descriptors, then two sets of feature bits, then an
1123  * array of configuration bytes.  This routine returns the configuration
1124  * pointer. */
1125 static u8 *device_config(const struct device *dev)
1126 {
1127         return (void *)(dev->desc + 1)
1128                 + dev->num_vq * sizeof(struct lguest_vqconfig)
1129                 + dev->feature_len * 2;
1130 }
1131
1132 /* This routine allocates a new "struct lguest_device_desc" from descriptor
1133  * table page just above the Guest's normal memory.  It returns a pointer to
1134  * that descriptor. */
1135 static struct lguest_device_desc *new_dev_desc(u16 type)
1136 {
1137         struct lguest_device_desc d = { .type = type };
1138         void *p;
1139
1140         /* Figure out where the next device config is, based on the last one. */
1141         if (devices.lastdev)
1142                 p = device_config(devices.lastdev)
1143                         + devices.lastdev->desc->config_len;
1144         else
1145                 p = devices.descpage;
1146
1147         /* We only have one page for all the descriptors. */
1148         if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
1149                 errx(1, "Too many devices");
1150
1151         /* p might not be aligned, so we memcpy in. */
1152         return memcpy(p, &d, sizeof(d));
1153 }
1154
1155 /* Each device descriptor is followed by the description of its virtqueues.  We
1156  * specify how many descriptors the virtqueue is to have. */
1157 static void add_virtqueue(struct device *dev, unsigned int num_descs,
1158                           void (*handle_output)(struct virtqueue *, bool))
1159 {
1160         unsigned int pages;
1161         struct virtqueue **i, *vq = malloc(sizeof(*vq));
1162         void *p;
1163
1164         /* First we need some memory for this virtqueue. */
1165         pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
1166                 / getpagesize();
1167         p = get_pages(pages);
1168
1169         /* Initialize the virtqueue */
1170         vq->next = NULL;
1171         vq->last_avail_idx = 0;
1172         vq->dev = dev;
1173         vq->inflight = 0;
1174         vq->blocked = false;
1175
1176         /* Initialize the configuration. */
1177         vq->config.num = num_descs;
1178         vq->config.irq = devices.next_irq++;
1179         vq->config.pfn = to_guest_phys(p) / getpagesize();
1180
1181         /* Initialize the vring. */
1182         vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
1183
1184         /* Append virtqueue to this device's descriptor.  We use
1185          * device_config() to get the end of the device's current virtqueues;
1186          * we check that we haven't added any config or feature information
1187          * yet, otherwise we'd be overwriting them. */
1188         assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
1189         memcpy(device_config(dev), &vq->config, sizeof(vq->config));
1190         dev->num_vq++;
1191         dev->desc->num_vq++;
1192
1193         verbose("Virtqueue page %#lx\n", to_guest_phys(p));
1194
1195         /* Add to tail of list, so dev->vq is first vq, dev->vq->next is
1196          * second.  */
1197         for (i = &dev->vq; *i; i = &(*i)->next);
1198         *i = vq;
1199
1200         /* Set the routine to call when the Guest does something to this
1201          * virtqueue. */
1202         vq->handle_output = handle_output;
1203
1204         /* As an optimization, set the advisory "Don't Notify Me" flag if we
1205          * don't have a handler */
1206         if (!handle_output)
1207                 vq->vring.used->flags = VRING_USED_F_NO_NOTIFY;
1208 }
1209
1210 /* The first half of the feature bitmask is for us to advertise features.  The
1211  * second half is for the Guest to accept features. */
1212 static void add_feature(struct device *dev, unsigned bit)
1213 {
1214         u8 *features = get_feature_bits(dev);
1215
1216         /* We can't extend the feature bits once we've added config bytes */
1217         if (dev->desc->feature_len <= bit / CHAR_BIT) {
1218                 assert(dev->desc->config_len == 0);
1219                 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
1220         }
1221
1222         features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
1223 }
1224
1225 /* This routine sets the configuration fields for an existing device's
1226  * descriptor.  It only works for the last device, but that's OK because that's
1227  * how we use it. */
1228 static void set_config(struct device *dev, unsigned len, const void *conf)
1229 {
1230         /* Check we haven't overflowed our single page. */
1231         if (device_config(dev) + len > devices.descpage + getpagesize())
1232                 errx(1, "Too many devices");
1233
1234         /* Copy in the config information, and store the length. */
1235         memcpy(device_config(dev), conf, len);
1236         dev->desc->config_len = len;
1237 }
1238
1239 /* This routine does all the creation and setup of a new device, including
1240  * calling new_dev_desc() to allocate the descriptor and device memory.
1241  *
1242  * See what I mean about userspace being boring? */
1243 static struct device *new_device(const char *name, u16 type, int fd,
1244                                  bool (*handle_input)(struct device *))
1245 {
1246         struct device *dev = malloc(sizeof(*dev));
1247
1248         /* Now we populate the fields one at a time. */
1249         dev->fd = fd;
1250         /* If we have an input handler for this file descriptor, then we add it
1251          * to the device_list's fdset and maxfd. */
1252         if (handle_input)
1253                 add_device_fd(dev->fd);
1254         dev->desc = new_dev_desc(type);
1255         dev->handle_input = handle_input;
1256         dev->name = name;
1257         dev->vq = NULL;
1258         dev->ready = NULL;
1259         dev->feature_len = 0;
1260         dev->num_vq = 0;
1261
1262         /* Append to device list.  Prepending to a single-linked list is
1263          * easier, but the user expects the devices to be arranged on the bus
1264          * in command-line order.  The first network device on the command line
1265          * is eth0, the first block device /dev/vda, etc. */
1266         if (devices.lastdev)
1267                 devices.lastdev->next = dev;
1268         else
1269                 devices.dev = dev;
1270         devices.lastdev = dev;
1271
1272         return dev;
1273 }
1274
1275 /* Our first setup routine is the console.  It's a fairly simple device, but
1276  * UNIX tty handling makes it uglier than it could be. */
1277 static void setup_console(void)
1278 {
1279         struct device *dev;
1280
1281         /* If we can save the initial standard input settings... */
1282         if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1283                 struct termios term = orig_term;
1284                 /* Then we turn off echo, line buffering and ^C etc.  We want a
1285                  * raw input stream to the Guest. */
1286                 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1287                 tcsetattr(STDIN_FILENO, TCSANOW, &term);
1288                 /* If we exit gracefully, the original settings will be
1289                  * restored so the user can see what they're typing. */
1290                 atexit(restore_term);
1291         }
1292
1293         dev = new_device("console", VIRTIO_ID_CONSOLE,
1294                          STDIN_FILENO, handle_console_input);
1295         /* We store the console state in dev->priv, and initialize it. */
1296         dev->priv = malloc(sizeof(struct console_abort));
1297         ((struct console_abort *)dev->priv)->count = 0;
1298
1299         /* The console needs two virtqueues: the input then the output.  When
1300          * they put something the input queue, we make sure we're listening to
1301          * stdin.  When they put something in the output queue, we write it to
1302          * stdout. */
1303         add_virtqueue(dev, VIRTQUEUE_NUM, enable_fd);
1304         add_virtqueue(dev, VIRTQUEUE_NUM, handle_console_output);
1305
1306         verbose("device %u: console\n", devices.device_num++);
1307 }
1308 /*:*/
1309
1310 static void timeout_alarm(int sig)
1311 {
1312         write(timeoutpipe[1], "", 1);
1313 }
1314
1315 static void setup_timeout(void)
1316 {
1317         if (pipe(timeoutpipe) != 0)
1318                 err(1, "Creating timeout pipe");
1319
1320         if (fcntl(timeoutpipe[1], F_SETFL,
1321                   fcntl(timeoutpipe[1], F_GETFL) | O_NONBLOCK) != 0)
1322                 err(1, "Making timeout pipe nonblocking");
1323
1324         add_device_fd(timeoutpipe[0]);
1325         signal(SIGALRM, timeout_alarm);
1326 }
1327
1328 /*M:010 Inter-guest networking is an interesting area.  Simplest is to have a
1329  * --sharenet=<name> option which opens or creates a named pipe.  This can be
1330  * used to send packets to another guest in a 1:1 manner.
1331  *
1332  * More sopisticated is to use one of the tools developed for project like UML
1333  * to do networking.
1334  *
1335  * Faster is to do virtio bonding in kernel.  Doing this 1:1 would be
1336  * completely generic ("here's my vring, attach to your vring") and would work
1337  * for any traffic.  Of course, namespace and permissions issues need to be
1338  * dealt with.  A more sophisticated "multi-channel" virtio_net.c could hide
1339  * multiple inter-guest channels behind one interface, although it would
1340  * require some manner of hotplugging new virtio channels.
1341  *
1342  * Finally, we could implement a virtio network switch in the kernel. :*/
1343
1344 static u32 str2ip(const char *ipaddr)
1345 {
1346         unsigned int b[4];
1347
1348         if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
1349                 errx(1, "Failed to parse IP address '%s'", ipaddr);
1350         return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
1351 }
1352
1353 static void str2mac(const char *macaddr, unsigned char mac[6])
1354 {
1355         unsigned int m[6];
1356         if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
1357                    &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
1358                 errx(1, "Failed to parse mac address '%s'", macaddr);
1359         mac[0] = m[0];
1360         mac[1] = m[1];
1361         mac[2] = m[2];
1362         mac[3] = m[3];
1363         mac[4] = m[4];
1364         mac[5] = m[5];
1365 }
1366
1367 /* This code is "adapted" from libbridge: it attaches the Host end of the
1368  * network device to the bridge device specified by the command line.
1369  *
1370  * This is yet another James Morris contribution (I'm an IP-level guy, so I
1371  * dislike bridging), and I just try not to break it. */
1372 static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1373 {
1374         int ifidx;
1375         struct ifreq ifr;
1376
1377         if (!*br_name)
1378                 errx(1, "must specify bridge name");
1379
1380         ifidx = if_nametoindex(if_name);
1381         if (!ifidx)
1382                 errx(1, "interface %s does not exist!", if_name);
1383
1384         strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
1385         ifr.ifr_name[IFNAMSIZ-1] = '\0';
1386         ifr.ifr_ifindex = ifidx;
1387         if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1388                 err(1, "can't add %s to bridge %s", if_name, br_name);
1389 }
1390
1391 /* This sets up the Host end of the network device with an IP address, brings
1392  * it up so packets will flow, the copies the MAC address into the hwaddr
1393  * pointer. */
1394 static void configure_device(int fd, const char *tapif, u32 ipaddr)
1395 {
1396         struct ifreq ifr;
1397         struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
1398
1399         memset(&ifr, 0, sizeof(ifr));
1400         strcpy(ifr.ifr_name, tapif);
1401
1402         /* Don't read these incantations.  Just cut & paste them like I did! */
1403         sin->sin_family = AF_INET;
1404         sin->sin_addr.s_addr = htonl(ipaddr);
1405         if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
1406                 err(1, "Setting %s interface address", tapif);
1407         ifr.ifr_flags = IFF_UP;
1408         if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
1409                 err(1, "Bringing interface %s up", tapif);
1410 }
1411
1412 static int get_tun_device(char tapif[IFNAMSIZ])
1413 {
1414         struct ifreq ifr;
1415         int netfd;
1416
1417         /* Start with this zeroed.  Messy but sure. */
1418         memset(&ifr, 0, sizeof(ifr));
1419
1420         /* We open the /dev/net/tun device and tell it we want a tap device.  A
1421          * tap device is like a tun device, only somehow different.  To tell
1422          * the truth, I completely blundered my way through this code, but it
1423          * works now! */
1424         netfd = open_or_die("/dev/net/tun", O_RDWR);
1425         ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
1426         strcpy(ifr.ifr_name, "tap%d");
1427         if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1428                 err(1, "configuring /dev/net/tun");
1429
1430         if (ioctl(netfd, TUNSETOFFLOAD,
1431                   TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
1432                 err(1, "Could not set features for tun device");
1433
1434         /* We don't need checksums calculated for packets coming in this
1435          * device: trust us! */
1436         ioctl(netfd, TUNSETNOCSUM, 1);
1437
1438         memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
1439         return netfd;
1440 }
1441
1442 /*L:195 Our network is a Host<->Guest network.  This can either use bridging or
1443  * routing, but the principle is the same: it uses the "tun" device to inject
1444  * packets into the Host as if they came in from a normal network card.  We
1445  * just shunt packets between the Guest and the tun device. */
1446 static void setup_tun_net(char *arg)
1447 {
1448         struct device *dev;
1449         int netfd, ipfd;
1450         u32 ip = INADDR_ANY;
1451         bool bridging = false;
1452         char tapif[IFNAMSIZ], *p;
1453         struct virtio_net_config conf;
1454
1455         netfd = get_tun_device(tapif);
1456
1457         /* First we create a new network device. */
1458         dev = new_device("net", VIRTIO_ID_NET, netfd, handle_tun_input);
1459
1460         /* Network devices need a receive and a send queue, just like
1461          * console. */
1462         add_virtqueue(dev, VIRTQUEUE_NUM, net_enable_fd);
1463         add_virtqueue(dev, VIRTQUEUE_NUM, handle_net_output);
1464
1465         /* We need a socket to perform the magic network ioctls to bring up the
1466          * tap interface, connect to the bridge etc.  Any socket will do! */
1467         ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1468         if (ipfd < 0)
1469                 err(1, "opening IP socket");
1470
1471         /* If the command line was --tunnet=bridge:<name> do bridging. */
1472         if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
1473                 arg += strlen(BRIDGE_PFX);
1474                 bridging = true;
1475         }
1476
1477         /* A mac address may follow the bridge name or IP address */
1478         p = strchr(arg, ':');
1479         if (p) {
1480                 str2mac(p+1, conf.mac);
1481                 add_feature(dev, VIRTIO_NET_F_MAC);
1482                 *p = '\0';
1483         }
1484
1485         /* arg is now either an IP address or a bridge name */
1486         if (bridging)
1487                 add_to_bridge(ipfd, tapif, arg);
1488         else
1489                 ip = str2ip(arg);
1490
1491         /* Set up the tun device. */
1492         configure_device(ipfd, tapif, ip);
1493
1494         add_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY);
1495         /* Expect Guest to handle everything except UFO */
1496         add_feature(dev, VIRTIO_NET_F_CSUM);
1497         add_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
1498         add_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
1499         add_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
1500         add_feature(dev, VIRTIO_NET_F_GUEST_ECN);
1501         add_feature(dev, VIRTIO_NET_F_HOST_TSO4);
1502         add_feature(dev, VIRTIO_NET_F_HOST_TSO6);
1503         add_feature(dev, VIRTIO_NET_F_HOST_ECN);
1504         set_config(dev, sizeof(conf), &conf);
1505
1506         /* We don't need the socket any more; setup is done. */
1507         close(ipfd);
1508
1509         devices.device_num++;
1510
1511         if (bridging)
1512                 verbose("device %u: tun %s attached to bridge: %s\n",
1513                         devices.device_num, tapif, arg);
1514         else
1515                 verbose("device %u: tun %s: %s\n",
1516                         devices.device_num, tapif, arg);
1517 }
1518
1519 /* Our block (disk) device should be really simple: the Guest asks for a block
1520  * number and we read or write that position in the file.  Unfortunately, that
1521  * was amazingly slow: the Guest waits until the read is finished before
1522  * running anything else, even if it could have been doing useful work.
1523  *
1524  * We could use async I/O, except it's reputed to suck so hard that characters
1525  * actually go missing from your code when you try to use it.
1526  *
1527  * So we farm the I/O out to thread, and communicate with it via a pipe. */
1528
1529 /* This hangs off device->priv. */
1530 struct vblk_info
1531 {
1532         /* The size of the file. */
1533         off64_t len;
1534
1535         /* The file descriptor for the file. */
1536         int fd;
1537
1538         /* IO thread listens on this file descriptor [0]. */
1539         int workpipe[2];
1540
1541         /* IO thread writes to this file descriptor to mark it done, then
1542          * Launcher triggers interrupt to Guest. */
1543         int done_fd;
1544 };
1545
1546 /*L:210
1547  * The Disk
1548  *
1549  * Remember that the block device is handled by a separate I/O thread.  We head
1550  * straight into the core of that thread here:
1551  */
1552 static bool service_io(struct device *dev)
1553 {
1554         struct vblk_info *vblk = dev->priv;
1555         unsigned int head, out_num, in_num, wlen;
1556         int ret;
1557         u8 *in;
1558         struct virtio_blk_outhdr *out;
1559         struct iovec iov[dev->vq->vring.num];
1560         off64_t off;
1561
1562         /* See if there's a request waiting.  If not, nothing to do. */
1563         head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
1564         if (head == dev->vq->vring.num)
1565                 return false;
1566
1567         /* Every block request should contain at least one output buffer
1568          * (detailing the location on disk and the type of request) and one
1569          * input buffer (to hold the result). */
1570         if (out_num == 0 || in_num == 0)
1571                 errx(1, "Bad virtblk cmd %u out=%u in=%u",
1572                      head, out_num, in_num);
1573
1574         out = convert(&iov[0], struct virtio_blk_outhdr);
1575         in = convert(&iov[out_num+in_num-1], u8);
1576         off = out->sector * 512;
1577
1578         /* The block device implements "barriers", where the Guest indicates
1579          * that it wants all previous writes to occur before this write.  We
1580          * don't have a way of asking our kernel to do a barrier, so we just
1581          * synchronize all the data in the file.  Pretty poor, no? */
1582         if (out->type & VIRTIO_BLK_T_BARRIER)
1583                 fdatasync(vblk->fd);
1584
1585         /* In general the virtio block driver is allowed to try SCSI commands.
1586          * It'd be nice if we supported eject, for example, but we don't. */
1587         if (out->type & VIRTIO_BLK_T_SCSI_CMD) {
1588                 fprintf(stderr, "Scsi commands unsupported\n");
1589                 *in = VIRTIO_BLK_S_UNSUPP;
1590                 wlen = sizeof(*in);
1591         } else if (out->type & VIRTIO_BLK_T_OUT) {
1592                 /* Write */
1593
1594                 /* Move to the right location in the block file.  This can fail
1595                  * if they try to write past end. */
1596                 if (lseek64(vblk->fd, off, SEEK_SET) != off)
1597                         err(1, "Bad seek to sector %llu", out->sector);
1598
1599                 ret = writev(vblk->fd, iov+1, out_num-1);
1600                 verbose("WRITE to sector %llu: %i\n", out->sector, ret);
1601
1602                 /* Grr... Now we know how long the descriptor they sent was, we
1603                  * make sure they didn't try to write over the end of the block
1604                  * file (possibly extending it). */
1605                 if (ret > 0 && off + ret > vblk->len) {
1606                         /* Trim it back to the correct length */
1607                         ftruncate64(vblk->fd, vblk->len);
1608                         /* Die, bad Guest, die. */
1609                         errx(1, "Write past end %llu+%u", off, ret);
1610                 }
1611                 wlen = sizeof(*in);
1612                 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
1613         } else {
1614                 /* Read */
1615
1616                 /* Move to the right location in the block file.  This can fail
1617                  * if they try to read past end. */
1618                 if (lseek64(vblk->fd, off, SEEK_SET) != off)
1619                         err(1, "Bad seek to sector %llu", out->sector);
1620
1621                 ret = readv(vblk->fd, iov+1, in_num-1);
1622                 verbose("READ from sector %llu: %i\n", out->sector, ret);
1623                 if (ret >= 0) {
1624                         wlen = sizeof(*in) + ret;
1625                         *in = VIRTIO_BLK_S_OK;
1626                 } else {
1627                         wlen = sizeof(*in);
1628                         *in = VIRTIO_BLK_S_IOERR;
1629                 }
1630         }
1631
1632         /* OK, so we noted that it was pretty poor to use an fdatasync as a
1633          * barrier.  But Christoph Hellwig points out that we need a sync
1634          * *afterwards* as well: "Barriers specify no reordering to the front
1635          * or the back."  And Jens Axboe confirmed it, so here we are: */
1636         if (out->type & VIRTIO_BLK_T_BARRIER)
1637                 fdatasync(vblk->fd);
1638
1639         /* We can't trigger an IRQ, because we're not the Launcher.  It does
1640          * that when we tell it we're done. */
1641         add_used(dev->vq, head, wlen);
1642         return true;
1643 }
1644
1645 /* This is the thread which actually services the I/O. */
1646 static int io_thread(void *_dev)
1647 {
1648         struct device *dev = _dev;
1649         struct vblk_info *vblk = dev->priv;
1650         char c;
1651
1652         /* Close other side of workpipe so we get 0 read when main dies. */
1653         close(vblk->workpipe[1]);
1654         /* Close the other side of the done_fd pipe. */
1655         close(dev->fd);
1656
1657         /* When this read fails, it means Launcher died, so we follow. */
1658         while (read(vblk->workpipe[0], &c, 1) == 1) {
1659                 /* We acknowledge each request immediately to reduce latency,
1660                  * rather than waiting until we've done them all.  I haven't
1661                  * measured to see if it makes any difference.
1662                  *
1663                  * That would be an interesting test, wouldn't it?  You could
1664                  * also try having more than one I/O thread. */
1665                 while (service_io(dev))
1666                         write(vblk->done_fd, &c, 1);
1667         }
1668         return 0;
1669 }
1670
1671 /* Now we've seen the I/O thread, we return to the Launcher to see what happens
1672  * when that thread tells us it's completed some I/O. */
1673 static bool handle_io_finish(struct device *dev)
1674 {
1675         char c;
1676
1677         /* If the I/O thread died, presumably it printed the error, so we
1678          * simply exit. */
1679         if (read(dev->fd, &c, 1) != 1)
1680                 exit(1);
1681
1682         /* It did some work, so trigger the irq. */
1683         trigger_irq(dev->vq);
1684         return true;
1685 }
1686
1687 /* When the Guest submits some I/O, we just need to wake the I/O thread. */
1688 static void handle_virtblk_output(struct virtqueue *vq, bool timeout)
1689 {
1690         struct vblk_info *vblk = vq->dev->priv;
1691         char c = 0;
1692
1693         /* Wake up I/O thread and tell it to go to work! */
1694         if (write(vblk->workpipe[1], &c, 1) != 1)
1695                 /* Presumably it indicated why it died. */
1696                 exit(1);
1697 }
1698
1699 /*L:198 This actually sets up a virtual block device. */
1700 static void setup_block_file(const char *filename)
1701 {
1702         int p[2];
1703         struct device *dev;
1704         struct vblk_info *vblk;
1705         void *stack;
1706         struct virtio_blk_config conf;
1707
1708         /* This is the pipe the I/O thread will use to tell us I/O is done. */
1709         pipe(p);
1710
1711         /* The device responds to return from I/O thread. */
1712         dev = new_device("block", VIRTIO_ID_BLOCK, p[0], handle_io_finish);
1713
1714         /* The device has one virtqueue, where the Guest places requests. */
1715         add_virtqueue(dev, VIRTQUEUE_NUM, handle_virtblk_output);
1716
1717         /* Allocate the room for our own bookkeeping */
1718         vblk = dev->priv = malloc(sizeof(*vblk));
1719
1720         /* First we open the file and store the length. */
1721         vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
1722         vblk->len = lseek64(vblk->fd, 0, SEEK_END);
1723
1724         /* We support barriers. */
1725         add_feature(dev, VIRTIO_BLK_F_BARRIER);
1726
1727         /* Tell Guest how many sectors this device has. */
1728         conf.capacity = cpu_to_le64(vblk->len / 512);
1729
1730         /* Tell Guest not to put in too many descriptors at once: two are used
1731          * for the in and out elements. */
1732         add_feature(dev, VIRTIO_BLK_F_SEG_MAX);
1733         conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
1734
1735         set_config(dev, sizeof(conf), &conf);
1736
1737         /* The I/O thread writes to this end of the pipe when done. */
1738         vblk->done_fd = p[1];
1739
1740         /* This is the second pipe, which is how we tell the I/O thread about
1741          * more work. */
1742         pipe(vblk->workpipe);
1743
1744         /* Create stack for thread and run it.  Since stack grows upwards, we
1745          * point the stack pointer to the end of this region. */
1746         stack = malloc(32768);
1747         /* SIGCHLD - We dont "wait" for our cloned thread, so prevent it from
1748          * becoming a zombie. */
1749         if (clone(io_thread, stack + 32768, CLONE_VM | SIGCHLD, dev) == -1)
1750                 err(1, "Creating clone");
1751
1752         /* We don't need to keep the I/O thread's end of the pipes open. */
1753         close(vblk->done_fd);
1754         close(vblk->workpipe[0]);
1755
1756         verbose("device %u: virtblock %llu sectors\n",
1757                 devices.device_num, le64_to_cpu(conf.capacity));
1758 }
1759
1760 /* Our random number generator device reads from /dev/random into the Guest's
1761  * input buffers.  The usual case is that the Guest doesn't want random numbers
1762  * and so has no buffers although /dev/random is still readable, whereas
1763  * console is the reverse.
1764  *
1765  * The same logic applies, however. */
1766 static bool handle_rng_input(struct device *dev)
1767 {
1768         int len;
1769         unsigned int head, in_num, out_num, totlen = 0;
1770         struct iovec iov[dev->vq->vring.num];
1771
1772         /* First we need a buffer from the Guests's virtqueue. */
1773         head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
1774
1775         /* If they're not ready for input, stop listening to this file
1776          * descriptor.  We'll start again once they add an input buffer. */
1777         if (head == dev->vq->vring.num)
1778                 return false;
1779
1780         if (out_num)
1781                 errx(1, "Output buffers in rng?");
1782
1783         /* This is why we convert to iovecs: the readv() call uses them, and so
1784          * it reads straight into the Guest's buffer.  We loop to make sure we
1785          * fill it. */
1786         while (!iov_empty(iov, in_num)) {
1787                 len = readv(dev->fd, iov, in_num);
1788                 if (len <= 0)
1789                         err(1, "Read from /dev/random gave %i", len);
1790                 iov_consume(iov, in_num, len);
1791                 totlen += len;
1792         }
1793
1794         /* Tell the Guest about the new input. */
1795         add_used_and_trigger(dev->vq, head, totlen);
1796
1797         /* Everything went OK! */
1798         return true;
1799 }
1800
1801 /* And this creates a "hardware" random number device for the Guest. */
1802 static void setup_rng(void)
1803 {
1804         struct device *dev;
1805         int fd;
1806
1807         fd = open_or_die("/dev/random", O_RDONLY);
1808
1809         /* The device responds to return from I/O thread. */
1810         dev = new_device("rng", VIRTIO_ID_RNG, fd, handle_rng_input);
1811
1812         /* The device has one virtqueue, where the Guest places inbufs. */
1813         add_virtqueue(dev, VIRTQUEUE_NUM, enable_fd);
1814
1815         verbose("device %u: rng\n", devices.device_num++);
1816 }
1817 /* That's the end of device setup. */
1818
1819 /*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
1820 static void __attribute__((noreturn)) restart_guest(void)
1821 {
1822         unsigned int i;
1823
1824         /* Since we don't track all open fds, we simply close everything beyond
1825          * stderr. */
1826         for (i = 3; i < FD_SETSIZE; i++)
1827                 close(i);
1828
1829         /* The exec automatically gets rid of the I/O and Waker threads. */
1830         execv(main_args[0], main_args);
1831         err(1, "Could not exec %s", main_args[0]);
1832 }
1833
1834 /*L:220 Finally we reach the core of the Launcher which runs the Guest, serves
1835  * its input and output, and finally, lays it to rest. */
1836 static void __attribute__((noreturn)) run_guest(void)
1837 {
1838         for (;;) {
1839                 unsigned long args[] = { LHREQ_BREAK, 0 };
1840                 unsigned long notify_addr;
1841                 int readval;
1842
1843                 /* We read from the /dev/lguest device to run the Guest. */
1844                 readval = pread(lguest_fd, &notify_addr,
1845                                 sizeof(notify_addr), cpu_id);
1846
1847                 /* One unsigned long means the Guest did HCALL_NOTIFY */
1848                 if (readval == sizeof(notify_addr)) {
1849                         verbose("Notify on address %#lx\n", notify_addr);
1850                         handle_output(notify_addr);
1851                         continue;
1852                 /* ENOENT means the Guest died.  Reading tells us why. */
1853                 } else if (errno == ENOENT) {
1854                         char reason[1024] = { 0 };
1855                         pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
1856                         errx(1, "%s", reason);
1857                 /* ERESTART means that we need to reboot the guest */
1858                 } else if (errno == ERESTART) {
1859                         restart_guest();
1860                 /* EAGAIN means a signal (timeout).
1861                  * Anything else means a bug or incompatible change. */
1862                 } else if (errno != EAGAIN)
1863                         err(1, "Running guest failed");
1864
1865                 /* Only service input on thread for CPU 0. */
1866                 if (cpu_id != 0)
1867                         continue;
1868
1869                 /* Service input, then unset the BREAK to release the Waker. */
1870                 handle_input();
1871                 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1872                         err(1, "Resetting break");
1873         }
1874 }
1875 /*L:240
1876  * This is the end of the Launcher.  The good news: we are over halfway
1877  * through!  The bad news: the most fiendish part of the code still lies ahead
1878  * of us.
1879  *
1880  * Are you ready?  Take a deep breath and join me in the core of the Host, in
1881  * "make Host".
1882  :*/
1883
1884 static struct option opts[] = {
1885         { "verbose", 0, NULL, 'v' },
1886         { "tunnet", 1, NULL, 't' },
1887         { "block", 1, NULL, 'b' },
1888         { "rng", 0, NULL, 'r' },
1889         { "initrd", 1, NULL, 'i' },
1890         { NULL },
1891 };
1892 static void usage(void)
1893 {
1894         errx(1, "Usage: lguest [--verbose] "
1895              "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
1896              "|--block=<filename>|--initrd=<filename>]...\n"
1897              "<mem-in-mb> vmlinux [args...]");
1898 }
1899
1900 /*L:105 The main routine is where the real work begins: */
1901 int main(int argc, char *argv[])
1902 {
1903         /* Memory, top-level pagetable, code startpoint and size of the
1904          * (optional) initrd. */
1905         unsigned long mem = 0, start, initrd_size = 0;
1906         /* Two temporaries. */
1907         int i, c;
1908         /* The boot information for the Guest. */
1909         struct boot_params *boot;
1910         /* If they specify an initrd file to load. */
1911         const char *initrd_name = NULL;
1912
1913         /* Save the args: we "reboot" by execing ourselves again. */
1914         main_args = argv;
1915         /* We don't "wait" for the children, so prevent them from becoming
1916          * zombies. */
1917         signal(SIGCHLD, SIG_IGN);
1918
1919         /* First we initialize the device list.  Since console and network
1920          * device receive input from a file descriptor, we keep an fdset
1921          * (infds) and the maximum fd number (max_infd) with the head of the
1922          * list.  We also keep a pointer to the last device.  Finally, we keep
1923          * the next interrupt number to use for devices (1: remember that 0 is
1924          * used by the timer). */
1925         FD_ZERO(&devices.infds);
1926         devices.max_infd = -1;
1927         devices.lastdev = NULL;
1928         devices.next_irq = 1;
1929
1930         cpu_id = 0;
1931         /* We need to know how much memory so we can set up the device
1932          * descriptor and memory pages for the devices as we parse the command
1933          * line.  So we quickly look through the arguments to find the amount
1934          * of memory now. */
1935         for (i = 1; i < argc; i++) {
1936                 if (argv[i][0] != '-') {
1937                         mem = atoi(argv[i]) * 1024 * 1024;
1938                         /* We start by mapping anonymous pages over all of
1939                          * guest-physical memory range.  This fills it with 0,
1940                          * and ensures that the Guest won't be killed when it
1941                          * tries to access it. */
1942                         guest_base = map_zeroed_pages(mem / getpagesize()
1943                                                       + DEVICE_PAGES);
1944                         guest_limit = mem;
1945                         guest_max = mem + DEVICE_PAGES*getpagesize();
1946                         devices.descpage = get_pages(1);
1947                         break;
1948                 }
1949         }
1950
1951         /* The options are fairly straight-forward */
1952         while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
1953                 switch (c) {
1954                 case 'v':
1955                         verbose = true;
1956                         break;
1957                 case 't':
1958                         setup_tun_net(optarg);
1959                         break;
1960                 case 'b':
1961                         setup_block_file(optarg);
1962                         break;
1963                 case 'r':
1964                         setup_rng();
1965                         break;
1966                 case 'i':
1967                         initrd_name = optarg;
1968                         break;
1969                 default:
1970                         warnx("Unknown argument %s", argv[optind]);
1971                         usage();
1972                 }
1973         }
1974         /* After the other arguments we expect memory and kernel image name,
1975          * followed by command line arguments for the kernel. */
1976         if (optind + 2 > argc)
1977                 usage();
1978
1979         verbose("Guest base is at %p\n", guest_base);
1980
1981         /* We always have a console device */
1982         setup_console();
1983
1984         /* We can timeout waiting for Guest network transmit. */
1985         setup_timeout();
1986
1987         /* Now we load the kernel */
1988         start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
1989
1990         /* Boot information is stashed at physical address 0 */
1991         boot = from_guest_phys(0);
1992
1993         /* Map the initrd image if requested (at top of physical memory) */
1994         if (initrd_name) {
1995                 initrd_size = load_initrd(initrd_name, mem);
1996                 /* These are the location in the Linux boot header where the
1997                  * start and size of the initrd are expected to be found. */
1998                 boot->hdr.ramdisk_image = mem - initrd_size;
1999                 boot->hdr.ramdisk_size = initrd_size;
2000                 /* The bootloader type 0xFF means "unknown"; that's OK. */
2001                 boot->hdr.type_of_loader = 0xFF;
2002         }
2003
2004         /* The Linux boot header contains an "E820" memory map: ours is a
2005          * simple, single region. */
2006         boot->e820_entries = 1;
2007         boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
2008         /* The boot header contains a command line pointer: we put the command
2009          * line after the boot header. */
2010         boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
2011         /* We use a simple helper to copy the arguments separated by spaces. */
2012         concat((char *)(boot + 1), argv+optind+2);
2013
2014         /* Boot protocol version: 2.07 supports the fields for lguest. */
2015         boot->hdr.version = 0x207;
2016
2017         /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
2018         boot->hdr.hardware_subarch = 1;
2019
2020         /* Tell the entry path not to try to reload segment registers. */
2021         boot->hdr.loadflags |= KEEP_SEGMENTS;
2022
2023         /* We tell the kernel to initialize the Guest: this returns the open
2024          * /dev/lguest file descriptor. */
2025         tell_kernel(start);
2026
2027         /* We clone off a thread, which wakes the Launcher whenever one of the
2028          * input file descriptors needs attention.  We call this the Waker, and
2029          * we'll cover it in a moment. */
2030         setup_waker();
2031
2032         /* Finally, run the Guest.  This doesn't return. */
2033         run_guest();
2034 }
2035 /*:*/
2036
2037 /*M:999
2038  * Mastery is done: you now know everything I do.
2039  *
2040  * But surely you have seen code, features and bugs in your wanderings which
2041  * you now yearn to attack?  That is the real game, and I look forward to you
2042  * patching and forking lguest into the Your-Name-Here-visor.
2043  *
2044  * Farewell, and good coding!
2045  * Rusty Russell.
2046  */