blob: e65d6cbf2419fd55d81008c9cbd139eb37a5f698 [file] [log] [blame]
Rusty Russellf938d2c2007-07-26 10:41:02 -07001/*P:100 This is the Launcher code, a simple program which lays out the
Rusty Russella6bd8e12008-03-28 11:05:53 -05002 * "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. :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07005#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>
Ronald G. Minnich6649bb72007-08-28 14:35:59 -070015#include <sys/param.h>
Rusty Russell8ca47e02007-07-19 01:49:29 -070016#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>
Rusty Russell17cbca22007-10-22 11:24:22 +100035#include <assert.h>
36#include <sched.h>
Rusty Russella586d4f2008-02-04 23:49:56 -050037#include <limits.h>
38#include <stddef.h>
Rusty Russella1618832008-07-29 09:58:35 -050039#include <signal.h>
Rusty Russellb45d8cb2007-10-22 10:56:24 +100040#include "linux/lguest_launcher.h"
Rusty Russell17cbca22007-10-22 11:24:22 +100041#include "linux/virtio_config.h"
42#include "linux/virtio_net.h"
43#include "linux/virtio_blk.h"
44#include "linux/virtio_console.h"
Rusty Russell28fd6d72008-07-29 09:58:33 -050045#include "linux/virtio_rng.h"
Rusty Russell17cbca22007-10-22 11:24:22 +100046#include "linux/virtio_ring.h"
Rusty Russelld5d02d62008-10-31 11:24:25 -050047#include "asm/bootparam.h"
Rusty Russella6bd8e12008-03-28 11:05:53 -050048/*L:110 We can ignore the 39 include files we need for this program, but I do
Rusty Russelldb24e8c2007-10-25 14:09:25 +100049 * 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. */
55typedef unsigned long long u64;
56typedef uint32_t u32;
57typedef uint16_t u16;
58typedef uint8_t u8;
Rusty Russelldde79782007-07-26 10:41:03 -070059/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070060
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
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100067/* We can have up to 256 pages for devices. */
68#define DEVICE_PAGES 256
Rusty Russell0f0c4fa2008-07-29 09:58:37 -050069/* This will occupy 3 pages: it must be a power of 2. */
70#define VIRTQUEUE_NUM 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070071
Rusty Russelldde79782007-07-26 10:41:03 -070072/*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. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070074static bool verbose;
75#define verbose(args...) \
76 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070077/*:*/
78
Rusty Russell8c798732008-07-29 09:58:38 -050079/* File descriptors for the Waker. */
80struct {
81 int pipe[2];
82 int lguest_fd;
83} waker_fds;
84
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100085/* The pointer to the start of guest memory. */
86static void *guest_base;
87/* The maximum guest physical address allowed, and maximum possible. */
88static unsigned long guest_limit, guest_max;
Rusty Russella1618832008-07-29 09:58:35 -050089/* The pipe for signal hander to write to. */
90static int timeoutpipe[2];
Rusty Russellaa124982008-07-29 09:58:36 -050091static unsigned int timeout_usec = 500;
Rusty Russell8ca47e02007-07-19 01:49:29 -070092
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -020093/* a per-cpu variable indicating whose vcpu is currently running */
94static unsigned int __thread cpu_id;
95
Rusty Russelldde79782007-07-26 10:41:03 -070096/* This is our list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070097struct device_list
98{
Rusty Russelldde79782007-07-26 10:41:03 -070099 /* Summary information about the devices in our list: ready to pass to
100 * select() to ask which need servicing.*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700101 fd_set infds;
102 int max_infd;
103
Rusty Russell17cbca22007-10-22 11:24:22 +1000104 /* Counter to assign interrupt numbers. */
105 unsigned int next_irq;
106
107 /* Counter to print out convenient device numbers. */
108 unsigned int device_num;
109
Rusty Russelldde79782007-07-26 10:41:03 -0700110 /* The descriptor page for the devices. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000111 u8 *descpage;
112
Rusty Russelldde79782007-07-26 10:41:03 -0700113 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700114 struct device *dev;
Rusty Russella586d4f2008-02-04 23:49:56 -0500115 /* And a pointer to the last device for easy append and also for
116 * configuration appending. */
117 struct device *lastdev;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700118};
119
Rusty Russell17cbca22007-10-22 11:24:22 +1000120/* The list of Guest devices, based on command line arguments. */
121static struct device_list devices;
122
Rusty Russelldde79782007-07-26 10:41:03 -0700123/* The device structure describes a single device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700124struct device
125{
Rusty Russelldde79782007-07-26 10:41:03 -0700126 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700127 struct device *next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000128
Rusty Russell713b15b2009-06-12 22:26:58 -0600129 /* The device's descriptor, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700130 struct lguest_device_desc *desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000131
Rusty Russell713b15b2009-06-12 22:26:58 -0600132 /* We can't trust desc values once Guest has booted: we use these. */
133 unsigned int feature_len;
134 unsigned int num_vq;
135
Rusty Russell17cbca22007-10-22 11:24:22 +1000136 /* The name of this device, for --verbose. */
137 const char *name;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700138
Rusty Russelldde79782007-07-26 10:41:03 -0700139 /* If handle_input is set, it wants to be called when this file
140 * descriptor is ready. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700141 int fd;
142 bool (*handle_input)(int fd, struct device *me);
143
Rusty Russell17cbca22007-10-22 11:24:22 +1000144 /* Any queues attached to this device */
145 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700146
Rusty Russella007a752008-05-02 21:50:53 -0500147 /* Handle status being finalized (ie. feature bits stable). */
148 void (*ready)(struct device *me);
149
Rusty Russell8ca47e02007-07-19 01:49:29 -0700150 /* Device-specific data. */
151 void *priv;
152};
153
Rusty Russell17cbca22007-10-22 11:24:22 +1000154/* The virtqueue structure describes a queue attached to a device. */
155struct virtqueue
156{
157 struct virtqueue *next;
158
159 /* Which device owns me. */
160 struct device *dev;
161
162 /* The configuration for this queue. */
163 struct lguest_vqconfig config;
164
165 /* The actual ring of buffers. */
166 struct vring vring;
167
168 /* Last available index we saw. */
169 u16 last_avail_idx;
170
Rusty Russella1618832008-07-29 09:58:35 -0500171 /* The routine to call when the Guest pings us, or timeout. */
172 void (*handle_output)(int fd, struct virtqueue *me, bool timeout);
Rusty Russell20887612008-05-30 15:09:46 -0500173
174 /* Outstanding buffers */
175 unsigned int inflight;
Rusty Russella1618832008-07-29 09:58:35 -0500176
177 /* Is this blocked awaiting a timer? */
178 bool blocked;
Rusty Russell17cbca22007-10-22 11:24:22 +1000179};
180
Balaji Raoec04b132007-12-28 14:26:24 +0530181/* Remember the arguments to the program so we can "reboot" */
182static char **main_args;
183
Rusty Russell17cbca22007-10-22 11:24:22 +1000184/* Since guest is UP and we don't run at the same time, we don't need barriers.
185 * But I include them in the code in case others copy it. */
186#define wmb()
187
188/* Convert an iovec element to the given type.
189 *
190 * This is a fairly ugly trick: we need to know the size of the type and
191 * alignment requirement to check the pointer is kosher. It's also nice to
192 * have the name of the type in case we report failure.
193 *
194 * Typing those three things all the time is cumbersome and error prone, so we
195 * have a macro which sets them all up and passes to the real function. */
196#define convert(iov, type) \
197 ((type *)_convert((iov), sizeof(type), __alignof__(type), #type))
198
199static void *_convert(struct iovec *iov, size_t size, size_t align,
200 const char *name)
201{
202 if (iov->iov_len != size)
203 errx(1, "Bad iovec size %zu for %s", iov->iov_len, name);
204 if ((unsigned long)iov->iov_base % align != 0)
205 errx(1, "Bad alignment %p for %s", iov->iov_base, name);
206 return iov->iov_base;
207}
208
Rusty Russellb5111792008-07-29 09:58:34 -0500209/* Wrapper for the last available index. Makes it easier to change. */
210#define lg_last_avail(vq) ((vq)->last_avail_idx)
211
Rusty Russell17cbca22007-10-22 11:24:22 +1000212/* The virtio configuration space is defined to be little-endian. x86 is
213 * little-endian too, but it's nice to be explicit so we have these helpers. */
214#define cpu_to_le16(v16) (v16)
215#define cpu_to_le32(v32) (v32)
216#define cpu_to_le64(v64) (v64)
217#define le16_to_cpu(v16) (v16)
218#define le32_to_cpu(v32) (v32)
Rusty Russella586d4f2008-02-04 23:49:56 -0500219#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000220
Rusty Russell28fd6d72008-07-29 09:58:33 -0500221/* Is this iovec empty? */
222static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
223{
224 unsigned int i;
225
226 for (i = 0; i < num_iov; i++)
227 if (iov[i].iov_len)
228 return false;
229 return true;
230}
231
232/* Take len bytes from the front of this iovec. */
233static void iov_consume(struct iovec iov[], unsigned num_iov, unsigned len)
234{
235 unsigned int i;
236
237 for (i = 0; i < num_iov; i++) {
238 unsigned int used;
239
240 used = iov[i].iov_len < len ? iov[i].iov_len : len;
241 iov[i].iov_base += used;
242 iov[i].iov_len -= used;
243 len -= used;
244 }
245 assert(len == 0);
246}
247
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500248/* The device virtqueue descriptors are followed by feature bitmasks. */
249static u8 *get_feature_bits(struct device *dev)
250{
251 return (u8 *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -0600252 + dev->num_vq * sizeof(struct lguest_vqconfig);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500253}
254
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000255/*L:100 The Launcher code itself takes us out into userspace, that scary place
256 * where pointers run wild and free! Unfortunately, like most userspace
257 * programs, it's quite boring (which is why everyone likes to hack on the
258 * kernel!). Perhaps if you make up an Lguest Drinking Game at this point, it
259 * will get you through this section. Or, maybe not.
260 *
261 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
262 * memory and stores it in "guest_base". In other words, Guest physical ==
263 * Launcher virtual with an offset.
264 *
265 * This can be tough to get your head around, but usually it just means that we
266 * use these trivial conversion functions when the Guest gives us it's
267 * "physical" addresses: */
268static void *from_guest_phys(unsigned long addr)
269{
270 return guest_base + addr;
271}
272
273static unsigned long to_guest_phys(const void *addr)
274{
275 return (addr - guest_base);
276}
277
Rusty Russelldde79782007-07-26 10:41:03 -0700278/*L:130
279 * Loading the Kernel.
280 *
281 * We start with couple of simple helper routines. open_or_die() avoids
282 * error-checking code cluttering the callers: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700283static int open_or_die(const char *name, int flags)
284{
285 int fd = open(name, flags);
286 if (fd < 0)
287 err(1, "Failed to open %s", name);
288 return fd;
289}
290
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000291/* map_zeroed_pages() takes a number of pages. */
292static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700293{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000294 int fd = open_or_die("/dev/zero", O_RDONLY);
295 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700296
Rusty Russelldde79782007-07-26 10:41:03 -0700297 /* We use a private mapping (ie. if we write to the page, it will be
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000298 * copied). */
299 addr = mmap(NULL, getpagesize() * num,
300 PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE, fd, 0);
301 if (addr == MAP_FAILED)
302 err(1, "Mmaping %u pages of /dev/zero", num);
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100303 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700304
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000305 return addr;
306}
307
308/* Get some more pages for a device. */
309static void *get_pages(unsigned int num)
310{
311 void *addr = from_guest_phys(guest_limit);
312
313 guest_limit += num * getpagesize();
314 if (guest_limit > guest_max)
315 errx(1, "Not enough memory for devices");
316 return addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700317}
318
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700319/* This routine is used to load the kernel or initrd. It tries mmap, but if
320 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
321 * it falls back to reading the memory in. */
322static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
323{
324 ssize_t r;
325
326 /* We map writable even though for some segments are marked read-only.
327 * The kernel really wants to be writable: it patches its own
328 * instructions.
329 *
330 * MAP_PRIVATE means that the page won't be copied until a write is
331 * done to it. This allows us to share untouched memory between
332 * Guests. */
333 if (mmap(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC,
334 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
335 return;
336
337 /* pread does a seek and a read in one shot: saves a few lines. */
338 r = pread(fd, addr, len, offset);
339 if (r != len)
340 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
341}
342
Rusty Russelldde79782007-07-26 10:41:03 -0700343/* This routine takes an open vmlinux image, which is in ELF, and maps it into
344 * the Guest memory. ELF = Embedded Linking Format, which is the format used
345 * by all modern binaries on Linux including the kernel.
346 *
347 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000348 * address. We use the physical address; the Guest will map itself to the
349 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700350 *
351 * We return the starting address. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000352static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700353{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700354 Elf32_Phdr phdr[ehdr->e_phnum];
355 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700356
Rusty Russelldde79782007-07-26 10:41:03 -0700357 /* Sanity checks on the main ELF header: an x86 executable with a
358 * reasonable number of correctly-sized program headers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700359 if (ehdr->e_type != ET_EXEC
360 || ehdr->e_machine != EM_386
361 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
362 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
363 errx(1, "Malformed elf header");
364
Rusty Russelldde79782007-07-26 10:41:03 -0700365 /* An ELF executable contains an ELF header and a number of "program"
366 * headers which indicate which parts ("segments") of the program to
367 * load where. */
368
369 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700370 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
371 err(1, "Seeking to program headers");
372 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
373 err(1, "Reading program headers");
374
Rusty Russelldde79782007-07-26 10:41:03 -0700375 /* Try all the headers: there are usually only three. A read-only one,
Rusty Russella6bd8e12008-03-28 11:05:53 -0500376 * a read-write one, and a "note" section which we don't load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700377 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700378 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700379 if (phdr[i].p_type != PT_LOAD)
380 continue;
381
382 verbose("Section %i: size %i addr %p\n",
383 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
384
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700385 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000386 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700387 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700388 }
389
Rusty Russell814a0e52007-10-22 11:29:44 +1000390 /* The entry point is given in the ELF header. */
391 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700392}
393
Rusty Russelldde79782007-07-26 10:41:03 -0700394/*L:150 A bzImage, unlike an ELF file, is not meant to be loaded. You're
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000395 * supposed to jump into it and it will unpack itself. We used to have to
396 * perform some hairy magic because the unpacking code scared me.
Rusty Russelldde79782007-07-26 10:41:03 -0700397 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000398 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
399 * a small patch to jump over the tricky bits in the Guest, so now we just read
400 * the funky header so we know where in the file to load, and away we go! */
Rusty Russell47436aa2007-10-22 11:03:36 +1000401static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700402{
Rusty Russell43d33b22007-10-22 11:29:57 +1000403 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000404 int r;
405 /* Modern bzImages get loaded at 1M. */
406 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700407
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000408 /* Go back to the start of the file and read the header. It should be
Uwe Hermann71cced62008-10-20 09:32:21 -0700409 * a Linux boot header (see Documentation/x86/i386/boot.txt) */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000410 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000411 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000412
Rusty Russell43d33b22007-10-22 11:29:57 +1000413 /* Inside the setup_hdr, we expect the magic "HdrS" */
414 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000415 errx(1, "This doesn't look like a bzImage to me");
416
Rusty Russell43d33b22007-10-22 11:29:57 +1000417 /* Skip over the extra sectors of the header. */
418 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000419
420 /* Now read everything into memory. in nice big chunks. */
421 while ((r = read(fd, p, 65536)) > 0)
422 p += r;
423
Rusty Russell43d33b22007-10-22 11:29:57 +1000424 /* Finally, code32_start tells us where to enter the kernel. */
425 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700426}
427
Rusty Russelldde79782007-07-26 10:41:03 -0700428/*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000429 * come wrapped up in the self-decompressing "bzImage" format. With a little
430 * work, we can load those, too. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000431static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700432{
433 Elf32_Ehdr hdr;
434
Rusty Russelldde79782007-07-26 10:41:03 -0700435 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700436 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
437 err(1, "Reading kernel");
438
Rusty Russelldde79782007-07-26 10:41:03 -0700439 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700440 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000441 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700442
Rusty Russella6bd8e12008-03-28 11:05:53 -0500443 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000444 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700445}
446
Rusty Russelldde79782007-07-26 10:41:03 -0700447/* This is a trivial little helper to align pages. Andi Kleen hated it because
448 * it calls getpagesize() twice: "it's dumb code."
449 *
450 * Kernel guys get really het up about optimization, even when it's not
451 * necessary. I leave this code as a reaction against that. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700452static inline unsigned long page_align(unsigned long addr)
453{
Rusty Russelldde79782007-07-26 10:41:03 -0700454 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700455 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
456}
457
Rusty Russelldde79782007-07-26 10:41:03 -0700458/*L:180 An "initial ram disk" is a disk image loaded into memory along with
459 * the kernel which the kernel can use to boot from without needing any
460 * drivers. Most distributions now use this as standard: the initrd contains
461 * the code to load the appropriate driver modules for the current machine.
462 *
463 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
464 * kernels. He sent me this (and tells me when I break it). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700465static unsigned long load_initrd(const char *name, unsigned long mem)
466{
467 int ifd;
468 struct stat st;
469 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700470
471 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700472 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700473 if (fstat(ifd, &st) < 0)
474 err(1, "fstat() on initrd '%s'", name);
475
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700476 /* We map the initrd at the top of memory, but mmap wants it to be
477 * page-aligned, so we round the size up for that. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700478 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000479 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russelldde79782007-07-26 10:41:03 -0700480 /* Once a file is mapped, you can close the file descriptor. It's a
481 * little odd, but quite useful. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700482 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700483 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700484
485 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700486 return len;
487}
Rusty Russelle1e72962007-10-25 15:02:50 +1000488/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700489
Rusty Russelldde79782007-07-26 10:41:03 -0700490/* Simple routine to roll all the commandline arguments together with spaces
491 * between them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700492static void concat(char *dst, char *args[])
493{
494 unsigned int i, len = 0;
495
496 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100497 if (i) {
498 strcat(dst+len, " ");
499 len++;
500 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700501 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100502 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700503 }
504 /* In case it's empty. */
505 dst[len] = '\0';
506}
507
Rusty Russelle1e72962007-10-25 15:02:50 +1000508/*L:185 This is where we actually tell the kernel to initialize the Guest. We
509 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300510 * the base of Guest "physical" memory, the top physical page to allow and the
511 * entry point for the Guest. */
512static int tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700513{
Jes Sorensen511801d2007-10-22 11:03:31 +1000514 unsigned long args[] = { LHREQ_INITIALIZE,
515 (unsigned long)guest_base,
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300516 guest_limit / getpagesize(), start };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700517 int fd;
518
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000519 verbose("Guest: %p - %p (%#lx)\n",
520 guest_base, guest_base + guest_limit, guest_limit);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700521 fd = open_or_die("/dev/lguest", O_RDWR);
522 if (write(fd, args, sizeof(args)) < 0)
523 err(1, "Writing to /dev/lguest");
Rusty Russelldde79782007-07-26 10:41:03 -0700524
525 /* We return the /dev/lguest file descriptor to control this Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700526 return fd;
527}
Rusty Russelldde79782007-07-26 10:41:03 -0700528/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700529
Rusty Russell17cbca22007-10-22 11:24:22 +1000530static void add_device_fd(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700531{
Rusty Russell17cbca22007-10-22 11:24:22 +1000532 FD_SET(fd, &devices.infds);
533 if (fd > devices.max_infd)
534 devices.max_infd = fd;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700535}
536
Rusty Russelldde79782007-07-26 10:41:03 -0700537/*L:200
538 * The Waker.
539 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000540 * With console, block and network devices, we can have lots of input which we
541 * need to process. We could try to tell the kernel what file descriptors to
542 * watch, but handing a file descriptor mask through to the kernel is fairly
543 * icky.
Rusty Russelldde79782007-07-26 10:41:03 -0700544 *
Rusty Russell8c798732008-07-29 09:58:38 -0500545 * Instead, we clone off a thread which watches the file descriptors and writes
Rusty Russelle1e72962007-10-25 15:02:50 +1000546 * the LHREQ_BREAK command to the /dev/lguest file descriptor to tell the Host
547 * stop running the Guest. This causes the Launcher to return from the
Rusty Russelldde79782007-07-26 10:41:03 -0700548 * /dev/lguest read with -EAGAIN, where it will write to /dev/lguest to reset
549 * the LHREQ_BREAK and wake us up again.
550 *
551 * This, of course, is merely a different *kind* of icky.
Rusty Russell8c798732008-07-29 09:58:38 -0500552 *
553 * Given my well-known antipathy to threads, I'd prefer to use processes. But
554 * it's easier to share Guest memory with threads, and trivial to share the
555 * devices.infds as the Launcher changes it.
Rusty Russelldde79782007-07-26 10:41:03 -0700556 */
Rusty Russell8c798732008-07-29 09:58:38 -0500557static int waker(void *unused)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700558{
Rusty Russell8c798732008-07-29 09:58:38 -0500559 /* Close the write end of the pipe: only the Launcher has it open. */
560 close(waker_fds.pipe[1]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700561
562 for (;;) {
Rusty Russell17cbca22007-10-22 11:24:22 +1000563 fd_set rfds = devices.infds;
Jes Sorensen511801d2007-10-22 11:03:31 +1000564 unsigned long args[] = { LHREQ_BREAK, 1 };
Rusty Russell8c798732008-07-29 09:58:38 -0500565 unsigned int maxfd = devices.max_infd;
566
567 /* We also listen to the pipe from the Launcher. */
568 FD_SET(waker_fds.pipe[0], &rfds);
569 if (waker_fds.pipe[0] > maxfd)
570 maxfd = waker_fds.pipe[0];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700571
Rusty Russelldde79782007-07-26 10:41:03 -0700572 /* Wait until input is ready from one of the devices. */
Rusty Russell8c798732008-07-29 09:58:38 -0500573 select(maxfd+1, &rfds, NULL, NULL, NULL);
574
575 /* Message from Launcher? */
576 if (FD_ISSET(waker_fds.pipe[0], &rfds)) {
577 char c;
578 /* If this fails, then assume Launcher has exited.
579 * Don't do anything on exit: we're just a thread! */
580 if (read(waker_fds.pipe[0], &c, 1) != 1)
581 _exit(0);
582 continue;
583 }
584
585 /* Send LHREQ_BREAK command to snap the Launcher out of it. */
586 pwrite(waker_fds.lguest_fd, args, sizeof(args), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700587 }
Rusty Russell8c798732008-07-29 09:58:38 -0500588 return 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700589}
590
Rusty Russelldde79782007-07-26 10:41:03 -0700591/* This routine just sets up a pipe to the Waker process. */
Rusty Russell8c798732008-07-29 09:58:38 -0500592static void setup_waker(int lguest_fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700593{
Rusty Russell8c798732008-07-29 09:58:38 -0500594 /* This pipe is closed when Launcher dies, telling Waker. */
595 if (pipe(waker_fds.pipe) != 0)
596 err(1, "Creating pipe for Waker");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700597
Rusty Russell8c798732008-07-29 09:58:38 -0500598 /* Waker also needs to know the lguest fd */
599 waker_fds.lguest_fd = lguest_fd;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700600
Rusty Russell8c798732008-07-29 09:58:38 -0500601 if (clone(waker, malloc(4096) + 4096, CLONE_VM | SIGCHLD, NULL) == -1)
602 err(1, "Creating Waker");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700603}
604
Rusty Russelle1e72962007-10-25 15:02:50 +1000605/*
Rusty Russelldde79782007-07-26 10:41:03 -0700606 * Device Handling.
607 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000608 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700609 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000610 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700611 * if something funny is going on:
612 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700613static void *_check_pointer(unsigned long addr, unsigned int size,
614 unsigned int line)
615{
Rusty Russelldde79782007-07-26 10:41:03 -0700616 /* We have to separately check addr and addr+size, because size could
617 * be huge and addr + size might wrap around. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000618 if (addr >= guest_limit || addr + size >= guest_limit)
Rusty Russell17cbca22007-10-22 11:24:22 +1000619 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russelldde79782007-07-26 10:41:03 -0700620 /* We return a pointer for the caller's convenience, now we know it's
621 * safe to use. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000622 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700623}
Rusty Russelldde79782007-07-26 10:41:03 -0700624/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700625#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
626
Rusty Russelle1e72962007-10-25 15:02:50 +1000627/* Each buffer in the virtqueues is actually a chain of descriptors. This
628 * function returns the next descriptor in the chain, or vq->vring.num if we're
629 * at the end. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000630static unsigned next_desc(struct virtqueue *vq, unsigned int i)
631{
632 unsigned int next;
633
634 /* If this descriptor says it doesn't chain, we're done. */
635 if (!(vq->vring.desc[i].flags & VRING_DESC_F_NEXT))
636 return vq->vring.num;
637
638 /* Check they're not leading us off end of descriptors. */
639 next = vq->vring.desc[i].next;
640 /* Make sure compiler knows to grab that: we don't want it changing! */
641 wmb();
642
643 if (next >= vq->vring.num)
644 errx(1, "Desc next is %u", next);
645
646 return next;
647}
648
649/* This looks in the virtqueue and for the first available buffer, and converts
650 * it to an iovec for convenient access. Since descriptors consist of some
651 * number of output then some number of input descriptors, it's actually two
652 * iovecs, but we pack them into one and note how many of each there were.
653 *
654 * This function returns the descriptor number found, or vq->vring.num (which
655 * is never a valid descriptor number) if none was found. */
656static unsigned get_vq_desc(struct virtqueue *vq,
657 struct iovec iov[],
658 unsigned int *out_num, unsigned int *in_num)
659{
660 unsigned int i, head;
Rusty Russellb5111792008-07-29 09:58:34 -0500661 u16 last_avail;
Rusty Russell17cbca22007-10-22 11:24:22 +1000662
663 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500664 last_avail = lg_last_avail(vq);
665 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000666 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500667 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000668
669 /* If there's nothing new since last we looked, return invalid. */
Rusty Russellb5111792008-07-29 09:58:34 -0500670 if (vq->vring.avail->idx == last_avail)
Rusty Russell17cbca22007-10-22 11:24:22 +1000671 return vq->vring.num;
672
673 /* Grab the next descriptor number they're advertising, and increment
674 * the index we've seen. */
Rusty Russellb5111792008-07-29 09:58:34 -0500675 head = vq->vring.avail->ring[last_avail % vq->vring.num];
676 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000677
678 /* If their number is silly, that's a fatal mistake. */
679 if (head >= vq->vring.num)
680 errx(1, "Guest says index %u is available", head);
681
682 /* When we start there are none of either input nor output. */
683 *out_num = *in_num = 0;
684
685 i = head;
686 do {
687 /* Grab the first descriptor, and check it's OK. */
688 iov[*out_num + *in_num].iov_len = vq->vring.desc[i].len;
689 iov[*out_num + *in_num].iov_base
690 = check_pointer(vq->vring.desc[i].addr,
691 vq->vring.desc[i].len);
692 /* If this is an input descriptor, increment that count. */
693 if (vq->vring.desc[i].flags & VRING_DESC_F_WRITE)
694 (*in_num)++;
695 else {
696 /* If it's an output descriptor, they're all supposed
697 * to come before any input descriptors. */
698 if (*in_num)
699 errx(1, "Descriptor has out after in");
700 (*out_num)++;
701 }
702
703 /* If we've got too many, that implies a descriptor loop. */
704 if (*out_num + *in_num > vq->vring.num)
705 errx(1, "Looped descriptor");
706 } while ((i = next_desc(vq, i)) != vq->vring.num);
707
Rusty Russell20887612008-05-30 15:09:46 -0500708 vq->inflight++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000709 return head;
710}
711
Rusty Russelle1e72962007-10-25 15:02:50 +1000712/* After we've used one of their buffers, we tell them about it. We'll then
Rusty Russell17cbca22007-10-22 11:24:22 +1000713 * want to send them an interrupt, using trigger_irq(). */
714static void add_used(struct virtqueue *vq, unsigned int head, int len)
715{
716 struct vring_used_elem *used;
717
Rusty Russelle1e72962007-10-25 15:02:50 +1000718 /* The virtqueue contains a ring of used buffers. Get a pointer to the
719 * next entry in that used ring. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000720 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
721 used->id = head;
722 used->len = len;
723 /* Make sure buffer is written before we update index. */
724 wmb();
725 vq->vring.used->idx++;
Rusty Russell20887612008-05-30 15:09:46 -0500726 vq->inflight--;
Rusty Russell17cbca22007-10-22 11:24:22 +1000727}
728
729/* This actually sends the interrupt for this virtqueue */
730static void trigger_irq(int fd, struct virtqueue *vq)
731{
732 unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
733
Rusty Russell20887612008-05-30 15:09:46 -0500734 /* If they don't want an interrupt, don't send one, unless empty. */
735 if ((vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)
736 && vq->inflight)
Rusty Russell17cbca22007-10-22 11:24:22 +1000737 return;
738
739 /* Send the Guest an interrupt tell them we used something up. */
740 if (write(fd, buf, sizeof(buf)) != 0)
741 err(1, "Triggering irq %i", vq->config.irq);
742}
743
744/* And here's the combo meal deal. Supersize me! */
745static void add_used_and_trigger(int fd, struct virtqueue *vq,
746 unsigned int head, int len)
747{
748 add_used(vq, head, len);
749 trigger_irq(fd, vq);
750}
751
Rusty Russelle1e72962007-10-25 15:02:50 +1000752/*
753 * The Console
754 *
755 * Here is the input terminal setting we save, and the routine to restore them
756 * on exit so the user gets their terminal back. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700757static struct termios orig_term;
758static void restore_term(void)
759{
760 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
761}
762
Rusty Russelldde79782007-07-26 10:41:03 -0700763/* We associate some data with the console for our exit hack. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700764struct console_abort
765{
Rusty Russelldde79782007-07-26 10:41:03 -0700766 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700767 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700768 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700769 struct timeval start;
770};
771
Rusty Russelldde79782007-07-26 10:41:03 -0700772/* This is the routine which handles console input (ie. stdin). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700773static bool handle_console_input(int fd, struct device *dev)
774{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700775 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000776 unsigned int head, in_num, out_num;
777 struct iovec iov[dev->vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700778 struct console_abort *abort = dev->priv;
779
Rusty Russell17cbca22007-10-22 11:24:22 +1000780 /* First we need a console buffer from the Guests's input virtqueue. */
781 head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000782
783 /* If they're not ready for input, stop listening to this file
784 * descriptor. We'll start again once they add an input buffer. */
785 if (head == dev->vq->vring.num)
786 return false;
787
788 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000789 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700790
Rusty Russelldde79782007-07-26 10:41:03 -0700791 /* This is why we convert to iovecs: the readv() call uses them, and so
792 * it reads straight into the Guest's buffer. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000793 len = readv(dev->fd, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700794 if (len <= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700795 /* This implies that the console is closed, is /dev/null, or
Rusty Russell17cbca22007-10-22 11:24:22 +1000796 * something went terribly wrong. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700797 warnx("Failed to get console input, ignoring console.");
Rusty Russell56ae43d2007-10-22 11:24:23 +1000798 /* Put the input terminal back. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000799 restore_term();
Rusty Russell56ae43d2007-10-22 11:24:23 +1000800 /* Remove callback from input vq, so it doesn't restart us. */
801 dev->vq->handle_output = NULL;
802 /* Stop listening to this fd: don't call us again. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000803 return false;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700804 }
805
Rusty Russell56ae43d2007-10-22 11:24:23 +1000806 /* Tell the Guest about the new input. */
807 add_used_and_trigger(fd, dev->vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700808
Rusty Russelldde79782007-07-26 10:41:03 -0700809 /* Three ^C within one second? Exit.
810 *
811 * This is such a hack, but works surprisingly well. Each ^C has to be
812 * in a buffer by itself, so they can't be too fast. But we check that
813 * we get three within about a second, so they can't be too slow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700814 if (len == 1 && ((char *)iov[0].iov_base)[0] == 3) {
815 if (!abort->count++)
816 gettimeofday(&abort->start, NULL);
817 else if (abort->count == 3) {
818 struct timeval now;
819 gettimeofday(&now, NULL);
820 if (now.tv_sec <= abort->start.tv_sec+1) {
Jes Sorensen511801d2007-10-22 11:03:31 +1000821 unsigned long args[] = { LHREQ_BREAK, 0 };
Rusty Russelldde79782007-07-26 10:41:03 -0700822 /* Close the fd so Waker will know it has to
823 * exit. */
Rusty Russell8c798732008-07-29 09:58:38 -0500824 close(waker_fds.pipe[1]);
825 /* Just in case Waker is blocked in BREAK, send
Rusty Russelldde79782007-07-26 10:41:03 -0700826 * unbreak now. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700827 write(fd, args, sizeof(args));
828 exit(2);
829 }
830 abort->count = 0;
831 }
832 } else
Rusty Russelldde79782007-07-26 10:41:03 -0700833 /* Any other key resets the abort counter. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700834 abort->count = 0;
835
Rusty Russelldde79782007-07-26 10:41:03 -0700836 /* Everything went OK! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700837 return true;
838}
839
Rusty Russell17cbca22007-10-22 11:24:22 +1000840/* Handling output for console is simple: we just get all the output buffers
841 * and write them to stdout. */
Rusty Russella1618832008-07-29 09:58:35 -0500842static void handle_console_output(int fd, struct virtqueue *vq, bool timeout)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700843{
Rusty Russell17cbca22007-10-22 11:24:22 +1000844 unsigned int head, out, in;
845 int len;
846 struct iovec iov[vq->vring.num];
847
848 /* Keep getting output buffers from the Guest until we run out. */
849 while ((head = get_vq_desc(vq, iov, &out, &in)) != vq->vring.num) {
850 if (in)
851 errx(1, "Input buffers in output queue?");
852 len = writev(STDOUT_FILENO, iov, out);
853 add_used_and_trigger(fd, vq, head, len);
854 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700855}
856
Rusty Russell1dc3e3b2008-08-26 00:19:27 -0500857/* This is called when we no longer want to hear about Guest changes to a
858 * virtqueue. This is more efficient in high-traffic cases, but it means we
859 * have to set a timer to check if any more changes have occurred. */
Rusty Russella1618832008-07-29 09:58:35 -0500860static void block_vq(struct virtqueue *vq)
861{
862 struct itimerval itm;
863
864 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
865 vq->blocked = true;
866
867 itm.it_interval.tv_sec = 0;
868 itm.it_interval.tv_usec = 0;
869 itm.it_value.tv_sec = 0;
Rusty Russellaa124982008-07-29 09:58:36 -0500870 itm.it_value.tv_usec = timeout_usec;
Rusty Russella1618832008-07-29 09:58:35 -0500871
872 setitimer(ITIMER_REAL, &itm, NULL);
873}
874
Rusty Russelle1e72962007-10-25 15:02:50 +1000875/*
876 * The Network
877 *
878 * Handling output for network is also simple: we get all the output buffers
Rusty Russell17cbca22007-10-22 11:24:22 +1000879 * and write them (ignoring the first element) to this device's file descriptor
Rusty Russella6bd8e12008-03-28 11:05:53 -0500880 * (/dev/net/tun).
881 */
Rusty Russella1618832008-07-29 09:58:35 -0500882static void handle_net_output(int fd, struct virtqueue *vq, bool timeout)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700883{
Rusty Russella1618832008-07-29 09:58:35 -0500884 unsigned int head, out, in, num = 0;
Rusty Russell17cbca22007-10-22 11:24:22 +1000885 int len;
886 struct iovec iov[vq->vring.num];
Rusty Russellaa124982008-07-29 09:58:36 -0500887 static int last_timeout_num;
Rusty Russell17cbca22007-10-22 11:24:22 +1000888
889 /* Keep getting output buffers from the Guest until we run out. */
890 while ((head = get_vq_desc(vq, iov, &out, &in)) != vq->vring.num) {
891 if (in)
892 errx(1, "Input buffers in output queue?");
Rusty Russell398f1872008-07-29 09:58:37 -0500893 len = writev(vq->dev->fd, iov, out);
894 if (len < 0)
895 err(1, "Writing network packet to tun");
Rusty Russell17cbca22007-10-22 11:24:22 +1000896 add_used_and_trigger(fd, vq, head, len);
Rusty Russella1618832008-07-29 09:58:35 -0500897 num++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000898 }
Rusty Russella1618832008-07-29 09:58:35 -0500899
900 /* Block further kicks and set up a timer if we saw anything. */
901 if (!timeout && num)
902 block_vq(vq);
Rusty Russellaa124982008-07-29 09:58:36 -0500903
Rusty Russell1dc3e3b2008-08-26 00:19:27 -0500904 /* We never quite know how long should we wait before we check the
905 * queue again for more packets. We start at 500 microseconds, and if
906 * we get fewer packets than last time, we assume we made the timeout
907 * too small and increase it by 10 microseconds. Otherwise, we drop it
908 * by one microsecond every time. It seems to work well enough. */
Rusty Russellaa124982008-07-29 09:58:36 -0500909 if (timeout) {
910 if (num < last_timeout_num)
911 timeout_usec += 10;
912 else if (timeout_usec > 1)
913 timeout_usec--;
914 last_timeout_num = num;
915 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700916}
917
Rusty Russell17cbca22007-10-22 11:24:22 +1000918/* This is where we handle a packet coming in from the tun device to our
919 * Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700920static bool handle_tun_input(int fd, struct device *dev)
921{
Rusty Russell17cbca22007-10-22 11:24:22 +1000922 unsigned int head, in_num, out_num;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700923 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000924 struct iovec iov[dev->vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700925
Rusty Russell17cbca22007-10-22 11:24:22 +1000926 /* First we need a network buffer from the Guests's recv virtqueue. */
927 head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
928 if (head == dev->vq->vring.num) {
Rusty Russelldde79782007-07-26 10:41:03 -0700929 /* Now, it's expected that if we try to send a packet too
Rusty Russell17cbca22007-10-22 11:24:22 +1000930 * early, the Guest won't be ready yet. Wait until the device
931 * status says it's ready. */
932 /* FIXME: Actually want DRIVER_ACTIVE here. */
Rusty Russell5dae7852008-07-29 09:58:35 -0500933
934 /* Now tell it we want to know if new things appear. */
935 dev->vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
936 wmb();
937
Rusty Russell56ae43d2007-10-22 11:24:23 +1000938 /* We'll turn this back on if input buffers are registered. */
939 return false;
Rusty Russell17cbca22007-10-22 11:24:22 +1000940 } else if (out_num)
941 errx(1, "Output buffers in network recv queue?");
942
Rusty Russelldde79782007-07-26 10:41:03 -0700943 /* Read the packet from the device directly into the Guest's buffer. */
Rusty Russell398f1872008-07-29 09:58:37 -0500944 len = readv(dev->fd, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700945 if (len <= 0)
946 err(1, "reading network");
Rusty Russelldde79782007-07-26 10:41:03 -0700947
Rusty Russell56ae43d2007-10-22 11:24:23 +1000948 /* Tell the Guest about the new packet. */
Rusty Russell398f1872008-07-29 09:58:37 -0500949 add_used_and_trigger(fd, dev->vq, head, len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000950
Rusty Russell8ca47e02007-07-19 01:49:29 -0700951 verbose("tun input packet len %i [%02x %02x] (%s)\n", len,
Rusty Russell17cbca22007-10-22 11:24:22 +1000952 ((u8 *)iov[1].iov_base)[0], ((u8 *)iov[1].iov_base)[1],
953 head != dev->vq->vring.num ? "sent" : "discarded");
954
Rusty Russelldde79782007-07-26 10:41:03 -0700955 /* All good. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700956 return true;
957}
958
Rusty Russelle1e72962007-10-25 15:02:50 +1000959/*L:215 This is the callback attached to the network and console input
960 * virtqueues: it ensures we try again, in case we stopped console or net
Rusty Russell56ae43d2007-10-22 11:24:23 +1000961 * delivery because Guest didn't have any buffers. */
Rusty Russella1618832008-07-29 09:58:35 -0500962static void enable_fd(int fd, struct virtqueue *vq, bool timeout)
Rusty Russell56ae43d2007-10-22 11:24:23 +1000963{
964 add_device_fd(vq->dev->fd);
Rusty Russell8c798732008-07-29 09:58:38 -0500965 /* Snap the Waker out of its select loop. */
966 write(waker_fds.pipe[1], "", 1);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000967}
968
Rusty Russella1618832008-07-29 09:58:35 -0500969static void net_enable_fd(int fd, struct virtqueue *vq, bool timeout)
Rusty Russell5dae7852008-07-29 09:58:35 -0500970{
971 /* We don't need to know again when Guest refills receive buffer. */
972 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russella1618832008-07-29 09:58:35 -0500973 enable_fd(fd, vq, timeout);
Rusty Russell5dae7852008-07-29 09:58:35 -0500974}
975
Rusty Russella007a752008-05-02 21:50:53 -0500976/* When the Guest tells us they updated the status field, we handle it. */
977static void update_device_status(struct device *dev)
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500978{
979 struct virtqueue *vq;
980
Rusty Russella007a752008-05-02 21:50:53 -0500981 /* This is a reset. */
982 if (dev->desc->status == 0) {
983 verbose("Resetting device %s\n", dev->name);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500984
Rusty Russella007a752008-05-02 21:50:53 -0500985 /* Clear any features they've acked. */
Rusty Russell713b15b2009-06-12 22:26:58 -0600986 memset(get_feature_bits(dev) + dev->feature_len, 0,
987 dev->feature_len);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500988
Rusty Russella007a752008-05-02 21:50:53 -0500989 /* Zero out the virtqueues. */
990 for (vq = dev->vq; vq; vq = vq->next) {
991 memset(vq->vring.desc, 0,
Rusty Russell2966af72008-12-30 09:25:58 -0600992 vring_size(vq->config.num, LGUEST_VRING_ALIGN));
Rusty Russellb5111792008-07-29 09:58:34 -0500993 lg_last_avail(vq) = 0;
Rusty Russella007a752008-05-02 21:50:53 -0500994 }
995 } else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
996 warnx("Device %s configuration FAILED", dev->name);
997 } else if (dev->desc->status & VIRTIO_CONFIG_S_DRIVER_OK) {
998 unsigned int i;
999
1000 verbose("Device %s OK: offered", dev->name);
Rusty Russell713b15b2009-06-12 22:26:58 -06001001 for (i = 0; i < dev->feature_len; i++)
Rusty Russell32c68e52008-07-29 09:58:32 -05001002 verbose(" %02x", get_feature_bits(dev)[i]);
Rusty Russella007a752008-05-02 21:50:53 -05001003 verbose(", accepted");
Rusty Russell713b15b2009-06-12 22:26:58 -06001004 for (i = 0; i < dev->feature_len; i++)
Rusty Russell32c68e52008-07-29 09:58:32 -05001005 verbose(" %02x", get_feature_bits(dev)
Rusty Russell713b15b2009-06-12 22:26:58 -06001006 [dev->feature_len+i]);
Rusty Russella007a752008-05-02 21:50:53 -05001007
1008 if (dev->ready)
1009 dev->ready(dev);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001010 }
1011}
1012
Rusty Russell17cbca22007-10-22 11:24:22 +10001013/* This is the generic routine we call when the Guest uses LHCALL_NOTIFY. */
1014static void handle_output(int fd, unsigned long addr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001015{
1016 struct device *i;
Rusty Russell17cbca22007-10-22 11:24:22 +10001017 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001018
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001019 /* Check each device and virtqueue. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001020 for (i = devices.dev; i; i = i->next) {
Rusty Russella007a752008-05-02 21:50:53 -05001021 /* Notifications to device descriptors update device status. */
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001022 if (from_guest_phys(addr) == i->desc) {
Rusty Russella007a752008-05-02 21:50:53 -05001023 update_device_status(i);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001024 return;
1025 }
1026
1027 /* Notifications to virtqueues mean output has occurred. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001028 for (vq = i->vq; vq; vq = vq->next) {
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001029 if (vq->config.pfn != addr/getpagesize())
1030 continue;
1031
1032 /* Guest should acknowledge (and set features!) before
1033 * using the device. */
1034 if (i->desc->status == 0) {
1035 warnx("%s gave early output", i->name);
Rusty Russell17cbca22007-10-22 11:24:22 +10001036 return;
1037 }
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001038
1039 if (strcmp(vq->dev->name, "console") != 0)
1040 verbose("Output to %s\n", vq->dev->name);
1041 if (vq->handle_output)
Rusty Russella1618832008-07-29 09:58:35 -05001042 vq->handle_output(fd, vq, false);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001043 return;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001044 }
1045 }
Rusty Russelldde79782007-07-26 10:41:03 -07001046
Rusty Russell17cbca22007-10-22 11:24:22 +10001047 /* Early console write is done using notify on a nul-terminated string
1048 * in Guest memory. */
1049 if (addr >= guest_limit)
1050 errx(1, "Bad NOTIFY %#lx", addr);
1051
1052 write(STDOUT_FILENO, from_guest_phys(addr),
1053 strnlen(from_guest_phys(addr), guest_limit - addr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001054}
1055
Rusty Russella1618832008-07-29 09:58:35 -05001056static void handle_timeout(int fd)
1057{
1058 char buf[32];
1059 struct device *i;
1060 struct virtqueue *vq;
1061
1062 /* Clear the pipe */
1063 read(timeoutpipe[0], buf, sizeof(buf));
1064
1065 /* Check each device and virtqueue: flush blocked ones. */
1066 for (i = devices.dev; i; i = i->next) {
1067 for (vq = i->vq; vq; vq = vq->next) {
1068 if (!vq->blocked)
1069 continue;
1070
1071 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
1072 vq->blocked = false;
1073 if (vq->handle_output)
1074 vq->handle_output(fd, vq, true);
1075 }
1076 }
1077}
1078
Rusty Russelle1e72962007-10-25 15:02:50 +10001079/* This is called when the Waker wakes us up: check for incoming file
Rusty Russelldde79782007-07-26 10:41:03 -07001080 * descriptors. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001081static void handle_input(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001082{
Rusty Russelldde79782007-07-26 10:41:03 -07001083 /* select() wants a zeroed timeval to mean "don't wait". */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001084 struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
1085
1086 for (;;) {
1087 struct device *i;
Rusty Russell17cbca22007-10-22 11:24:22 +10001088 fd_set fds = devices.infds;
Rusty Russella1618832008-07-29 09:58:35 -05001089 int num;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001090
Rusty Russella1618832008-07-29 09:58:35 -05001091 num = select(devices.max_infd+1, &fds, NULL, NULL, &poll);
1092 /* Could get interrupted */
1093 if (num < 0)
1094 continue;
Rusty Russelldde79782007-07-26 10:41:03 -07001095 /* If nothing is ready, we're done. */
Rusty Russella1618832008-07-29 09:58:35 -05001096 if (num == 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001097 break;
1098
Rusty Russella6bd8e12008-03-28 11:05:53 -05001099 /* Otherwise, call the device(s) which have readable file
1100 * descriptors and a method of handling them. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001101 for (i = devices.dev; i; i = i->next) {
Rusty Russell8ca47e02007-07-19 01:49:29 -07001102 if (i->handle_input && FD_ISSET(i->fd, &fds)) {
Rusty Russell56ae43d2007-10-22 11:24:23 +10001103 if (i->handle_input(fd, i))
1104 continue;
1105
Rusty Russelldde79782007-07-26 10:41:03 -07001106 /* If handle_input() returns false, it means we
Rusty Russell56ae43d2007-10-22 11:24:23 +10001107 * should no longer service it. Networking and
1108 * console do this when there's no input
1109 * buffers to deliver into. Console also uses
Rusty Russella6bd8e12008-03-28 11:05:53 -05001110 * it when it discovers that stdin is closed. */
Rusty Russell56ae43d2007-10-22 11:24:23 +10001111 FD_CLR(i->fd, &devices.infds);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001112 }
1113 }
Rusty Russella1618832008-07-29 09:58:35 -05001114
1115 /* Is this the timeout fd? */
1116 if (FD_ISSET(timeoutpipe[0], &fds))
1117 handle_timeout(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001118 }
1119}
1120
Rusty Russelldde79782007-07-26 10:41:03 -07001121/*L:190
1122 * Device Setup
1123 *
1124 * All devices need a descriptor so the Guest knows it exists, and a "struct
1125 * device" so the Launcher can keep track of it. We have common helper
Rusty Russella6bd8e12008-03-28 11:05:53 -05001126 * routines to allocate and manage them.
1127 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001128
1129/* The layout of the device page is a "struct lguest_device_desc" followed by a
1130 * number of virtqueue descriptors, then two sets of feature bits, then an
1131 * array of configuration bytes. This routine returns the configuration
1132 * pointer. */
1133static u8 *device_config(const struct device *dev)
1134{
1135 return (void *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -06001136 + dev->num_vq * sizeof(struct lguest_vqconfig)
1137 + dev->feature_len * 2;
Rusty Russella586d4f2008-02-04 23:49:56 -05001138}
1139
1140/* This routine allocates a new "struct lguest_device_desc" from descriptor
1141 * table page just above the Guest's normal memory. It returns a pointer to
1142 * that descriptor. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001143static struct lguest_device_desc *new_dev_desc(u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001144{
Rusty Russella586d4f2008-02-04 23:49:56 -05001145 struct lguest_device_desc d = { .type = type };
1146 void *p;
1147
1148 /* Figure out where the next device config is, based on the last one. */
1149 if (devices.lastdev)
1150 p = device_config(devices.lastdev)
1151 + devices.lastdev->desc->config_len;
1152 else
1153 p = devices.descpage;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001154
Rusty Russell17cbca22007-10-22 11:24:22 +10001155 /* We only have one page for all the descriptors. */
Rusty Russella586d4f2008-02-04 23:49:56 -05001156 if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
Rusty Russell17cbca22007-10-22 11:24:22 +10001157 errx(1, "Too many devices");
1158
Rusty Russella586d4f2008-02-04 23:49:56 -05001159 /* p might not be aligned, so we memcpy in. */
1160 return memcpy(p, &d, sizeof(d));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001161}
1162
Rusty Russella586d4f2008-02-04 23:49:56 -05001163/* Each device descriptor is followed by the description of its virtqueues. We
1164 * specify how many descriptors the virtqueue is to have. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001165static void add_virtqueue(struct device *dev, unsigned int num_descs,
Rusty Russella1618832008-07-29 09:58:35 -05001166 void (*handle_output)(int, struct virtqueue *, bool))
Rusty Russell17cbca22007-10-22 11:24:22 +10001167{
1168 unsigned int pages;
1169 struct virtqueue **i, *vq = malloc(sizeof(*vq));
1170 void *p;
1171
Rusty Russella6bd8e12008-03-28 11:05:53 -05001172 /* First we need some memory for this virtqueue. */
Rusty Russell2966af72008-12-30 09:25:58 -06001173 pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
Rusty Russell42b36cc2007-11-12 13:39:18 +11001174 / getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10001175 p = get_pages(pages);
1176
Rusty Russelld1c856e2007-11-19 11:20:40 -05001177 /* Initialize the virtqueue */
1178 vq->next = NULL;
1179 vq->last_avail_idx = 0;
1180 vq->dev = dev;
Rusty Russell20887612008-05-30 15:09:46 -05001181 vq->inflight = 0;
Rusty Russella1618832008-07-29 09:58:35 -05001182 vq->blocked = false;
Rusty Russelld1c856e2007-11-19 11:20:40 -05001183
Rusty Russell17cbca22007-10-22 11:24:22 +10001184 /* Initialize the configuration. */
1185 vq->config.num = num_descs;
1186 vq->config.irq = devices.next_irq++;
1187 vq->config.pfn = to_guest_phys(p) / getpagesize();
1188
1189 /* Initialize the vring. */
Rusty Russell2966af72008-12-30 09:25:58 -06001190 vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
Rusty Russell17cbca22007-10-22 11:24:22 +10001191
Rusty Russella586d4f2008-02-04 23:49:56 -05001192 /* Append virtqueue to this device's descriptor. We use
1193 * device_config() to get the end of the device's current virtqueues;
1194 * we check that we haven't added any config or feature information
1195 * yet, otherwise we'd be overwriting them. */
1196 assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
1197 memcpy(device_config(dev), &vq->config, sizeof(vq->config));
Rusty Russell713b15b2009-06-12 22:26:58 -06001198 dev->num_vq++;
Rusty Russella586d4f2008-02-04 23:49:56 -05001199 dev->desc->num_vq++;
1200
1201 verbose("Virtqueue page %#lx\n", to_guest_phys(p));
Rusty Russell17cbca22007-10-22 11:24:22 +10001202
1203 /* Add to tail of list, so dev->vq is first vq, dev->vq->next is
1204 * second. */
1205 for (i = &dev->vq; *i; i = &(*i)->next);
1206 *i = vq;
1207
Rusty Russelle1e72962007-10-25 15:02:50 +10001208 /* Set the routine to call when the Guest does something to this
1209 * virtqueue. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001210 vq->handle_output = handle_output;
Rusty Russelle1e72962007-10-25 15:02:50 +10001211
Rusty Russell426e3e02008-02-04 23:49:59 -05001212 /* As an optimization, set the advisory "Don't Notify Me" flag if we
1213 * don't have a handler */
Rusty Russell17cbca22007-10-22 11:24:22 +10001214 if (!handle_output)
1215 vq->vring.used->flags = VRING_USED_F_NO_NOTIFY;
1216}
1217
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001218/* The first half of the feature bitmask is for us to advertise features. The
Rusty Russella6bd8e12008-03-28 11:05:53 -05001219 * second half is for the Guest to accept features. */
Rusty Russella586d4f2008-02-04 23:49:56 -05001220static void add_feature(struct device *dev, unsigned bit)
1221{
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001222 u8 *features = get_feature_bits(dev);
Rusty Russella586d4f2008-02-04 23:49:56 -05001223
1224 /* We can't extend the feature bits once we've added config bytes */
1225 if (dev->desc->feature_len <= bit / CHAR_BIT) {
1226 assert(dev->desc->config_len == 0);
Rusty Russell713b15b2009-06-12 22:26:58 -06001227 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
Rusty Russella586d4f2008-02-04 23:49:56 -05001228 }
1229
Rusty Russella586d4f2008-02-04 23:49:56 -05001230 features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
1231}
1232
1233/* This routine sets the configuration fields for an existing device's
1234 * descriptor. It only works for the last device, but that's OK because that's
1235 * how we use it. */
1236static void set_config(struct device *dev, unsigned len, const void *conf)
1237{
1238 /* Check we haven't overflowed our single page. */
1239 if (device_config(dev) + len > devices.descpage + getpagesize())
1240 errx(1, "Too many devices");
1241
1242 /* Copy in the config information, and store the length. */
1243 memcpy(device_config(dev), conf, len);
1244 dev->desc->config_len = len;
1245}
1246
Rusty Russell17cbca22007-10-22 11:24:22 +10001247/* This routine does all the creation and setup of a new device, including
Rusty Russella6bd8e12008-03-28 11:05:53 -05001248 * calling new_dev_desc() to allocate the descriptor and device memory.
1249 *
1250 * See what I mean about userspace being boring? */
Rusty Russell17cbca22007-10-22 11:24:22 +10001251static struct device *new_device(const char *name, u16 type, int fd,
1252 bool (*handle_input)(int, struct device *))
Rusty Russell8ca47e02007-07-19 01:49:29 -07001253{
1254 struct device *dev = malloc(sizeof(*dev));
1255
Rusty Russelldde79782007-07-26 10:41:03 -07001256 /* Now we populate the fields one at a time. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001257 dev->fd = fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001258 /* If we have an input handler for this file descriptor, then we add it
1259 * to the device_list's fdset and maxfd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001260 if (handle_input)
Rusty Russell17cbca22007-10-22 11:24:22 +10001261 add_device_fd(dev->fd);
1262 dev->desc = new_dev_desc(type);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001263 dev->handle_input = handle_input;
Rusty Russell17cbca22007-10-22 11:24:22 +10001264 dev->name = name;
Rusty Russelld1c856e2007-11-19 11:20:40 -05001265 dev->vq = NULL;
Rusty Russella007a752008-05-02 21:50:53 -05001266 dev->ready = NULL;
Rusty Russell713b15b2009-06-12 22:26:58 -06001267 dev->feature_len = 0;
1268 dev->num_vq = 0;
Rusty Russella586d4f2008-02-04 23:49:56 -05001269
1270 /* Append to device list. Prepending to a single-linked list is
1271 * easier, but the user expects the devices to be arranged on the bus
1272 * in command-line order. The first network device on the command line
1273 * is eth0, the first block device /dev/vda, etc. */
1274 if (devices.lastdev)
1275 devices.lastdev->next = dev;
1276 else
1277 devices.dev = dev;
1278 devices.lastdev = dev;
1279
Rusty Russell8ca47e02007-07-19 01:49:29 -07001280 return dev;
1281}
1282
Rusty Russelldde79782007-07-26 10:41:03 -07001283/* Our first setup routine is the console. It's a fairly simple device, but
1284 * UNIX tty handling makes it uglier than it could be. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001285static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001286{
1287 struct device *dev;
1288
Rusty Russelldde79782007-07-26 10:41:03 -07001289 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001290 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1291 struct termios term = orig_term;
Rusty Russelldde79782007-07-26 10:41:03 -07001292 /* Then we turn off echo, line buffering and ^C etc. We want a
1293 * raw input stream to the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001294 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1295 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russelldde79782007-07-26 10:41:03 -07001296 /* If we exit gracefully, the original settings will be
1297 * restored so the user can see what they're typing. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001298 atexit(restore_term);
1299 }
1300
Rusty Russell17cbca22007-10-22 11:24:22 +10001301 dev = new_device("console", VIRTIO_ID_CONSOLE,
1302 STDIN_FILENO, handle_console_input);
Rusty Russelldde79782007-07-26 10:41:03 -07001303 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001304 dev->priv = malloc(sizeof(struct console_abort));
1305 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001306
Rusty Russell56ae43d2007-10-22 11:24:23 +10001307 /* The console needs two virtqueues: the input then the output. When
1308 * they put something the input queue, we make sure we're listening to
1309 * stdin. When they put something in the output queue, we write it to
Rusty Russelle1e72962007-10-25 15:02:50 +10001310 * stdout. */
Rusty Russell56ae43d2007-10-22 11:24:23 +10001311 add_virtqueue(dev, VIRTQUEUE_NUM, enable_fd);
Rusty Russell17cbca22007-10-22 11:24:22 +10001312 add_virtqueue(dev, VIRTQUEUE_NUM, handle_console_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001313
Rusty Russell17cbca22007-10-22 11:24:22 +10001314 verbose("device %u: console\n", devices.device_num++);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001315}
Rusty Russelldde79782007-07-26 10:41:03 -07001316/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001317
Rusty Russella1618832008-07-29 09:58:35 -05001318static void timeout_alarm(int sig)
1319{
1320 write(timeoutpipe[1], "", 1);
1321}
1322
1323static void setup_timeout(void)
1324{
1325 if (pipe(timeoutpipe) != 0)
1326 err(1, "Creating timeout pipe");
1327
1328 if (fcntl(timeoutpipe[1], F_SETFL,
1329 fcntl(timeoutpipe[1], F_GETFL) | O_NONBLOCK) != 0)
1330 err(1, "Making timeout pipe nonblocking");
1331
1332 add_device_fd(timeoutpipe[0]);
1333 signal(SIGALRM, timeout_alarm);
1334}
1335
Rusty Russell17cbca22007-10-22 11:24:22 +10001336/*M:010 Inter-guest networking is an interesting area. Simplest is to have a
1337 * --sharenet=<name> option which opens or creates a named pipe. This can be
1338 * used to send packets to another guest in a 1:1 manner.
1339 *
1340 * More sopisticated is to use one of the tools developed for project like UML
1341 * to do networking.
1342 *
1343 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
1344 * completely generic ("here's my vring, attach to your vring") and would work
1345 * for any traffic. Of course, namespace and permissions issues need to be
1346 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
1347 * multiple inter-guest channels behind one interface, although it would
1348 * require some manner of hotplugging new virtio channels.
1349 *
1350 * Finally, we could implement a virtio network switch in the kernel. :*/
1351
Rusty Russell8ca47e02007-07-19 01:49:29 -07001352static u32 str2ip(const char *ipaddr)
1353{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001354 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07001355
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001356 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
1357 errx(1, "Failed to parse IP address '%s'", ipaddr);
1358 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
1359}
1360
1361static void str2mac(const char *macaddr, unsigned char mac[6])
1362{
1363 unsigned int m[6];
1364 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
1365 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
1366 errx(1, "Failed to parse mac address '%s'", macaddr);
1367 mac[0] = m[0];
1368 mac[1] = m[1];
1369 mac[2] = m[2];
1370 mac[3] = m[3];
1371 mac[4] = m[4];
1372 mac[5] = m[5];
Rusty Russell8ca47e02007-07-19 01:49:29 -07001373}
1374
Rusty Russelldde79782007-07-26 10:41:03 -07001375/* This code is "adapted" from libbridge: it attaches the Host end of the
1376 * network device to the bridge device specified by the command line.
1377 *
1378 * This is yet another James Morris contribution (I'm an IP-level guy, so I
1379 * dislike bridging), and I just try not to break it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001380static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1381{
1382 int ifidx;
1383 struct ifreq ifr;
1384
1385 if (!*br_name)
1386 errx(1, "must specify bridge name");
1387
1388 ifidx = if_nametoindex(if_name);
1389 if (!ifidx)
1390 errx(1, "interface %s does not exist!", if_name);
1391
1392 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001393 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07001394 ifr.ifr_ifindex = ifidx;
1395 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1396 err(1, "can't add %s to bridge %s", if_name, br_name);
1397}
1398
Rusty Russelldde79782007-07-26 10:41:03 -07001399/* This sets up the Host end of the network device with an IP address, brings
1400 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell17cbca22007-10-22 11:24:22 +10001401 * pointer. */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001402static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001403{
1404 struct ifreq ifr;
1405 struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
1406
1407 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001408 strcpy(ifr.ifr_name, tapif);
1409
1410 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001411 sin->sin_family = AF_INET;
1412 sin->sin_addr.s_addr = htonl(ipaddr);
1413 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001414 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001415 ifr.ifr_flags = IFF_UP;
1416 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001417 err(1, "Bringing interface %s up", tapif);
1418}
1419
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001420static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07001421{
Rusty Russell8ca47e02007-07-19 01:49:29 -07001422 struct ifreq ifr;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001423 int netfd;
1424
1425 /* Start with this zeroed. Messy but sure. */
1426 memset(&ifr, 0, sizeof(ifr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001427
Rusty Russelldde79782007-07-26 10:41:03 -07001428 /* We open the /dev/net/tun device and tell it we want a tap device. A
1429 * tap device is like a tun device, only somehow different. To tell
1430 * the truth, I completely blundered my way through this code, but it
1431 * works now! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001432 netfd = open_or_die("/dev/net/tun", O_RDWR);
Rusty Russell398f1872008-07-29 09:58:37 -05001433 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001434 strcpy(ifr.ifr_name, "tap%d");
1435 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1436 err(1, "configuring /dev/net/tun");
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001437
Rusty Russell398f1872008-07-29 09:58:37 -05001438 if (ioctl(netfd, TUNSETOFFLOAD,
1439 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
1440 err(1, "Could not set features for tun device");
1441
Rusty Russelldde79782007-07-26 10:41:03 -07001442 /* We don't need checksums calculated for packets coming in this
1443 * device: trust us! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001444 ioctl(netfd, TUNSETNOCSUM, 1);
1445
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001446 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
1447 return netfd;
1448}
1449
1450/*L:195 Our network is a Host<->Guest network. This can either use bridging or
1451 * routing, but the principle is the same: it uses the "tun" device to inject
1452 * packets into the Host as if they came in from a normal network card. We
1453 * just shunt packets between the Guest and the tun device. */
1454static void setup_tun_net(char *arg)
1455{
1456 struct device *dev;
1457 int netfd, ipfd;
1458 u32 ip = INADDR_ANY;
1459 bool bridging = false;
1460 char tapif[IFNAMSIZ], *p;
1461 struct virtio_net_config conf;
1462
1463 netfd = get_tun_device(tapif);
1464
Rusty Russell17cbca22007-10-22 11:24:22 +10001465 /* First we create a new network device. */
1466 dev = new_device("net", VIRTIO_ID_NET, netfd, handle_tun_input);
Rusty Russelldde79782007-07-26 10:41:03 -07001467
Rusty Russell56ae43d2007-10-22 11:24:23 +10001468 /* Network devices need a receive and a send queue, just like
1469 * console. */
Rusty Russell5dae7852008-07-29 09:58:35 -05001470 add_virtqueue(dev, VIRTQUEUE_NUM, net_enable_fd);
Rusty Russell17cbca22007-10-22 11:24:22 +10001471 add_virtqueue(dev, VIRTQUEUE_NUM, handle_net_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001472
Rusty Russelldde79782007-07-26 10:41:03 -07001473 /* We need a socket to perform the magic network ioctls to bring up the
1474 * tap interface, connect to the bridge etc. Any socket will do! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001475 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1476 if (ipfd < 0)
1477 err(1, "opening IP socket");
1478
Rusty Russelldde79782007-07-26 10:41:03 -07001479 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001480 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001481 arg += strlen(BRIDGE_PFX);
1482 bridging = true;
1483 }
1484
1485 /* A mac address may follow the bridge name or IP address */
1486 p = strchr(arg, ':');
1487 if (p) {
1488 str2mac(p+1, conf.mac);
Rusty Russell40c42072008-08-12 17:52:51 -05001489 add_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001490 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001491 }
1492
1493 /* arg is now either an IP address or a bridge name */
1494 if (bridging)
1495 add_to_bridge(ipfd, tapif, arg);
1496 else
Rusty Russell8ca47e02007-07-19 01:49:29 -07001497 ip = str2ip(arg);
1498
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001499 /* Set up the tun device. */
1500 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001501
Rusty Russell20887612008-05-30 15:09:46 -05001502 add_feature(dev, VIRTIO_F_NOTIFY_ON_EMPTY);
Rusty Russell398f1872008-07-29 09:58:37 -05001503 /* Expect Guest to handle everything except UFO */
1504 add_feature(dev, VIRTIO_NET_F_CSUM);
1505 add_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
Rusty Russell398f1872008-07-29 09:58:37 -05001506 add_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
1507 add_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
1508 add_feature(dev, VIRTIO_NET_F_GUEST_ECN);
1509 add_feature(dev, VIRTIO_NET_F_HOST_TSO4);
1510 add_feature(dev, VIRTIO_NET_F_HOST_TSO6);
1511 add_feature(dev, VIRTIO_NET_F_HOST_ECN);
Rusty Russella586d4f2008-02-04 23:49:56 -05001512 set_config(dev, sizeof(conf), &conf);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001513
Rusty Russella586d4f2008-02-04 23:49:56 -05001514 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001515 close(ipfd);
1516
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001517 devices.device_num++;
1518
1519 if (bridging)
1520 verbose("device %u: tun %s attached to bridge: %s\n",
1521 devices.device_num, tapif, arg);
1522 else
1523 verbose("device %u: tun %s: %s\n",
1524 devices.device_num, tapif, arg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001525}
Rusty Russell17cbca22007-10-22 11:24:22 +10001526
Rusty Russelle1e72962007-10-25 15:02:50 +10001527/* Our block (disk) device should be really simple: the Guest asks for a block
1528 * number and we read or write that position in the file. Unfortunately, that
1529 * was amazingly slow: the Guest waits until the read is finished before
1530 * running anything else, even if it could have been doing useful work.
Rusty Russell17cbca22007-10-22 11:24:22 +10001531 *
Rusty Russelle1e72962007-10-25 15:02:50 +10001532 * We could use async I/O, except it's reputed to suck so hard that characters
1533 * actually go missing from your code when you try to use it.
Rusty Russell17cbca22007-10-22 11:24:22 +10001534 *
1535 * So we farm the I/O out to thread, and communicate with it via a pipe. */
1536
Rusty Russelle1e72962007-10-25 15:02:50 +10001537/* This hangs off device->priv. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001538struct vblk_info
1539{
1540 /* The size of the file. */
1541 off64_t len;
1542
1543 /* The file descriptor for the file. */
1544 int fd;
1545
1546 /* IO thread listens on this file descriptor [0]. */
1547 int workpipe[2];
1548
1549 /* IO thread writes to this file descriptor to mark it done, then
1550 * Launcher triggers interrupt to Guest. */
1551 int done_fd;
1552};
1553
Rusty Russelle1e72962007-10-25 15:02:50 +10001554/*L:210
1555 * The Disk
1556 *
1557 * Remember that the block device is handled by a separate I/O thread. We head
1558 * straight into the core of that thread here:
1559 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001560static bool service_io(struct device *dev)
1561{
1562 struct vblk_info *vblk = dev->priv;
1563 unsigned int head, out_num, in_num, wlen;
1564 int ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05001565 u8 *in;
Rusty Russell17cbca22007-10-22 11:24:22 +10001566 struct virtio_blk_outhdr *out;
1567 struct iovec iov[dev->vq->vring.num];
1568 off64_t off;
1569
Rusty Russelle1e72962007-10-25 15:02:50 +10001570 /* See if there's a request waiting. If not, nothing to do. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001571 head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
1572 if (head == dev->vq->vring.num)
1573 return false;
1574
Rusty Russelle1e72962007-10-25 15:02:50 +10001575 /* Every block request should contain at least one output buffer
1576 * (detailing the location on disk and the type of request) and one
1577 * input buffer (to hold the result). */
Rusty Russell17cbca22007-10-22 11:24:22 +10001578 if (out_num == 0 || in_num == 0)
1579 errx(1, "Bad virtblk cmd %u out=%u in=%u",
1580 head, out_num, in_num);
1581
1582 out = convert(&iov[0], struct virtio_blk_outhdr);
Rusty Russellcb38fa22008-05-02 21:50:45 -05001583 in = convert(&iov[out_num+in_num-1], u8);
Rusty Russell17cbca22007-10-22 11:24:22 +10001584 off = out->sector * 512;
1585
Rusty Russelle1e72962007-10-25 15:02:50 +10001586 /* The block device implements "barriers", where the Guest indicates
1587 * that it wants all previous writes to occur before this write. We
1588 * don't have a way of asking our kernel to do a barrier, so we just
1589 * synchronize all the data in the file. Pretty poor, no? */
Rusty Russell17cbca22007-10-22 11:24:22 +10001590 if (out->type & VIRTIO_BLK_T_BARRIER)
1591 fdatasync(vblk->fd);
1592
Rusty Russelle1e72962007-10-25 15:02:50 +10001593 /* In general the virtio block driver is allowed to try SCSI commands.
1594 * It'd be nice if we supported eject, for example, but we don't. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001595 if (out->type & VIRTIO_BLK_T_SCSI_CMD) {
1596 fprintf(stderr, "Scsi commands unsupported\n");
Rusty Russellcb38fa22008-05-02 21:50:45 -05001597 *in = VIRTIO_BLK_S_UNSUPP;
Anthony Liguori1200e642007-11-08 21:13:44 -06001598 wlen = sizeof(*in);
Rusty Russell17cbca22007-10-22 11:24:22 +10001599 } else if (out->type & VIRTIO_BLK_T_OUT) {
1600 /* Write */
1601
1602 /* Move to the right location in the block file. This can fail
1603 * if they try to write past end. */
1604 if (lseek64(vblk->fd, off, SEEK_SET) != off)
1605 err(1, "Bad seek to sector %llu", out->sector);
1606
1607 ret = writev(vblk->fd, iov+1, out_num-1);
1608 verbose("WRITE to sector %llu: %i\n", out->sector, ret);
1609
1610 /* Grr... Now we know how long the descriptor they sent was, we
1611 * make sure they didn't try to write over the end of the block
1612 * file (possibly extending it). */
1613 if (ret > 0 && off + ret > vblk->len) {
1614 /* Trim it back to the correct length */
1615 ftruncate64(vblk->fd, vblk->len);
1616 /* Die, bad Guest, die. */
1617 errx(1, "Write past end %llu+%u", off, ret);
1618 }
Anthony Liguori1200e642007-11-08 21:13:44 -06001619 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05001620 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10001621 } else {
1622 /* Read */
1623
1624 /* Move to the right location in the block file. This can fail
1625 * if they try to read past end. */
1626 if (lseek64(vblk->fd, off, SEEK_SET) != off)
1627 err(1, "Bad seek to sector %llu", out->sector);
1628
1629 ret = readv(vblk->fd, iov+1, in_num-1);
1630 verbose("READ from sector %llu: %i\n", out->sector, ret);
1631 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06001632 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05001633 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10001634 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06001635 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05001636 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10001637 }
1638 }
1639
Rusty Russelld1881d32009-03-30 21:55:25 -06001640 /* OK, so we noted that it was pretty poor to use an fdatasync as a
1641 * barrier. But Christoph Hellwig points out that we need a sync
1642 * *afterwards* as well: "Barriers specify no reordering to the front
1643 * or the back." And Jens Axboe confirmed it, so here we are: */
1644 if (out->type & VIRTIO_BLK_T_BARRIER)
1645 fdatasync(vblk->fd);
1646
Rusty Russell17cbca22007-10-22 11:24:22 +10001647 /* We can't trigger an IRQ, because we're not the Launcher. It does
1648 * that when we tell it we're done. */
1649 add_used(dev->vq, head, wlen);
1650 return true;
1651}
1652
1653/* This is the thread which actually services the I/O. */
1654static int io_thread(void *_dev)
1655{
1656 struct device *dev = _dev;
1657 struct vblk_info *vblk = dev->priv;
1658 char c;
1659
1660 /* Close other side of workpipe so we get 0 read when main dies. */
1661 close(vblk->workpipe[1]);
1662 /* Close the other side of the done_fd pipe. */
1663 close(dev->fd);
1664
1665 /* When this read fails, it means Launcher died, so we follow. */
1666 while (read(vblk->workpipe[0], &c, 1) == 1) {
Rusty Russelle1e72962007-10-25 15:02:50 +10001667 /* We acknowledge each request immediately to reduce latency,
Rusty Russell17cbca22007-10-22 11:24:22 +10001668 * rather than waiting until we've done them all. I haven't
Rusty Russella6bd8e12008-03-28 11:05:53 -05001669 * measured to see if it makes any difference.
1670 *
1671 * That would be an interesting test, wouldn't it? You could
1672 * also try having more than one I/O thread. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001673 while (service_io(dev))
1674 write(vblk->done_fd, &c, 1);
1675 }
1676 return 0;
1677}
1678
Rusty Russelle1e72962007-10-25 15:02:50 +10001679/* Now we've seen the I/O thread, we return to the Launcher to see what happens
Rusty Russella6bd8e12008-03-28 11:05:53 -05001680 * when that thread tells us it's completed some I/O. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001681static bool handle_io_finish(int fd, struct device *dev)
1682{
1683 char c;
1684
Rusty Russelle1e72962007-10-25 15:02:50 +10001685 /* If the I/O thread died, presumably it printed the error, so we
1686 * simply exit. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001687 if (read(dev->fd, &c, 1) != 1)
1688 exit(1);
1689
1690 /* It did some work, so trigger the irq. */
1691 trigger_irq(fd, dev->vq);
1692 return true;
1693}
1694
Rusty Russelle1e72962007-10-25 15:02:50 +10001695/* When the Guest submits some I/O, we just need to wake the I/O thread. */
Rusty Russella1618832008-07-29 09:58:35 -05001696static void handle_virtblk_output(int fd, struct virtqueue *vq, bool timeout)
Rusty Russell17cbca22007-10-22 11:24:22 +10001697{
1698 struct vblk_info *vblk = vq->dev->priv;
1699 char c = 0;
1700
1701 /* Wake up I/O thread and tell it to go to work! */
1702 if (write(vblk->workpipe[1], &c, 1) != 1)
1703 /* Presumably it indicated why it died. */
1704 exit(1);
1705}
1706
Rusty Russelle1e72962007-10-25 15:02:50 +10001707/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001708static void setup_block_file(const char *filename)
1709{
1710 int p[2];
1711 struct device *dev;
1712 struct vblk_info *vblk;
1713 void *stack;
Rusty Russella586d4f2008-02-04 23:49:56 -05001714 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10001715
1716 /* This is the pipe the I/O thread will use to tell us I/O is done. */
1717 pipe(p);
1718
1719 /* The device responds to return from I/O thread. */
1720 dev = new_device("block", VIRTIO_ID_BLOCK, p[0], handle_io_finish);
1721
Rusty Russelle1e72962007-10-25 15:02:50 +10001722 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001723 add_virtqueue(dev, VIRTQUEUE_NUM, handle_virtblk_output);
1724
1725 /* Allocate the room for our own bookkeeping */
1726 vblk = dev->priv = malloc(sizeof(*vblk));
1727
1728 /* First we open the file and store the length. */
1729 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
1730 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
1731
Rusty Russella586d4f2008-02-04 23:49:56 -05001732 /* We support barriers. */
1733 add_feature(dev, VIRTIO_BLK_F_BARRIER);
1734
Rusty Russell17cbca22007-10-22 11:24:22 +10001735 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05001736 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10001737
1738 /* Tell Guest not to put in too many descriptors at once: two are used
1739 * for the in and out elements. */
Rusty Russella586d4f2008-02-04 23:49:56 -05001740 add_feature(dev, VIRTIO_BLK_F_SEG_MAX);
1741 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
1742
1743 set_config(dev, sizeof(conf), &conf);
Rusty Russell17cbca22007-10-22 11:24:22 +10001744
1745 /* The I/O thread writes to this end of the pipe when done. */
1746 vblk->done_fd = p[1];
1747
Rusty Russelle1e72962007-10-25 15:02:50 +10001748 /* This is the second pipe, which is how we tell the I/O thread about
1749 * more work. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001750 pipe(vblk->workpipe);
1751
Rusty Russella6bd8e12008-03-28 11:05:53 -05001752 /* Create stack for thread and run it. Since stack grows upwards, we
1753 * point the stack pointer to the end of this region. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001754 stack = malloc(32768);
Balaji Raoec04b132007-12-28 14:26:24 +05301755 /* SIGCHLD - We dont "wait" for our cloned thread, so prevent it from
1756 * becoming a zombie. */
Rusty Russella6bd8e12008-03-28 11:05:53 -05001757 if (clone(io_thread, stack + 32768, CLONE_VM | SIGCHLD, dev) == -1)
Rusty Russell17cbca22007-10-22 11:24:22 +10001758 err(1, "Creating clone");
1759
1760 /* We don't need to keep the I/O thread's end of the pipes open. */
1761 close(vblk->done_fd);
1762 close(vblk->workpipe[0]);
1763
1764 verbose("device %u: virtblock %llu sectors\n",
Rusty Russella586d4f2008-02-04 23:49:56 -05001765 devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10001766}
Rusty Russell28fd6d72008-07-29 09:58:33 -05001767
1768/* Our random number generator device reads from /dev/random into the Guest's
1769 * input buffers. The usual case is that the Guest doesn't want random numbers
1770 * and so has no buffers although /dev/random is still readable, whereas
1771 * console is the reverse.
1772 *
1773 * The same logic applies, however. */
1774static bool handle_rng_input(int fd, struct device *dev)
1775{
1776 int len;
1777 unsigned int head, in_num, out_num, totlen = 0;
1778 struct iovec iov[dev->vq->vring.num];
1779
1780 /* First we need a buffer from the Guests's virtqueue. */
1781 head = get_vq_desc(dev->vq, iov, &out_num, &in_num);
1782
1783 /* If they're not ready for input, stop listening to this file
1784 * descriptor. We'll start again once they add an input buffer. */
1785 if (head == dev->vq->vring.num)
1786 return false;
1787
1788 if (out_num)
1789 errx(1, "Output buffers in rng?");
1790
1791 /* This is why we convert to iovecs: the readv() call uses them, and so
1792 * it reads straight into the Guest's buffer. We loop to make sure we
1793 * fill it. */
1794 while (!iov_empty(iov, in_num)) {
1795 len = readv(dev->fd, iov, in_num);
1796 if (len <= 0)
1797 err(1, "Read from /dev/random gave %i", len);
1798 iov_consume(iov, in_num, len);
1799 totlen += len;
1800 }
1801
1802 /* Tell the Guest about the new input. */
1803 add_used_and_trigger(fd, dev->vq, head, totlen);
1804
1805 /* Everything went OK! */
1806 return true;
1807}
1808
1809/* And this creates a "hardware" random number device for the Guest. */
1810static void setup_rng(void)
1811{
1812 struct device *dev;
1813 int fd;
1814
1815 fd = open_or_die("/dev/random", O_RDONLY);
1816
1817 /* The device responds to return from I/O thread. */
1818 dev = new_device("rng", VIRTIO_ID_RNG, fd, handle_rng_input);
1819
1820 /* The device has one virtqueue, where the Guest places inbufs. */
1821 add_virtqueue(dev, VIRTQUEUE_NUM, enable_fd);
1822
1823 verbose("device %u: rng\n", devices.device_num++);
1824}
Rusty Russella6bd8e12008-03-28 11:05:53 -05001825/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05301826
Rusty Russella6bd8e12008-03-28 11:05:53 -05001827/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05301828static void __attribute__((noreturn)) restart_guest(void)
1829{
1830 unsigned int i;
1831
Rusty Russell8c798732008-07-29 09:58:38 -05001832 /* Since we don't track all open fds, we simply close everything beyond
1833 * stderr. */
Balaji Raoec04b132007-12-28 14:26:24 +05301834 for (i = 3; i < FD_SETSIZE; i++)
1835 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05001836
1837 /* The exec automatically gets rid of the I/O and Waker threads. */
Balaji Raoec04b132007-12-28 14:26:24 +05301838 execv(main_args[0], main_args);
1839 err(1, "Could not exec %s", main_args[0]);
1840}
Rusty Russell8ca47e02007-07-19 01:49:29 -07001841
Rusty Russella6bd8e12008-03-28 11:05:53 -05001842/*L:220 Finally we reach the core of the Launcher which runs the Guest, serves
Rusty Russelldde79782007-07-26 10:41:03 -07001843 * its input and output, and finally, lays it to rest. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001844static void __attribute__((noreturn)) run_guest(int lguest_fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001845{
1846 for (;;) {
Jes Sorensen511801d2007-10-22 11:03:31 +10001847 unsigned long args[] = { LHREQ_BREAK, 0 };
Rusty Russell17cbca22007-10-22 11:24:22 +10001848 unsigned long notify_addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001849 int readval;
1850
1851 /* We read from the /dev/lguest device to run the Guest. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02001852 readval = pread(lguest_fd, &notify_addr,
1853 sizeof(notify_addr), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001854
Rusty Russell17cbca22007-10-22 11:24:22 +10001855 /* One unsigned long means the Guest did HCALL_NOTIFY */
1856 if (readval == sizeof(notify_addr)) {
1857 verbose("Notify on address %#lx\n", notify_addr);
1858 handle_output(lguest_fd, notify_addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001859 continue;
Rusty Russelldde79782007-07-26 10:41:03 -07001860 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001861 } else if (errno == ENOENT) {
1862 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02001863 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001864 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05301865 /* ERESTART means that we need to reboot the guest */
1866 } else if (errno == ERESTART) {
1867 restart_guest();
Rusty Russella1618832008-07-29 09:58:35 -05001868 /* EAGAIN means a signal (timeout).
Rusty Russelldde79782007-07-26 10:41:03 -07001869 * Anything else means a bug or incompatible change. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001870 } else if (errno != EAGAIN)
1871 err(1, "Running guest failed");
Rusty Russelldde79782007-07-26 10:41:03 -07001872
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02001873 /* Only service input on thread for CPU 0. */
1874 if (cpu_id != 0)
1875 continue;
1876
Rusty Russelle1e72962007-10-25 15:02:50 +10001877 /* Service input, then unset the BREAK to release the Waker. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001878 handle_input(lguest_fd);
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02001879 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001880 err(1, "Resetting break");
1881 }
1882}
Rusty Russella6bd8e12008-03-28 11:05:53 -05001883/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10001884 * This is the end of the Launcher. The good news: we are over halfway
1885 * through! The bad news: the most fiendish part of the code still lies ahead
1886 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07001887 *
Rusty Russelle1e72962007-10-25 15:02:50 +10001888 * Are you ready? Take a deep breath and join me in the core of the Host, in
1889 * "make Host".
1890 :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001891
1892static struct option opts[] = {
1893 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07001894 { "tunnet", 1, NULL, 't' },
1895 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05001896 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07001897 { "initrd", 1, NULL, 'i' },
1898 { NULL },
1899};
1900static void usage(void)
1901{
1902 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001903 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07001904 "|--block=<filename>|--initrd=<filename>]...\n"
1905 "<mem-in-mb> vmlinux [args...]");
1906}
1907
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001908/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001909int main(int argc, char *argv[])
1910{
Rusty Russell47436aa2007-10-22 11:03:36 +10001911 /* Memory, top-level pagetable, code startpoint and size of the
1912 * (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03001913 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russelle1e72962007-10-25 15:02:50 +10001914 /* Two temporaries and the /dev/lguest file descriptor. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001915 int i, c, lguest_fd;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001916 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10001917 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07001918 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001919 const char *initrd_name = NULL;
1920
Balaji Raoec04b132007-12-28 14:26:24 +05301921 /* Save the args: we "reboot" by execing ourselves again. */
1922 main_args = argv;
1923 /* We don't "wait" for the children, so prevent them from becoming
1924 * zombies. */
1925 signal(SIGCHLD, SIG_IGN);
1926
Rusty Russelldde79782007-07-26 10:41:03 -07001927 /* First we initialize the device list. Since console and network
1928 * device receive input from a file descriptor, we keep an fdset
1929 * (infds) and the maximum fd number (max_infd) with the head of the
Rusty Russella586d4f2008-02-04 23:49:56 -05001930 * list. We also keep a pointer to the last device. Finally, we keep
Rusty Russella6bd8e12008-03-28 11:05:53 -05001931 * the next interrupt number to use for devices (1: remember that 0 is
1932 * used by the timer). */
Rusty Russell17cbca22007-10-22 11:24:22 +10001933 FD_ZERO(&devices.infds);
1934 devices.max_infd = -1;
Rusty Russella586d4f2008-02-04 23:49:56 -05001935 devices.lastdev = NULL;
Rusty Russell17cbca22007-10-22 11:24:22 +10001936 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001937
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02001938 cpu_id = 0;
Rusty Russelldde79782007-07-26 10:41:03 -07001939 /* We need to know how much memory so we can set up the device
1940 * descriptor and memory pages for the devices as we parse the command
1941 * line. So we quickly look through the arguments to find the amount
1942 * of memory now. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001943 for (i = 1; i < argc; i++) {
1944 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001945 mem = atoi(argv[i]) * 1024 * 1024;
1946 /* We start by mapping anonymous pages over all of
1947 * guest-physical memory range. This fills it with 0,
1948 * and ensures that the Guest won't be killed when it
1949 * tries to access it. */
1950 guest_base = map_zeroed_pages(mem / getpagesize()
1951 + DEVICE_PAGES);
1952 guest_limit = mem;
1953 guest_max = mem + DEVICE_PAGES*getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10001954 devices.descpage = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07001955 break;
1956 }
1957 }
Rusty Russelldde79782007-07-26 10:41:03 -07001958
1959 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001960 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
1961 switch (c) {
1962 case 'v':
1963 verbose = true;
1964 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001965 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10001966 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001967 break;
1968 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10001969 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001970 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05001971 case 'r':
1972 setup_rng();
1973 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001974 case 'i':
1975 initrd_name = optarg;
1976 break;
1977 default:
1978 warnx("Unknown argument %s", argv[optind]);
1979 usage();
1980 }
1981 }
Rusty Russelldde79782007-07-26 10:41:03 -07001982 /* After the other arguments we expect memory and kernel image name,
1983 * followed by command line arguments for the kernel. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001984 if (optind + 2 > argc)
1985 usage();
1986
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001987 verbose("Guest base is at %p\n", guest_base);
1988
Rusty Russelldde79782007-07-26 10:41:03 -07001989 /* We always have a console device */
Rusty Russell17cbca22007-10-22 11:24:22 +10001990 setup_console();
Rusty Russell8ca47e02007-07-19 01:49:29 -07001991
Rusty Russella1618832008-07-29 09:58:35 -05001992 /* We can timeout waiting for Guest network transmit. */
1993 setup_timeout();
1994
Rusty Russell8ca47e02007-07-19 01:49:29 -07001995 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10001996 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001997
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001998 /* Boot information is stashed at physical address 0 */
1999 boot = from_guest_phys(0);
2000
Rusty Russelldde79782007-07-26 10:41:03 -07002001 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002002 if (initrd_name) {
2003 initrd_size = load_initrd(initrd_name, mem);
Rusty Russelldde79782007-07-26 10:41:03 -07002004 /* These are the location in the Linux boot header where the
2005 * start and size of the initrd are expected to be found. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002006 boot->hdr.ramdisk_image = mem - initrd_size;
2007 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07002008 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002009 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002010 }
2011
Rusty Russelldde79782007-07-26 10:41:03 -07002012 /* The Linux boot header contains an "E820" memory map: ours is a
2013 * simple, single region. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002014 boot->e820_entries = 1;
2015 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russelldde79782007-07-26 10:41:03 -07002016 /* The boot header contains a command line pointer: we put the command
Rusty Russell43d33b22007-10-22 11:29:57 +10002017 * line after the boot header. */
2018 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10002019 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002020 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07002021
Rusty Russell814a0e52007-10-22 11:29:44 +10002022 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002023 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10002024
2025 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002026 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10002027
Rusty Russell43d33b22007-10-22 11:29:57 +10002028 /* Tell the entry path not to try to reload segment registers. */
2029 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002030
Rusty Russelldde79782007-07-26 10:41:03 -07002031 /* We tell the kernel to initialize the Guest: this returns the open
2032 * /dev/lguest file descriptor. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002033 lguest_fd = tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07002034
Rusty Russell8c798732008-07-29 09:58:38 -05002035 /* We clone off a thread, which wakes the Launcher whenever one of the
2036 * input file descriptors needs attention. We call this the Waker, and
2037 * we'll cover it in a moment. */
2038 setup_waker(lguest_fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002039
Rusty Russelldde79782007-07-26 10:41:03 -07002040 /* Finally, run the Guest. This doesn't return. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002041 run_guest(lguest_fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002042}
Rusty Russellf56a3842007-07-26 10:41:05 -07002043/*:*/
2044
2045/*M:999
2046 * Mastery is done: you now know everything I do.
2047 *
2048 * But surely you have seen code, features and bugs in your wanderings which
2049 * you now yearn to attack? That is the real game, and I look forward to you
2050 * patching and forking lguest into the Your-Name-Here-visor.
2051 *
2052 * Farewell, and good coding!
2053 * Rusty Russell.
2054 */