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