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