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