blob: 80dc6346030e9a907b5ca77ccf4aa5e7df7c7a54 [file] [log] [blame]
Rusty Russell2e04ef72009-07-30 16:03:45 -06001/*P:100
2 * This is the Launcher code, a simple program which lays out the "physical"
3 * memory for the new Guest by mapping the kernel image and the virtual
4 * devices, then opens /dev/lguest to tell the kernel about the Guest and
5 * control it.
6:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07007#define _LARGEFILE64_SOURCE
8#define _GNU_SOURCE
9#include <stdio.h>
10#include <string.h>
11#include <unistd.h>
12#include <err.h>
13#include <stdint.h>
14#include <stdlib.h>
15#include <elf.h>
16#include <sys/mman.h>
Ronald G. Minnich6649bb72007-08-28 14:35:59 -070017#include <sys/param.h>
Rusty Russell8ca47e02007-07-19 01:49:29 -070018#include <sys/types.h>
19#include <sys/stat.h>
20#include <sys/wait.h>
Rusty Russell659a0e62009-06-12 22:27:10 -060021#include <sys/eventfd.h>
Rusty Russell8ca47e02007-07-19 01:49:29 -070022#include <fcntl.h>
23#include <stdbool.h>
24#include <errno.h>
25#include <ctype.h>
26#include <sys/socket.h>
27#include <sys/ioctl.h>
28#include <sys/time.h>
29#include <time.h>
30#include <netinet/in.h>
31#include <net/if.h>
32#include <linux/sockios.h>
33#include <linux/if_tun.h>
34#include <sys/uio.h>
35#include <termios.h>
36#include <getopt.h>
Rusty Russell17cbca22007-10-22 11:24:22 +100037#include <assert.h>
38#include <sched.h>
Rusty Russella586d4f2008-02-04 23:49:56 -050039#include <limits.h>
40#include <stddef.h>
Rusty Russella1618832008-07-29 09:58:35 -050041#include <signal.h>
Philip Sanderson8aeb36e2011-01-20 21:37:28 -060042#include <pwd.h>
43#include <grp.h>
Rusty Russellc565650b2015-02-11 15:15:10 +103044#include <sys/user.h>
Rusty Russelld7fbf6e2015-02-11 15:15:11 +103045#include <linux/pci_regs.h>
Philip Sanderson8aeb36e2011-01-20 21:37:28 -060046
Rusty Russell927cfb92013-07-15 10:50:13 +093047#ifndef VIRTIO_F_ANY_LAYOUT
48#define VIRTIO_F_ANY_LAYOUT 27
49#endif
50
Rusty Russell2e04ef72009-07-30 16:03:45 -060051/*L:110
Rusty Russell9f542882011-07-22 14:39:50 +093052 * We can ignore the 43 include files we need for this program, but I do want
Rusty Russell2e04ef72009-07-30 16:03:45 -060053 * to draw attention to the use of kernel-style types.
Rusty Russelldb24e8c2007-10-25 14:09:25 +100054 *
55 * As Linus said, "C is a Spartan language, and so should your naming be." I
56 * like these abbreviations, so we define them here. Note that u64 is always
57 * unsigned long long, which works on all Linux systems: this means that we can
Rusty Russell2e04ef72009-07-30 16:03:45 -060058 * use %llu in printf for any u64.
59 */
Rusty Russelldb24e8c2007-10-25 14:09:25 +100060typedef unsigned long long u64;
61typedef uint32_t u32;
62typedef uint16_t u16;
63typedef uint8_t u8;
Rusty Russelldde79782007-07-26 10:41:03 -070064/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -070065
Rusty Russelleb39f832015-02-11 15:19:01 +103066#define VIRTIO_CONFIG_NO_LEGACY
Rusty Russell93153072015-02-11 15:15:11 +103067#define VIRTIO_PCI_NO_LEGACY
Rusty Russell50516542015-02-11 15:15:12 +103068#define VIRTIO_BLK_NO_LEGACY
Rusty Russell93153072015-02-11 15:15:11 +103069
70/* Use in-kernel ones, which defines VIRTIO_F_VERSION_1 */
71#include "../../include/uapi/linux/virtio_config.h"
Rusty Russellbf6d4032015-02-11 15:16:01 +103072#include "../../include/uapi/linux/virtio_net.h"
Rusty Russell50516542015-02-11 15:15:12 +103073#include "../../include/uapi/linux/virtio_blk.h"
Rusty Russelle8330d92015-02-11 15:23:01 +103074#include "../../include/uapi/linux/virtio_console.h"
Rusty Russell0d5b5d32015-02-11 15:17:01 +103075#include "../../include/uapi/linux/virtio_rng.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093076#include <linux/virtio_ring.h>
Rusty Russell93153072015-02-11 15:15:11 +103077#include "../../include/uapi/linux/virtio_pci.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093078#include <asm/bootparam.h>
79#include "../../include/linux/lguest_launcher.h"
80
Rusty Russell8ca47e02007-07-19 01:49:29 -070081#define BRIDGE_PFX "bridge:"
82#ifndef SIOCBRADDIF
83#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
84#endif
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100085/* We can have up to 256 pages for devices. */
86#define DEVICE_PAGES 256
Rusty Russell0f0c4fa2008-07-29 09:58:37 -050087/* This will occupy 3 pages: it must be a power of 2. */
88#define VIRTQUEUE_NUM 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070089
Rusty Russell2e04ef72009-07-30 16:03:45 -060090/*L:120
91 * verbose is both a global flag and a macro. The C preprocessor allows
92 * this, and although I wouldn't recommend it, it works quite nicely here.
93 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070094static bool verbose;
95#define verbose(args...) \
96 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070097/*:*/
98
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100099/* The pointer to the start of guest memory. */
100static void *guest_base;
101/* The maximum guest physical address allowed, and maximum possible. */
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030102static unsigned long guest_limit, guest_max, guest_mmio;
Rusty Russell56739c802009-06-12 22:26:59 -0600103/* The /dev/lguest file descriptor. */
104static int lguest_fd;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700105
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -0200106/* a per-cpu variable indicating whose vcpu is currently running */
107static unsigned int __thread cpu_id;
108
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030109/* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
110#define MAX_PCI_DEVICES 32
111
Rusty Russelldde79782007-07-26 10:41:03 -0700112/* This is our list of devices. */
Rusty Russell1842f232009-07-30 16:03:46 -0600113struct device_list {
Rusty Russell17cbca22007-10-22 11:24:22 +1000114 /* Counter to assign interrupt numbers. */
115 unsigned int next_irq;
116
117 /* Counter to print out convenient device numbers. */
118 unsigned int device_num;
119
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030120 /* PCI devices. */
121 struct device *pci[MAX_PCI_DEVICES];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700122};
123
Rusty Russell17cbca22007-10-22 11:24:22 +1000124/* The list of Guest devices, based on command line arguments. */
125static struct device_list devices;
126
Rusty Russell93153072015-02-11 15:15:11 +1030127struct virtio_pci_cfg_cap {
128 struct virtio_pci_cap cap;
Rusty Russellb2ce1ea2015-02-13 17:13:41 +1030129 u32 pci_cfg_data; /* Data for BAR access. */
Rusty Russell93153072015-02-11 15:15:11 +1030130};
131
132struct virtio_pci_mmio {
133 struct virtio_pci_common_cfg cfg;
134 u16 notify;
135 u8 isr;
136 u8 padding;
137 /* Device-specific configuration follows this. */
138};
139
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030140/* This is the layout (little-endian) of the PCI config space. */
141struct pci_config {
142 u16 vendor_id, device_id;
143 u16 command, status;
144 u8 revid, prog_if, subclass, class;
145 u8 cacheline_size, lat_timer, header_type, bist;
146 u32 bar[6];
147 u32 cardbus_cis_ptr;
148 u16 subsystem_vendor_id, subsystem_device_id;
149 u32 expansion_rom_addr;
150 u8 capabilities, reserved1[3];
151 u32 reserved2;
152 u8 irq_line, irq_pin, min_grant, max_latency;
Rusty Russell93153072015-02-11 15:15:11 +1030153
154 /* Now, this is the linked capability list. */
155 struct virtio_pci_cap common;
156 struct virtio_pci_notify_cap notify;
157 struct virtio_pci_cap isr;
158 struct virtio_pci_cap device;
Rusty Russell93153072015-02-11 15:15:11 +1030159 struct virtio_pci_cfg_cap cfg_access;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030160};
161
Rusty Russelldde79782007-07-26 10:41:03 -0700162/* The device structure describes a single device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600163struct device {
Rusty Russell17cbca22007-10-22 11:24:22 +1000164 /* The name of this device, for --verbose. */
165 const char *name;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700166
Rusty Russell17cbca22007-10-22 11:24:22 +1000167 /* Any queues attached to this device */
168 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700169
Rusty Russell659a0e62009-06-12 22:27:10 -0600170 /* Is it operational */
171 bool running;
Rusty Russella007a752008-05-02 21:50:53 -0500172
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030173 /* PCI configuration */
174 union {
175 struct pci_config config;
176 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
177 };
178
Rusty Russell93153072015-02-11 15:15:11 +1030179 /* Features we offer, and those accepted. */
180 u64 features, features_accepted;
181
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030182 /* Device-specific config hangs off the end of this. */
183 struct virtio_pci_mmio *mmio;
184
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030185 /* PCI MMIO resources (all in BAR0) */
186 size_t mmio_size;
187 u32 mmio_addr;
188
Rusty Russell8ca47e02007-07-19 01:49:29 -0700189 /* Device-specific data. */
190 void *priv;
191};
192
Rusty Russell17cbca22007-10-22 11:24:22 +1000193/* The virtqueue structure describes a queue attached to a device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600194struct virtqueue {
Rusty Russell17cbca22007-10-22 11:24:22 +1000195 struct virtqueue *next;
196
197 /* Which device owns me. */
198 struct device *dev;
199
Rusty Russell17cbca22007-10-22 11:24:22 +1000200 /* The actual ring of buffers. */
201 struct vring vring;
202
Rusty Russell93153072015-02-11 15:15:11 +1030203 /* The information about this virtqueue (we only use queue_size on) */
204 struct virtio_pci_common_cfg pci_config;
205
Rusty Russell17cbca22007-10-22 11:24:22 +1000206 /* Last available index we saw. */
207 u16 last_avail_idx;
208
Rusty Russell95c517c2009-06-12 22:27:11 -0600209 /* How many are used since we sent last irq? */
210 unsigned int pending_used;
211
Rusty Russell659a0e62009-06-12 22:27:10 -0600212 /* Eventfd where Guest notifications arrive. */
213 int eventfd;
Rusty Russell20887612008-05-30 15:09:46 -0500214
Rusty Russell659a0e62009-06-12 22:27:10 -0600215 /* Function for the thread which is servicing this virtqueue. */
216 void (*service)(struct virtqueue *vq);
217 pid_t thread;
Rusty Russell17cbca22007-10-22 11:24:22 +1000218};
219
Balaji Raoec04b132007-12-28 14:26:24 +0530220/* Remember the arguments to the program so we can "reboot" */
221static char **main_args;
222
Rusty Russell659a0e62009-06-12 22:27:10 -0600223/* The original tty settings to restore on exit. */
224static struct termios orig_term;
225
Rusty Russell2e04ef72009-07-30 16:03:45 -0600226/*
227 * We have to be careful with barriers: our devices are all run in separate
Rusty Russellf7027c62009-06-12 22:27:00 -0600228 * threads and so we need to make sure that changes visible to the Guest happen
Rusty Russell2e04ef72009-07-30 16:03:45 -0600229 * in precise order.
230 */
Rusty Russellf7027c62009-06-12 22:27:00 -0600231#define wmb() __asm__ __volatile__("" : : : "memory")
Rusty Russell0d69a652013-07-02 15:35:14 +0930232#define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
233#define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
Rusty Russell17cbca22007-10-22 11:24:22 +1000234
Rusty Russellb5111792008-07-29 09:58:34 -0500235/* Wrapper for the last available index. Makes it easier to change. */
236#define lg_last_avail(vq) ((vq)->last_avail_idx)
237
Rusty Russell2e04ef72009-07-30 16:03:45 -0600238/*
239 * The virtio configuration space is defined to be little-endian. x86 is
240 * little-endian too, but it's nice to be explicit so we have these helpers.
241 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000242#define cpu_to_le16(v16) (v16)
243#define cpu_to_le32(v32) (v32)
244#define cpu_to_le64(v64) (v64)
245#define le16_to_cpu(v16) (v16)
246#define le32_to_cpu(v32) (v32)
Rusty Russella586d4f2008-02-04 23:49:56 -0500247#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000248
Rusty Russell28fd6d72008-07-29 09:58:33 -0500249/* Is this iovec empty? */
250static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
251{
252 unsigned int i;
253
254 for (i = 0; i < num_iov; i++)
255 if (iov[i].iov_len)
256 return false;
257 return true;
258}
259
260/* Take len bytes from the front of this iovec. */
Rusty Russellc0316a92012-10-16 23:56:13 +1030261static void iov_consume(struct iovec iov[], unsigned num_iov,
262 void *dest, unsigned len)
Rusty Russell28fd6d72008-07-29 09:58:33 -0500263{
264 unsigned int i;
265
266 for (i = 0; i < num_iov; i++) {
267 unsigned int used;
268
269 used = iov[i].iov_len < len ? iov[i].iov_len : len;
Rusty Russellc0316a92012-10-16 23:56:13 +1030270 if (dest) {
271 memcpy(dest, iov[i].iov_base, used);
272 dest += used;
273 }
Rusty Russell28fd6d72008-07-29 09:58:33 -0500274 iov[i].iov_base += used;
275 iov[i].iov_len -= used;
276 len -= used;
277 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030278 if (len != 0)
279 errx(1, "iovec too short!");
Rusty Russell28fd6d72008-07-29 09:58:33 -0500280}
281
Rusty Russell2e04ef72009-07-30 16:03:45 -0600282/*L:100
283 * The Launcher code itself takes us out into userspace, that scary place where
284 * pointers run wild and free! Unfortunately, like most userspace programs,
285 * it's quite boring (which is why everyone likes to hack on the kernel!).
286 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
287 * you through this section. Or, maybe not.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000288 *
289 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
290 * memory and stores it in "guest_base". In other words, Guest physical ==
291 * Launcher virtual with an offset.
292 *
293 * This can be tough to get your head around, but usually it just means that we
Francis Galieguea33f3222010-04-23 00:08:02 +0200294 * use these trivial conversion functions when the Guest gives us its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600295 * "physical" addresses:
296 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000297static void *from_guest_phys(unsigned long addr)
298{
299 return guest_base + addr;
300}
301
302static unsigned long to_guest_phys(const void *addr)
303{
304 return (addr - guest_base);
305}
306
Rusty Russelldde79782007-07-26 10:41:03 -0700307/*L:130
308 * Loading the Kernel.
309 *
310 * We start with couple of simple helper routines. open_or_die() avoids
Rusty Russell2e04ef72009-07-30 16:03:45 -0600311 * error-checking code cluttering the callers:
312 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700313static int open_or_die(const char *name, int flags)
314{
315 int fd = open(name, flags);
316 if (fd < 0)
317 err(1, "Failed to open %s", name);
318 return fd;
319}
320
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000321/* map_zeroed_pages() takes a number of pages. */
322static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700323{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000324 int fd = open_or_die("/dev/zero", O_RDONLY);
325 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700326
Rusty Russell2e04ef72009-07-30 16:03:45 -0600327 /*
328 * We use a private mapping (ie. if we write to the page, it will be
Philip Sanderson5230ff02011-01-20 21:37:28 -0600329 * copied). We allocate an extra two pages PROT_NONE to act as guard
330 * pages against read/write attempts that exceed allocated space.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600331 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600332 addr = mmap(NULL, getpagesize() * (num+2),
333 PROT_NONE, MAP_PRIVATE, fd, 0);
334
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000335 if (addr == MAP_FAILED)
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200336 err(1, "Mmapping %u pages of /dev/zero", num);
Rusty Russella91d74a2009-07-30 16:03:45 -0600337
Philip Sanderson5230ff02011-01-20 21:37:28 -0600338 if (mprotect(addr + getpagesize(), getpagesize() * num,
339 PROT_READ|PROT_WRITE) == -1)
340 err(1, "mprotect rw %u pages failed", num);
341
Rusty Russella91d74a2009-07-30 16:03:45 -0600342 /*
343 * One neat mmap feature is that you can close the fd, and it
344 * stays mapped.
345 */
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100346 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700347
Philip Sanderson5230ff02011-01-20 21:37:28 -0600348 /* Return address after PROT_NONE page */
349 return addr + getpagesize();
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000350}
351
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030352/* Get some bytes which won't be mapped into the guest. */
353static unsigned long get_mmio_region(size_t size)
354{
355 unsigned long addr = guest_mmio;
356 size_t i;
357
358 if (!size)
359 return addr;
360
361 /* Size has to be a power of 2 (and multiple of 16) */
362 for (i = 1; i < size; i <<= 1);
363
364 guest_mmio += i;
365
366 return addr;
367}
368
Rusty Russell2e04ef72009-07-30 16:03:45 -0600369/*
370 * This routine is used to load the kernel or initrd. It tries mmap, but if
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700371 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
Rusty Russell2e04ef72009-07-30 16:03:45 -0600372 * it falls back to reading the memory in.
373 */
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700374static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
375{
376 ssize_t r;
377
Rusty Russell2e04ef72009-07-30 16:03:45 -0600378 /*
379 * We map writable even though for some segments are marked read-only.
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700380 * The kernel really wants to be writable: it patches its own
381 * instructions.
382 *
383 * MAP_PRIVATE means that the page won't be copied until a write is
384 * done to it. This allows us to share untouched memory between
Rusty Russell2e04ef72009-07-30 16:03:45 -0600385 * Guests.
386 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600387 if (mmap(addr, len, PROT_READ|PROT_WRITE,
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700388 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
389 return;
390
391 /* pread does a seek and a read in one shot: saves a few lines. */
392 r = pread(fd, addr, len, offset);
393 if (r != len)
394 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
395}
396
Rusty Russell2e04ef72009-07-30 16:03:45 -0600397/*
398 * This routine takes an open vmlinux image, which is in ELF, and maps it into
Rusty Russelldde79782007-07-26 10:41:03 -0700399 * the Guest memory. ELF = Embedded Linking Format, which is the format used
400 * by all modern binaries on Linux including the kernel.
401 *
402 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000403 * address. We use the physical address; the Guest will map itself to the
404 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700405 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600406 * We return the starting address.
407 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000408static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700409{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700410 Elf32_Phdr phdr[ehdr->e_phnum];
411 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700412
Rusty Russell2e04ef72009-07-30 16:03:45 -0600413 /*
414 * Sanity checks on the main ELF header: an x86 executable with a
415 * reasonable number of correctly-sized program headers.
416 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700417 if (ehdr->e_type != ET_EXEC
418 || ehdr->e_machine != EM_386
419 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
420 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
421 errx(1, "Malformed elf header");
422
Rusty Russell2e04ef72009-07-30 16:03:45 -0600423 /*
424 * An ELF executable contains an ELF header and a number of "program"
Rusty Russelldde79782007-07-26 10:41:03 -0700425 * headers which indicate which parts ("segments") of the program to
Rusty Russell2e04ef72009-07-30 16:03:45 -0600426 * load where.
427 */
Rusty Russelldde79782007-07-26 10:41:03 -0700428
429 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700430 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
431 err(1, "Seeking to program headers");
432 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
433 err(1, "Reading program headers");
434
Rusty Russell2e04ef72009-07-30 16:03:45 -0600435 /*
436 * Try all the headers: there are usually only three. A read-only one,
437 * a read-write one, and a "note" section which we don't load.
438 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700439 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700440 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700441 if (phdr[i].p_type != PT_LOAD)
442 continue;
443
444 verbose("Section %i: size %i addr %p\n",
445 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
446
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700447 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000448 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700449 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700450 }
451
Rusty Russell814a0e52007-10-22 11:29:44 +1000452 /* The entry point is given in the ELF header. */
453 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700454}
455
Rusty Russell2e04ef72009-07-30 16:03:45 -0600456/*L:150
457 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
458 * to jump into it and it will unpack itself. We used to have to perform some
459 * hairy magic because the unpacking code scared me.
Rusty Russelldde79782007-07-26 10:41:03 -0700460 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000461 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
462 * a small patch to jump over the tricky bits in the Guest, so now we just read
Rusty Russell2e04ef72009-07-30 16:03:45 -0600463 * the funky header so we know where in the file to load, and away we go!
464 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000465static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700466{
Rusty Russell43d33b22007-10-22 11:29:57 +1000467 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000468 int r;
469 /* Modern bzImages get loaded at 1M. */
470 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700471
Rusty Russell2e04ef72009-07-30 16:03:45 -0600472 /*
473 * Go back to the start of the file and read the header. It should be
Paul Bolle395cf962011-08-15 02:02:26 +0200474 * a Linux boot header (see Documentation/x86/boot.txt)
Rusty Russell2e04ef72009-07-30 16:03:45 -0600475 */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000476 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000477 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000478
Rusty Russell43d33b22007-10-22 11:29:57 +1000479 /* Inside the setup_hdr, we expect the magic "HdrS" */
480 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000481 errx(1, "This doesn't look like a bzImage to me");
482
Rusty Russell43d33b22007-10-22 11:29:57 +1000483 /* Skip over the extra sectors of the header. */
484 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000485
486 /* Now read everything into memory. in nice big chunks. */
487 while ((r = read(fd, p, 65536)) > 0)
488 p += r;
489
Rusty Russell43d33b22007-10-22 11:29:57 +1000490 /* Finally, code32_start tells us where to enter the kernel. */
491 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700492}
493
Rusty Russell2e04ef72009-07-30 16:03:45 -0600494/*L:140
495 * Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000496 * come wrapped up in the self-decompressing "bzImage" format. With a little
Rusty Russell2e04ef72009-07-30 16:03:45 -0600497 * work, we can load those, too.
498 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000499static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700500{
501 Elf32_Ehdr hdr;
502
Rusty Russelldde79782007-07-26 10:41:03 -0700503 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700504 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
505 err(1, "Reading kernel");
506
Rusty Russelldde79782007-07-26 10:41:03 -0700507 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700508 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000509 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700510
Rusty Russella6bd8e12008-03-28 11:05:53 -0500511 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000512 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700513}
514
Rusty Russell2e04ef72009-07-30 16:03:45 -0600515/*
516 * This is a trivial little helper to align pages. Andi Kleen hated it because
Rusty Russelldde79782007-07-26 10:41:03 -0700517 * it calls getpagesize() twice: "it's dumb code."
518 *
519 * Kernel guys get really het up about optimization, even when it's not
Rusty Russell2e04ef72009-07-30 16:03:45 -0600520 * necessary. I leave this code as a reaction against that.
521 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700522static inline unsigned long page_align(unsigned long addr)
523{
Rusty Russelldde79782007-07-26 10:41:03 -0700524 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700525 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
526}
527
Rusty Russell2e04ef72009-07-30 16:03:45 -0600528/*L:180
529 * An "initial ram disk" is a disk image loaded into memory along with the
530 * kernel which the kernel can use to boot from without needing any drivers.
531 * Most distributions now use this as standard: the initrd contains the code to
532 * load the appropriate driver modules for the current machine.
Rusty Russelldde79782007-07-26 10:41:03 -0700533 *
534 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600535 * kernels. He sent me this (and tells me when I break it).
536 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700537static unsigned long load_initrd(const char *name, unsigned long mem)
538{
539 int ifd;
540 struct stat st;
541 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700542
543 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700544 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700545 if (fstat(ifd, &st) < 0)
546 err(1, "fstat() on initrd '%s'", name);
547
Rusty Russell2e04ef72009-07-30 16:03:45 -0600548 /*
549 * We map the initrd at the top of memory, but mmap wants it to be
550 * page-aligned, so we round the size up for that.
551 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700552 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000553 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600554 /*
555 * Once a file is mapped, you can close the file descriptor. It's a
556 * little odd, but quite useful.
557 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700558 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700559 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700560
561 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700562 return len;
563}
Rusty Russelle1e72962007-10-25 15:02:50 +1000564/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700565
Rusty Russell2e04ef72009-07-30 16:03:45 -0600566/*
567 * Simple routine to roll all the commandline arguments together with spaces
568 * between them.
569 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700570static void concat(char *dst, char *args[])
571{
572 unsigned int i, len = 0;
573
574 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100575 if (i) {
576 strcat(dst+len, " ");
577 len++;
578 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700579 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100580 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700581 }
582 /* In case it's empty. */
583 dst[len] = '\0';
584}
585
Rusty Russell2e04ef72009-07-30 16:03:45 -0600586/*L:185
587 * This is where we actually tell the kernel to initialize the Guest. We
Rusty Russelle1e72962007-10-25 15:02:50 +1000588 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300589 * the base of Guest "physical" memory, the top physical page to allow and the
Rusty Russell2e04ef72009-07-30 16:03:45 -0600590 * entry point for the Guest.
591 */
Rusty Russell56739c802009-06-12 22:26:59 -0600592static void tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700593{
Jes Sorensen511801d2007-10-22 11:03:31 +1000594 unsigned long args[] = { LHREQ_INITIALIZE,
595 (unsigned long)guest_base,
Rusty Russell7313d522015-02-11 15:15:10 +1030596 guest_limit / getpagesize(), start,
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030597 (guest_mmio+getpagesize()-1) / getpagesize() };
598 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
599 guest_base, guest_base + guest_limit,
600 guest_limit, guest_mmio);
Rusty Russell56739c802009-06-12 22:26:59 -0600601 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
602 if (write(lguest_fd, args, sizeof(args)) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700603 err(1, "Writing to /dev/lguest");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700604}
Rusty Russelldde79782007-07-26 10:41:03 -0700605/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700606
Rusty Russella91d74a2009-07-30 16:03:45 -0600607/*L:200
Rusty Russelldde79782007-07-26 10:41:03 -0700608 * Device Handling.
609 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000610 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700611 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000612 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700613 * if something funny is going on:
614 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700615static void *_check_pointer(unsigned long addr, unsigned int size,
616 unsigned int line)
617{
Rusty Russell2e04ef72009-07-30 16:03:45 -0600618 /*
Philip Sanderson5230ff02011-01-20 21:37:28 -0600619 * Check if the requested address and size exceeds the allocated memory,
620 * or addr + size wraps around.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600621 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600622 if ((addr + size) > guest_limit || (addr + size) < addr)
Rusty Russell17cbca22007-10-22 11:24:22 +1000623 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600624 /*
625 * We return a pointer for the caller's convenience, now we know it's
626 * safe to use.
627 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000628 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700629}
Rusty Russelldde79782007-07-26 10:41:03 -0700630/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700631#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
632
Rusty Russell2e04ef72009-07-30 16:03:45 -0600633/*
634 * Each buffer in the virtqueues is actually a chain of descriptors. This
Rusty Russelle1e72962007-10-25 15:02:50 +1000635 * function returns the next descriptor in the chain, or vq->vring.num if we're
Rusty Russell2e04ef72009-07-30 16:03:45 -0600636 * at the end.
637 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100638static unsigned next_desc(struct vring_desc *desc,
639 unsigned int i, unsigned int max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000640{
641 unsigned int next;
642
643 /* If this descriptor says it doesn't chain, we're done. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100644 if (!(desc[i].flags & VRING_DESC_F_NEXT))
645 return max;
Rusty Russell17cbca22007-10-22 11:24:22 +1000646
647 /* Check they're not leading us off end of descriptors. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100648 next = desc[i].next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000649 /* Make sure compiler knows to grab that: we don't want it changing! */
650 wmb();
651
Mark McLoughlind1f01322009-05-11 18:11:46 +0100652 if (next >= max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000653 errx(1, "Desc next is %u", next);
654
655 return next;
656}
657
Rusty Russella91d74a2009-07-30 16:03:45 -0600658/*
659 * This actually sends the interrupt for this virtqueue, if we've used a
660 * buffer.
661 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600662static void trigger_irq(struct virtqueue *vq)
663{
Rusty Russelld9028ed2015-02-11 15:21:01 +1030664 unsigned long buf[] = { LHREQ_IRQ, vq->dev->config.irq_line };
Rusty Russell38bc2b82009-06-12 22:27:11 -0600665
Rusty Russell95c517c2009-06-12 22:27:11 -0600666 /* Don't inform them if nothing used. */
667 if (!vq->pending_used)
668 return;
669 vq->pending_used = 0;
670
Rusty Russellca60a422009-09-23 22:26:47 -0600671 /* If they don't want an interrupt, don't send one... */
672 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
Rusty Russell990c91f2011-05-30 11:14:12 -0600673 return;
Rusty Russellca60a422009-09-23 22:26:47 -0600674 }
Rusty Russell38bc2b82009-06-12 22:27:11 -0600675
Rusty Russell8dc425f2015-02-13 17:13:41 +1030676 /*
677 * 4.1.4.5.1:
678 *
679 * If MSI-X capability is disabled, the device MUST set the Queue
680 * Interrupt bit in ISR status before sending a virtqueue notification
681 * to the driver.
682 */
Rusty Russelld9028ed2015-02-11 15:21:01 +1030683 vq->dev->mmio->isr = 0x1;
Rusty Russell93153072015-02-11 15:15:11 +1030684
Rusty Russell38bc2b82009-06-12 22:27:11 -0600685 /* Send the Guest an interrupt tell them we used something up. */
686 if (write(lguest_fd, buf, sizeof(buf)) != 0)
Rusty Russelld9028ed2015-02-11 15:21:01 +1030687 err(1, "Triggering irq %i", vq->dev->config.irq_line);
Rusty Russell38bc2b82009-06-12 22:27:11 -0600688}
689
Rusty Russell2e04ef72009-07-30 16:03:45 -0600690/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600691 * This looks in the virtqueue for the first available buffer, and converts
Rusty Russell17cbca22007-10-22 11:24:22 +1000692 * it to an iovec for convenient access. Since descriptors consist of some
693 * number of output then some number of input descriptors, it's actually two
694 * iovecs, but we pack them into one and note how many of each there were.
695 *
Rusty Russella91d74a2009-07-30 16:03:45 -0600696 * This function waits if necessary, and returns the descriptor number found.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600697 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600698static unsigned wait_for_vq_desc(struct virtqueue *vq,
699 struct iovec iov[],
700 unsigned int *out_num, unsigned int *in_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000701{
Mark McLoughlind1f01322009-05-11 18:11:46 +0100702 unsigned int i, head, max;
703 struct vring_desc *desc;
Rusty Russell659a0e62009-06-12 22:27:10 -0600704 u16 last_avail = lg_last_avail(vq);
705
Rusty Russella91d74a2009-07-30 16:03:45 -0600706 /* There's nothing available? */
Rusty Russell659a0e62009-06-12 22:27:10 -0600707 while (last_avail == vq->vring.avail->idx) {
708 u64 event;
709
Rusty Russella91d74a2009-07-30 16:03:45 -0600710 /*
711 * Since we're about to sleep, now is a good time to tell the
712 * Guest about what we've used up to now.
713 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600714 trigger_irq(vq);
715
Rusty Russellb60da132009-06-12 22:27:12 -0600716 /* OK, now we need to know about added descriptors. */
717 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
718
Rusty Russell2e04ef72009-07-30 16:03:45 -0600719 /*
720 * They could have slipped one in as we were doing that: make
721 * sure it's written, then check again.
722 */
Rusty Russellb60da132009-06-12 22:27:12 -0600723 mb();
724 if (last_avail != vq->vring.avail->idx) {
725 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
726 break;
727 }
728
Rusty Russell659a0e62009-06-12 22:27:10 -0600729 /* Nothing new? Wait for eventfd to tell us they refilled. */
730 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
731 errx(1, "Event read failed?");
Rusty Russellb60da132009-06-12 22:27:12 -0600732
733 /* We don't need to be notified again. */
734 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russell659a0e62009-06-12 22:27:10 -0600735 }
Rusty Russell17cbca22007-10-22 11:24:22 +1000736
737 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500738 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000739 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500740 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000741
Rusty Russell8fd9a632013-07-02 15:35:13 +0930742 /*
743 * Make sure we read the descriptor number *after* we read the ring
744 * update; don't let the cpu or compiler change the order.
745 */
746 rmb();
747
Rusty Russell2e04ef72009-07-30 16:03:45 -0600748 /*
749 * Grab the next descriptor number they're advertising, and increment
750 * the index we've seen.
751 */
Rusty Russellb5111792008-07-29 09:58:34 -0500752 head = vq->vring.avail->ring[last_avail % vq->vring.num];
753 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000754
755 /* If their number is silly, that's a fatal mistake. */
756 if (head >= vq->vring.num)
757 errx(1, "Guest says index %u is available", head);
758
759 /* When we start there are none of either input nor output. */
760 *out_num = *in_num = 0;
761
Mark McLoughlind1f01322009-05-11 18:11:46 +0100762 max = vq->vring.num;
763 desc = vq->vring.desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000764 i = head;
Mark McLoughlind1f01322009-05-11 18:11:46 +0100765
Rusty Russell2e04ef72009-07-30 16:03:45 -0600766 /*
Rusty Russell8fd9a632013-07-02 15:35:13 +0930767 * We have to read the descriptor after we read the descriptor number,
768 * but there's a data dependency there so the CPU shouldn't reorder
769 * that: no rmb() required.
770 */
771
772 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -0600773 * If this is an indirect entry, then this buffer contains a descriptor
774 * table which we handle as if it's any normal descriptor chain.
775 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100776 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
777 if (desc[i].len % sizeof(struct vring_desc))
778 errx(1, "Invalid size for indirect buffer table");
779
780 max = desc[i].len / sizeof(struct vring_desc);
781 desc = check_pointer(desc[i].addr, desc[i].len);
782 i = 0;
783 }
784
Rusty Russell17cbca22007-10-22 11:24:22 +1000785 do {
786 /* Grab the first descriptor, and check it's OK. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100787 iov[*out_num + *in_num].iov_len = desc[i].len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000788 iov[*out_num + *in_num].iov_base
Mark McLoughlind1f01322009-05-11 18:11:46 +0100789 = check_pointer(desc[i].addr, desc[i].len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000790 /* If this is an input descriptor, increment that count. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100791 if (desc[i].flags & VRING_DESC_F_WRITE)
Rusty Russell17cbca22007-10-22 11:24:22 +1000792 (*in_num)++;
793 else {
Rusty Russell2e04ef72009-07-30 16:03:45 -0600794 /*
795 * If it's an output descriptor, they're all supposed
796 * to come before any input descriptors.
797 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000798 if (*in_num)
799 errx(1, "Descriptor has out after in");
800 (*out_num)++;
801 }
802
803 /* If we've got too many, that implies a descriptor loop. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100804 if (*out_num + *in_num > max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000805 errx(1, "Looped descriptor");
Mark McLoughlind1f01322009-05-11 18:11:46 +0100806 } while ((i = next_desc(desc, i, max)) != max);
Rusty Russell17cbca22007-10-22 11:24:22 +1000807
808 return head;
809}
810
Rusty Russell2e04ef72009-07-30 16:03:45 -0600811/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600812 * After we've used one of their buffers, we tell the Guest about it. Sometime
813 * later we'll want to send them an interrupt using trigger_irq(); note that
814 * wait_for_vq_desc() does that for us if it has to wait.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600815 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000816static void add_used(struct virtqueue *vq, unsigned int head, int len)
817{
818 struct vring_used_elem *used;
819
Rusty Russell2e04ef72009-07-30 16:03:45 -0600820 /*
821 * The virtqueue contains a ring of used buffers. Get a pointer to the
822 * next entry in that used ring.
823 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000824 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
825 used->id = head;
826 used->len = len;
827 /* Make sure buffer is written before we update index. */
828 wmb();
829 vq->vring.used->idx++;
Rusty Russell95c517c2009-06-12 22:27:11 -0600830 vq->pending_used++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000831}
832
Rusty Russell17cbca22007-10-22 11:24:22 +1000833/* And here's the combo meal deal. Supersize me! */
Rusty Russell56739c802009-06-12 22:26:59 -0600834static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
Rusty Russell17cbca22007-10-22 11:24:22 +1000835{
836 add_used(vq, head, len);
Rusty Russell56739c802009-06-12 22:26:59 -0600837 trigger_irq(vq);
Rusty Russell17cbca22007-10-22 11:24:22 +1000838}
839
Rusty Russelle1e72962007-10-25 15:02:50 +1000840/*
841 * The Console
842 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600843 * We associate some data with the console for our exit hack.
844 */
Rusty Russell1842f232009-07-30 16:03:46 -0600845struct console_abort {
Rusty Russelldde79782007-07-26 10:41:03 -0700846 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700847 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700848 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700849 struct timeval start;
850};
851
Rusty Russelldde79782007-07-26 10:41:03 -0700852/* This is the routine which handles console input (ie. stdin). */
Rusty Russell659a0e62009-06-12 22:27:10 -0600853static void console_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700854{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700855 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000856 unsigned int head, in_num, out_num;
Rusty Russell659a0e62009-06-12 22:27:10 -0600857 struct console_abort *abort = vq->dev->priv;
858 struct iovec iov[vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700859
Rusty Russella91d74a2009-07-30 16:03:45 -0600860 /* Make sure there's a descriptor available. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600861 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000862 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000863 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700864
Rusty Russella91d74a2009-07-30 16:03:45 -0600865 /* Read into it. This is where we usually wait. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600866 len = readv(STDIN_FILENO, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700867 if (len <= 0) {
Rusty Russell659a0e62009-06-12 22:27:10 -0600868 /* Ran out of input? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700869 warnx("Failed to get console input, ignoring console.");
Rusty Russell2e04ef72009-07-30 16:03:45 -0600870 /*
871 * For simplicity, dying threads kill the whole Launcher. So
872 * just nap here.
873 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600874 for (;;)
875 pause();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700876 }
877
Rusty Russella91d74a2009-07-30 16:03:45 -0600878 /* Tell the Guest we used a buffer. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600879 add_used_and_trigger(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700880
Rusty Russell2e04ef72009-07-30 16:03:45 -0600881 /*
882 * Three ^C within one second? Exit.
Rusty Russelldde79782007-07-26 10:41:03 -0700883 *
Rusty Russell659a0e62009-06-12 22:27:10 -0600884 * This is such a hack, but works surprisingly well. Each ^C has to
885 * be in a buffer by itself, so they can't be too fast. But we check
886 * that we get three within about a second, so they can't be too
Rusty Russell2e04ef72009-07-30 16:03:45 -0600887 * slow.
888 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600889 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700890 abort->count = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -0600891 return;
892 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700893
Rusty Russell659a0e62009-06-12 22:27:10 -0600894 abort->count++;
895 if (abort->count == 1)
896 gettimeofday(&abort->start, NULL);
897 else if (abort->count == 3) {
898 struct timeval now;
899 gettimeofday(&now, NULL);
900 /* Kill all Launcher processes with SIGINT, like normal ^C */
901 if (now.tv_sec <= abort->start.tv_sec+1)
902 kill(0, SIGINT);
903 abort->count = 0;
904 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700905}
906
Rusty Russell659a0e62009-06-12 22:27:10 -0600907/* This is the routine which handles console output (ie. stdout). */
908static void console_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700909{
Rusty Russell17cbca22007-10-22 11:24:22 +1000910 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000911 struct iovec iov[vq->vring.num];
912
Rusty Russella91d74a2009-07-30 16:03:45 -0600913 /* We usually wait in here, for the Guest to give us something. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600914 head = wait_for_vq_desc(vq, iov, &out, &in);
915 if (in)
916 errx(1, "Input buffers in console output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600917
918 /* writev can return a partial write, so we loop here. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600919 while (!iov_empty(iov, out)) {
920 int len = writev(STDOUT_FILENO, iov, out);
Sakari Ailuse0377e22011-06-26 19:36:46 +0300921 if (len <= 0) {
922 warn("Write to stdout gave %i (%d)", len, errno);
923 break;
924 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030925 iov_consume(iov, out, NULL, len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000926 }
Rusty Russella91d74a2009-07-30 16:03:45 -0600927
928 /*
929 * We're finished with that buffer: if we're going to sleep,
930 * wait_for_vq_desc() will prod the Guest with an interrupt.
931 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600932 add_used(vq, head, 0);
Rusty Russella1618832008-07-29 09:58:35 -0500933}
934
Rusty Russelle1e72962007-10-25 15:02:50 +1000935/*
936 * The Network
937 *
938 * Handling output for network is also simple: we get all the output buffers
Rusty Russell659a0e62009-06-12 22:27:10 -0600939 * and write them to /dev/net/tun.
Rusty Russella6bd8e12008-03-28 11:05:53 -0500940 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600941struct net_info {
942 int tunfd;
943};
944
945static void net_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700946{
Rusty Russell659a0e62009-06-12 22:27:10 -0600947 struct net_info *net_info = vq->dev->priv;
948 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000949 struct iovec iov[vq->vring.num];
950
Rusty Russella91d74a2009-07-30 16:03:45 -0600951 /* We usually wait in here for the Guest to give us a packet. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600952 head = wait_for_vq_desc(vq, iov, &out, &in);
953 if (in)
954 errx(1, "Input buffers in net output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600955 /*
956 * Send the whole thing through to /dev/net/tun. It expects the exact
957 * same format: what a coincidence!
958 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600959 if (writev(net_info->tunfd, iov, out) < 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +0300960 warnx("Write to tun failed (%d)?", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -0600961
962 /*
963 * Done with that one; wait_for_vq_desc() will send the interrupt if
964 * all packets are processed.
965 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600966 add_used(vq, head, 0);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700967}
968
Rusty Russella91d74a2009-07-30 16:03:45 -0600969/*
970 * Handling network input is a bit trickier, because I've tried to optimize it.
971 *
972 * First we have a helper routine which tells is if from this file descriptor
973 * (ie. the /dev/net/tun device) will block:
974 */
Rusty Russell4a8962e2009-06-12 22:27:12 -0600975static bool will_block(int fd)
976{
977 fd_set fdset;
978 struct timeval zero = { 0, 0 };
979 FD_ZERO(&fdset);
980 FD_SET(fd, &fdset);
981 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
982}
983
Rusty Russella91d74a2009-07-30 16:03:45 -0600984/*
985 * This handles packets coming in from the tun device to our Guest. Like all
986 * service routines, it gets called again as soon as it returns, so you don't
987 * see a while(1) loop here.
988 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600989static void net_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700990{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700991 int len;
Rusty Russell659a0e62009-06-12 22:27:10 -0600992 unsigned int head, out, in;
993 struct iovec iov[vq->vring.num];
994 struct net_info *net_info = vq->dev->priv;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700995
Rusty Russella91d74a2009-07-30 16:03:45 -0600996 /*
997 * Get a descriptor to write an incoming packet into. This will also
998 * send an interrupt if they're out of descriptors.
999 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001000 head = wait_for_vq_desc(vq, iov, &out, &in);
1001 if (out)
1002 errx(1, "Output buffers in net input queue?");
Rusty Russell4a8962e2009-06-12 22:27:12 -06001003
Rusty Russella91d74a2009-07-30 16:03:45 -06001004 /*
1005 * If it looks like we'll block reading from the tun device, send them
1006 * an interrupt.
1007 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001008 if (vq->pending_used && will_block(net_info->tunfd))
1009 trigger_irq(vq);
1010
Rusty Russella91d74a2009-07-30 16:03:45 -06001011 /*
1012 * Read in the packet. This is where we normally wait (when there's no
1013 * incoming network traffic).
1014 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001015 len = readv(net_info->tunfd, iov, in);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001016 if (len <= 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +03001017 warn("Failed to read from tun (%d).", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -06001018
1019 /*
1020 * Mark that packet buffer as used, but don't interrupt here. We want
1021 * to wait until we've done as much work as we can.
1022 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001023 add_used(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001024}
Rusty Russella91d74a2009-07-30 16:03:45 -06001025/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001026
Rusty Russella91d74a2009-07-30 16:03:45 -06001027/* This is the helper to create threads: run the service routine in a loop. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001028static int do_thread(void *_vq)
Rusty Russell56ae43d2007-10-22 11:24:23 +10001029{
Rusty Russell659a0e62009-06-12 22:27:10 -06001030 struct virtqueue *vq = _vq;
1031
1032 for (;;)
1033 vq->service(vq);
1034 return 0;
Rusty Russell56ae43d2007-10-22 11:24:23 +10001035}
1036
Rusty Russell2e04ef72009-07-30 16:03:45 -06001037/*
1038 * When a child dies, we kill our entire process group with SIGTERM. This
1039 * also has the side effect that the shell restores the console for us!
1040 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001041static void kill_launcher(int signal)
Rusty Russell5dae7852008-07-29 09:58:35 -05001042{
Rusty Russell659a0e62009-06-12 22:27:10 -06001043 kill(0, SIGTERM);
1044}
1045
Rusty Russelld2dbdac2015-02-13 17:13:40 +10301046static void reset_vq_pci_config(struct virtqueue *vq)
1047{
1048 vq->pci_config.queue_size = VIRTQUEUE_NUM;
1049 vq->pci_config.queue_enable = 0;
1050}
1051
Rusty Russell659a0e62009-06-12 22:27:10 -06001052static void reset_device(struct device *dev)
1053{
1054 struct virtqueue *vq;
1055
1056 verbose("Resetting device %s\n", dev->name);
1057
1058 /* Clear any features they've acked. */
Rusty Russelld9028ed2015-02-11 15:21:01 +10301059 dev->features_accepted = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06001060
1061 /* We're going to be explicitly killing threads, so ignore them. */
1062 signal(SIGCHLD, SIG_IGN);
1063
Rusty Russelld2dbdac2015-02-13 17:13:40 +10301064 /*
1065 * 4.1.4.3.1:
1066 *
1067 * The device MUST present a 0 in queue_enable on reset.
1068 *
1069 * This means we set it here, and reset the saved ones in every vq.
1070 */
1071 dev->mmio->cfg.queue_enable = 0;
1072
Rusty Russelld9028ed2015-02-11 15:21:01 +10301073 /* Get rid of the virtqueue threads */
Rusty Russell659a0e62009-06-12 22:27:10 -06001074 for (vq = dev->vq; vq; vq = vq->next) {
Rusty Russelld2dbdac2015-02-13 17:13:40 +10301075 vq->last_avail_idx = 0;
1076 reset_vq_pci_config(vq);
Rusty Russell659a0e62009-06-12 22:27:10 -06001077 if (vq->thread != (pid_t)-1) {
1078 kill(vq->thread, SIGTERM);
1079 waitpid(vq->thread, NULL, 0);
1080 vq->thread = (pid_t)-1;
1081 }
Rusty Russell659a0e62009-06-12 22:27:10 -06001082 }
1083 dev->running = false;
1084
1085 /* Now we care if threads die. */
1086 signal(SIGCHLD, (void *)kill_launcher);
1087}
1088
Rusty Russell659a0e62009-06-12 22:27:10 -06001089static void cleanup_devices(void)
1090{
Rusty Russelld9028ed2015-02-11 15:21:01 +10301091 unsigned int i;
Rusty Russell659a0e62009-06-12 22:27:10 -06001092
Rusty Russelld9028ed2015-02-11 15:21:01 +10301093 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1094 struct device *d = devices.pci[i];
1095 if (!d)
1096 continue;
1097 reset_device(d);
1098 }
Rusty Russell659a0e62009-06-12 22:27:10 -06001099
1100 /* If we saved off the original terminal settings, restore them now. */
1101 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1102 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
Rusty Russell5dae7852008-07-29 09:58:35 -05001103}
1104
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301105/*L:217
1106 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1107 * code.
1108 */
1109
Rusty Russell8e709462015-02-11 15:15:12 +10301110/* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1111static struct device pci_host_bridge;
1112
1113static void init_pci_host_bridge(void)
1114{
1115 pci_host_bridge.name = "PCI Host Bridge";
1116 pci_host_bridge.config.class = 0x06; /* bridge */
1117 pci_host_bridge.config.subclass = 0; /* host bridge */
1118 devices.pci[0] = &pci_host_bridge;
1119}
1120
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301121/* The IO ports used to read the PCI config space. */
1122#define PCI_CONFIG_ADDR 0xCF8
1123#define PCI_CONFIG_DATA 0xCFC
1124
1125/*
1126 * Not really portable, but does help readability: this is what the Guest
1127 * writes to the PCI_CONFIG_ADDR IO port.
1128 */
1129union pci_config_addr {
1130 struct {
1131 unsigned mbz: 2;
1132 unsigned offset: 6;
1133 unsigned funcnum: 3;
1134 unsigned devnum: 5;
1135 unsigned busnum: 8;
1136 unsigned reserved: 7;
1137 unsigned enabled : 1;
1138 } bits;
1139 u32 val;
1140};
1141
1142/*
1143 * We cache what they wrote to the address port, so we know what they're
1144 * talking about when they access the data port.
1145 */
1146static union pci_config_addr pci_config_addr;
1147
1148static struct device *find_pci_device(unsigned int index)
1149{
1150 return devices.pci[index];
1151}
1152
1153/* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1154static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1155{
1156 assert(off < 4);
1157 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1158 *val = (v >> (off * 8)) & mask;
1159}
1160
1161/* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1162static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1163{
1164 assert(off < 4);
1165 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1166 *dst &= ~(mask << (off * 8));
1167 *dst |= (v & mask) << (off * 8);
1168}
1169
1170/*
1171 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1172 * PCI_CONFIG_ADDR.
1173 */
1174static struct device *dev_and_reg(u32 *reg)
1175{
1176 if (!pci_config_addr.bits.enabled)
1177 return NULL;
1178
1179 if (pci_config_addr.bits.funcnum != 0)
1180 return NULL;
1181
1182 if (pci_config_addr.bits.busnum != 0)
1183 return NULL;
1184
1185 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1186 return NULL;
1187
1188 *reg = pci_config_addr.bits.offset;
1189 return find_pci_device(pci_config_addr.bits.devnum);
1190}
1191
Rusty Russell59eba782015-02-11 15:24:01 +10301192/*
1193 * We can get invalid combinations of values while they're writing, so we
1194 * only fault if they try to write with some invalid bar/offset/length.
1195 */
1196static bool valid_bar_access(struct device *d,
1197 struct virtio_pci_cfg_cap *cfg_access)
1198{
1199 /* We only have 1 bar (BAR0) */
1200 if (cfg_access->cap.bar != 0)
1201 return false;
1202
1203 /* Check it's within BAR0. */
1204 if (cfg_access->cap.offset >= d->mmio_size
1205 || cfg_access->cap.offset + cfg_access->cap.length > d->mmio_size)
1206 return false;
1207
1208 /* Check length is 1, 2 or 4. */
1209 if (cfg_access->cap.length != 1
1210 && cfg_access->cap.length != 2
1211 && cfg_access->cap.length != 4)
1212 return false;
1213
Rusty Russellc97eb672015-02-13 17:13:42 +10301214 /*
1215 * 4.1.4.7.2:
1216 *
1217 * The driver MUST NOT write a cap.offset which is not a multiple of
1218 * cap.length (ie. all accesses MUST be aligned).
1219 */
Rusty Russell59eba782015-02-11 15:24:01 +10301220 if (cfg_access->cap.offset % cfg_access->cap.length != 0)
1221 return false;
1222
1223 /* Return pointer into word in BAR0. */
1224 return true;
1225}
1226
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301227/* Is this accessing the PCI config address port?. */
1228static bool is_pci_addr_port(u16 port)
1229{
1230 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1231}
1232
1233static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1234{
1235 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1236 &pci_config_addr.val);
1237 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1238 pci_config_addr.bits.enabled ? "" : " DISABLED",
1239 val, mask,
1240 pci_config_addr.bits.busnum,
1241 pci_config_addr.bits.devnum,
1242 pci_config_addr.bits.funcnum,
1243 pci_config_addr.bits.offset);
1244 return true;
1245}
1246
1247static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1248{
1249 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1250}
1251
1252/* Is this accessing the PCI config data port?. */
1253static bool is_pci_data_port(u16 port)
1254{
1255 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1256}
1257
Rusty Russell59eba782015-02-11 15:24:01 +10301258static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask);
1259
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301260static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1261{
1262 u32 reg, portoff;
1263 struct device *d = dev_and_reg(&reg);
1264
1265 /* Complain if they don't belong to a device. */
1266 if (!d)
1267 return false;
1268
1269 /* They can do 1 byte writes, etc. */
1270 portoff = port - PCI_CONFIG_DATA;
1271
1272 /*
1273 * PCI uses a weird way to determine the BAR size: the OS
1274 * writes all 1's, and sees which ones stick.
1275 */
1276 if (&d->config_words[reg] == &d->config.bar[0]) {
1277 int i;
1278
1279 iowrite(portoff, val, mask, &d->config.bar[0]);
1280 for (i = 0; (1 << i) < d->mmio_size; i++)
1281 d->config.bar[0] &= ~(1 << i);
1282 return true;
1283 } else if ((&d->config_words[reg] > &d->config.bar[0]
1284 && &d->config_words[reg] <= &d->config.bar[6])
1285 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1286 /* Allow writing to any other BAR, or expansion ROM */
1287 iowrite(portoff, val, mask, &d->config_words[reg]);
1288 return true;
1289 /* We let them overide latency timer and cacheline size */
1290 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1291 /* Only let them change the first two fields. */
1292 if (mask == 0xFFFFFFFF)
1293 mask = 0xFFFF;
1294 iowrite(portoff, val, mask, &d->config_words[reg]);
1295 return true;
1296 } else if (&d->config_words[reg] == (void *)&d->config.command
1297 && mask == 0xFFFF) {
1298 /* Ignore command writes. */
1299 return true;
Rusty Russell59eba782015-02-11 15:24:01 +10301300 } else if (&d->config_words[reg]
1301 == (void *)&d->config.cfg_access.cap.bar
1302 || &d->config_words[reg]
1303 == &d->config.cfg_access.cap.length
1304 || &d->config_words[reg]
1305 == &d->config.cfg_access.cap.offset) {
1306
1307 /*
1308 * The VIRTIO_PCI_CAP_PCI_CFG capability
1309 * provides a backdoor to access the MMIO
1310 * regions without mapping them. Weird, but
1311 * useful.
1312 */
1313 iowrite(portoff, val, mask, &d->config_words[reg]);
1314 return true;
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301315 } else if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
Rusty Russell59eba782015-02-11 15:24:01 +10301316 u32 write_mask;
1317
Rusty Russell8dc425f2015-02-13 17:13:41 +10301318 /*
1319 * 4.1.4.7.1:
1320 *
1321 * Upon detecting driver write access to pci_cfg_data, the
1322 * device MUST execute a write access at offset cap.offset at
1323 * BAR selected by cap.bar using the first cap.length bytes
1324 * from pci_cfg_data.
1325 */
1326
Rusty Russell59eba782015-02-11 15:24:01 +10301327 /* Must be bar 0 */
1328 if (!valid_bar_access(d, &d->config.cfg_access))
1329 return false;
1330
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301331 iowrite(portoff, val, mask, &d->config.cfg_access.pci_cfg_data);
Rusty Russell59eba782015-02-11 15:24:01 +10301332
1333 /*
1334 * Now emulate a write. The mask we use is set by
1335 * len, *not* this write!
1336 */
1337 write_mask = (1ULL<<(8*d->config.cfg_access.cap.length)) - 1;
1338 verbose("Window writing %#x/%#x to bar %u, offset %u len %u\n",
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301339 d->config.cfg_access.pci_cfg_data, write_mask,
Rusty Russell59eba782015-02-11 15:24:01 +10301340 d->config.cfg_access.cap.bar,
1341 d->config.cfg_access.cap.offset,
1342 d->config.cfg_access.cap.length);
1343
1344 emulate_mmio_write(d, d->config.cfg_access.cap.offset,
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301345 d->config.cfg_access.pci_cfg_data,
1346 write_mask);
Rusty Russell59eba782015-02-11 15:24:01 +10301347 return true;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301348 }
1349
Rusty Russellc97eb672015-02-13 17:13:42 +10301350 /*
1351 * 4.1.4.1:
1352 *
1353 * The driver MUST NOT write into any field of the capability
1354 * structure, with the exception of those with cap_type
1355 * VIRTIO_PCI_CAP_PCI_CFG...
1356 */
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301357 return false;
1358}
1359
Rusty Russell59eba782015-02-11 15:24:01 +10301360static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask);
1361
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301362static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1363{
1364 u32 reg;
1365 struct device *d = dev_and_reg(&reg);
1366
1367 if (!d)
1368 return;
Rusty Russell59eba782015-02-11 15:24:01 +10301369
1370 /* Read through the PCI MMIO access window is special */
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301371 if (&d->config_words[reg] == &d->config.cfg_access.pci_cfg_data) {
Rusty Russell59eba782015-02-11 15:24:01 +10301372 u32 read_mask;
1373
Rusty Russell8dc425f2015-02-13 17:13:41 +10301374 /*
1375 * 4.1.4.7.1:
1376 *
1377 * Upon detecting driver read access to pci_cfg_data, the
1378 * device MUST execute a read access of length cap.length at
1379 * offset cap.offset at BAR selected by cap.bar and store the
1380 * first cap.length bytes in pci_cfg_data.
1381 */
Rusty Russell59eba782015-02-11 15:24:01 +10301382 /* Must be bar 0 */
1383 if (!valid_bar_access(d, &d->config.cfg_access))
1384 errx(1, "Invalid cfg_access to bar%u, offset %u len %u",
1385 d->config.cfg_access.cap.bar,
1386 d->config.cfg_access.cap.offset,
1387 d->config.cfg_access.cap.length);
1388
1389 /*
1390 * Read into the window. The mask we use is set by
1391 * len, *not* this read!
1392 */
1393 read_mask = (1ULL<<(8*d->config.cfg_access.cap.length))-1;
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301394 d->config.cfg_access.pci_cfg_data
Rusty Russell59eba782015-02-11 15:24:01 +10301395 = emulate_mmio_read(d,
1396 d->config.cfg_access.cap.offset,
1397 read_mask);
1398 verbose("Window read %#x/%#x from bar %u, offset %u len %u\n",
Rusty Russellb2ce1ea2015-02-13 17:13:41 +10301399 d->config.cfg_access.pci_cfg_data, read_mask,
Rusty Russell59eba782015-02-11 15:24:01 +10301400 d->config.cfg_access.cap.bar,
1401 d->config.cfg_access.cap.offset,
1402 d->config.cfg_access.cap.length);
1403 }
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301404 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1405}
1406
Rusty Russellc565650b2015-02-11 15:15:10 +10301407/*L:216
1408 * This is where we emulate a handful of Guest instructions. It's ugly
1409 * and we used to do it in the kernel but it grew over time.
1410 */
1411
1412/*
1413 * We use the ptrace syscall's pt_regs struct to talk about registers
1414 * to lguest: these macros convert the names to the offsets.
1415 */
1416#define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1417#define setreg(name, val) \
1418 setreg_off(offsetof(struct user_regs_struct, name), (val))
1419
1420static u32 getreg_off(size_t offset)
1421{
1422 u32 r;
1423 unsigned long args[] = { LHREQ_GETREG, offset };
1424
1425 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1426 err(1, "Getting register %u", offset);
1427 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1428 err(1, "Reading register %u", offset);
1429
1430 return r;
1431}
1432
1433static void setreg_off(size_t offset, u32 val)
1434{
1435 unsigned long args[] = { LHREQ_SETREG, offset, val };
1436
1437 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1438 err(1, "Setting register %u", offset);
1439}
1440
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301441/* Get register by instruction encoding */
1442static u32 getreg_num(unsigned regnum, u32 mask)
1443{
1444 /* 8 bit ops use regnums 4-7 for high parts of word */
1445 if (mask == 0xFF && (regnum & 0x4))
1446 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1447
1448 switch (regnum) {
1449 case 0: return getreg(eax) & mask;
1450 case 1: return getreg(ecx) & mask;
1451 case 2: return getreg(edx) & mask;
1452 case 3: return getreg(ebx) & mask;
1453 case 4: return getreg(esp) & mask;
1454 case 5: return getreg(ebp) & mask;
1455 case 6: return getreg(esi) & mask;
1456 case 7: return getreg(edi) & mask;
1457 }
1458 abort();
1459}
1460
1461/* Set register by instruction encoding */
1462static void setreg_num(unsigned regnum, u32 val, u32 mask)
1463{
1464 /* Don't try to set bits out of range */
1465 assert(~(val & ~mask));
1466
1467 /* 8 bit ops use regnums 4-7 for high parts of word */
1468 if (mask == 0xFF && (regnum & 0x4)) {
1469 /* Construct the 16 bits we want. */
1470 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1471 setreg_num(regnum & 0x3, val, 0xFFFF);
1472 return;
1473 }
1474
1475 switch (regnum) {
1476 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1477 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1478 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1479 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1480 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1481 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1482 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1483 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1484 }
1485 abort();
1486}
1487
1488/* Get bytes of displacement appended to instruction, from r/m encoding */
1489static u32 insn_displacement_len(u8 mod_reg_rm)
1490{
1491 /* Switch on the mod bits */
1492 switch (mod_reg_rm >> 6) {
1493 case 0:
1494 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1495 if ((mod_reg_rm & 0x7) == 0x5)
1496 return 2;
1497 /* Normally, mod == 0 means no literal displacement */
1498 return 0;
1499 case 1:
1500 /* One byte displacement */
1501 return 1;
1502 case 2:
1503 /* Four byte displacement */
1504 return 4;
1505 case 3:
1506 /* Register mode */
1507 return 0;
1508 }
1509 abort();
1510}
1511
Rusty Russellc565650b2015-02-11 15:15:10 +10301512static void emulate_insn(const u8 insn[])
1513{
1514 unsigned long args[] = { LHREQ_TRAP, 13 };
1515 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1516 unsigned int eax, port, mask;
1517 /*
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301518 * Default is to return all-ones on IO port reads, which traditionally
Rusty Russellc565650b2015-02-11 15:15:10 +10301519 * means "there's nothing there".
1520 */
1521 u32 val = 0xFFFFFFFF;
1522
1523 /*
1524 * This must be the Guest kernel trying to do something, not userspace!
1525 * The bottom two bits of the CS segment register are the privilege
1526 * level.
1527 */
1528 if ((getreg(xcs) & 3) != 0x1)
1529 goto no_emulate;
1530
1531 /* Decoding x86 instructions is icky. */
1532
1533 /*
1534 * Around 2.6.33, the kernel started using an emulation for the
1535 * cmpxchg8b instruction in early boot on many configurations. This
1536 * code isn't paravirtualized, and it tries to disable interrupts.
1537 * Ignore it, which will Mostly Work.
1538 */
1539 if (insn[insnlen] == 0xfa) {
1540 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1541 insnlen = 1;
1542 goto skip_insn;
1543 }
1544
1545 /*
1546 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1547 */
1548 if (insn[insnlen] == 0x66) {
1549 small_operand = 1;
1550 /* The instruction is 1 byte so far, read the next byte. */
1551 insnlen = 1;
1552 }
1553
1554 /* If the lower bit isn't set, it's a single byte access */
1555 byte_access = !(insn[insnlen] & 1);
1556
1557 /*
1558 * Now we can ignore the lower bit and decode the 4 opcodes
1559 * we need to emulate.
1560 */
1561 switch (insn[insnlen] & 0xFE) {
1562 case 0xE4: /* in <next byte>,%al */
1563 port = insn[insnlen+1];
1564 insnlen += 2;
1565 in = 1;
1566 break;
1567 case 0xEC: /* in (%dx),%al */
1568 port = getreg(edx) & 0xFFFF;
1569 insnlen += 1;
1570 in = 1;
1571 break;
1572 case 0xE6: /* out %al,<next byte> */
1573 port = insn[insnlen+1];
1574 insnlen += 2;
1575 break;
1576 case 0xEE: /* out %al,(%dx) */
1577 port = getreg(edx) & 0xFFFF;
1578 insnlen += 1;
1579 break;
1580 default:
1581 /* OK, we don't know what this is, can't emulate. */
1582 goto no_emulate;
1583 }
1584
1585 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1586 if (byte_access)
1587 mask = 0xFF;
1588 else if (small_operand)
1589 mask = 0xFFFF;
1590 else
1591 mask = 0xFFFFFFFF;
1592
1593 /*
1594 * If it was an "IN" instruction, they expect the result to be read
1595 * into %eax, so we change %eax.
1596 */
1597 eax = getreg(eax);
1598
1599 if (in) {
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301600 /* This is the PS/2 keyboard status; 1 means ready for output */
1601 if (port == 0x64)
1602 val = 1;
1603 else if (is_pci_addr_port(port))
1604 pci_addr_ioread(port, mask, &val);
1605 else if (is_pci_data_port(port))
1606 pci_data_ioread(port, mask, &val);
1607
Rusty Russellc565650b2015-02-11 15:15:10 +10301608 /* Clear the bits we're about to read */
1609 eax &= ~mask;
1610 /* Copy bits in from val. */
1611 eax |= val & mask;
1612 /* Now update the register. */
1613 setreg(eax, eax);
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301614 } else {
1615 if (is_pci_addr_port(port)) {
1616 if (!pci_addr_iowrite(port, mask, eax))
1617 goto bad_io;
1618 } else if (is_pci_data_port(port)) {
1619 if (!pci_data_iowrite(port, mask, eax))
1620 goto bad_io;
1621 }
1622 /* There are many other ports, eg. CMOS clock, serial
1623 * and parallel ports, so we ignore them all. */
Rusty Russellc565650b2015-02-11 15:15:10 +10301624 }
1625
1626 verbose("IO %s of %x to %u: %#08x\n",
1627 in ? "IN" : "OUT", mask, port, eax);
1628skip_insn:
1629 /* Finally, we've "done" the instruction, so move past it. */
1630 setreg(eip, getreg(eip) + insnlen);
1631 return;
1632
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301633bad_io:
1634 warnx("Attempt to %s port %u (%#x mask)",
1635 in ? "read from" : "write to", port, mask);
1636
Rusty Russellc565650b2015-02-11 15:15:10 +10301637no_emulate:
1638 /* Inject trap into Guest. */
1639 if (write(lguest_fd, args, sizeof(args)) < 0)
1640 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1641}
1642
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301643static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1644{
1645 unsigned int i;
1646
1647 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1648 struct device *d = devices.pci[i];
1649
1650 if (!d)
1651 continue;
1652 if (paddr < d->mmio_addr)
1653 continue;
1654 if (paddr >= d->mmio_addr + d->mmio_size)
1655 continue;
1656 *off = paddr - d->mmio_addr;
1657 return d;
1658 }
1659 return NULL;
1660}
1661
Rusty Russell93153072015-02-11 15:15:11 +10301662/* FIXME: Use vq array. */
1663static struct virtqueue *vq_by_num(struct device *d, u32 num)
1664{
1665 struct virtqueue *vq = d->vq;
1666
1667 while (num-- && vq)
1668 vq = vq->next;
1669
1670 return vq;
1671}
1672
1673static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1674 struct virtqueue *vq)
1675{
1676 vq->pci_config = *cfg;
1677}
1678
1679static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1680 struct virtqueue *vq)
1681{
1682 /* Only restore the per-vq part */
1683 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1684
1685 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1686 sizeof(*cfg) - off);
1687}
1688
1689/*
1690 * When they enable the virtqueue, we check that their setup is valid.
1691 */
1692static void enable_virtqueue(struct device *d, struct virtqueue *vq)
1693{
1694 /*
1695 * Create stack for thread. Since the stack grows upwards, we point
1696 * the stack pointer to the end of this region.
1697 */
1698 char *stack = malloc(32768);
1699
1700 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1701 if (vq->pci_config.queue_desc_hi
1702 || vq->pci_config.queue_avail_hi
1703 || vq->pci_config.queue_used_hi)
1704 errx(1, "%s: invalid 64-bit queue address", d->name);
1705
1706 /* Initialize the virtqueue and check they're all in range. */
1707 vq->vring.num = vq->pci_config.queue_size;
1708 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1709 sizeof(*vq->vring.desc) * vq->vring.num);
1710 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1711 sizeof(*vq->vring.avail)
1712 + (sizeof(vq->vring.avail->ring[0])
1713 * vq->vring.num));
1714 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1715 sizeof(*vq->vring.used)
1716 + (sizeof(vq->vring.used->ring[0])
1717 * vq->vring.num));
1718
1719
1720 /* Create a zero-initialized eventfd. */
1721 vq->eventfd = eventfd(0, 0);
1722 if (vq->eventfd < 0)
1723 err(1, "Creating eventfd");
1724
1725 /*
1726 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1727 * we get a signal if it dies.
1728 */
1729 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1730 if (vq->thread == (pid_t)-1)
1731 err(1, "Creating clone");
1732}
1733
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301734static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1735{
Rusty Russell93153072015-02-11 15:15:11 +10301736 struct virtqueue *vq;
1737
1738 switch (off) {
1739 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
Rusty Russell8dc425f2015-02-13 17:13:41 +10301740 /*
1741 * 4.1.4.3.1:
1742 *
1743 * The device MUST present the feature bits it is offering in
1744 * device_feature, starting at bit device_feature_select ∗ 32
1745 * for any device_feature_select written by the driver
1746 */
Rusty Russell93153072015-02-11 15:15:11 +10301747 if (val == 0)
1748 d->mmio->cfg.device_feature = d->features;
1749 else if (val == 1)
1750 d->mmio->cfg.device_feature = (d->features >> 32);
1751 else
1752 d->mmio->cfg.device_feature = 0;
1753 goto write_through32;
1754 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1755 if (val > 1)
1756 errx(1, "%s: Unexpected driver select %u",
1757 d->name, val);
1758 goto write_through32;
1759 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1760 if (d->mmio->cfg.guest_feature_select == 0) {
1761 d->features_accepted &= ~((u64)0xFFFFFFFF);
1762 d->features_accepted |= val;
1763 } else {
1764 assert(d->mmio->cfg.guest_feature_select == 1);
Rusty Russell53aceb42015-02-13 17:13:41 +10301765 d->features_accepted &= 0xFFFFFFFF;
Rusty Russell93153072015-02-11 15:15:11 +10301766 d->features_accepted |= ((u64)val) << 32;
1767 }
1768 if (d->features_accepted & ~d->features)
1769 errx(1, "%s: over-accepted features %#llx of %#llx",
1770 d->name, d->features_accepted, d->features);
1771 goto write_through32;
1772 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1773 verbose("%s: device status -> %#x\n", d->name, val);
Rusty Russell8dc425f2015-02-13 17:13:41 +10301774 /*
1775 * 4.1.4.3.1:
1776 *
1777 * The device MUST reset when 0 is written to device_status,
1778 * and present a 0 in device_status once that is done.
1779 */
Rusty Russell93153072015-02-11 15:15:11 +10301780 if (val == 0)
Rusty Russelld9028ed2015-02-11 15:21:01 +10301781 reset_device(d);
Rusty Russell93153072015-02-11 15:15:11 +10301782 goto write_through8;
1783 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1784 vq = vq_by_num(d, val);
Rusty Russell8dc425f2015-02-13 17:13:41 +10301785 /*
1786 * 4.1.4.3.1:
1787 *
1788 * The device MUST present a 0 in queue_size if the virtqueue
1789 * corresponding to the current queue_select is unavailable.
1790 */
Rusty Russell93153072015-02-11 15:15:11 +10301791 if (!vq) {
1792 d->mmio->cfg.queue_size = 0;
1793 goto write_through16;
1794 }
1795 /* Save registers for old vq, if it was a valid vq */
1796 if (d->mmio->cfg.queue_size)
1797 save_vq_config(&d->mmio->cfg,
1798 vq_by_num(d, d->mmio->cfg.queue_select));
1799 /* Restore the registers for the queue they asked for */
1800 restore_vq_config(&d->mmio->cfg, vq);
1801 goto write_through16;
1802 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
Rusty Russellc97eb672015-02-13 17:13:42 +10301803 /*
1804 * 4.1.4.3.2:
1805 *
1806 * The driver MUST NOT write a value which is not a power of 2
1807 * to queue_size.
1808 */
Rusty Russell93153072015-02-11 15:15:11 +10301809 if (val & (val-1))
1810 errx(1, "%s: invalid queue size %u\n", d->name, val);
1811 if (d->mmio->cfg.queue_enable)
1812 errx(1, "%s: changing queue size on live device",
1813 d->name);
1814 goto write_through16;
1815 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
1816 errx(1, "%s: attempt to set MSIX vector to %u",
1817 d->name, val);
1818 case offsetof(struct virtio_pci_mmio, cfg.queue_enable):
Rusty Russellc97eb672015-02-13 17:13:42 +10301819 /*
1820 * 4.1.4.3.2:
1821 *
1822 * The driver MUST NOT write a 0 to queue_enable.
1823 */
Rusty Russell93153072015-02-11 15:15:11 +10301824 if (val != 1)
1825 errx(1, "%s: setting queue_enable to %u", d->name, val);
1826 d->mmio->cfg.queue_enable = val;
1827 save_vq_config(&d->mmio->cfg,
1828 vq_by_num(d, d->mmio->cfg.queue_select));
Rusty Russellc97eb672015-02-13 17:13:42 +10301829 /*
1830 * 4.1.4.3.2:
1831 *
1832 * The driver MUST configure the other virtqueue fields before
1833 * enabling the virtqueue with queue_enable.
1834 */
Rusty Russell93153072015-02-11 15:15:11 +10301835 enable_virtqueue(d, vq_by_num(d, d->mmio->cfg.queue_select));
1836 goto write_through16;
1837 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
1838 errx(1, "%s: attempt to write to queue_notify_off", d->name);
1839 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
1840 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
1841 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
1842 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
1843 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
1844 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
Rusty Russellc97eb672015-02-13 17:13:42 +10301845 /*
1846 * 4.1.4.3.2:
1847 *
1848 * The driver MUST configure the other virtqueue fields before
1849 * enabling the virtqueue with queue_enable.
1850 */
Rusty Russell93153072015-02-11 15:15:11 +10301851 if (d->mmio->cfg.queue_enable)
1852 errx(1, "%s: changing queue on live device",
1853 d->name);
1854 goto write_through32;
1855 case offsetof(struct virtio_pci_mmio, notify):
1856 vq = vq_by_num(d, val);
1857 if (!vq)
1858 errx(1, "Invalid vq notification on %u", val);
1859 /* Notify the process handling this vq by adding 1 to eventfd */
1860 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
1861 goto write_through16;
1862 case offsetof(struct virtio_pci_mmio, isr):
1863 errx(1, "%s: Unexpected write to isr", d->name);
Rusty Russelle8330d92015-02-11 15:23:01 +10301864 /* Weird corner case: write to emerg_wr of console */
1865 case sizeof(struct virtio_pci_mmio)
1866 + offsetof(struct virtio_console_config, emerg_wr):
1867 if (strcmp(d->name, "console") == 0) {
1868 char c = val;
1869 write(STDOUT_FILENO, &c, 1);
1870 goto write_through32;
1871 }
1872 /* Fall through... */
Rusty Russell93153072015-02-11 15:15:11 +10301873 default:
Rusty Russellc97eb672015-02-13 17:13:42 +10301874 /*
1875 * 4.1.4.3.2:
1876 *
1877 * The driver MUST NOT write to device_feature, num_queues,
1878 * config_generation or queue_notify_off.
1879 */
Rusty Russell93153072015-02-11 15:15:11 +10301880 errx(1, "%s: Unexpected write to offset %u", d->name, off);
1881 }
1882
Rusty Russellc97eb672015-02-13 17:13:42 +10301883
1884 /*
1885 * 4.1.3.1:
1886 *
1887 * The driver MUST access each field using the “natural” access
1888 * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
1889 * 16-bit fields and 8-bit accesses for 8-bit fields.
1890 */
Rusty Russell93153072015-02-11 15:15:11 +10301891write_through32:
1892 if (mask != 0xFFFFFFFF) {
1893 errx(1, "%s: non-32-bit write to offset %u (%#x)",
1894 d->name, off, getreg(eip));
1895 return;
1896 }
1897 memcpy((char *)d->mmio + off, &val, 4);
1898 return;
1899
1900write_through16:
1901 if (mask != 0xFFFF)
1902 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
1903 d->name, mask, off, getreg(eip));
1904 memcpy((char *)d->mmio + off, &val, 2);
1905 return;
1906
1907write_through8:
1908 if (mask != 0xFF)
1909 errx(1, "%s: non-8-bit write to offset %u (%#x)",
1910 d->name, off, getreg(eip));
1911 memcpy((char *)d->mmio + off, &val, 1);
1912 return;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301913}
1914
1915static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
1916{
Rusty Russell93153072015-02-11 15:15:11 +10301917 u8 isr;
1918 u32 val = 0;
1919
1920 switch (off) {
1921 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1922 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
1923 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1924 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1925 goto read_through32;
1926 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
1927 errx(1, "%s: read of msix_config", d->name);
1928 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
1929 goto read_through16;
1930 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1931 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
Rusty Russell8dc425f2015-02-13 17:13:41 +10301932 /*
1933 * 4.1.4.3.1:
1934 *
1935 * The device MUST present a changed config_generation after
1936 * the driver has read a device-specific configuration value
1937 * which has changed since any part of the device-specific
1938 * configuration was last read.
1939 *
1940 * This is simple: none of our devices change config, so this
1941 * is always 0.
1942 */
Rusty Russell93153072015-02-11 15:15:11 +10301943 goto read_through8;
1944 case offsetof(struct virtio_pci_mmio, notify):
1945 goto read_through16;
1946 case offsetof(struct virtio_pci_mmio, isr):
1947 if (mask != 0xFF)
1948 errx(1, "%s: non-8-bit read from offset %u (%#x)",
1949 d->name, off, getreg(eip));
Rusty Russell93153072015-02-11 15:15:11 +10301950 isr = d->mmio->isr;
Rusty Russell8dc425f2015-02-13 17:13:41 +10301951 /*
1952 * 4.1.4.5.1:
1953 *
1954 * The device MUST reset ISR status to 0 on driver read.
1955 */
Rusty Russell93153072015-02-11 15:15:11 +10301956 d->mmio->isr = 0;
1957 return isr;
1958 case offsetof(struct virtio_pci_mmio, padding):
1959 errx(1, "%s: read from padding (%#x)",
1960 d->name, getreg(eip));
1961 default:
1962 /* Read from device config space, beware unaligned overflow */
1963 if (off > d->mmio_size - 4)
1964 errx(1, "%s: read past end (%#x)",
1965 d->name, getreg(eip));
1966 if (mask == 0xFFFFFFFF)
1967 goto read_through32;
1968 else if (mask == 0xFFFF)
1969 goto read_through16;
1970 else
1971 goto read_through8;
1972 }
1973
Rusty Russellc97eb672015-02-13 17:13:42 +10301974 /*
1975 * 4.1.3.1:
1976 *
1977 * The driver MUST access each field using the “natural” access
1978 * method, i.e. 32-bit accesses for 32-bit fields, 16-bit accesses for
1979 * 16-bit fields and 8-bit accesses for 8-bit fields.
1980 */
Rusty Russell93153072015-02-11 15:15:11 +10301981read_through32:
1982 if (mask != 0xFFFFFFFF)
1983 errx(1, "%s: non-32-bit read to offset %u (%#x)",
1984 d->name, off, getreg(eip));
1985 memcpy(&val, (char *)d->mmio + off, 4);
1986 return val;
1987
1988read_through16:
1989 if (mask != 0xFFFF)
1990 errx(1, "%s: non-16-bit read to offset %u (%#x)",
1991 d->name, off, getreg(eip));
1992 memcpy(&val, (char *)d->mmio + off, 2);
1993 return val;
1994
1995read_through8:
1996 if (mask != 0xFF)
1997 errx(1, "%s: non-8-bit read to offset %u (%#x)",
1998 d->name, off, getreg(eip));
1999 memcpy(&val, (char *)d->mmio + off, 1);
2000 return val;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302001}
2002
2003static void emulate_mmio(unsigned long paddr, const u8 *insn)
2004{
2005 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
2006 struct device *d = find_mmio_region(paddr, &off);
2007 unsigned long args[] = { LHREQ_TRAP, 14 };
2008
2009 if (!d) {
2010 warnx("MMIO touching %#08lx (not a device)", paddr);
2011 goto reinject;
2012 }
2013
2014 /* Prefix makes it a 16 bit op */
2015 if (insn[0] == 0x66) {
2016 mask = 0xFFFF;
2017 insnlen++;
2018 }
2019
2020 /* iowrite */
2021 if (insn[insnlen] == 0x89) {
2022 /* Next byte is r/m byte: bits 3-5 are register. */
2023 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
2024 emulate_mmio_write(d, off, val, mask);
2025 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2026 } else if (insn[insnlen] == 0x8b) { /* ioread */
2027 /* Next byte is r/m byte: bits 3-5 are register. */
2028 val = emulate_mmio_read(d, off, mask);
2029 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
2030 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
2031 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
2032 mask = 0xff;
2033 /* Next byte is r/m byte: bits 3-5 are register. */
2034 val = getreg_num((insn[1] >> 3) & 0x7, mask);
2035 emulate_mmio_write(d, off, val, mask);
2036 insnlen = 2 + insn_displacement_len(insn[1]);
2037 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
2038 mask = 0xff;
2039 val = emulate_mmio_read(d, off, mask);
2040 setreg_num((insn[1] >> 3) & 0x7, val, mask);
2041 insnlen = 2 + insn_displacement_len(insn[1]);
2042 } else {
2043 warnx("Unknown MMIO instruction touching %#08lx:"
2044 " %02x %02x %02x %02x at %u",
2045 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
2046 reinject:
2047 /* Inject trap into Guest. */
2048 if (write(lguest_fd, args, sizeof(args)) < 0)
2049 err(1, "Reinjecting trap 14 for fault at %#x",
2050 getreg(eip));
2051 return;
2052 }
2053
2054 /* Finally, we've "done" the instruction, so move past it. */
2055 setreg(eip, getreg(eip) + insnlen);
2056}
Rusty Russellc565650b2015-02-11 15:15:10 +10302057
Rusty Russelldde79782007-07-26 10:41:03 -07002058/*L:190
2059 * Device Setup
2060 *
2061 * All devices need a descriptor so the Guest knows it exists, and a "struct
2062 * device" so the Launcher can keep track of it. We have common helper
Rusty Russella6bd8e12008-03-28 11:05:53 -05002063 * routines to allocate and manage them.
2064 */
Rusty Russell93153072015-02-11 15:15:11 +10302065static void add_pci_virtqueue(struct device *dev,
2066 void (*service)(struct virtqueue *))
2067{
2068 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2069
2070 /* Initialize the virtqueue */
2071 vq->next = NULL;
2072 vq->last_avail_idx = 0;
2073 vq->dev = dev;
2074
2075 /*
2076 * This is the routine the service thread will run, and its Process ID
2077 * once it's running.
2078 */
2079 vq->service = service;
2080 vq->thread = (pid_t)-1;
2081
2082 /* Initialize the configuration. */
Rusty Russelld2dbdac2015-02-13 17:13:40 +10302083 reset_vq_pci_config(vq);
Rusty Russell93153072015-02-11 15:15:11 +10302084 vq->pci_config.queue_notify_off = 0;
2085
2086 /* Add one to the number of queues */
2087 vq->dev->mmio->cfg.num_queues++;
2088
Rusty Russell93153072015-02-11 15:15:11 +10302089 /*
2090 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2091 * second.
2092 */
2093 for (i = &dev->vq; *i; i = &(*i)->next);
2094 *i = vq;
2095}
2096
Rusty Russelld9028ed2015-02-11 15:21:01 +10302097/* The Guest accesses the feature bits via the PCI common config MMIO region */
Rusty Russell93153072015-02-11 15:15:11 +10302098static void add_pci_feature(struct device *dev, unsigned bit)
2099{
2100 dev->features |= (1ULL << bit);
2101}
2102
Rusty Russell93153072015-02-11 15:15:11 +10302103/* For devices with no config. */
2104static void no_device_config(struct device *dev)
2105{
2106 dev->mmio_addr = get_mmio_region(dev->mmio_size);
2107
2108 dev->config.bar[0] = dev->mmio_addr;
2109 /* Bottom 4 bits must be zero */
2110 assert(~(dev->config.bar[0] & 0xF));
2111}
2112
2113/* This puts the device config into BAR0 */
2114static void set_device_config(struct device *dev, const void *conf, size_t len)
2115{
2116 /* Set up BAR 0 */
2117 dev->mmio_size += len;
2118 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2119 memcpy(dev->mmio + 1, conf, len);
2120
Rusty Russell8dc425f2015-02-13 17:13:41 +10302121 /*
2122 * 4.1.4.6:
2123 *
2124 * The device MUST present at least one VIRTIO_PCI_CAP_DEVICE_CFG
2125 * capability for any device type which has a device-specific
2126 * configuration.
2127 */
Rusty Russell93153072015-02-11 15:15:11 +10302128 /* Hook up device cfg */
2129 dev->config.cfg_access.cap.cap_next
2130 = offsetof(struct pci_config, device);
2131
Rusty Russell8dc425f2015-02-13 17:13:41 +10302132 /*
2133 * 4.1.4.6.1:
2134 *
2135 * The offset for the device-specific configuration MUST be 4-byte
2136 * aligned.
2137 */
2138 assert(dev->config.cfg_access.cap.cap_next % 4 == 0);
2139
Rusty Russell93153072015-02-11 15:15:11 +10302140 /* Fix up device cfg field length. */
2141 dev->config.device.length = len;
2142
2143 /* The rest is the same as the no-config case */
2144 no_device_config(dev);
2145}
2146
2147static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2148 size_t bar_offset, size_t bar_bytes, u8 next)
2149{
2150 cap->cap_vndr = PCI_CAP_ID_VNDR;
2151 cap->cap_next = next;
2152 cap->cap_len = caplen;
2153 cap->cfg_type = type;
2154 cap->bar = 0;
2155 memset(cap->padding, 0, sizeof(cap->padding));
2156 cap->offset = bar_offset;
2157 cap->length = bar_bytes;
2158}
2159
2160/*
2161 * This sets up the pci_config structure, as defined in the virtio 1.0
2162 * standard (and PCI standard).
2163 */
2164static void init_pci_config(struct pci_config *pci, u16 type,
2165 u8 class, u8 subclass)
2166{
2167 size_t bar_offset, bar_len;
2168
Rusty Russell8dc425f2015-02-13 17:13:41 +10302169 /*
2170 * 4.1.4.4.1:
2171 *
2172 * The device MUST either present notify_off_multiplier as an even
2173 * power of 2, or present notify_off_multiplier as 0.
2174 */
Rusty Russell93153072015-02-11 15:15:11 +10302175 memset(pci, 0, sizeof(*pci));
2176
2177 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2178 pci->vendor_id = 0x1AF4;
2179 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2180 pci->device_id = 0x1040 + type;
2181
2182 /*
2183 * PCI have specific codes for different types of devices.
2184 * Linux doesn't care, but it's a good clue for people looking
2185 * at the device.
Rusty Russell93153072015-02-11 15:15:11 +10302186 */
2187 pci->class = class;
2188 pci->subclass = subclass;
2189
2190 /*
Rusty Russell8dc425f2015-02-13 17:13:41 +10302191 * 4.1.2.1:
2192 *
2193 * Non-transitional devices SHOULD have a PCI Revision ID of 1 or
2194 * higher
Rusty Russell93153072015-02-11 15:15:11 +10302195 */
2196 pci->revid = 1;
2197
2198 /*
Rusty Russell8dc425f2015-02-13 17:13:41 +10302199 * 4.1.2.1:
2200 *
2201 * Non-transitional devices SHOULD have a PCI Subsystem Device ID of
2202 * 0x40 or higher.
Rusty Russell93153072015-02-11 15:15:11 +10302203 */
2204 pci->subsystem_device_id = 0x40;
2205
2206 /* We use our dummy interrupt controller, and irq_line is the irq */
2207 pci->irq_line = devices.next_irq++;
2208 pci->irq_pin = 0;
2209
2210 /* Support for extended capabilities. */
2211 pci->status = (1 << 4);
2212
2213 /* Link them in. */
Rusty Russell8dc425f2015-02-13 17:13:41 +10302214 /*
2215 * 4.1.4.3.1:
2216 *
2217 * The device MUST present at least one common configuration
2218 * capability.
2219 */
Rusty Russell93153072015-02-11 15:15:11 +10302220 pci->capabilities = offsetof(struct pci_config, common);
2221
Rusty Russell8dc425f2015-02-13 17:13:41 +10302222 /* 4.1.4.3.1 ... offset MUST be 4-byte aligned. */
2223 assert(pci->capabilities % 4 == 0);
2224
Rusty Russell93153072015-02-11 15:15:11 +10302225 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2226 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2227 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2228 bar_offset, bar_len,
2229 offsetof(struct pci_config, notify));
2230
Rusty Russell8dc425f2015-02-13 17:13:41 +10302231 /*
2232 * 4.1.4.4.1:
2233 *
2234 * The device MUST present at least one notification capability.
2235 */
Rusty Russell93153072015-02-11 15:15:11 +10302236 bar_offset += bar_len;
2237 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
Rusty Russell8dc425f2015-02-13 17:13:41 +10302238
2239 /*
2240 * 4.1.4.4.1:
2241 *
2242 * The cap.offset MUST be 2-byte aligned.
2243 */
2244 assert(pci->common.cap_next % 2 == 0);
2245
Rusty Russell93153072015-02-11 15:15:11 +10302246 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
Rusty Russell8dc425f2015-02-13 17:13:41 +10302247 /*
2248 * 4.1.4.4.1:
2249 *
2250 * The value cap.length presented by the device MUST be at least 2 and
2251 * MUST be large enough to support queue notification offsets for all
2252 * supported queues in all possible configurations.
2253 */
2254 assert(bar_len >= 2);
2255
Rusty Russell93153072015-02-11 15:15:11 +10302256 init_cap(&pci->notify.cap, sizeof(pci->notify),
2257 VIRTIO_PCI_CAP_NOTIFY_CFG,
2258 bar_offset, bar_len,
2259 offsetof(struct pci_config, isr));
2260
2261 bar_offset += bar_len;
2262 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
Rusty Russell8dc425f2015-02-13 17:13:41 +10302263 /*
2264 * 4.1.4.5.1:
2265 *
2266 * The device MUST present at least one VIRTIO_PCI_CAP_ISR_CFG
2267 * capability.
2268 */
Rusty Russell93153072015-02-11 15:15:11 +10302269 init_cap(&pci->isr, sizeof(pci->isr),
2270 VIRTIO_PCI_CAP_ISR_CFG,
2271 bar_offset, bar_len,
2272 offsetof(struct pci_config, cfg_access));
2273
Rusty Russell8dc425f2015-02-13 17:13:41 +10302274 /*
2275 * 4.1.4.7.1:
2276 *
2277 * The device MUST present at least one VIRTIO_PCI_CAP_PCI_CFG
2278 * capability.
2279 */
Rusty Russell93153072015-02-11 15:15:11 +10302280 /* This doesn't have any presence in the BAR */
2281 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2282 VIRTIO_PCI_CAP_PCI_CFG,
2283 0, 0, 0);
2284
2285 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2286 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2287
2288 /*
2289 * This gets sewn in and length set in set_device_config().
2290 * Some devices don't have a device configuration interface, so
2291 * we never expose this if we don't call set_device_config().
2292 */
2293 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2294 bar_offset, 0, 0);
2295}
2296
Rusty Russell2e04ef72009-07-30 16:03:45 -06002297/*
Rusty Russelld9028ed2015-02-11 15:21:01 +10302298 * This routine does all the creation and setup of a new device, but we don't
2299 * actually place the MMIO region until we know the size (if any) of the
2300 * device-specific config. And we don't actually start the service threads
2301 * until later.
Rusty Russella6bd8e12008-03-28 11:05:53 -05002302 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002303 * See what I mean about userspace being boring?
2304 */
Rusty Russell93153072015-02-11 15:15:11 +10302305static struct device *new_pci_device(const char *name, u16 type,
2306 u8 class, u8 subclass)
2307{
2308 struct device *dev = malloc(sizeof(*dev));
2309
2310 /* Now we populate the fields one at a time. */
Rusty Russell93153072015-02-11 15:15:11 +10302311 dev->name = name;
2312 dev->vq = NULL;
Rusty Russell93153072015-02-11 15:15:11 +10302313 dev->running = false;
Rusty Russell93153072015-02-11 15:15:11 +10302314 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2315 dev->mmio = calloc(1, dev->mmio_size);
2316 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2317 dev->features_accepted = 0;
2318
Rusty Russelld9028ed2015-02-11 15:21:01 +10302319 if (devices.device_num + 1 >= MAX_PCI_DEVICES)
Rusty Russell93153072015-02-11 15:15:11 +10302320 errx(1, "Can only handle 31 PCI devices");
2321
2322 init_pci_config(&dev->config, type, class, subclass);
2323 assert(!devices.pci[devices.device_num+1]);
2324 devices.pci[++devices.device_num] = dev;
2325
2326 return dev;
2327}
2328
Rusty Russell2e04ef72009-07-30 16:03:45 -06002329/*
2330 * Our first setup routine is the console. It's a fairly simple device, but
2331 * UNIX tty handling makes it uglier than it could be.
2332 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002333static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002334{
2335 struct device *dev;
Rusty Russelle8330d92015-02-11 15:23:01 +10302336 struct virtio_console_config conf;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002337
Rusty Russelldde79782007-07-26 10:41:03 -07002338 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002339 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2340 struct termios term = orig_term;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002341 /*
2342 * Then we turn off echo, line buffering and ^C etc: We want a
2343 * raw input stream to the Guest.
2344 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002345 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2346 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002347 }
2348
Rusty Russellebff0112015-02-11 15:18:01 +10302349 dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002350
Rusty Russelldde79782007-07-26 10:41:03 -07002351 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002352 dev->priv = malloc(sizeof(struct console_abort));
2353 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002354
Rusty Russell2e04ef72009-07-30 16:03:45 -06002355 /*
2356 * The console needs two virtqueues: the input then the output. When
Rusty Russell56ae43d2007-10-22 11:24:23 +10002357 * they put something the input queue, we make sure we're listening to
2358 * stdin. When they put something in the output queue, we write it to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002359 * stdout.
2360 */
Rusty Russellebff0112015-02-11 15:18:01 +10302361 add_pci_virtqueue(dev, console_input);
2362 add_pci_virtqueue(dev, console_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002363
Rusty Russelle8330d92015-02-11 15:23:01 +10302364 /* We need a configuration area for the emerg_wr early writes. */
2365 add_pci_feature(dev, VIRTIO_CONSOLE_F_EMERG_WRITE);
2366 set_device_config(dev, &conf, sizeof(conf));
Rusty Russellebff0112015-02-11 15:18:01 +10302367
2368 verbose("device %u: console\n", devices.device_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002369}
Rusty Russelldde79782007-07-26 10:41:03 -07002370/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002371
Rusty Russell2e04ef72009-07-30 16:03:45 -06002372/*M:010
2373 * Inter-guest networking is an interesting area. Simplest is to have a
Rusty Russell17cbca22007-10-22 11:24:22 +10002374 * --sharenet=<name> option which opens or creates a named pipe. This can be
2375 * used to send packets to another guest in a 1:1 manner.
2376 *
Rusty Russell9f542882011-07-22 14:39:50 +09302377 * More sophisticated is to use one of the tools developed for project like UML
Rusty Russell17cbca22007-10-22 11:24:22 +10002378 * to do networking.
2379 *
2380 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2381 * completely generic ("here's my vring, attach to your vring") and would work
2382 * for any traffic. Of course, namespace and permissions issues need to be
2383 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2384 * multiple inter-guest channels behind one interface, although it would
2385 * require some manner of hotplugging new virtio channels.
2386 *
Rusty Russell9f542882011-07-22 14:39:50 +09302387 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002388:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002389
Rusty Russell8ca47e02007-07-19 01:49:29 -07002390static u32 str2ip(const char *ipaddr)
2391{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002392 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002393
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002394 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2395 errx(1, "Failed to parse IP address '%s'", ipaddr);
2396 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2397}
2398
2399static void str2mac(const char *macaddr, unsigned char mac[6])
2400{
2401 unsigned int m[6];
2402 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2403 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2404 errx(1, "Failed to parse mac address '%s'", macaddr);
2405 mac[0] = m[0];
2406 mac[1] = m[1];
2407 mac[2] = m[2];
2408 mac[3] = m[3];
2409 mac[4] = m[4];
2410 mac[5] = m[5];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002411}
2412
Rusty Russell2e04ef72009-07-30 16:03:45 -06002413/*
2414 * This code is "adapted" from libbridge: it attaches the Host end of the
Rusty Russelldde79782007-07-26 10:41:03 -07002415 * network device to the bridge device specified by the command line.
2416 *
2417 * This is yet another James Morris contribution (I'm an IP-level guy, so I
Rusty Russell2e04ef72009-07-30 16:03:45 -06002418 * dislike bridging), and I just try not to break it.
2419 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002420static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2421{
2422 int ifidx;
2423 struct ifreq ifr;
2424
2425 if (!*br_name)
2426 errx(1, "must specify bridge name");
2427
2428 ifidx = if_nametoindex(if_name);
2429 if (!ifidx)
2430 errx(1, "interface %s does not exist!", if_name);
2431
2432 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002433 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07002434 ifr.ifr_ifindex = ifidx;
2435 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2436 err(1, "can't add %s to bridge %s", if_name, br_name);
2437}
2438
Rusty Russell2e04ef72009-07-30 16:03:45 -06002439/*
2440 * This sets up the Host end of the network device with an IP address, brings
Rusty Russelldde79782007-07-26 10:41:03 -07002441 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell2e04ef72009-07-30 16:03:45 -06002442 * pointer.
2443 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002444static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002445{
2446 struct ifreq ifr;
Rusty Russellf8466192010-08-27 08:39:48 -06002447 struct sockaddr_in sin;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002448
2449 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002450 strcpy(ifr.ifr_name, tapif);
2451
2452 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russellf8466192010-08-27 08:39:48 -06002453 sin.sin_family = AF_INET;
2454 sin.sin_addr.s_addr = htonl(ipaddr);
2455 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002456 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002457 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002458 ifr.ifr_flags = IFF_UP;
2459 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002460 err(1, "Bringing interface %s up", tapif);
2461}
2462
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002463static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07002464{
Rusty Russell8ca47e02007-07-19 01:49:29 -07002465 struct ifreq ifr;
Rusty Russellbf6d4032015-02-11 15:16:01 +10302466 int vnet_hdr_sz;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002467 int netfd;
2468
2469 /* Start with this zeroed. Messy but sure. */
2470 memset(&ifr, 0, sizeof(ifr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002471
Rusty Russell2e04ef72009-07-30 16:03:45 -06002472 /*
2473 * We open the /dev/net/tun device and tell it we want a tap device. A
Rusty Russelldde79782007-07-26 10:41:03 -07002474 * tap device is like a tun device, only somehow different. To tell
2475 * the truth, I completely blundered my way through this code, but it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002476 * works now!
2477 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002478 netfd = open_or_die("/dev/net/tun", O_RDWR);
Rusty Russell398f1872008-07-29 09:58:37 -05002479 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002480 strcpy(ifr.ifr_name, "tap%d");
2481 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2482 err(1, "configuring /dev/net/tun");
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002483
Rusty Russell398f1872008-07-29 09:58:37 -05002484 if (ioctl(netfd, TUNSETOFFLOAD,
2485 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2486 err(1, "Could not set features for tun device");
2487
Rusty Russell2e04ef72009-07-30 16:03:45 -06002488 /*
2489 * We don't need checksums calculated for packets coming in this
2490 * device: trust us!
2491 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002492 ioctl(netfd, TUNSETNOCSUM, 1);
2493
Rusty Russellbf6d4032015-02-11 15:16:01 +10302494 /*
2495 * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2496 * field at the end of the network header iff
2497 * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
2498 * that became the norm, but we need to tell the tun device
2499 * about our expanded header (which is called
2500 * virtio_net_hdr_mrg_rxbuf in the legacy system).
2501 */
2502 vnet_hdr_sz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2503 if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
2504 err(1, "Setting tun header size to %u", vnet_hdr_sz);
2505
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002506 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2507 return netfd;
2508}
2509
Rusty Russell2e04ef72009-07-30 16:03:45 -06002510/*L:195
2511 * Our network is a Host<->Guest network. This can either use bridging or
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002512 * routing, but the principle is the same: it uses the "tun" device to inject
2513 * packets into the Host as if they came in from a normal network card. We
Rusty Russell2e04ef72009-07-30 16:03:45 -06002514 * just shunt packets between the Guest and the tun device.
2515 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002516static void setup_tun_net(char *arg)
2517{
2518 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002519 struct net_info *net_info = malloc(sizeof(*net_info));
2520 int ipfd;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002521 u32 ip = INADDR_ANY;
2522 bool bridging = false;
2523 char tapif[IFNAMSIZ], *p;
2524 struct virtio_net_config conf;
2525
Rusty Russell659a0e62009-06-12 22:27:10 -06002526 net_info->tunfd = get_tun_device(tapif);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002527
Rusty Russell17cbca22007-10-22 11:24:22 +10002528 /* First we create a new network device. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302529 dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002530 dev->priv = net_info;
Rusty Russelldde79782007-07-26 10:41:03 -07002531
Rusty Russell2e04ef72009-07-30 16:03:45 -06002532 /* Network devices need a recv and a send queue, just like console. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302533 add_pci_virtqueue(dev, net_input);
2534 add_pci_virtqueue(dev, net_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002535
Rusty Russell2e04ef72009-07-30 16:03:45 -06002536 /*
2537 * We need a socket to perform the magic network ioctls to bring up the
2538 * tap interface, connect to the bridge etc. Any socket will do!
2539 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002540 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2541 if (ipfd < 0)
2542 err(1, "opening IP socket");
2543
Rusty Russelldde79782007-07-26 10:41:03 -07002544 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002545 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002546 arg += strlen(BRIDGE_PFX);
2547 bridging = true;
2548 }
2549
2550 /* A mac address may follow the bridge name or IP address */
2551 p = strchr(arg, ':');
2552 if (p) {
2553 str2mac(p+1, conf.mac);
Rusty Russellbf6d4032015-02-11 15:16:01 +10302554 add_pci_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002555 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002556 }
2557
2558 /* arg is now either an IP address or a bridge name */
2559 if (bridging)
2560 add_to_bridge(ipfd, tapif, arg);
2561 else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002562 ip = str2ip(arg);
2563
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002564 /* Set up the tun device. */
2565 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002566
Rusty Russell398f1872008-07-29 09:58:37 -05002567 /* Expect Guest to handle everything except UFO */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302568 add_pci_feature(dev, VIRTIO_NET_F_CSUM);
2569 add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2570 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2571 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2572 add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2573 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2574 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2575 add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
Mark McLoughlind1f01322009-05-11 18:11:46 +01002576 /* We handle indirect ring entries */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302577 add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2578 set_device_config(dev, &conf, sizeof(conf));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002579
Rusty Russella586d4f2008-02-04 23:49:56 -05002580 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002581 close(ipfd);
2582
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002583 if (bridging)
2584 verbose("device %u: tun %s attached to bridge: %s\n",
2585 devices.device_num, tapif, arg);
2586 else
2587 verbose("device %u: tun %s: %s\n",
2588 devices.device_num, tapif, arg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002589}
Rusty Russella91d74a2009-07-30 16:03:45 -06002590/*:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002591
Rusty Russelle1e72962007-10-25 15:02:50 +10002592/* This hangs off device->priv. */
Rusty Russell1842f232009-07-30 16:03:46 -06002593struct vblk_info {
Rusty Russell17cbca22007-10-22 11:24:22 +10002594 /* The size of the file. */
2595 off64_t len;
2596
2597 /* The file descriptor for the file. */
2598 int fd;
2599
Rusty Russell17cbca22007-10-22 11:24:22 +10002600};
2601
Rusty Russelle1e72962007-10-25 15:02:50 +10002602/*L:210
2603 * The Disk
2604 *
Rusty Russella91d74a2009-07-30 16:03:45 -06002605 * The disk only has one virtqueue, so it only has one thread. It is really
2606 * simple: the Guest asks for a block number and we read or write that position
2607 * in the file.
2608 *
2609 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2610 * slow: the Guest waits until the read is finished before running anything
2611 * else, even if it could have been doing useful work.
2612 *
2613 * We could have used async I/O, except it's reputed to suck so hard that
2614 * characters actually go missing from your code when you try to use it.
Rusty Russelle1e72962007-10-25 15:02:50 +10002615 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002616static void blk_request(struct virtqueue *vq)
Rusty Russell17cbca22007-10-22 11:24:22 +10002617{
Rusty Russell659a0e62009-06-12 22:27:10 -06002618 struct vblk_info *vblk = vq->dev->priv;
Rusty Russell17cbca22007-10-22 11:24:22 +10002619 unsigned int head, out_num, in_num, wlen;
Rusty Russellc0316a92012-10-16 23:56:13 +10302620 int ret, i;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002621 u8 *in;
Rusty Russellc0316a92012-10-16 23:56:13 +10302622 struct virtio_blk_outhdr out;
Rusty Russell659a0e62009-06-12 22:27:10 -06002623 struct iovec iov[vq->vring.num];
Rusty Russell17cbca22007-10-22 11:24:22 +10002624 off64_t off;
2625
Rusty Russella91d74a2009-07-30 16:03:45 -06002626 /*
2627 * Get the next request, where we normally wait. It triggers the
2628 * interrupt to acknowledge previously serviced requests (if any).
2629 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002630 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002631
Rusty Russellc0316a92012-10-16 23:56:13 +10302632 /* Copy the output header from the front of the iov (adjusts iov) */
2633 iov_consume(iov, out_num, &out, sizeof(out));
Rusty Russell17cbca22007-10-22 11:24:22 +10002634
Rusty Russellc0316a92012-10-16 23:56:13 +10302635 /* Find and trim end of iov input array, for our status byte. */
2636 in = NULL;
2637 for (i = out_num + in_num - 1; i >= out_num; i--) {
2638 if (iov[i].iov_len > 0) {
2639 in = iov[i].iov_base + iov[i].iov_len - 1;
2640 iov[i].iov_len--;
2641 break;
2642 }
2643 }
2644 if (!in)
2645 errx(1, "Bad virtblk cmd with no room for status");
2646
Rusty Russella91d74a2009-07-30 16:03:45 -06002647 /*
2648 * For historical reasons, block operations are expressed in 512 byte
2649 * "sectors".
2650 */
Rusty Russellc0316a92012-10-16 23:56:13 +10302651 off = out.sector * 512;
Rusty Russell17cbca22007-10-22 11:24:22 +10002652
Rusty Russell50516542015-02-11 15:15:12 +10302653 if (out.type & VIRTIO_BLK_T_OUT) {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002654 /*
2655 * Write
2656 *
2657 * Move to the right location in the block file. This can fail
2658 * if they try to write past end.
2659 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002660 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302661 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002662
Rusty Russellc0316a92012-10-16 23:56:13 +10302663 ret = writev(vblk->fd, iov, out_num);
2664 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
Rusty Russell17cbca22007-10-22 11:24:22 +10002665
Rusty Russell2e04ef72009-07-30 16:03:45 -06002666 /*
2667 * Grr... Now we know how long the descriptor they sent was, we
Rusty Russell17cbca22007-10-22 11:24:22 +10002668 * make sure they didn't try to write over the end of the block
Rusty Russell2e04ef72009-07-30 16:03:45 -06002669 * file (possibly extending it).
2670 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002671 if (ret > 0 && off + ret > vblk->len) {
2672 /* Trim it back to the correct length */
2673 ftruncate64(vblk->fd, vblk->len);
2674 /* Die, bad Guest, die. */
2675 errx(1, "Write past end %llu+%u", off, ret);
2676 }
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002677
2678 wlen = sizeof(*in);
2679 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russellc0316a92012-10-16 23:56:13 +10302680 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002681 /* Flush */
2682 ret = fdatasync(vblk->fd);
2683 verbose("FLUSH fdatasync: %i\n", ret);
Anthony Liguori1200e642007-11-08 21:13:44 -06002684 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002685 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10002686 } else {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002687 /*
2688 * Read
2689 *
2690 * Move to the right location in the block file. This can fail
2691 * if they try to read past end.
2692 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002693 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302694 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002695
Rusty Russellc0316a92012-10-16 23:56:13 +10302696 ret = readv(vblk->fd, iov + out_num, in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002697 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06002698 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002699 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10002700 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06002701 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002702 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10002703 }
2704 }
2705
Rusty Russella91d74a2009-07-30 16:03:45 -06002706 /* Finished that request. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002707 add_used(vq, head, wlen);
Rusty Russell17cbca22007-10-22 11:24:22 +10002708}
2709
Rusty Russelle1e72962007-10-25 15:02:50 +10002710/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002711static void setup_block_file(const char *filename)
2712{
Rusty Russell17cbca22007-10-22 11:24:22 +10002713 struct device *dev;
2714 struct vblk_info *vblk;
Rusty Russella586d4f2008-02-04 23:49:56 -05002715 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10002716
Rusty Russell50516542015-02-11 15:15:12 +10302717 /* Create the device. */
2718 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
Rusty Russell17cbca22007-10-22 11:24:22 +10002719
Rusty Russelle1e72962007-10-25 15:02:50 +10002720 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell50516542015-02-11 15:15:12 +10302721 add_pci_virtqueue(dev, blk_request);
Rusty Russell17cbca22007-10-22 11:24:22 +10002722
2723 /* Allocate the room for our own bookkeeping */
2724 vblk = dev->priv = malloc(sizeof(*vblk));
2725
2726 /* First we open the file and store the length. */
2727 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
2728 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
2729
2730 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002731 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10002732
Rusty Russell2e04ef72009-07-30 16:03:45 -06002733 /*
2734 * Tell Guest not to put in too many descriptors at once: two are used
2735 * for the in and out elements.
2736 */
Rusty Russell50516542015-02-11 15:15:12 +10302737 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
Rusty Russella586d4f2008-02-04 23:49:56 -05002738 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2739
Rusty Russell50516542015-02-11 15:15:12 +10302740 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
Rusty Russell17cbca22007-10-22 11:24:22 +10002741
Rusty Russell17cbca22007-10-22 11:24:22 +10002742 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell50516542015-02-11 15:15:12 +10302743 devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10002744}
Rusty Russell28fd6d72008-07-29 09:58:33 -05002745
Rusty Russell2e04ef72009-07-30 16:03:45 -06002746/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10302747 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05002748 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10302749 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05002750 * console is the reverse.
2751 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002752 * The same logic applies, however.
2753 */
2754struct rng_info {
2755 int rfd;
2756};
2757
Rusty Russell659a0e62009-06-12 22:27:10 -06002758static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05002759{
2760 int len;
2761 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002762 struct rng_info *rng_info = vq->dev->priv;
2763 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05002764
2765 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002766 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002767 if (out_num)
2768 errx(1, "Output buffers in rng?");
2769
Rusty Russell2e04ef72009-07-30 16:03:45 -06002770 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06002771 * Just like the console write, we loop to cover the whole iovec.
2772 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002773 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002774 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06002775 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002776 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10302777 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10302778 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002779 totlen += len;
2780 }
2781
2782 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002783 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002784}
2785
Rusty Russell2e04ef72009-07-30 16:03:45 -06002786/*L:199
2787 * This creates a "hardware" random number device for the Guest.
2788 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002789static void setup_rng(void)
2790{
2791 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002792 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05002793
Rusty Russella454bb32015-02-11 15:15:09 +10302794 /* Our device's private info simply contains the /dev/urandom fd. */
2795 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002796
Rusty Russell2e04ef72009-07-30 16:03:45 -06002797 /* Create the new device. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302798 dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
Rusty Russell659a0e62009-06-12 22:27:10 -06002799 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002800
2801 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302802 add_pci_virtqueue(dev, rng_input);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002803
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302804 /* We don't have any configuration space */
2805 no_device_config(dev);
2806
2807 verbose("device %u: rng\n", devices.device_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002808}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002809/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05302810
Rusty Russella6bd8e12008-03-28 11:05:53 -05002811/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05302812static void __attribute__((noreturn)) restart_guest(void)
2813{
2814 unsigned int i;
2815
Rusty Russell2e04ef72009-07-30 16:03:45 -06002816 /*
2817 * Since we don't track all open fds, we simply close everything beyond
2818 * stderr.
2819 */
Balaji Raoec04b132007-12-28 14:26:24 +05302820 for (i = 3; i < FD_SETSIZE; i++)
2821 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05002822
Rusty Russell659a0e62009-06-12 22:27:10 -06002823 /* Reset all the devices (kills all threads). */
2824 cleanup_devices();
2825
Balaji Raoec04b132007-12-28 14:26:24 +05302826 execv(main_args[0], main_args);
2827 err(1, "Could not exec %s", main_args[0]);
2828}
Rusty Russell8ca47e02007-07-19 01:49:29 -07002829
Rusty Russell2e04ef72009-07-30 16:03:45 -06002830/*L:220
2831 * Finally we reach the core of the Launcher which runs the Guest, serves
2832 * its input and output, and finally, lays it to rest.
2833 */
Rusty Russell56739c802009-06-12 22:26:59 -06002834static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002835{
2836 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10302837 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002838 int readval;
2839
2840 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302841 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302842 if (readval == sizeof(notify)) {
Rusty Russell00f8d542015-02-11 15:27:01 +10302843 if (notify.trap == 13) {
Rusty Russellc565650b2015-02-11 15:15:10 +10302844 verbose("Emulating instruction at %#x\n",
2845 getreg(eip));
2846 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302847 } else if (notify.trap == 14) {
2848 verbose("Emulating MMIO at %#x\n",
2849 getreg(eip));
2850 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302851 } else
2852 errx(1, "Unknown trap %i addr %#08x\n",
2853 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07002854 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002855 } else if (errno == ENOENT) {
2856 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002857 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002858 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05302859 /* ERESTART means that we need to reboot the guest */
2860 } else if (errno == ERESTART) {
2861 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06002862 /* Anything else means a bug or incompatible change. */
2863 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002864 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002865 }
2866}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002867/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10002868 * This is the end of the Launcher. The good news: we are over halfway
2869 * through! The bad news: the most fiendish part of the code still lies ahead
2870 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07002871 *
Rusty Russelle1e72962007-10-25 15:02:50 +10002872 * Are you ready? Take a deep breath and join me in the core of the Host, in
2873 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06002874:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002875
2876static struct option opts[] = {
2877 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002878 { "tunnet", 1, NULL, 't' },
2879 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05002880 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002881 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002882 { "username", 1, NULL, 'u' },
2883 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002884 { NULL },
2885};
2886static void usage(void)
2887{
2888 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002889 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07002890 "|--block=<filename>|--initrd=<filename>]...\n"
2891 "<mem-in-mb> vmlinux [args...]");
2892}
2893
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002894/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002895int main(int argc, char *argv[])
2896{
Rusty Russell2e04ef72009-07-30 16:03:45 -06002897 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002898 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06002899 /* Two temporaries. */
2900 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002901 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002902 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07002903 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002904 const char *initrd_name = NULL;
2905
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002906 /* Password structure for initgroups/setres[gu]id */
2907 struct passwd *user_details = NULL;
2908
2909 /* Directory to chroot to */
2910 char *chroot_path = NULL;
2911
Balaji Raoec04b132007-12-28 14:26:24 +05302912 /* Save the args: we "reboot" by execing ourselves again. */
2913 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05302914
Rusty Russell2e04ef72009-07-30 16:03:45 -06002915 /*
Rusty Russelld9028ed2015-02-11 15:21:01 +10302916 * First we initialize the device list. We remember next interrupt
2917 * number to use for devices (1: remember that 0 is used by the timer).
Rusty Russell2e04ef72009-07-30 16:03:45 -06002918 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002919 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002920
Rusty Russella91d74a2009-07-30 16:03:45 -06002921 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002922 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06002923
Rusty Russell2e04ef72009-07-30 16:03:45 -06002924 /*
2925 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07002926 * descriptor and memory pages for the devices as we parse the command
2927 * line. So we quickly look through the arguments to find the amount
Rusty Russell2e04ef72009-07-30 16:03:45 -06002928 * of memory now.
2929 */
Rusty Russell6570c45992007-07-23 18:43:56 -07002930 for (i = 1; i < argc; i++) {
2931 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002932 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002933 /*
2934 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002935 * guest-physical memory range. This fills it with 0,
2936 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002937 * tries to access it.
2938 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002939 guest_base = map_zeroed_pages(mem / getpagesize()
2940 + DEVICE_PAGES);
2941 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10302942 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell6570c45992007-07-23 18:43:56 -07002943 break;
2944 }
2945 }
Rusty Russelldde79782007-07-26 10:41:03 -07002946
Rusty Russell713e3f72015-02-11 15:25:01 +10302947 /* We always have a console device, and it's always device 1. */
2948 setup_console();
2949
Rusty Russelldde79782007-07-26 10:41:03 -07002950 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002951 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2952 switch (c) {
2953 case 'v':
2954 verbose = true;
2955 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002956 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10002957 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002958 break;
2959 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10002960 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002961 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002962 case 'r':
2963 setup_rng();
2964 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002965 case 'i':
2966 initrd_name = optarg;
2967 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002968 case 'u':
2969 user_details = getpwnam(optarg);
2970 if (!user_details)
2971 err(1, "getpwnam failed, incorrect username?");
2972 break;
2973 case 'c':
2974 chroot_path = optarg;
2975 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002976 default:
2977 warnx("Unknown argument %s", argv[optind]);
2978 usage();
2979 }
2980 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06002981 /*
2982 * After the other arguments we expect memory and kernel image name,
2983 * followed by command line arguments for the kernel.
2984 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002985 if (optind + 2 > argc)
2986 usage();
2987
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002988 verbose("Guest base is at %p\n", guest_base);
2989
Rusty Russell8e709462015-02-11 15:15:12 +10302990 /* Initialize the (fake) PCI host bridge device. */
2991 init_pci_host_bridge();
2992
Rusty Russell8ca47e02007-07-19 01:49:29 -07002993 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10002994 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002995
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002996 /* Boot information is stashed at physical address 0 */
2997 boot = from_guest_phys(0);
2998
Rusty Russelldde79782007-07-26 10:41:03 -07002999 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003000 if (initrd_name) {
3001 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06003002 /*
3003 * These are the location in the Linux boot header where the
3004 * start and size of the initrd are expected to be found.
3005 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003006 boot->hdr.ramdisk_image = mem - initrd_size;
3007 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07003008 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003009 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003010 }
3011
Rusty Russell2e04ef72009-07-30 16:03:45 -06003012 /*
3013 * The Linux boot header contains an "E820" memory map: ours is a
3014 * simple, single region.
3015 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003016 boot->e820_entries = 1;
3017 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06003018 /*
3019 * The boot header contains a command line pointer: we put the command
3020 * line after the boot header.
3021 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003022 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10003023 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003024 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07003025
Rusty Russelle22a5392011-08-15 10:15:10 +09303026 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3027 boot->hdr.kernel_alignment = 0x1000000;
3028
Rusty Russell814a0e52007-10-22 11:29:44 +10003029 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003030 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10003031
3032 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003033 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10003034
Rusty Russell43d33b22007-10-22 11:29:57 +10003035 /* Tell the entry path not to try to reload segment registers. */
3036 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003037
Rusty Russell9f542882011-07-22 14:39:50 +09303038 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06003039 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07003040
Rusty Russella91d74a2009-07-30 16:03:45 -06003041 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06003042 signal(SIGCHLD, kill_launcher);
3043
3044 /* If we exit via err(), this kills all the threads, restores tty. */
3045 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003046
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003047 /* If requested, chroot to a directory */
3048 if (chroot_path) {
3049 if (chroot(chroot_path) != 0)
3050 err(1, "chroot(\"%s\") failed", chroot_path);
3051
3052 if (chdir("/") != 0)
3053 err(1, "chdir(\"/\") failed");
3054
3055 verbose("chroot done\n");
3056 }
3057
3058 /* If requested, drop privileges */
3059 if (user_details) {
3060 uid_t u;
3061 gid_t g;
3062
3063 u = user_details->pw_uid;
3064 g = user_details->pw_gid;
3065
3066 if (initgroups(user_details->pw_name, g) != 0)
3067 err(1, "initgroups failed");
3068
3069 if (setresgid(g, g, g) != 0)
3070 err(1, "setresgid failed");
3071
3072 if (setresuid(u, u, u) != 0)
3073 err(1, "setresuid failed");
3074
3075 verbose("Dropping privileges completed\n");
3076 }
3077
Rusty Russelldde79782007-07-26 10:41:03 -07003078 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06003079 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003080}
Rusty Russellf56a3842007-07-26 10:41:05 -07003081/*:*/
3082
3083/*M:999
3084 * Mastery is done: you now know everything I do.
3085 *
3086 * But surely you have seen code, features and bugs in your wanderings which
3087 * you now yearn to attack? That is the real game, and I look forward to you
3088 * patching and forking lguest into the Your-Name-Here-visor.
3089 *
3090 * Farewell, and good coding!
3091 * Rusty Russell.
3092 */