blob: 70ee62a0eb9aea8103d7b8d345fae4b826de523b [file] [log] [blame]
Rusty Russell2e04ef72009-07-30 16:03:45 -06001/*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:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07007#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>
Ronald G. Minnich6649bb72007-08-28 14:35:59 -070017#include <sys/param.h>
Rusty Russell8ca47e02007-07-19 01:49:29 -070018#include <sys/types.h>
19#include <sys/stat.h>
20#include <sys/wait.h>
Rusty Russell659a0e62009-06-12 22:27:10 -060021#include <sys/eventfd.h>
Rusty Russell8ca47e02007-07-19 01:49:29 -070022#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>
Rusty Russell17cbca22007-10-22 11:24:22 +100037#include <assert.h>
38#include <sched.h>
Rusty Russella586d4f2008-02-04 23:49:56 -050039#include <limits.h>
40#include <stddef.h>
Rusty Russella1618832008-07-29 09:58:35 -050041#include <signal.h>
Philip Sanderson8aeb36e2011-01-20 21:37:28 -060042#include <pwd.h>
43#include <grp.h>
Rusty Russellc565650b2015-02-11 15:15:10 +103044#include <sys/user.h>
Rusty Russelld7fbf6e2015-02-11 15:15:11 +103045#include <linux/pci_regs.h>
Philip Sanderson8aeb36e2011-01-20 21:37:28 -060046
Rusty Russell927cfb92013-07-15 10:50:13 +093047#ifndef VIRTIO_F_ANY_LAYOUT
48#define VIRTIO_F_ANY_LAYOUT 27
49#endif
50
Rusty Russell2e04ef72009-07-30 16:03:45 -060051/*L:110
Rusty Russell9f542882011-07-22 14:39:50 +093052 * We can ignore the 43 include files we need for this program, but I do want
Rusty Russell2e04ef72009-07-30 16:03:45 -060053 * to draw attention to the use of kernel-style types.
Rusty Russelldb24e8c2007-10-25 14:09:25 +100054 *
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
Rusty Russell2e04ef72009-07-30 16:03:45 -060058 * use %llu in printf for any u64.
59 */
Rusty Russelldb24e8c2007-10-25 14:09:25 +100060typedef unsigned long long u64;
61typedef uint32_t u32;
62typedef uint16_t u16;
63typedef uint8_t u8;
Rusty Russelldde79782007-07-26 10:41:03 -070064/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070065
Rusty Russelleb39f832015-02-11 15:19:01 +103066#define VIRTIO_CONFIG_NO_LEGACY
Rusty Russell93153072015-02-11 15:15:11 +103067#define VIRTIO_PCI_NO_LEGACY
Rusty Russell50516542015-02-11 15:15:12 +103068#define VIRTIO_BLK_NO_LEGACY
Rusty Russell93153072015-02-11 15:15:11 +103069
70/* Use in-kernel ones, which defines VIRTIO_F_VERSION_1 */
71#include "../../include/uapi/linux/virtio_config.h"
Rusty Russellbf6d4032015-02-11 15:16:01 +103072#include "../../include/uapi/linux/virtio_net.h"
Rusty Russell50516542015-02-11 15:15:12 +103073#include "../../include/uapi/linux/virtio_blk.h"
Rusty Russelle8330d92015-02-11 15:23:01 +103074#include "../../include/uapi/linux/virtio_console.h"
Rusty Russell0d5b5d32015-02-11 15:17:01 +103075#include "../../include/uapi/linux/virtio_rng.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093076#include <linux/virtio_ring.h>
Rusty Russell93153072015-02-11 15:15:11 +103077#include "../../include/uapi/linux/virtio_pci.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093078#include <asm/bootparam.h>
79#include "../../include/linux/lguest_launcher.h"
80
Rusty Russell8ca47e02007-07-19 01:49:29 -070081#define BRIDGE_PFX "bridge:"
82#ifndef SIOCBRADDIF
83#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
84#endif
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100085/* We can have up to 256 pages for devices. */
86#define DEVICE_PAGES 256
Rusty Russell0f0c4fa2008-07-29 09:58:37 -050087/* This will occupy 3 pages: it must be a power of 2. */
88#define VIRTQUEUE_NUM 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070089
Rusty Russell2e04ef72009-07-30 16:03:45 -060090/*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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070094static bool verbose;
95#define verbose(args...) \
96 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070097/*:*/
98
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100099/* The pointer to the start of guest memory. */
100static void *guest_base;
101/* The maximum guest physical address allowed, and maximum possible. */
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030102static unsigned long guest_limit, guest_max, guest_mmio;
Rusty Russell56739c802009-06-12 22:26:59 -0600103/* The /dev/lguest file descriptor. */
104static int lguest_fd;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700105
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -0200106/* a per-cpu variable indicating whose vcpu is currently running */
107static unsigned int __thread cpu_id;
108
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030109/* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
110#define MAX_PCI_DEVICES 32
111
Rusty Russelldde79782007-07-26 10:41:03 -0700112/* This is our list of devices. */
Rusty Russell1842f232009-07-30 16:03:46 -0600113struct device_list {
Rusty Russell17cbca22007-10-22 11:24:22 +1000114 /* 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
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030120 /* PCI devices. */
121 struct device *pci[MAX_PCI_DEVICES];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700122};
123
Rusty Russell17cbca22007-10-22 11:24:22 +1000124/* The list of Guest devices, based on command line arguments. */
125static struct device_list devices;
126
Rusty Russell93153072015-02-11 15:15:11 +1030127struct virtio_pci_cfg_cap {
128 struct virtio_pci_cap cap;
Rusty Russellb2ce1ea2015-02-13 17:13:41 +1030129 u32 pci_cfg_data; /* Data for BAR access. */
Rusty Russell93153072015-02-11 15:15:11 +1030130};
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
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030140/* 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;
Rusty Russell93153072015-02-11 15:15:11 +1030153
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;
Rusty Russell93153072015-02-11 15:15:11 +1030159 struct virtio_pci_cfg_cap cfg_access;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030160};
161
Rusty Russelldde79782007-07-26 10:41:03 -0700162/* The device structure describes a single device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600163struct device {
Rusty Russell17cbca22007-10-22 11:24:22 +1000164 /* The name of this device, for --verbose. */
165 const char *name;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700166
Rusty Russell17cbca22007-10-22 11:24:22 +1000167 /* Any queues attached to this device */
168 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700169
Rusty Russell659a0e62009-06-12 22:27:10 -0600170 /* Is it operational */
171 bool running;
Rusty Russella007a752008-05-02 21:50:53 -0500172
Rusty Russelld39a6782015-02-13 17:13:43 +1030173 /* Has it written FEATURES_OK but not re-checked it? */
174 bool wrote_features_ok;
175
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030176 /* PCI configuration */
177 union {
178 struct pci_config config;
179 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
180 };
181
Rusty Russell93153072015-02-11 15:15:11 +1030182 /* Features we offer, and those accepted. */
183 u64 features, features_accepted;
184
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030185 /* Device-specific config hangs off the end of this. */
186 struct virtio_pci_mmio *mmio;
187
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030188 /* PCI MMIO resources (all in BAR0) */
189 size_t mmio_size;
190 u32 mmio_addr;
191
Rusty Russell8ca47e02007-07-19 01:49:29 -0700192 /* Device-specific data. */
193 void *priv;
194};
195
Rusty Russell17cbca22007-10-22 11:24:22 +1000196/* The virtqueue structure describes a queue attached to a device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600197struct virtqueue {
Rusty Russell17cbca22007-10-22 11:24:22 +1000198 struct virtqueue *next;
199
200 /* Which device owns me. */
201 struct device *dev;
202
Rusty Russell17c56d62015-02-13 17:13:43 +1030203 /* Name for printing errors. */
204 const char *name;
205
Rusty Russell17cbca22007-10-22 11:24:22 +1000206 /* The actual ring of buffers. */
207 struct vring vring;
208
Rusty Russell93153072015-02-11 15:15:11 +1030209 /* The information about this virtqueue (we only use queue_size on) */
210 struct virtio_pci_common_cfg pci_config;
211
Rusty Russell17cbca22007-10-22 11:24:22 +1000212 /* Last available index we saw. */
213 u16 last_avail_idx;
214
Rusty Russell95c517c2009-06-12 22:27:11 -0600215 /* How many are used since we sent last irq? */
216 unsigned int pending_used;
217
Rusty Russell659a0e62009-06-12 22:27:10 -0600218 /* Eventfd where Guest notifications arrive. */
219 int eventfd;
Rusty Russell20887612008-05-30 15:09:46 -0500220
Rusty Russell659a0e62009-06-12 22:27:10 -0600221 /* Function for the thread which is servicing this virtqueue. */
222 void (*service)(struct virtqueue *vq);
223 pid_t thread;
Rusty Russell17cbca22007-10-22 11:24:22 +1000224};
225
Balaji Raoec04b132007-12-28 14:26:24 +0530226/* Remember the arguments to the program so we can "reboot" */
227static char **main_args;
228
Rusty Russell659a0e62009-06-12 22:27:10 -0600229/* The original tty settings to restore on exit. */
230static struct termios orig_term;
231
Rusty Russell2e04ef72009-07-30 16:03:45 -0600232/*
233 * We have to be careful with barriers: our devices are all run in separate
Rusty Russellf7027c62009-06-12 22:27:00 -0600234 * threads and so we need to make sure that changes visible to the Guest happen
Rusty Russell2e04ef72009-07-30 16:03:45 -0600235 * in precise order.
236 */
Rusty Russellf7027c62009-06-12 22:27:00 -0600237#define wmb() __asm__ __volatile__("" : : : "memory")
Rusty Russell0d69a652013-07-02 15:35:14 +0930238#define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
239#define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
Rusty Russell17cbca22007-10-22 11:24:22 +1000240
Rusty Russellb5111792008-07-29 09:58:34 -0500241/* Wrapper for the last available index. Makes it easier to change. */
242#define lg_last_avail(vq) ((vq)->last_avail_idx)
243
Rusty Russell2e04ef72009-07-30 16:03:45 -0600244/*
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 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000248#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)
Rusty Russella586d4f2008-02-04 23:49:56 -0500253#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000254
Rusty Russell28fd6d72008-07-29 09:58:33 -0500255/* 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. */
Rusty Russellc0316a92012-10-16 23:56:13 +1030267static void iov_consume(struct iovec iov[], unsigned num_iov,
268 void *dest, unsigned len)
Rusty Russell28fd6d72008-07-29 09:58:33 -0500269{
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;
Rusty Russellc0316a92012-10-16 23:56:13 +1030276 if (dest) {
277 memcpy(dest, iov[i].iov_base, used);
278 dest += used;
279 }
Rusty Russell28fd6d72008-07-29 09:58:33 -0500280 iov[i].iov_base += used;
281 iov[i].iov_len -= used;
282 len -= used;
283 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030284 if (len != 0)
285 errx(1, "iovec too short!");
Rusty Russell28fd6d72008-07-29 09:58:33 -0500286}
287
Rusty Russell2e04ef72009-07-30 16:03:45 -0600288/*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.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000294 *
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
Francis Galieguea33f3222010-04-23 00:08:02 +0200300 * use these trivial conversion functions when the Guest gives us its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600301 * "physical" addresses:
302 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000303static 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
Rusty Russelldde79782007-07-26 10:41:03 -0700313/*L:130
314 * Loading the Kernel.
315 *
316 * We start with couple of simple helper routines. open_or_die() avoids
Rusty Russell2e04ef72009-07-30 16:03:45 -0600317 * error-checking code cluttering the callers:
318 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700319static 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
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000327/* map_zeroed_pages() takes a number of pages. */
328static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700329{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000330 int fd = open_or_die("/dev/zero", O_RDONLY);
331 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700332
Rusty Russell2e04ef72009-07-30 16:03:45 -0600333 /*
334 * We use a private mapping (ie. if we write to the page, it will be
Philip Sanderson5230ff02011-01-20 21:37:28 -0600335 * copied). We allocate an extra two pages PROT_NONE to act as guard
336 * pages against read/write attempts that exceed allocated space.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600337 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600338 addr = mmap(NULL, getpagesize() * (num+2),
339 PROT_NONE, MAP_PRIVATE, fd, 0);
340
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000341 if (addr == MAP_FAILED)
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200342 err(1, "Mmapping %u pages of /dev/zero", num);
Rusty Russella91d74a2009-07-30 16:03:45 -0600343
Philip Sanderson5230ff02011-01-20 21:37:28 -0600344 if (mprotect(addr + getpagesize(), getpagesize() * num,
345 PROT_READ|PROT_WRITE) == -1)
346 err(1, "mprotect rw %u pages failed", num);
347
Rusty Russella91d74a2009-07-30 16:03:45 -0600348 /*
349 * One neat mmap feature is that you can close the fd, and it
350 * stays mapped.
351 */
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100352 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700353
Philip Sanderson5230ff02011-01-20 21:37:28 -0600354 /* Return address after PROT_NONE page */
355 return addr + getpagesize();
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000356}
357
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030358/* 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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600375/*
376 * This routine is used to load the kernel or initrd. It tries mmap, but if
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700377 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
Rusty Russell2e04ef72009-07-30 16:03:45 -0600378 * it falls back to reading the memory in.
379 */
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700380static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
381{
382 ssize_t r;
383
Rusty Russell2e04ef72009-07-30 16:03:45 -0600384 /*
385 * We map writable even though for some segments are marked read-only.
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700386 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600391 * Guests.
392 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600393 if (mmap(addr, len, PROT_READ|PROT_WRITE,
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700394 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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600403/*
404 * This routine takes an open vmlinux image, which is in ELF, and maps it into
Rusty Russelldde79782007-07-26 10:41:03 -0700405 * 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
Rusty Russell47436aa2007-10-22 11:03:36 +1000409 * address. We use the physical address; the Guest will map itself to the
410 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700411 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600412 * We return the starting address.
413 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000414static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700415{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700416 Elf32_Phdr phdr[ehdr->e_phnum];
417 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700418
Rusty Russell2e04ef72009-07-30 16:03:45 -0600419 /*
420 * Sanity checks on the main ELF header: an x86 executable with a
421 * reasonable number of correctly-sized program headers.
422 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700423 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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600429 /*
430 * An ELF executable contains an ELF header and a number of "program"
Rusty Russelldde79782007-07-26 10:41:03 -0700431 * headers which indicate which parts ("segments") of the program to
Rusty Russell2e04ef72009-07-30 16:03:45 -0600432 * load where.
433 */
Rusty Russelldde79782007-07-26 10:41:03 -0700434
435 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700436 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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600441 /*
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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700445 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700446 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700447 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
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700453 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000454 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700455 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700456 }
457
Rusty Russell814a0e52007-10-22 11:29:44 +1000458 /* The entry point is given in the ELF header. */
459 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700460}
461
Rusty Russell2e04ef72009-07-30 16:03:45 -0600462/*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.
Rusty Russelldde79782007-07-26 10:41:03 -0700466 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000467 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600469 * the funky header so we know where in the file to load, and away we go!
470 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000471static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700472{
Rusty Russell43d33b22007-10-22 11:29:57 +1000473 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000474 int r;
475 /* Modern bzImages get loaded at 1M. */
476 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700477
Rusty Russell2e04ef72009-07-30 16:03:45 -0600478 /*
479 * Go back to the start of the file and read the header. It should be
Paul Bolle395cf962011-08-15 02:02:26 +0200480 * a Linux boot header (see Documentation/x86/boot.txt)
Rusty Russell2e04ef72009-07-30 16:03:45 -0600481 */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000482 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000483 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000484
Rusty Russell43d33b22007-10-22 11:29:57 +1000485 /* Inside the setup_hdr, we expect the magic "HdrS" */
486 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000487 errx(1, "This doesn't look like a bzImage to me");
488
Rusty Russell43d33b22007-10-22 11:29:57 +1000489 /* Skip over the extra sectors of the header. */
490 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000491
492 /* Now read everything into memory. in nice big chunks. */
493 while ((r = read(fd, p, 65536)) > 0)
494 p += r;
495
Rusty Russell43d33b22007-10-22 11:29:57 +1000496 /* Finally, code32_start tells us where to enter the kernel. */
497 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700498}
499
Rusty Russell2e04ef72009-07-30 16:03:45 -0600500/*L:140
501 * Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000502 * come wrapped up in the self-decompressing "bzImage" format. With a little
Rusty Russell2e04ef72009-07-30 16:03:45 -0600503 * work, we can load those, too.
504 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000505static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700506{
507 Elf32_Ehdr hdr;
508
Rusty Russelldde79782007-07-26 10:41:03 -0700509 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700510 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
511 err(1, "Reading kernel");
512
Rusty Russelldde79782007-07-26 10:41:03 -0700513 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700514 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000515 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700516
Rusty Russella6bd8e12008-03-28 11:05:53 -0500517 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000518 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700519}
520
Rusty Russell2e04ef72009-07-30 16:03:45 -0600521/*
522 * This is a trivial little helper to align pages. Andi Kleen hated it because
Rusty Russelldde79782007-07-26 10:41:03 -0700523 * it calls getpagesize() twice: "it's dumb code."
524 *
525 * Kernel guys get really het up about optimization, even when it's not
Rusty Russell2e04ef72009-07-30 16:03:45 -0600526 * necessary. I leave this code as a reaction against that.
527 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700528static inline unsigned long page_align(unsigned long addr)
529{
Rusty Russelldde79782007-07-26 10:41:03 -0700530 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700531 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
532}
533
Rusty Russell2e04ef72009-07-30 16:03:45 -0600534/*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.
Rusty Russelldde79782007-07-26 10:41:03 -0700539 *
540 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600541 * kernels. He sent me this (and tells me when I break it).
542 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700543static unsigned long load_initrd(const char *name, unsigned long mem)
544{
545 int ifd;
546 struct stat st;
547 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700548
549 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700550 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700551 if (fstat(ifd, &st) < 0)
552 err(1, "fstat() on initrd '%s'", name);
553
Rusty Russell2e04ef72009-07-30 16:03:45 -0600554 /*
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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700558 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000559 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600560 /*
561 * Once a file is mapped, you can close the file descriptor. It's a
562 * little odd, but quite useful.
563 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700564 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700565 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700566
567 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700568 return len;
569}
Rusty Russelle1e72962007-10-25 15:02:50 +1000570/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700571
Rusty Russell2e04ef72009-07-30 16:03:45 -0600572/*
573 * Simple routine to roll all the commandline arguments together with spaces
574 * between them.
575 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700576static void concat(char *dst, char *args[])
577{
578 unsigned int i, len = 0;
579
580 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100581 if (i) {
582 strcat(dst+len, " ");
583 len++;
584 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700585 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100586 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700587 }
588 /* In case it's empty. */
589 dst[len] = '\0';
590}
591
Rusty Russell2e04ef72009-07-30 16:03:45 -0600592/*L:185
593 * This is where we actually tell the kernel to initialize the Guest. We
Rusty Russelle1e72962007-10-25 15:02:50 +1000594 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300595 * the base of Guest "physical" memory, the top physical page to allow and the
Rusty Russell2e04ef72009-07-30 16:03:45 -0600596 * entry point for the Guest.
597 */
Rusty Russell56739c802009-06-12 22:26:59 -0600598static void tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700599{
Jes Sorensen511801d2007-10-22 11:03:31 +1000600 unsigned long args[] = { LHREQ_INITIALIZE,
601 (unsigned long)guest_base,
Rusty Russell7313d522015-02-11 15:15:10 +1030602 guest_limit / getpagesize(), start,
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030603 (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);
Rusty Russell56739c802009-06-12 22:26:59 -0600607 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
608 if (write(lguest_fd, args, sizeof(args)) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700609 err(1, "Writing to /dev/lguest");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700610}
Rusty Russelldde79782007-07-26 10:41:03 -0700611/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700612
Rusty Russella91d74a2009-07-30 16:03:45 -0600613/*L:200
Rusty Russelldde79782007-07-26 10:41:03 -0700614 * Device Handling.
615 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000616 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700617 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000618 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700619 * if something funny is going on:
620 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700621static void *_check_pointer(unsigned long addr, unsigned int size,
622 unsigned int line)
623{
Rusty Russell2e04ef72009-07-30 16:03:45 -0600624 /*
Philip Sanderson5230ff02011-01-20 21:37:28 -0600625 * Check if the requested address and size exceeds the allocated memory,
626 * or addr + size wraps around.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600627 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600628 if ((addr + size) > guest_limit || (addr + size) < addr)
Rusty Russell17cbca22007-10-22 11:24:22 +1000629 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600630 /*
631 * We return a pointer for the caller's convenience, now we know it's
632 * safe to use.
633 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000634 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700635}
Rusty Russelldde79782007-07-26 10:41:03 -0700636/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700637#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
638
Rusty Russell2e04ef72009-07-30 16:03:45 -0600639/*
640 * Each buffer in the virtqueues is actually a chain of descriptors. This
Rusty Russelle1e72962007-10-25 15:02:50 +1000641 * function returns the next descriptor in the chain, or vq->vring.num if we're
Rusty Russell2e04ef72009-07-30 16:03:45 -0600642 * at the end.
643 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100644static unsigned next_desc(struct vring_desc *desc,
645 unsigned int i, unsigned int max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000646{
647 unsigned int next;
648
649 /* If this descriptor says it doesn't chain, we're done. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100650 if (!(desc[i].flags & VRING_DESC_F_NEXT))
651 return max;
Rusty Russell17cbca22007-10-22 11:24:22 +1000652
653 /* Check they're not leading us off end of descriptors. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100654 next = desc[i].next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000655 /* Make sure compiler knows to grab that: we don't want it changing! */
656 wmb();
657
Mark McLoughlind1f01322009-05-11 18:11:46 +0100658 if (next >= max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000659 errx(1, "Desc next is %u", next);
660
661 return next;
662}
663
Rusty Russella91d74a2009-07-30 16:03:45 -0600664/*
665 * This actually sends the interrupt for this virtqueue, if we've used a
666 * buffer.
667 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600668static void trigger_irq(struct virtqueue *vq)
669{
Rusty Russelld9028ed2015-02-11 15:21:01 +1030670 unsigned long buf[] = { LHREQ_IRQ, vq->dev->config.irq_line };
Rusty Russell38bc2b82009-06-12 22:27:11 -0600671
Rusty Russell95c517c2009-06-12 22:27:11 -0600672 /* Don't inform them if nothing used. */
673 if (!vq->pending_used)
674 return;
675 vq->pending_used = 0;
676
Rusty Russelld39a6782015-02-13 17:13:43 +1030677 /*
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 */
Rusty Russellca60a422009-09-23 22:26:47 -0600697 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
Rusty Russell990c91f2011-05-30 11:14:12 -0600698 return;
Rusty Russellca60a422009-09-23 22:26:47 -0600699 }
Rusty Russell38bc2b82009-06-12 22:27:11 -0600700
Rusty Russell8dc425f2015-02-13 17:13:41 +1030701 /*
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 */
Rusty Russelld9028ed2015-02-11 15:21:01 +1030708 vq->dev->mmio->isr = 0x1;
Rusty Russell93153072015-02-11 15:15:11 +1030709
Rusty Russell38bc2b82009-06-12 22:27:11 -0600710 /* Send the Guest an interrupt tell them we used something up. */
711 if (write(lguest_fd, buf, sizeof(buf)) != 0)
Rusty Russelld9028ed2015-02-11 15:21:01 +1030712 err(1, "Triggering irq %i", vq->dev->config.irq_line);
Rusty Russell38bc2b82009-06-12 22:27:11 -0600713}
714
Rusty Russell2e04ef72009-07-30 16:03:45 -0600715/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600716 * This looks in the virtqueue for the first available buffer, and converts
Rusty Russell17cbca22007-10-22 11:24:22 +1000717 * 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 *
Rusty Russella91d74a2009-07-30 16:03:45 -0600721 * This function waits if necessary, and returns the descriptor number found.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600722 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600723static unsigned wait_for_vq_desc(struct virtqueue *vq,
724 struct iovec iov[],
725 unsigned int *out_num, unsigned int *in_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000726{
Mark McLoughlind1f01322009-05-11 18:11:46 +0100727 unsigned int i, head, max;
728 struct vring_desc *desc;
Rusty Russell659a0e62009-06-12 22:27:10 -0600729 u16 last_avail = lg_last_avail(vq);
730
Rusty Russelld39a6782015-02-13 17:13:43 +1030731 /*
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
Rusty Russella91d74a2009-07-30 16:03:45 -0600739 /* There's nothing available? */
Rusty Russell659a0e62009-06-12 22:27:10 -0600740 while (last_avail == vq->vring.avail->idx) {
741 u64 event;
742
Rusty Russella91d74a2009-07-30 16:03:45 -0600743 /*
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 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600747 trigger_irq(vq);
748
Rusty Russellb60da132009-06-12 22:27:12 -0600749 /* OK, now we need to know about added descriptors. */
750 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
751
Rusty Russell2e04ef72009-07-30 16:03:45 -0600752 /*
753 * They could have slipped one in as we were doing that: make
754 * sure it's written, then check again.
755 */
Rusty Russellb60da132009-06-12 22:27:12 -0600756 mb();
757 if (last_avail != vq->vring.avail->idx) {
758 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
759 break;
760 }
761
Rusty Russell659a0e62009-06-12 22:27:10 -0600762 /* 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?");
Rusty Russellb60da132009-06-12 22:27:12 -0600765
766 /* We don't need to be notified again. */
767 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russell659a0e62009-06-12 22:27:10 -0600768 }
Rusty Russell17cbca22007-10-22 11:24:22 +1000769
770 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500771 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000772 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500773 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000774
Rusty Russell8fd9a632013-07-02 15:35:13 +0930775 /*
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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600781 /*
782 * Grab the next descriptor number they're advertising, and increment
783 * the index we've seen.
784 */
Rusty Russellb5111792008-07-29 09:58:34 -0500785 head = vq->vring.avail->ring[last_avail % vq->vring.num];
786 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000787
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
Mark McLoughlind1f01322009-05-11 18:11:46 +0100795 max = vq->vring.num;
796 desc = vq->vring.desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000797 i = head;
Mark McLoughlind1f01322009-05-11 18:11:46 +0100798
Rusty Russell2e04ef72009-07-30 16:03:45 -0600799 /*
Rusty Russell8fd9a632013-07-02 15:35:13 +0930800 * 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
Rusty Russell17cbca22007-10-22 11:24:22 +1000805 do {
Rusty Russell3afe3e02015-02-13 17:13:42 +1030806 /*
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) {
Rusty Russelld39a6782015-02-13 17:13:43 +1030812 /* 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
Rusty Russell3afe3e02015-02-13 17:13:42 +1030844 if (desc[i].len % sizeof(struct vring_desc))
845 errx(1, "Invalid size for indirect buffer table");
Rusty Russelld39a6782015-02-13 17:13:43 +1030846 /*
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 */
Rusty Russell3afe3e02015-02-13 17:13:42 +1030855
856 max = desc[i].len / sizeof(struct vring_desc);
857 desc = check_pointer(desc[i].addr, desc[i].len);
858 i = 0;
Rusty Russelld39a6782015-02-13 17:13:43 +1030859
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);
Rusty Russell3afe3e02015-02-13 17:13:42 +1030868 }
869
Rusty Russell17cbca22007-10-22 11:24:22 +1000870 /* Grab the first descriptor, and check it's OK. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100871 iov[*out_num + *in_num].iov_len = desc[i].len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000872 iov[*out_num + *in_num].iov_base
Mark McLoughlind1f01322009-05-11 18:11:46 +0100873 = check_pointer(desc[i].addr, desc[i].len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000874 /* If this is an input descriptor, increment that count. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100875 if (desc[i].flags & VRING_DESC_F_WRITE)
Rusty Russell17cbca22007-10-22 11:24:22 +1000876 (*in_num)++;
877 else {
Rusty Russell2e04ef72009-07-30 16:03:45 -0600878 /*
879 * If it's an output descriptor, they're all supposed
880 * to come before any input descriptors.
881 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000882 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. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100888 if (*out_num + *in_num > max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000889 errx(1, "Looped descriptor");
Mark McLoughlind1f01322009-05-11 18:11:46 +0100890 } while ((i = next_desc(desc, i, max)) != max);
Rusty Russell17cbca22007-10-22 11:24:22 +1000891
892 return head;
893}
894
Rusty Russell2e04ef72009-07-30 16:03:45 -0600895/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600896 * 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.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600899 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000900static void add_used(struct virtqueue *vq, unsigned int head, int len)
901{
902 struct vring_used_elem *used;
903
Rusty Russell2e04ef72009-07-30 16:03:45 -0600904 /*
905 * The virtqueue contains a ring of used buffers. Get a pointer to the
906 * next entry in that used ring.
907 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000908 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++;
Rusty Russell95c517c2009-06-12 22:27:11 -0600914 vq->pending_used++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000915}
916
Rusty Russell17cbca22007-10-22 11:24:22 +1000917/* And here's the combo meal deal. Supersize me! */
Rusty Russell56739c802009-06-12 22:26:59 -0600918static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
Rusty Russell17cbca22007-10-22 11:24:22 +1000919{
920 add_used(vq, head, len);
Rusty Russell56739c802009-06-12 22:26:59 -0600921 trigger_irq(vq);
Rusty Russell17cbca22007-10-22 11:24:22 +1000922}
923
Rusty Russelle1e72962007-10-25 15:02:50 +1000924/*
925 * The Console
926 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600927 * We associate some data with the console for our exit hack.
928 */
Rusty Russell1842f232009-07-30 16:03:46 -0600929struct console_abort {
Rusty Russelldde79782007-07-26 10:41:03 -0700930 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700931 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700932 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700933 struct timeval start;
934};
935
Rusty Russelldde79782007-07-26 10:41:03 -0700936/* This is the routine which handles console input (ie. stdin). */
Rusty Russell659a0e62009-06-12 22:27:10 -0600937static void console_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700938{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700939 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000940 unsigned int head, in_num, out_num;
Rusty Russell659a0e62009-06-12 22:27:10 -0600941 struct console_abort *abort = vq->dev->priv;
942 struct iovec iov[vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700943
Rusty Russella91d74a2009-07-30 16:03:45 -0600944 /* Make sure there's a descriptor available. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600945 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000946 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000947 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700948
Rusty Russella91d74a2009-07-30 16:03:45 -0600949 /* Read into it. This is where we usually wait. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600950 len = readv(STDIN_FILENO, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700951 if (len <= 0) {
Rusty Russell659a0e62009-06-12 22:27:10 -0600952 /* Ran out of input? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700953 warnx("Failed to get console input, ignoring console.");
Rusty Russell2e04ef72009-07-30 16:03:45 -0600954 /*
955 * For simplicity, dying threads kill the whole Launcher. So
956 * just nap here.
957 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600958 for (;;)
959 pause();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700960 }
961
Rusty Russella91d74a2009-07-30 16:03:45 -0600962 /* Tell the Guest we used a buffer. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600963 add_used_and_trigger(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700964
Rusty Russell2e04ef72009-07-30 16:03:45 -0600965 /*
966 * Three ^C within one second? Exit.
Rusty Russelldde79782007-07-26 10:41:03 -0700967 *
Rusty Russell659a0e62009-06-12 22:27:10 -0600968 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -0600971 * slow.
972 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600973 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700974 abort->count = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -0600975 return;
976 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700977
Rusty Russell659a0e62009-06-12 22:27:10 -0600978 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 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700989}
990
Rusty Russell659a0e62009-06-12 22:27:10 -0600991/* This is the routine which handles console output (ie. stdout). */
992static void console_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700993{
Rusty Russell17cbca22007-10-22 11:24:22 +1000994 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000995 struct iovec iov[vq->vring.num];
996
Rusty Russella91d74a2009-07-30 16:03:45 -0600997 /* We usually wait in here, for the Guest to give us something. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600998 head = wait_for_vq_desc(vq, iov, &out, &in);
999 if (in)
1000 errx(1, "Input buffers in console output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -06001001
1002 /* writev can return a partial write, so we loop here. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001003 while (!iov_empty(iov, out)) {
1004 int len = writev(STDOUT_FILENO, iov, out);
Sakari Ailuse0377e22011-06-26 19:36:46 +03001005 if (len <= 0) {
1006 warn("Write to stdout gave %i (%d)", len, errno);
1007 break;
1008 }
Rusty Russellc0316a92012-10-16 23:56:13 +10301009 iov_consume(iov, out, NULL, len);
Rusty Russell17cbca22007-10-22 11:24:22 +10001010 }
Rusty Russella91d74a2009-07-30 16:03:45 -06001011
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 */
Rusty Russell38bc2b82009-06-12 22:27:11 -06001016 add_used(vq, head, 0);
Rusty Russella1618832008-07-29 09:58:35 -05001017}
1018
Rusty Russelle1e72962007-10-25 15:02:50 +10001019/*
1020 * The Network
1021 *
1022 * Handling output for network is also simple: we get all the output buffers
Rusty Russell659a0e62009-06-12 22:27:10 -06001023 * and write them to /dev/net/tun.
Rusty Russella6bd8e12008-03-28 11:05:53 -05001024 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001025struct net_info {
1026 int tunfd;
1027};
1028
1029static void net_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001030{
Rusty Russell659a0e62009-06-12 22:27:10 -06001031 struct net_info *net_info = vq->dev->priv;
1032 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +10001033 struct iovec iov[vq->vring.num];
1034
Rusty Russella91d74a2009-07-30 16:03:45 -06001035 /* We usually wait in here for the Guest to give us a packet. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001036 head = wait_for_vq_desc(vq, iov, &out, &in);
1037 if (in)
1038 errx(1, "Input buffers in net output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -06001039 /*
1040 * Send the whole thing through to /dev/net/tun. It expects the exact
1041 * same format: what a coincidence!
1042 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001043 if (writev(net_info->tunfd, iov, out) < 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +03001044 warnx("Write to tun failed (%d)?", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -06001045
1046 /*
1047 * Done with that one; wait_for_vq_desc() will send the interrupt if
1048 * all packets are processed.
1049 */
Rusty Russell38bc2b82009-06-12 22:27:11 -06001050 add_used(vq, head, 0);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001051}
1052
Rusty Russella91d74a2009-07-30 16:03:45 -06001053/*
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 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001059static 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
Rusty Russella91d74a2009-07-30 16:03:45 -06001068/*
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 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001073static void net_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001074{
Rusty Russell8ca47e02007-07-19 01:49:29 -07001075 int len;
Rusty Russell659a0e62009-06-12 22:27:10 -06001076 unsigned int head, out, in;
1077 struct iovec iov[vq->vring.num];
1078 struct net_info *net_info = vq->dev->priv;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001079
Rusty Russella91d74a2009-07-30 16:03:45 -06001080 /*
1081 * Get a descriptor to write an incoming packet into. This will also
1082 * send an interrupt if they're out of descriptors.
1083 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001084 head = wait_for_vq_desc(vq, iov, &out, &in);
1085 if (out)
1086 errx(1, "Output buffers in net input queue?");
Rusty Russell4a8962e2009-06-12 22:27:12 -06001087
Rusty Russella91d74a2009-07-30 16:03:45 -06001088 /*
1089 * If it looks like we'll block reading from the tun device, send them
1090 * an interrupt.
1091 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001092 if (vq->pending_used && will_block(net_info->tunfd))
1093 trigger_irq(vq);
1094
Rusty Russella91d74a2009-07-30 16:03:45 -06001095 /*
1096 * Read in the packet. This is where we normally wait (when there's no
1097 * incoming network traffic).
1098 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001099 len = readv(net_info->tunfd, iov, in);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001100 if (len <= 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +03001101 warn("Failed to read from tun (%d).", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -06001102
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 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001107 add_used(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001108}
Rusty Russella91d74a2009-07-30 16:03:45 -06001109/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001110
Rusty Russella91d74a2009-07-30 16:03:45 -06001111/* This is the helper to create threads: run the service routine in a loop. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001112static int do_thread(void *_vq)
Rusty Russell56ae43d2007-10-22 11:24:23 +10001113{
Rusty Russell659a0e62009-06-12 22:27:10 -06001114 struct virtqueue *vq = _vq;
1115
1116 for (;;)
1117 vq->service(vq);
1118 return 0;
Rusty Russell56ae43d2007-10-22 11:24:23 +10001119}
1120
Rusty Russell2e04ef72009-07-30 16:03:45 -06001121/*
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 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001125static void kill_launcher(int signal)
Rusty Russell5dae7852008-07-29 09:58:35 -05001126{
Rusty Russell659a0e62009-06-12 22:27:10 -06001127 kill(0, SIGTERM);
1128}
1129
Rusty Russelld2dbdac2015-02-13 17:13:40 +10301130static 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
Rusty Russell659a0e62009-06-12 22:27:10 -06001136static void reset_device(struct device *dev)
1137{
1138 struct virtqueue *vq;
1139
1140 verbose("Resetting device %s\n", dev->name);
1141
1142 /* Clear any features they've acked. */
Rusty Russelld9028ed2015-02-11 15:21:01 +10301143 dev->features_accepted = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06001144
1145 /* We're going to be explicitly killing threads, so ignore them. */
1146 signal(SIGCHLD, SIG_IGN);
1147
Rusty Russelld2dbdac2015-02-13 17:13:40 +10301148 /*
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
Rusty Russelld9028ed2015-02-11 15:21:01 +10301157 /* Get rid of the virtqueue threads */
Rusty Russell659a0e62009-06-12 22:27:10 -06001158 for (vq = dev->vq; vq; vq = vq->next) {
Rusty Russelld2dbdac2015-02-13 17:13:40 +10301159 vq->last_avail_idx = 0;
1160 reset_vq_pci_config(vq);
Rusty Russell659a0e62009-06-12 22:27:10 -06001161 if (vq->thread != (pid_t)-1) {
1162 kill(vq->thread, SIGTERM);
1163 waitpid(vq->thread, NULL, 0);
1164 vq->thread = (pid_t)-1;
1165 }
Rusty Russell659a0e62009-06-12 22:27:10 -06001166 }
1167 dev->running = false;
Rusty Russelld39a6782015-02-13 17:13:43 +10301168 dev->wrote_features_ok = false;
Rusty Russell659a0e62009-06-12 22:27:10 -06001169
1170 /* Now we care if threads die. */
1171 signal(SIGCHLD, (void *)kill_launcher);
1172}
1173
Rusty Russell659a0e62009-06-12 22:27:10 -06001174static void cleanup_devices(void)
1175{
Rusty Russelld9028ed2015-02-11 15:21:01 +10301176 unsigned int i;
Rusty Russell659a0e62009-06-12 22:27:10 -06001177
Rusty Russelld9028ed2015-02-11 15:21:01 +10301178 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1179 struct device *d = devices.pci[i];
1180 if (!d)
1181 continue;
1182 reset_device(d);
1183 }
Rusty Russell659a0e62009-06-12 22:27:10 -06001184
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);
Rusty Russell5dae7852008-07-29 09:58:35 -05001188}
1189
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301190/*L:217
1191 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1192 * code.
1193 */
1194
Rusty Russell8e709462015-02-11 15:15:12 +10301195/* 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
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301206/* 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
Rusty Russell59eba782015-02-11 15:24:01 +10301277/*
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
Rusty Russellc97eb672015-02-13 17:13:42 +10301299 /*
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 */
Rusty Russell59eba782015-02-11 15:24:01 +10301305 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
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301312/* 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
Rusty Russell59eba782015-02-11 15:24:01 +10301343static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask);
1344
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301345static 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;
Rusty Russell59eba782015-02-11 15:24:01 +10301385 } 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;
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301400 } else if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
Rusty Russell59eba782015-02-11 15:24:01 +10301401 u32 write_mask;
1402
Rusty Russell8dc425f2015-02-13 17:13:41 +10301403 /*
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
Rusty Russell59eba782015-02-11 15:24:01 +10301412 /* Must be bar 0 */
1413 if (!valid_bar_access(d, &d->config.cfg_access))
1414 return false;
1415
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301416 iowrite(portoff, val, mask, &d->config.cfg_access.pci_cfg_data);
Rusty Russell59eba782015-02-11 15:24:01 +10301417
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",
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301424 d->config.cfg_access.pci_cfg_data, write_mask,
Rusty Russell59eba782015-02-11 15:24:01 +10301425 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,
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301430 d->config.cfg_access.pci_cfg_data,
1431 write_mask);
Rusty Russell59eba782015-02-11 15:24:01 +10301432 return true;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301433 }
1434
Rusty Russellc97eb672015-02-13 17:13:42 +10301435 /*
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 */
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301442 return false;
1443}
1444
Rusty Russell59eba782015-02-11 15:24:01 +10301445static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask);
1446
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301447static 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;
Rusty Russell59eba782015-02-11 15:24:01 +10301454
1455 /* Read through the PCI MMIO access window is special */
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301456 if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
Rusty Russell59eba782015-02-11 15:24:01 +10301457 u32 read_mask;
1458
Rusty Russell8dc425f2015-02-13 17:13:41 +10301459 /*
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 */
Rusty Russell59eba782015-02-11 15:24:01 +10301467 /* 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;
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301479 d->config.cfg_access.pci_cfg_data
Rusty Russell59eba782015-02-11 15:24:01 +10301480 = 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",
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301484 d->config.cfg_access.pci_cfg_data, read_mask,
Rusty Russell59eba782015-02-11 15:24:01 +10301485 d->config.cfg_access.cap.bar,
1486 d->config.cfg_access.cap.offset,
1487 d->config.cfg_access.cap.length);
1488 }
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301489 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1490}
1491
Rusty Russellc565650b2015-02-11 15:15:10 +10301492/*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
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301526/* 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
Rusty Russellc565650b2015-02-11 15:15:10 +10301597static 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 /*
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301603 * Default is to return all-ones on IO port reads, which traditionally
Rusty Russellc565650b2015-02-11 15:15:10 +10301604 * 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) {
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301685 /* 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
Rusty Russellc565650b2015-02-11 15:15:10 +10301693 /* 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);
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301699 } 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. */
Rusty Russellc565650b2015-02-11 15:15:10 +10301709 }
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
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301718bad_io:
1719 warnx("Attempt to %s port %u (%#x mask)",
1720 in ? "read from" : "write to", port, mask);
1721
Rusty Russellc565650b2015-02-11 15:15:10 +10301722no_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
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301728static 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
Rusty Russell93153072015-02-11 15:15:11 +10301747/* 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/*
Rusty Russelld761b032015-02-13 17:13:42 +10301775 * 4.1.4.3.2:
1776 *
1777 * The driver MUST configure the other virtqueue fields before
1778 * enabling the virtqueue with queue_enable.
1779 *
Rusty Russell93153072015-02-11 15:15:11 +10301780 * When they enable the virtqueue, we check that their setup is valid.
1781 */
Rusty Russelld761b032015-02-13 17:13:42 +10301782static void check_virtqueue(struct device *d, struct virtqueue *vq)
Rusty Russell93153072015-02-11 15:15:11 +10301783{
Rusty Russell93153072015-02-11 15:15:11 +10301784 /* 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
Rusty Russelld39a6782015-02-13 17:13:43 +10301790 /*
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
Rusty Russell93153072015-02-11 15:15:11 +10301802 /* 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));
Rusty Russelld39a6782015-02-13 17:13:43 +10301814
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);
Rusty Russelld761b032015-02-13 17:13:42 +10301824}
Rusty Russell93153072015-02-11 15:15:11 +10301825
Rusty Russelld761b032015-02-13 17:13:42 +10301826static 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);
Rusty Russell93153072015-02-11 15:15:11 +10301833
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
Rusty Russelld761b032015-02-13 17:13:42 +10301848static 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
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301858static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1859{
Rusty Russell93153072015-02-11 15:15:11 +10301860 struct virtqueue *vq;
1861
1862 switch (off) {
1863 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
Rusty Russell8dc425f2015-02-13 17:13:41 +10301864 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10301871 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;
Rusty Russelld39a6782015-02-13 17:13:43 +10301877 goto feature_write_through32;
Rusty Russell93153072015-02-11 15:15:11 +10301878 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);
Rusty Russelld39a6782015-02-13 17:13:43 +10301882 goto feature_write_through32;
Rusty Russell93153072015-02-11 15:15:11 +10301883 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);
Rusty Russell53aceb42015-02-13 17:13:41 +10301889 d->features_accepted &= 0xFFFFFFFF;
Rusty Russell93153072015-02-11 15:15:11 +10301890 d->features_accepted |= ((u64)val) << 32;
1891 }
Rusty Russelld39a6782015-02-13 17:13:43 +10301892 /*
1893 * 2.2.1:
1894 *
1895 * The driver MUST NOT accept a feature which the device did
1896 * not offer
1897 */
Rusty Russell93153072015-02-11 15:15:11 +10301898 if (d->features_accepted & ~d->features)
1899 errx(1, "%s: over-accepted features %#llx of %#llx",
1900 d->name, d->features_accepted, d->features);
Rusty Russelld39a6782015-02-13 17:13:43 +10301901 goto feature_write_through32;
1902 case offsetof(struct virtio_pci_mmio, cfg.device_status): {
1903 u8 prev;
1904
Rusty Russell93153072015-02-11 15:15:11 +10301905 verbose("%s: device status -> %#x\n", d->name, val);
Rusty Russell8dc425f2015-02-13 17:13:41 +10301906 /*
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 */
Rusty Russelld39a6782015-02-13 17:13:43 +10301912 if (val == 0) {
Rusty Russelld9028ed2015-02-11 15:21:01 +10301913 reset_device(d);
Rusty Russelld39a6782015-02-13 17:13:43 +10301914 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);
Rusty Russelld761b032015-02-13 17:13:42 +10301921
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
Rusty Russelld39a6782015-02-13 17:13:43 +10301932 /*
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 }
Rusty Russell93153072015-02-11 15:15:11 +10301991 goto write_through8;
Rusty Russelld39a6782015-02-13 17:13:43 +10301992 }
Rusty Russell93153072015-02-11 15:15:11 +10301993 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1994 vq = vq_by_num(d, val);
Rusty Russell8dc425f2015-02-13 17:13:41 +10301995 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302001 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):
Rusty Russellc97eb672015-02-13 17:13:42 +10302013 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302019 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);
Rusty Russelld39a6782015-02-13 17:13:43 +10302028 case offsetof(struct virtio_pci_mmio, cfg.queue_enable): {
2029 struct virtqueue *vq = vq_by_num(d, d->mmio->cfg.queue_select);
2030
Rusty Russellc97eb672015-02-13 17:13:42 +10302031 /*
2032 * 4.1.4.3.2:
2033 *
2034 * The driver MUST NOT write a 0 to queue_enable.
2035 */
Rusty Russell93153072015-02-11 15:15:11 +10302036 if (val != 1)
2037 errx(1, "%s: setting queue_enable to %u", d->name, val);
Rusty Russelld39a6782015-02-13 17:13:43 +10302038
Rusty Russellc97eb672015-02-13 17:13:42 +10302039 /*
Rusty Russelld39a6782015-02-13 17:13:43 +10302040 * 3.1.1:
Rusty Russellc97eb672015-02-13 17:13:42 +10302041 *
Rusty Russelld39a6782015-02-13 17:13:43 +10302042 * 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.
Rusty Russellc97eb672015-02-13 17:13:42 +10302050 */
Rusty Russelld39a6782015-02-13 17:13:43 +10302051 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);
Rusty Russell93153072015-02-11 15:15:11 +10302057 goto write_through16;
Rusty Russelld39a6782015-02-13 17:13:43 +10302058 }
Rusty Russell93153072015-02-11 15:15:11 +10302059 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):
Rusty Russellc97eb672015-02-13 17:13:42 +10302067 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302073 if (d->mmio->cfg.queue_enable)
2074 errx(1, "%s: changing queue on live device",
2075 d->name);
Rusty Russelld39a6782015-02-13 17:13:43 +10302076
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
Rusty Russell93153072015-02-11 15:15:11 +10302096 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);
Rusty Russelle8330d92015-02-11 15:23:01 +10302106 /* 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... */
Rusty Russell93153072015-02-11 15:15:11 +10302115 default:
Rusty Russellc97eb672015-02-13 17:13:42 +10302116 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302122 errx(1, "%s: Unexpected write to offset %u", d->name, off);
2123 }
2124
Rusty Russelld39a6782015-02-13 17:13:43 +10302125feature_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);
Rusty Russellc97eb672015-02-13 17:13:42 +10302146
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302154write_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;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302176}
2177
2178static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
2179{
Rusty Russell93153072015-02-11 15:15:11 +10302180 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):
Rusty Russelld39a6782015-02-13 17:13:43 +10302188 /*
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);
Rusty Russell93153072015-02-11 15:15:11 +10302202 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):
Rusty Russelld39a6782015-02-13 17:13:43 +10302208 /* As they did read, any write of FEATURES_OK is now fine. */
2209 d->wrote_features_ok = false;
2210 goto read_through8;
Rusty Russell93153072015-02-11 15:15:11 +10302211 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
Rusty Russell8dc425f2015-02-13 17:13:41 +10302212 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302223 goto read_through8;
2224 case offsetof(struct virtio_pci_mmio, notify):
Rusty Russelld39a6782015-02-13 17:13:43 +10302225 /*
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);
Rusty Russell93153072015-02-11 15:15:11 +10302234 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));
Rusty Russell93153072015-02-11 15:15:11 +10302239 isr = d->mmio->isr;
Rusty Russell8dc425f2015-02-13 17:13:41 +10302240 /*
2241 * 4.1.4.5.1:
2242 *
2243 * The device MUST reset ISR status to 0 on driver read.
2244 */
Rusty Russell93153072015-02-11 15:15:11 +10302245 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));
Rusty Russelld39a6782015-02-13 17:13:43 +10302255
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
Rusty Russell93153072015-02-11 15:15:11 +10302272 if (mask == 0xFFFFFFFF)
2273 goto read_through32;
2274 else if (mask == 0xFFFF)
2275 goto read_through16;
2276 else
2277 goto read_through8;
2278 }
2279
Rusty Russellc97eb672015-02-13 17:13:42 +10302280 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302287read_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;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302307}
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}
Rusty Russellc565650b2015-02-11 15:15:10 +10302363
Rusty Russelldde79782007-07-26 10:41:03 -07002364/*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
Rusty Russella6bd8e12008-03-28 11:05:53 -05002369 * routines to allocate and manage them.
2370 */
Rusty Russell93153072015-02-11 15:15:11 +10302371static void add_pci_virtqueue(struct device *dev,
Rusty Russell17c56d62015-02-13 17:13:43 +10302372 void (*service)(struct virtqueue *),
2373 const char *name)
Rusty Russell93153072015-02-11 15:15:11 +10302374{
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;
Rusty Russell17c56d62015-02-13 17:13:43 +10302381 vq->name = name;
Rusty Russell93153072015-02-11 15:15:11 +10302382
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. */
Rusty Russelld2dbdac2015-02-13 17:13:40 +10302391 reset_vq_pci_config(vq);
Rusty Russell93153072015-02-11 15:15:11 +10302392 vq->pci_config.queue_notify_off = 0;
2393
2394 /* Add one to the number of queues */
2395 vq->dev->mmio->cfg.num_queues++;
2396
Rusty Russell93153072015-02-11 15:15:11 +10302397 /*
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
Rusty Russelld9028ed2015-02-11 15:21:01 +10302405/* The Guest accesses the feature bits via the PCI common config MMIO region */
Rusty Russell93153072015-02-11 15:15:11 +10302406static void add_pci_feature(struct device *dev, unsigned bit)
2407{
2408 dev->features |= (1ULL << bit);
2409}
2410
Rusty Russell93153072015-02-11 15:15:11 +10302411/* 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
Rusty Russell8dc425f2015-02-13 17:13:41 +10302429 /*
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 */
Rusty Russell93153072015-02-11 15:15:11 +10302436 /* Hook up device cfg */
2437 dev->config.cfg_access.cap.cap_next
2438 = offsetof(struct pci_config, device);
2439
Rusty Russell8dc425f2015-02-13 17:13:41 +10302440 /*
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
Rusty Russell93153072015-02-11 15:15:11 +10302448 /* 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
Rusty Russell8dc425f2015-02-13 17:13:41 +10302477 /*
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.
Rusty Russelld39a6782015-02-13 17:13:43 +10302482 *
2483 * 2.1.2:
2484 *
2485 * The device MUST initialize device status to 0 upon reset.
Rusty Russell8dc425f2015-02-13 17:13:41 +10302486 */
Rusty Russell93153072015-02-11 15:15:11 +10302487 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.
Rusty Russell93153072015-02-11 15:15:11 +10302498 */
2499 pci->class = class;
2500 pci->subclass = subclass;
2501
2502 /*
Rusty Russell8dc425f2015-02-13 17:13:41 +10302503 * 4.1.2.1:
2504 *
2505 * Non-transitional devices SHOULD have a PCI Revision ID of 1 or
2506 * higher
Rusty Russell93153072015-02-11 15:15:11 +10302507 */
2508 pci->revid = 1;
2509
2510 /*
Rusty Russell8dc425f2015-02-13 17:13:41 +10302511 * 4.1.2.1:
2512 *
2513 * Non-transitional devices SHOULD have a PCI Subsystem Device ID of
2514 * 0x40 or higher.
Rusty Russell93153072015-02-11 15:15:11 +10302515 */
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. */
Rusty Russell8dc425f2015-02-13 17:13:41 +10302526 /*
2527 * 4.1.4.3.1:
2528 *
2529 * The device MUST present at least one common configuration
2530 * capability.
2531 */
Rusty Russell93153072015-02-11 15:15:11 +10302532 pci->capabilities = offsetof(struct pci_config, common);
2533
Rusty Russell8dc425f2015-02-13 17:13:41 +10302534 /* 4.1.4.3.1 ... offset MUST be 4-byte aligned. */
2535 assert(pci->capabilities % 4 == 0);
2536
Rusty Russell93153072015-02-11 15:15:11 +10302537 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
Rusty Russell8dc425f2015-02-13 17:13:41 +10302543 /*
2544 * 4.1.4.4.1:
2545 *
2546 * The device MUST present at least one notification capability.
2547 */
Rusty Russell93153072015-02-11 15:15:11 +10302548 bar_offset += bar_len;
2549 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
Rusty Russell8dc425f2015-02-13 17:13:41 +10302550
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
Rusty Russell93153072015-02-11 15:15:11 +10302558 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
Rusty Russell8dc425f2015-02-13 17:13:41 +10302559 /*
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
Rusty Russell93153072015-02-11 15:15:11 +10302568 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);
Rusty Russell8dc425f2015-02-13 17:13:41 +10302575 /*
2576 * 4.1.4.5.1:
2577 *
2578 * The device MUST present at least one VIRTIO_PCI_CAP_ISR_CFG
2579 * capability.
2580 */
Rusty Russell93153072015-02-11 15:15:11 +10302581 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
Rusty Russell8dc425f2015-02-13 17:13:41 +10302586 /*
2587 * 4.1.4.7.1:
2588 *
2589 * The device MUST present at least one VIRTIO_PCI_CAP_PCI_CFG
2590 * capability.
2591 */
Rusty Russell93153072015-02-11 15:15:11 +10302592 /* 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002609/*
Rusty Russelld9028ed2015-02-11 15:21:01 +10302610 * 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.
Rusty Russella6bd8e12008-03-28 11:05:53 -05002614 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002615 * See what I mean about userspace being boring?
2616 */
Rusty Russell93153072015-02-11 15:15:11 +10302617static 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. */
Rusty Russell93153072015-02-11 15:15:11 +10302623 dev->name = name;
2624 dev->vq = NULL;
Rusty Russell93153072015-02-11 15:15:11 +10302625 dev->running = false;
Rusty Russelld39a6782015-02-13 17:13:43 +10302626 dev->wrote_features_ok = false;
Rusty Russell93153072015-02-11 15:15:11 +10302627 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
Rusty Russelld9028ed2015-02-11 15:21:01 +10302632 if (devices.device_num + 1 >= MAX_PCI_DEVICES)
Rusty Russell93153072015-02-11 15:15:11 +10302633 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002642/*
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 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002646static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002647{
2648 struct device *dev;
Rusty Russelle8330d92015-02-11 15:23:01 +10302649 struct virtio_console_config conf;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002650
Rusty Russelldde79782007-07-26 10:41:03 -07002651 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002652 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2653 struct termios term = orig_term;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002654 /*
2655 * Then we turn off echo, line buffering and ^C etc: We want a
2656 * raw input stream to the Guest.
2657 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002658 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2659 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002660 }
2661
Rusty Russellebff0112015-02-11 15:18:01 +10302662 dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002663
Rusty Russelldde79782007-07-26 10:41:03 -07002664 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002665 dev->priv = malloc(sizeof(struct console_abort));
2666 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002667
Rusty Russell2e04ef72009-07-30 16:03:45 -06002668 /*
2669 * The console needs two virtqueues: the input then the output. When
Rusty Russell56ae43d2007-10-22 11:24:23 +10002670 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002672 * stdout.
2673 */
Rusty Russell17c56d62015-02-13 17:13:43 +10302674 add_pci_virtqueue(dev, console_input, "input");
2675 add_pci_virtqueue(dev, console_output, "output");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002676
Rusty Russelle8330d92015-02-11 15:23:01 +10302677 /* 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));
Rusty Russellebff0112015-02-11 15:18:01 +10302680
2681 verbose("device %u: console\n", devices.device_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002682}
Rusty Russelldde79782007-07-26 10:41:03 -07002683/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002684
Rusty Russell2e04ef72009-07-30 16:03:45 -06002685/*M:010
2686 * Inter-guest networking is an interesting area. Simplest is to have a
Rusty Russell17cbca22007-10-22 11:24:22 +10002687 * --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.
2689 *
Rusty Russell9f542882011-07-22 14:39:50 +09302690 * More sophisticated is to use one of the tools developed for project like UML
Rusty Russell17cbca22007-10-22 11:24:22 +10002691 * to do networking.
2692 *
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 *
Rusty Russell9f542882011-07-22 14:39:50 +09302700 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002701:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002702
Rusty Russell8ca47e02007-07-19 01:49:29 -07002703static u32 str2ip(const char *ipaddr)
2704{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002705 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002706
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002707 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];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002724}
2725
Rusty Russell2e04ef72009-07-30 16:03:45 -06002726/*
2727 * This code is "adapted" from libbridge: it attaches the Host end of the
Rusty Russelldde79782007-07-26 10:41:03 -07002728 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002731 * dislike bridging), and I just try not to break it.
2732 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002733static 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);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002746 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07002747 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002752/*
2753 * This sets up the Host end of the network device with an IP address, brings
Rusty Russelldde79782007-07-26 10:41:03 -07002754 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell2e04ef72009-07-30 16:03:45 -06002755 * pointer.
2756 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002757static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002758{
2759 struct ifreq ifr;
Rusty Russellf8466192010-08-27 08:39:48 -06002760 struct sockaddr_in sin;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002761
2762 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002763 strcpy(ifr.ifr_name, tapif);
2764
2765 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russellf8466192010-08-27 08:39:48 -06002766 sin.sin_family = AF_INET;
2767 sin.sin_addr.s_addr = htonl(ipaddr);
2768 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002769 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002770 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002771 ifr.ifr_flags = IFF_UP;
2772 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002773 err(1, "Bringing interface %s up", tapif);
2774}
2775
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002776static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07002777{
Rusty Russell8ca47e02007-07-19 01:49:29 -07002778 struct ifreq ifr;
Rusty Russellbf6d4032015-02-11 15:16:01 +10302779 int vnet_hdr_sz;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002780 int netfd;
2781
2782 /* Start with this zeroed. Messy but sure. */
2783 memset(&ifr, 0, sizeof(ifr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002784
Rusty Russell2e04ef72009-07-30 16:03:45 -06002785 /*
2786 * We open the /dev/net/tun device and tell it we want a tap device. A
Rusty Russelldde79782007-07-26 10:41:03 -07002787 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002789 * works now!
2790 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002791 netfd = open_or_die("/dev/net/tun", O_RDWR);
Rusty Russell398f1872008-07-29 09:58:37 -05002792 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002793 strcpy(ifr.ifr_name, "tap%d");
2794 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2795 err(1, "configuring /dev/net/tun");
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002796
Rusty Russell398f1872008-07-29 09:58:37 -05002797 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002801 /*
2802 * We don't need checksums calculated for packets coming in this
2803 * device: trust us!
2804 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002805 ioctl(netfd, TUNSETNOCSUM, 1);
2806
Rusty Russellbf6d4032015-02-11 15:16:01 +10302807 /*
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
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002819 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2820 return netfd;
2821}
2822
Rusty Russell2e04ef72009-07-30 16:03:45 -06002823/*L:195
2824 * Our network is a Host<->Guest network. This can either use bridging or
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002825 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06002827 * just shunt packets between the Guest and the tun device.
2828 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002829static void setup_tun_net(char *arg)
2830{
2831 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002832 struct net_info *net_info = malloc(sizeof(*net_info));
2833 int ipfd;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002834 u32 ip = INADDR_ANY;
2835 bool bridging = false;
2836 char tapif[IFNAMSIZ], *p;
2837 struct virtio_net_config conf;
2838
Rusty Russell659a0e62009-06-12 22:27:10 -06002839 net_info->tunfd = get_tun_device(tapif);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002840
Rusty Russell17cbca22007-10-22 11:24:22 +10002841 /* First we create a new network device. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302842 dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002843 dev->priv = net_info;
Rusty Russelldde79782007-07-26 10:41:03 -07002844
Rusty Russell2e04ef72009-07-30 16:03:45 -06002845 /* Network devices need a recv and a send queue, just like console. */
Rusty Russell17c56d62015-02-13 17:13:43 +10302846 add_pci_virtqueue(dev, net_input, "rx");
2847 add_pci_virtqueue(dev, net_output, "tx");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002848
Rusty Russell2e04ef72009-07-30 16:03:45 -06002849 /*
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 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002853 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2854 if (ipfd < 0)
2855 err(1, "opening IP socket");
2856
Rusty Russelldde79782007-07-26 10:41:03 -07002857 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002858 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002859 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);
Rusty Russellbf6d4032015-02-11 15:16:01 +10302867 add_pci_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002868 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002869 }
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
Rusty Russell8ca47e02007-07-19 01:49:29 -07002875 ip = str2ip(arg);
2876
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002877 /* Set up the tun device. */
2878 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002879
Rusty Russell398f1872008-07-29 09:58:37 -05002880 /* Expect Guest to handle everything except UFO */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302881 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);
Mark McLoughlind1f01322009-05-11 18:11:46 +01002889 /* We handle indirect ring entries */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302890 add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2891 set_device_config(dev, &conf, sizeof(conf));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002892
Rusty Russella586d4f2008-02-04 23:49:56 -05002893 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002894 close(ipfd);
2895
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002896 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);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002902}
Rusty Russella91d74a2009-07-30 16:03:45 -06002903/*:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002904
Rusty Russelle1e72962007-10-25 15:02:50 +10002905/* This hangs off device->priv. */
Rusty Russell1842f232009-07-30 16:03:46 -06002906struct vblk_info {
Rusty Russell17cbca22007-10-22 11:24:22 +10002907 /* The size of the file. */
2908 off64_t len;
2909
2910 /* The file descriptor for the file. */
2911 int fd;
2912
Rusty Russell17cbca22007-10-22 11:24:22 +10002913};
2914
Rusty Russelle1e72962007-10-25 15:02:50 +10002915/*L:210
2916 * The Disk
2917 *
Rusty Russella91d74a2009-07-30 16:03:45 -06002918 * 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.
Rusty Russelle1e72962007-10-25 15:02:50 +10002928 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002929static void blk_request(struct virtqueue *vq)
Rusty Russell17cbca22007-10-22 11:24:22 +10002930{
Rusty Russell659a0e62009-06-12 22:27:10 -06002931 struct vblk_info *vblk = vq->dev->priv;
Rusty Russell17cbca22007-10-22 11:24:22 +10002932 unsigned int head, out_num, in_num, wlen;
Rusty Russellc0316a92012-10-16 23:56:13 +10302933 int ret, i;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002934 u8 *in;
Rusty Russellc0316a92012-10-16 23:56:13 +10302935 struct virtio_blk_outhdr out;
Rusty Russell659a0e62009-06-12 22:27:10 -06002936 struct iovec iov[vq->vring.num];
Rusty Russell17cbca22007-10-22 11:24:22 +10002937 off64_t off;
2938
Rusty Russella91d74a2009-07-30 16:03:45 -06002939 /*
2940 * Get the next request, where we normally wait. It triggers the
2941 * interrupt to acknowledge previously serviced requests (if any).
2942 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002943 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002944
Rusty Russellc0316a92012-10-16 23:56:13 +10302945 /* Copy the output header from the front of the iov (adjusts iov) */
2946 iov_consume(iov, out_num, &out, sizeof(out));
Rusty Russell17cbca22007-10-22 11:24:22 +10002947
Rusty Russellc0316a92012-10-16 23:56:13 +10302948 /* 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");
2959
Rusty Russella91d74a2009-07-30 16:03:45 -06002960 /*
2961 * For historical reasons, block operations are expressed in 512 byte
2962 * "sectors".
2963 */
Rusty Russellc0316a92012-10-16 23:56:13 +10302964 off = out.sector * 512;
Rusty Russell17cbca22007-10-22 11:24:22 +10002965
Rusty Russell50516542015-02-11 15:15:12 +10302966 if (out.type & VIRTIO_BLK_T_OUT) {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002967 /*
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 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002973 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302974 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002975
Rusty Russellc0316a92012-10-16 23:56:13 +10302976 ret = writev(vblk->fd, iov, out_num);
2977 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
Rusty Russell17cbca22007-10-22 11:24:22 +10002978
Rusty Russell2e04ef72009-07-30 16:03:45 -06002979 /*
2980 * Grr... Now we know how long the descriptor they sent was, we
Rusty Russell17cbca22007-10-22 11:24:22 +10002981 * make sure they didn't try to write over the end of the block
Rusty Russell2e04ef72009-07-30 16:03:45 -06002982 * file (possibly extending it).
2983 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002984 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 }
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002990
2991 wlen = sizeof(*in);
2992 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russellc0316a92012-10-16 23:56:13 +10302993 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002994 /* Flush */
2995 ret = fdatasync(vblk->fd);
2996 verbose("FLUSH fdatasync: %i\n", ret);
Anthony Liguori1200e642007-11-08 21:13:44 -06002997 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002998 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10002999 } else {
Rusty Russell2e04ef72009-07-30 16:03:45 -06003000 /*
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 */
Rusty Russell17cbca22007-10-22 11:24:22 +10003006 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10303007 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10003008
Rusty Russellc0316a92012-10-16 23:56:13 +10303009 ret = readv(vblk->fd, iov + out_num, in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10003010 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06003011 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05003012 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10003013 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06003014 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05003015 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10003016 }
3017 }
3018
Rusty Russella91d74a2009-07-30 16:03:45 -06003019 /* Finished that request. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06003020 add_used(vq, head, wlen);
Rusty Russell17cbca22007-10-22 11:24:22 +10003021}
3022
Rusty Russelle1e72962007-10-25 15:02:50 +10003023/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10003024static void setup_block_file(const char *filename)
3025{
Rusty Russell17cbca22007-10-22 11:24:22 +10003026 struct device *dev;
3027 struct vblk_info *vblk;
Rusty Russella586d4f2008-02-04 23:49:56 -05003028 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10003029
Rusty Russell50516542015-02-11 15:15:12 +10303030 /* Create the device. */
3031 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
Rusty Russell17cbca22007-10-22 11:24:22 +10003032
Rusty Russelle1e72962007-10-25 15:02:50 +10003033 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell17c56d62015-02-13 17:13:43 +10303034 add_pci_virtqueue(dev, blk_request, "request");
Rusty Russell17cbca22007-10-22 11:24:22 +10003035
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. */
Rusty Russella586d4f2008-02-04 23:49:56 -05003044 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10003045
Rusty Russell2e04ef72009-07-30 16:03:45 -06003046 /*
3047 * Tell Guest not to put in too many descriptors at once: two are used
3048 * for the in and out elements.
3049 */
Rusty Russell50516542015-02-11 15:15:12 +10303050 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
Rusty Russella586d4f2008-02-04 23:49:56 -05003051 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
3052
Rusty Russell50516542015-02-11 15:15:12 +10303053 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
Rusty Russell17cbca22007-10-22 11:24:22 +10003054
Rusty Russell17cbca22007-10-22 11:24:22 +10003055 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell50516542015-02-11 15:15:12 +10303056 devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10003057}
Rusty Russell28fd6d72008-07-29 09:58:33 -05003058
Rusty Russell2e04ef72009-07-30 16:03:45 -06003059/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10303060 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05003061 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10303062 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05003063 * console is the reverse.
3064 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06003065 * The same logic applies, however.
3066 */
3067struct rng_info {
3068 int rfd;
3069};
3070
Rusty Russell659a0e62009-06-12 22:27:10 -06003071static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05003072{
3073 int len;
3074 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06003075 struct rng_info *rng_info = vq->dev->priv;
3076 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05003077
3078 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06003079 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05003080 if (out_num)
3081 errx(1, "Output buffers in rng?");
3082
Rusty Russell2e04ef72009-07-30 16:03:45 -06003083 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06003084 * Just like the console write, we loop to cover the whole iovec.
3085 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06003086 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05003087 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06003088 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05003089 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10303090 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10303091 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05003092 totlen += len;
3093 }
3094
3095 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06003096 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05003097}
3098
Rusty Russell2e04ef72009-07-30 16:03:45 -06003099/*L:199
3100 * This creates a "hardware" random number device for the Guest.
3101 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05003102static void setup_rng(void)
3103{
3104 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06003105 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05003106
Rusty Russella454bb32015-02-11 15:15:09 +10303107 /* Our device's private info simply contains the /dev/urandom fd. */
3108 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05003109
Rusty Russell2e04ef72009-07-30 16:03:45 -06003110 /* Create the new device. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10303111 dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
Rusty Russell659a0e62009-06-12 22:27:10 -06003112 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05003113
3114 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell17c56d62015-02-13 17:13:43 +10303115 add_pci_virtqueue(dev, rng_input, "input");
Rusty Russell28fd6d72008-07-29 09:58:33 -05003116
Rusty Russell0d5b5d32015-02-11 15:17:01 +10303117 /* We don't have any configuration space */
3118 no_device_config(dev);
3119
3120 verbose("device %u: rng\n", devices.device_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05003121}
Rusty Russella6bd8e12008-03-28 11:05:53 -05003122/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05303123
Rusty Russella6bd8e12008-03-28 11:05:53 -05003124/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05303125static void __attribute__((noreturn)) restart_guest(void)
3126{
3127 unsigned int i;
3128
Rusty Russell2e04ef72009-07-30 16:03:45 -06003129 /*
3130 * Since we don't track all open fds, we simply close everything beyond
3131 * stderr.
3132 */
Balaji Raoec04b132007-12-28 14:26:24 +05303133 for (i = 3; i < FD_SETSIZE; i++)
3134 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05003135
Rusty Russell659a0e62009-06-12 22:27:10 -06003136 /* Reset all the devices (kills all threads). */
3137 cleanup_devices();
3138
Balaji Raoec04b132007-12-28 14:26:24 +05303139 execv(main_args[0], main_args);
3140 err(1, "Could not exec %s", main_args[0]);
3141}
Rusty Russell8ca47e02007-07-19 01:49:29 -07003142
Rusty Russell2e04ef72009-07-30 16:03:45 -06003143/*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 */
Rusty Russell56739c802009-06-12 22:26:59 -06003147static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07003148{
3149 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10303150 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003151 int readval;
3152
3153 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10303154 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell69a09dc2015-02-11 15:15:09 +10303155 if (readval == sizeof(notify)) {
Rusty Russell00f8d542015-02-11 15:27:01 +10303156 if (notify.trap == 13) {
Rusty Russellc565650b2015-02-11 15:15:10 +10303157 verbose("Emulating instruction at %#x\n",
3158 getreg(eip));
3159 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10303160 } else if (notify.trap == 14) {
3161 verbose("Emulating MMIO at %#x\n",
3162 getreg(eip));
3163 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10303164 } else
3165 errx(1, "Unknown trap %i addr %#08x\n",
3166 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07003167 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003168 } else if (errno == ENOENT) {
3169 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02003170 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003171 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05303172 /* ERESTART means that we need to reboot the guest */
3173 } else if (errno == ERESTART) {
3174 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06003175 /* Anything else means a bug or incompatible change. */
3176 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07003177 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07003178 }
3179}
Rusty Russella6bd8e12008-03-28 11:05:53 -05003180/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10003181 * 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.
Rusty Russelldde79782007-07-26 10:41:03 -07003184 *
Rusty Russelle1e72962007-10-25 15:02:50 +10003185 * Are you ready? Take a deep breath and join me in the core of the Host, in
3186 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06003187:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07003188
3189static struct option opts[] = {
3190 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07003191 { "tunnet", 1, NULL, 't' },
3192 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05003193 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07003194 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003195 { "username", 1, NULL, 'u' },
3196 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07003197 { NULL },
3198};
3199static void usage(void)
3200{
3201 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05003202 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07003203 "|--block=<filename>|--initrd=<filename>]...\n"
3204 "<mem-in-mb> vmlinux [args...]");
3205}
3206
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003207/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003208int main(int argc, char *argv[])
3209{
Rusty Russell2e04ef72009-07-30 16:03:45 -06003210 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03003211 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06003212 /* Two temporaries. */
3213 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003214 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003215 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07003216 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003217 const char *initrd_name = NULL;
3218
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003219 /* 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
Balaji Raoec04b132007-12-28 14:26:24 +05303225 /* Save the args: we "reboot" by execing ourselves again. */
3226 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05303227
Rusty Russell2e04ef72009-07-30 16:03:45 -06003228 /*
Rusty Russelld9028ed2015-02-11 15:21:01 +10303229 * 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).
Rusty Russell2e04ef72009-07-30 16:03:45 -06003231 */
Rusty Russell17cbca22007-10-22 11:24:22 +10003232 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003233
Rusty Russella91d74a2009-07-30 16:03:45 -06003234 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02003235 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06003236
Rusty Russell2e04ef72009-07-30 16:03:45 -06003237 /*
3238 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07003239 * 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
Rusty Russell2e04ef72009-07-30 16:03:45 -06003241 * of memory now.
3242 */
Rusty Russell6570c45992007-07-23 18:43:56 -07003243 for (i = 1; i < argc; i++) {
3244 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003245 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06003246 /*
3247 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003248 * guest-physical memory range. This fills it with 0,
3249 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06003250 * tries to access it.
3251 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003252 guest_base = map_zeroed_pages(mem / getpagesize()
3253 + DEVICE_PAGES);
3254 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10303255 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell6570c45992007-07-23 18:43:56 -07003256 break;
3257 }
3258 }
Rusty Russelldde79782007-07-26 10:41:03 -07003259
Rusty Russell713e3f72015-02-11 15:25:01 +10303260 /* We always have a console device, and it's always device 1. */
3261 setup_console();
3262
Rusty Russelldde79782007-07-26 10:41:03 -07003263 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003264 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
3265 switch (c) {
3266 case 'v':
3267 verbose = true;
3268 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003269 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10003270 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003271 break;
3272 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10003273 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003274 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05003275 case 'r':
3276 setup_rng();
3277 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003278 case 'i':
3279 initrd_name = optarg;
3280 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003281 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;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003289 default:
3290 warnx("Unknown argument %s", argv[optind]);
3291 usage();
3292 }
3293 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06003294 /*
3295 * After the other arguments we expect memory and kernel image name,
3296 * followed by command line arguments for the kernel.
3297 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003298 if (optind + 2 > argc)
3299 usage();
3300
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003301 verbose("Guest base is at %p\n", guest_base);
3302
Rusty Russell8e709462015-02-11 15:15:12 +10303303 /* Initialize the (fake) PCI host bridge device. */
3304 init_pci_host_bridge();
3305
Rusty Russell8ca47e02007-07-19 01:49:29 -07003306 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10003307 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07003308
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003309 /* Boot information is stashed at physical address 0 */
3310 boot = from_guest_phys(0);
3311
Rusty Russelldde79782007-07-26 10:41:03 -07003312 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003313 if (initrd_name) {
3314 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06003315 /*
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 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003319 boot->hdr.ramdisk_image = mem - initrd_size;
3320 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07003321 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003322 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003323 }
3324
Rusty Russell2e04ef72009-07-30 16:03:45 -06003325 /*
3326 * The Linux boot header contains an "E820" memory map: ours is a
3327 * simple, single region.
3328 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003329 boot->e820_entries = 1;
3330 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06003331 /*
3332 * The boot header contains a command line pointer: we put the command
3333 * line after the boot header.
3334 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003335 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10003336 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003337 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07003338
Rusty Russelle22a5392011-08-15 10:15:10 +09303339 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3340 boot->hdr.kernel_alignment = 0x1000000;
3341
Rusty Russell814a0e52007-10-22 11:29:44 +10003342 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003343 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10003344
3345 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003346 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10003347
Rusty Russell43d33b22007-10-22 11:29:57 +10003348 /* Tell the entry path not to try to reload segment registers. */
3349 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003350
Rusty Russell9f542882011-07-22 14:39:50 +09303351 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06003352 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07003353
Rusty Russella91d74a2009-07-30 16:03:45 -06003354 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06003355 signal(SIGCHLD, kill_launcher);
3356
3357 /* If we exit via err(), this kills all the threads, restores tty. */
3358 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003359
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003360 /* 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
Rusty Russelldde79782007-07-26 10:41:03 -07003391 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06003392 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003393}
Rusty Russellf56a3842007-07-26 10:41:05 -07003394/*:*/
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 */