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