blob: e3c4d3d7dc2aa47cdc25b5cd306dfbeee95344f5 [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;
129 u32 window; /* Data for BAR access. */
130};
131
132struct virtio_pci_mmio {
133 struct virtio_pci_common_cfg cfg;
134 u16 notify;
135 u8 isr;
136 u8 padding;
137 /* Device-specific configuration follows this. */
138};
139
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 Russelld7fbf6e2015-02-11 15:15:11 +1030173 /* PCI configuration */
174 union {
175 struct pci_config config;
176 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
177 };
178
Rusty Russell93153072015-02-11 15:15:11 +1030179 /* Features we offer, and those accepted. */
180 u64 features, features_accepted;
181
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030182 /* Device-specific config hangs off the end of this. */
183 struct virtio_pci_mmio *mmio;
184
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030185 /* PCI MMIO resources (all in BAR0) */
186 size_t mmio_size;
187 u32 mmio_addr;
188
Rusty Russell8ca47e02007-07-19 01:49:29 -0700189 /* Device-specific data. */
190 void *priv;
191};
192
Rusty Russell17cbca22007-10-22 11:24:22 +1000193/* The virtqueue structure describes a queue attached to a device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600194struct virtqueue {
Rusty Russell17cbca22007-10-22 11:24:22 +1000195 struct virtqueue *next;
196
197 /* Which device owns me. */
198 struct device *dev;
199
Rusty Russell17cbca22007-10-22 11:24:22 +1000200 /* The actual ring of buffers. */
201 struct vring vring;
202
Rusty Russell93153072015-02-11 15:15:11 +1030203 /* The information about this virtqueue (we only use queue_size on) */
204 struct virtio_pci_common_cfg pci_config;
205
Rusty Russell17cbca22007-10-22 11:24:22 +1000206 /* Last available index we saw. */
207 u16 last_avail_idx;
208
Rusty Russell95c517c2009-06-12 22:27:11 -0600209 /* How many are used since we sent last irq? */
210 unsigned int pending_used;
211
Rusty Russell659a0e62009-06-12 22:27:10 -0600212 /* Eventfd where Guest notifications arrive. */
213 int eventfd;
Rusty Russell20887612008-05-30 15:09:46 -0500214
Rusty Russell659a0e62009-06-12 22:27:10 -0600215 /* Function for the thread which is servicing this virtqueue. */
216 void (*service)(struct virtqueue *vq);
217 pid_t thread;
Rusty Russell17cbca22007-10-22 11:24:22 +1000218};
219
Balaji Raoec04b132007-12-28 14:26:24 +0530220/* Remember the arguments to the program so we can "reboot" */
221static char **main_args;
222
Rusty Russell659a0e62009-06-12 22:27:10 -0600223/* The original tty settings to restore on exit. */
224static struct termios orig_term;
225
Rusty Russell2e04ef72009-07-30 16:03:45 -0600226/*
227 * We have to be careful with barriers: our devices are all run in separate
Rusty Russellf7027c62009-06-12 22:27:00 -0600228 * threads and so we need to make sure that changes visible to the Guest happen
Rusty Russell2e04ef72009-07-30 16:03:45 -0600229 * in precise order.
230 */
Rusty Russellf7027c62009-06-12 22:27:00 -0600231#define wmb() __asm__ __volatile__("" : : : "memory")
Rusty Russell0d69a652013-07-02 15:35:14 +0930232#define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
233#define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
Rusty Russell17cbca22007-10-22 11:24:22 +1000234
Rusty Russellb5111792008-07-29 09:58:34 -0500235/* Wrapper for the last available index. Makes it easier to change. */
236#define lg_last_avail(vq) ((vq)->last_avail_idx)
237
Rusty Russell2e04ef72009-07-30 16:03:45 -0600238/*
239 * The virtio configuration space is defined to be little-endian. x86 is
240 * little-endian too, but it's nice to be explicit so we have these helpers.
241 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000242#define cpu_to_le16(v16) (v16)
243#define cpu_to_le32(v32) (v32)
244#define cpu_to_le64(v64) (v64)
245#define le16_to_cpu(v16) (v16)
246#define le32_to_cpu(v32) (v32)
Rusty Russella586d4f2008-02-04 23:49:56 -0500247#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000248
Rusty Russell28fd6d72008-07-29 09:58:33 -0500249/* Is this iovec empty? */
250static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
251{
252 unsigned int i;
253
254 for (i = 0; i < num_iov; i++)
255 if (iov[i].iov_len)
256 return false;
257 return true;
258}
259
260/* Take len bytes from the front of this iovec. */
Rusty Russellc0316a92012-10-16 23:56:13 +1030261static void iov_consume(struct iovec iov[], unsigned num_iov,
262 void *dest, unsigned len)
Rusty Russell28fd6d72008-07-29 09:58:33 -0500263{
264 unsigned int i;
265
266 for (i = 0; i < num_iov; i++) {
267 unsigned int used;
268
269 used = iov[i].iov_len < len ? iov[i].iov_len : len;
Rusty Russellc0316a92012-10-16 23:56:13 +1030270 if (dest) {
271 memcpy(dest, iov[i].iov_base, used);
272 dest += used;
273 }
Rusty Russell28fd6d72008-07-29 09:58:33 -0500274 iov[i].iov_base += used;
275 iov[i].iov_len -= used;
276 len -= used;
277 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030278 if (len != 0)
279 errx(1, "iovec too short!");
Rusty Russell28fd6d72008-07-29 09:58:33 -0500280}
281
Rusty Russell2e04ef72009-07-30 16:03:45 -0600282/*L:100
283 * The Launcher code itself takes us out into userspace, that scary place where
284 * pointers run wild and free! Unfortunately, like most userspace programs,
285 * it's quite boring (which is why everyone likes to hack on the kernel!).
286 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
287 * you through this section. Or, maybe not.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000288 *
289 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
290 * memory and stores it in "guest_base". In other words, Guest physical ==
291 * Launcher virtual with an offset.
292 *
293 * This can be tough to get your head around, but usually it just means that we
Francis Galieguea33f3222010-04-23 00:08:02 +0200294 * use these trivial conversion functions when the Guest gives us its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600295 * "physical" addresses:
296 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000297static void *from_guest_phys(unsigned long addr)
298{
299 return guest_base + addr;
300}
301
302static unsigned long to_guest_phys(const void *addr)
303{
304 return (addr - guest_base);
305}
306
Rusty Russelldde79782007-07-26 10:41:03 -0700307/*L:130
308 * Loading the Kernel.
309 *
310 * We start with couple of simple helper routines. open_or_die() avoids
Rusty Russell2e04ef72009-07-30 16:03:45 -0600311 * error-checking code cluttering the callers:
312 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700313static int open_or_die(const char *name, int flags)
314{
315 int fd = open(name, flags);
316 if (fd < 0)
317 err(1, "Failed to open %s", name);
318 return fd;
319}
320
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000321/* map_zeroed_pages() takes a number of pages. */
322static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700323{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000324 int fd = open_or_die("/dev/zero", O_RDONLY);
325 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700326
Rusty Russell2e04ef72009-07-30 16:03:45 -0600327 /*
328 * We use a private mapping (ie. if we write to the page, it will be
Philip Sanderson5230ff02011-01-20 21:37:28 -0600329 * copied). We allocate an extra two pages PROT_NONE to act as guard
330 * pages against read/write attempts that exceed allocated space.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600331 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600332 addr = mmap(NULL, getpagesize() * (num+2),
333 PROT_NONE, MAP_PRIVATE, fd, 0);
334
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000335 if (addr == MAP_FAILED)
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200336 err(1, "Mmapping %u pages of /dev/zero", num);
Rusty Russella91d74a2009-07-30 16:03:45 -0600337
Philip Sanderson5230ff02011-01-20 21:37:28 -0600338 if (mprotect(addr + getpagesize(), getpagesize() * num,
339 PROT_READ|PROT_WRITE) == -1)
340 err(1, "mprotect rw %u pages failed", num);
341
Rusty Russella91d74a2009-07-30 16:03:45 -0600342 /*
343 * One neat mmap feature is that you can close the fd, and it
344 * stays mapped.
345 */
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100346 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700347
Philip Sanderson5230ff02011-01-20 21:37:28 -0600348 /* Return address after PROT_NONE page */
349 return addr + getpagesize();
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000350}
351
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030352/* Get some bytes which won't be mapped into the guest. */
353static unsigned long get_mmio_region(size_t size)
354{
355 unsigned long addr = guest_mmio;
356 size_t i;
357
358 if (!size)
359 return addr;
360
361 /* Size has to be a power of 2 (and multiple of 16) */
362 for (i = 1; i < size; i <<= 1);
363
364 guest_mmio += i;
365
366 return addr;
367}
368
Rusty Russell2e04ef72009-07-30 16:03:45 -0600369/*
370 * This routine is used to load the kernel or initrd. It tries mmap, but if
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700371 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
Rusty Russell2e04ef72009-07-30 16:03:45 -0600372 * it falls back to reading the memory in.
373 */
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700374static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
375{
376 ssize_t r;
377
Rusty Russell2e04ef72009-07-30 16:03:45 -0600378 /*
379 * We map writable even though for some segments are marked read-only.
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700380 * The kernel really wants to be writable: it patches its own
381 * instructions.
382 *
383 * MAP_PRIVATE means that the page won't be copied until a write is
384 * done to it. This allows us to share untouched memory between
Rusty Russell2e04ef72009-07-30 16:03:45 -0600385 * Guests.
386 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600387 if (mmap(addr, len, PROT_READ|PROT_WRITE,
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700388 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
389 return;
390
391 /* pread does a seek and a read in one shot: saves a few lines. */
392 r = pread(fd, addr, len, offset);
393 if (r != len)
394 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
395}
396
Rusty Russell2e04ef72009-07-30 16:03:45 -0600397/*
398 * This routine takes an open vmlinux image, which is in ELF, and maps it into
Rusty Russelldde79782007-07-26 10:41:03 -0700399 * the Guest memory. ELF = Embedded Linking Format, which is the format used
400 * by all modern binaries on Linux including the kernel.
401 *
402 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000403 * address. We use the physical address; the Guest will map itself to the
404 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700405 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600406 * We return the starting address.
407 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000408static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700409{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700410 Elf32_Phdr phdr[ehdr->e_phnum];
411 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700412
Rusty Russell2e04ef72009-07-30 16:03:45 -0600413 /*
414 * Sanity checks on the main ELF header: an x86 executable with a
415 * reasonable number of correctly-sized program headers.
416 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700417 if (ehdr->e_type != ET_EXEC
418 || ehdr->e_machine != EM_386
419 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
420 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
421 errx(1, "Malformed elf header");
422
Rusty Russell2e04ef72009-07-30 16:03:45 -0600423 /*
424 * An ELF executable contains an ELF header and a number of "program"
Rusty Russelldde79782007-07-26 10:41:03 -0700425 * headers which indicate which parts ("segments") of the program to
Rusty Russell2e04ef72009-07-30 16:03:45 -0600426 * load where.
427 */
Rusty Russelldde79782007-07-26 10:41:03 -0700428
429 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700430 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
431 err(1, "Seeking to program headers");
432 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
433 err(1, "Reading program headers");
434
Rusty Russell2e04ef72009-07-30 16:03:45 -0600435 /*
436 * Try all the headers: there are usually only three. A read-only one,
437 * a read-write one, and a "note" section which we don't load.
438 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700439 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700440 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700441 if (phdr[i].p_type != PT_LOAD)
442 continue;
443
444 verbose("Section %i: size %i addr %p\n",
445 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
446
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700447 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000448 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700449 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700450 }
451
Rusty Russell814a0e52007-10-22 11:29:44 +1000452 /* The entry point is given in the ELF header. */
453 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700454}
455
Rusty Russell2e04ef72009-07-30 16:03:45 -0600456/*L:150
457 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
458 * to jump into it and it will unpack itself. We used to have to perform some
459 * hairy magic because the unpacking code scared me.
Rusty Russelldde79782007-07-26 10:41:03 -0700460 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000461 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
462 * a small patch to jump over the tricky bits in the Guest, so now we just read
Rusty Russell2e04ef72009-07-30 16:03:45 -0600463 * the funky header so we know where in the file to load, and away we go!
464 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000465static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700466{
Rusty Russell43d33b22007-10-22 11:29:57 +1000467 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000468 int r;
469 /* Modern bzImages get loaded at 1M. */
470 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700471
Rusty Russell2e04ef72009-07-30 16:03:45 -0600472 /*
473 * Go back to the start of the file and read the header. It should be
Paul Bolle395cf962011-08-15 02:02:26 +0200474 * a Linux boot header (see Documentation/x86/boot.txt)
Rusty Russell2e04ef72009-07-30 16:03:45 -0600475 */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000476 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000477 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000478
Rusty Russell43d33b22007-10-22 11:29:57 +1000479 /* Inside the setup_hdr, we expect the magic "HdrS" */
480 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000481 errx(1, "This doesn't look like a bzImage to me");
482
Rusty Russell43d33b22007-10-22 11:29:57 +1000483 /* Skip over the extra sectors of the header. */
484 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000485
486 /* Now read everything into memory. in nice big chunks. */
487 while ((r = read(fd, p, 65536)) > 0)
488 p += r;
489
Rusty Russell43d33b22007-10-22 11:29:57 +1000490 /* Finally, code32_start tells us where to enter the kernel. */
491 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700492}
493
Rusty Russell2e04ef72009-07-30 16:03:45 -0600494/*L:140
495 * Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000496 * come wrapped up in the self-decompressing "bzImage" format. With a little
Rusty Russell2e04ef72009-07-30 16:03:45 -0600497 * work, we can load those, too.
498 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000499static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700500{
501 Elf32_Ehdr hdr;
502
Rusty Russelldde79782007-07-26 10:41:03 -0700503 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700504 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
505 err(1, "Reading kernel");
506
Rusty Russelldde79782007-07-26 10:41:03 -0700507 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700508 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000509 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700510
Rusty Russella6bd8e12008-03-28 11:05:53 -0500511 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000512 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700513}
514
Rusty Russell2e04ef72009-07-30 16:03:45 -0600515/*
516 * This is a trivial little helper to align pages. Andi Kleen hated it because
Rusty Russelldde79782007-07-26 10:41:03 -0700517 * it calls getpagesize() twice: "it's dumb code."
518 *
519 * Kernel guys get really het up about optimization, even when it's not
Rusty Russell2e04ef72009-07-30 16:03:45 -0600520 * necessary. I leave this code as a reaction against that.
521 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700522static inline unsigned long page_align(unsigned long addr)
523{
Rusty Russelldde79782007-07-26 10:41:03 -0700524 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700525 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
526}
527
Rusty Russell2e04ef72009-07-30 16:03:45 -0600528/*L:180
529 * An "initial ram disk" is a disk image loaded into memory along with the
530 * kernel which the kernel can use to boot from without needing any drivers.
531 * Most distributions now use this as standard: the initrd contains the code to
532 * load the appropriate driver modules for the current machine.
Rusty Russelldde79782007-07-26 10:41:03 -0700533 *
534 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600535 * kernels. He sent me this (and tells me when I break it).
536 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700537static unsigned long load_initrd(const char *name, unsigned long mem)
538{
539 int ifd;
540 struct stat st;
541 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700542
543 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700544 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700545 if (fstat(ifd, &st) < 0)
546 err(1, "fstat() on initrd '%s'", name);
547
Rusty Russell2e04ef72009-07-30 16:03:45 -0600548 /*
549 * We map the initrd at the top of memory, but mmap wants it to be
550 * page-aligned, so we round the size up for that.
551 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700552 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000553 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600554 /*
555 * Once a file is mapped, you can close the file descriptor. It's a
556 * little odd, but quite useful.
557 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700558 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700559 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700560
561 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700562 return len;
563}
Rusty Russelle1e72962007-10-25 15:02:50 +1000564/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700565
Rusty Russell2e04ef72009-07-30 16:03:45 -0600566/*
567 * Simple routine to roll all the commandline arguments together with spaces
568 * between them.
569 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700570static void concat(char *dst, char *args[])
571{
572 unsigned int i, len = 0;
573
574 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100575 if (i) {
576 strcat(dst+len, " ");
577 len++;
578 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700579 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100580 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700581 }
582 /* In case it's empty. */
583 dst[len] = '\0';
584}
585
Rusty Russell2e04ef72009-07-30 16:03:45 -0600586/*L:185
587 * This is where we actually tell the kernel to initialize the Guest. We
Rusty Russelle1e72962007-10-25 15:02:50 +1000588 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300589 * the base of Guest "physical" memory, the top physical page to allow and the
Rusty Russell2e04ef72009-07-30 16:03:45 -0600590 * entry point for the Guest.
591 */
Rusty Russell56739c802009-06-12 22:26:59 -0600592static void tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700593{
Jes Sorensen511801d2007-10-22 11:03:31 +1000594 unsigned long args[] = { LHREQ_INITIALIZE,
595 (unsigned long)guest_base,
Rusty Russell7313d522015-02-11 15:15:10 +1030596 guest_limit / getpagesize(), start,
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030597 (guest_mmio+getpagesize()-1) / getpagesize() };
598 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
599 guest_base, guest_base + guest_limit,
600 guest_limit, guest_mmio);
Rusty Russell56739c802009-06-12 22:26:59 -0600601 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
602 if (write(lguest_fd, args, sizeof(args)) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700603 err(1, "Writing to /dev/lguest");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700604}
Rusty Russelldde79782007-07-26 10:41:03 -0700605/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700606
Rusty Russella91d74a2009-07-30 16:03:45 -0600607/*L:200
Rusty Russelldde79782007-07-26 10:41:03 -0700608 * Device Handling.
609 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000610 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700611 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000612 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700613 * if something funny is going on:
614 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700615static void *_check_pointer(unsigned long addr, unsigned int size,
616 unsigned int line)
617{
Rusty Russell2e04ef72009-07-30 16:03:45 -0600618 /*
Philip Sanderson5230ff02011-01-20 21:37:28 -0600619 * Check if the requested address and size exceeds the allocated memory,
620 * or addr + size wraps around.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600621 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600622 if ((addr + size) > guest_limit || (addr + size) < addr)
Rusty Russell17cbca22007-10-22 11:24:22 +1000623 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600624 /*
625 * We return a pointer for the caller's convenience, now we know it's
626 * safe to use.
627 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000628 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700629}
Rusty Russelldde79782007-07-26 10:41:03 -0700630/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700631#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
632
Rusty Russell2e04ef72009-07-30 16:03:45 -0600633/*
634 * Each buffer in the virtqueues is actually a chain of descriptors. This
Rusty Russelle1e72962007-10-25 15:02:50 +1000635 * function returns the next descriptor in the chain, or vq->vring.num if we're
Rusty Russell2e04ef72009-07-30 16:03:45 -0600636 * at the end.
637 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100638static unsigned next_desc(struct vring_desc *desc,
639 unsigned int i, unsigned int max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000640{
641 unsigned int next;
642
643 /* If this descriptor says it doesn't chain, we're done. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100644 if (!(desc[i].flags & VRING_DESC_F_NEXT))
645 return max;
Rusty Russell17cbca22007-10-22 11:24:22 +1000646
647 /* Check they're not leading us off end of descriptors. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100648 next = desc[i].next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000649 /* Make sure compiler knows to grab that: we don't want it changing! */
650 wmb();
651
Mark McLoughlind1f01322009-05-11 18:11:46 +0100652 if (next >= max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000653 errx(1, "Desc next is %u", next);
654
655 return next;
656}
657
Rusty Russella91d74a2009-07-30 16:03:45 -0600658/*
659 * This actually sends the interrupt for this virtqueue, if we've used a
660 * buffer.
661 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600662static void trigger_irq(struct virtqueue *vq)
663{
Rusty Russelld9028ed2015-02-11 15:21:01 +1030664 unsigned long buf[] = { LHREQ_IRQ, vq->dev->config.irq_line };
Rusty Russell38bc2b82009-06-12 22:27:11 -0600665
Rusty Russell95c517c2009-06-12 22:27:11 -0600666 /* Don't inform them if nothing used. */
667 if (!vq->pending_used)
668 return;
669 vq->pending_used = 0;
670
Rusty Russellca60a422009-09-23 22:26:47 -0600671 /* If they don't want an interrupt, don't send one... */
672 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
Rusty Russell990c91f2011-05-30 11:14:12 -0600673 return;
Rusty Russellca60a422009-09-23 22:26:47 -0600674 }
Rusty Russell38bc2b82009-06-12 22:27:11 -0600675
Rusty Russelld9028ed2015-02-11 15:21:01 +1030676 /* Set isr to 1 (queue interrupt pending) */
677 vq->dev->mmio->isr = 0x1;
Rusty Russell93153072015-02-11 15:15:11 +1030678
Rusty Russell38bc2b82009-06-12 22:27:11 -0600679 /* Send the Guest an interrupt tell them we used something up. */
680 if (write(lguest_fd, buf, sizeof(buf)) != 0)
Rusty Russelld9028ed2015-02-11 15:21:01 +1030681 err(1, "Triggering irq %i", vq->dev->config.irq_line);
Rusty Russell38bc2b82009-06-12 22:27:11 -0600682}
683
Rusty Russell2e04ef72009-07-30 16:03:45 -0600684/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600685 * This looks in the virtqueue for the first available buffer, and converts
Rusty Russell17cbca22007-10-22 11:24:22 +1000686 * it to an iovec for convenient access. Since descriptors consist of some
687 * number of output then some number of input descriptors, it's actually two
688 * iovecs, but we pack them into one and note how many of each there were.
689 *
Rusty Russella91d74a2009-07-30 16:03:45 -0600690 * This function waits if necessary, and returns the descriptor number found.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600691 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600692static unsigned wait_for_vq_desc(struct virtqueue *vq,
693 struct iovec iov[],
694 unsigned int *out_num, unsigned int *in_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000695{
Mark McLoughlind1f01322009-05-11 18:11:46 +0100696 unsigned int i, head, max;
697 struct vring_desc *desc;
Rusty Russell659a0e62009-06-12 22:27:10 -0600698 u16 last_avail = lg_last_avail(vq);
699
Rusty Russella91d74a2009-07-30 16:03:45 -0600700 /* There's nothing available? */
Rusty Russell659a0e62009-06-12 22:27:10 -0600701 while (last_avail == vq->vring.avail->idx) {
702 u64 event;
703
Rusty Russella91d74a2009-07-30 16:03:45 -0600704 /*
705 * Since we're about to sleep, now is a good time to tell the
706 * Guest about what we've used up to now.
707 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600708 trigger_irq(vq);
709
Rusty Russellb60da132009-06-12 22:27:12 -0600710 /* OK, now we need to know about added descriptors. */
711 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
712
Rusty Russell2e04ef72009-07-30 16:03:45 -0600713 /*
714 * They could have slipped one in as we were doing that: make
715 * sure it's written, then check again.
716 */
Rusty Russellb60da132009-06-12 22:27:12 -0600717 mb();
718 if (last_avail != vq->vring.avail->idx) {
719 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
720 break;
721 }
722
Rusty Russell659a0e62009-06-12 22:27:10 -0600723 /* Nothing new? Wait for eventfd to tell us they refilled. */
724 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
725 errx(1, "Event read failed?");
Rusty Russellb60da132009-06-12 22:27:12 -0600726
727 /* We don't need to be notified again. */
728 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russell659a0e62009-06-12 22:27:10 -0600729 }
Rusty Russell17cbca22007-10-22 11:24:22 +1000730
731 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500732 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000733 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500734 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000735
Rusty Russell8fd9a632013-07-02 15:35:13 +0930736 /*
737 * Make sure we read the descriptor number *after* we read the ring
738 * update; don't let the cpu or compiler change the order.
739 */
740 rmb();
741
Rusty Russell2e04ef72009-07-30 16:03:45 -0600742 /*
743 * Grab the next descriptor number they're advertising, and increment
744 * the index we've seen.
745 */
Rusty Russellb5111792008-07-29 09:58:34 -0500746 head = vq->vring.avail->ring[last_avail % vq->vring.num];
747 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000748
749 /* If their number is silly, that's a fatal mistake. */
750 if (head >= vq->vring.num)
751 errx(1, "Guest says index %u is available", head);
752
753 /* When we start there are none of either input nor output. */
754 *out_num = *in_num = 0;
755
Mark McLoughlind1f01322009-05-11 18:11:46 +0100756 max = vq->vring.num;
757 desc = vq->vring.desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000758 i = head;
Mark McLoughlind1f01322009-05-11 18:11:46 +0100759
Rusty Russell2e04ef72009-07-30 16:03:45 -0600760 /*
Rusty Russell8fd9a632013-07-02 15:35:13 +0930761 * We have to read the descriptor after we read the descriptor number,
762 * but there's a data dependency there so the CPU shouldn't reorder
763 * that: no rmb() required.
764 */
765
766 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -0600767 * If this is an indirect entry, then this buffer contains a descriptor
768 * table which we handle as if it's any normal descriptor chain.
769 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100770 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
771 if (desc[i].len % sizeof(struct vring_desc))
772 errx(1, "Invalid size for indirect buffer table");
773
774 max = desc[i].len / sizeof(struct vring_desc);
775 desc = check_pointer(desc[i].addr, desc[i].len);
776 i = 0;
777 }
778
Rusty Russell17cbca22007-10-22 11:24:22 +1000779 do {
780 /* Grab the first descriptor, and check it's OK. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100781 iov[*out_num + *in_num].iov_len = desc[i].len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000782 iov[*out_num + *in_num].iov_base
Mark McLoughlind1f01322009-05-11 18:11:46 +0100783 = check_pointer(desc[i].addr, desc[i].len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000784 /* If this is an input descriptor, increment that count. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100785 if (desc[i].flags & VRING_DESC_F_WRITE)
Rusty Russell17cbca22007-10-22 11:24:22 +1000786 (*in_num)++;
787 else {
Rusty Russell2e04ef72009-07-30 16:03:45 -0600788 /*
789 * If it's an output descriptor, they're all supposed
790 * to come before any input descriptors.
791 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000792 if (*in_num)
793 errx(1, "Descriptor has out after in");
794 (*out_num)++;
795 }
796
797 /* If we've got too many, that implies a descriptor loop. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100798 if (*out_num + *in_num > max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000799 errx(1, "Looped descriptor");
Mark McLoughlind1f01322009-05-11 18:11:46 +0100800 } while ((i = next_desc(desc, i, max)) != max);
Rusty Russell17cbca22007-10-22 11:24:22 +1000801
802 return head;
803}
804
Rusty Russell2e04ef72009-07-30 16:03:45 -0600805/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600806 * After we've used one of their buffers, we tell the Guest about it. Sometime
807 * later we'll want to send them an interrupt using trigger_irq(); note that
808 * wait_for_vq_desc() does that for us if it has to wait.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600809 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000810static void add_used(struct virtqueue *vq, unsigned int head, int len)
811{
812 struct vring_used_elem *used;
813
Rusty Russell2e04ef72009-07-30 16:03:45 -0600814 /*
815 * The virtqueue contains a ring of used buffers. Get a pointer to the
816 * next entry in that used ring.
817 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000818 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
819 used->id = head;
820 used->len = len;
821 /* Make sure buffer is written before we update index. */
822 wmb();
823 vq->vring.used->idx++;
Rusty Russell95c517c2009-06-12 22:27:11 -0600824 vq->pending_used++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000825}
826
Rusty Russell17cbca22007-10-22 11:24:22 +1000827/* And here's the combo meal deal. Supersize me! */
Rusty Russell56739c802009-06-12 22:26:59 -0600828static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
Rusty Russell17cbca22007-10-22 11:24:22 +1000829{
830 add_used(vq, head, len);
Rusty Russell56739c802009-06-12 22:26:59 -0600831 trigger_irq(vq);
Rusty Russell17cbca22007-10-22 11:24:22 +1000832}
833
Rusty Russelle1e72962007-10-25 15:02:50 +1000834/*
835 * The Console
836 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600837 * We associate some data with the console for our exit hack.
838 */
Rusty Russell1842f232009-07-30 16:03:46 -0600839struct console_abort {
Rusty Russelldde79782007-07-26 10:41:03 -0700840 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700841 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700842 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700843 struct timeval start;
844};
845
Rusty Russelldde79782007-07-26 10:41:03 -0700846/* This is the routine which handles console input (ie. stdin). */
Rusty Russell659a0e62009-06-12 22:27:10 -0600847static void console_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700848{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700849 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000850 unsigned int head, in_num, out_num;
Rusty Russell659a0e62009-06-12 22:27:10 -0600851 struct console_abort *abort = vq->dev->priv;
852 struct iovec iov[vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700853
Rusty Russella91d74a2009-07-30 16:03:45 -0600854 /* Make sure there's a descriptor available. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600855 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000856 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000857 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700858
Rusty Russella91d74a2009-07-30 16:03:45 -0600859 /* Read into it. This is where we usually wait. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600860 len = readv(STDIN_FILENO, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700861 if (len <= 0) {
Rusty Russell659a0e62009-06-12 22:27:10 -0600862 /* Ran out of input? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700863 warnx("Failed to get console input, ignoring console.");
Rusty Russell2e04ef72009-07-30 16:03:45 -0600864 /*
865 * For simplicity, dying threads kill the whole Launcher. So
866 * just nap here.
867 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600868 for (;;)
869 pause();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700870 }
871
Rusty Russella91d74a2009-07-30 16:03:45 -0600872 /* Tell the Guest we used a buffer. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600873 add_used_and_trigger(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700874
Rusty Russell2e04ef72009-07-30 16:03:45 -0600875 /*
876 * Three ^C within one second? Exit.
Rusty Russelldde79782007-07-26 10:41:03 -0700877 *
Rusty Russell659a0e62009-06-12 22:27:10 -0600878 * This is such a hack, but works surprisingly well. Each ^C has to
879 * be in a buffer by itself, so they can't be too fast. But we check
880 * that we get three within about a second, so they can't be too
Rusty Russell2e04ef72009-07-30 16:03:45 -0600881 * slow.
882 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600883 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700884 abort->count = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -0600885 return;
886 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700887
Rusty Russell659a0e62009-06-12 22:27:10 -0600888 abort->count++;
889 if (abort->count == 1)
890 gettimeofday(&abort->start, NULL);
891 else if (abort->count == 3) {
892 struct timeval now;
893 gettimeofday(&now, NULL);
894 /* Kill all Launcher processes with SIGINT, like normal ^C */
895 if (now.tv_sec <= abort->start.tv_sec+1)
896 kill(0, SIGINT);
897 abort->count = 0;
898 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700899}
900
Rusty Russell659a0e62009-06-12 22:27:10 -0600901/* This is the routine which handles console output (ie. stdout). */
902static void console_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700903{
Rusty Russell17cbca22007-10-22 11:24:22 +1000904 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000905 struct iovec iov[vq->vring.num];
906
Rusty Russella91d74a2009-07-30 16:03:45 -0600907 /* We usually wait in here, for the Guest to give us something. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600908 head = wait_for_vq_desc(vq, iov, &out, &in);
909 if (in)
910 errx(1, "Input buffers in console output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600911
912 /* writev can return a partial write, so we loop here. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600913 while (!iov_empty(iov, out)) {
914 int len = writev(STDOUT_FILENO, iov, out);
Sakari Ailuse0377e22011-06-26 19:36:46 +0300915 if (len <= 0) {
916 warn("Write to stdout gave %i (%d)", len, errno);
917 break;
918 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030919 iov_consume(iov, out, NULL, len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000920 }
Rusty Russella91d74a2009-07-30 16:03:45 -0600921
922 /*
923 * We're finished with that buffer: if we're going to sleep,
924 * wait_for_vq_desc() will prod the Guest with an interrupt.
925 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600926 add_used(vq, head, 0);
Rusty Russella1618832008-07-29 09:58:35 -0500927}
928
Rusty Russelle1e72962007-10-25 15:02:50 +1000929/*
930 * The Network
931 *
932 * Handling output for network is also simple: we get all the output buffers
Rusty Russell659a0e62009-06-12 22:27:10 -0600933 * and write them to /dev/net/tun.
Rusty Russella6bd8e12008-03-28 11:05:53 -0500934 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600935struct net_info {
936 int tunfd;
937};
938
939static void net_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700940{
Rusty Russell659a0e62009-06-12 22:27:10 -0600941 struct net_info *net_info = vq->dev->priv;
942 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000943 struct iovec iov[vq->vring.num];
944
Rusty Russella91d74a2009-07-30 16:03:45 -0600945 /* We usually wait in here for the Guest to give us a packet. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600946 head = wait_for_vq_desc(vq, iov, &out, &in);
947 if (in)
948 errx(1, "Input buffers in net output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600949 /*
950 * Send the whole thing through to /dev/net/tun. It expects the exact
951 * same format: what a coincidence!
952 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600953 if (writev(net_info->tunfd, iov, out) < 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +0300954 warnx("Write to tun failed (%d)?", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -0600955
956 /*
957 * Done with that one; wait_for_vq_desc() will send the interrupt if
958 * all packets are processed.
959 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600960 add_used(vq, head, 0);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700961}
962
Rusty Russella91d74a2009-07-30 16:03:45 -0600963/*
964 * Handling network input is a bit trickier, because I've tried to optimize it.
965 *
966 * First we have a helper routine which tells is if from this file descriptor
967 * (ie. the /dev/net/tun device) will block:
968 */
Rusty Russell4a8962e2009-06-12 22:27:12 -0600969static bool will_block(int fd)
970{
971 fd_set fdset;
972 struct timeval zero = { 0, 0 };
973 FD_ZERO(&fdset);
974 FD_SET(fd, &fdset);
975 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
976}
977
Rusty Russella91d74a2009-07-30 16:03:45 -0600978/*
979 * This handles packets coming in from the tun device to our Guest. Like all
980 * service routines, it gets called again as soon as it returns, so you don't
981 * see a while(1) loop here.
982 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600983static void net_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700984{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700985 int len;
Rusty Russell659a0e62009-06-12 22:27:10 -0600986 unsigned int head, out, in;
987 struct iovec iov[vq->vring.num];
988 struct net_info *net_info = vq->dev->priv;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700989
Rusty Russella91d74a2009-07-30 16:03:45 -0600990 /*
991 * Get a descriptor to write an incoming packet into. This will also
992 * send an interrupt if they're out of descriptors.
993 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600994 head = wait_for_vq_desc(vq, iov, &out, &in);
995 if (out)
996 errx(1, "Output buffers in net input queue?");
Rusty Russell4a8962e2009-06-12 22:27:12 -0600997
Rusty Russella91d74a2009-07-30 16:03:45 -0600998 /*
999 * If it looks like we'll block reading from the tun device, send them
1000 * an interrupt.
1001 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001002 if (vq->pending_used && will_block(net_info->tunfd))
1003 trigger_irq(vq);
1004
Rusty Russella91d74a2009-07-30 16:03:45 -06001005 /*
1006 * Read in the packet. This is where we normally wait (when there's no
1007 * incoming network traffic).
1008 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001009 len = readv(net_info->tunfd, iov, in);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001010 if (len <= 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +03001011 warn("Failed to read from tun (%d).", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -06001012
1013 /*
1014 * Mark that packet buffer as used, but don't interrupt here. We want
1015 * to wait until we've done as much work as we can.
1016 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001017 add_used(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001018}
Rusty Russella91d74a2009-07-30 16:03:45 -06001019/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001020
Rusty Russella91d74a2009-07-30 16:03:45 -06001021/* This is the helper to create threads: run the service routine in a loop. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001022static int do_thread(void *_vq)
Rusty Russell56ae43d2007-10-22 11:24:23 +10001023{
Rusty Russell659a0e62009-06-12 22:27:10 -06001024 struct virtqueue *vq = _vq;
1025
1026 for (;;)
1027 vq->service(vq);
1028 return 0;
Rusty Russell56ae43d2007-10-22 11:24:23 +10001029}
1030
Rusty Russell2e04ef72009-07-30 16:03:45 -06001031/*
1032 * When a child dies, we kill our entire process group with SIGTERM. This
1033 * also has the side effect that the shell restores the console for us!
1034 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001035static void kill_launcher(int signal)
Rusty Russell5dae7852008-07-29 09:58:35 -05001036{
Rusty Russell659a0e62009-06-12 22:27:10 -06001037 kill(0, SIGTERM);
1038}
1039
1040static void reset_device(struct device *dev)
1041{
1042 struct virtqueue *vq;
1043
1044 verbose("Resetting device %s\n", dev->name);
1045
1046 /* Clear any features they've acked. */
Rusty Russelld9028ed2015-02-11 15:21:01 +10301047 dev->features_accepted = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06001048
1049 /* We're going to be explicitly killing threads, so ignore them. */
1050 signal(SIGCHLD, SIG_IGN);
1051
Rusty Russelld9028ed2015-02-11 15:21:01 +10301052 /* Get rid of the virtqueue threads */
Rusty Russell659a0e62009-06-12 22:27:10 -06001053 for (vq = dev->vq; vq; vq = vq->next) {
1054 if (vq->thread != (pid_t)-1) {
1055 kill(vq->thread, SIGTERM);
1056 waitpid(vq->thread, NULL, 0);
1057 vq->thread = (pid_t)-1;
1058 }
Rusty Russell659a0e62009-06-12 22:27:10 -06001059 }
1060 dev->running = false;
1061
1062 /* Now we care if threads die. */
1063 signal(SIGCHLD, (void *)kill_launcher);
1064}
1065
Rusty Russell659a0e62009-06-12 22:27:10 -06001066static void cleanup_devices(void)
1067{
Rusty Russelld9028ed2015-02-11 15:21:01 +10301068 unsigned int i;
Rusty Russell659a0e62009-06-12 22:27:10 -06001069
Rusty Russelld9028ed2015-02-11 15:21:01 +10301070 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1071 struct device *d = devices.pci[i];
1072 if (!d)
1073 continue;
1074 reset_device(d);
1075 }
Rusty Russell659a0e62009-06-12 22:27:10 -06001076
1077 /* If we saved off the original terminal settings, restore them now. */
1078 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1079 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
Rusty Russell5dae7852008-07-29 09:58:35 -05001080}
1081
Rusty Russella91d74a2009-07-30 16:03:45 -06001082/*L:215
Rusty Russelld9028ed2015-02-11 15:21:01 +10301083 * This is the generic routine we call when the Guest uses LHCALL_NOTIFY.
Rusty Russella91d74a2009-07-30 16:03:45 -06001084 */
Rusty Russell56739c802009-06-12 22:26:59 -06001085static void handle_output(unsigned long addr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001086{
Rusty Russell2e04ef72009-07-30 16:03:45 -06001087 /*
1088 * Early console write is done using notify on a nul-terminated string
1089 * in Guest memory. It's also great for hacking debugging messages
1090 * into a Guest.
1091 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001092 if (addr >= guest_limit)
1093 errx(1, "Bad NOTIFY %#lx", addr);
1094
1095 write(STDOUT_FILENO, from_guest_phys(addr),
1096 strnlen(from_guest_phys(addr), guest_limit - addr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001097}
1098
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301099/*L:217
1100 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1101 * code.
1102 */
1103
Rusty Russell8e709462015-02-11 15:15:12 +10301104/* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1105static struct device pci_host_bridge;
1106
1107static void init_pci_host_bridge(void)
1108{
1109 pci_host_bridge.name = "PCI Host Bridge";
1110 pci_host_bridge.config.class = 0x06; /* bridge */
1111 pci_host_bridge.config.subclass = 0; /* host bridge */
1112 devices.pci[0] = &pci_host_bridge;
1113}
1114
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301115/* The IO ports used to read the PCI config space. */
1116#define PCI_CONFIG_ADDR 0xCF8
1117#define PCI_CONFIG_DATA 0xCFC
1118
1119/*
1120 * Not really portable, but does help readability: this is what the Guest
1121 * writes to the PCI_CONFIG_ADDR IO port.
1122 */
1123union pci_config_addr {
1124 struct {
1125 unsigned mbz: 2;
1126 unsigned offset: 6;
1127 unsigned funcnum: 3;
1128 unsigned devnum: 5;
1129 unsigned busnum: 8;
1130 unsigned reserved: 7;
1131 unsigned enabled : 1;
1132 } bits;
1133 u32 val;
1134};
1135
1136/*
1137 * We cache what they wrote to the address port, so we know what they're
1138 * talking about when they access the data port.
1139 */
1140static union pci_config_addr pci_config_addr;
1141
1142static struct device *find_pci_device(unsigned int index)
1143{
1144 return devices.pci[index];
1145}
1146
1147/* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1148static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1149{
1150 assert(off < 4);
1151 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1152 *val = (v >> (off * 8)) & mask;
1153}
1154
1155/* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1156static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1157{
1158 assert(off < 4);
1159 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1160 *dst &= ~(mask << (off * 8));
1161 *dst |= (v & mask) << (off * 8);
1162}
1163
1164/*
1165 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1166 * PCI_CONFIG_ADDR.
1167 */
1168static struct device *dev_and_reg(u32 *reg)
1169{
1170 if (!pci_config_addr.bits.enabled)
1171 return NULL;
1172
1173 if (pci_config_addr.bits.funcnum != 0)
1174 return NULL;
1175
1176 if (pci_config_addr.bits.busnum != 0)
1177 return NULL;
1178
1179 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1180 return NULL;
1181
1182 *reg = pci_config_addr.bits.offset;
1183 return find_pci_device(pci_config_addr.bits.devnum);
1184}
1185
Rusty Russell59eba782015-02-11 15:24:01 +10301186/*
1187 * We can get invalid combinations of values while they're writing, so we
1188 * only fault if they try to write with some invalid bar/offset/length.
1189 */
1190static bool valid_bar_access(struct device *d,
1191 struct virtio_pci_cfg_cap *cfg_access)
1192{
1193 /* We only have 1 bar (BAR0) */
1194 if (cfg_access->cap.bar != 0)
1195 return false;
1196
1197 /* Check it's within BAR0. */
1198 if (cfg_access->cap.offset >= d->mmio_size
1199 || cfg_access->cap.offset + cfg_access->cap.length > d->mmio_size)
1200 return false;
1201
1202 /* Check length is 1, 2 or 4. */
1203 if (cfg_access->cap.length != 1
1204 && cfg_access->cap.length != 2
1205 && cfg_access->cap.length != 4)
1206 return false;
1207
1208 /* Offset must be multiple of length */
1209 if (cfg_access->cap.offset % cfg_access->cap.length != 0)
1210 return false;
1211
1212 /* Return pointer into word in BAR0. */
1213 return true;
1214}
1215
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301216/* Is this accessing the PCI config address port?. */
1217static bool is_pci_addr_port(u16 port)
1218{
1219 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1220}
1221
1222static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1223{
1224 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1225 &pci_config_addr.val);
1226 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1227 pci_config_addr.bits.enabled ? "" : " DISABLED",
1228 val, mask,
1229 pci_config_addr.bits.busnum,
1230 pci_config_addr.bits.devnum,
1231 pci_config_addr.bits.funcnum,
1232 pci_config_addr.bits.offset);
1233 return true;
1234}
1235
1236static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1237{
1238 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1239}
1240
1241/* Is this accessing the PCI config data port?. */
1242static bool is_pci_data_port(u16 port)
1243{
1244 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1245}
1246
Rusty Russell59eba782015-02-11 15:24:01 +10301247static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask);
1248
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301249static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1250{
1251 u32 reg, portoff;
1252 struct device *d = dev_and_reg(&reg);
1253
1254 /* Complain if they don't belong to a device. */
1255 if (!d)
1256 return false;
1257
1258 /* They can do 1 byte writes, etc. */
1259 portoff = port - PCI_CONFIG_DATA;
1260
1261 /*
1262 * PCI uses a weird way to determine the BAR size: the OS
1263 * writes all 1's, and sees which ones stick.
1264 */
1265 if (&d->config_words[reg] == &d->config.bar[0]) {
1266 int i;
1267
1268 iowrite(portoff, val, mask, &d->config.bar[0]);
1269 for (i = 0; (1 << i) < d->mmio_size; i++)
1270 d->config.bar[0] &= ~(1 << i);
1271 return true;
1272 } else if ((&d->config_words[reg] > &d->config.bar[0]
1273 && &d->config_words[reg] <= &d->config.bar[6])
1274 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1275 /* Allow writing to any other BAR, or expansion ROM */
1276 iowrite(portoff, val, mask, &d->config_words[reg]);
1277 return true;
1278 /* We let them overide latency timer and cacheline size */
1279 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1280 /* Only let them change the first two fields. */
1281 if (mask == 0xFFFFFFFF)
1282 mask = 0xFFFF;
1283 iowrite(portoff, val, mask, &d->config_words[reg]);
1284 return true;
1285 } else if (&d->config_words[reg] == (void *)&d->config.command
1286 && mask == 0xFFFF) {
1287 /* Ignore command writes. */
1288 return true;
Rusty Russell59eba782015-02-11 15:24:01 +10301289 } else if (&d->config_words[reg]
1290 == (void *)&d->config.cfg_access.cap.bar
1291 || &d->config_words[reg]
1292 == &d->config.cfg_access.cap.length
1293 || &d->config_words[reg]
1294 == &d->config.cfg_access.cap.offset) {
1295
1296 /*
1297 * The VIRTIO_PCI_CAP_PCI_CFG capability
1298 * provides a backdoor to access the MMIO
1299 * regions without mapping them. Weird, but
1300 * useful.
1301 */
1302 iowrite(portoff, val, mask, &d->config_words[reg]);
1303 return true;
1304 } else if (&d->config_words[reg] == &d->config.cfg_access.window) {
1305 u32 write_mask;
1306
1307 /* Must be bar 0 */
1308 if (!valid_bar_access(d, &d->config.cfg_access))
1309 return false;
1310
1311 /* First copy what they wrote into the window */
1312 iowrite(portoff, val, mask, &d->config.cfg_access.window);
1313
1314 /*
1315 * Now emulate a write. The mask we use is set by
1316 * len, *not* this write!
1317 */
1318 write_mask = (1ULL<<(8*d->config.cfg_access.cap.length)) - 1;
1319 verbose("Window writing %#x/%#x to bar %u, offset %u len %u\n",
1320 d->config.cfg_access.window, write_mask,
1321 d->config.cfg_access.cap.bar,
1322 d->config.cfg_access.cap.offset,
1323 d->config.cfg_access.cap.length);
1324
1325 emulate_mmio_write(d, d->config.cfg_access.cap.offset,
1326 d->config.cfg_access.window, write_mask);
1327 return true;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301328 }
1329
1330 /* Complain about other writes. */
1331 return false;
1332}
1333
Rusty Russell59eba782015-02-11 15:24:01 +10301334static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask);
1335
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301336static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1337{
1338 u32 reg;
1339 struct device *d = dev_and_reg(&reg);
1340
1341 if (!d)
1342 return;
Rusty Russell59eba782015-02-11 15:24:01 +10301343
1344 /* Read through the PCI MMIO access window is special */
1345 if (&d->config_words[reg] == &d->config.cfg_access.window) {
1346 u32 read_mask;
1347
1348 /* Must be bar 0 */
1349 if (!valid_bar_access(d, &d->config.cfg_access))
1350 errx(1, "Invalid cfg_access to bar%u, offset %u len %u",
1351 d->config.cfg_access.cap.bar,
1352 d->config.cfg_access.cap.offset,
1353 d->config.cfg_access.cap.length);
1354
1355 /*
1356 * Read into the window. The mask we use is set by
1357 * len, *not* this read!
1358 */
1359 read_mask = (1ULL<<(8*d->config.cfg_access.cap.length))-1;
1360 d->config.cfg_access.window
1361 = emulate_mmio_read(d,
1362 d->config.cfg_access.cap.offset,
1363 read_mask);
1364 verbose("Window read %#x/%#x from bar %u, offset %u len %u\n",
1365 d->config.cfg_access.window, read_mask,
1366 d->config.cfg_access.cap.bar,
1367 d->config.cfg_access.cap.offset,
1368 d->config.cfg_access.cap.length);
1369 }
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301370 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1371}
1372
Rusty Russellc565650b2015-02-11 15:15:10 +10301373/*L:216
1374 * This is where we emulate a handful of Guest instructions. It's ugly
1375 * and we used to do it in the kernel but it grew over time.
1376 */
1377
1378/*
1379 * We use the ptrace syscall's pt_regs struct to talk about registers
1380 * to lguest: these macros convert the names to the offsets.
1381 */
1382#define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1383#define setreg(name, val) \
1384 setreg_off(offsetof(struct user_regs_struct, name), (val))
1385
1386static u32 getreg_off(size_t offset)
1387{
1388 u32 r;
1389 unsigned long args[] = { LHREQ_GETREG, offset };
1390
1391 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1392 err(1, "Getting register %u", offset);
1393 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1394 err(1, "Reading register %u", offset);
1395
1396 return r;
1397}
1398
1399static void setreg_off(size_t offset, u32 val)
1400{
1401 unsigned long args[] = { LHREQ_SETREG, offset, val };
1402
1403 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1404 err(1, "Setting register %u", offset);
1405}
1406
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301407/* Get register by instruction encoding */
1408static u32 getreg_num(unsigned regnum, u32 mask)
1409{
1410 /* 8 bit ops use regnums 4-7 for high parts of word */
1411 if (mask == 0xFF && (regnum & 0x4))
1412 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1413
1414 switch (regnum) {
1415 case 0: return getreg(eax) & mask;
1416 case 1: return getreg(ecx) & mask;
1417 case 2: return getreg(edx) & mask;
1418 case 3: return getreg(ebx) & mask;
1419 case 4: return getreg(esp) & mask;
1420 case 5: return getreg(ebp) & mask;
1421 case 6: return getreg(esi) & mask;
1422 case 7: return getreg(edi) & mask;
1423 }
1424 abort();
1425}
1426
1427/* Set register by instruction encoding */
1428static void setreg_num(unsigned regnum, u32 val, u32 mask)
1429{
1430 /* Don't try to set bits out of range */
1431 assert(~(val & ~mask));
1432
1433 /* 8 bit ops use regnums 4-7 for high parts of word */
1434 if (mask == 0xFF && (regnum & 0x4)) {
1435 /* Construct the 16 bits we want. */
1436 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1437 setreg_num(regnum & 0x3, val, 0xFFFF);
1438 return;
1439 }
1440
1441 switch (regnum) {
1442 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1443 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1444 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1445 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1446 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1447 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1448 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1449 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1450 }
1451 abort();
1452}
1453
1454/* Get bytes of displacement appended to instruction, from r/m encoding */
1455static u32 insn_displacement_len(u8 mod_reg_rm)
1456{
1457 /* Switch on the mod bits */
1458 switch (mod_reg_rm >> 6) {
1459 case 0:
1460 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1461 if ((mod_reg_rm & 0x7) == 0x5)
1462 return 2;
1463 /* Normally, mod == 0 means no literal displacement */
1464 return 0;
1465 case 1:
1466 /* One byte displacement */
1467 return 1;
1468 case 2:
1469 /* Four byte displacement */
1470 return 4;
1471 case 3:
1472 /* Register mode */
1473 return 0;
1474 }
1475 abort();
1476}
1477
Rusty Russellc565650b2015-02-11 15:15:10 +10301478static void emulate_insn(const u8 insn[])
1479{
1480 unsigned long args[] = { LHREQ_TRAP, 13 };
1481 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1482 unsigned int eax, port, mask;
1483 /*
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301484 * Default is to return all-ones on IO port reads, which traditionally
Rusty Russellc565650b2015-02-11 15:15:10 +10301485 * means "there's nothing there".
1486 */
1487 u32 val = 0xFFFFFFFF;
1488
1489 /*
1490 * This must be the Guest kernel trying to do something, not userspace!
1491 * The bottom two bits of the CS segment register are the privilege
1492 * level.
1493 */
1494 if ((getreg(xcs) & 3) != 0x1)
1495 goto no_emulate;
1496
1497 /* Decoding x86 instructions is icky. */
1498
1499 /*
1500 * Around 2.6.33, the kernel started using an emulation for the
1501 * cmpxchg8b instruction in early boot on many configurations. This
1502 * code isn't paravirtualized, and it tries to disable interrupts.
1503 * Ignore it, which will Mostly Work.
1504 */
1505 if (insn[insnlen] == 0xfa) {
1506 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1507 insnlen = 1;
1508 goto skip_insn;
1509 }
1510
1511 /*
1512 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1513 */
1514 if (insn[insnlen] == 0x66) {
1515 small_operand = 1;
1516 /* The instruction is 1 byte so far, read the next byte. */
1517 insnlen = 1;
1518 }
1519
1520 /* If the lower bit isn't set, it's a single byte access */
1521 byte_access = !(insn[insnlen] & 1);
1522
1523 /*
1524 * Now we can ignore the lower bit and decode the 4 opcodes
1525 * we need to emulate.
1526 */
1527 switch (insn[insnlen] & 0xFE) {
1528 case 0xE4: /* in <next byte>,%al */
1529 port = insn[insnlen+1];
1530 insnlen += 2;
1531 in = 1;
1532 break;
1533 case 0xEC: /* in (%dx),%al */
1534 port = getreg(edx) & 0xFFFF;
1535 insnlen += 1;
1536 in = 1;
1537 break;
1538 case 0xE6: /* out %al,<next byte> */
1539 port = insn[insnlen+1];
1540 insnlen += 2;
1541 break;
1542 case 0xEE: /* out %al,(%dx) */
1543 port = getreg(edx) & 0xFFFF;
1544 insnlen += 1;
1545 break;
1546 default:
1547 /* OK, we don't know what this is, can't emulate. */
1548 goto no_emulate;
1549 }
1550
1551 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1552 if (byte_access)
1553 mask = 0xFF;
1554 else if (small_operand)
1555 mask = 0xFFFF;
1556 else
1557 mask = 0xFFFFFFFF;
1558
1559 /*
1560 * If it was an "IN" instruction, they expect the result to be read
1561 * into %eax, so we change %eax.
1562 */
1563 eax = getreg(eax);
1564
1565 if (in) {
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301566 /* This is the PS/2 keyboard status; 1 means ready for output */
1567 if (port == 0x64)
1568 val = 1;
1569 else if (is_pci_addr_port(port))
1570 pci_addr_ioread(port, mask, &val);
1571 else if (is_pci_data_port(port))
1572 pci_data_ioread(port, mask, &val);
1573
Rusty Russellc565650b2015-02-11 15:15:10 +10301574 /* Clear the bits we're about to read */
1575 eax &= ~mask;
1576 /* Copy bits in from val. */
1577 eax |= val & mask;
1578 /* Now update the register. */
1579 setreg(eax, eax);
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301580 } else {
1581 if (is_pci_addr_port(port)) {
1582 if (!pci_addr_iowrite(port, mask, eax))
1583 goto bad_io;
1584 } else if (is_pci_data_port(port)) {
1585 if (!pci_data_iowrite(port, mask, eax))
1586 goto bad_io;
1587 }
1588 /* There are many other ports, eg. CMOS clock, serial
1589 * and parallel ports, so we ignore them all. */
Rusty Russellc565650b2015-02-11 15:15:10 +10301590 }
1591
1592 verbose("IO %s of %x to %u: %#08x\n",
1593 in ? "IN" : "OUT", mask, port, eax);
1594skip_insn:
1595 /* Finally, we've "done" the instruction, so move past it. */
1596 setreg(eip, getreg(eip) + insnlen);
1597 return;
1598
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301599bad_io:
1600 warnx("Attempt to %s port %u (%#x mask)",
1601 in ? "read from" : "write to", port, mask);
1602
Rusty Russellc565650b2015-02-11 15:15:10 +10301603no_emulate:
1604 /* Inject trap into Guest. */
1605 if (write(lguest_fd, args, sizeof(args)) < 0)
1606 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1607}
1608
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301609static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1610{
1611 unsigned int i;
1612
1613 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1614 struct device *d = devices.pci[i];
1615
1616 if (!d)
1617 continue;
1618 if (paddr < d->mmio_addr)
1619 continue;
1620 if (paddr >= d->mmio_addr + d->mmio_size)
1621 continue;
1622 *off = paddr - d->mmio_addr;
1623 return d;
1624 }
1625 return NULL;
1626}
1627
Rusty Russell93153072015-02-11 15:15:11 +10301628/* FIXME: Use vq array. */
1629static struct virtqueue *vq_by_num(struct device *d, u32 num)
1630{
1631 struct virtqueue *vq = d->vq;
1632
1633 while (num-- && vq)
1634 vq = vq->next;
1635
1636 return vq;
1637}
1638
1639static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1640 struct virtqueue *vq)
1641{
1642 vq->pci_config = *cfg;
1643}
1644
1645static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1646 struct virtqueue *vq)
1647{
1648 /* Only restore the per-vq part */
1649 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1650
1651 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1652 sizeof(*cfg) - off);
1653}
1654
1655/*
1656 * When they enable the virtqueue, we check that their setup is valid.
1657 */
1658static void enable_virtqueue(struct device *d, struct virtqueue *vq)
1659{
1660 /*
1661 * Create stack for thread. Since the stack grows upwards, we point
1662 * the stack pointer to the end of this region.
1663 */
1664 char *stack = malloc(32768);
1665
1666 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1667 if (vq->pci_config.queue_desc_hi
1668 || vq->pci_config.queue_avail_hi
1669 || vq->pci_config.queue_used_hi)
1670 errx(1, "%s: invalid 64-bit queue address", d->name);
1671
1672 /* Initialize the virtqueue and check they're all in range. */
1673 vq->vring.num = vq->pci_config.queue_size;
1674 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1675 sizeof(*vq->vring.desc) * vq->vring.num);
1676 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1677 sizeof(*vq->vring.avail)
1678 + (sizeof(vq->vring.avail->ring[0])
1679 * vq->vring.num));
1680 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1681 sizeof(*vq->vring.used)
1682 + (sizeof(vq->vring.used->ring[0])
1683 * vq->vring.num));
1684
1685
1686 /* Create a zero-initialized eventfd. */
1687 vq->eventfd = eventfd(0, 0);
1688 if (vq->eventfd < 0)
1689 err(1, "Creating eventfd");
1690
1691 /*
1692 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1693 * we get a signal if it dies.
1694 */
1695 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1696 if (vq->thread == (pid_t)-1)
1697 err(1, "Creating clone");
1698}
1699
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301700static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1701{
Rusty Russell93153072015-02-11 15:15:11 +10301702 struct virtqueue *vq;
1703
1704 switch (off) {
1705 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1706 if (val == 0)
1707 d->mmio->cfg.device_feature = d->features;
1708 else if (val == 1)
1709 d->mmio->cfg.device_feature = (d->features >> 32);
1710 else
1711 d->mmio->cfg.device_feature = 0;
1712 goto write_through32;
1713 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1714 if (val > 1)
1715 errx(1, "%s: Unexpected driver select %u",
1716 d->name, val);
1717 goto write_through32;
1718 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1719 if (d->mmio->cfg.guest_feature_select == 0) {
1720 d->features_accepted &= ~((u64)0xFFFFFFFF);
1721 d->features_accepted |= val;
1722 } else {
1723 assert(d->mmio->cfg.guest_feature_select == 1);
1724 d->features_accepted &= ((u64)0xFFFFFFFF << 32);
1725 d->features_accepted |= ((u64)val) << 32;
1726 }
1727 if (d->features_accepted & ~d->features)
1728 errx(1, "%s: over-accepted features %#llx of %#llx",
1729 d->name, d->features_accepted, d->features);
1730 goto write_through32;
1731 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1732 verbose("%s: device status -> %#x\n", d->name, val);
1733 if (val == 0)
Rusty Russelld9028ed2015-02-11 15:21:01 +10301734 reset_device(d);
Rusty Russell93153072015-02-11 15:15:11 +10301735 goto write_through8;
1736 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1737 vq = vq_by_num(d, val);
1738 /* Out of range? Return size 0 */
1739 if (!vq) {
1740 d->mmio->cfg.queue_size = 0;
1741 goto write_through16;
1742 }
1743 /* Save registers for old vq, if it was a valid vq */
1744 if (d->mmio->cfg.queue_size)
1745 save_vq_config(&d->mmio->cfg,
1746 vq_by_num(d, d->mmio->cfg.queue_select));
1747 /* Restore the registers for the queue they asked for */
1748 restore_vq_config(&d->mmio->cfg, vq);
1749 goto write_through16;
1750 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
1751 if (val & (val-1))
1752 errx(1, "%s: invalid queue size %u\n", d->name, val);
1753 if (d->mmio->cfg.queue_enable)
1754 errx(1, "%s: changing queue size on live device",
1755 d->name);
1756 goto write_through16;
1757 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
1758 errx(1, "%s: attempt to set MSIX vector to %u",
1759 d->name, val);
1760 case offsetof(struct virtio_pci_mmio, cfg.queue_enable):
1761 if (val != 1)
1762 errx(1, "%s: setting queue_enable to %u", d->name, val);
1763 d->mmio->cfg.queue_enable = val;
1764 save_vq_config(&d->mmio->cfg,
1765 vq_by_num(d, d->mmio->cfg.queue_select));
1766 enable_virtqueue(d, vq_by_num(d, d->mmio->cfg.queue_select));
1767 goto write_through16;
1768 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
1769 errx(1, "%s: attempt to write to queue_notify_off", d->name);
1770 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
1771 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
1772 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
1773 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
1774 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
1775 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
1776 if (d->mmio->cfg.queue_enable)
1777 errx(1, "%s: changing queue on live device",
1778 d->name);
1779 goto write_through32;
1780 case offsetof(struct virtio_pci_mmio, notify):
1781 vq = vq_by_num(d, val);
1782 if (!vq)
1783 errx(1, "Invalid vq notification on %u", val);
1784 /* Notify the process handling this vq by adding 1 to eventfd */
1785 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
1786 goto write_through16;
1787 case offsetof(struct virtio_pci_mmio, isr):
1788 errx(1, "%s: Unexpected write to isr", d->name);
Rusty Russelle8330d92015-02-11 15:23:01 +10301789 /* Weird corner case: write to emerg_wr of console */
1790 case sizeof(struct virtio_pci_mmio)
1791 + offsetof(struct virtio_console_config, emerg_wr):
1792 if (strcmp(d->name, "console") == 0) {
1793 char c = val;
1794 write(STDOUT_FILENO, &c, 1);
1795 goto write_through32;
1796 }
1797 /* Fall through... */
Rusty Russell93153072015-02-11 15:15:11 +10301798 default:
1799 errx(1, "%s: Unexpected write to offset %u", d->name, off);
1800 }
1801
1802write_through32:
1803 if (mask != 0xFFFFFFFF) {
1804 errx(1, "%s: non-32-bit write to offset %u (%#x)",
1805 d->name, off, getreg(eip));
1806 return;
1807 }
1808 memcpy((char *)d->mmio + off, &val, 4);
1809 return;
1810
1811write_through16:
1812 if (mask != 0xFFFF)
1813 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
1814 d->name, mask, off, getreg(eip));
1815 memcpy((char *)d->mmio + off, &val, 2);
1816 return;
1817
1818write_through8:
1819 if (mask != 0xFF)
1820 errx(1, "%s: non-8-bit write to offset %u (%#x)",
1821 d->name, off, getreg(eip));
1822 memcpy((char *)d->mmio + off, &val, 1);
1823 return;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301824}
1825
1826static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
1827{
Rusty Russell93153072015-02-11 15:15:11 +10301828 u8 isr;
1829 u32 val = 0;
1830
1831 switch (off) {
1832 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1833 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
1834 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1835 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1836 goto read_through32;
1837 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
1838 errx(1, "%s: read of msix_config", d->name);
1839 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
1840 goto read_through16;
1841 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1842 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
1843 goto read_through8;
1844 case offsetof(struct virtio_pci_mmio, notify):
1845 goto read_through16;
1846 case offsetof(struct virtio_pci_mmio, isr):
1847 if (mask != 0xFF)
1848 errx(1, "%s: non-8-bit read from offset %u (%#x)",
1849 d->name, off, getreg(eip));
1850 /* Read resets the isr */
1851 isr = d->mmio->isr;
1852 d->mmio->isr = 0;
1853 return isr;
1854 case offsetof(struct virtio_pci_mmio, padding):
1855 errx(1, "%s: read from padding (%#x)",
1856 d->name, getreg(eip));
1857 default:
1858 /* Read from device config space, beware unaligned overflow */
1859 if (off > d->mmio_size - 4)
1860 errx(1, "%s: read past end (%#x)",
1861 d->name, getreg(eip));
1862 if (mask == 0xFFFFFFFF)
1863 goto read_through32;
1864 else if (mask == 0xFFFF)
1865 goto read_through16;
1866 else
1867 goto read_through8;
1868 }
1869
1870read_through32:
1871 if (mask != 0xFFFFFFFF)
1872 errx(1, "%s: non-32-bit read to offset %u (%#x)",
1873 d->name, off, getreg(eip));
1874 memcpy(&val, (char *)d->mmio + off, 4);
1875 return val;
1876
1877read_through16:
1878 if (mask != 0xFFFF)
1879 errx(1, "%s: non-16-bit read to offset %u (%#x)",
1880 d->name, off, getreg(eip));
1881 memcpy(&val, (char *)d->mmio + off, 2);
1882 return val;
1883
1884read_through8:
1885 if (mask != 0xFF)
1886 errx(1, "%s: non-8-bit read to offset %u (%#x)",
1887 d->name, off, getreg(eip));
1888 memcpy(&val, (char *)d->mmio + off, 1);
1889 return val;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301890}
1891
1892static void emulate_mmio(unsigned long paddr, const u8 *insn)
1893{
1894 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
1895 struct device *d = find_mmio_region(paddr, &off);
1896 unsigned long args[] = { LHREQ_TRAP, 14 };
1897
1898 if (!d) {
1899 warnx("MMIO touching %#08lx (not a device)", paddr);
1900 goto reinject;
1901 }
1902
1903 /* Prefix makes it a 16 bit op */
1904 if (insn[0] == 0x66) {
1905 mask = 0xFFFF;
1906 insnlen++;
1907 }
1908
1909 /* iowrite */
1910 if (insn[insnlen] == 0x89) {
1911 /* Next byte is r/m byte: bits 3-5 are register. */
1912 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
1913 emulate_mmio_write(d, off, val, mask);
1914 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1915 } else if (insn[insnlen] == 0x8b) { /* ioread */
1916 /* Next byte is r/m byte: bits 3-5 are register. */
1917 val = emulate_mmio_read(d, off, mask);
1918 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
1919 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1920 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
1921 mask = 0xff;
1922 /* Next byte is r/m byte: bits 3-5 are register. */
1923 val = getreg_num((insn[1] >> 3) & 0x7, mask);
1924 emulate_mmio_write(d, off, val, mask);
1925 insnlen = 2 + insn_displacement_len(insn[1]);
1926 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
1927 mask = 0xff;
1928 val = emulate_mmio_read(d, off, mask);
1929 setreg_num((insn[1] >> 3) & 0x7, val, mask);
1930 insnlen = 2 + insn_displacement_len(insn[1]);
1931 } else {
1932 warnx("Unknown MMIO instruction touching %#08lx:"
1933 " %02x %02x %02x %02x at %u",
1934 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
1935 reinject:
1936 /* Inject trap into Guest. */
1937 if (write(lguest_fd, args, sizeof(args)) < 0)
1938 err(1, "Reinjecting trap 14 for fault at %#x",
1939 getreg(eip));
1940 return;
1941 }
1942
1943 /* Finally, we've "done" the instruction, so move past it. */
1944 setreg(eip, getreg(eip) + insnlen);
1945}
Rusty Russellc565650b2015-02-11 15:15:10 +10301946
Rusty Russelldde79782007-07-26 10:41:03 -07001947/*L:190
1948 * Device Setup
1949 *
1950 * All devices need a descriptor so the Guest knows it exists, and a "struct
1951 * device" so the Launcher can keep track of it. We have common helper
Rusty Russella6bd8e12008-03-28 11:05:53 -05001952 * routines to allocate and manage them.
1953 */
Rusty Russell93153072015-02-11 15:15:11 +10301954static void add_pci_virtqueue(struct device *dev,
1955 void (*service)(struct virtqueue *))
1956{
1957 struct virtqueue **i, *vq = malloc(sizeof(*vq));
1958
1959 /* Initialize the virtqueue */
1960 vq->next = NULL;
1961 vq->last_avail_idx = 0;
1962 vq->dev = dev;
1963
1964 /*
1965 * This is the routine the service thread will run, and its Process ID
1966 * once it's running.
1967 */
1968 vq->service = service;
1969 vq->thread = (pid_t)-1;
1970
1971 /* Initialize the configuration. */
1972 vq->pci_config.queue_size = VIRTQUEUE_NUM;
1973 vq->pci_config.queue_enable = 0;
1974 vq->pci_config.queue_notify_off = 0;
1975
1976 /* Add one to the number of queues */
1977 vq->dev->mmio->cfg.num_queues++;
1978
Rusty Russell93153072015-02-11 15:15:11 +10301979 /*
1980 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
1981 * second.
1982 */
1983 for (i = &dev->vq; *i; i = &(*i)->next);
1984 *i = vq;
1985}
1986
Rusty Russelld9028ed2015-02-11 15:21:01 +10301987/* The Guest accesses the feature bits via the PCI common config MMIO region */
Rusty Russell93153072015-02-11 15:15:11 +10301988static void add_pci_feature(struct device *dev, unsigned bit)
1989{
1990 dev->features |= (1ULL << bit);
1991}
1992
Rusty Russell93153072015-02-11 15:15:11 +10301993/* For devices with no config. */
1994static void no_device_config(struct device *dev)
1995{
1996 dev->mmio_addr = get_mmio_region(dev->mmio_size);
1997
1998 dev->config.bar[0] = dev->mmio_addr;
1999 /* Bottom 4 bits must be zero */
2000 assert(~(dev->config.bar[0] & 0xF));
2001}
2002
2003/* This puts the device config into BAR0 */
2004static void set_device_config(struct device *dev, const void *conf, size_t len)
2005{
2006 /* Set up BAR 0 */
2007 dev->mmio_size += len;
2008 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2009 memcpy(dev->mmio + 1, conf, len);
2010
2011 /* Hook up device cfg */
2012 dev->config.cfg_access.cap.cap_next
2013 = offsetof(struct pci_config, device);
2014
2015 /* Fix up device cfg field length. */
2016 dev->config.device.length = len;
2017
2018 /* The rest is the same as the no-config case */
2019 no_device_config(dev);
2020}
2021
2022static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2023 size_t bar_offset, size_t bar_bytes, u8 next)
2024{
2025 cap->cap_vndr = PCI_CAP_ID_VNDR;
2026 cap->cap_next = next;
2027 cap->cap_len = caplen;
2028 cap->cfg_type = type;
2029 cap->bar = 0;
2030 memset(cap->padding, 0, sizeof(cap->padding));
2031 cap->offset = bar_offset;
2032 cap->length = bar_bytes;
2033}
2034
2035/*
2036 * This sets up the pci_config structure, as defined in the virtio 1.0
2037 * standard (and PCI standard).
2038 */
2039static void init_pci_config(struct pci_config *pci, u16 type,
2040 u8 class, u8 subclass)
2041{
2042 size_t bar_offset, bar_len;
2043
2044 /* Save typing: most thing are happy being zero. */
2045 memset(pci, 0, sizeof(*pci));
2046
2047 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2048 pci->vendor_id = 0x1AF4;
2049 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2050 pci->device_id = 0x1040 + type;
2051
2052 /*
2053 * PCI have specific codes for different types of devices.
2054 * Linux doesn't care, but it's a good clue for people looking
2055 * at the device.
Rusty Russell93153072015-02-11 15:15:11 +10302056 */
2057 pci->class = class;
2058 pci->subclass = subclass;
2059
2060 /*
2061 * 4.1.2.1 Non-transitional devices SHOULD have a PCI Revision
2062 * ID of 1 or higher
2063 */
2064 pci->revid = 1;
2065
2066 /*
2067 * 4.1.2.1 Non-transitional devices SHOULD have a PCI
2068 * Subsystem Device ID of 0x40 or higher.
2069 */
2070 pci->subsystem_device_id = 0x40;
2071
2072 /* We use our dummy interrupt controller, and irq_line is the irq */
2073 pci->irq_line = devices.next_irq++;
2074 pci->irq_pin = 0;
2075
2076 /* Support for extended capabilities. */
2077 pci->status = (1 << 4);
2078
2079 /* Link them in. */
2080 pci->capabilities = offsetof(struct pci_config, common);
2081
2082 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2083 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2084 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2085 bar_offset, bar_len,
2086 offsetof(struct pci_config, notify));
2087
2088 bar_offset += bar_len;
2089 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2090 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2091 init_cap(&pci->notify.cap, sizeof(pci->notify),
2092 VIRTIO_PCI_CAP_NOTIFY_CFG,
2093 bar_offset, bar_len,
2094 offsetof(struct pci_config, isr));
2095
2096 bar_offset += bar_len;
2097 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2098 init_cap(&pci->isr, sizeof(pci->isr),
2099 VIRTIO_PCI_CAP_ISR_CFG,
2100 bar_offset, bar_len,
2101 offsetof(struct pci_config, cfg_access));
2102
2103 /* This doesn't have any presence in the BAR */
2104 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2105 VIRTIO_PCI_CAP_PCI_CFG,
2106 0, 0, 0);
2107
2108 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2109 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2110
2111 /*
2112 * This gets sewn in and length set in set_device_config().
2113 * Some devices don't have a device configuration interface, so
2114 * we never expose this if we don't call set_device_config().
2115 */
2116 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2117 bar_offset, 0, 0);
2118}
2119
Rusty Russell2e04ef72009-07-30 16:03:45 -06002120/*
Rusty Russelld9028ed2015-02-11 15:21:01 +10302121 * This routine does all the creation and setup of a new device, but we don't
2122 * actually place the MMIO region until we know the size (if any) of the
2123 * device-specific config. And we don't actually start the service threads
2124 * until later.
Rusty Russella6bd8e12008-03-28 11:05:53 -05002125 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002126 * See what I mean about userspace being boring?
2127 */
Rusty Russell93153072015-02-11 15:15:11 +10302128static struct device *new_pci_device(const char *name, u16 type,
2129 u8 class, u8 subclass)
2130{
2131 struct device *dev = malloc(sizeof(*dev));
2132
2133 /* Now we populate the fields one at a time. */
Rusty Russell93153072015-02-11 15:15:11 +10302134 dev->name = name;
2135 dev->vq = NULL;
Rusty Russell93153072015-02-11 15:15:11 +10302136 dev->running = false;
Rusty Russell93153072015-02-11 15:15:11 +10302137 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2138 dev->mmio = calloc(1, dev->mmio_size);
2139 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2140 dev->features_accepted = 0;
2141
Rusty Russelld9028ed2015-02-11 15:21:01 +10302142 if (devices.device_num + 1 >= MAX_PCI_DEVICES)
Rusty Russell93153072015-02-11 15:15:11 +10302143 errx(1, "Can only handle 31 PCI devices");
2144
2145 init_pci_config(&dev->config, type, class, subclass);
2146 assert(!devices.pci[devices.device_num+1]);
2147 devices.pci[++devices.device_num] = dev;
2148
2149 return dev;
2150}
2151
Rusty Russell2e04ef72009-07-30 16:03:45 -06002152/*
2153 * Our first setup routine is the console. It's a fairly simple device, but
2154 * UNIX tty handling makes it uglier than it could be.
2155 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002156static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002157{
2158 struct device *dev;
Rusty Russelle8330d92015-02-11 15:23:01 +10302159 struct virtio_console_config conf;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002160
Rusty Russelldde79782007-07-26 10:41:03 -07002161 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002162 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2163 struct termios term = orig_term;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002164 /*
2165 * Then we turn off echo, line buffering and ^C etc: We want a
2166 * raw input stream to the Guest.
2167 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002168 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2169 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002170 }
2171
Rusty Russellebff0112015-02-11 15:18:01 +10302172 dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002173
Rusty Russelldde79782007-07-26 10:41:03 -07002174 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002175 dev->priv = malloc(sizeof(struct console_abort));
2176 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002177
Rusty Russell2e04ef72009-07-30 16:03:45 -06002178 /*
2179 * The console needs two virtqueues: the input then the output. When
Rusty Russell56ae43d2007-10-22 11:24:23 +10002180 * they put something the input queue, we make sure we're listening to
2181 * stdin. When they put something in the output queue, we write it to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002182 * stdout.
2183 */
Rusty Russellebff0112015-02-11 15:18:01 +10302184 add_pci_virtqueue(dev, console_input);
2185 add_pci_virtqueue(dev, console_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002186
Rusty Russelle8330d92015-02-11 15:23:01 +10302187 /* We need a configuration area for the emerg_wr early writes. */
2188 add_pci_feature(dev, VIRTIO_CONSOLE_F_EMERG_WRITE);
2189 set_device_config(dev, &conf, sizeof(conf));
Rusty Russellebff0112015-02-11 15:18:01 +10302190
2191 verbose("device %u: console\n", devices.device_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002192}
Rusty Russelldde79782007-07-26 10:41:03 -07002193/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002194
Rusty Russell2e04ef72009-07-30 16:03:45 -06002195/*M:010
2196 * Inter-guest networking is an interesting area. Simplest is to have a
Rusty Russell17cbca22007-10-22 11:24:22 +10002197 * --sharenet=<name> option which opens or creates a named pipe. This can be
2198 * used to send packets to another guest in a 1:1 manner.
2199 *
Rusty Russell9f542882011-07-22 14:39:50 +09302200 * More sophisticated is to use one of the tools developed for project like UML
Rusty Russell17cbca22007-10-22 11:24:22 +10002201 * to do networking.
2202 *
2203 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2204 * completely generic ("here's my vring, attach to your vring") and would work
2205 * for any traffic. Of course, namespace and permissions issues need to be
2206 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2207 * multiple inter-guest channels behind one interface, although it would
2208 * require some manner of hotplugging new virtio channels.
2209 *
Rusty Russell9f542882011-07-22 14:39:50 +09302210 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002211:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002212
Rusty Russell8ca47e02007-07-19 01:49:29 -07002213static u32 str2ip(const char *ipaddr)
2214{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002215 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002216
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002217 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2218 errx(1, "Failed to parse IP address '%s'", ipaddr);
2219 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2220}
2221
2222static void str2mac(const char *macaddr, unsigned char mac[6])
2223{
2224 unsigned int m[6];
2225 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2226 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2227 errx(1, "Failed to parse mac address '%s'", macaddr);
2228 mac[0] = m[0];
2229 mac[1] = m[1];
2230 mac[2] = m[2];
2231 mac[3] = m[3];
2232 mac[4] = m[4];
2233 mac[5] = m[5];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002234}
2235
Rusty Russell2e04ef72009-07-30 16:03:45 -06002236/*
2237 * This code is "adapted" from libbridge: it attaches the Host end of the
Rusty Russelldde79782007-07-26 10:41:03 -07002238 * network device to the bridge device specified by the command line.
2239 *
2240 * This is yet another James Morris contribution (I'm an IP-level guy, so I
Rusty Russell2e04ef72009-07-30 16:03:45 -06002241 * dislike bridging), and I just try not to break it.
2242 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002243static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2244{
2245 int ifidx;
2246 struct ifreq ifr;
2247
2248 if (!*br_name)
2249 errx(1, "must specify bridge name");
2250
2251 ifidx = if_nametoindex(if_name);
2252 if (!ifidx)
2253 errx(1, "interface %s does not exist!", if_name);
2254
2255 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002256 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07002257 ifr.ifr_ifindex = ifidx;
2258 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2259 err(1, "can't add %s to bridge %s", if_name, br_name);
2260}
2261
Rusty Russell2e04ef72009-07-30 16:03:45 -06002262/*
2263 * This sets up the Host end of the network device with an IP address, brings
Rusty Russelldde79782007-07-26 10:41:03 -07002264 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell2e04ef72009-07-30 16:03:45 -06002265 * pointer.
2266 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002267static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002268{
2269 struct ifreq ifr;
Rusty Russellf8466192010-08-27 08:39:48 -06002270 struct sockaddr_in sin;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002271
2272 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002273 strcpy(ifr.ifr_name, tapif);
2274
2275 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russellf8466192010-08-27 08:39:48 -06002276 sin.sin_family = AF_INET;
2277 sin.sin_addr.s_addr = htonl(ipaddr);
2278 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002279 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002280 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002281 ifr.ifr_flags = IFF_UP;
2282 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002283 err(1, "Bringing interface %s up", tapif);
2284}
2285
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002286static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07002287{
Rusty Russell8ca47e02007-07-19 01:49:29 -07002288 struct ifreq ifr;
Rusty Russellbf6d4032015-02-11 15:16:01 +10302289 int vnet_hdr_sz;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002290 int netfd;
2291
2292 /* Start with this zeroed. Messy but sure. */
2293 memset(&ifr, 0, sizeof(ifr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002294
Rusty Russell2e04ef72009-07-30 16:03:45 -06002295 /*
2296 * We open the /dev/net/tun device and tell it we want a tap device. A
Rusty Russelldde79782007-07-26 10:41:03 -07002297 * tap device is like a tun device, only somehow different. To tell
2298 * the truth, I completely blundered my way through this code, but it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002299 * works now!
2300 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002301 netfd = open_or_die("/dev/net/tun", O_RDWR);
Rusty Russell398f1872008-07-29 09:58:37 -05002302 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002303 strcpy(ifr.ifr_name, "tap%d");
2304 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2305 err(1, "configuring /dev/net/tun");
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002306
Rusty Russell398f1872008-07-29 09:58:37 -05002307 if (ioctl(netfd, TUNSETOFFLOAD,
2308 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2309 err(1, "Could not set features for tun device");
2310
Rusty Russell2e04ef72009-07-30 16:03:45 -06002311 /*
2312 * We don't need checksums calculated for packets coming in this
2313 * device: trust us!
2314 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002315 ioctl(netfd, TUNSETNOCSUM, 1);
2316
Rusty Russellbf6d4032015-02-11 15:16:01 +10302317 /*
2318 * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2319 * field at the end of the network header iff
2320 * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
2321 * that became the norm, but we need to tell the tun device
2322 * about our expanded header (which is called
2323 * virtio_net_hdr_mrg_rxbuf in the legacy system).
2324 */
2325 vnet_hdr_sz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2326 if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
2327 err(1, "Setting tun header size to %u", vnet_hdr_sz);
2328
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002329 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2330 return netfd;
2331}
2332
Rusty Russell2e04ef72009-07-30 16:03:45 -06002333/*L:195
2334 * Our network is a Host<->Guest network. This can either use bridging or
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002335 * routing, but the principle is the same: it uses the "tun" device to inject
2336 * packets into the Host as if they came in from a normal network card. We
Rusty Russell2e04ef72009-07-30 16:03:45 -06002337 * just shunt packets between the Guest and the tun device.
2338 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002339static void setup_tun_net(char *arg)
2340{
2341 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002342 struct net_info *net_info = malloc(sizeof(*net_info));
2343 int ipfd;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002344 u32 ip = INADDR_ANY;
2345 bool bridging = false;
2346 char tapif[IFNAMSIZ], *p;
2347 struct virtio_net_config conf;
2348
Rusty Russell659a0e62009-06-12 22:27:10 -06002349 net_info->tunfd = get_tun_device(tapif);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002350
Rusty Russell17cbca22007-10-22 11:24:22 +10002351 /* First we create a new network device. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302352 dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002353 dev->priv = net_info;
Rusty Russelldde79782007-07-26 10:41:03 -07002354
Rusty Russell2e04ef72009-07-30 16:03:45 -06002355 /* Network devices need a recv and a send queue, just like console. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302356 add_pci_virtqueue(dev, net_input);
2357 add_pci_virtqueue(dev, net_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002358
Rusty Russell2e04ef72009-07-30 16:03:45 -06002359 /*
2360 * We need a socket to perform the magic network ioctls to bring up the
2361 * tap interface, connect to the bridge etc. Any socket will do!
2362 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002363 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2364 if (ipfd < 0)
2365 err(1, "opening IP socket");
2366
Rusty Russelldde79782007-07-26 10:41:03 -07002367 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002368 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002369 arg += strlen(BRIDGE_PFX);
2370 bridging = true;
2371 }
2372
2373 /* A mac address may follow the bridge name or IP address */
2374 p = strchr(arg, ':');
2375 if (p) {
2376 str2mac(p+1, conf.mac);
Rusty Russellbf6d4032015-02-11 15:16:01 +10302377 add_pci_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002378 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002379 }
2380
2381 /* arg is now either an IP address or a bridge name */
2382 if (bridging)
2383 add_to_bridge(ipfd, tapif, arg);
2384 else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002385 ip = str2ip(arg);
2386
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002387 /* Set up the tun device. */
2388 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002389
Rusty Russell398f1872008-07-29 09:58:37 -05002390 /* Expect Guest to handle everything except UFO */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302391 add_pci_feature(dev, VIRTIO_NET_F_CSUM);
2392 add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2393 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2394 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2395 add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2396 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2397 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2398 add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
Mark McLoughlind1f01322009-05-11 18:11:46 +01002399 /* We handle indirect ring entries */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302400 add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2401 set_device_config(dev, &conf, sizeof(conf));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002402
Rusty Russella586d4f2008-02-04 23:49:56 -05002403 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002404 close(ipfd);
2405
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002406 if (bridging)
2407 verbose("device %u: tun %s attached to bridge: %s\n",
2408 devices.device_num, tapif, arg);
2409 else
2410 verbose("device %u: tun %s: %s\n",
2411 devices.device_num, tapif, arg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002412}
Rusty Russella91d74a2009-07-30 16:03:45 -06002413/*:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002414
Rusty Russelle1e72962007-10-25 15:02:50 +10002415/* This hangs off device->priv. */
Rusty Russell1842f232009-07-30 16:03:46 -06002416struct vblk_info {
Rusty Russell17cbca22007-10-22 11:24:22 +10002417 /* The size of the file. */
2418 off64_t len;
2419
2420 /* The file descriptor for the file. */
2421 int fd;
2422
Rusty Russell17cbca22007-10-22 11:24:22 +10002423};
2424
Rusty Russelle1e72962007-10-25 15:02:50 +10002425/*L:210
2426 * The Disk
2427 *
Rusty Russella91d74a2009-07-30 16:03:45 -06002428 * The disk only has one virtqueue, so it only has one thread. It is really
2429 * simple: the Guest asks for a block number and we read or write that position
2430 * in the file.
2431 *
2432 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2433 * slow: the Guest waits until the read is finished before running anything
2434 * else, even if it could have been doing useful work.
2435 *
2436 * We could have used async I/O, except it's reputed to suck so hard that
2437 * characters actually go missing from your code when you try to use it.
Rusty Russelle1e72962007-10-25 15:02:50 +10002438 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002439static void blk_request(struct virtqueue *vq)
Rusty Russell17cbca22007-10-22 11:24:22 +10002440{
Rusty Russell659a0e62009-06-12 22:27:10 -06002441 struct vblk_info *vblk = vq->dev->priv;
Rusty Russell17cbca22007-10-22 11:24:22 +10002442 unsigned int head, out_num, in_num, wlen;
Rusty Russellc0316a92012-10-16 23:56:13 +10302443 int ret, i;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002444 u8 *in;
Rusty Russellc0316a92012-10-16 23:56:13 +10302445 struct virtio_blk_outhdr out;
Rusty Russell659a0e62009-06-12 22:27:10 -06002446 struct iovec iov[vq->vring.num];
Rusty Russell17cbca22007-10-22 11:24:22 +10002447 off64_t off;
2448
Rusty Russella91d74a2009-07-30 16:03:45 -06002449 /*
2450 * Get the next request, where we normally wait. It triggers the
2451 * interrupt to acknowledge previously serviced requests (if any).
2452 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002453 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002454
Rusty Russellc0316a92012-10-16 23:56:13 +10302455 /* Copy the output header from the front of the iov (adjusts iov) */
2456 iov_consume(iov, out_num, &out, sizeof(out));
Rusty Russell17cbca22007-10-22 11:24:22 +10002457
Rusty Russellc0316a92012-10-16 23:56:13 +10302458 /* Find and trim end of iov input array, for our status byte. */
2459 in = NULL;
2460 for (i = out_num + in_num - 1; i >= out_num; i--) {
2461 if (iov[i].iov_len > 0) {
2462 in = iov[i].iov_base + iov[i].iov_len - 1;
2463 iov[i].iov_len--;
2464 break;
2465 }
2466 }
2467 if (!in)
2468 errx(1, "Bad virtblk cmd with no room for status");
2469
Rusty Russella91d74a2009-07-30 16:03:45 -06002470 /*
2471 * For historical reasons, block operations are expressed in 512 byte
2472 * "sectors".
2473 */
Rusty Russellc0316a92012-10-16 23:56:13 +10302474 off = out.sector * 512;
Rusty Russell17cbca22007-10-22 11:24:22 +10002475
Rusty Russell50516542015-02-11 15:15:12 +10302476 if (out.type & VIRTIO_BLK_T_OUT) {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002477 /*
2478 * Write
2479 *
2480 * Move to the right location in the block file. This can fail
2481 * if they try to write past end.
2482 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002483 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302484 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002485
Rusty Russellc0316a92012-10-16 23:56:13 +10302486 ret = writev(vblk->fd, iov, out_num);
2487 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
Rusty Russell17cbca22007-10-22 11:24:22 +10002488
Rusty Russell2e04ef72009-07-30 16:03:45 -06002489 /*
2490 * Grr... Now we know how long the descriptor they sent was, we
Rusty Russell17cbca22007-10-22 11:24:22 +10002491 * make sure they didn't try to write over the end of the block
Rusty Russell2e04ef72009-07-30 16:03:45 -06002492 * file (possibly extending it).
2493 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002494 if (ret > 0 && off + ret > vblk->len) {
2495 /* Trim it back to the correct length */
2496 ftruncate64(vblk->fd, vblk->len);
2497 /* Die, bad Guest, die. */
2498 errx(1, "Write past end %llu+%u", off, ret);
2499 }
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002500
2501 wlen = sizeof(*in);
2502 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russellc0316a92012-10-16 23:56:13 +10302503 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002504 /* Flush */
2505 ret = fdatasync(vblk->fd);
2506 verbose("FLUSH fdatasync: %i\n", ret);
Anthony Liguori1200e642007-11-08 21:13:44 -06002507 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002508 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10002509 } else {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002510 /*
2511 * Read
2512 *
2513 * Move to the right location in the block file. This can fail
2514 * if they try to read past end.
2515 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002516 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302517 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002518
Rusty Russellc0316a92012-10-16 23:56:13 +10302519 ret = readv(vblk->fd, iov + out_num, in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002520 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06002521 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002522 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10002523 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06002524 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002525 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10002526 }
2527 }
2528
Rusty Russella91d74a2009-07-30 16:03:45 -06002529 /* Finished that request. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002530 add_used(vq, head, wlen);
Rusty Russell17cbca22007-10-22 11:24:22 +10002531}
2532
Rusty Russelle1e72962007-10-25 15:02:50 +10002533/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002534static void setup_block_file(const char *filename)
2535{
Rusty Russell17cbca22007-10-22 11:24:22 +10002536 struct device *dev;
2537 struct vblk_info *vblk;
Rusty Russella586d4f2008-02-04 23:49:56 -05002538 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10002539
Rusty Russell50516542015-02-11 15:15:12 +10302540 /* Create the device. */
2541 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
Rusty Russell17cbca22007-10-22 11:24:22 +10002542
Rusty Russelle1e72962007-10-25 15:02:50 +10002543 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell50516542015-02-11 15:15:12 +10302544 add_pci_virtqueue(dev, blk_request);
Rusty Russell17cbca22007-10-22 11:24:22 +10002545
2546 /* Allocate the room for our own bookkeeping */
2547 vblk = dev->priv = malloc(sizeof(*vblk));
2548
2549 /* First we open the file and store the length. */
2550 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
2551 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
2552
2553 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002554 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10002555
Rusty Russell2e04ef72009-07-30 16:03:45 -06002556 /*
2557 * Tell Guest not to put in too many descriptors at once: two are used
2558 * for the in and out elements.
2559 */
Rusty Russell50516542015-02-11 15:15:12 +10302560 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
Rusty Russella586d4f2008-02-04 23:49:56 -05002561 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2562
Rusty Russell50516542015-02-11 15:15:12 +10302563 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
Rusty Russell17cbca22007-10-22 11:24:22 +10002564
Rusty Russell17cbca22007-10-22 11:24:22 +10002565 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell50516542015-02-11 15:15:12 +10302566 devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10002567}
Rusty Russell28fd6d72008-07-29 09:58:33 -05002568
Rusty Russell2e04ef72009-07-30 16:03:45 -06002569/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10302570 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05002571 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10302572 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05002573 * console is the reverse.
2574 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002575 * The same logic applies, however.
2576 */
2577struct rng_info {
2578 int rfd;
2579};
2580
Rusty Russell659a0e62009-06-12 22:27:10 -06002581static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05002582{
2583 int len;
2584 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002585 struct rng_info *rng_info = vq->dev->priv;
2586 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05002587
2588 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002589 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002590 if (out_num)
2591 errx(1, "Output buffers in rng?");
2592
Rusty Russell2e04ef72009-07-30 16:03:45 -06002593 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06002594 * Just like the console write, we loop to cover the whole iovec.
2595 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002596 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002597 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06002598 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002599 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10302600 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10302601 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002602 totlen += len;
2603 }
2604
2605 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002606 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002607}
2608
Rusty Russell2e04ef72009-07-30 16:03:45 -06002609/*L:199
2610 * This creates a "hardware" random number device for the Guest.
2611 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002612static void setup_rng(void)
2613{
2614 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002615 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05002616
Rusty Russella454bb32015-02-11 15:15:09 +10302617 /* Our device's private info simply contains the /dev/urandom fd. */
2618 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002619
Rusty Russell2e04ef72009-07-30 16:03:45 -06002620 /* Create the new device. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302621 dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
Rusty Russell659a0e62009-06-12 22:27:10 -06002622 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002623
2624 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302625 add_pci_virtqueue(dev, rng_input);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002626
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302627 /* We don't have any configuration space */
2628 no_device_config(dev);
2629
2630 verbose("device %u: rng\n", devices.device_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002631}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002632/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05302633
Rusty Russella6bd8e12008-03-28 11:05:53 -05002634/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05302635static void __attribute__((noreturn)) restart_guest(void)
2636{
2637 unsigned int i;
2638
Rusty Russell2e04ef72009-07-30 16:03:45 -06002639 /*
2640 * Since we don't track all open fds, we simply close everything beyond
2641 * stderr.
2642 */
Balaji Raoec04b132007-12-28 14:26:24 +05302643 for (i = 3; i < FD_SETSIZE; i++)
2644 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05002645
Rusty Russell659a0e62009-06-12 22:27:10 -06002646 /* Reset all the devices (kills all threads). */
2647 cleanup_devices();
2648
Balaji Raoec04b132007-12-28 14:26:24 +05302649 execv(main_args[0], main_args);
2650 err(1, "Could not exec %s", main_args[0]);
2651}
Rusty Russell8ca47e02007-07-19 01:49:29 -07002652
Rusty Russell2e04ef72009-07-30 16:03:45 -06002653/*L:220
2654 * Finally we reach the core of the Launcher which runs the Guest, serves
2655 * its input and output, and finally, lays it to rest.
2656 */
Rusty Russell56739c802009-06-12 22:26:59 -06002657static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002658{
2659 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10302660 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002661 int readval;
2662
2663 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302664 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002665
Rusty Russell17cbca22007-10-22 11:24:22 +10002666 /* One unsigned long means the Guest did HCALL_NOTIFY */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302667 if (readval == sizeof(notify)) {
2668 if (notify.trap == 0x1F) {
2669 verbose("Notify on address %#08x\n",
2670 notify.addr);
2671 handle_output(notify.addr);
Rusty Russellc565650b2015-02-11 15:15:10 +10302672 } else if (notify.trap == 13) {
2673 verbose("Emulating instruction at %#x\n",
2674 getreg(eip));
2675 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302676 } else if (notify.trap == 14) {
2677 verbose("Emulating MMIO at %#x\n",
2678 getreg(eip));
2679 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302680 } else
2681 errx(1, "Unknown trap %i addr %#08x\n",
2682 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07002683 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002684 } else if (errno == ENOENT) {
2685 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002686 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002687 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05302688 /* ERESTART means that we need to reboot the guest */
2689 } else if (errno == ERESTART) {
2690 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06002691 /* Anything else means a bug or incompatible change. */
2692 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002693 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002694 }
2695}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002696/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10002697 * This is the end of the Launcher. The good news: we are over halfway
2698 * through! The bad news: the most fiendish part of the code still lies ahead
2699 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07002700 *
Rusty Russelle1e72962007-10-25 15:02:50 +10002701 * Are you ready? Take a deep breath and join me in the core of the Host, in
2702 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06002703:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002704
2705static struct option opts[] = {
2706 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002707 { "tunnet", 1, NULL, 't' },
2708 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05002709 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002710 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002711 { "username", 1, NULL, 'u' },
2712 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002713 { NULL },
2714};
2715static void usage(void)
2716{
2717 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002718 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07002719 "|--block=<filename>|--initrd=<filename>]...\n"
2720 "<mem-in-mb> vmlinux [args...]");
2721}
2722
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002723/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002724int main(int argc, char *argv[])
2725{
Rusty Russell2e04ef72009-07-30 16:03:45 -06002726 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002727 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06002728 /* Two temporaries. */
2729 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002730 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002731 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07002732 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002733 const char *initrd_name = NULL;
2734
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002735 /* Password structure for initgroups/setres[gu]id */
2736 struct passwd *user_details = NULL;
2737
2738 /* Directory to chroot to */
2739 char *chroot_path = NULL;
2740
Balaji Raoec04b132007-12-28 14:26:24 +05302741 /* Save the args: we "reboot" by execing ourselves again. */
2742 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05302743
Rusty Russell2e04ef72009-07-30 16:03:45 -06002744 /*
Rusty Russelld9028ed2015-02-11 15:21:01 +10302745 * First we initialize the device list. We remember next interrupt
2746 * number to use for devices (1: remember that 0 is used by the timer).
Rusty Russell2e04ef72009-07-30 16:03:45 -06002747 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002748 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002749
Rusty Russella91d74a2009-07-30 16:03:45 -06002750 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002751 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06002752
Rusty Russell2e04ef72009-07-30 16:03:45 -06002753 /*
2754 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07002755 * descriptor and memory pages for the devices as we parse the command
2756 * line. So we quickly look through the arguments to find the amount
Rusty Russell2e04ef72009-07-30 16:03:45 -06002757 * of memory now.
2758 */
Rusty Russell6570c45992007-07-23 18:43:56 -07002759 for (i = 1; i < argc; i++) {
2760 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002761 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002762 /*
2763 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002764 * guest-physical memory range. This fills it with 0,
2765 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002766 * tries to access it.
2767 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002768 guest_base = map_zeroed_pages(mem / getpagesize()
2769 + DEVICE_PAGES);
2770 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10302771 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell6570c45992007-07-23 18:43:56 -07002772 break;
2773 }
2774 }
Rusty Russelldde79782007-07-26 10:41:03 -07002775
2776 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002777 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2778 switch (c) {
2779 case 'v':
2780 verbose = true;
2781 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002782 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10002783 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002784 break;
2785 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10002786 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002787 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002788 case 'r':
2789 setup_rng();
2790 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002791 case 'i':
2792 initrd_name = optarg;
2793 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002794 case 'u':
2795 user_details = getpwnam(optarg);
2796 if (!user_details)
2797 err(1, "getpwnam failed, incorrect username?");
2798 break;
2799 case 'c':
2800 chroot_path = optarg;
2801 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002802 default:
2803 warnx("Unknown argument %s", argv[optind]);
2804 usage();
2805 }
2806 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06002807 /*
2808 * After the other arguments we expect memory and kernel image name,
2809 * followed by command line arguments for the kernel.
2810 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002811 if (optind + 2 > argc)
2812 usage();
2813
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002814 verbose("Guest base is at %p\n", guest_base);
2815
Rusty Russelldde79782007-07-26 10:41:03 -07002816 /* We always have a console device */
Rusty Russell17cbca22007-10-22 11:24:22 +10002817 setup_console();
Rusty Russell8ca47e02007-07-19 01:49:29 -07002818
Rusty Russell8e709462015-02-11 15:15:12 +10302819 /* Initialize the (fake) PCI host bridge device. */
2820 init_pci_host_bridge();
2821
Rusty Russell8ca47e02007-07-19 01:49:29 -07002822 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10002823 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002824
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002825 /* Boot information is stashed at physical address 0 */
2826 boot = from_guest_phys(0);
2827
Rusty Russelldde79782007-07-26 10:41:03 -07002828 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002829 if (initrd_name) {
2830 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06002831 /*
2832 * These are the location in the Linux boot header where the
2833 * start and size of the initrd are expected to be found.
2834 */
Rusty Russell43d33b22007-10-22 11:29:57 +10002835 boot->hdr.ramdisk_image = mem - initrd_size;
2836 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07002837 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002838 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002839 }
2840
Rusty Russell2e04ef72009-07-30 16:03:45 -06002841 /*
2842 * The Linux boot header contains an "E820" memory map: ours is a
2843 * simple, single region.
2844 */
Rusty Russell43d33b22007-10-22 11:29:57 +10002845 boot->e820_entries = 1;
2846 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06002847 /*
2848 * The boot header contains a command line pointer: we put the command
2849 * line after the boot header.
2850 */
Rusty Russell43d33b22007-10-22 11:29:57 +10002851 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10002852 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002853 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07002854
Rusty Russelle22a5392011-08-15 10:15:10 +09302855 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
2856 boot->hdr.kernel_alignment = 0x1000000;
2857
Rusty Russell814a0e52007-10-22 11:29:44 +10002858 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002859 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10002860
2861 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002862 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10002863
Rusty Russell43d33b22007-10-22 11:29:57 +10002864 /* Tell the entry path not to try to reload segment registers. */
2865 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002866
Rusty Russell9f542882011-07-22 14:39:50 +09302867 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06002868 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07002869
Rusty Russella91d74a2009-07-30 16:03:45 -06002870 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002871 signal(SIGCHLD, kill_launcher);
2872
2873 /* If we exit via err(), this kills all the threads, restores tty. */
2874 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002875
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002876 /* If requested, chroot to a directory */
2877 if (chroot_path) {
2878 if (chroot(chroot_path) != 0)
2879 err(1, "chroot(\"%s\") failed", chroot_path);
2880
2881 if (chdir("/") != 0)
2882 err(1, "chdir(\"/\") failed");
2883
2884 verbose("chroot done\n");
2885 }
2886
2887 /* If requested, drop privileges */
2888 if (user_details) {
2889 uid_t u;
2890 gid_t g;
2891
2892 u = user_details->pw_uid;
2893 g = user_details->pw_gid;
2894
2895 if (initgroups(user_details->pw_name, g) != 0)
2896 err(1, "initgroups failed");
2897
2898 if (setresgid(g, g, g) != 0)
2899 err(1, "setresgid failed");
2900
2901 if (setresuid(u, u, u) != 0)
2902 err(1, "setresuid failed");
2903
2904 verbose("Dropping privileges completed\n");
2905 }
2906
Rusty Russelldde79782007-07-26 10:41:03 -07002907 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06002908 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07002909}
Rusty Russellf56a3842007-07-26 10:41:05 -07002910/*:*/
2911
2912/*M:999
2913 * Mastery is done: you now know everything I do.
2914 *
2915 * But surely you have seen code, features and bugs in your wanderings which
2916 * you now yearn to attack? That is the real game, and I look forward to you
2917 * patching and forking lguest into the Your-Name-Here-visor.
2918 *
2919 * Farewell, and good coding!
2920 * Rusty Russell.
2921 */