blob: d7e26f02595923c13c7b962bde33f5d704252976 [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.
4 *
5 * The only trick: the Makefile links it at a high address so it will be clear
6 * of the guest memory region. It means that each Guest cannot have more than
7 * about 2.5G of memory on a normally configured Host. :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07008#define _LARGEFILE64_SOURCE
9#define _GNU_SOURCE
10#include <stdio.h>
11#include <string.h>
12#include <unistd.h>
13#include <err.h>
14#include <stdint.h>
15#include <stdlib.h>
16#include <elf.h>
17#include <sys/mman.h>
18#include <sys/types.h>
19#include <sys/stat.h>
20#include <sys/wait.h>
21#include <fcntl.h>
22#include <stdbool.h>
23#include <errno.h>
24#include <ctype.h>
25#include <sys/socket.h>
26#include <sys/ioctl.h>
27#include <sys/time.h>
28#include <time.h>
29#include <netinet/in.h>
30#include <net/if.h>
31#include <linux/sockios.h>
32#include <linux/if_tun.h>
33#include <sys/uio.h>
34#include <termios.h>
35#include <getopt.h>
36#include <zlib.h>
Rusty Russelldde79782007-07-26 10:41:03 -070037/*L:110 We can ignore the 28 include files we need for this program, but I do
38 * want to draw attention to the use of kernel-style types.
39 *
40 * As Linus said, "C is a Spartan language, and so should your naming be." I
41 * like these abbreviations and the header we need uses them, so we define them
42 * here.
43 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070044typedef unsigned long long u64;
45typedef uint32_t u32;
46typedef uint16_t u16;
47typedef uint8_t u8;
48#include "../../include/linux/lguest_launcher.h"
49#include "../../include/asm-i386/e820.h"
Rusty Russelldde79782007-07-26 10:41:03 -070050/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070051
52#define PAGE_PRESENT 0x7 /* Present, RW, Execute */
53#define NET_PEERNUM 1
54#define BRIDGE_PFX "bridge:"
55#ifndef SIOCBRADDIF
56#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
57#endif
58
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 Russelldde79782007-07-26 10:41:03 -070068/* The top of guest physical memory. */
Rusty Russell6570c45992007-07-23 18:43:56 -070069static u32 top;
Rusty Russell8ca47e02007-07-19 01:49:29 -070070
Rusty Russelldde79782007-07-26 10:41:03 -070071/* This is our list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070072struct device_list
73{
Rusty Russelldde79782007-07-26 10:41:03 -070074 /* Summary information about the devices in our list: ready to pass to
75 * select() to ask which need servicing.*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070076 fd_set infds;
77 int max_infd;
78
Rusty Russelldde79782007-07-26 10:41:03 -070079 /* The descriptor page for the devices. */
Rusty Russell6570c45992007-07-23 18:43:56 -070080 struct lguest_device_desc *descs;
Rusty Russelldde79782007-07-26 10:41:03 -070081
82 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070083 struct device *dev;
Rusty Russelldde79782007-07-26 10:41:03 -070084 /* ... And an end pointer so we can easily append new devices */
Rusty Russell8ca47e02007-07-19 01:49:29 -070085 struct device **lastdev;
86};
87
Rusty Russelldde79782007-07-26 10:41:03 -070088/* The device structure describes a single device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070089struct device
90{
Rusty Russelldde79782007-07-26 10:41:03 -070091 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070092 struct device *next;
Rusty Russelldde79782007-07-26 10:41:03 -070093 /* The descriptor for this device, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070094 struct lguest_device_desc *desc;
Rusty Russelldde79782007-07-26 10:41:03 -070095 /* The memory page(s) of this device, if any. Also mapped in Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -070096 void *mem;
97
Rusty Russelldde79782007-07-26 10:41:03 -070098 /* If handle_input is set, it wants to be called when this file
99 * descriptor is ready. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700100 int fd;
101 bool (*handle_input)(int fd, struct device *me);
102
Rusty Russelldde79782007-07-26 10:41:03 -0700103 /* If handle_output is set, it wants to be called when the Guest sends
104 * DMA to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700105 unsigned long watch_key;
106 u32 (*handle_output)(int fd, const struct iovec *iov,
107 unsigned int num, struct device *me);
108
109 /* Device-specific data. */
110 void *priv;
111};
112
Rusty Russelldde79782007-07-26 10:41:03 -0700113/*L:130
114 * Loading the Kernel.
115 *
116 * We start with couple of simple helper routines. open_or_die() avoids
117 * error-checking code cluttering the callers: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700118static int open_or_die(const char *name, int flags)
119{
120 int fd = open(name, flags);
121 if (fd < 0)
122 err(1, "Failed to open %s", name);
123 return fd;
124}
125
Rusty Russelldde79782007-07-26 10:41:03 -0700126/* map_zeroed_pages() takes a (page-aligned) address and a number of pages. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700127static void *map_zeroed_pages(unsigned long addr, unsigned int num)
128{
Rusty Russelldde79782007-07-26 10:41:03 -0700129 /* We cache the /dev/zero file-descriptor so we only open it once. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700130 static int fd = -1;
131
132 if (fd == -1)
133 fd = open_or_die("/dev/zero", O_RDONLY);
134
Rusty Russelldde79782007-07-26 10:41:03 -0700135 /* We use a private mapping (ie. if we write to the page, it will be
136 * copied), and obviously we insist that it be mapped where we ask. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700137 if (mmap((void *)addr, getpagesize() * num,
138 PROT_READ|PROT_WRITE|PROT_EXEC, MAP_FIXED|MAP_PRIVATE, fd, 0)
139 != (void *)addr)
140 err(1, "Mmaping %u pages of /dev/zero @%p", num, (void *)addr);
Rusty Russelldde79782007-07-26 10:41:03 -0700141
142 /* Returning the address is just a courtesy: can simplify callers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700143 return (void *)addr;
144}
145
Rusty Russelldde79782007-07-26 10:41:03 -0700146/* To find out where to start we look for the magic Guest string, which marks
147 * the code we see in lguest_asm.S. This is a hack which we are currently
148 * plotting to replace with the normal Linux entry point. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700149static unsigned long entry_point(void *start, void *end,
150 unsigned long page_offset)
151{
152 void *p;
153
Rusty Russelldde79782007-07-26 10:41:03 -0700154 /* The scan gives us the physical starting address. We want the
155 * virtual address in this case, and fortunately, we already figured
156 * out the physical-virtual difference and passed it here in
157 * "page_offset". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700158 for (p = start; p < end; p++)
159 if (memcmp(p, "GenuineLguest", strlen("GenuineLguest")) == 0)
160 return (long)p + strlen("GenuineLguest") + page_offset;
161
162 err(1, "Is this image a genuine lguest?");
163}
164
Rusty Russelldde79782007-07-26 10:41:03 -0700165/* This routine takes an open vmlinux image, which is in ELF, and maps it into
166 * the Guest memory. ELF = Embedded Linking Format, which is the format used
167 * by all modern binaries on Linux including the kernel.
168 *
169 * The ELF headers give *two* addresses: a physical address, and a virtual
170 * address. The Guest kernel expects to be placed in memory at the physical
171 * address, and the page tables set up so it will correspond to that virtual
172 * address. We return the difference between the virtual and physical
173 * addresses in the "page_offset" pointer.
174 *
175 * We return the starting address. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700176static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr,
177 unsigned long *page_offset)
178{
179 void *addr;
180 Elf32_Phdr phdr[ehdr->e_phnum];
181 unsigned int i;
182 unsigned long start = -1UL, end = 0;
183
Rusty Russelldde79782007-07-26 10:41:03 -0700184 /* Sanity checks on the main ELF header: an x86 executable with a
185 * reasonable number of correctly-sized program headers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700186 if (ehdr->e_type != ET_EXEC
187 || ehdr->e_machine != EM_386
188 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
189 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
190 errx(1, "Malformed elf header");
191
Rusty Russelldde79782007-07-26 10:41:03 -0700192 /* An ELF executable contains an ELF header and a number of "program"
193 * headers which indicate which parts ("segments") of the program to
194 * load where. */
195
196 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700197 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
198 err(1, "Seeking to program headers");
199 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
200 err(1, "Reading program headers");
201
Rusty Russelldde79782007-07-26 10:41:03 -0700202 /* We don't know page_offset yet. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700203 *page_offset = 0;
Rusty Russelldde79782007-07-26 10:41:03 -0700204
205 /* Try all the headers: there are usually only three. A read-only one,
206 * a read-write one, and a "note" section which isn't loadable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700207 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700208 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700209 if (phdr[i].p_type != PT_LOAD)
210 continue;
211
212 verbose("Section %i: size %i addr %p\n",
213 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
214
Rusty Russelldde79782007-07-26 10:41:03 -0700215 /* We expect a simple linear address space: every segment must
216 * have the same difference between virtual (p_vaddr) and
217 * physical (p_paddr) address. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700218 if (!*page_offset)
219 *page_offset = phdr[i].p_vaddr - phdr[i].p_paddr;
220 else if (*page_offset != phdr[i].p_vaddr - phdr[i].p_paddr)
221 errx(1, "Page offset of section %i different", i);
222
Rusty Russelldde79782007-07-26 10:41:03 -0700223 /* We track the first and last address we mapped, so we can
224 * tell entry_point() where to scan. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700225 if (phdr[i].p_paddr < start)
226 start = phdr[i].p_paddr;
227 if (phdr[i].p_paddr + phdr[i].p_filesz > end)
228 end = phdr[i].p_paddr + phdr[i].p_filesz;
229
Rusty Russelldde79782007-07-26 10:41:03 -0700230 /* We map this section of the file at its physical address. We
231 * map it read & write even if the header says this segment is
232 * read-only. The kernel really wants to be writable: it
233 * patches its own instructions which would normally be
234 * read-only.
235 *
236 * MAP_PRIVATE means that the page won't be copied until a
237 * write is done to it. This allows us to share much of the
238 * kernel memory between Guests. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700239 addr = mmap((void *)phdr[i].p_paddr,
240 phdr[i].p_filesz,
241 PROT_READ|PROT_WRITE|PROT_EXEC,
242 MAP_FIXED|MAP_PRIVATE,
243 elf_fd, phdr[i].p_offset);
244 if (addr != (void *)phdr[i].p_paddr)
245 err(1, "Mmaping vmlinux seg %i gave %p not %p",
246 i, addr, (void *)phdr[i].p_paddr);
247 }
248
249 return entry_point((void *)start, (void *)end, *page_offset);
250}
251
Rusty Russelldde79782007-07-26 10:41:03 -0700252/*L:170 Prepare to be SHOCKED and AMAZED. And possibly a trifle nauseated.
253 *
254 * We know that CONFIG_PAGE_OFFSET sets what virtual address the kernel expects
255 * to be. We don't know what that option was, but we can figure it out
256 * approximately by looking at the addresses in the code. I chose the common
257 * case of reading a memory location into the %eax register:
258 *
259 * movl <some-address>, %eax
260 *
261 * This gets encoded as five bytes: "0xA1 <4-byte-address>". For example,
262 * "0xA1 0x18 0x60 0x47 0xC0" reads the address 0xC0476018 into %eax.
263 *
264 * In this example can guess that the kernel was compiled with
265 * CONFIG_PAGE_OFFSET set to 0xC0000000 (it's always a round number). If the
266 * kernel were larger than 16MB, we might see 0xC1 addresses show up, but our
267 * kernel isn't that bloated yet.
268 *
269 * Unfortunately, x86 has variable-length instructions, so finding this
270 * particular instruction properly involves writing a disassembler. Instead,
271 * we rely on statistics. We look for "0xA1" and tally the different bytes
272 * which occur 4 bytes later (the "0xC0" in our example above). When one of
273 * those bytes appears three times, we can be reasonably confident that it
274 * forms the start of CONFIG_PAGE_OFFSET.
275 *
276 * This is amazingly reliable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700277static unsigned long intuit_page_offset(unsigned char *img, unsigned long len)
278{
279 unsigned int i, possibilities[256] = { 0 };
280
281 for (i = 0; i + 4 < len; i++) {
282 /* mov 0xXXXXXXXX,%eax */
283 if (img[i] == 0xA1 && ++possibilities[img[i+4]] > 3)
284 return (unsigned long)img[i+4] << 24;
285 }
286 errx(1, "could not determine page offset");
287}
288
Rusty Russelldde79782007-07-26 10:41:03 -0700289/*L:160 Unfortunately the entire ELF image isn't compressed: the segments
290 * which need loading are extracted and compressed raw. This denies us the
291 * information we need to make a fully-general loader. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700292static unsigned long unpack_bzimage(int fd, unsigned long *page_offset)
293{
294 gzFile f;
295 int ret, len = 0;
Rusty Russelldde79782007-07-26 10:41:03 -0700296 /* A bzImage always gets loaded at physical address 1M. This is
297 * actually configurable as CONFIG_PHYSICAL_START, but as the comment
298 * there says, "Don't change this unless you know what you are doing".
299 * Indeed. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700300 void *img = (void *)0x100000;
301
Rusty Russelldde79782007-07-26 10:41:03 -0700302 /* gzdopen takes our file descriptor (carefully placed at the start of
303 * the GZIP header we found) and returns a gzFile. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700304 f = gzdopen(fd, "rb");
Rusty Russelldde79782007-07-26 10:41:03 -0700305 /* We read it into memory in 64k chunks until we hit the end. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700306 while ((ret = gzread(f, img + len, 65536)) > 0)
307 len += ret;
308 if (ret < 0)
309 err(1, "reading image from bzImage");
310
311 verbose("Unpacked size %i addr %p\n", len, img);
Rusty Russelldde79782007-07-26 10:41:03 -0700312
313 /* Without the ELF header, we can't tell virtual-physical gap. This is
314 * CONFIG_PAGE_OFFSET, and people do actually change it. Fortunately,
315 * I have a clever way of figuring it out from the code itself. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700316 *page_offset = intuit_page_offset(img, len);
317
318 return entry_point(img, img + len, *page_offset);
319}
320
Rusty Russelldde79782007-07-26 10:41:03 -0700321/*L:150 A bzImage, unlike an ELF file, is not meant to be loaded. You're
322 * supposed to jump into it and it will unpack itself. We can't do that
323 * because the Guest can't run the unpacking code, and adding features to
324 * lguest kills puppies, so we don't want to.
325 *
326 * The bzImage is formed by putting the decompressing code in front of the
327 * compressed kernel code. So we can simple scan through it looking for the
328 * first "gzip" header, and start decompressing from there. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700329static unsigned long load_bzimage(int fd, unsigned long *page_offset)
330{
331 unsigned char c;
332 int state = 0;
333
Rusty Russelldde79782007-07-26 10:41:03 -0700334 /* GZIP header is 0x1F 0x8B <method> <flags>... <compressed-by>. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700335 while (read(fd, &c, 1) == 1) {
336 switch (state) {
337 case 0:
338 if (c == 0x1F)
339 state++;
340 break;
341 case 1:
342 if (c == 0x8B)
343 state++;
344 else
345 state = 0;
346 break;
347 case 2 ... 8:
348 state++;
349 break;
350 case 9:
Rusty Russelldde79782007-07-26 10:41:03 -0700351 /* Seek back to the start of the gzip header. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700352 lseek(fd, -10, SEEK_CUR);
Rusty Russelldde79782007-07-26 10:41:03 -0700353 /* One final check: "compressed under UNIX". */
354 if (c != 0x03)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700355 state = -1;
356 else
357 return unpack_bzimage(fd, page_offset);
358 }
359 }
360 errx(1, "Could not find kernel in bzImage");
361}
362
Rusty Russelldde79782007-07-26 10:41:03 -0700363/*L:140 Loading the kernel is easy when it's a "vmlinux", but most kernels
364 * come wrapped up in the self-decompressing "bzImage" format. With some funky
365 * coding, we can load those, too. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700366static unsigned long load_kernel(int fd, unsigned long *page_offset)
367{
368 Elf32_Ehdr hdr;
369
Rusty Russelldde79782007-07-26 10:41:03 -0700370 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700371 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
372 err(1, "Reading kernel");
373
Rusty Russelldde79782007-07-26 10:41:03 -0700374 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700375 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
376 return map_elf(fd, &hdr, page_offset);
377
Rusty Russelldde79782007-07-26 10:41:03 -0700378 /* Otherwise we assume it's a bzImage, and try to unpack it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700379 return load_bzimage(fd, page_offset);
380}
381
Rusty Russelldde79782007-07-26 10:41:03 -0700382/* This is a trivial little helper to align pages. Andi Kleen hated it because
383 * it calls getpagesize() twice: "it's dumb code."
384 *
385 * Kernel guys get really het up about optimization, even when it's not
386 * necessary. I leave this code as a reaction against that. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700387static inline unsigned long page_align(unsigned long addr)
388{
Rusty Russelldde79782007-07-26 10:41:03 -0700389 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700390 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
391}
392
Rusty Russelldde79782007-07-26 10:41:03 -0700393/*L:180 An "initial ram disk" is a disk image loaded into memory along with
394 * the kernel which the kernel can use to boot from without needing any
395 * drivers. Most distributions now use this as standard: the initrd contains
396 * the code to load the appropriate driver modules for the current machine.
397 *
398 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
399 * kernels. He sent me this (and tells me when I break it). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700400static unsigned long load_initrd(const char *name, unsigned long mem)
401{
402 int ifd;
403 struct stat st;
404 unsigned long len;
405 void *iaddr;
406
407 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700408 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700409 if (fstat(ifd, &st) < 0)
410 err(1, "fstat() on initrd '%s'", name);
411
Rusty Russelldde79782007-07-26 10:41:03 -0700412 /* The length needs to be rounded up to a page size: mmap needs the
413 * address to be page aligned. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700414 len = page_align(st.st_size);
Rusty Russelldde79782007-07-26 10:41:03 -0700415 /* We map the initrd at the top of memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700416 iaddr = mmap((void *)mem - len, st.st_size,
417 PROT_READ|PROT_EXEC|PROT_WRITE,
418 MAP_FIXED|MAP_PRIVATE, ifd, 0);
419 if (iaddr != (void *)mem - len)
420 err(1, "Mmaping initrd '%s' returned %p not %p",
421 name, iaddr, (void *)mem - len);
Rusty Russelldde79782007-07-26 10:41:03 -0700422 /* Once a file is mapped, you can close the file descriptor. It's a
423 * little odd, but quite useful. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700424 close(ifd);
425 verbose("mapped initrd %s size=%lu @ %p\n", name, st.st_size, iaddr);
Rusty Russelldde79782007-07-26 10:41:03 -0700426
427 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700428 return len;
429}
430
Rusty Russelldde79782007-07-26 10:41:03 -0700431/* Once we know how much memory we have, and the address the Guest kernel
432 * expects, we can construct simple linear page tables which will get the Guest
433 * far enough into the boot to create its own.
434 *
435 * We lay them out of the way, just below the initrd (which is why we need to
436 * know its size). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700437static unsigned long setup_pagetables(unsigned long mem,
438 unsigned long initrd_size,
439 unsigned long page_offset)
440{
441 u32 *pgdir, *linear;
442 unsigned int mapped_pages, i, linear_pages;
443 unsigned int ptes_per_page = getpagesize()/sizeof(u32);
444
Rusty Russelldde79782007-07-26 10:41:03 -0700445 /* Ideally we map all physical memory starting at page_offset.
446 * However, if page_offset is 0xC0000000 we can only map 1G of physical
447 * (0xC0000000 + 1G overflows). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700448 if (mem <= -page_offset)
449 mapped_pages = mem/getpagesize();
450 else
451 mapped_pages = -page_offset/getpagesize();
452
Rusty Russelldde79782007-07-26 10:41:03 -0700453 /* Each PTE page can map ptes_per_page pages: how many do we need? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700454 linear_pages = (mapped_pages + ptes_per_page-1)/ptes_per_page;
455
Rusty Russelldde79782007-07-26 10:41:03 -0700456 /* We put the toplevel page directory page at the top of memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700457 pgdir = (void *)mem - initrd_size - getpagesize();
Rusty Russelldde79782007-07-26 10:41:03 -0700458
459 /* Now we use the next linear_pages pages as pte pages */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700460 linear = (void *)pgdir - linear_pages*getpagesize();
461
Rusty Russelldde79782007-07-26 10:41:03 -0700462 /* Linear mapping is easy: put every page's address into the mapping in
463 * order. PAGE_PRESENT contains the flags Present, Writable and
464 * Executable. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700465 for (i = 0; i < mapped_pages; i++)
466 linear[i] = ((i * getpagesize()) | PAGE_PRESENT);
467
Rusty Russelldde79782007-07-26 10:41:03 -0700468 /* The top level points to the linear page table pages above. The
469 * entry representing page_offset points to the first one, and they
470 * continue from there. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700471 for (i = 0; i < mapped_pages; i += ptes_per_page) {
472 pgdir[(i + page_offset/getpagesize())/ptes_per_page]
473 = (((u32)linear + i*sizeof(u32)) | PAGE_PRESENT);
474 }
475
476 verbose("Linear mapping of %u pages in %u pte pages at %p\n",
477 mapped_pages, linear_pages, linear);
478
Rusty Russelldde79782007-07-26 10:41:03 -0700479 /* We return the top level (guest-physical) address: the kernel needs
480 * to know where it is. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700481 return (unsigned long)pgdir;
482}
483
Rusty Russelldde79782007-07-26 10:41:03 -0700484/* Simple routine to roll all the commandline arguments together with spaces
485 * between them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700486static void concat(char *dst, char *args[])
487{
488 unsigned int i, len = 0;
489
490 for (i = 0; args[i]; i++) {
491 strcpy(dst+len, args[i]);
492 strcat(dst+len, " ");
493 len += strlen(args[i]) + 1;
494 }
495 /* In case it's empty. */
496 dst[len] = '\0';
497}
498
Rusty Russelldde79782007-07-26 10:41:03 -0700499/* This is where we actually tell the kernel to initialize the Guest. We saw
500 * the arguments it expects when we looked at initialize() in lguest_user.c:
501 * the top physical page to allow, the top level pagetable, the entry point and
502 * the page_offset constant for the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700503static int tell_kernel(u32 pgdir, u32 start, u32 page_offset)
504{
505 u32 args[] = { LHREQ_INITIALIZE,
Rusty Russell6570c45992007-07-23 18:43:56 -0700506 top/getpagesize(), pgdir, start, page_offset };
Rusty Russell8ca47e02007-07-19 01:49:29 -0700507 int fd;
508
509 fd = open_or_die("/dev/lguest", O_RDWR);
510 if (write(fd, args, sizeof(args)) < 0)
511 err(1, "Writing to /dev/lguest");
Rusty Russelldde79782007-07-26 10:41:03 -0700512
513 /* We return the /dev/lguest file descriptor to control this Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700514 return fd;
515}
Rusty Russelldde79782007-07-26 10:41:03 -0700516/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700517
518static void set_fd(int fd, struct device_list *devices)
519{
520 FD_SET(fd, &devices->infds);
521 if (fd > devices->max_infd)
522 devices->max_infd = fd;
523}
524
Rusty Russelldde79782007-07-26 10:41:03 -0700525/*L:200
526 * The Waker.
527 *
528 * With a console and network devices, we can have lots of input which we need
529 * to process. We could try to tell the kernel what file descriptors to watch,
530 * but handing a file descriptor mask through to the kernel is fairly icky.
531 *
532 * Instead, we fork off a process which watches the file descriptors and writes
533 * the LHREQ_BREAK command to the /dev/lguest filedescriptor to tell the Host
534 * loop to stop running the Guest. This causes it to return from the
535 * /dev/lguest read with -EAGAIN, where it will write to /dev/lguest to reset
536 * the LHREQ_BREAK and wake us up again.
537 *
538 * This, of course, is merely a different *kind* of icky.
539 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700540static void wake_parent(int pipefd, int lguest_fd, struct device_list *devices)
541{
Rusty Russelldde79782007-07-26 10:41:03 -0700542 /* Add the pipe from the Launcher to the fdset in the device_list, so
543 * we watch it, too. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700544 set_fd(pipefd, devices);
545
546 for (;;) {
547 fd_set rfds = devices->infds;
548 u32 args[] = { LHREQ_BREAK, 1 };
549
Rusty Russelldde79782007-07-26 10:41:03 -0700550 /* Wait until input is ready from one of the devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700551 select(devices->max_infd+1, &rfds, NULL, NULL, NULL);
Rusty Russelldde79782007-07-26 10:41:03 -0700552 /* Is it a message from the Launcher? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700553 if (FD_ISSET(pipefd, &rfds)) {
554 int ignorefd;
Rusty Russelldde79782007-07-26 10:41:03 -0700555 /* If read() returns 0, it means the Launcher has
556 * exited. We silently follow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700557 if (read(pipefd, &ignorefd, sizeof(ignorefd)) == 0)
558 exit(0);
Rusty Russelldde79782007-07-26 10:41:03 -0700559 /* Otherwise it's telling us there's a problem with one
560 * of the devices, and we should ignore that file
561 * descriptor from now on. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700562 FD_CLR(ignorefd, &devices->infds);
Rusty Russelldde79782007-07-26 10:41:03 -0700563 } else /* Send LHREQ_BREAK command. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700564 write(lguest_fd, args, sizeof(args));
565 }
566}
567
Rusty Russelldde79782007-07-26 10:41:03 -0700568/* This routine just sets up a pipe to the Waker process. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700569static int setup_waker(int lguest_fd, struct device_list *device_list)
570{
571 int pipefd[2], child;
572
Rusty Russelldde79782007-07-26 10:41:03 -0700573 /* We create a pipe to talk to the waker, and also so it knows when the
574 * Launcher dies (and closes pipe). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700575 pipe(pipefd);
576 child = fork();
577 if (child == -1)
578 err(1, "forking");
579
580 if (child == 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700581 /* Close the "writing" end of our copy of the pipe */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700582 close(pipefd[1]);
583 wake_parent(pipefd[0], lguest_fd, device_list);
584 }
Rusty Russelldde79782007-07-26 10:41:03 -0700585 /* Close the reading end of our copy of the pipe. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700586 close(pipefd[0]);
587
Rusty Russelldde79782007-07-26 10:41:03 -0700588 /* Here is the fd used to talk to the waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700589 return pipefd[1];
590}
591
Rusty Russelldde79782007-07-26 10:41:03 -0700592/*L:210
593 * Device Handling.
594 *
595 * When the Guest sends DMA to us, it sends us an array of addresses and sizes.
596 * We need to make sure it's not trying to reach into the Launcher itself, so
597 * we have a convenient routine which check it and exits with an error message
598 * if something funny is going on:
599 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700600static void *_check_pointer(unsigned long addr, unsigned int size,
601 unsigned int line)
602{
Rusty Russelldde79782007-07-26 10:41:03 -0700603 /* We have to separately check addr and addr+size, because size could
604 * be huge and addr + size might wrap around. */
Rusty Russell6570c45992007-07-23 18:43:56 -0700605 if (addr >= top || addr + size >= top)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700606 errx(1, "%s:%i: Invalid address %li", __FILE__, line, addr);
Rusty Russelldde79782007-07-26 10:41:03 -0700607 /* We return a pointer for the caller's convenience, now we know it's
608 * safe to use. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700609 return (void *)addr;
610}
Rusty Russelldde79782007-07-26 10:41:03 -0700611/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700612#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
613
Rusty Russelldde79782007-07-26 10:41:03 -0700614/* The Guest has given us the address of a "struct lguest_dma". We check it's
615 * OK and convert it to an iovec (which is a simple array of ptr/size
616 * pairs). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700617static u32 *dma2iov(unsigned long dma, struct iovec iov[], unsigned *num)
618{
619 unsigned int i;
620 struct lguest_dma *udma;
621
Rusty Russelldde79782007-07-26 10:41:03 -0700622 /* First we make sure that the array memory itself is valid. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700623 udma = check_pointer(dma, sizeof(*udma));
Rusty Russelldde79782007-07-26 10:41:03 -0700624 /* Now we check each element */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700625 for (i = 0; i < LGUEST_MAX_DMA_SECTIONS; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700626 /* A zero length ends the array. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700627 if (!udma->len[i])
628 break;
629
630 iov[i].iov_base = check_pointer(udma->addr[i], udma->len[i]);
631 iov[i].iov_len = udma->len[i];
632 }
633 *num = i;
Rusty Russelldde79782007-07-26 10:41:03 -0700634
635 /* We return the pointer to where the caller should write the amount of
636 * the buffer used. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700637 return &udma->used_len;
638}
639
Rusty Russelldde79782007-07-26 10:41:03 -0700640/* This routine gets a DMA buffer from the Guest for a given key, and converts
641 * it to an iovec array. It returns the interrupt the Guest wants when we're
642 * finished, and a pointer to the "used_len" field to fill in. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700643static u32 *get_dma_buffer(int fd, void *key,
644 struct iovec iov[], unsigned int *num, u32 *irq)
645{
646 u32 buf[] = { LHREQ_GETDMA, (u32)key };
647 unsigned long udma;
648 u32 *res;
649
Rusty Russelldde79782007-07-26 10:41:03 -0700650 /* Ask the kernel for a DMA buffer corresponding to this key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700651 udma = write(fd, buf, sizeof(buf));
Rusty Russelldde79782007-07-26 10:41:03 -0700652 /* They haven't registered any, or they're all used? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700653 if (udma == (unsigned long)-1)
654 return NULL;
655
Rusty Russelldde79782007-07-26 10:41:03 -0700656 /* Convert it into our iovec array */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700657 res = dma2iov(udma, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700658 /* The kernel stashes irq in ->used_len to get it out to us. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700659 *irq = *res;
Rusty Russelldde79782007-07-26 10:41:03 -0700660 /* Return a pointer to ((struct lguest_dma *)udma)->used_len. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700661 return res;
662}
663
Rusty Russelldde79782007-07-26 10:41:03 -0700664/* This is a convenient routine to send the Guest an interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700665static void trigger_irq(int fd, u32 irq)
666{
667 u32 buf[] = { LHREQ_IRQ, irq };
668 if (write(fd, buf, sizeof(buf)) != 0)
669 err(1, "Triggering irq %i", irq);
670}
671
Rusty Russelldde79782007-07-26 10:41:03 -0700672/* This simply sets up an iovec array where we can put data to be discarded.
673 * This happens when the Guest doesn't want or can't handle the input: we have
674 * to get rid of it somewhere, and if we bury it in the ceiling space it will
675 * start to smell after a week. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700676static void discard_iovec(struct iovec *iov, unsigned int *num)
677{
678 static char discard_buf[1024];
679 *num = 1;
680 iov->iov_base = discard_buf;
681 iov->iov_len = sizeof(discard_buf);
682}
683
Rusty Russelldde79782007-07-26 10:41:03 -0700684/* Here is the input terminal setting we save, and the routine to restore them
685 * on exit so the user can see what they type next. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700686static struct termios orig_term;
687static void restore_term(void)
688{
689 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
690}
691
Rusty Russelldde79782007-07-26 10:41:03 -0700692/* We associate some data with the console for our exit hack. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700693struct console_abort
694{
Rusty Russelldde79782007-07-26 10:41:03 -0700695 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700696 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700697 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700698 struct timeval start;
699};
700
Rusty Russelldde79782007-07-26 10:41:03 -0700701/* This is the routine which handles console input (ie. stdin). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700702static bool handle_console_input(int fd, struct device *dev)
703{
704 u32 irq = 0, *lenp;
705 int len;
706 unsigned int num;
707 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
708 struct console_abort *abort = dev->priv;
709
Rusty Russelldde79782007-07-26 10:41:03 -0700710 /* First we get the console buffer from the Guest. The key is dev->mem
711 * which was set to 0 in setup_console(). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700712 lenp = get_dma_buffer(fd, dev->mem, iov, &num, &irq);
713 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700714 /* If it's not ready for input, warn and set up to discard. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700715 warn("console: no dma buffer!");
716 discard_iovec(iov, &num);
717 }
718
Rusty Russelldde79782007-07-26 10:41:03 -0700719 /* This is why we convert to iovecs: the readv() call uses them, and so
720 * it reads straight into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700721 len = readv(dev->fd, iov, num);
722 if (len <= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -0700723 /* This implies that the console is closed, is /dev/null, or
724 * something went terribly wrong. We still go through the rest
725 * of the logic, though, especially the exit handling below. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700726 warnx("Failed to get console input, ignoring console.");
727 len = 0;
728 }
729
Rusty Russelldde79782007-07-26 10:41:03 -0700730 /* If we read the data into the Guest, fill in the length and send the
731 * interrupt. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700732 if (lenp) {
733 *lenp = len;
734 trigger_irq(fd, irq);
735 }
736
Rusty Russelldde79782007-07-26 10:41:03 -0700737 /* Three ^C within one second? Exit.
738 *
739 * This is such a hack, but works surprisingly well. Each ^C has to be
740 * in a buffer by itself, so they can't be too fast. But we check that
741 * we get three within about a second, so they can't be too slow. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700742 if (len == 1 && ((char *)iov[0].iov_base)[0] == 3) {
743 if (!abort->count++)
744 gettimeofday(&abort->start, NULL);
745 else if (abort->count == 3) {
746 struct timeval now;
747 gettimeofday(&now, NULL);
748 if (now.tv_sec <= abort->start.tv_sec+1) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700749 u32 args[] = { LHREQ_BREAK, 0 };
Rusty Russelldde79782007-07-26 10:41:03 -0700750 /* Close the fd so Waker will know it has to
751 * exit. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700752 close(waker_fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700753 /* Just in case waker is blocked in BREAK, send
754 * unbreak now. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700755 write(fd, args, sizeof(args));
756 exit(2);
757 }
758 abort->count = 0;
759 }
760 } else
Rusty Russelldde79782007-07-26 10:41:03 -0700761 /* Any other key resets the abort counter. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700762 abort->count = 0;
763
Rusty Russelldde79782007-07-26 10:41:03 -0700764 /* Now, if we didn't read anything, put the input terminal back and
765 * return failure (meaning, don't call us again). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700766 if (!len) {
767 restore_term();
768 return false;
769 }
Rusty Russelldde79782007-07-26 10:41:03 -0700770 /* Everything went OK! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700771 return true;
772}
773
Rusty Russelldde79782007-07-26 10:41:03 -0700774/* Handling console output is much simpler than input. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700775static u32 handle_console_output(int fd, const struct iovec *iov,
776 unsigned num, struct device*dev)
777{
Rusty Russelldde79782007-07-26 10:41:03 -0700778 /* Whatever the Guest sends, write it to standard output. Return the
779 * number of bytes written. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700780 return writev(STDOUT_FILENO, iov, num);
781}
782
Rusty Russelldde79782007-07-26 10:41:03 -0700783/* Guest->Host network output is also pretty easy. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700784static u32 handle_tun_output(int fd, const struct iovec *iov,
785 unsigned num, struct device *dev)
786{
Rusty Russelldde79782007-07-26 10:41:03 -0700787 /* We put a flag in the "priv" pointer of the network device, and set
788 * it as soon as we see output. We'll see why in handle_tun_input() */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700789 *(bool *)dev->priv = true;
Rusty Russelldde79782007-07-26 10:41:03 -0700790 /* Whatever packet the Guest sent us, write it out to the tun
791 * device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700792 return writev(dev->fd, iov, num);
793}
794
Rusty Russelldde79782007-07-26 10:41:03 -0700795/* This matches the peer_key() in lguest_net.c. The key for any given slot
796 * is the address of the network device's page plus 4 * the slot number. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700797static unsigned long peer_offset(unsigned int peernum)
798{
799 return 4 * peernum;
800}
801
Rusty Russelldde79782007-07-26 10:41:03 -0700802/* This is where we handle a packet coming in from the tun device */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700803static bool handle_tun_input(int fd, struct device *dev)
804{
805 u32 irq = 0, *lenp;
806 int len;
807 unsigned num;
808 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
809
Rusty Russelldde79782007-07-26 10:41:03 -0700810 /* First we get a buffer the Guest has bound to its key. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700811 lenp = get_dma_buffer(fd, dev->mem+peer_offset(NET_PEERNUM), iov, &num,
812 &irq);
813 if (!lenp) {
Rusty Russelldde79782007-07-26 10:41:03 -0700814 /* Now, it's expected that if we try to send a packet too
815 * early, the Guest won't be ready yet. This is why we set a
816 * flag when the Guest sends its first packet. If it's sent a
817 * packet we assume it should be ready to receive them.
818 *
819 * Actually, this is what the status bits in the descriptor are
820 * for: we should *use* them. FIXME! */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700821 if (*(bool *)dev->priv)
822 warn("network: no dma buffer!");
823 discard_iovec(iov, &num);
824 }
825
Rusty Russelldde79782007-07-26 10:41:03 -0700826 /* Read the packet from the device directly into the Guest's buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700827 len = readv(dev->fd, iov, num);
828 if (len <= 0)
829 err(1, "reading network");
Rusty Russelldde79782007-07-26 10:41:03 -0700830
831 /* Write the used_len, and trigger the interrupt for the Guest */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700832 if (lenp) {
833 *lenp = len;
834 trigger_irq(fd, irq);
835 }
836 verbose("tun input packet len %i [%02x %02x] (%s)\n", len,
837 ((u8 *)iov[0].iov_base)[0], ((u8 *)iov[0].iov_base)[1],
838 lenp ? "sent" : "discarded");
Rusty Russelldde79782007-07-26 10:41:03 -0700839 /* All good. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700840 return true;
841}
842
Rusty Russelldde79782007-07-26 10:41:03 -0700843/* The last device handling routine is block output: the Guest has sent a DMA
844 * to the block device. It will have placed the command it wants in the
845 * "struct lguest_block_page". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700846static u32 handle_block_output(int fd, const struct iovec *iov,
847 unsigned num, struct device *dev)
848{
849 struct lguest_block_page *p = dev->mem;
850 u32 irq, *lenp;
851 unsigned int len, reply_num;
852 struct iovec reply[LGUEST_MAX_DMA_SECTIONS];
853 off64_t device_len, off = (off64_t)p->sector * 512;
854
Rusty Russelldde79782007-07-26 10:41:03 -0700855 /* First we extract the device length from the dev->priv pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700856 device_len = *(off64_t *)dev->priv;
857
Rusty Russelldde79782007-07-26 10:41:03 -0700858 /* We first check that the read or write is within the length of the
859 * block file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700860 if (off >= device_len)
861 err(1, "Bad offset %llu vs %llu", off, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700862 /* Move to the right location in the block file. This shouldn't fail,
863 * but best to check. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700864 if (lseek64(dev->fd, off, SEEK_SET) != off)
865 err(1, "Bad seek to sector %i", p->sector);
866
867 verbose("Block: %s at offset %llu\n", p->type ? "WRITE" : "READ", off);
868
Rusty Russelldde79782007-07-26 10:41:03 -0700869 /* They were supposed to bind a reply buffer at key equal to the start
870 * of the block device memory. We need this to tell them when the
871 * request is finished. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700872 lenp = get_dma_buffer(fd, dev->mem, reply, &reply_num, &irq);
873 if (!lenp)
874 err(1, "Block request didn't give us a dma buffer");
875
876 if (p->type) {
Rusty Russelldde79782007-07-26 10:41:03 -0700877 /* A write request. The DMA they sent contained the data, so
878 * write it out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700879 len = writev(dev->fd, iov, num);
Rusty Russelldde79782007-07-26 10:41:03 -0700880 /* Grr... Now we know how long the "struct lguest_dma" they
881 * sent was, we make sure they didn't try to write over the end
882 * of the block file (possibly extending it). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700883 if (off + len > device_len) {
Rusty Russelldde79782007-07-26 10:41:03 -0700884 /* Trim it back to the correct length */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700885 ftruncate(dev->fd, device_len);
Rusty Russelldde79782007-07-26 10:41:03 -0700886 /* Die, bad Guest, die. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700887 errx(1, "Write past end %llu+%u", off, len);
888 }
Rusty Russelldde79782007-07-26 10:41:03 -0700889 /* The reply length is 0: we just send back an empty DMA to
890 * interrupt them and tell them the write is finished. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700891 *lenp = 0;
892 } else {
Rusty Russelldde79782007-07-26 10:41:03 -0700893 /* A read request. They sent an empty DMA to start the
894 * request, and we put the read contents into the reply
895 * buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700896 len = readv(dev->fd, reply, reply_num);
897 *lenp = len;
898 }
899
Rusty Russelldde79782007-07-26 10:41:03 -0700900 /* The result is 1 (done), 2 if there was an error (short read or
901 * write). */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700902 p->result = 1 + (p->bytes != len);
Rusty Russelldde79782007-07-26 10:41:03 -0700903 /* Now tell them we've used their reply buffer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700904 trigger_irq(fd, irq);
Rusty Russelldde79782007-07-26 10:41:03 -0700905
906 /* We're supposed to return the number of bytes of the output buffer we
907 * used. But the block device uses the "result" field instead, so we
908 * don't bother. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700909 return 0;
910}
911
Rusty Russelldde79782007-07-26 10:41:03 -0700912/* This is the generic routine we call when the Guest sends some DMA out. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700913static void handle_output(int fd, unsigned long dma, unsigned long key,
914 struct device_list *devices)
915{
916 struct device *i;
917 u32 *lenp;
918 struct iovec iov[LGUEST_MAX_DMA_SECTIONS];
919 unsigned num = 0;
920
Rusty Russelldde79782007-07-26 10:41:03 -0700921 /* Convert the "struct lguest_dma" they're sending to a "struct
922 * iovec". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700923 lenp = dma2iov(dma, iov, &num);
Rusty Russelldde79782007-07-26 10:41:03 -0700924
925 /* Check each device: if they expect output to this key, tell them to
926 * handle it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700927 for (i = devices->dev; i; i = i->next) {
928 if (i->handle_output && key == i->watch_key) {
Rusty Russelldde79782007-07-26 10:41:03 -0700929 /* We write the result straight into the used_len field
930 * for them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700931 *lenp = i->handle_output(fd, iov, num, i);
932 return;
933 }
934 }
Rusty Russelldde79782007-07-26 10:41:03 -0700935
936 /* This can happen: the kernel sends any SEND_DMA which doesn't match
937 * another Guest to us. It could be that another Guest just left a
938 * network, for example. But it's unusual. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700939 warnx("Pending dma %p, key %p", (void *)dma, (void *)key);
940}
941
Rusty Russelldde79782007-07-26 10:41:03 -0700942/* This is called when the waker wakes us up: check for incoming file
943 * descriptors. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700944static void handle_input(int fd, struct device_list *devices)
945{
Rusty Russelldde79782007-07-26 10:41:03 -0700946 /* select() wants a zeroed timeval to mean "don't wait". */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700947 struct timeval poll = { .tv_sec = 0, .tv_usec = 0 };
948
949 for (;;) {
950 struct device *i;
951 fd_set fds = devices->infds;
952
Rusty Russelldde79782007-07-26 10:41:03 -0700953 /* If nothing is ready, we're done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700954 if (select(devices->max_infd+1, &fds, NULL, NULL, &poll) == 0)
955 break;
956
Rusty Russelldde79782007-07-26 10:41:03 -0700957 /* Otherwise, call the device(s) which have readable
958 * file descriptors and a method of handling them. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700959 for (i = devices->dev; i; i = i->next) {
960 if (i->handle_input && FD_ISSET(i->fd, &fds)) {
Rusty Russelldde79782007-07-26 10:41:03 -0700961 /* If handle_input() returns false, it means we
962 * should no longer service it.
963 * handle_console_input() does this. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700964 if (!i->handle_input(fd, i)) {
Rusty Russelldde79782007-07-26 10:41:03 -0700965 /* Clear it from the set of input file
966 * descriptors kept at the head of the
967 * device list. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700968 FD_CLR(i->fd, &devices->infds);
969 /* Tell waker to ignore it too... */
970 write(waker_fd, &i->fd, sizeof(i->fd));
971 }
972 }
973 }
974 }
975}
976
Rusty Russelldde79782007-07-26 10:41:03 -0700977/*L:190
978 * Device Setup
979 *
980 * All devices need a descriptor so the Guest knows it exists, and a "struct
981 * device" so the Launcher can keep track of it. We have common helper
982 * routines to allocate them.
983 *
984 * This routine allocates a new "struct lguest_device_desc" from descriptor
985 * table in the devices array just above the Guest's normal memory. */
Rusty Russell6570c45992007-07-23 18:43:56 -0700986static struct lguest_device_desc *
987new_dev_desc(struct lguest_device_desc *descs,
988 u16 type, u16 features, u16 num_pages)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700989{
Rusty Russell6570c45992007-07-23 18:43:56 -0700990 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700991
Rusty Russell6570c45992007-07-23 18:43:56 -0700992 for (i = 0; i < LGUEST_MAX_DEVICES; i++) {
993 if (!descs[i].type) {
994 descs[i].type = type;
995 descs[i].features = features;
996 descs[i].num_pages = num_pages;
Rusty Russelldde79782007-07-26 10:41:03 -0700997 /* If they said the device needs memory, we allocate
998 * that now, bumping up the top of Guest memory. */
Rusty Russell6570c45992007-07-23 18:43:56 -0700999 if (num_pages) {
1000 map_zeroed_pages(top, num_pages);
1001 descs[i].pfn = top/getpagesize();
1002 top += num_pages*getpagesize();
1003 }
1004 return &descs[i];
1005 }
1006 }
1007 errx(1, "too many devices");
Rusty Russell8ca47e02007-07-19 01:49:29 -07001008}
1009
Rusty Russelldde79782007-07-26 10:41:03 -07001010/* This monster routine does all the creation and setup of a new device,
1011 * including caling new_dev_desc() to allocate the descriptor and device
1012 * memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001013static struct device *new_device(struct device_list *devices,
1014 u16 type, u16 num_pages, u16 features,
1015 int fd,
1016 bool (*handle_input)(int, struct device *),
1017 unsigned long watch_off,
1018 u32 (*handle_output)(int,
1019 const struct iovec *,
1020 unsigned,
1021 struct device *))
1022{
1023 struct device *dev = malloc(sizeof(*dev));
1024
Rusty Russelldde79782007-07-26 10:41:03 -07001025 /* Append to device list. Prepending to a single-linked list is
1026 * easier, but the user expects the devices to be arranged on the bus
1027 * in command-line order. The first network device on the command line
1028 * is eth0, the first block device /dev/lgba, etc. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001029 *devices->lastdev = dev;
1030 dev->next = NULL;
1031 devices->lastdev = &dev->next;
1032
Rusty Russelldde79782007-07-26 10:41:03 -07001033 /* Now we populate the fields one at a time. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001034 dev->fd = fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001035 /* If we have an input handler for this file descriptor, then we add it
1036 * to the device_list's fdset and maxfd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001037 if (handle_input)
1038 set_fd(dev->fd, devices);
Rusty Russell6570c45992007-07-23 18:43:56 -07001039 dev->desc = new_dev_desc(devices->descs, type, features, num_pages);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001040 dev->mem = (void *)(dev->desc->pfn * getpagesize());
1041 dev->handle_input = handle_input;
1042 dev->watch_key = (unsigned long)dev->mem + watch_off;
1043 dev->handle_output = handle_output;
1044 return dev;
1045}
1046
Rusty Russelldde79782007-07-26 10:41:03 -07001047/* Our first setup routine is the console. It's a fairly simple device, but
1048 * UNIX tty handling makes it uglier than it could be. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001049static void setup_console(struct device_list *devices)
1050{
1051 struct device *dev;
1052
Rusty Russelldde79782007-07-26 10:41:03 -07001053 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001054 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1055 struct termios term = orig_term;
Rusty Russelldde79782007-07-26 10:41:03 -07001056 /* Then we turn off echo, line buffering and ^C etc. We want a
1057 * raw input stream to the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001058 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1059 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russelldde79782007-07-26 10:41:03 -07001060 /* If we exit gracefully, the original settings will be
1061 * restored so the user can see what they're typing. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001062 atexit(restore_term);
1063 }
1064
Rusty Russelldde79782007-07-26 10:41:03 -07001065 /* We don't currently require any memory for the console, so we ask for
1066 * 0 pages. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001067 dev = new_device(devices, LGUEST_DEVICE_T_CONSOLE, 0, 0,
1068 STDIN_FILENO, handle_console_input,
1069 LGUEST_CONSOLE_DMA_KEY, handle_console_output);
Rusty Russelldde79782007-07-26 10:41:03 -07001070 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001071 dev->priv = malloc(sizeof(struct console_abort));
1072 ((struct console_abort *)dev->priv)->count = 0;
1073 verbose("device %p: console\n",
1074 (void *)(dev->desc->pfn * getpagesize()));
1075}
1076
Rusty Russelldde79782007-07-26 10:41:03 -07001077/* Setting up a block file is also fairly straightforward. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001078static void setup_block_file(const char *filename, struct device_list *devices)
1079{
1080 int fd;
1081 struct device *dev;
1082 off64_t *device_len;
1083 struct lguest_block_page *p;
1084
Rusty Russelldde79782007-07-26 10:41:03 -07001085 /* We open with O_LARGEFILE because otherwise we get stuck at 2G. We
1086 * open with O_DIRECT because otherwise our benchmarks go much too
1087 * fast. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001088 fd = open_or_die(filename, O_RDWR|O_LARGEFILE|O_DIRECT);
Rusty Russelldde79782007-07-26 10:41:03 -07001089
1090 /* We want one page, and have no input handler (the block file never
1091 * has anything interesting to say to us). Our timing will be quite
1092 * random, so it should be a reasonable randomness source. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001093 dev = new_device(devices, LGUEST_DEVICE_T_BLOCK, 1,
1094 LGUEST_DEVICE_F_RANDOMNESS,
1095 fd, NULL, 0, handle_block_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001096
Rusty Russelldde79782007-07-26 10:41:03 -07001097 /* We store the device size in the private area */
1098 device_len = dev->priv = malloc(sizeof(*device_len));
1099 /* This is the safe way of establishing the size of our device: it
1100 * might be a normal file or an actual block device like /dev/hdb. */
1101 *device_len = lseek64(fd, 0, SEEK_END);
1102
1103 /* The device memory is a "struct lguest_block_page". It's zeroed
1104 * already, we just need to put in the device size. Block devices
1105 * think in sectors (ie. 512 byte chunks), so we translate here. */
1106 p = dev->mem;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001107 p->num_sectors = *device_len/512;
1108 verbose("device %p: block %i sectors\n",
1109 (void *)(dev->desc->pfn * getpagesize()), p->num_sectors);
1110}
1111
Rusty Russelldde79782007-07-26 10:41:03 -07001112/*
1113 * Network Devices.
1114 *
1115 * Setting up network devices is quite a pain, because we have three types.
1116 * First, we have the inter-Guest network. This is a file which is mapped into
1117 * the address space of the Guests who are on the network. Because it is a
1118 * shared mapping, the same page underlies all the devices, and they can send
1119 * DMA to each other.
1120 *
1121 * Remember from our network driver, the Guest is told what slot in the page it
1122 * is to use. We use exclusive fnctl locks to reserve a slot. If another
1123 * Guest is using a slot, the lock will fail and we try another. Because fnctl
1124 * locks are cleaned up automatically when we die, this cleverly means that our
1125 * reservation on the slot will vanish if we crash. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001126static unsigned int find_slot(int netfd, const char *filename)
1127{
1128 struct flock fl;
1129
1130 fl.l_type = F_WRLCK;
1131 fl.l_whence = SEEK_SET;
1132 fl.l_len = 1;
Rusty Russelldde79782007-07-26 10:41:03 -07001133 /* Try a 1 byte lock in each possible position number */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001134 for (fl.l_start = 0;
1135 fl.l_start < getpagesize()/sizeof(struct lguest_net);
1136 fl.l_start++) {
Rusty Russelldde79782007-07-26 10:41:03 -07001137 /* If we succeed, return the slot number. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001138 if (fcntl(netfd, F_SETLK, &fl) == 0)
1139 return fl.l_start;
1140 }
1141 errx(1, "No free slots in network file %s", filename);
1142}
1143
Rusty Russelldde79782007-07-26 10:41:03 -07001144/* This function sets up the network file */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001145static void setup_net_file(const char *filename,
1146 struct device_list *devices)
1147{
1148 int netfd;
1149 struct device *dev;
1150
Rusty Russelldde79782007-07-26 10:41:03 -07001151 /* We don't use open_or_die() here: for friendliness we create the file
1152 * if it doesn't already exist. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001153 netfd = open(filename, O_RDWR, 0);
1154 if (netfd < 0) {
1155 if (errno == ENOENT) {
1156 netfd = open(filename, O_RDWR|O_CREAT, 0600);
1157 if (netfd >= 0) {
Rusty Russelldde79782007-07-26 10:41:03 -07001158 /* If we succeeded, initialize the file with a
1159 * blank page. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001160 char page[getpagesize()];
1161 memset(page, 0, sizeof(page));
1162 write(netfd, page, sizeof(page));
1163 }
1164 }
1165 if (netfd < 0)
1166 err(1, "cannot open net file '%s'", filename);
1167 }
1168
Rusty Russelldde79782007-07-26 10:41:03 -07001169 /* We need 1 page, and the features indicate the slot to use and that
1170 * no checksum is needed. We never touch this device again; it's
1171 * between the Guests on the network, so we don't register input or
1172 * output handlers. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001173 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1174 find_slot(netfd, filename)|LGUEST_NET_F_NOCSUM,
1175 -1, NULL, 0, NULL);
1176
Rusty Russelldde79782007-07-26 10:41:03 -07001177 /* Map the shared file. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001178 if (mmap(dev->mem, getpagesize(), PROT_READ|PROT_WRITE,
1179 MAP_FIXED|MAP_SHARED, netfd, 0) != dev->mem)
1180 err(1, "could not mmap '%s'", filename);
1181 verbose("device %p: shared net %s, peer %i\n",
1182 (void *)(dev->desc->pfn * getpagesize()), filename,
1183 dev->desc->features & ~LGUEST_NET_F_NOCSUM);
1184}
Rusty Russelldde79782007-07-26 10:41:03 -07001185/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001186
1187static u32 str2ip(const char *ipaddr)
1188{
1189 unsigned int byte[4];
1190
1191 sscanf(ipaddr, "%u.%u.%u.%u", &byte[0], &byte[1], &byte[2], &byte[3]);
1192 return (byte[0] << 24) | (byte[1] << 16) | (byte[2] << 8) | byte[3];
1193}
1194
Rusty Russelldde79782007-07-26 10:41:03 -07001195/* This code is "adapted" from libbridge: it attaches the Host end of the
1196 * network device to the bridge device specified by the command line.
1197 *
1198 * This is yet another James Morris contribution (I'm an IP-level guy, so I
1199 * dislike bridging), and I just try not to break it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001200static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1201{
1202 int ifidx;
1203 struct ifreq ifr;
1204
1205 if (!*br_name)
1206 errx(1, "must specify bridge name");
1207
1208 ifidx = if_nametoindex(if_name);
1209 if (!ifidx)
1210 errx(1, "interface %s does not exist!", if_name);
1211
1212 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
1213 ifr.ifr_ifindex = ifidx;
1214 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1215 err(1, "can't add %s to bridge %s", if_name, br_name);
1216}
1217
Rusty Russelldde79782007-07-26 10:41:03 -07001218/* This sets up the Host end of the network device with an IP address, brings
1219 * it up so packets will flow, the copies the MAC address into the hwaddr
1220 * pointer (in practice, the Host's slot in the network device's memory). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001221static void configure_device(int fd, const char *devname, u32 ipaddr,
1222 unsigned char hwaddr[6])
1223{
1224 struct ifreq ifr;
1225 struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
1226
Rusty Russelldde79782007-07-26 10:41:03 -07001227 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001228 memset(&ifr, 0, sizeof(ifr));
1229 strcpy(ifr.ifr_name, devname);
1230 sin->sin_family = AF_INET;
1231 sin->sin_addr.s_addr = htonl(ipaddr);
1232 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
1233 err(1, "Setting %s interface address", devname);
1234 ifr.ifr_flags = IFF_UP;
1235 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
1236 err(1, "Bringing interface %s up", devname);
1237
Rusty Russelldde79782007-07-26 10:41:03 -07001238 /* SIOC stands for Socket I/O Control. G means Get (vs S for Set
1239 * above). IF means Interface, and HWADDR is hardware address.
1240 * Simple! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001241 if (ioctl(fd, SIOCGIFHWADDR, &ifr) != 0)
1242 err(1, "getting hw address for %s", devname);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001243 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);
1244}
1245
Rusty Russelldde79782007-07-26 10:41:03 -07001246/*L:195 The other kind of network is a Host<->Guest network. This can either
1247 * use briding or routing, but the principle is the same: it uses the "tun"
1248 * device to inject packets into the Host as if they came in from a normal
1249 * network card. We just shunt packets between the Guest and the tun
1250 * device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001251static void setup_tun_net(const char *arg, struct device_list *devices)
1252{
1253 struct device *dev;
1254 struct ifreq ifr;
1255 int netfd, ipfd;
1256 u32 ip;
1257 const char *br_name = NULL;
1258
Rusty Russelldde79782007-07-26 10:41:03 -07001259 /* We open the /dev/net/tun device and tell it we want a tap device. A
1260 * tap device is like a tun device, only somehow different. To tell
1261 * the truth, I completely blundered my way through this code, but it
1262 * works now! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001263 netfd = open_or_die("/dev/net/tun", O_RDWR);
1264 memset(&ifr, 0, sizeof(ifr));
1265 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1266 strcpy(ifr.ifr_name, "tap%d");
1267 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1268 err(1, "configuring /dev/net/tun");
Rusty Russelldde79782007-07-26 10:41:03 -07001269 /* We don't need checksums calculated for packets coming in this
1270 * device: trust us! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001271 ioctl(netfd, TUNSETNOCSUM, 1);
1272
Rusty Russelldde79782007-07-26 10:41:03 -07001273 /* We create the net device with 1 page, using the features field of
1274 * the descriptor to tell the Guest it is in slot 1 (NET_PEERNUM), and
1275 * that the device has fairly random timing. We do *not* specify
1276 * LGUEST_NET_F_NOCSUM: these packets can reach the real world.
1277 *
1278 * We will put our MAC address is slot 0 for the Guest to see, so
1279 * it will send packets to us using the key "peer_offset(0)": */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001280 dev = new_device(devices, LGUEST_DEVICE_T_NET, 1,
1281 NET_PEERNUM|LGUEST_DEVICE_F_RANDOMNESS, netfd,
1282 handle_tun_input, peer_offset(0), handle_tun_output);
Rusty Russelldde79782007-07-26 10:41:03 -07001283
1284 /* We keep a flag which says whether we've seen packets come out from
1285 * this network device. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001286 dev->priv = malloc(sizeof(bool));
1287 *(bool *)dev->priv = false;
1288
Rusty Russelldde79782007-07-26 10:41:03 -07001289 /* We need a socket to perform the magic network ioctls to bring up the
1290 * tap interface, connect to the bridge etc. Any socket will do! */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001291 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1292 if (ipfd < 0)
1293 err(1, "opening IP socket");
1294
Rusty Russelldde79782007-07-26 10:41:03 -07001295 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001296 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
1297 ip = INADDR_ANY;
1298 br_name = arg + strlen(BRIDGE_PFX);
1299 add_to_bridge(ipfd, ifr.ifr_name, br_name);
Rusty Russelldde79782007-07-26 10:41:03 -07001300 } else /* It is an IP address to set up the device with */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001301 ip = str2ip(arg);
1302
Rusty Russelldde79782007-07-26 10:41:03 -07001303 /* We are peer 0, ie. first slot, so we hand dev->mem to this routine
1304 * to write the MAC address at the start of the device memory. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001305 configure_device(ipfd, ifr.ifr_name, ip, dev->mem);
1306
Rusty Russelldde79782007-07-26 10:41:03 -07001307 /* Set "promisc" bit: we want every single packet if we're going to
1308 * bridge to other machines (and otherwise it doesn't matter). */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001309 *((u8 *)dev->mem) |= 0x1;
1310
1311 close(ipfd);
1312
1313 verbose("device %p: tun net %u.%u.%u.%u\n",
1314 (void *)(dev->desc->pfn * getpagesize()),
1315 (u8)(ip>>24), (u8)(ip>>16), (u8)(ip>>8), (u8)ip);
1316 if (br_name)
1317 verbose("attached to bridge: %s\n", br_name);
1318}
Rusty Russelldde79782007-07-26 10:41:03 -07001319/* That's the end of device setup. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001320
Rusty Russelldde79782007-07-26 10:41:03 -07001321/*L:220 Finally we reach the core of the Launcher, which runs the Guest, serves
1322 * its input and output, and finally, lays it to rest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001323static void __attribute__((noreturn))
1324run_guest(int lguest_fd, struct device_list *device_list)
1325{
1326 for (;;) {
1327 u32 args[] = { LHREQ_BREAK, 0 };
1328 unsigned long arr[2];
1329 int readval;
1330
1331 /* We read from the /dev/lguest device to run the Guest. */
1332 readval = read(lguest_fd, arr, sizeof(arr));
1333
Rusty Russelldde79782007-07-26 10:41:03 -07001334 /* The read can only really return sizeof(arr) (the Guest did a
1335 * SEND_DMA to us), or an error. */
1336
1337 /* For a successful read, arr[0] is the address of the "struct
1338 * lguest_dma", and arr[1] is the key the Guest sent to. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001339 if (readval == sizeof(arr)) {
1340 handle_output(lguest_fd, arr[0], arr[1], device_list);
1341 continue;
Rusty Russelldde79782007-07-26 10:41:03 -07001342 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001343 } else if (errno == ENOENT) {
1344 char reason[1024] = { 0 };
1345 read(lguest_fd, reason, sizeof(reason)-1);
1346 errx(1, "%s", reason);
Rusty Russelldde79782007-07-26 10:41:03 -07001347 /* EAGAIN means the waker wanted us to look at some input.
1348 * Anything else means a bug or incompatible change. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001349 } else if (errno != EAGAIN)
1350 err(1, "Running guest failed");
Rusty Russelldde79782007-07-26 10:41:03 -07001351
1352 /* Service input, then unset the BREAK which releases
1353 * the Waker. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001354 handle_input(lguest_fd, device_list);
1355 if (write(lguest_fd, args, sizeof(args)) < 0)
1356 err(1, "Resetting break");
1357 }
1358}
Rusty Russelldde79782007-07-26 10:41:03 -07001359/*
1360 * This is the end of the Launcher.
1361 *
1362 * But wait! We've seen I/O from the Launcher, and we've seen I/O from the
1363 * Drivers. If we were to see the Host kernel I/O code, our understanding
1364 * would be complete... :*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001365
1366static struct option opts[] = {
1367 { "verbose", 0, NULL, 'v' },
1368 { "sharenet", 1, NULL, 's' },
1369 { "tunnet", 1, NULL, 't' },
1370 { "block", 1, NULL, 'b' },
1371 { "initrd", 1, NULL, 'i' },
1372 { NULL },
1373};
1374static void usage(void)
1375{
1376 errx(1, "Usage: lguest [--verbose] "
1377 "[--sharenet=<filename>|--tunnet=(<ipaddr>|bridge:<bridgename>)\n"
1378 "|--block=<filename>|--initrd=<filename>]...\n"
1379 "<mem-in-mb> vmlinux [args...]");
1380}
1381
Rusty Russelldde79782007-07-26 10:41:03 -07001382/*L:100 The Launcher code itself takes us out into userspace, that scary place
1383 * where pointers run wild and free! Unfortunately, like most userspace
1384 * programs, it's quite boring (which is why everyone like to hack on the
1385 * kernel!). Perhaps if you make up an Lguest Drinking Game at this point, it
1386 * will get you through this section. Or, maybe not.
1387 *
1388 * The Launcher binary sits up high, usually starting at address 0xB8000000.
1389 * Everything below this is the "physical" memory for the Guest. For example,
1390 * if the Guest were to write a "1" at physical address 0, we would see a "1"
1391 * in the Launcher at "(int *)0". Guest physical == Launcher virtual.
1392 *
1393 * This can be tough to get your head around, but usually it just means that we
1394 * don't need to do any conversion when the Guest gives us it's "physical"
1395 * addresses.
1396 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001397int main(int argc, char *argv[])
1398{
Rusty Russelldde79782007-07-26 10:41:03 -07001399 /* Memory, top-level pagetable, code startpoint, PAGE_OFFSET and size
1400 * of the (optional) initrd. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001401 unsigned long mem = 0, pgdir, start, page_offset, initrd_size = 0;
Rusty Russelldde79782007-07-26 10:41:03 -07001402 /* A temporary and the /dev/lguest file descriptor. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001403 int i, c, lguest_fd;
Rusty Russelldde79782007-07-26 10:41:03 -07001404 /* The list of Guest devices, based on command line arguments. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001405 struct device_list device_list;
Rusty Russelldde79782007-07-26 10:41:03 -07001406 /* The boot information for the Guest: at guest-physical address 0. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001407 void *boot = (void *)0;
Rusty Russelldde79782007-07-26 10:41:03 -07001408 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001409 const char *initrd_name = NULL;
1410
Rusty Russelldde79782007-07-26 10:41:03 -07001411 /* First we initialize the device list. Since console and network
1412 * device receive input from a file descriptor, we keep an fdset
1413 * (infds) and the maximum fd number (max_infd) with the head of the
1414 * list. We also keep a pointer to the last device, for easy appending
1415 * to the list. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001416 device_list.max_infd = -1;
1417 device_list.dev = NULL;
1418 device_list.lastdev = &device_list.dev;
1419 FD_ZERO(&device_list.infds);
1420
Rusty Russelldde79782007-07-26 10:41:03 -07001421 /* We need to know how much memory so we can set up the device
1422 * descriptor and memory pages for the devices as we parse the command
1423 * line. So we quickly look through the arguments to find the amount
1424 * of memory now. */
Rusty Russell6570c45992007-07-23 18:43:56 -07001425 for (i = 1; i < argc; i++) {
1426 if (argv[i][0] != '-') {
1427 mem = top = atoi(argv[i]) * 1024 * 1024;
1428 device_list.descs = map_zeroed_pages(top, 1);
1429 top += getpagesize();
1430 break;
1431 }
1432 }
Rusty Russelldde79782007-07-26 10:41:03 -07001433
1434 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001435 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
1436 switch (c) {
1437 case 'v':
1438 verbose = true;
1439 break;
1440 case 's':
1441 setup_net_file(optarg, &device_list);
1442 break;
1443 case 't':
1444 setup_tun_net(optarg, &device_list);
1445 break;
1446 case 'b':
1447 setup_block_file(optarg, &device_list);
1448 break;
1449 case 'i':
1450 initrd_name = optarg;
1451 break;
1452 default:
1453 warnx("Unknown argument %s", argv[optind]);
1454 usage();
1455 }
1456 }
Rusty Russelldde79782007-07-26 10:41:03 -07001457 /* After the other arguments we expect memory and kernel image name,
1458 * followed by command line arguments for the kernel. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001459 if (optind + 2 > argc)
1460 usage();
1461
Rusty Russelldde79782007-07-26 10:41:03 -07001462 /* We always have a console device */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001463 setup_console(&device_list);
1464
Rusty Russelldde79782007-07-26 10:41:03 -07001465 /* We start by mapping anonymous pages over all of guest-physical
1466 * memory range. This fills it with 0, and ensures that the Guest
1467 * won't be killed when it tries to access it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001468 map_zeroed_pages(0, mem / getpagesize());
1469
1470 /* Now we load the kernel */
1471 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY),
1472 &page_offset);
1473
Rusty Russelldde79782007-07-26 10:41:03 -07001474 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001475 if (initrd_name) {
1476 initrd_size = load_initrd(initrd_name, mem);
Rusty Russelldde79782007-07-26 10:41:03 -07001477 /* These are the location in the Linux boot header where the
1478 * start and size of the initrd are expected to be found. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001479 *(unsigned long *)(boot+0x218) = mem - initrd_size;
1480 *(unsigned long *)(boot+0x21c) = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07001481 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001482 *(unsigned char *)(boot+0x210) = 0xFF;
1483 }
1484
Rusty Russelldde79782007-07-26 10:41:03 -07001485 /* Set up the initial linear pagetables, starting below the initrd. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001486 pgdir = setup_pagetables(mem, initrd_size, page_offset);
1487
Rusty Russelldde79782007-07-26 10:41:03 -07001488 /* The Linux boot header contains an "E820" memory map: ours is a
1489 * simple, single region. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001490 *(char*)(boot+E820NR) = 1;
1491 *((struct e820entry *)(boot+E820MAP))
1492 = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russelldde79782007-07-26 10:41:03 -07001493 /* The boot header contains a command line pointer: we put the command
1494 * line after the boot header (at address 4096) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001495 *(void **)(boot + 0x228) = boot + 4096;
1496 concat(boot + 4096, argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07001497
1498 /* The guest type value of "1" tells the Guest it's under lguest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001499 *(int *)(boot + 0x23c) = 1;
1500
Rusty Russelldde79782007-07-26 10:41:03 -07001501 /* We tell the kernel to initialize the Guest: this returns the open
1502 * /dev/lguest file descriptor. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001503 lguest_fd = tell_kernel(pgdir, start, page_offset);
Rusty Russelldde79782007-07-26 10:41:03 -07001504
1505 /* We fork off a child process, which wakes the Launcher whenever one
1506 * of the input file descriptors needs attention. Otherwise we would
1507 * run the Guest until it tries to output something. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001508 waker_fd = setup_waker(lguest_fd, &device_list);
1509
Rusty Russelldde79782007-07-26 10:41:03 -07001510 /* Finally, run the Guest. This doesn't return. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001511 run_guest(lguest_fd, &device_list);
1512}