blob: 32c2eaf94c4df59a260e7990406329057fea5c68 [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
2 * "physical" memory for the new Guest by mapping the kernel image and the
3 * virtual devices, then reads repeatedly from /dev/lguest to run the Guest.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10004:*/
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 Russelldde79782007-07-26 10:41:03 -070035/*L:110 We can ignore the 28 include files we need for this program, but I do
36 * want to draw attention to the use of kernel-style types.
37 *
38 * As Linus said, "C is a Spartan language, and so should your naming be." I
39 * like these abbreviations and the header we need uses them, so we define them
40 * here.
41 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070042typedef unsigned long long u64;
43typedef uint32_t u32;
44typedef uint16_t u16;
45typedef uint8_t u8;
Rusty Russellb45d8cb2007-10-22 10:56:24 +100046#include "linux/lguest_launcher.h"
47#include "asm-x86/e820.h"
Rusty Russelldde79782007-07-26 10:41:03 -070048/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070049
50#define PAGE_PRESENT 0x7 /* Present, RW, Execute */
51#define NET_PEERNUM 1
52#define BRIDGE_PFX "bridge:"
53#ifndef SIOCBRADDIF
54#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
55#endif
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100056/* We can have up to 256 pages for devices. */
57#define DEVICE_PAGES 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070058
Rusty Russelldde79782007-07-26 10:41:03 -070059/*L:120 verbose is both a global flag and a macro. The C preprocessor allows
60 * this, and although I wouldn't recommend it, it works quite nicely here. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070061static bool verbose;
62#define verbose(args...) \
63 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070064/*:*/
65
66/* The pipe to send commands to the waker process */
Rusty Russell8ca47e02007-07-19 01:49:29 -070067static int waker_fd;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100068/* The pointer to the start of guest memory. */
69static void *guest_base;
70/* The maximum guest physical address allowed, and maximum possible. */
71static unsigned long guest_limit, guest_max;
Rusty Russell8ca47e02007-07-19 01:49:29 -070072
Rusty Russelldde79782007-07-26 10:41:03 -070073/* This is our list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070074struct device_list
75{
Rusty Russelldde79782007-07-26 10:41:03 -070076 /* Summary information about the devices in our list: ready to pass to
77 * select() to ask which need servicing.*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070078 fd_set infds;
79 int max_infd;
80
Rusty Russelldde79782007-07-26 10:41:03 -070081 /* The descriptor page for the devices. */
Rusty Russell6570c45992007-07-23 18:43:56 -070082 struct lguest_device_desc *descs;
Rusty Russelldde79782007-07-26 10:41:03 -070083
84 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070085 struct device *dev;
Rusty Russelldde79782007-07-26 10:41:03 -070086 /* ... And an end pointer so we can easily append new devices */
Rusty Russell8ca47e02007-07-19 01:49:29 -070087 struct device **lastdev;
88};
89
Rusty Russelldde79782007-07-26 10:41:03 -070090/* The device structure describes a single device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070091struct device
92{
Rusty Russelldde79782007-07-26 10:41:03 -070093 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070094 struct device *next;
Rusty Russelldde79782007-07-26 10:41:03 -070095 /* The descriptor for this device, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070096 struct lguest_device_desc *desc;
Rusty Russelldde79782007-07-26 10:41:03 -070097 /* The memory page(s) of this device, if any. Also mapped in Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070098 void *mem;
99
Rusty Russelldde79782007-07-26 10:41:03 -0700100 /* If handle_input is set, it wants to be called when this file
101 * descriptor is ready. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700102 int fd;
103 bool (*handle_input)(int fd, struct device *me);
104
Rusty Russelldde79782007-07-26 10:41:03 -0700105 /* If handle_output is set, it wants to be called when the Guest sends
106 * DMA to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700107 unsigned long watch_key;
108 u32 (*handle_output)(int fd, const struct iovec *iov,
109 unsigned int num, struct device *me);
110
111 /* Device-specific data. */
112 void *priv;
113};
114
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000115/*L:100 The Launcher code itself takes us out into userspace, that scary place
116 * where pointers run wild and free! Unfortunately, like most userspace
117 * programs, it's quite boring (which is why everyone likes to hack on the
118 * kernel!). Perhaps if you make up an Lguest Drinking Game at this point, it
119 * will get you through this section. Or, maybe not.
120 *
121 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
122 * memory and stores it in "guest_base". In other words, Guest physical ==
123 * Launcher virtual with an offset.
124 *
125 * This can be tough to get your head around, but usually it just means that we
126 * use these trivial conversion functions when the Guest gives us it's
127 * "physical" addresses: */
128static void *from_guest_phys(unsigned long addr)
129{
130 return guest_base + addr;
131}
132
133static unsigned long to_guest_phys(const void *addr)
134{
135 return (addr - guest_base);
136}
137
Rusty Russelldde79782007-07-26 10:41:03 -0700138/*L:130
139 * Loading the Kernel.
140 *
141 * We start with couple of simple helper routines. open_or_die() avoids
142 * error-checking code cluttering the callers: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700143static int open_or_die(const char *name, int flags)
144{
145 int fd = open(name, flags);
146 if (fd < 0)
147 err(1, "Failed to open %s", name);
148 return fd;
149}
150
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000151/* map_zeroed_pages() takes a number of pages. */
152static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700153{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000154 int fd = open_or_die("/dev/zero", O_RDONLY);
155 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700156
Rusty Russelldde79782007-07-26 10:41:03 -0700157 /* We use a private mapping (ie. if we write to the page, it will be
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000158 * copied). */
159 addr = mmap(NULL, getpagesize() * num,
160 PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE, fd, 0);
161 if (addr == MAP_FAILED)
162 err(1, "Mmaping %u pages of /dev/zero", num);
Rusty Russelldde79782007-07-26 10:41:03 -0700163
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000164 return addr;
165}
166
167/* Get some more pages for a device. */
168static void *get_pages(unsigned int num)
169{
170 void *addr = from_guest_phys(guest_limit);
171
172 guest_limit += num * getpagesize();
173 if (guest_limit > guest_max)
174 errx(1, "Not enough memory for devices");
175 return addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700176}
177
Rusty Russelldde79782007-07-26 10:41:03 -0700178/* To find out where to start we look for the magic Guest string, which marks
179 * the code we see in lguest_asm.S. This is a hack which we are currently
180 * plotting to replace with the normal Linux entry point. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000181static unsigned long entry_point(const void *start, const void *end)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700182{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000183 const void *p;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700184
Rusty Russell47436aa2007-10-22 11:03:36 +1000185 /* The scan gives us the physical starting address. We boot with
186 * pagetables set up with virtual and physical the same, so that's
187 * OK. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700188 for (p = start; p < end; p++)
189 if (memcmp(p, "GenuineLguest", strlen("GenuineLguest")) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000190 return to_guest_phys(p + strlen("GenuineLguest"));
Rusty Russell8ca47e02007-07-19 01:49:29 -0700191
Glauber de Oliveira Costababed5c2007-10-22 10:56:21 +1000192 errx(1, "Is this image a genuine lguest?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700193}
194
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700195/* This routine is used to load the kernel or initrd. It tries mmap, but if
196 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
197 * it falls back to reading the memory in. */
198static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
199{
200 ssize_t r;
201
202 /* We map writable even though for some segments are marked read-only.
203 * The kernel really wants to be writable: it patches its own
204 * instructions.
205 *
206 * MAP_PRIVATE means that the page won't be copied until a write is
207 * done to it. This allows us to share untouched memory between
208 * Guests. */
209 if (mmap(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC,
210 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
211 return;
212
213 /* pread does a seek and a read in one shot: saves a few lines. */
214 r = pread(fd, addr, len, offset);
215 if (r != len)
216 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
217}
218
Rusty Russelldde79782007-07-26 10:41:03 -0700219/* This routine takes an open vmlinux image, which is in ELF, and maps it into
220 * the Guest memory. ELF = Embedded Linking Format, which is the format used
221 * by all modern binaries on Linux including the kernel.
222 *
223 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000224 * address. We use the physical address; the Guest will map itself to the
225 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700226 *
227 * We return the starting address. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000228static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700229{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000230 void *start = (void *)-1, *end = NULL;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700231 Elf32_Phdr phdr[ehdr->e_phnum];
232 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700233
Rusty Russelldde79782007-07-26 10:41:03 -0700234 /* Sanity checks on the main ELF header: an x86 executable with a
235 * reasonable number of correctly-sized program headers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700236 if (ehdr->e_type != ET_EXEC
237 || ehdr->e_machine != EM_386
238 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
239 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
240 errx(1, "Malformed elf header");
241
Rusty Russelldde79782007-07-26 10:41:03 -0700242 /* An ELF executable contains an ELF header and a number of "program"
243 * headers which indicate which parts ("segments") of the program to
244 * load where. */
245
246 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700247 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
248 err(1, "Seeking to program headers");
249 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
250 err(1, "Reading program headers");
251
Rusty Russelldde79782007-07-26 10:41:03 -0700252 /* Try all the headers: there are usually only three. A read-only one,
253 * a read-write one, and a "note" section which isn't loadable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700254 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700255 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700256 if (phdr[i].p_type != PT_LOAD)
257 continue;
258
259 verbose("Section %i: size %i addr %p\n",
260 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
261
Rusty Russelldde79782007-07-26 10:41:03 -0700262 /* We track the first and last address we mapped, so we can
263 * tell entry_point() where to scan. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000264 if (from_guest_phys(phdr[i].p_paddr) < start)
265 start = from_guest_phys(phdr[i].p_paddr);
266 if (from_guest_phys(phdr[i].p_paddr) + phdr[i].p_filesz > end)
267 end=from_guest_phys(phdr[i].p_paddr)+phdr[i].p_filesz;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700268
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700269 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000270 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700271 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700272 }
273
Rusty Russell47436aa2007-10-22 11:03:36 +1000274 return entry_point(start, end);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700275}
276
Rusty Russelldde79782007-07-26 10:41:03 -0700277/*L:160 Unfortunately the entire ELF image isn't compressed: the segments
278 * which need loading are extracted and compressed raw. This denies us the
279 * information we need to make a fully-general loader. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000280static unsigned long unpack_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700281{
282 gzFile f;
283 int ret, len = 0;
Rusty Russelldde79782007-07-26 10:41:03 -0700284 /* A bzImage always gets loaded at physical address 1M. This is
285 * actually configurable as CONFIG_PHYSICAL_START, but as the comment
286 * there says, "Don't change this unless you know what you are doing".
287 * Indeed. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000288 void *img = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700289
Rusty Russelldde79782007-07-26 10:41:03 -0700290 /* gzdopen takes our file descriptor (carefully placed at the start of
291 * the GZIP header we found) and returns a gzFile. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700292 f = gzdopen(fd, "rb");
Rusty Russelldde79782007-07-26 10:41:03 -0700293 /* We read it into memory in 64k chunks until we hit the end. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700294 while ((ret = gzread(f, img + len, 65536)) > 0)
295 len += ret;
296 if (ret < 0)
297 err(1, "reading image from bzImage");
298
299 verbose("Unpacked size %i addr %p\n", len, img);
Rusty Russelldde79782007-07-26 10:41:03 -0700300
Rusty Russell47436aa2007-10-22 11:03:36 +1000301 return entry_point(img, img + len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700302}
303
Rusty Russelldde79782007-07-26 10:41:03 -0700304/*L:150 A bzImage, unlike an ELF file, is not meant to be loaded. You're
305 * supposed to jump into it and it will unpack itself. We can't do that
306 * because the Guest can't run the unpacking code, and adding features to
307 * lguest kills puppies, so we don't want to.
308 *
309 * The bzImage is formed by putting the decompressing code in front of the
310 * compressed kernel code. So we can simple scan through it looking for the
311 * first "gzip" header, and start decompressing from there. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000312static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700313{
314 unsigned char c;
315 int state = 0;
316
Rusty Russelldde79782007-07-26 10:41:03 -0700317 /* GZIP header is 0x1F 0x8B <method> <flags>... <compressed-by>. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700318 while (read(fd, &c, 1) == 1) {
319 switch (state) {
320 case 0:
321 if (c == 0x1F)
322 state++;
323 break;
324 case 1:
325 if (c == 0x8B)
326 state++;
327 else
328 state = 0;
329 break;
330 case 2 ... 8:
331 state++;
332 break;
333 case 9:
Rusty Russelldde79782007-07-26 10:41:03 -0700334 /* Seek back to the start of the gzip header. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700335 lseek(fd, -10, SEEK_CUR);
Rusty Russelldde79782007-07-26 10:41:03 -0700336 /* One final check: "compressed under UNIX". */
337 if (c != 0x03)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700338 state = -1;
339 else
Rusty Russell47436aa2007-10-22 11:03:36 +1000340 return unpack_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700341 }
342 }
343 errx(1, "Could not find kernel in bzImage");
344}
345
Rusty Russelldde79782007-07-26 10:41:03 -0700346/*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels
347 * come wrapped up in the self-decompressing "bzImage" format. With some funky
348 * coding, we can load those, too. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000349static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700350{
351 Elf32_Ehdr hdr;
352
Rusty Russelldde79782007-07-26 10:41:03 -0700353 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700354 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
355 err(1, "Reading kernel");
356
Rusty Russelldde79782007-07-26 10:41:03 -0700357 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700358 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000359 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700360
Rusty Russelldde79782007-07-26 10:41:03 -0700361 /* Otherwise we assume it's a bzImage, and try to unpack it */
Rusty Russell47436aa2007-10-22 11:03:36 +1000362 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700363}
364
Rusty Russelldde79782007-07-26 10:41:03 -0700365/* This is a trivial little helper to align pages. Andi Kleen hated it because
366 * it calls getpagesize() twice: "it's dumb code."
367 *
368 * Kernel guys get really het up about optimization, even when it's not
369 * necessary. I leave this code as a reaction against that. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700370static inline unsigned long page_align(unsigned long addr)
371{
Rusty Russelldde79782007-07-26 10:41:03 -0700372 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700373 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
374}
375
Rusty Russelldde79782007-07-26 10:41:03 -0700376/*L:180 An "initial ram disk" is a disk image loaded into memory along with
377 * the kernel which the kernel can use to boot from without needing any
378 * drivers. Most distributions now use this as standard: the initrd contains
379 * the code to load the appropriate driver modules for the current machine.
380 *
381 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
382 * kernels. He sent me this (and tells me when I break it). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700383static unsigned long load_initrd(const char *name, unsigned long mem)
384{
385 int ifd;
386 struct stat st;
387 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700388
389 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700390 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700391 if (fstat(ifd, &st) < 0)
392 err(1, "fstat() on initrd '%s'", name);
393
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700394 /* We map the initrd at the top of memory, but mmap wants it to be
395 * page-aligned, so we round the size up for that. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700396 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000397 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russelldde79782007-07-26 10:41:03 -0700398 /* Once a file is mapped, you can close the file descriptor. It's a
399 * little odd, but quite useful. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700400 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700401 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700402
403 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700404 return len;
405}
406
Rusty Russell47436aa2007-10-22 11:03:36 +1000407/* Once we know how much memory we have, we can construct simple linear page
408 * tables which set virtual == physical which will get the Guest far enough
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000409 * into the boot to create its own.
Rusty Russelldde79782007-07-26 10:41:03 -0700410 *
411 * We lay them out of the way, just below the initrd (which is why we need to
412 * know its size). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700413static unsigned long setup_pagetables(unsigned long mem,
Rusty Russell47436aa2007-10-22 11:03:36 +1000414 unsigned long initrd_size)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700415{
Jes Sorensen511801d2007-10-22 11:03:31 +1000416 unsigned long *pgdir, *linear;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700417 unsigned int mapped_pages, i, linear_pages;
Jes Sorensen511801d2007-10-22 11:03:31 +1000418 unsigned int ptes_per_page = getpagesize()/sizeof(void *);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700419
Rusty Russell47436aa2007-10-22 11:03:36 +1000420 mapped_pages = mem/getpagesize();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700421
Rusty Russelldde79782007-07-26 10:41:03 -0700422 /* Each PTE page can map ptes_per_page pages: how many do we need? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700423 linear_pages = (mapped_pages + ptes_per_page-1)/ptes_per_page;
424
Rusty Russelldde79782007-07-26 10:41:03 -0700425 /* We put the toplevel page directory page at the top of memory. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000426 pgdir = from_guest_phys(mem) - initrd_size - getpagesize();
Rusty Russelldde79782007-07-26 10:41:03 -0700427
428 /* Now we use the next linear_pages pages as pte pages */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700429 linear = (void *)pgdir - linear_pages*getpagesize();
430
Rusty Russelldde79782007-07-26 10:41:03 -0700431 /* Linear mapping is easy: put every page's address into the mapping in
432 * order. PAGE_PRESENT contains the flags Present, Writable and
433 * Executable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700434 for (i = 0; i < mapped_pages; i++)
435 linear[i] = ((i * getpagesize()) | PAGE_PRESENT);
436
Rusty Russell47436aa2007-10-22 11:03:36 +1000437 /* The top level points to the linear page table pages above. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700438 for (i = 0; i < mapped_pages; i += ptes_per_page) {
Rusty Russell47436aa2007-10-22 11:03:36 +1000439 pgdir[i/ptes_per_page]
Jes Sorensen511801d2007-10-22 11:03:31 +1000440 = ((to_guest_phys(linear) + i*sizeof(void *))
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000441 | PAGE_PRESENT);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700442 }
443
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000444 verbose("Linear mapping of %u pages in %u pte pages at %#lx\n",
445 mapped_pages, linear_pages, to_guest_phys(linear));
Rusty Russell8ca47e02007-07-19 01:49:29 -0700446
Rusty Russelldde79782007-07-26 10:41:03 -0700447 /* We return the top level (guest-physical) address: the kernel needs
448 * to know where it is. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000449 return to_guest_phys(pgdir);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700450}
451
Rusty Russelldde79782007-07-26 10:41:03 -0700452/* Simple routine to roll all the commandline arguments together with spaces
453 * between them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700454static void concat(char *dst, char *args[])
455{
456 unsigned int i, len = 0;
457
458 for (i = 0; args[i]; i++) {
459 strcpy(dst+len, args[i]);
460 strcat(dst+len, " ");
461 len += strlen(args[i]) + 1;
462 }
463 /* In case it's empty. */
464 dst[len] = '\0';
465}
466
Rusty Russelldde79782007-07-26 10:41:03 -0700467/* This is where we actually tell the kernel to initialize the Guest. We saw
468 * the arguments it expects when we looked at initialize() in lguest_user.c:
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000469 * the base of guest "physical" memory, the top physical page to allow, the
Rusty Russell47436aa2007-10-22 11:03:36 +1000470 * top level pagetable and the entry point for the Guest. */
471static int tell_kernel(unsigned long pgdir, unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700472{
Jes Sorensen511801d2007-10-22 11:03:31 +1000473 unsigned long args[] = { LHREQ_INITIALIZE,
474 (unsigned long)guest_base,
Rusty Russell47436aa2007-10-22 11:03:36 +1000475 guest_limit / getpagesize(), pgdir, start };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700476 int fd;
477
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000478 verbose("Guest: %p - %p (%#lx)\n",
479 guest_base, guest_base + guest_limit, guest_limit);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700480 fd = open_or_die("/dev/lguest", O_RDWR);
481 if (write(fd, args, sizeof(args)) < 0)
482 err(1, "Writing to /dev/lguest");
Rusty Russelldde79782007-07-26 10:41:03 -0700483
484 /* We return the /dev/lguest file descriptor to control this Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700485 return fd;
486}
Rusty Russelldde79782007-07-26 10:41:03 -0700487/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700488
489static void set_fd(int fd, struct device_list *devices)
490{
491 FD_SET(fd, &devices->infds);
492 if (fd > devices->max_infd)
493 devices->max_infd = fd;
494}
495
Rusty Russelldde79782007-07-26 10:41:03 -0700496/*L:200
497 * The Waker.
498 *
499 * With a console and network devices, we can have lots of input which we need
500 * to process. We could try to tell the kernel what file descriptors to watch,
501 * but handing a file descriptor mask through to the kernel is fairly icky.
502 *
503 * Instead, we fork off a process which watches the file descriptors and writes
504 * the LHREQ_BREAK command to the /dev/lguest filedescriptor to tell the Host
505 * loop to stop running the Guest. This causes it to return from the
506 * /dev/lguest read with -EAGAIN, where it will write to /dev/lguest to reset
507 * the LHREQ_BREAK and wake us up again.
508 *
509 * This, of course, is merely a different *kind* of icky.
510 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700511static void wake_parent(int pipefd, int lguest_fd, struct device_list *devices)
512{
Rusty Russelldde79782007-07-26 10:41:03 -0700513 /* Add the pipe from the Launcher to the fdset in the device_list, so
514 * we watch it, too. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700515 set_fd(pipefd, devices);
516
517 for (;;) {
518 fd_set rfds = devices->infds;
Jes Sorensen511801d2007-10-22 11:03:31 +1000519 unsigned long args[] = { LHREQ_BREAK, 1 };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700520
Rusty Russelldde79782007-07-26 10:41:03 -0700521 /* Wait until input is ready from one of the devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700522 select(devices->max_infd+1, &rfds, NULL, NULL, NULL);
Rusty Russelldde79782007-07-26 10:41:03 -0700523 /* Is it a message from the Launcher? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700524 if (FD_ISSET(pipefd, &rfds)) {
525 int ignorefd;
Rusty Russelldde79782007-07-26 10:41:03 -0700526 /* If read() returns 0, it means the Launcher has
527 * exited. We silently follow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700528 if (read(pipefd, &ignorefd, sizeof(ignorefd)) == 0)
529 exit(0);
Rusty Russelldde79782007-07-26 10:41:03 -0700530 /* Otherwise it's telling us there's a problem with one
531 * of the devices, and we should ignore that file
532 * descriptor from now on. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700533 FD_CLR(ignorefd, &devices->infds);
Rusty Russelldde79782007-07-26 10:41:03 -0700534 } else /* Send LHREQ_BREAK command. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700535 write(lguest_fd, args, sizeof(args));
536 }
537}
538
Rusty Russelldde79782007-07-26 10:41:03 -0700539/* This routine just sets up a pipe to the Waker process. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700540static int setup_waker(int lguest_fd, struct device_list *device_list)
541{
542 int pipefd[2], child;
543
Rusty Russelldde79782007-07-26 10:41:03 -0700544 /* We create a pipe to talk to the waker, and also so it knows when the
545 * Launcher dies (and closes pipe). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700546 pipe(pipefd);
547 child = fork();
548 if (child == -1)
549 err(1, "forking");
550
551 if (child == 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700552 /* Close the "writing" end of our copy of the pipe */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700553 close(pipefd[1]);
554 wake_parent(pipefd[0], lguest_fd, device_list);
555 }
Rusty Russelldde79782007-07-26 10:41:03 -0700556 /* Close the reading end of our copy of the pipe. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700557 close(pipefd[0]);
558
Rusty Russelldde79782007-07-26 10:41:03 -0700559 /* Here is the fd used to talk to the waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700560 return pipefd[1];
561}
562
Rusty Russelldde79782007-07-26 10:41:03 -0700563/*L:210
564 * Device Handling.
565 *
566 * When the Guest sends DMA to us, it sends us an array of addresses and sizes.
567 * We need to make sure it's not trying to reach into the Launcher itself, so
568 * we have a convenient routine which check it and exits with an error message
569 * if something funny is going on:
570 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700571static void *_check_pointer(unsigned long addr, unsigned int size,
572 unsigned int line)
573{
Rusty Russelldde79782007-07-26 10:41:03 -0700574 /* We have to separately check addr and addr+size, because size could
575 * be huge and addr + size might wrap around. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000576 if (addr >= guest_limit || addr + size >= guest_limit)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700577 errx(1, "%s:%i: Invalid address %li", __FILE__, line, addr);
Rusty Russelldde79782007-07-26 10:41:03 -0700578 /* We return a pointer for the caller's convenience, now we know it's
579 * safe to use. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000580 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700581}
Rusty Russelldde79782007-07-26 10:41:03 -0700582/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700583#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
584
Rusty Russelldde79782007-07-26 10:41:03 -0700585/* The Guest has given us the address of a "struct lguest_dma". We check it's
586 * OK and convert it to an iovec (which is a simple array of ptr/size
587 * pairs). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700588static u32 *dma2iov(unsigned long dma, struct iovec iov[], unsigned *num)
589{
590 unsigned int i;
591 struct lguest_dma *udma;
592
Rusty Russelldde79782007-07-26 10:41:03 -0700593 /* First we make sure that the array memory itself is valid. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700594 udma = check_pointer(dma, sizeof(*udma));
Rusty Russelldde79782007-07-26 10:41:03 -0700595 /* Now we check each element */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700596 for (i = 0; i < LGUEST_MAX_DMA_SECTIONS; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700597 /* A zero length ends the array. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700598 if (!udma->len[i])
599 break;
600
601 iov[i].iov_base = check_pointer(udma->addr[i], udma->len[i]);
602 iov[i].iov_len = udma->len[i];
603 }
604 *num = i;
Rusty Russelldde79782007-07-26 10:41:03 -0700605
606 /* We return the pointer to where the caller should write the amount of
607 * the buffer used. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700608 return &udma->used_len;
609}
610
Rusty Russelldde79782007-07-26 10:41:03 -0700611/* This routine gets a DMA buffer from the Guest for a given key, and converts
612 * it to an iovec array. It returns the interrupt the Guest wants when we're
613 * finished, and a pointer to the "used_len" field to fill in. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700614static u32 *get_dma_buffer(int fd, void *key,
615 struct iovec iov[], unsigned int *num, u32 *irq)
616{
Jes Sorensen511801d2007-10-22 11:03:31 +1000617 unsigned long buf[] = { LHREQ_GETDMA, to_guest_phys(key) };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700618 unsigned long udma;
619 u32 *res;
620
Rusty Russelldde79782007-07-26 10:41:03 -0700621 /* Ask the kernel for a DMA buffer corresponding to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700622 udma = write(fd, buf, sizeof(buf));
Rusty Russelldde79782007-07-26 10:41:03 -0700623 /* They haven't registered any, or they're all used? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700624 if (udma == (unsigned long)-1)
625 return NULL;
626
Rusty Russelldde79782007-07-26 10:41:03 -0700627 /* Convert it into our iovec array */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700628 res = dma2iov(udma, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700629 /* The kernel stashes irq in ->used_len to get it out to us. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700630 *irq = *res;
Rusty Russelldde79782007-07-26 10:41:03 -0700631 /* Return a pointer to ((struct lguest_dma *)udma)->used_len. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700632 return res;
633}
634
Rusty Russelldde79782007-07-26 10:41:03 -0700635/* This is a convenient routine to send the Guest an interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700636static void trigger_irq(int fd, u32 irq)
637{
Jes Sorensen511801d2007-10-22 11:03:31 +1000638 unsigned long buf[] = { LHREQ_IRQ, irq };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700639 if (write(fd, buf, sizeof(buf)) != 0)
640 err(1, "Triggering irq %i", irq);
641}
642
Rusty Russelldde79782007-07-26 10:41:03 -0700643/* This simply sets up an iovec array where we can put data to be discarded.
644 * This happens when the Guest doesn't want or can't handle the input: we have
645 * to get rid of it somewhere, and if we bury it in the ceiling space it will
646 * start to smell after a week. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700647static void discard_iovec(struct iovec *iov, unsigned int *num)
648{
649 static char discard_buf[1024];
650 *num = 1;
651 iov->iov_base = discard_buf;
652 iov->iov_len = sizeof(discard_buf);
653}
654
Rusty Russelldde79782007-07-26 10:41:03 -0700655/* Here is the input terminal setting we save, and the routine to restore them
656 * on exit so the user can see what they type next. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700657static struct termios orig_term;
658static void restore_term(void)
659{
660 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
661}
662
Rusty Russelldde79782007-07-26 10:41:03 -0700663/* We associate some data with the console for our exit hack. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700664struct console_abort
665{
Rusty Russelldde79782007-07-26 10:41:03 -0700666 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700667 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700668 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700669 struct timeval start;
670};
671
Rusty Russelldde79782007-07-26 10:41:03 -0700672/* This is the routine which handles console input (ie. stdin). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700673static bool handle_console_input(int fd, struct device *dev)
674{
675 u32 irq = 0, *lenp;
676 int len;
677 unsigned int num;
678 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
679 struct console_abort *abort = dev->priv;
680
Rusty Russelldde79782007-07-26 10:41:03 -0700681 /* First we get the console buffer from the Guest. The key is dev->mem
682 * which was set to 0 in setup_console(). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700683 lenp = get_dma_buffer(fd, dev->mem, iov, &num, &irq);
684 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700685 /* If it's not ready for input, warn and set up to discard. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700686 warn("console: no dma buffer!");
687 discard_iovec(iov, &num);
688 }
689
Rusty Russelldde79782007-07-26 10:41:03 -0700690 /* This is why we convert to iovecs: the readv() call uses them, and so
691 * it reads straight into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700692 len = readv(dev->fd, iov, num);
693 if (len <= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700694 /* This implies that the console is closed, is /dev/null, or
695 * something went terribly wrong. We still go through the rest
696 * of the logic, though, especially the exit handling below. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700697 warnx("Failed to get console input, ignoring console.");
698 len = 0;
699 }
700
Rusty Russelldde79782007-07-26 10:41:03 -0700701 /* If we read the data into the Guest, fill in the length and send the
702 * interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700703 if (lenp) {
704 *lenp = len;
705 trigger_irq(fd, irq);
706 }
707
Rusty Russelldde79782007-07-26 10:41:03 -0700708 /* Three ^C within one second? Exit.
709 *
710 * This is such a hack, but works surprisingly well. Each ^C has to be
711 * in a buffer by itself, so they can't be too fast. But we check that
712 * we get three within about a second, so they can't be too slow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700713 if (len == 1 && ((char *)iov[0].iov_base)[0] == 3) {
714 if (!abort->count++)
715 gettimeofday(&abort->start, NULL);
716 else if (abort->count == 3) {
717 struct timeval now;
718 gettimeofday(&now, NULL);
719 if (now.tv_sec <= abort->start.tv_sec+1) {
Jes Sorensen511801d2007-10-22 11:03:31 +1000720 unsigned long args[] = { LHREQ_BREAK, 0 };
Rusty Russelldde79782007-07-26 10:41:03 -0700721 /* Close the fd so Waker will know it has to
722 * exit. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700723 close(waker_fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700724 /* Just in case waker is blocked in BREAK, send
725 * unbreak now. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700726 write(fd, args, sizeof(args));
727 exit(2);
728 }
729 abort->count = 0;
730 }
731 } else
Rusty Russelldde79782007-07-26 10:41:03 -0700732 /* Any other key resets the abort counter. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700733 abort->count = 0;
734
Rusty Russelldde79782007-07-26 10:41:03 -0700735 /* Now, if we didn't read anything, put the input terminal back and
736 * return failure (meaning, don't call us again). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700737 if (!len) {
738 restore_term();
739 return false;
740 }
Rusty Russelldde79782007-07-26 10:41:03 -0700741 /* Everything went OK! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700742 return true;
743}
744
Rusty Russelldde79782007-07-26 10:41:03 -0700745/* Handling console output is much simpler than input. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700746static u32 handle_console_output(int fd, const struct iovec *iov,
747 unsigned num, struct device*dev)
748{
Rusty Russelldde79782007-07-26 10:41:03 -0700749 /* Whatever the Guest sends, write it to standard output. Return the
750 * number of bytes written. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700751 return writev(STDOUT_FILENO, iov, num);
752}
753
Rusty Russelldde79782007-07-26 10:41:03 -0700754/* Guest->Host network output is also pretty easy. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700755static u32 handle_tun_output(int fd, const struct iovec *iov,
756 unsigned num, struct device *dev)
757{
Rusty Russelldde79782007-07-26 10:41:03 -0700758 /* We put a flag in the "priv" pointer of the network device, and set
759 * it as soon as we see output. We'll see why in handle_tun_input() */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700760 *(bool *)dev->priv = true;
Rusty Russelldde79782007-07-26 10:41:03 -0700761 /* Whatever packet the Guest sent us, write it out to the tun
762 * device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700763 return writev(dev->fd, iov, num);
764}
765
Rusty Russelldde79782007-07-26 10:41:03 -0700766/* This matches the peer_key() in lguest_net.c. The key for any given slot
767 * is the address of the network device's page plus 4 * the slot number. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700768static unsigned long peer_offset(unsigned int peernum)
769{
770 return 4 * peernum;
771}
772
Rusty Russelldde79782007-07-26 10:41:03 -0700773/* This is where we handle a packet coming in from the tun device */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700774static bool handle_tun_input(int fd, struct device *dev)
775{
776 u32 irq = 0, *lenp;
777 int len;
778 unsigned num;
779 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
780
Rusty Russelldde79782007-07-26 10:41:03 -0700781 /* First we get a buffer the Guest has bound to its key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700782 lenp = get_dma_buffer(fd, dev->mem+peer_offset(NET_PEERNUM), iov, &num,
783 &irq);
784 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700785 /* Now, it's expected that if we try to send a packet too
786 * early, the Guest won't be ready yet. This is why we set a
787 * flag when the Guest sends its first packet. If it's sent a
788 * packet we assume it should be ready to receive them.
789 *
790 * Actually, this is what the status bits in the descriptor are
791 * for: we should *use* them. FIXME! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700792 if (*(bool *)dev->priv)
793 warn("network: no dma buffer!");
794 discard_iovec(iov, &num);
795 }
796
Rusty Russelldde79782007-07-26 10:41:03 -0700797 /* Read the packet from the device directly into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700798 len = readv(dev->fd, iov, num);
799 if (len <= 0)
800 err(1, "reading network");
Rusty Russelldde79782007-07-26 10:41:03 -0700801
802 /* Write the used_len, and trigger the interrupt for the Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700803 if (lenp) {
804 *lenp = len;
805 trigger_irq(fd, irq);
806 }
807 verbose("tun input packet len %i [%02x %02x] (%s)\n", len,
808 ((u8 *)iov[0].iov_base)[0], ((u8 *)iov[0].iov_base)[1],
809 lenp ? "sent" : "discarded");
Rusty Russelldde79782007-07-26 10:41:03 -0700810 /* All good. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700811 return true;
812}
813
Rusty Russelldde79782007-07-26 10:41:03 -0700814/* The last device handling routine is block output: the Guest has sent a DMA
815 * to the block device. It will have placed the command it wants in the
816 * "struct lguest_block_page". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700817static u32 handle_block_output(int fd, const struct iovec *iov,
818 unsigned num, struct device *dev)
819{
820 struct lguest_block_page *p = dev->mem;
821 u32 irq, *lenp;
822 unsigned int len, reply_num;
823 struct iovec reply[LGUEST_MAX_DMA_SECTIONS];
824 off64_t device_len, off = (off64_t)p->sector * 512;
825
Rusty Russelldde79782007-07-26 10:41:03 -0700826 /* First we extract the device length from the dev->priv pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700827 device_len = *(off64_t *)dev->priv;
828
Rusty Russelldde79782007-07-26 10:41:03 -0700829 /* We first check that the read or write is within the length of the
830 * block file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700831 if (off >= device_len)
Glauber de Oliveira Costababed5c2007-10-22 10:56:21 +1000832 errx(1, "Bad offset %llu vs %llu", off, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700833 /* Move to the right location in the block file. This shouldn't fail,
834 * but best to check. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700835 if (lseek64(dev->fd, off, SEEK_SET) != off)
836 err(1, "Bad seek to sector %i", p->sector);
837
838 verbose("Block: %s at offset %llu\n", p->type ? "WRITE" : "READ", off);
839
Rusty Russelldde79782007-07-26 10:41:03 -0700840 /* They were supposed to bind a reply buffer at key equal to the start
841 * of the block device memory. We need this to tell them when the
842 * request is finished. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700843 lenp = get_dma_buffer(fd, dev->mem, reply, &reply_num, &irq);
844 if (!lenp)
845 err(1, "Block request didn't give us a dma buffer");
846
847 if (p->type) {
Rusty Russelldde79782007-07-26 10:41:03 -0700848 /* A write request. The DMA they sent contained the data, so
849 * write it out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700850 len = writev(dev->fd, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700851 /* Grr... Now we know how long the "struct lguest_dma" they
852 * sent was, we make sure they didn't try to write over the end
853 * of the block file (possibly extending it). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700854 if (off + len > device_len) {
Rusty Russelldde79782007-07-26 10:41:03 -0700855 /* Trim it back to the correct length */
Chris Malleyf6a592e2007-09-26 14:19:18 +1000856 ftruncate64(dev->fd, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700857 /* Die, bad Guest, die. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700858 errx(1, "Write past end %llu+%u", off, len);
859 }
Rusty Russelldde79782007-07-26 10:41:03 -0700860 /* The reply length is 0: we just send back an empty DMA to
861 * interrupt them and tell them the write is finished. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700862 *lenp = 0;
863 } else {
Rusty Russelldde79782007-07-26 10:41:03 -0700864 /* A read request. They sent an empty DMA to start the
865 * request, and we put the read contents into the reply
866 * buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700867 len = readv(dev->fd, reply, reply_num);
868 *lenp = len;
869 }
870
Rusty Russelldde79782007-07-26 10:41:03 -0700871 /* The result is 1 (done), 2 if there was an error (short read or
872 * write). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700873 p->result = 1 + (p->bytes != len);
Rusty Russelldde79782007-07-26 10:41:03 -0700874 /* Now tell them we've used their reply buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700875 trigger_irq(fd, irq);
Rusty Russelldde79782007-07-26 10:41:03 -0700876
877 /* We're supposed to return the number of bytes of the output buffer we
878 * used. But the block device uses the "result" field instead, so we
879 * don't bother. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700880 return 0;
881}
882
Rusty Russelldde79782007-07-26 10:41:03 -0700883/* This is the generic routine we call when the Guest sends some DMA out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700884static void handle_output(int fd, unsigned long dma, unsigned long key,
885 struct device_list *devices)
886{
887 struct device *i;
888 u32 *lenp;
889 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
890 unsigned num = 0;
891
Rusty Russelldde79782007-07-26 10:41:03 -0700892 /* Convert the "struct lguest_dma" they're sending to a "struct
893 * iovec". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700894 lenp = dma2iov(dma, iov, &num);
Rusty Russelldde79782007-07-26 10:41:03 -0700895
896 /* Check each device: if they expect output to this key, tell them to
897 * handle it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700898 for (i = devices->dev; i; i = i->next) {
899 if (i->handle_output && key == i->watch_key) {
Rusty Russelldde79782007-07-26 10:41:03 -0700900 /* We write the result straight into the used_len field
901 * for them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700902 *lenp = i->handle_output(fd, iov, num, i);
903 return;
904 }
905 }
Rusty Russelldde79782007-07-26 10:41:03 -0700906
907 /* This can happen: the kernel sends any SEND_DMA which doesn't match
908 * another Guest to us. It could be that another Guest just left a
909 * network, for example. But it's unusual. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700910 warnx("Pending dma %p, key %p", (void *)dma, (void *)key);
911}
912
Rusty Russelldde79782007-07-26 10:41:03 -0700913/* This is called when the waker wakes us up: check for incoming file
914 * descriptors. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700915static void handle_input(int fd, struct device_list *devices)
916{
Rusty Russelldde79782007-07-26 10:41:03 -0700917 /* select() wants a zeroed timeval to mean "don't wait". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700918 struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
919
920 for (;;) {
921 struct device *i;
922 fd_set fds = devices->infds;
923
Rusty Russelldde79782007-07-26 10:41:03 -0700924 /* If nothing is ready, we're done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700925 if (select(devices->max_infd+1, &fds, NULL, NULL, &poll) == 0)
926 break;
927
Rusty Russelldde79782007-07-26 10:41:03 -0700928 /* Otherwise, call the device(s) which have readable
929 * file descriptors and a method of handling them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700930 for (i = devices->dev; i; i = i->next) {
931 if (i->handle_input && FD_ISSET(i->fd, &fds)) {
Rusty Russelldde79782007-07-26 10:41:03 -0700932 /* If handle_input() returns false, it means we
933 * should no longer service it.
934 * handle_console_input() does this. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700935 if (!i->handle_input(fd, i)) {
Rusty Russelldde79782007-07-26 10:41:03 -0700936 /* Clear it from the set of input file
937 * descriptors kept at the head of the
938 * device list. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700939 FD_CLR(i->fd, &devices->infds);
940 /* Tell waker to ignore it too... */
941 write(waker_fd, &i->fd, sizeof(i->fd));
942 }
943 }
944 }
945 }
946}
947
Rusty Russelldde79782007-07-26 10:41:03 -0700948/*L:190
949 * Device Setup
950 *
951 * All devices need a descriptor so the Guest knows it exists, and a "struct
952 * device" so the Launcher can keep track of it. We have common helper
953 * routines to allocate them.
954 *
955 * This routine allocates a new "struct lguest_device_desc" from descriptor
956 * table in the devices array just above the Guest's normal memory. */
Rusty Russell6570c45992007-07-23 18:43:56 -0700957static struct lguest_device_desc *
958new_dev_desc(struct lguest_device_desc *descs,
959 u16 type, u16 features, u16 num_pages)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700960{
Rusty Russell6570c45992007-07-23 18:43:56 -0700961 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700962
Rusty Russell6570c45992007-07-23 18:43:56 -0700963 for (i = 0; i < LGUEST_MAX_DEVICES; i++) {
964 if (!descs[i].type) {
965 descs[i].type = type;
966 descs[i].features = features;
967 descs[i].num_pages = num_pages;
Rusty Russelldde79782007-07-26 10:41:03 -0700968 /* If they said the device needs memory, we allocate
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000969 * that now. */
Rusty Russell6570c45992007-07-23 18:43:56 -0700970 if (num_pages) {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000971 unsigned long pa;
972 pa = to_guest_phys(get_pages(num_pages));
973 descs[i].pfn = pa / getpagesize();
Rusty Russell6570c45992007-07-23 18:43:56 -0700974 }
975 return &descs[i];
976 }
977 }
978 errx(1, "too many devices");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700979}
980
Rusty Russelldde79782007-07-26 10:41:03 -0700981/* This monster routine does all the creation and setup of a new device,
982 * including caling new_dev_desc() to allocate the descriptor and device
983 * memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700984static struct device *new_device(struct device_list *devices,
985 u16 type, u16 num_pages, u16 features,
986 int fd,
987 bool (*handle_input)(int, struct device *),
988 unsigned long watch_off,
989 u32 (*handle_output)(int,
990 const struct iovec *,
991 unsigned,
992 struct device *))
993{
994 struct device *dev = malloc(sizeof(*dev));
995
Rusty Russelldde79782007-07-26 10:41:03 -0700996 /* Append to device list. Prepending to a single-linked list is
997 * easier, but the user expects the devices to be arranged on the bus
998 * in command-line order. The first network device on the command line
999 * is eth0, the first block device /dev/lgba, etc. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001000 *devices->lastdev = dev;
1001 dev->next = NULL;
1002 devices->lastdev = &dev->next;
1003
Rusty Russelldde79782007-07-26 10:41:03 -07001004 /* Now we populate the fields one at a time. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001005 dev->fd = fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001006 /* If we have an input handler for this file descriptor, then we add it
1007 * to the device_list's fdset and maxfd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001008 if (handle_input)
1009 set_fd(dev->fd, devices);
Rusty Russell6570c45992007-07-23 18:43:56 -07001010 dev->desc = new_dev_desc(devices->descs, type, features, num_pages);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001011 dev->mem = from_guest_phys(dev->desc->pfn * getpagesize());
Rusty Russell8ca47e02007-07-19 01:49:29 -07001012 dev->handle_input = handle_input;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001013 dev->watch_key = to_guest_phys(dev->mem) + watch_off;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001014 dev->handle_output = handle_output;
1015 return dev;
1016}
1017
Rusty Russelldde79782007-07-26 10:41:03 -07001018/* Our first setup routine is the console. It's a fairly simple device, but
1019 * UNIX tty handling makes it uglier than it could be. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001020static void setup_console(struct device_list *devices)
1021{
1022 struct device *dev;
1023
Rusty Russelldde79782007-07-26 10:41:03 -07001024 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001025 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1026 struct termios term = orig_term;
Rusty Russelldde79782007-07-26 10:41:03 -07001027 /* Then we turn off echo, line buffering and ^C etc. We want a
1028 * raw input stream to the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001029 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1030 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russelldde79782007-07-26 10:41:03 -07001031 /* If we exit gracefully, the original settings will be
1032 * restored so the user can see what they're typing. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001033 atexit(restore_term);
1034 }
1035
Rusty Russelldde79782007-07-26 10:41:03 -07001036 /* We don't currently require any memory for the console, so we ask for
1037 * 0 pages. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001038 dev = new_device(devices, LGUEST_DEVICE_T_CONSOLE, 0, 0,
1039 STDIN_FILENO, handle_console_input,
1040 LGUEST_CONSOLE_DMA_KEY, handle_console_output);
Rusty Russelldde79782007-07-26 10:41:03 -07001041 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001042 dev->priv = malloc(sizeof(struct console_abort));
1043 ((struct console_abort *)dev->priv)->count = 0;
1044 verbose("device %p: console\n",
1045 (void *)(dev->desc->pfn * getpagesize()));
1046}
1047
Rusty Russelldde79782007-07-26 10:41:03 -07001048/* Setting up a block file is also fairly straightforward. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001049static void setup_block_file(const char *filename, struct device_list *devices)
1050{
1051 int fd;
1052 struct device *dev;
1053 off64_t *device_len;
1054 struct lguest_block_page *p;
1055
Rusty Russelldde79782007-07-26 10:41:03 -07001056 /* We open with O_LARGEFILE because otherwise we get stuck at 2G. We
1057 * open with O_DIRECT because otherwise our benchmarks go much too
1058 * fast. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001059 fd = open_or_die(filename, O_RDWR|O_LARGEFILE|O_DIRECT);
Rusty Russelldde79782007-07-26 10:41:03 -07001060
1061 /* We want one page, and have no input handler (the block file never
1062 * has anything interesting to say to us). Our timing will be quite
1063 * random, so it should be a reasonable randomness source. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001064 dev = new_device(devices, LGUEST_DEVICE_T_BLOCK, 1,
1065 LGUEST_DEVICE_F_RANDOMNESS,
1066 fd, NULL, 0, handle_block_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001067
Rusty Russelldde79782007-07-26 10:41:03 -07001068 /* We store the device size in the private area */
1069 device_len = dev->priv = malloc(sizeof(*device_len));
1070 /* This is the safe way of establishing the size of our device: it
1071 * might be a normal file or an actual block device like /dev/hdb. */
1072 *device_len = lseek64(fd, 0, SEEK_END);
1073
1074 /* The device memory is a "struct lguest_block_page". It's zeroed
1075 * already, we just need to put in the device size. Block devices
1076 * think in sectors (ie. 512 byte chunks), so we translate here. */
1077 p = dev->mem;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001078 p->num_sectors = *device_len/512;
1079 verbose("device %p: block %i sectors\n",
1080 (void *)(dev->desc->pfn * getpagesize()), p->num_sectors);
1081}
1082
Rusty Russelldde79782007-07-26 10:41:03 -07001083/*
1084 * Network Devices.
1085 *
1086 * Setting up network devices is quite a pain, because we have three types.
1087 * First, we have the inter-Guest network. This is a file which is mapped into
1088 * the address space of the Guests who are on the network. Because it is a
1089 * shared mapping, the same page underlies all the devices, and they can send
1090 * DMA to each other.
1091 *
1092 * Remember from our network driver, the Guest is told what slot in the page it
1093 * is to use. We use exclusive fnctl locks to reserve a slot. If another
1094 * Guest is using a slot, the lock will fail and we try another. Because fnctl
1095 * locks are cleaned up automatically when we die, this cleverly means that our
1096 * reservation on the slot will vanish if we crash. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001097static unsigned int find_slot(int netfd, const char *filename)
1098{
1099 struct flock fl;
1100
1101 fl.l_type = F_WRLCK;
1102 fl.l_whence = SEEK_SET;
1103 fl.l_len = 1;
Rusty Russelldde79782007-07-26 10:41:03 -07001104 /* Try a 1 byte lock in each possible position number */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001105 for (fl.l_start = 0;
1106 fl.l_start < getpagesize()/sizeof(struct lguest_net);
1107 fl.l_start++) {
Rusty Russelldde79782007-07-26 10:41:03 -07001108 /* If we succeed, return the slot number. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001109 if (fcntl(netfd, F_SETLK, &fl) == 0)
1110 return fl.l_start;
1111 }
1112 errx(1, "No free slots in network file %s", filename);
1113}
1114
Rusty Russelldde79782007-07-26 10:41:03 -07001115/* This function sets up the network file */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001116static void setup_net_file(const char *filename,
1117 struct device_list *devices)
1118{
1119 int netfd;
1120 struct device *dev;
1121
Rusty Russelldde79782007-07-26 10:41:03 -07001122 /* We don't use open_or_die() here: for friendliness we create the file
1123 * if it doesn't already exist. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001124 netfd = open(filename, O_RDWR, 0);
1125 if (netfd < 0) {
1126 if (errno == ENOENT) {
1127 netfd = open(filename, O_RDWR|O_CREAT, 0600);
1128 if (netfd >= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -07001129 /* If we succeeded, initialize the file with a
1130 * blank page. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001131 char page[getpagesize()];
1132 memset(page, 0, sizeof(page));
1133 write(netfd, page, sizeof(page));
1134 }
1135 }
1136 if (netfd < 0)
1137 err(1, "cannot open net file '%s'", filename);
1138 }
1139
Rusty Russelldde79782007-07-26 10:41:03 -07001140 /* We need 1 page, and the features indicate the slot to use and that
1141 * no checksum is needed. We never touch this device again; it's
1142 * between the Guests on the network, so we don't register input or
1143 * output handlers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001144 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1145 find_slot(netfd, filename)|LGUEST_NET_F_NOCSUM,
1146 -1, NULL, 0, NULL);
1147
Rusty Russelldde79782007-07-26 10:41:03 -07001148 /* Map the shared file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001149 if (mmap(dev->mem, getpagesize(), PROT_READ|PROT_WRITE,
1150 MAP_FIXED|MAP_SHARED, netfd, 0) != dev->mem)
1151 err(1, "could not mmap '%s'", filename);
1152 verbose("device %p: shared net %s, peer %i\n",
1153 (void *)(dev->desc->pfn * getpagesize()), filename,
1154 dev->desc->features & ~LGUEST_NET_F_NOCSUM);
1155}
Rusty Russelldde79782007-07-26 10:41:03 -07001156/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001157
1158static u32 str2ip(const char *ipaddr)
1159{
1160 unsigned int byte[4];
1161
1162 sscanf(ipaddr, "%u.%u.%u.%u", &byte[0], &byte[1], &byte[2], &byte[3]);
1163 return (byte[0] << 24) | (byte[1] << 16) | (byte[2] << 8) | byte[3];
1164}
1165
Rusty Russelldde79782007-07-26 10:41:03 -07001166/* This code is "adapted" from libbridge: it attaches the Host end of the
1167 * network device to the bridge device specified by the command line.
1168 *
1169 * This is yet another James Morris contribution (I'm an IP-level guy, so I
1170 * dislike bridging), and I just try not to break it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001171static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1172{
1173 int ifidx;
1174 struct ifreq ifr;
1175
1176 if (!*br_name)
1177 errx(1, "must specify bridge name");
1178
1179 ifidx = if_nametoindex(if_name);
1180 if (!ifidx)
1181 errx(1, "interface %s does not exist!", if_name);
1182
1183 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
1184 ifr.ifr_ifindex = ifidx;
1185 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1186 err(1, "can't add %s to bridge %s", if_name, br_name);
1187}
1188
Rusty Russelldde79782007-07-26 10:41:03 -07001189/* This sets up the Host end of the network device with an IP address, brings
1190 * it up so packets will flow, the copies the MAC address into the hwaddr
1191 * pointer (in practice, the Host's slot in the network device's memory). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001192static void configure_device(int fd, const char *devname, u32 ipaddr,
1193 unsigned char hwaddr[6])
1194{
1195 struct ifreq ifr;
1196 struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
1197
Rusty Russelldde79782007-07-26 10:41:03 -07001198 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001199 memset(&ifr, 0, sizeof(ifr));
1200 strcpy(ifr.ifr_name, devname);
1201 sin->sin_family = AF_INET;
1202 sin->sin_addr.s_addr = htonl(ipaddr);
1203 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
1204 err(1, "Setting %s interface address", devname);
1205 ifr.ifr_flags = IFF_UP;
1206 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
1207 err(1, "Bringing interface %s up", devname);
1208
Rusty Russelldde79782007-07-26 10:41:03 -07001209 /* SIOC stands for Socket I/O Control. G means Get (vs S for Set
1210 * above). IF means Interface, and HWADDR is hardware address.
1211 * Simple! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001212 if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0)
1213 err(1, "getting hw address for %s", devname);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001214 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);
1215}
1216
Rusty Russelldde79782007-07-26 10:41:03 -07001217/*L:195 The other kind of network is a Host<->Guest network. This can either
1218 * use briding or routing, but the principle is the same: it uses the "tun"
1219 * device to inject packets into the Host as if they came in from a normal
1220 * network card. We just shunt packets between the Guest and the tun
1221 * device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001222static void setup_tun_net(const char *arg, struct device_list *devices)
1223{
1224 struct device *dev;
1225 struct ifreq ifr;
1226 int netfd, ipfd;
1227 u32 ip;
1228 const char *br_name = NULL;
1229
Rusty Russelldde79782007-07-26 10:41:03 -07001230 /* We open the /dev/net/tun device and tell it we want a tap device. A
1231 * tap device is like a tun device, only somehow different. To tell
1232 * the truth, I completely blundered my way through this code, but it
1233 * works now! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001234 netfd = open_or_die("/dev/net/tun", O_RDWR);
1235 memset(&ifr, 0, sizeof(ifr));
1236 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1237 strcpy(ifr.ifr_name, "tap%d");
1238 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1239 err(1, "configuring /dev/net/tun");
Rusty Russelldde79782007-07-26 10:41:03 -07001240 /* We don't need checksums calculated for packets coming in this
1241 * device: trust us! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001242 ioctl(netfd, TUNSETNOCSUM, 1);
1243
Rusty Russelldde79782007-07-26 10:41:03 -07001244 /* We create the net device with 1 page, using the features field of
1245 * the descriptor to tell the Guest it is in slot 1 (NET_PEERNUM), and
1246 * that the device has fairly random timing. We do *not* specify
1247 * LGUEST_NET_F_NOCSUM: these packets can reach the real world.
1248 *
1249 * We will put our MAC address is slot 0 for the Guest to see, so
1250 * it will send packets to us using the key "peer_offset(0)": */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001251 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1252 NET_PEERNUM|LGUEST_DEVICE_F_RANDOMNESS, netfd,
1253 handle_tun_input, peer_offset(0), handle_tun_output);
Rusty Russelldde79782007-07-26 10:41:03 -07001254
1255 /* We keep a flag which says whether we've seen packets come out from
1256 * this network device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001257 dev->priv = malloc(sizeof(bool));
1258 *(bool *)dev->priv = false;
1259
Rusty Russelldde79782007-07-26 10:41:03 -07001260 /* We need a socket to perform the magic network ioctls to bring up the
1261 * tap interface, connect to the bridge etc. Any socket will do! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001262 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1263 if (ipfd < 0)
1264 err(1, "opening IP socket");
1265
Rusty Russelldde79782007-07-26 10:41:03 -07001266 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001267 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
1268 ip = INADDR_ANY;
1269 br_name = arg + strlen(BRIDGE_PFX);
1270 add_to_bridge(ipfd, ifr.ifr_name, br_name);
Rusty Russelldde79782007-07-26 10:41:03 -07001271 } else /* It is an IP address to set up the device with */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001272 ip = str2ip(arg);
1273
Rusty Russelldde79782007-07-26 10:41:03 -07001274 /* We are peer 0, ie. first slot, so we hand dev->mem to this routine
1275 * to write the MAC address at the start of the device memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001276 configure_device(ipfd, ifr.ifr_name, ip, dev->mem);
1277
Rusty Russelldde79782007-07-26 10:41:03 -07001278 /* Set "promisc" bit: we want every single packet if we're going to
1279 * bridge to other machines (and otherwise it doesn't matter). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001280 *((u8 *)dev->mem) |= 0x1;
1281
1282 close(ipfd);
1283
1284 verbose("device %p: tun net %u.%u.%u.%u\n",
1285 (void *)(dev->desc->pfn * getpagesize()),
1286 (u8)(ip>>24), (u8)(ip>>16), (u8)(ip>>8), (u8)ip);
1287 if (br_name)
1288 verbose("attached to bridge: %s\n", br_name);
1289}
Rusty Russelldde79782007-07-26 10:41:03 -07001290/* That's the end of device setup. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001291
Rusty Russelldde79782007-07-26 10:41:03 -07001292/*L:220 Finally we reach the core of the Launcher, which runs the Guest, serves
1293 * its input and output, and finally, lays it to rest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001294static void __attribute__((noreturn))
1295run_guest(int lguest_fd, struct device_list *device_list)
1296{
1297 for (;;) {
Jes Sorensen511801d2007-10-22 11:03:31 +10001298 unsigned long args[] = { LHREQ_BREAK, 0 };
Rusty Russell8ca47e02007-07-19 01:49:29 -07001299 unsigned long arr[2];
1300 int readval;
1301
1302 /* We read from the /dev/lguest device to run the Guest. */
1303 readval = read(lguest_fd, arr, sizeof(arr));
1304
Rusty Russelldde79782007-07-26 10:41:03 -07001305 /* The read can only really return sizeof(arr) (the Guest did a
1306 * SEND_DMA to us), or an error. */
1307
1308 /* For a successful read, arr[0] is the address of the "struct
1309 * lguest_dma", and arr[1] is the key the Guest sent to. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001310 if (readval == sizeof(arr)) {
1311 handle_output(lguest_fd, arr[0], arr[1], device_list);
1312 continue;
Rusty Russelldde79782007-07-26 10:41:03 -07001313 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001314 } else if (errno == ENOENT) {
1315 char reason[1024] = { 0 };
1316 read(lguest_fd, reason, sizeof(reason)-1);
1317 errx(1, "%s", reason);
Rusty Russelldde79782007-07-26 10:41:03 -07001318 /* EAGAIN means the waker wanted us to look at some input.
1319 * Anything else means a bug or incompatible change. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001320 } else if (errno != EAGAIN)
1321 err(1, "Running guest failed");
Rusty Russelldde79782007-07-26 10:41:03 -07001322
1323 /* Service input, then unset the BREAK which releases
1324 * the Waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001325 handle_input(lguest_fd, device_list);
1326 if (write(lguest_fd, args, sizeof(args)) < 0)
1327 err(1, "Resetting break");
1328 }
1329}
Rusty Russelldde79782007-07-26 10:41:03 -07001330/*
1331 * This is the end of the Launcher.
1332 *
1333 * But wait! We've seen I/O from the Launcher, and we've seen I/O from the
1334 * Drivers. If we were to see the Host kernel I/O code, our understanding
1335 * would be complete... :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001336
1337static struct option opts[] = {
1338 { "verbose", 0, NULL, 'v' },
1339 { "sharenet", 1, NULL, 's' },
1340 { "tunnet", 1, NULL, 't' },
1341 { "block", 1, NULL, 'b' },
1342 { "initrd", 1, NULL, 'i' },
1343 { NULL },
1344};
1345static void usage(void)
1346{
1347 errx(1, "Usage: lguest [--verbose] "
1348 "[--sharenet=<filename>|--tunnet=(<ipaddr>|bridge:<bridgename>)\n"
1349 "|--block=<filename>|--initrd=<filename>]...\n"
1350 "<mem-in-mb> vmlinux [args...]");
1351}
1352
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001353/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001354int main(int argc, char *argv[])
1355{
Rusty Russell47436aa2007-10-22 11:03:36 +10001356 /* Memory, top-level pagetable, code startpoint and size of the
1357 * (optional) initrd. */
1358 unsigned long mem = 0, pgdir, start, initrd_size = 0;
Rusty Russelldde79782007-07-26 10:41:03 -07001359 /* A temporary and the /dev/lguest file descriptor. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001360 int i, c, lguest_fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001361 /* The list of Guest devices, based on command line arguments. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001362 struct device_list device_list;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001363 /* The boot information for the Guest. */
1364 void *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07001365 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001366 const char *initrd_name = NULL;
1367
Rusty Russelldde79782007-07-26 10:41:03 -07001368 /* First we initialize the device list. Since console and network
1369 * device receive input from a file descriptor, we keep an fdset
1370 * (infds) and the maximum fd number (max_infd) with the head of the
1371 * list. We also keep a pointer to the last device, for easy appending
1372 * to the list. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001373 device_list.max_infd = -1;
1374 device_list.dev = NULL;
1375 device_list.lastdev = &device_list.dev;
1376 FD_ZERO(&device_list.infds);
1377
Rusty Russelldde79782007-07-26 10:41:03 -07001378 /* We need to know how much memory so we can set up the device
1379 * descriptor and memory pages for the devices as we parse the command
1380 * line. So we quickly look through the arguments to find the amount
1381 * of memory now. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001382 for (i = 1; i < argc; i++) {
1383 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001384 mem = atoi(argv[i]) * 1024 * 1024;
1385 /* We start by mapping anonymous pages over all of
1386 * guest-physical memory range. This fills it with 0,
1387 * and ensures that the Guest won't be killed when it
1388 * tries to access it. */
1389 guest_base = map_zeroed_pages(mem / getpagesize()
1390 + DEVICE_PAGES);
1391 guest_limit = mem;
1392 guest_max = mem + DEVICE_PAGES*getpagesize();
1393 device_list.descs = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07001394 break;
1395 }
1396 }
Rusty Russelldde79782007-07-26 10:41:03 -07001397
1398 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001399 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
1400 switch (c) {
1401 case 'v':
1402 verbose = true;
1403 break;
1404 case 's':
1405 setup_net_file(optarg, &device_list);
1406 break;
1407 case 't':
1408 setup_tun_net(optarg, &device_list);
1409 break;
1410 case 'b':
1411 setup_block_file(optarg, &device_list);
1412 break;
1413 case 'i':
1414 initrd_name = optarg;
1415 break;
1416 default:
1417 warnx("Unknown argument %s", argv[optind]);
1418 usage();
1419 }
1420 }
Rusty Russelldde79782007-07-26 10:41:03 -07001421 /* After the other arguments we expect memory and kernel image name,
1422 * followed by command line arguments for the kernel. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001423 if (optind + 2 > argc)
1424 usage();
1425
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001426 verbose("Guest base is at %p\n", guest_base);
1427
Rusty Russelldde79782007-07-26 10:41:03 -07001428 /* We always have a console device */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001429 setup_console(&device_list);
1430
Rusty Russell8ca47e02007-07-19 01:49:29 -07001431 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10001432 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001433
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001434 /* Boot information is stashed at physical address 0 */
1435 boot = from_guest_phys(0);
1436
Rusty Russelldde79782007-07-26 10:41:03 -07001437 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001438 if (initrd_name) {
1439 initrd_size = load_initrd(initrd_name, mem);
Rusty Russelldde79782007-07-26 10:41:03 -07001440 /* These are the location in the Linux boot header where the
1441 * start and size of the initrd are expected to be found. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001442 *(unsigned long *)(boot+0x218) = mem - initrd_size;
1443 *(unsigned long *)(boot+0x21c) = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07001444 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001445 *(unsigned char *)(boot+0x210) = 0xFF;
1446 }
1447
Rusty Russelldde79782007-07-26 10:41:03 -07001448 /* Set up the initial linear pagetables, starting below the initrd. */
Rusty Russell47436aa2007-10-22 11:03:36 +10001449 pgdir = setup_pagetables(mem, initrd_size);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001450
Rusty Russelldde79782007-07-26 10:41:03 -07001451 /* The Linux boot header contains an "E820" memory map: ours is a
1452 * simple, single region. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001453 *(char*)(boot+E820NR) = 1;
1454 *((struct e820entry *)(boot+E820MAP))
1455 = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russelldde79782007-07-26 10:41:03 -07001456 /* The boot header contains a command line pointer: we put the command
1457 * line after the boot header (at address 4096) */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10001458 *(u32 *)(boot + 0x228) = 4096;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001459 concat(boot + 4096, argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07001460
1461 /* The guest type value of "1" tells the Guest it's under lguest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001462 *(int *)(boot + 0x23c) = 1;
1463
Rusty Russelldde79782007-07-26 10:41:03 -07001464 /* We tell the kernel to initialize the Guest: this returns the open
1465 * /dev/lguest file descriptor. */
Rusty Russell47436aa2007-10-22 11:03:36 +10001466 lguest_fd = tell_kernel(pgdir, start);
Rusty Russelldde79782007-07-26 10:41:03 -07001467
1468 /* We fork off a child process, which wakes the Launcher whenever one
1469 * of the input file descriptors needs attention. Otherwise we would
1470 * run the Guest until it tries to output something. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001471 waker_fd = setup_waker(lguest_fd, &device_list);
1472
Rusty Russelldde79782007-07-26 10:41:03 -07001473 /* Finally, run the Guest. This doesn't return. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001474 run_guest(lguest_fd, &device_list);
1475}
Rusty Russellf56a3842007-07-26 10:41:05 -07001476/*:*/
1477
1478/*M:999
1479 * Mastery is done: you now know everything I do.
1480 *
1481 * But surely you have seen code, features and bugs in your wanderings which
1482 * you now yearn to attack? That is the real game, and I look forward to you
1483 * patching and forking lguest into the Your-Name-Here-visor.
1484 *
1485 * Farewell, and good coding!
1486 * Rusty Russell.
1487 */