blob: e52a3571076ac13ff972e40e1f39eb1ef06ac368 [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>
Philip Sanderson8aeb36e2011-01-20 21:37:28 -060045
Rusty Russell927cfb92013-07-15 10:50:13 +093046#ifndef VIRTIO_F_ANY_LAYOUT
47#define VIRTIO_F_ANY_LAYOUT 27
48#endif
49
Rusty Russell2e04ef72009-07-30 16:03:45 -060050/*L:110
Rusty Russell9f542882011-07-22 14:39:50 +093051 * We can ignore the 43 include files we need for this program, but I do want
Rusty Russell2e04ef72009-07-30 16:03:45 -060052 * to draw attention to the use of kernel-style types.
Rusty Russelldb24e8c2007-10-25 14:09:25 +100053 *
54 * As Linus said, "C is a Spartan language, and so should your naming be." I
55 * like these abbreviations, so we define them here. Note that u64 is always
56 * unsigned long long, which works on all Linux systems: this means that we can
Rusty Russell2e04ef72009-07-30 16:03:45 -060057 * use %llu in printf for any u64.
58 */
Rusty Russelldb24e8c2007-10-25 14:09:25 +100059typedef unsigned long long u64;
60typedef uint32_t u32;
61typedef uint16_t u16;
62typedef uint8_t u8;
Rusty Russelldde79782007-07-26 10:41:03 -070063/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070064
Rusty Russelle6dc0412013-07-04 11:22:58 +093065#include <linux/virtio_config.h>
66#include <linux/virtio_net.h>
67#include <linux/virtio_blk.h>
68#include <linux/virtio_console.h>
69#include <linux/virtio_rng.h>
70#include <linux/virtio_ring.h>
71#include <asm/bootparam.h>
72#include "../../include/linux/lguest_launcher.h"
73
Rusty Russell8ca47e02007-07-19 01:49:29 -070074#define BRIDGE_PFX "bridge:"
75#ifndef SIOCBRADDIF
76#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
77#endif
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100078/* We can have up to 256 pages for devices. */
79#define DEVICE_PAGES 256
Rusty Russell0f0c4fa2008-07-29 09:58:37 -050080/* This will occupy 3 pages: it must be a power of 2. */
81#define VIRTQUEUE_NUM 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070082
Rusty Russell2e04ef72009-07-30 16:03:45 -060083/*L:120
84 * verbose is both a global flag and a macro. The C preprocessor allows
85 * this, and although I wouldn't recommend it, it works quite nicely here.
86 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070087static bool verbose;
88#define verbose(args...) \
89 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070090/*:*/
91
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100092/* The pointer to the start of guest memory. */
93static void *guest_base;
94/* The maximum guest physical address allowed, and maximum possible. */
Rusty Russell0a6bcc12015-02-11 15:15:11 +103095static unsigned long guest_limit, guest_max, guest_mmio;
Rusty Russell56739c802009-06-12 22:26:59 -060096/* The /dev/lguest file descriptor. */
97static int lguest_fd;
Rusty Russell8ca47e02007-07-19 01:49:29 -070098
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -020099/* a per-cpu variable indicating whose vcpu is currently running */
100static unsigned int __thread cpu_id;
101
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030102/* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
103#define MAX_PCI_DEVICES 32
104
Rusty Russelldde79782007-07-26 10:41:03 -0700105/* This is our list of devices. */
Rusty Russell1842f232009-07-30 16:03:46 -0600106struct device_list {
Rusty Russell17cbca22007-10-22 11:24:22 +1000107 /* Counter to assign interrupt numbers. */
108 unsigned int next_irq;
109
110 /* Counter to print out convenient device numbers. */
111 unsigned int device_num;
112
Rusty Russelldde79782007-07-26 10:41:03 -0700113 /* The descriptor page for the devices. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000114 u8 *descpage;
115
Rusty Russelldde79782007-07-26 10:41:03 -0700116 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700117 struct device *dev;
Rusty Russell2e04ef72009-07-30 16:03:45 -0600118 /* And a pointer to the last device for easy append. */
Rusty Russella586d4f2008-02-04 23:49:56 -0500119 struct device *lastdev;
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030120
121 /* PCI devices. */
122 struct device *pci[MAX_PCI_DEVICES];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700123};
124
Rusty Russell17cbca22007-10-22 11:24:22 +1000125/* The list of Guest devices, based on command line arguments. */
126static struct device_list devices;
127
Rusty Russelldde79782007-07-26 10:41:03 -0700128/* The device structure describes a single device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600129struct device {
Rusty Russelldde79782007-07-26 10:41:03 -0700130 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700131 struct device *next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000132
Rusty Russell713b15b2009-06-12 22:26:58 -0600133 /* The device's descriptor, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700134 struct lguest_device_desc *desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000135
Rusty Russell713b15b2009-06-12 22:26:58 -0600136 /* We can't trust desc values once Guest has booted: we use these. */
137 unsigned int feature_len;
138 unsigned int num_vq;
139
Rusty Russell17cbca22007-10-22 11:24:22 +1000140 /* The name of this device, for --verbose. */
141 const char *name;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700142
Rusty Russell17cbca22007-10-22 11:24:22 +1000143 /* Any queues attached to this device */
144 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700145
Rusty Russell659a0e62009-06-12 22:27:10 -0600146 /* Is it operational */
147 bool running;
Rusty Russella007a752008-05-02 21:50:53 -0500148
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030149 /* PCI MMIO resources (all in BAR0) */
150 size_t mmio_size;
151 u32 mmio_addr;
152
Rusty Russell8ca47e02007-07-19 01:49:29 -0700153 /* Device-specific data. */
154 void *priv;
155};
156
Rusty Russell17cbca22007-10-22 11:24:22 +1000157/* The virtqueue structure describes a queue attached to a device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600158struct virtqueue {
Rusty Russell17cbca22007-10-22 11:24:22 +1000159 struct virtqueue *next;
160
161 /* Which device owns me. */
162 struct device *dev;
163
164 /* The configuration for this queue. */
165 struct lguest_vqconfig config;
166
167 /* The actual ring of buffers. */
168 struct vring vring;
169
170 /* Last available index we saw. */
171 u16 last_avail_idx;
172
Rusty Russell95c517c2009-06-12 22:27:11 -0600173 /* How many are used since we sent last irq? */
174 unsigned int pending_used;
175
Rusty Russell659a0e62009-06-12 22:27:10 -0600176 /* Eventfd where Guest notifications arrive. */
177 int eventfd;
Rusty Russell20887612008-05-30 15:09:46 -0500178
Rusty Russell659a0e62009-06-12 22:27:10 -0600179 /* Function for the thread which is servicing this virtqueue. */
180 void (*service)(struct virtqueue *vq);
181 pid_t thread;
Rusty Russell17cbca22007-10-22 11:24:22 +1000182};
183
Balaji Raoec04b132007-12-28 14:26:24 +0530184/* Remember the arguments to the program so we can "reboot" */
185static char **main_args;
186
Rusty Russell659a0e62009-06-12 22:27:10 -0600187/* The original tty settings to restore on exit. */
188static struct termios orig_term;
189
Rusty Russell2e04ef72009-07-30 16:03:45 -0600190/*
191 * We have to be careful with barriers: our devices are all run in separate
Rusty Russellf7027c62009-06-12 22:27:00 -0600192 * threads and so we need to make sure that changes visible to the Guest happen
Rusty Russell2e04ef72009-07-30 16:03:45 -0600193 * in precise order.
194 */
Rusty Russellf7027c62009-06-12 22:27:00 -0600195#define wmb() __asm__ __volatile__("" : : : "memory")
Rusty Russell0d69a652013-07-02 15:35:14 +0930196#define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
197#define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
Rusty Russell17cbca22007-10-22 11:24:22 +1000198
Rusty Russellb5111792008-07-29 09:58:34 -0500199/* Wrapper for the last available index. Makes it easier to change. */
200#define lg_last_avail(vq) ((vq)->last_avail_idx)
201
Rusty Russell2e04ef72009-07-30 16:03:45 -0600202/*
203 * The virtio configuration space is defined to be little-endian. x86 is
204 * little-endian too, but it's nice to be explicit so we have these helpers.
205 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000206#define cpu_to_le16(v16) (v16)
207#define cpu_to_le32(v32) (v32)
208#define cpu_to_le64(v64) (v64)
209#define le16_to_cpu(v16) (v16)
210#define le32_to_cpu(v32) (v32)
Rusty Russella586d4f2008-02-04 23:49:56 -0500211#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000212
Rusty Russell28fd6d72008-07-29 09:58:33 -0500213/* Is this iovec empty? */
214static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
215{
216 unsigned int i;
217
218 for (i = 0; i < num_iov; i++)
219 if (iov[i].iov_len)
220 return false;
221 return true;
222}
223
224/* Take len bytes from the front of this iovec. */
Rusty Russellc0316a92012-10-16 23:56:13 +1030225static void iov_consume(struct iovec iov[], unsigned num_iov,
226 void *dest, unsigned len)
Rusty Russell28fd6d72008-07-29 09:58:33 -0500227{
228 unsigned int i;
229
230 for (i = 0; i < num_iov; i++) {
231 unsigned int used;
232
233 used = iov[i].iov_len < len ? iov[i].iov_len : len;
Rusty Russellc0316a92012-10-16 23:56:13 +1030234 if (dest) {
235 memcpy(dest, iov[i].iov_base, used);
236 dest += used;
237 }
Rusty Russell28fd6d72008-07-29 09:58:33 -0500238 iov[i].iov_base += used;
239 iov[i].iov_len -= used;
240 len -= used;
241 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030242 if (len != 0)
243 errx(1, "iovec too short!");
Rusty Russell28fd6d72008-07-29 09:58:33 -0500244}
245
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500246/* The device virtqueue descriptors are followed by feature bitmasks. */
247static u8 *get_feature_bits(struct device *dev)
248{
249 return (u8 *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -0600250 + dev->num_vq * sizeof(struct lguest_vqconfig);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500251}
252
Rusty Russell2e04ef72009-07-30 16:03:45 -0600253/*L:100
254 * The Launcher code itself takes us out into userspace, that scary place where
255 * pointers run wild and free! Unfortunately, like most userspace programs,
256 * it's quite boring (which is why everyone likes to hack on the kernel!).
257 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
258 * you through this section. Or, maybe not.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000259 *
260 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
261 * memory and stores it in "guest_base". In other words, Guest physical ==
262 * Launcher virtual with an offset.
263 *
264 * This can be tough to get your head around, but usually it just means that we
Francis Galieguea33f3222010-04-23 00:08:02 +0200265 * use these trivial conversion functions when the Guest gives us its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600266 * "physical" addresses:
267 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000268static void *from_guest_phys(unsigned long addr)
269{
270 return guest_base + addr;
271}
272
273static unsigned long to_guest_phys(const void *addr)
274{
275 return (addr - guest_base);
276}
277
Rusty Russelldde79782007-07-26 10:41:03 -0700278/*L:130
279 * Loading the Kernel.
280 *
281 * We start with couple of simple helper routines. open_or_die() avoids
Rusty Russell2e04ef72009-07-30 16:03:45 -0600282 * error-checking code cluttering the callers:
283 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700284static int open_or_die(const char *name, int flags)
285{
286 int fd = open(name, flags);
287 if (fd < 0)
288 err(1, "Failed to open %s", name);
289 return fd;
290}
291
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000292/* map_zeroed_pages() takes a number of pages. */
293static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700294{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000295 int fd = open_or_die("/dev/zero", O_RDONLY);
296 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700297
Rusty Russell2e04ef72009-07-30 16:03:45 -0600298 /*
299 * We use a private mapping (ie. if we write to the page, it will be
Philip Sanderson5230ff02011-01-20 21:37:28 -0600300 * copied). We allocate an extra two pages PROT_NONE to act as guard
301 * pages against read/write attempts that exceed allocated space.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600302 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600303 addr = mmap(NULL, getpagesize() * (num+2),
304 PROT_NONE, MAP_PRIVATE, fd, 0);
305
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000306 if (addr == MAP_FAILED)
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200307 err(1, "Mmapping %u pages of /dev/zero", num);
Rusty Russella91d74a2009-07-30 16:03:45 -0600308
Philip Sanderson5230ff02011-01-20 21:37:28 -0600309 if (mprotect(addr + getpagesize(), getpagesize() * num,
310 PROT_READ|PROT_WRITE) == -1)
311 err(1, "mprotect rw %u pages failed", num);
312
Rusty Russella91d74a2009-07-30 16:03:45 -0600313 /*
314 * One neat mmap feature is that you can close the fd, and it
315 * stays mapped.
316 */
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100317 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700318
Philip Sanderson5230ff02011-01-20 21:37:28 -0600319 /* Return address after PROT_NONE page */
320 return addr + getpagesize();
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000321}
322
323/* Get some more pages for a device. */
324static void *get_pages(unsigned int num)
325{
326 void *addr = from_guest_phys(guest_limit);
327
328 guest_limit += num * getpagesize();
329 if (guest_limit > guest_max)
330 errx(1, "Not enough memory for devices");
331 return addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700332}
333
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030334/* Get some bytes which won't be mapped into the guest. */
335static unsigned long get_mmio_region(size_t size)
336{
337 unsigned long addr = guest_mmio;
338 size_t i;
339
340 if (!size)
341 return addr;
342
343 /* Size has to be a power of 2 (and multiple of 16) */
344 for (i = 1; i < size; i <<= 1);
345
346 guest_mmio += i;
347
348 return addr;
349}
350
Rusty Russell2e04ef72009-07-30 16:03:45 -0600351/*
352 * This routine is used to load the kernel or initrd. It tries mmap, but if
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700353 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
Rusty Russell2e04ef72009-07-30 16:03:45 -0600354 * it falls back to reading the memory in.
355 */
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700356static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
357{
358 ssize_t r;
359
Rusty Russell2e04ef72009-07-30 16:03:45 -0600360 /*
361 * We map writable even though for some segments are marked read-only.
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700362 * The kernel really wants to be writable: it patches its own
363 * instructions.
364 *
365 * MAP_PRIVATE means that the page won't be copied until a write is
366 * done to it. This allows us to share untouched memory between
Rusty Russell2e04ef72009-07-30 16:03:45 -0600367 * Guests.
368 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600369 if (mmap(addr, len, PROT_READ|PROT_WRITE,
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700370 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
371 return;
372
373 /* pread does a seek and a read in one shot: saves a few lines. */
374 r = pread(fd, addr, len, offset);
375 if (r != len)
376 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
377}
378
Rusty Russell2e04ef72009-07-30 16:03:45 -0600379/*
380 * This routine takes an open vmlinux image, which is in ELF, and maps it into
Rusty Russelldde79782007-07-26 10:41:03 -0700381 * the Guest memory. ELF = Embedded Linking Format, which is the format used
382 * by all modern binaries on Linux including the kernel.
383 *
384 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000385 * address. We use the physical address; the Guest will map itself to the
386 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700387 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600388 * We return the starting address.
389 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000390static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700391{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700392 Elf32_Phdr phdr[ehdr->e_phnum];
393 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700394
Rusty Russell2e04ef72009-07-30 16:03:45 -0600395 /*
396 * Sanity checks on the main ELF header: an x86 executable with a
397 * reasonable number of correctly-sized program headers.
398 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700399 if (ehdr->e_type != ET_EXEC
400 || ehdr->e_machine != EM_386
401 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
402 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
403 errx(1, "Malformed elf header");
404
Rusty Russell2e04ef72009-07-30 16:03:45 -0600405 /*
406 * An ELF executable contains an ELF header and a number of "program"
Rusty Russelldde79782007-07-26 10:41:03 -0700407 * headers which indicate which parts ("segments") of the program to
Rusty Russell2e04ef72009-07-30 16:03:45 -0600408 * load where.
409 */
Rusty Russelldde79782007-07-26 10:41:03 -0700410
411 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700412 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
413 err(1, "Seeking to program headers");
414 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
415 err(1, "Reading program headers");
416
Rusty Russell2e04ef72009-07-30 16:03:45 -0600417 /*
418 * Try all the headers: there are usually only three. A read-only one,
419 * a read-write one, and a "note" section which we don't load.
420 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700421 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700422 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700423 if (phdr[i].p_type != PT_LOAD)
424 continue;
425
426 verbose("Section %i: size %i addr %p\n",
427 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
428
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700429 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000430 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700431 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700432 }
433
Rusty Russell814a0e52007-10-22 11:29:44 +1000434 /* The entry point is given in the ELF header. */
435 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700436}
437
Rusty Russell2e04ef72009-07-30 16:03:45 -0600438/*L:150
439 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
440 * to jump into it and it will unpack itself. We used to have to perform some
441 * hairy magic because the unpacking code scared me.
Rusty Russelldde79782007-07-26 10:41:03 -0700442 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000443 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
444 * a small patch to jump over the tricky bits in the Guest, so now we just read
Rusty Russell2e04ef72009-07-30 16:03:45 -0600445 * the funky header so we know where in the file to load, and away we go!
446 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000447static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700448{
Rusty Russell43d33b22007-10-22 11:29:57 +1000449 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000450 int r;
451 /* Modern bzImages get loaded at 1M. */
452 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700453
Rusty Russell2e04ef72009-07-30 16:03:45 -0600454 /*
455 * Go back to the start of the file and read the header. It should be
Paul Bolle395cf962011-08-15 02:02:26 +0200456 * a Linux boot header (see Documentation/x86/boot.txt)
Rusty Russell2e04ef72009-07-30 16:03:45 -0600457 */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000458 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000459 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000460
Rusty Russell43d33b22007-10-22 11:29:57 +1000461 /* Inside the setup_hdr, we expect the magic "HdrS" */
462 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000463 errx(1, "This doesn't look like a bzImage to me");
464
Rusty Russell43d33b22007-10-22 11:29:57 +1000465 /* Skip over the extra sectors of the header. */
466 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000467
468 /* Now read everything into memory. in nice big chunks. */
469 while ((r = read(fd, p, 65536)) > 0)
470 p += r;
471
Rusty Russell43d33b22007-10-22 11:29:57 +1000472 /* Finally, code32_start tells us where to enter the kernel. */
473 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700474}
475
Rusty Russell2e04ef72009-07-30 16:03:45 -0600476/*L:140
477 * Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000478 * come wrapped up in the self-decompressing "bzImage" format. With a little
Rusty Russell2e04ef72009-07-30 16:03:45 -0600479 * work, we can load those, too.
480 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000481static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700482{
483 Elf32_Ehdr hdr;
484
Rusty Russelldde79782007-07-26 10:41:03 -0700485 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700486 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
487 err(1, "Reading kernel");
488
Rusty Russelldde79782007-07-26 10:41:03 -0700489 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700490 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000491 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700492
Rusty Russella6bd8e12008-03-28 11:05:53 -0500493 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000494 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700495}
496
Rusty Russell2e04ef72009-07-30 16:03:45 -0600497/*
498 * This is a trivial little helper to align pages. Andi Kleen hated it because
Rusty Russelldde79782007-07-26 10:41:03 -0700499 * it calls getpagesize() twice: "it's dumb code."
500 *
501 * Kernel guys get really het up about optimization, even when it's not
Rusty Russell2e04ef72009-07-30 16:03:45 -0600502 * necessary. I leave this code as a reaction against that.
503 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700504static inline unsigned long page_align(unsigned long addr)
505{
Rusty Russelldde79782007-07-26 10:41:03 -0700506 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700507 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
508}
509
Rusty Russell2e04ef72009-07-30 16:03:45 -0600510/*L:180
511 * An "initial ram disk" is a disk image loaded into memory along with the
512 * kernel which the kernel can use to boot from without needing any drivers.
513 * Most distributions now use this as standard: the initrd contains the code to
514 * load the appropriate driver modules for the current machine.
Rusty Russelldde79782007-07-26 10:41:03 -0700515 *
516 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600517 * kernels. He sent me this (and tells me when I break it).
518 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700519static unsigned long load_initrd(const char *name, unsigned long mem)
520{
521 int ifd;
522 struct stat st;
523 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700524
525 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700526 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700527 if (fstat(ifd, &st) < 0)
528 err(1, "fstat() on initrd '%s'", name);
529
Rusty Russell2e04ef72009-07-30 16:03:45 -0600530 /*
531 * We map the initrd at the top of memory, but mmap wants it to be
532 * page-aligned, so we round the size up for that.
533 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700534 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000535 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600536 /*
537 * Once a file is mapped, you can close the file descriptor. It's a
538 * little odd, but quite useful.
539 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700540 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700541 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700542
543 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700544 return len;
545}
Rusty Russelle1e72962007-10-25 15:02:50 +1000546/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700547
Rusty Russell2e04ef72009-07-30 16:03:45 -0600548/*
549 * Simple routine to roll all the commandline arguments together with spaces
550 * between them.
551 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700552static void concat(char *dst, char *args[])
553{
554 unsigned int i, len = 0;
555
556 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100557 if (i) {
558 strcat(dst+len, " ");
559 len++;
560 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700561 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100562 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700563 }
564 /* In case it's empty. */
565 dst[len] = '\0';
566}
567
Rusty Russell2e04ef72009-07-30 16:03:45 -0600568/*L:185
569 * This is where we actually tell the kernel to initialize the Guest. We
Rusty Russelle1e72962007-10-25 15:02:50 +1000570 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300571 * the base of Guest "physical" memory, the top physical page to allow and the
Rusty Russell2e04ef72009-07-30 16:03:45 -0600572 * entry point for the Guest.
573 */
Rusty Russell56739c802009-06-12 22:26:59 -0600574static void tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700575{
Jes Sorensen511801d2007-10-22 11:03:31 +1000576 unsigned long args[] = { LHREQ_INITIALIZE,
577 (unsigned long)guest_base,
Rusty Russell7313d522015-02-11 15:15:10 +1030578 guest_limit / getpagesize(), start,
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030579 (guest_mmio+getpagesize()-1) / getpagesize() };
580 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
581 guest_base, guest_base + guest_limit,
582 guest_limit, guest_mmio);
Rusty Russell56739c802009-06-12 22:26:59 -0600583 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
584 if (write(lguest_fd, args, sizeof(args)) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700585 err(1, "Writing to /dev/lguest");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700586}
Rusty Russelldde79782007-07-26 10:41:03 -0700587/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700588
Rusty Russella91d74a2009-07-30 16:03:45 -0600589/*L:200
Rusty Russelldde79782007-07-26 10:41:03 -0700590 * Device Handling.
591 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000592 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700593 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000594 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700595 * if something funny is going on:
596 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700597static void *_check_pointer(unsigned long addr, unsigned int size,
598 unsigned int line)
599{
Rusty Russell2e04ef72009-07-30 16:03:45 -0600600 /*
Philip Sanderson5230ff02011-01-20 21:37:28 -0600601 * Check if the requested address and size exceeds the allocated memory,
602 * or addr + size wraps around.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600603 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600604 if ((addr + size) > guest_limit || (addr + size) < addr)
Rusty Russell17cbca22007-10-22 11:24:22 +1000605 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600606 /*
607 * We return a pointer for the caller's convenience, now we know it's
608 * safe to use.
609 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000610 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700611}
Rusty Russelldde79782007-07-26 10:41:03 -0700612/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700613#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
614
Rusty Russell2e04ef72009-07-30 16:03:45 -0600615/*
616 * Each buffer in the virtqueues is actually a chain of descriptors. This
Rusty Russelle1e72962007-10-25 15:02:50 +1000617 * function returns the next descriptor in the chain, or vq->vring.num if we're
Rusty Russell2e04ef72009-07-30 16:03:45 -0600618 * at the end.
619 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100620static unsigned next_desc(struct vring_desc *desc,
621 unsigned int i, unsigned int max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000622{
623 unsigned int next;
624
625 /* If this descriptor says it doesn't chain, we're done. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100626 if (!(desc[i].flags & VRING_DESC_F_NEXT))
627 return max;
Rusty Russell17cbca22007-10-22 11:24:22 +1000628
629 /* Check they're not leading us off end of descriptors. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100630 next = desc[i].next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000631 /* Make sure compiler knows to grab that: we don't want it changing! */
632 wmb();
633
Mark McLoughlind1f01322009-05-11 18:11:46 +0100634 if (next >= max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000635 errx(1, "Desc next is %u", next);
636
637 return next;
638}
639
Rusty Russella91d74a2009-07-30 16:03:45 -0600640/*
641 * This actually sends the interrupt for this virtqueue, if we've used a
642 * buffer.
643 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600644static void trigger_irq(struct virtqueue *vq)
645{
646 unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
647
Rusty Russell95c517c2009-06-12 22:27:11 -0600648 /* Don't inform them if nothing used. */
649 if (!vq->pending_used)
650 return;
651 vq->pending_used = 0;
652
Rusty Russellca60a422009-09-23 22:26:47 -0600653 /* If they don't want an interrupt, don't send one... */
654 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
Rusty Russell990c91f2011-05-30 11:14:12 -0600655 return;
Rusty Russellca60a422009-09-23 22:26:47 -0600656 }
Rusty Russell38bc2b82009-06-12 22:27:11 -0600657
658 /* Send the Guest an interrupt tell them we used something up. */
659 if (write(lguest_fd, buf, sizeof(buf)) != 0)
660 err(1, "Triggering irq %i", vq->config.irq);
661}
662
Rusty Russell2e04ef72009-07-30 16:03:45 -0600663/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600664 * This looks in the virtqueue for the first available buffer, and converts
Rusty Russell17cbca22007-10-22 11:24:22 +1000665 * it to an iovec for convenient access. Since descriptors consist of some
666 * number of output then some number of input descriptors, it's actually two
667 * iovecs, but we pack them into one and note how many of each there were.
668 *
Rusty Russella91d74a2009-07-30 16:03:45 -0600669 * This function waits if necessary, and returns the descriptor number found.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600670 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600671static unsigned wait_for_vq_desc(struct virtqueue *vq,
672 struct iovec iov[],
673 unsigned int *out_num, unsigned int *in_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000674{
Mark McLoughlind1f01322009-05-11 18:11:46 +0100675 unsigned int i, head, max;
676 struct vring_desc *desc;
Rusty Russell659a0e62009-06-12 22:27:10 -0600677 u16 last_avail = lg_last_avail(vq);
678
Rusty Russella91d74a2009-07-30 16:03:45 -0600679 /* There's nothing available? */
Rusty Russell659a0e62009-06-12 22:27:10 -0600680 while (last_avail == vq->vring.avail->idx) {
681 u64 event;
682
Rusty Russella91d74a2009-07-30 16:03:45 -0600683 /*
684 * Since we're about to sleep, now is a good time to tell the
685 * Guest about what we've used up to now.
686 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600687 trigger_irq(vq);
688
Rusty Russellb60da132009-06-12 22:27:12 -0600689 /* OK, now we need to know about added descriptors. */
690 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
691
Rusty Russell2e04ef72009-07-30 16:03:45 -0600692 /*
693 * They could have slipped one in as we were doing that: make
694 * sure it's written, then check again.
695 */
Rusty Russellb60da132009-06-12 22:27:12 -0600696 mb();
697 if (last_avail != vq->vring.avail->idx) {
698 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
699 break;
700 }
701
Rusty Russell659a0e62009-06-12 22:27:10 -0600702 /* Nothing new? Wait for eventfd to tell us they refilled. */
703 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
704 errx(1, "Event read failed?");
Rusty Russellb60da132009-06-12 22:27:12 -0600705
706 /* We don't need to be notified again. */
707 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russell659a0e62009-06-12 22:27:10 -0600708 }
Rusty Russell17cbca22007-10-22 11:24:22 +1000709
710 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500711 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000712 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500713 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000714
Rusty Russell8fd9a632013-07-02 15:35:13 +0930715 /*
716 * Make sure we read the descriptor number *after* we read the ring
717 * update; don't let the cpu or compiler change the order.
718 */
719 rmb();
720
Rusty Russell2e04ef72009-07-30 16:03:45 -0600721 /*
722 * Grab the next descriptor number they're advertising, and increment
723 * the index we've seen.
724 */
Rusty Russellb5111792008-07-29 09:58:34 -0500725 head = vq->vring.avail->ring[last_avail % vq->vring.num];
726 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000727
728 /* If their number is silly, that's a fatal mistake. */
729 if (head >= vq->vring.num)
730 errx(1, "Guest says index %u is available", head);
731
732 /* When we start there are none of either input nor output. */
733 *out_num = *in_num = 0;
734
Mark McLoughlind1f01322009-05-11 18:11:46 +0100735 max = vq->vring.num;
736 desc = vq->vring.desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000737 i = head;
Mark McLoughlind1f01322009-05-11 18:11:46 +0100738
Rusty Russell2e04ef72009-07-30 16:03:45 -0600739 /*
Rusty Russell8fd9a632013-07-02 15:35:13 +0930740 * We have to read the descriptor after we read the descriptor number,
741 * but there's a data dependency there so the CPU shouldn't reorder
742 * that: no rmb() required.
743 */
744
745 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -0600746 * If this is an indirect entry, then this buffer contains a descriptor
747 * table which we handle as if it's any normal descriptor chain.
748 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100749 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
750 if (desc[i].len % sizeof(struct vring_desc))
751 errx(1, "Invalid size for indirect buffer table");
752
753 max = desc[i].len / sizeof(struct vring_desc);
754 desc = check_pointer(desc[i].addr, desc[i].len);
755 i = 0;
756 }
757
Rusty Russell17cbca22007-10-22 11:24:22 +1000758 do {
759 /* Grab the first descriptor, and check it's OK. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100760 iov[*out_num + *in_num].iov_len = desc[i].len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000761 iov[*out_num + *in_num].iov_base
Mark McLoughlind1f01322009-05-11 18:11:46 +0100762 = check_pointer(desc[i].addr, desc[i].len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000763 /* If this is an input descriptor, increment that count. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100764 if (desc[i].flags & VRING_DESC_F_WRITE)
Rusty Russell17cbca22007-10-22 11:24:22 +1000765 (*in_num)++;
766 else {
Rusty Russell2e04ef72009-07-30 16:03:45 -0600767 /*
768 * If it's an output descriptor, they're all supposed
769 * to come before any input descriptors.
770 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000771 if (*in_num)
772 errx(1, "Descriptor has out after in");
773 (*out_num)++;
774 }
775
776 /* If we've got too many, that implies a descriptor loop. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100777 if (*out_num + *in_num > max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000778 errx(1, "Looped descriptor");
Mark McLoughlind1f01322009-05-11 18:11:46 +0100779 } while ((i = next_desc(desc, i, max)) != max);
Rusty Russell17cbca22007-10-22 11:24:22 +1000780
781 return head;
782}
783
Rusty Russell2e04ef72009-07-30 16:03:45 -0600784/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600785 * After we've used one of their buffers, we tell the Guest about it. Sometime
786 * later we'll want to send them an interrupt using trigger_irq(); note that
787 * wait_for_vq_desc() does that for us if it has to wait.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600788 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000789static void add_used(struct virtqueue *vq, unsigned int head, int len)
790{
791 struct vring_used_elem *used;
792
Rusty Russell2e04ef72009-07-30 16:03:45 -0600793 /*
794 * The virtqueue contains a ring of used buffers. Get a pointer to the
795 * next entry in that used ring.
796 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000797 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
798 used->id = head;
799 used->len = len;
800 /* Make sure buffer is written before we update index. */
801 wmb();
802 vq->vring.used->idx++;
Rusty Russell95c517c2009-06-12 22:27:11 -0600803 vq->pending_used++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000804}
805
Rusty Russell17cbca22007-10-22 11:24:22 +1000806/* And here's the combo meal deal. Supersize me! */
Rusty Russell56739c802009-06-12 22:26:59 -0600807static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
Rusty Russell17cbca22007-10-22 11:24:22 +1000808{
809 add_used(vq, head, len);
Rusty Russell56739c802009-06-12 22:26:59 -0600810 trigger_irq(vq);
Rusty Russell17cbca22007-10-22 11:24:22 +1000811}
812
Rusty Russelle1e72962007-10-25 15:02:50 +1000813/*
814 * The Console
815 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600816 * We associate some data with the console for our exit hack.
817 */
Rusty Russell1842f232009-07-30 16:03:46 -0600818struct console_abort {
Rusty Russelldde79782007-07-26 10:41:03 -0700819 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700820 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700821 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700822 struct timeval start;
823};
824
Rusty Russelldde79782007-07-26 10:41:03 -0700825/* This is the routine which handles console input (ie. stdin). */
Rusty Russell659a0e62009-06-12 22:27:10 -0600826static void console_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700827{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700828 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000829 unsigned int head, in_num, out_num;
Rusty Russell659a0e62009-06-12 22:27:10 -0600830 struct console_abort *abort = vq->dev->priv;
831 struct iovec iov[vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700832
Rusty Russella91d74a2009-07-30 16:03:45 -0600833 /* Make sure there's a descriptor available. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600834 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000835 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000836 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700837
Rusty Russella91d74a2009-07-30 16:03:45 -0600838 /* Read into it. This is where we usually wait. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600839 len = readv(STDIN_FILENO, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700840 if (len <= 0) {
Rusty Russell659a0e62009-06-12 22:27:10 -0600841 /* Ran out of input? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700842 warnx("Failed to get console input, ignoring console.");
Rusty Russell2e04ef72009-07-30 16:03:45 -0600843 /*
844 * For simplicity, dying threads kill the whole Launcher. So
845 * just nap here.
846 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600847 for (;;)
848 pause();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700849 }
850
Rusty Russella91d74a2009-07-30 16:03:45 -0600851 /* Tell the Guest we used a buffer. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600852 add_used_and_trigger(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700853
Rusty Russell2e04ef72009-07-30 16:03:45 -0600854 /*
855 * Three ^C within one second? Exit.
Rusty Russelldde79782007-07-26 10:41:03 -0700856 *
Rusty Russell659a0e62009-06-12 22:27:10 -0600857 * This is such a hack, but works surprisingly well. Each ^C has to
858 * be in a buffer by itself, so they can't be too fast. But we check
859 * that we get three within about a second, so they can't be too
Rusty Russell2e04ef72009-07-30 16:03:45 -0600860 * slow.
861 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600862 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700863 abort->count = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -0600864 return;
865 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700866
Rusty Russell659a0e62009-06-12 22:27:10 -0600867 abort->count++;
868 if (abort->count == 1)
869 gettimeofday(&abort->start, NULL);
870 else if (abort->count == 3) {
871 struct timeval now;
872 gettimeofday(&now, NULL);
873 /* Kill all Launcher processes with SIGINT, like normal ^C */
874 if (now.tv_sec <= abort->start.tv_sec+1)
875 kill(0, SIGINT);
876 abort->count = 0;
877 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700878}
879
Rusty Russell659a0e62009-06-12 22:27:10 -0600880/* This is the routine which handles console output (ie. stdout). */
881static void console_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700882{
Rusty Russell17cbca22007-10-22 11:24:22 +1000883 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000884 struct iovec iov[vq->vring.num];
885
Rusty Russella91d74a2009-07-30 16:03:45 -0600886 /* We usually wait in here, for the Guest to give us something. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600887 head = wait_for_vq_desc(vq, iov, &out, &in);
888 if (in)
889 errx(1, "Input buffers in console output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600890
891 /* writev can return a partial write, so we loop here. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600892 while (!iov_empty(iov, out)) {
893 int len = writev(STDOUT_FILENO, iov, out);
Sakari Ailuse0377e22011-06-26 19:36:46 +0300894 if (len <= 0) {
895 warn("Write to stdout gave %i (%d)", len, errno);
896 break;
897 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030898 iov_consume(iov, out, NULL, len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000899 }
Rusty Russella91d74a2009-07-30 16:03:45 -0600900
901 /*
902 * We're finished with that buffer: if we're going to sleep,
903 * wait_for_vq_desc() will prod the Guest with an interrupt.
904 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600905 add_used(vq, head, 0);
Rusty Russella1618832008-07-29 09:58:35 -0500906}
907
Rusty Russelle1e72962007-10-25 15:02:50 +1000908/*
909 * The Network
910 *
911 * Handling output for network is also simple: we get all the output buffers
Rusty Russell659a0e62009-06-12 22:27:10 -0600912 * and write them to /dev/net/tun.
Rusty Russella6bd8e12008-03-28 11:05:53 -0500913 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600914struct net_info {
915 int tunfd;
916};
917
918static void net_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700919{
Rusty Russell659a0e62009-06-12 22:27:10 -0600920 struct net_info *net_info = vq->dev->priv;
921 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000922 struct iovec iov[vq->vring.num];
923
Rusty Russella91d74a2009-07-30 16:03:45 -0600924 /* We usually wait in here for the Guest to give us a packet. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600925 head = wait_for_vq_desc(vq, iov, &out, &in);
926 if (in)
927 errx(1, "Input buffers in net output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600928 /*
929 * Send the whole thing through to /dev/net/tun. It expects the exact
930 * same format: what a coincidence!
931 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600932 if (writev(net_info->tunfd, iov, out) < 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +0300933 warnx("Write to tun failed (%d)?", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -0600934
935 /*
936 * Done with that one; wait_for_vq_desc() will send the interrupt if
937 * all packets are processed.
938 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600939 add_used(vq, head, 0);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700940}
941
Rusty Russella91d74a2009-07-30 16:03:45 -0600942/*
943 * Handling network input is a bit trickier, because I've tried to optimize it.
944 *
945 * First we have a helper routine which tells is if from this file descriptor
946 * (ie. the /dev/net/tun device) will block:
947 */
Rusty Russell4a8962e2009-06-12 22:27:12 -0600948static bool will_block(int fd)
949{
950 fd_set fdset;
951 struct timeval zero = { 0, 0 };
952 FD_ZERO(&fdset);
953 FD_SET(fd, &fdset);
954 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
955}
956
Rusty Russella91d74a2009-07-30 16:03:45 -0600957/*
958 * This handles packets coming in from the tun device to our Guest. Like all
959 * service routines, it gets called again as soon as it returns, so you don't
960 * see a while(1) loop here.
961 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600962static void net_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700963{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700964 int len;
Rusty Russell659a0e62009-06-12 22:27:10 -0600965 unsigned int head, out, in;
966 struct iovec iov[vq->vring.num];
967 struct net_info *net_info = vq->dev->priv;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700968
Rusty Russella91d74a2009-07-30 16:03:45 -0600969 /*
970 * Get a descriptor to write an incoming packet into. This will also
971 * send an interrupt if they're out of descriptors.
972 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600973 head = wait_for_vq_desc(vq, iov, &out, &in);
974 if (out)
975 errx(1, "Output buffers in net input queue?");
Rusty Russell4a8962e2009-06-12 22:27:12 -0600976
Rusty Russella91d74a2009-07-30 16:03:45 -0600977 /*
978 * If it looks like we'll block reading from the tun device, send them
979 * an interrupt.
980 */
Rusty Russell4a8962e2009-06-12 22:27:12 -0600981 if (vq->pending_used && will_block(net_info->tunfd))
982 trigger_irq(vq);
983
Rusty Russella91d74a2009-07-30 16:03:45 -0600984 /*
985 * Read in the packet. This is where we normally wait (when there's no
986 * incoming network traffic).
987 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600988 len = readv(net_info->tunfd, iov, in);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700989 if (len <= 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +0300990 warn("Failed to read from tun (%d).", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -0600991
992 /*
993 * Mark that packet buffer as used, but don't interrupt here. We want
994 * to wait until we've done as much work as we can.
995 */
Rusty Russell4a8962e2009-06-12 22:27:12 -0600996 add_used(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700997}
Rusty Russella91d74a2009-07-30 16:03:45 -0600998/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700999
Rusty Russella91d74a2009-07-30 16:03:45 -06001000/* This is the helper to create threads: run the service routine in a loop. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001001static int do_thread(void *_vq)
Rusty Russell56ae43d2007-10-22 11:24:23 +10001002{
Rusty Russell659a0e62009-06-12 22:27:10 -06001003 struct virtqueue *vq = _vq;
1004
1005 for (;;)
1006 vq->service(vq);
1007 return 0;
Rusty Russell56ae43d2007-10-22 11:24:23 +10001008}
1009
Rusty Russell2e04ef72009-07-30 16:03:45 -06001010/*
1011 * When a child dies, we kill our entire process group with SIGTERM. This
1012 * also has the side effect that the shell restores the console for us!
1013 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001014static void kill_launcher(int signal)
Rusty Russell5dae7852008-07-29 09:58:35 -05001015{
Rusty Russell659a0e62009-06-12 22:27:10 -06001016 kill(0, SIGTERM);
1017}
1018
1019static void reset_device(struct device *dev)
1020{
1021 struct virtqueue *vq;
1022
1023 verbose("Resetting device %s\n", dev->name);
1024
1025 /* Clear any features they've acked. */
1026 memset(get_feature_bits(dev) + dev->feature_len, 0, dev->feature_len);
1027
1028 /* We're going to be explicitly killing threads, so ignore them. */
1029 signal(SIGCHLD, SIG_IGN);
1030
1031 /* Zero out the virtqueues, get rid of their threads */
1032 for (vq = dev->vq; vq; vq = vq->next) {
1033 if (vq->thread != (pid_t)-1) {
1034 kill(vq->thread, SIGTERM);
1035 waitpid(vq->thread, NULL, 0);
1036 vq->thread = (pid_t)-1;
1037 }
1038 memset(vq->vring.desc, 0,
1039 vring_size(vq->config.num, LGUEST_VRING_ALIGN));
1040 lg_last_avail(vq) = 0;
1041 }
1042 dev->running = false;
1043
1044 /* Now we care if threads die. */
1045 signal(SIGCHLD, (void *)kill_launcher);
1046}
1047
Rusty Russella91d74a2009-07-30 16:03:45 -06001048/*L:216
1049 * This actually creates the thread which services the virtqueue for a device.
1050 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001051static void create_thread(struct virtqueue *vq)
1052{
Rusty Russell2e04ef72009-07-30 16:03:45 -06001053 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06001054 * Create stack for thread. Since the stack grows upwards, we point
1055 * the stack pointer to the end of this region.
Rusty Russell2e04ef72009-07-30 16:03:45 -06001056 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001057 char *stack = malloc(32768);
1058 unsigned long args[] = { LHREQ_EVENTFD,
1059 vq->config.pfn*getpagesize(), 0 };
1060
1061 /* Create a zero-initialized eventfd. */
1062 vq->eventfd = eventfd(0, 0);
1063 if (vq->eventfd < 0)
1064 err(1, "Creating eventfd");
1065 args[2] = vq->eventfd;
1066
Rusty Russella91d74a2009-07-30 16:03:45 -06001067 /*
1068 * Attach an eventfd to this virtqueue: it will go off when the Guest
1069 * does an LHCALL_NOTIFY for this vq.
1070 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001071 if (write(lguest_fd, &args, sizeof(args)) != 0)
1072 err(1, "Attaching eventfd");
1073
Rusty Russella91d74a2009-07-30 16:03:45 -06001074 /*
1075 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1076 * we get a signal if it dies.
1077 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001078 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1079 if (vq->thread == (pid_t)-1)
1080 err(1, "Creating clone");
Rusty Russella91d74a2009-07-30 16:03:45 -06001081
1082 /* We close our local copy now the child has it. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001083 close(vq->eventfd);
1084}
1085
1086static void start_device(struct device *dev)
1087{
1088 unsigned int i;
1089 struct virtqueue *vq;
1090
1091 verbose("Device %s OK: offered", dev->name);
1092 for (i = 0; i < dev->feature_len; i++)
1093 verbose(" %02x", get_feature_bits(dev)[i]);
1094 verbose(", accepted");
1095 for (i = 0; i < dev->feature_len; i++)
1096 verbose(" %02x", get_feature_bits(dev)
1097 [dev->feature_len+i]);
1098
1099 for (vq = dev->vq; vq; vq = vq->next) {
1100 if (vq->service)
1101 create_thread(vq);
1102 }
1103 dev->running = true;
1104}
1105
1106static void cleanup_devices(void)
1107{
1108 struct device *dev;
1109
1110 for (dev = devices.dev; dev; dev = dev->next)
1111 reset_device(dev);
1112
1113 /* If we saved off the original terminal settings, restore them now. */
1114 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1115 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
Rusty Russell5dae7852008-07-29 09:58:35 -05001116}
1117
Rusty Russella007a752008-05-02 21:50:53 -05001118/* When the Guest tells us they updated the status field, we handle it. */
1119static void update_device_status(struct device *dev)
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001120{
Rusty Russell659a0e62009-06-12 22:27:10 -06001121 /* A zero status is a reset, otherwise it's a set of flags. */
1122 if (dev->desc->status == 0)
1123 reset_device(dev);
1124 else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
Rusty Russella007a752008-05-02 21:50:53 -05001125 warnx("Device %s configuration FAILED", dev->name);
Rusty Russell659a0e62009-06-12 22:27:10 -06001126 if (dev->running)
1127 reset_device(dev);
Rusty Russell3c3ed482011-07-22 14:39:49 +09301128 } else {
1129 if (dev->running)
1130 err(1, "Device %s features finalized twice", dev->name);
1131 start_device(dev);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001132 }
1133}
1134
Rusty Russella91d74a2009-07-30 16:03:45 -06001135/*L:215
1136 * This is the generic routine we call when the Guest uses LHCALL_NOTIFY. In
1137 * particular, it's used to notify us of device status changes during boot.
1138 */
Rusty Russell56739c802009-06-12 22:26:59 -06001139static void handle_output(unsigned long addr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001140{
1141 struct device *i;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001142
Rusty Russell659a0e62009-06-12 22:27:10 -06001143 /* Check each device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001144 for (i = devices.dev; i; i = i->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001145 struct virtqueue *vq;
1146
Rusty Russella91d74a2009-07-30 16:03:45 -06001147 /*
1148 * Notifications to device descriptors mean they updated the
1149 * device status.
1150 */
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001151 if (from_guest_phys(addr) == i->desc) {
Rusty Russella007a752008-05-02 21:50:53 -05001152 update_device_status(i);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001153 return;
1154 }
1155
Rusty Russell3c3ed482011-07-22 14:39:49 +09301156 /* Devices should not be used before features are finalized. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001157 for (vq = i->vq; vq; vq = vq->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001158 if (addr != vq->config.pfn*getpagesize())
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001159 continue;
Rusty Russell3c3ed482011-07-22 14:39:49 +09301160 errx(1, "Notification on %s before setup!", i->name);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001161 }
1162 }
Rusty Russelldde79782007-07-26 10:41:03 -07001163
Rusty Russell2e04ef72009-07-30 16:03:45 -06001164 /*
1165 * Early console write is done using notify on a nul-terminated string
1166 * in Guest memory. It's also great for hacking debugging messages
1167 * into a Guest.
1168 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001169 if (addr >= guest_limit)
1170 errx(1, "Bad NOTIFY %#lx", addr);
1171
1172 write(STDOUT_FILENO, from_guest_phys(addr),
1173 strnlen(from_guest_phys(addr), guest_limit - addr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001174}
1175
Rusty Russellc565650b2015-02-11 15:15:10 +10301176/*L:216
1177 * This is where we emulate a handful of Guest instructions. It's ugly
1178 * and we used to do it in the kernel but it grew over time.
1179 */
1180
1181/*
1182 * We use the ptrace syscall's pt_regs struct to talk about registers
1183 * to lguest: these macros convert the names to the offsets.
1184 */
1185#define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1186#define setreg(name, val) \
1187 setreg_off(offsetof(struct user_regs_struct, name), (val))
1188
1189static u32 getreg_off(size_t offset)
1190{
1191 u32 r;
1192 unsigned long args[] = { LHREQ_GETREG, offset };
1193
1194 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1195 err(1, "Getting register %u", offset);
1196 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1197 err(1, "Reading register %u", offset);
1198
1199 return r;
1200}
1201
1202static void setreg_off(size_t offset, u32 val)
1203{
1204 unsigned long args[] = { LHREQ_SETREG, offset, val };
1205
1206 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1207 err(1, "Setting register %u", offset);
1208}
1209
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301210/* Get register by instruction encoding */
1211static u32 getreg_num(unsigned regnum, u32 mask)
1212{
1213 /* 8 bit ops use regnums 4-7 for high parts of word */
1214 if (mask == 0xFF && (regnum & 0x4))
1215 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1216
1217 switch (regnum) {
1218 case 0: return getreg(eax) & mask;
1219 case 1: return getreg(ecx) & mask;
1220 case 2: return getreg(edx) & mask;
1221 case 3: return getreg(ebx) & mask;
1222 case 4: return getreg(esp) & mask;
1223 case 5: return getreg(ebp) & mask;
1224 case 6: return getreg(esi) & mask;
1225 case 7: return getreg(edi) & mask;
1226 }
1227 abort();
1228}
1229
1230/* Set register by instruction encoding */
1231static void setreg_num(unsigned regnum, u32 val, u32 mask)
1232{
1233 /* Don't try to set bits out of range */
1234 assert(~(val & ~mask));
1235
1236 /* 8 bit ops use regnums 4-7 for high parts of word */
1237 if (mask == 0xFF && (regnum & 0x4)) {
1238 /* Construct the 16 bits we want. */
1239 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1240 setreg_num(regnum & 0x3, val, 0xFFFF);
1241 return;
1242 }
1243
1244 switch (regnum) {
1245 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1246 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1247 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1248 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1249 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1250 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1251 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1252 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1253 }
1254 abort();
1255}
1256
1257/* Get bytes of displacement appended to instruction, from r/m encoding */
1258static u32 insn_displacement_len(u8 mod_reg_rm)
1259{
1260 /* Switch on the mod bits */
1261 switch (mod_reg_rm >> 6) {
1262 case 0:
1263 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1264 if ((mod_reg_rm & 0x7) == 0x5)
1265 return 2;
1266 /* Normally, mod == 0 means no literal displacement */
1267 return 0;
1268 case 1:
1269 /* One byte displacement */
1270 return 1;
1271 case 2:
1272 /* Four byte displacement */
1273 return 4;
1274 case 3:
1275 /* Register mode */
1276 return 0;
1277 }
1278 abort();
1279}
1280
Rusty Russellc565650b2015-02-11 15:15:10 +10301281static void emulate_insn(const u8 insn[])
1282{
1283 unsigned long args[] = { LHREQ_TRAP, 13 };
1284 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1285 unsigned int eax, port, mask;
1286 /*
1287 * We always return all-ones on IO port reads, which traditionally
1288 * means "there's nothing there".
1289 */
1290 u32 val = 0xFFFFFFFF;
1291
1292 /*
1293 * This must be the Guest kernel trying to do something, not userspace!
1294 * The bottom two bits of the CS segment register are the privilege
1295 * level.
1296 */
1297 if ((getreg(xcs) & 3) != 0x1)
1298 goto no_emulate;
1299
1300 /* Decoding x86 instructions is icky. */
1301
1302 /*
1303 * Around 2.6.33, the kernel started using an emulation for the
1304 * cmpxchg8b instruction in early boot on many configurations. This
1305 * code isn't paravirtualized, and it tries to disable interrupts.
1306 * Ignore it, which will Mostly Work.
1307 */
1308 if (insn[insnlen] == 0xfa) {
1309 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1310 insnlen = 1;
1311 goto skip_insn;
1312 }
1313
1314 /*
1315 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1316 */
1317 if (insn[insnlen] == 0x66) {
1318 small_operand = 1;
1319 /* The instruction is 1 byte so far, read the next byte. */
1320 insnlen = 1;
1321 }
1322
1323 /* If the lower bit isn't set, it's a single byte access */
1324 byte_access = !(insn[insnlen] & 1);
1325
1326 /*
1327 * Now we can ignore the lower bit and decode the 4 opcodes
1328 * we need to emulate.
1329 */
1330 switch (insn[insnlen] & 0xFE) {
1331 case 0xE4: /* in <next byte>,%al */
1332 port = insn[insnlen+1];
1333 insnlen += 2;
1334 in = 1;
1335 break;
1336 case 0xEC: /* in (%dx),%al */
1337 port = getreg(edx) & 0xFFFF;
1338 insnlen += 1;
1339 in = 1;
1340 break;
1341 case 0xE6: /* out %al,<next byte> */
1342 port = insn[insnlen+1];
1343 insnlen += 2;
1344 break;
1345 case 0xEE: /* out %al,(%dx) */
1346 port = getreg(edx) & 0xFFFF;
1347 insnlen += 1;
1348 break;
1349 default:
1350 /* OK, we don't know what this is, can't emulate. */
1351 goto no_emulate;
1352 }
1353
1354 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1355 if (byte_access)
1356 mask = 0xFF;
1357 else if (small_operand)
1358 mask = 0xFFFF;
1359 else
1360 mask = 0xFFFFFFFF;
1361
Rusty Russell48fd6b72015-02-11 15:15:10 +10301362 /* This is the PS/2 keyboard status; 1 means ready for output */
1363 if (port == 0x64)
1364 val = 1;
1365
Rusty Russellc565650b2015-02-11 15:15:10 +10301366 /*
1367 * If it was an "IN" instruction, they expect the result to be read
1368 * into %eax, so we change %eax.
1369 */
1370 eax = getreg(eax);
1371
1372 if (in) {
1373 /* Clear the bits we're about to read */
1374 eax &= ~mask;
1375 /* Copy bits in from val. */
1376 eax |= val & mask;
1377 /* Now update the register. */
1378 setreg(eax, eax);
1379 }
1380
1381 verbose("IO %s of %x to %u: %#08x\n",
1382 in ? "IN" : "OUT", mask, port, eax);
1383skip_insn:
1384 /* Finally, we've "done" the instruction, so move past it. */
1385 setreg(eip, getreg(eip) + insnlen);
1386 return;
1387
1388no_emulate:
1389 /* Inject trap into Guest. */
1390 if (write(lguest_fd, args, sizeof(args)) < 0)
1391 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1392}
1393
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301394static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1395{
1396 unsigned int i;
1397
1398 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1399 struct device *d = devices.pci[i];
1400
1401 if (!d)
1402 continue;
1403 if (paddr < d->mmio_addr)
1404 continue;
1405 if (paddr >= d->mmio_addr + d->mmio_size)
1406 continue;
1407 *off = paddr - d->mmio_addr;
1408 return d;
1409 }
1410 return NULL;
1411}
1412
1413static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1414{
1415}
1416
1417static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
1418{
1419 return 0xFFFFFFFF;
1420}
1421
1422static void emulate_mmio(unsigned long paddr, const u8 *insn)
1423{
1424 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
1425 struct device *d = find_mmio_region(paddr, &off);
1426 unsigned long args[] = { LHREQ_TRAP, 14 };
1427
1428 if (!d) {
1429 warnx("MMIO touching %#08lx (not a device)", paddr);
1430 goto reinject;
1431 }
1432
1433 /* Prefix makes it a 16 bit op */
1434 if (insn[0] == 0x66) {
1435 mask = 0xFFFF;
1436 insnlen++;
1437 }
1438
1439 /* iowrite */
1440 if (insn[insnlen] == 0x89) {
1441 /* Next byte is r/m byte: bits 3-5 are register. */
1442 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
1443 emulate_mmio_write(d, off, val, mask);
1444 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1445 } else if (insn[insnlen] == 0x8b) { /* ioread */
1446 /* Next byte is r/m byte: bits 3-5 are register. */
1447 val = emulate_mmio_read(d, off, mask);
1448 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
1449 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1450 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
1451 mask = 0xff;
1452 /* Next byte is r/m byte: bits 3-5 are register. */
1453 val = getreg_num((insn[1] >> 3) & 0x7, mask);
1454 emulate_mmio_write(d, off, val, mask);
1455 insnlen = 2 + insn_displacement_len(insn[1]);
1456 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
1457 mask = 0xff;
1458 val = emulate_mmio_read(d, off, mask);
1459 setreg_num((insn[1] >> 3) & 0x7, val, mask);
1460 insnlen = 2 + insn_displacement_len(insn[1]);
1461 } else {
1462 warnx("Unknown MMIO instruction touching %#08lx:"
1463 " %02x %02x %02x %02x at %u",
1464 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
1465 reinject:
1466 /* Inject trap into Guest. */
1467 if (write(lguest_fd, args, sizeof(args)) < 0)
1468 err(1, "Reinjecting trap 14 for fault at %#x",
1469 getreg(eip));
1470 return;
1471 }
1472
1473 /* Finally, we've "done" the instruction, so move past it. */
1474 setreg(eip, getreg(eip) + insnlen);
1475}
Rusty Russellc565650b2015-02-11 15:15:10 +10301476
Rusty Russelldde79782007-07-26 10:41:03 -07001477/*L:190
1478 * Device Setup
1479 *
1480 * All devices need a descriptor so the Guest knows it exists, and a "struct
1481 * device" so the Launcher can keep track of it. We have common helper
Rusty Russella6bd8e12008-03-28 11:05:53 -05001482 * routines to allocate and manage them.
1483 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001484
Rusty Russell2e04ef72009-07-30 16:03:45 -06001485/*
1486 * The layout of the device page is a "struct lguest_device_desc" followed by a
Rusty Russella586d4f2008-02-04 23:49:56 -05001487 * number of virtqueue descriptors, then two sets of feature bits, then an
1488 * array of configuration bytes. This routine returns the configuration
Rusty Russell2e04ef72009-07-30 16:03:45 -06001489 * pointer.
1490 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001491static u8 *device_config(const struct device *dev)
1492{
1493 return (void *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -06001494 + dev->num_vq * sizeof(struct lguest_vqconfig)
1495 + dev->feature_len * 2;
Rusty Russella586d4f2008-02-04 23:49:56 -05001496}
1497
Rusty Russell2e04ef72009-07-30 16:03:45 -06001498/*
1499 * This routine allocates a new "struct lguest_device_desc" from descriptor
Rusty Russella586d4f2008-02-04 23:49:56 -05001500 * table page just above the Guest's normal memory. It returns a pointer to
Rusty Russell2e04ef72009-07-30 16:03:45 -06001501 * that descriptor.
1502 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001503static struct lguest_device_desc *new_dev_desc(u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001504{
Rusty Russella586d4f2008-02-04 23:49:56 -05001505 struct lguest_device_desc d = { .type = type };
1506 void *p;
1507
1508 /* Figure out where the next device config is, based on the last one. */
1509 if (devices.lastdev)
1510 p = device_config(devices.lastdev)
1511 + devices.lastdev->desc->config_len;
1512 else
1513 p = devices.descpage;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001514
Rusty Russell17cbca22007-10-22 11:24:22 +10001515 /* We only have one page for all the descriptors. */
Rusty Russella586d4f2008-02-04 23:49:56 -05001516 if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
Rusty Russell17cbca22007-10-22 11:24:22 +10001517 errx(1, "Too many devices");
1518
Rusty Russella586d4f2008-02-04 23:49:56 -05001519 /* p might not be aligned, so we memcpy in. */
1520 return memcpy(p, &d, sizeof(d));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001521}
1522
Rusty Russell2e04ef72009-07-30 16:03:45 -06001523/*
1524 * Each device descriptor is followed by the description of its virtqueues. We
1525 * specify how many descriptors the virtqueue is to have.
1526 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001527static void add_virtqueue(struct device *dev, unsigned int num_descs,
Rusty Russell659a0e62009-06-12 22:27:10 -06001528 void (*service)(struct virtqueue *))
Rusty Russell17cbca22007-10-22 11:24:22 +10001529{
1530 unsigned int pages;
1531 struct virtqueue **i, *vq = malloc(sizeof(*vq));
1532 void *p;
1533
Rusty Russella6bd8e12008-03-28 11:05:53 -05001534 /* First we need some memory for this virtqueue. */
Rusty Russell2966af72008-12-30 09:25:58 -06001535 pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
Rusty Russell42b36cc2007-11-12 13:39:18 +11001536 / getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10001537 p = get_pages(pages);
1538
Rusty Russelld1c856e2007-11-19 11:20:40 -05001539 /* Initialize the virtqueue */
1540 vq->next = NULL;
1541 vq->last_avail_idx = 0;
1542 vq->dev = dev;
Rusty Russella91d74a2009-07-30 16:03:45 -06001543
1544 /*
1545 * This is the routine the service thread will run, and its Process ID
1546 * once it's running.
1547 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001548 vq->service = service;
1549 vq->thread = (pid_t)-1;
Rusty Russelld1c856e2007-11-19 11:20:40 -05001550
Rusty Russell17cbca22007-10-22 11:24:22 +10001551 /* Initialize the configuration. */
1552 vq->config.num = num_descs;
1553 vq->config.irq = devices.next_irq++;
1554 vq->config.pfn = to_guest_phys(p) / getpagesize();
1555
1556 /* Initialize the vring. */
Rusty Russell2966af72008-12-30 09:25:58 -06001557 vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
Rusty Russell17cbca22007-10-22 11:24:22 +10001558
Rusty Russell2e04ef72009-07-30 16:03:45 -06001559 /*
1560 * Append virtqueue to this device's descriptor. We use
Rusty Russella586d4f2008-02-04 23:49:56 -05001561 * device_config() to get the end of the device's current virtqueues;
1562 * we check that we haven't added any config or feature information
Rusty Russell2e04ef72009-07-30 16:03:45 -06001563 * yet, otherwise we'd be overwriting them.
1564 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001565 assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
1566 memcpy(device_config(dev), &vq->config, sizeof(vq->config));
Rusty Russell713b15b2009-06-12 22:26:58 -06001567 dev->num_vq++;
Rusty Russella586d4f2008-02-04 23:49:56 -05001568 dev->desc->num_vq++;
1569
1570 verbose("Virtqueue page %#lx\n", to_guest_phys(p));
Rusty Russell17cbca22007-10-22 11:24:22 +10001571
Rusty Russell2e04ef72009-07-30 16:03:45 -06001572 /*
1573 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
1574 * second.
1575 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001576 for (i = &dev->vq; *i; i = &(*i)->next);
1577 *i = vq;
Rusty Russell17cbca22007-10-22 11:24:22 +10001578}
1579
Rusty Russell2e04ef72009-07-30 16:03:45 -06001580/*
1581 * The first half of the feature bitmask is for us to advertise features. The
1582 * second half is for the Guest to accept features.
1583 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001584static void add_feature(struct device *dev, unsigned bit)
1585{
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001586 u8 *features = get_feature_bits(dev);
Rusty Russella586d4f2008-02-04 23:49:56 -05001587
1588 /* We can't extend the feature bits once we've added config bytes */
1589 if (dev->desc->feature_len <= bit / CHAR_BIT) {
1590 assert(dev->desc->config_len == 0);
Rusty Russell713b15b2009-06-12 22:26:58 -06001591 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
Rusty Russella586d4f2008-02-04 23:49:56 -05001592 }
1593
Rusty Russella586d4f2008-02-04 23:49:56 -05001594 features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
1595}
1596
Rusty Russell2e04ef72009-07-30 16:03:45 -06001597/*
1598 * This routine sets the configuration fields for an existing device's
Rusty Russella586d4f2008-02-04 23:49:56 -05001599 * descriptor. It only works for the last device, but that's OK because that's
Rusty Russell2e04ef72009-07-30 16:03:45 -06001600 * how we use it.
1601 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001602static void set_config(struct device *dev, unsigned len, const void *conf)
1603{
1604 /* Check we haven't overflowed our single page. */
1605 if (device_config(dev) + len > devices.descpage + getpagesize())
1606 errx(1, "Too many devices");
1607
1608 /* Copy in the config information, and store the length. */
1609 memcpy(device_config(dev), conf, len);
1610 dev->desc->config_len = len;
Rusty Russell8ef562d2009-07-30 16:03:43 -06001611
1612 /* Size must fit in config_len field (8 bits)! */
1613 assert(dev->desc->config_len == len);
Rusty Russella586d4f2008-02-04 23:49:56 -05001614}
1615
Rusty Russell2e04ef72009-07-30 16:03:45 -06001616/*
1617 * This routine does all the creation and setup of a new device, including
Rusty Russella91d74a2009-07-30 16:03:45 -06001618 * calling new_dev_desc() to allocate the descriptor and device memory. We
1619 * don't actually start the service threads until later.
Rusty Russella6bd8e12008-03-28 11:05:53 -05001620 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06001621 * See what I mean about userspace being boring?
1622 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001623static struct device *new_device(const char *name, u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001624{
1625 struct device *dev = malloc(sizeof(*dev));
1626
Rusty Russelldde79782007-07-26 10:41:03 -07001627 /* Now we populate the fields one at a time. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001628 dev->desc = new_dev_desc(type);
Rusty Russell17cbca22007-10-22 11:24:22 +10001629 dev->name = name;
Rusty Russelld1c856e2007-11-19 11:20:40 -05001630 dev->vq = NULL;
Rusty Russell713b15b2009-06-12 22:26:58 -06001631 dev->feature_len = 0;
1632 dev->num_vq = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06001633 dev->running = false;
Rusty Russellca16f582012-10-04 12:03:25 +09301634 dev->next = NULL;
Rusty Russella586d4f2008-02-04 23:49:56 -05001635
Rusty Russell2e04ef72009-07-30 16:03:45 -06001636 /*
1637 * Append to device list. Prepending to a single-linked list is
Rusty Russella586d4f2008-02-04 23:49:56 -05001638 * easier, but the user expects the devices to be arranged on the bus
1639 * in command-line order. The first network device on the command line
Rusty Russell2e04ef72009-07-30 16:03:45 -06001640 * is eth0, the first block device /dev/vda, etc.
1641 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001642 if (devices.lastdev)
1643 devices.lastdev->next = dev;
1644 else
1645 devices.dev = dev;
1646 devices.lastdev = dev;
1647
Rusty Russell8ca47e02007-07-19 01:49:29 -07001648 return dev;
1649}
1650
Rusty Russell2e04ef72009-07-30 16:03:45 -06001651/*
1652 * Our first setup routine is the console. It's a fairly simple device, but
1653 * UNIX tty handling makes it uglier than it could be.
1654 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001655static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001656{
1657 struct device *dev;
1658
Rusty Russelldde79782007-07-26 10:41:03 -07001659 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001660 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1661 struct termios term = orig_term;
Rusty Russell2e04ef72009-07-30 16:03:45 -06001662 /*
1663 * Then we turn off echo, line buffering and ^C etc: We want a
1664 * raw input stream to the Guest.
1665 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001666 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1667 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001668 }
1669
Rusty Russell659a0e62009-06-12 22:27:10 -06001670 dev = new_device("console", VIRTIO_ID_CONSOLE);
1671
Rusty Russelldde79782007-07-26 10:41:03 -07001672 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001673 dev->priv = malloc(sizeof(struct console_abort));
1674 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001675
Rusty Russell2e04ef72009-07-30 16:03:45 -06001676 /*
1677 * The console needs two virtqueues: the input then the output. When
Rusty Russell56ae43d2007-10-22 11:24:23 +10001678 * they put something the input queue, we make sure we're listening to
1679 * stdin. When they put something in the output queue, we write it to
Rusty Russell2e04ef72009-07-30 16:03:45 -06001680 * stdout.
1681 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001682 add_virtqueue(dev, VIRTQUEUE_NUM, console_input);
1683 add_virtqueue(dev, VIRTQUEUE_NUM, console_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001684
Rusty Russell659a0e62009-06-12 22:27:10 -06001685 verbose("device %u: console\n", ++devices.device_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001686}
Rusty Russelldde79782007-07-26 10:41:03 -07001687/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001688
Rusty Russell2e04ef72009-07-30 16:03:45 -06001689/*M:010
1690 * Inter-guest networking is an interesting area. Simplest is to have a
Rusty Russell17cbca22007-10-22 11:24:22 +10001691 * --sharenet=<name> option which opens or creates a named pipe. This can be
1692 * used to send packets to another guest in a 1:1 manner.
1693 *
Rusty Russell9f542882011-07-22 14:39:50 +09301694 * More sophisticated is to use one of the tools developed for project like UML
Rusty Russell17cbca22007-10-22 11:24:22 +10001695 * to do networking.
1696 *
1697 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
1698 * completely generic ("here's my vring, attach to your vring") and would work
1699 * for any traffic. Of course, namespace and permissions issues need to be
1700 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
1701 * multiple inter-guest channels behind one interface, although it would
1702 * require some manner of hotplugging new virtio channels.
1703 *
Rusty Russell9f542882011-07-22 14:39:50 +09301704 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
Rusty Russell2e04ef72009-07-30 16:03:45 -06001705:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10001706
Rusty Russell8ca47e02007-07-19 01:49:29 -07001707static u32 str2ip(const char *ipaddr)
1708{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001709 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07001710
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001711 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
1712 errx(1, "Failed to parse IP address '%s'", ipaddr);
1713 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
1714}
1715
1716static void str2mac(const char *macaddr, unsigned char mac[6])
1717{
1718 unsigned int m[6];
1719 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
1720 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
1721 errx(1, "Failed to parse mac address '%s'", macaddr);
1722 mac[0] = m[0];
1723 mac[1] = m[1];
1724 mac[2] = m[2];
1725 mac[3] = m[3];
1726 mac[4] = m[4];
1727 mac[5] = m[5];
Rusty Russell8ca47e02007-07-19 01:49:29 -07001728}
1729
Rusty Russell2e04ef72009-07-30 16:03:45 -06001730/*
1731 * This code is "adapted" from libbridge: it attaches the Host end of the
Rusty Russelldde79782007-07-26 10:41:03 -07001732 * network device to the bridge device specified by the command line.
1733 *
1734 * This is yet another James Morris contribution (I'm an IP-level guy, so I
Rusty Russell2e04ef72009-07-30 16:03:45 -06001735 * dislike bridging), and I just try not to break it.
1736 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001737static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1738{
1739 int ifidx;
1740 struct ifreq ifr;
1741
1742 if (!*br_name)
1743 errx(1, "must specify bridge name");
1744
1745 ifidx = if_nametoindex(if_name);
1746 if (!ifidx)
1747 errx(1, "interface %s does not exist!", if_name);
1748
1749 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001750 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07001751 ifr.ifr_ifindex = ifidx;
1752 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1753 err(1, "can't add %s to bridge %s", if_name, br_name);
1754}
1755
Rusty Russell2e04ef72009-07-30 16:03:45 -06001756/*
1757 * This sets up the Host end of the network device with an IP address, brings
Rusty Russelldde79782007-07-26 10:41:03 -07001758 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell2e04ef72009-07-30 16:03:45 -06001759 * pointer.
1760 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001761static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001762{
1763 struct ifreq ifr;
Rusty Russellf8466192010-08-27 08:39:48 -06001764 struct sockaddr_in sin;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001765
1766 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001767 strcpy(ifr.ifr_name, tapif);
1768
1769 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russellf8466192010-08-27 08:39:48 -06001770 sin.sin_family = AF_INET;
1771 sin.sin_addr.s_addr = htonl(ipaddr);
1772 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001773 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001774 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001775 ifr.ifr_flags = IFF_UP;
1776 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001777 err(1, "Bringing interface %s up", tapif);
1778}
1779
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001780static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07001781{
Rusty Russell8ca47e02007-07-19 01:49:29 -07001782 struct ifreq ifr;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001783 int netfd;
1784
1785 /* Start with this zeroed. Messy but sure. */
1786 memset(&ifr, 0, sizeof(ifr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001787
Rusty Russell2e04ef72009-07-30 16:03:45 -06001788 /*
1789 * We open the /dev/net/tun device and tell it we want a tap device. A
Rusty Russelldde79782007-07-26 10:41:03 -07001790 * tap device is like a tun device, only somehow different. To tell
1791 * the truth, I completely blundered my way through this code, but it
Rusty Russell2e04ef72009-07-30 16:03:45 -06001792 * works now!
1793 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001794 netfd = open_or_die("/dev/net/tun", O_RDWR);
Rusty Russell398f1872008-07-29 09:58:37 -05001795 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001796 strcpy(ifr.ifr_name, "tap%d");
1797 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1798 err(1, "configuring /dev/net/tun");
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001799
Rusty Russell398f1872008-07-29 09:58:37 -05001800 if (ioctl(netfd, TUNSETOFFLOAD,
1801 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
1802 err(1, "Could not set features for tun device");
1803
Rusty Russell2e04ef72009-07-30 16:03:45 -06001804 /*
1805 * We don't need checksums calculated for packets coming in this
1806 * device: trust us!
1807 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001808 ioctl(netfd, TUNSETNOCSUM, 1);
1809
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001810 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
1811 return netfd;
1812}
1813
Rusty Russell2e04ef72009-07-30 16:03:45 -06001814/*L:195
1815 * Our network is a Host<->Guest network. This can either use bridging or
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001816 * routing, but the principle is the same: it uses the "tun" device to inject
1817 * packets into the Host as if they came in from a normal network card. We
Rusty Russell2e04ef72009-07-30 16:03:45 -06001818 * just shunt packets between the Guest and the tun device.
1819 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001820static void setup_tun_net(char *arg)
1821{
1822 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06001823 struct net_info *net_info = malloc(sizeof(*net_info));
1824 int ipfd;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001825 u32 ip = INADDR_ANY;
1826 bool bridging = false;
1827 char tapif[IFNAMSIZ], *p;
1828 struct virtio_net_config conf;
1829
Rusty Russell659a0e62009-06-12 22:27:10 -06001830 net_info->tunfd = get_tun_device(tapif);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001831
Rusty Russell17cbca22007-10-22 11:24:22 +10001832 /* First we create a new network device. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001833 dev = new_device("net", VIRTIO_ID_NET);
1834 dev->priv = net_info;
Rusty Russelldde79782007-07-26 10:41:03 -07001835
Rusty Russell2e04ef72009-07-30 16:03:45 -06001836 /* Network devices need a recv and a send queue, just like console. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001837 add_virtqueue(dev, VIRTQUEUE_NUM, net_input);
1838 add_virtqueue(dev, VIRTQUEUE_NUM, net_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001839
Rusty Russell2e04ef72009-07-30 16:03:45 -06001840 /*
1841 * We need a socket to perform the magic network ioctls to bring up the
1842 * tap interface, connect to the bridge etc. Any socket will do!
1843 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001844 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1845 if (ipfd < 0)
1846 err(1, "opening IP socket");
1847
Rusty Russelldde79782007-07-26 10:41:03 -07001848 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001849 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001850 arg += strlen(BRIDGE_PFX);
1851 bridging = true;
1852 }
1853
1854 /* A mac address may follow the bridge name or IP address */
1855 p = strchr(arg, ':');
1856 if (p) {
1857 str2mac(p+1, conf.mac);
Rusty Russell40c42072008-08-12 17:52:51 -05001858 add_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001859 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001860 }
1861
1862 /* arg is now either an IP address or a bridge name */
1863 if (bridging)
1864 add_to_bridge(ipfd, tapif, arg);
1865 else
Rusty Russell8ca47e02007-07-19 01:49:29 -07001866 ip = str2ip(arg);
1867
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001868 /* Set up the tun device. */
1869 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001870
Rusty Russell398f1872008-07-29 09:58:37 -05001871 /* Expect Guest to handle everything except UFO */
1872 add_feature(dev, VIRTIO_NET_F_CSUM);
1873 add_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
Rusty Russell398f1872008-07-29 09:58:37 -05001874 add_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
1875 add_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
1876 add_feature(dev, VIRTIO_NET_F_GUEST_ECN);
1877 add_feature(dev, VIRTIO_NET_F_HOST_TSO4);
1878 add_feature(dev, VIRTIO_NET_F_HOST_TSO6);
1879 add_feature(dev, VIRTIO_NET_F_HOST_ECN);
Mark McLoughlind1f01322009-05-11 18:11:46 +01001880 /* We handle indirect ring entries */
1881 add_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
Rusty Russell927cfb92013-07-15 10:50:13 +09301882 /* We're compliant with the damn spec. */
1883 add_feature(dev, VIRTIO_F_ANY_LAYOUT);
Rusty Russella586d4f2008-02-04 23:49:56 -05001884 set_config(dev, sizeof(conf), &conf);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001885
Rusty Russella586d4f2008-02-04 23:49:56 -05001886 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07001887 close(ipfd);
1888
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05001889 devices.device_num++;
1890
1891 if (bridging)
1892 verbose("device %u: tun %s attached to bridge: %s\n",
1893 devices.device_num, tapif, arg);
1894 else
1895 verbose("device %u: tun %s: %s\n",
1896 devices.device_num, tapif, arg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001897}
Rusty Russella91d74a2009-07-30 16:03:45 -06001898/*:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10001899
Rusty Russelle1e72962007-10-25 15:02:50 +10001900/* This hangs off device->priv. */
Rusty Russell1842f232009-07-30 16:03:46 -06001901struct vblk_info {
Rusty Russell17cbca22007-10-22 11:24:22 +10001902 /* The size of the file. */
1903 off64_t len;
1904
1905 /* The file descriptor for the file. */
1906 int fd;
1907
Rusty Russell17cbca22007-10-22 11:24:22 +10001908};
1909
Rusty Russelle1e72962007-10-25 15:02:50 +10001910/*L:210
1911 * The Disk
1912 *
Rusty Russella91d74a2009-07-30 16:03:45 -06001913 * The disk only has one virtqueue, so it only has one thread. It is really
1914 * simple: the Guest asks for a block number and we read or write that position
1915 * in the file.
1916 *
1917 * Before we serviced each virtqueue in a separate thread, that was unacceptably
1918 * slow: the Guest waits until the read is finished before running anything
1919 * else, even if it could have been doing useful work.
1920 *
1921 * We could have used async I/O, except it's reputed to suck so hard that
1922 * characters actually go missing from your code when you try to use it.
Rusty Russelle1e72962007-10-25 15:02:50 +10001923 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001924static void blk_request(struct virtqueue *vq)
Rusty Russell17cbca22007-10-22 11:24:22 +10001925{
Rusty Russell659a0e62009-06-12 22:27:10 -06001926 struct vblk_info *vblk = vq->dev->priv;
Rusty Russell17cbca22007-10-22 11:24:22 +10001927 unsigned int head, out_num, in_num, wlen;
Rusty Russellc0316a92012-10-16 23:56:13 +10301928 int ret, i;
Rusty Russellcb38fa22008-05-02 21:50:45 -05001929 u8 *in;
Rusty Russellc0316a92012-10-16 23:56:13 +10301930 struct virtio_blk_outhdr out;
Rusty Russell659a0e62009-06-12 22:27:10 -06001931 struct iovec iov[vq->vring.num];
Rusty Russell17cbca22007-10-22 11:24:22 +10001932 off64_t off;
1933
Rusty Russella91d74a2009-07-30 16:03:45 -06001934 /*
1935 * Get the next request, where we normally wait. It triggers the
1936 * interrupt to acknowledge previously serviced requests (if any).
1937 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001938 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10001939
Rusty Russellc0316a92012-10-16 23:56:13 +10301940 /* Copy the output header from the front of the iov (adjusts iov) */
1941 iov_consume(iov, out_num, &out, sizeof(out));
Rusty Russell17cbca22007-10-22 11:24:22 +10001942
Rusty Russellc0316a92012-10-16 23:56:13 +10301943 /* Find and trim end of iov input array, for our status byte. */
1944 in = NULL;
1945 for (i = out_num + in_num - 1; i >= out_num; i--) {
1946 if (iov[i].iov_len > 0) {
1947 in = iov[i].iov_base + iov[i].iov_len - 1;
1948 iov[i].iov_len--;
1949 break;
1950 }
1951 }
1952 if (!in)
1953 errx(1, "Bad virtblk cmd with no room for status");
1954
Rusty Russella91d74a2009-07-30 16:03:45 -06001955 /*
1956 * For historical reasons, block operations are expressed in 512 byte
1957 * "sectors".
1958 */
Rusty Russellc0316a92012-10-16 23:56:13 +10301959 off = out.sector * 512;
Rusty Russell17cbca22007-10-22 11:24:22 +10001960
Rusty Russell2e04ef72009-07-30 16:03:45 -06001961 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -06001962 * In general the virtio block driver is allowed to try SCSI commands.
1963 * It'd be nice if we supported eject, for example, but we don't.
1964 */
Rusty Russellc0316a92012-10-16 23:56:13 +10301965 if (out.type & VIRTIO_BLK_T_SCSI_CMD) {
Rusty Russell17cbca22007-10-22 11:24:22 +10001966 fprintf(stderr, "Scsi commands unsupported\n");
Rusty Russellcb38fa22008-05-02 21:50:45 -05001967 *in = VIRTIO_BLK_S_UNSUPP;
Anthony Liguori1200e642007-11-08 21:13:44 -06001968 wlen = sizeof(*in);
Rusty Russellc0316a92012-10-16 23:56:13 +10301969 } else if (out.type & VIRTIO_BLK_T_OUT) {
Rusty Russell2e04ef72009-07-30 16:03:45 -06001970 /*
1971 * Write
1972 *
1973 * Move to the right location in the block file. This can fail
1974 * if they try to write past end.
1975 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001976 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10301977 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10001978
Rusty Russellc0316a92012-10-16 23:56:13 +10301979 ret = writev(vblk->fd, iov, out_num);
1980 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
Rusty Russell17cbca22007-10-22 11:24:22 +10001981
Rusty Russell2e04ef72009-07-30 16:03:45 -06001982 /*
1983 * Grr... Now we know how long the descriptor they sent was, we
Rusty Russell17cbca22007-10-22 11:24:22 +10001984 * make sure they didn't try to write over the end of the block
Rusty Russell2e04ef72009-07-30 16:03:45 -06001985 * file (possibly extending it).
1986 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001987 if (ret > 0 && off + ret > vblk->len) {
1988 /* Trim it back to the correct length */
1989 ftruncate64(vblk->fd, vblk->len);
1990 /* Die, bad Guest, die. */
1991 errx(1, "Write past end %llu+%u", off, ret);
1992 }
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02001993
1994 wlen = sizeof(*in);
1995 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russellc0316a92012-10-16 23:56:13 +10301996 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02001997 /* Flush */
1998 ret = fdatasync(vblk->fd);
1999 verbose("FLUSH fdatasync: %i\n", ret);
Anthony Liguori1200e642007-11-08 21:13:44 -06002000 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002001 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10002002 } else {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002003 /*
2004 * Read
2005 *
2006 * Move to the right location in the block file. This can fail
2007 * if they try to read past end.
2008 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002009 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302010 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002011
Rusty Russellc0316a92012-10-16 23:56:13 +10302012 ret = readv(vblk->fd, iov + out_num, in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002013 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06002014 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002015 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10002016 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06002017 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002018 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10002019 }
2020 }
2021
Rusty Russella91d74a2009-07-30 16:03:45 -06002022 /* Finished that request. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002023 add_used(vq, head, wlen);
Rusty Russell17cbca22007-10-22 11:24:22 +10002024}
2025
Rusty Russelle1e72962007-10-25 15:02:50 +10002026/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002027static void setup_block_file(const char *filename)
2028{
Rusty Russell17cbca22007-10-22 11:24:22 +10002029 struct device *dev;
2030 struct vblk_info *vblk;
Rusty Russella586d4f2008-02-04 23:49:56 -05002031 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10002032
Rusty Russell2e04ef72009-07-30 16:03:45 -06002033 /* Creat the device. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002034 dev = new_device("block", VIRTIO_ID_BLOCK);
Rusty Russell17cbca22007-10-22 11:24:22 +10002035
Rusty Russelle1e72962007-10-25 15:02:50 +10002036 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002037 add_virtqueue(dev, VIRTQUEUE_NUM, blk_request);
Rusty Russell17cbca22007-10-22 11:24:22 +10002038
2039 /* Allocate the room for our own bookkeeping */
2040 vblk = dev->priv = malloc(sizeof(*vblk));
2041
2042 /* First we open the file and store the length. */
2043 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
2044 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
2045
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002046 /* We support FLUSH. */
2047 add_feature(dev, VIRTIO_BLK_F_FLUSH);
Rusty Russella586d4f2008-02-04 23:49:56 -05002048
Rusty Russell17cbca22007-10-22 11:24:22 +10002049 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002050 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10002051
Rusty Russell2e04ef72009-07-30 16:03:45 -06002052 /*
2053 * Tell Guest not to put in too many descriptors at once: two are used
2054 * for the in and out elements.
2055 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002056 add_feature(dev, VIRTIO_BLK_F_SEG_MAX);
2057 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2058
Rusty Russell8ef562d2009-07-30 16:03:43 -06002059 /* Don't try to put whole struct: we have 8 bit limit. */
2060 set_config(dev, offsetof(struct virtio_blk_config, geometry), &conf);
Rusty Russell17cbca22007-10-22 11:24:22 +10002061
Rusty Russell17cbca22007-10-22 11:24:22 +10002062 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell659a0e62009-06-12 22:27:10 -06002063 ++devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10002064}
Rusty Russell28fd6d72008-07-29 09:58:33 -05002065
Rusty Russell2e04ef72009-07-30 16:03:45 -06002066/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10302067 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05002068 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10302069 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05002070 * console is the reverse.
2071 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002072 * The same logic applies, however.
2073 */
2074struct rng_info {
2075 int rfd;
2076};
2077
Rusty Russell659a0e62009-06-12 22:27:10 -06002078static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05002079{
2080 int len;
2081 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002082 struct rng_info *rng_info = vq->dev->priv;
2083 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05002084
2085 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002086 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002087 if (out_num)
2088 errx(1, "Output buffers in rng?");
2089
Rusty Russell2e04ef72009-07-30 16:03:45 -06002090 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06002091 * Just like the console write, we loop to cover the whole iovec.
2092 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002093 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002094 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06002095 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002096 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10302097 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10302098 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002099 totlen += len;
2100 }
2101
2102 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002103 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002104}
2105
Rusty Russell2e04ef72009-07-30 16:03:45 -06002106/*L:199
2107 * This creates a "hardware" random number device for the Guest.
2108 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002109static void setup_rng(void)
2110{
2111 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002112 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05002113
Rusty Russella454bb32015-02-11 15:15:09 +10302114 /* Our device's private info simply contains the /dev/urandom fd. */
2115 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002116
Rusty Russell2e04ef72009-07-30 16:03:45 -06002117 /* Create the new device. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002118 dev = new_device("rng", VIRTIO_ID_RNG);
2119 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002120
2121 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002122 add_virtqueue(dev, VIRTQUEUE_NUM, rng_input);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002123
2124 verbose("device %u: rng\n", devices.device_num++);
2125}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002126/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05302127
Rusty Russella6bd8e12008-03-28 11:05:53 -05002128/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05302129static void __attribute__((noreturn)) restart_guest(void)
2130{
2131 unsigned int i;
2132
Rusty Russell2e04ef72009-07-30 16:03:45 -06002133 /*
2134 * Since we don't track all open fds, we simply close everything beyond
2135 * stderr.
2136 */
Balaji Raoec04b132007-12-28 14:26:24 +05302137 for (i = 3; i < FD_SETSIZE; i++)
2138 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05002139
Rusty Russell659a0e62009-06-12 22:27:10 -06002140 /* Reset all the devices (kills all threads). */
2141 cleanup_devices();
2142
Balaji Raoec04b132007-12-28 14:26:24 +05302143 execv(main_args[0], main_args);
2144 err(1, "Could not exec %s", main_args[0]);
2145}
Rusty Russell8ca47e02007-07-19 01:49:29 -07002146
Rusty Russell2e04ef72009-07-30 16:03:45 -06002147/*L:220
2148 * Finally we reach the core of the Launcher which runs the Guest, serves
2149 * its input and output, and finally, lays it to rest.
2150 */
Rusty Russell56739c802009-06-12 22:26:59 -06002151static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002152{
2153 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10302154 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002155 int readval;
2156
2157 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302158 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002159
Rusty Russell17cbca22007-10-22 11:24:22 +10002160 /* One unsigned long means the Guest did HCALL_NOTIFY */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302161 if (readval == sizeof(notify)) {
2162 if (notify.trap == 0x1F) {
2163 verbose("Notify on address %#08x\n",
2164 notify.addr);
2165 handle_output(notify.addr);
Rusty Russellc565650b2015-02-11 15:15:10 +10302166 } else if (notify.trap == 13) {
2167 verbose("Emulating instruction at %#x\n",
2168 getreg(eip));
2169 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302170 } else if (notify.trap == 14) {
2171 verbose("Emulating MMIO at %#x\n",
2172 getreg(eip));
2173 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302174 } else
2175 errx(1, "Unknown trap %i addr %#08x\n",
2176 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07002177 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002178 } else if (errno == ENOENT) {
2179 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002180 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002181 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05302182 /* ERESTART means that we need to reboot the guest */
2183 } else if (errno == ERESTART) {
2184 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06002185 /* Anything else means a bug or incompatible change. */
2186 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002187 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002188 }
2189}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002190/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10002191 * This is the end of the Launcher. The good news: we are over halfway
2192 * through! The bad news: the most fiendish part of the code still lies ahead
2193 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07002194 *
Rusty Russelle1e72962007-10-25 15:02:50 +10002195 * Are you ready? Take a deep breath and join me in the core of the Host, in
2196 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06002197:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002198
2199static struct option opts[] = {
2200 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002201 { "tunnet", 1, NULL, 't' },
2202 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05002203 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002204 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002205 { "username", 1, NULL, 'u' },
2206 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002207 { NULL },
2208};
2209static void usage(void)
2210{
2211 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002212 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07002213 "|--block=<filename>|--initrd=<filename>]...\n"
2214 "<mem-in-mb> vmlinux [args...]");
2215}
2216
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002217/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002218int main(int argc, char *argv[])
2219{
Rusty Russell2e04ef72009-07-30 16:03:45 -06002220 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002221 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06002222 /* Two temporaries. */
2223 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002224 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002225 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07002226 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002227 const char *initrd_name = NULL;
2228
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002229 /* Password structure for initgroups/setres[gu]id */
2230 struct passwd *user_details = NULL;
2231
2232 /* Directory to chroot to */
2233 char *chroot_path = NULL;
2234
Balaji Raoec04b132007-12-28 14:26:24 +05302235 /* Save the args: we "reboot" by execing ourselves again. */
2236 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05302237
Rusty Russell2e04ef72009-07-30 16:03:45 -06002238 /*
2239 * First we initialize the device list. We keep a pointer to the last
Rusty Russell659a0e62009-06-12 22:27:10 -06002240 * device, and the next interrupt number to use for devices (1:
Rusty Russell2e04ef72009-07-30 16:03:45 -06002241 * remember that 0 is used by the timer).
2242 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002243 devices.lastdev = NULL;
Rusty Russell17cbca22007-10-22 11:24:22 +10002244 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002245
Rusty Russella91d74a2009-07-30 16:03:45 -06002246 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002247 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06002248
Rusty Russell2e04ef72009-07-30 16:03:45 -06002249 /*
2250 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07002251 * descriptor and memory pages for the devices as we parse the command
2252 * line. So we quickly look through the arguments to find the amount
Rusty Russell2e04ef72009-07-30 16:03:45 -06002253 * of memory now.
2254 */
Rusty Russell6570c45992007-07-23 18:43:56 -07002255 for (i = 1; i < argc; i++) {
2256 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002257 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002258 /*
2259 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002260 * guest-physical memory range. This fills it with 0,
2261 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002262 * tries to access it.
2263 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002264 guest_base = map_zeroed_pages(mem / getpagesize()
2265 + DEVICE_PAGES);
2266 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10302267 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002268 devices.descpage = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07002269 break;
2270 }
2271 }
Rusty Russelldde79782007-07-26 10:41:03 -07002272
2273 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002274 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2275 switch (c) {
2276 case 'v':
2277 verbose = true;
2278 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002279 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10002280 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002281 break;
2282 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10002283 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002284 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002285 case 'r':
2286 setup_rng();
2287 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002288 case 'i':
2289 initrd_name = optarg;
2290 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002291 case 'u':
2292 user_details = getpwnam(optarg);
2293 if (!user_details)
2294 err(1, "getpwnam failed, incorrect username?");
2295 break;
2296 case 'c':
2297 chroot_path = optarg;
2298 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002299 default:
2300 warnx("Unknown argument %s", argv[optind]);
2301 usage();
2302 }
2303 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06002304 /*
2305 * After the other arguments we expect memory and kernel image name,
2306 * followed by command line arguments for the kernel.
2307 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002308 if (optind + 2 > argc)
2309 usage();
2310
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002311 verbose("Guest base is at %p\n", guest_base);
2312
Rusty Russelldde79782007-07-26 10:41:03 -07002313 /* We always have a console device */
Rusty Russell17cbca22007-10-22 11:24:22 +10002314 setup_console();
Rusty Russell8ca47e02007-07-19 01:49:29 -07002315
Rusty Russell8ca47e02007-07-19 01:49:29 -07002316 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10002317 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002318
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002319 /* Boot information is stashed at physical address 0 */
2320 boot = from_guest_phys(0);
2321
Rusty Russelldde79782007-07-26 10:41:03 -07002322 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002323 if (initrd_name) {
2324 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06002325 /*
2326 * These are the location in the Linux boot header where the
2327 * start and size of the initrd are expected to be found.
2328 */
Rusty Russell43d33b22007-10-22 11:29:57 +10002329 boot->hdr.ramdisk_image = mem - initrd_size;
2330 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07002331 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002332 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002333 }
2334
Rusty Russell2e04ef72009-07-30 16:03:45 -06002335 /*
2336 * The Linux boot header contains an "E820" memory map: ours is a
2337 * simple, single region.
2338 */
Rusty Russell43d33b22007-10-22 11:29:57 +10002339 boot->e820_entries = 1;
2340 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06002341 /*
2342 * The boot header contains a command line pointer: we put the command
2343 * line after the boot header.
2344 */
Rusty Russell43d33b22007-10-22 11:29:57 +10002345 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10002346 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002347 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07002348
Rusty Russelle22a5392011-08-15 10:15:10 +09302349 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
2350 boot->hdr.kernel_alignment = 0x1000000;
2351
Rusty Russell814a0e52007-10-22 11:29:44 +10002352 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002353 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10002354
2355 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002356 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10002357
Rusty Russell43d33b22007-10-22 11:29:57 +10002358 /* Tell the entry path not to try to reload segment registers. */
2359 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002360
Rusty Russell9f542882011-07-22 14:39:50 +09302361 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06002362 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07002363
Rusty Russella91d74a2009-07-30 16:03:45 -06002364 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002365 signal(SIGCHLD, kill_launcher);
2366
2367 /* If we exit via err(), this kills all the threads, restores tty. */
2368 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002369
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002370 /* If requested, chroot to a directory */
2371 if (chroot_path) {
2372 if (chroot(chroot_path) != 0)
2373 err(1, "chroot(\"%s\") failed", chroot_path);
2374
2375 if (chdir("/") != 0)
2376 err(1, "chdir(\"/\") failed");
2377
2378 verbose("chroot done\n");
2379 }
2380
2381 /* If requested, drop privileges */
2382 if (user_details) {
2383 uid_t u;
2384 gid_t g;
2385
2386 u = user_details->pw_uid;
2387 g = user_details->pw_gid;
2388
2389 if (initgroups(user_details->pw_name, g) != 0)
2390 err(1, "initgroups failed");
2391
2392 if (setresgid(g, g, g) != 0)
2393 err(1, "setresgid failed");
2394
2395 if (setresuid(u, u, u) != 0)
2396 err(1, "setresuid failed");
2397
2398 verbose("Dropping privileges completed\n");
2399 }
2400
Rusty Russelldde79782007-07-26 10:41:03 -07002401 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06002402 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07002403}
Rusty Russellf56a3842007-07-26 10:41:05 -07002404/*:*/
2405
2406/*M:999
2407 * Mastery is done: you now know everything I do.
2408 *
2409 * But surely you have seen code, features and bugs in your wanderings which
2410 * you now yearn to attack? That is the real game, and I look forward to you
2411 * patching and forking lguest into the Your-Name-Here-visor.
2412 *
2413 * Farewell, and good coding!
2414 * Rusty Russell.
2415 */