blob: 663166aff1f50885cf7ff7fe1c945ad777d14201 [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 Russelle6dc0412013-07-04 11:22:58 +093074#include <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 Russelldde79782007-07-26 10:41:03 -0700120 /* The descriptor page for the devices. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000121 u8 *descpage;
122
Rusty Russelldde79782007-07-26 10:41:03 -0700123 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700124 struct device *dev;
Rusty Russell2e04ef72009-07-30 16:03:45 -0600125 /* And a pointer to the last device for easy append. */
Rusty Russella586d4f2008-02-04 23:49:56 -0500126 struct device *lastdev;
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030127
128 /* PCI devices. */
129 struct device *pci[MAX_PCI_DEVICES];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700130};
131
Rusty Russell17cbca22007-10-22 11:24:22 +1000132/* The list of Guest devices, based on command line arguments. */
133static struct device_list devices;
134
Rusty Russell93153072015-02-11 15:15:11 +1030135struct virtio_pci_cfg_cap {
136 struct virtio_pci_cap cap;
137 u32 window; /* Data for BAR access. */
138};
139
140struct virtio_pci_mmio {
141 struct virtio_pci_common_cfg cfg;
142 u16 notify;
143 u8 isr;
144 u8 padding;
145 /* Device-specific configuration follows this. */
146};
147
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030148/* This is the layout (little-endian) of the PCI config space. */
149struct pci_config {
150 u16 vendor_id, device_id;
151 u16 command, status;
152 u8 revid, prog_if, subclass, class;
153 u8 cacheline_size, lat_timer, header_type, bist;
154 u32 bar[6];
155 u32 cardbus_cis_ptr;
156 u16 subsystem_vendor_id, subsystem_device_id;
157 u32 expansion_rom_addr;
158 u8 capabilities, reserved1[3];
159 u32 reserved2;
160 u8 irq_line, irq_pin, min_grant, max_latency;
Rusty Russell93153072015-02-11 15:15:11 +1030161
162 /* Now, this is the linked capability list. */
163 struct virtio_pci_cap common;
164 struct virtio_pci_notify_cap notify;
165 struct virtio_pci_cap isr;
166 struct virtio_pci_cap device;
167 /* FIXME: Implement this! */
168 struct virtio_pci_cfg_cap cfg_access;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030169};
170
Rusty Russelldde79782007-07-26 10:41:03 -0700171/* The device structure describes a single device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600172struct device {
Rusty Russelldde79782007-07-26 10:41:03 -0700173 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700174 struct device *next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000175
Rusty Russell713b15b2009-06-12 22:26:58 -0600176 /* The device's descriptor, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700177 struct lguest_device_desc *desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000178
Rusty Russell713b15b2009-06-12 22:26:58 -0600179 /* We can't trust desc values once Guest has booted: we use these. */
180 unsigned int feature_len;
181 unsigned int num_vq;
182
Rusty Russell17cbca22007-10-22 11:24:22 +1000183 /* The name of this device, for --verbose. */
184 const char *name;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700185
Rusty Russell17cbca22007-10-22 11:24:22 +1000186 /* Any queues attached to this device */
187 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700188
Rusty Russell659a0e62009-06-12 22:27:10 -0600189 /* Is it operational */
190 bool running;
Rusty Russella007a752008-05-02 21:50:53 -0500191
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030192 /* PCI configuration */
193 union {
194 struct pci_config config;
195 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
196 };
197
Rusty Russell93153072015-02-11 15:15:11 +1030198 /* Features we offer, and those accepted. */
199 u64 features, features_accepted;
200
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030201 /* Device-specific config hangs off the end of this. */
202 struct virtio_pci_mmio *mmio;
203
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030204 /* PCI MMIO resources (all in BAR0) */
205 size_t mmio_size;
206 u32 mmio_addr;
207
Rusty Russell8ca47e02007-07-19 01:49:29 -0700208 /* Device-specific data. */
209 void *priv;
210};
211
Rusty Russell17cbca22007-10-22 11:24:22 +1000212/* The virtqueue structure describes a queue attached to a device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600213struct virtqueue {
Rusty Russell17cbca22007-10-22 11:24:22 +1000214 struct virtqueue *next;
215
216 /* Which device owns me. */
217 struct device *dev;
218
219 /* The configuration for this queue. */
220 struct lguest_vqconfig config;
221
222 /* The actual ring of buffers. */
223 struct vring vring;
224
Rusty Russell93153072015-02-11 15:15:11 +1030225 /* The information about this virtqueue (we only use queue_size on) */
226 struct virtio_pci_common_cfg pci_config;
227
Rusty Russell17cbca22007-10-22 11:24:22 +1000228 /* Last available index we saw. */
229 u16 last_avail_idx;
230
Rusty Russell95c517c2009-06-12 22:27:11 -0600231 /* How many are used since we sent last irq? */
232 unsigned int pending_used;
233
Rusty Russell659a0e62009-06-12 22:27:10 -0600234 /* Eventfd where Guest notifications arrive. */
235 int eventfd;
Rusty Russell20887612008-05-30 15:09:46 -0500236
Rusty Russell659a0e62009-06-12 22:27:10 -0600237 /* Function for the thread which is servicing this virtqueue. */
238 void (*service)(struct virtqueue *vq);
239 pid_t thread;
Rusty Russell17cbca22007-10-22 11:24:22 +1000240};
241
Balaji Raoec04b132007-12-28 14:26:24 +0530242/* Remember the arguments to the program so we can "reboot" */
243static char **main_args;
244
Rusty Russell659a0e62009-06-12 22:27:10 -0600245/* The original tty settings to restore on exit. */
246static struct termios orig_term;
247
Rusty Russell2e04ef72009-07-30 16:03:45 -0600248/*
249 * We have to be careful with barriers: our devices are all run in separate
Rusty Russellf7027c62009-06-12 22:27:00 -0600250 * threads and so we need to make sure that changes visible to the Guest happen
Rusty Russell2e04ef72009-07-30 16:03:45 -0600251 * in precise order.
252 */
Rusty Russellf7027c62009-06-12 22:27:00 -0600253#define wmb() __asm__ __volatile__("" : : : "memory")
Rusty Russell0d69a652013-07-02 15:35:14 +0930254#define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
255#define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
Rusty Russell17cbca22007-10-22 11:24:22 +1000256
Rusty Russellb5111792008-07-29 09:58:34 -0500257/* Wrapper for the last available index. Makes it easier to change. */
258#define lg_last_avail(vq) ((vq)->last_avail_idx)
259
Rusty Russell2e04ef72009-07-30 16:03:45 -0600260/*
261 * The virtio configuration space is defined to be little-endian. x86 is
262 * little-endian too, but it's nice to be explicit so we have these helpers.
263 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000264#define cpu_to_le16(v16) (v16)
265#define cpu_to_le32(v32) (v32)
266#define cpu_to_le64(v64) (v64)
267#define le16_to_cpu(v16) (v16)
268#define le32_to_cpu(v32) (v32)
Rusty Russella586d4f2008-02-04 23:49:56 -0500269#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000270
Rusty Russell28fd6d72008-07-29 09:58:33 -0500271/* Is this iovec empty? */
272static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
273{
274 unsigned int i;
275
276 for (i = 0; i < num_iov; i++)
277 if (iov[i].iov_len)
278 return false;
279 return true;
280}
281
282/* Take len bytes from the front of this iovec. */
Rusty Russellc0316a92012-10-16 23:56:13 +1030283static void iov_consume(struct iovec iov[], unsigned num_iov,
284 void *dest, unsigned len)
Rusty Russell28fd6d72008-07-29 09:58:33 -0500285{
286 unsigned int i;
287
288 for (i = 0; i < num_iov; i++) {
289 unsigned int used;
290
291 used = iov[i].iov_len < len ? iov[i].iov_len : len;
Rusty Russellc0316a92012-10-16 23:56:13 +1030292 if (dest) {
293 memcpy(dest, iov[i].iov_base, used);
294 dest += used;
295 }
Rusty Russell28fd6d72008-07-29 09:58:33 -0500296 iov[i].iov_base += used;
297 iov[i].iov_len -= used;
298 len -= used;
299 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030300 if (len != 0)
301 errx(1, "iovec too short!");
Rusty Russell28fd6d72008-07-29 09:58:33 -0500302}
303
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500304/* The device virtqueue descriptors are followed by feature bitmasks. */
305static u8 *get_feature_bits(struct device *dev)
306{
307 return (u8 *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -0600308 + dev->num_vq * sizeof(struct lguest_vqconfig);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500309}
310
Rusty Russell2e04ef72009-07-30 16:03:45 -0600311/*L:100
312 * The Launcher code itself takes us out into userspace, that scary place where
313 * pointers run wild and free! Unfortunately, like most userspace programs,
314 * it's quite boring (which is why everyone likes to hack on the kernel!).
315 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
316 * you through this section. Or, maybe not.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000317 *
318 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
319 * memory and stores it in "guest_base". In other words, Guest physical ==
320 * Launcher virtual with an offset.
321 *
322 * This can be tough to get your head around, but usually it just means that we
Francis Galieguea33f3222010-04-23 00:08:02 +0200323 * use these trivial conversion functions when the Guest gives us its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600324 * "physical" addresses:
325 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000326static void *from_guest_phys(unsigned long addr)
327{
328 return guest_base + addr;
329}
330
331static unsigned long to_guest_phys(const void *addr)
332{
333 return (addr - guest_base);
334}
335
Rusty Russelldde79782007-07-26 10:41:03 -0700336/*L:130
337 * Loading the Kernel.
338 *
339 * We start with couple of simple helper routines. open_or_die() avoids
Rusty Russell2e04ef72009-07-30 16:03:45 -0600340 * error-checking code cluttering the callers:
341 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700342static int open_or_die(const char *name, int flags)
343{
344 int fd = open(name, flags);
345 if (fd < 0)
346 err(1, "Failed to open %s", name);
347 return fd;
348}
349
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000350/* map_zeroed_pages() takes a number of pages. */
351static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700352{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000353 int fd = open_or_die("/dev/zero", O_RDONLY);
354 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700355
Rusty Russell2e04ef72009-07-30 16:03:45 -0600356 /*
357 * We use a private mapping (ie. if we write to the page, it will be
Philip Sanderson5230ff02011-01-20 21:37:28 -0600358 * copied). We allocate an extra two pages PROT_NONE to act as guard
359 * pages against read/write attempts that exceed allocated space.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600360 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600361 addr = mmap(NULL, getpagesize() * (num+2),
362 PROT_NONE, MAP_PRIVATE, fd, 0);
363
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000364 if (addr == MAP_FAILED)
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200365 err(1, "Mmapping %u pages of /dev/zero", num);
Rusty Russella91d74a2009-07-30 16:03:45 -0600366
Philip Sanderson5230ff02011-01-20 21:37:28 -0600367 if (mprotect(addr + getpagesize(), getpagesize() * num,
368 PROT_READ|PROT_WRITE) == -1)
369 err(1, "mprotect rw %u pages failed", num);
370
Rusty Russella91d74a2009-07-30 16:03:45 -0600371 /*
372 * One neat mmap feature is that you can close the fd, and it
373 * stays mapped.
374 */
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100375 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700376
Philip Sanderson5230ff02011-01-20 21:37:28 -0600377 /* Return address after PROT_NONE page */
378 return addr + getpagesize();
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000379}
380
381/* Get some more pages for a device. */
382static void *get_pages(unsigned int num)
383{
384 void *addr = from_guest_phys(guest_limit);
385
386 guest_limit += num * getpagesize();
387 if (guest_limit > guest_max)
388 errx(1, "Not enough memory for devices");
389 return addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700390}
391
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030392/* Get some bytes which won't be mapped into the guest. */
393static unsigned long get_mmio_region(size_t size)
394{
395 unsigned long addr = guest_mmio;
396 size_t i;
397
398 if (!size)
399 return addr;
400
401 /* Size has to be a power of 2 (and multiple of 16) */
402 for (i = 1; i < size; i <<= 1);
403
404 guest_mmio += i;
405
406 return addr;
407}
408
Rusty Russell2e04ef72009-07-30 16:03:45 -0600409/*
410 * This routine is used to load the kernel or initrd. It tries mmap, but if
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700411 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
Rusty Russell2e04ef72009-07-30 16:03:45 -0600412 * it falls back to reading the memory in.
413 */
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700414static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
415{
416 ssize_t r;
417
Rusty Russell2e04ef72009-07-30 16:03:45 -0600418 /*
419 * We map writable even though for some segments are marked read-only.
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700420 * The kernel really wants to be writable: it patches its own
421 * instructions.
422 *
423 * MAP_PRIVATE means that the page won't be copied until a write is
424 * done to it. This allows us to share untouched memory between
Rusty Russell2e04ef72009-07-30 16:03:45 -0600425 * Guests.
426 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600427 if (mmap(addr, len, PROT_READ|PROT_WRITE,
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700428 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
429 return;
430
431 /* pread does a seek and a read in one shot: saves a few lines. */
432 r = pread(fd, addr, len, offset);
433 if (r != len)
434 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
435}
436
Rusty Russell2e04ef72009-07-30 16:03:45 -0600437/*
438 * This routine takes an open vmlinux image, which is in ELF, and maps it into
Rusty Russelldde79782007-07-26 10:41:03 -0700439 * the Guest memory. ELF = Embedded Linking Format, which is the format used
440 * by all modern binaries on Linux including the kernel.
441 *
442 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000443 * address. We use the physical address; the Guest will map itself to the
444 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700445 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600446 * We return the starting address.
447 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000448static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700449{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700450 Elf32_Phdr phdr[ehdr->e_phnum];
451 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700452
Rusty Russell2e04ef72009-07-30 16:03:45 -0600453 /*
454 * Sanity checks on the main ELF header: an x86 executable with a
455 * reasonable number of correctly-sized program headers.
456 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700457 if (ehdr->e_type != ET_EXEC
458 || ehdr->e_machine != EM_386
459 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
460 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
461 errx(1, "Malformed elf header");
462
Rusty Russell2e04ef72009-07-30 16:03:45 -0600463 /*
464 * An ELF executable contains an ELF header and a number of "program"
Rusty Russelldde79782007-07-26 10:41:03 -0700465 * headers which indicate which parts ("segments") of the program to
Rusty Russell2e04ef72009-07-30 16:03:45 -0600466 * load where.
467 */
Rusty Russelldde79782007-07-26 10:41:03 -0700468
469 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700470 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
471 err(1, "Seeking to program headers");
472 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
473 err(1, "Reading program headers");
474
Rusty Russell2e04ef72009-07-30 16:03:45 -0600475 /*
476 * Try all the headers: there are usually only three. A read-only one,
477 * a read-write one, and a "note" section which we don't load.
478 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700479 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700480 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700481 if (phdr[i].p_type != PT_LOAD)
482 continue;
483
484 verbose("Section %i: size %i addr %p\n",
485 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
486
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700487 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000488 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700489 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700490 }
491
Rusty Russell814a0e52007-10-22 11:29:44 +1000492 /* The entry point is given in the ELF header. */
493 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700494}
495
Rusty Russell2e04ef72009-07-30 16:03:45 -0600496/*L:150
497 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
498 * to jump into it and it will unpack itself. We used to have to perform some
499 * hairy magic because the unpacking code scared me.
Rusty Russelldde79782007-07-26 10:41:03 -0700500 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000501 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
502 * a small patch to jump over the tricky bits in the Guest, so now we just read
Rusty Russell2e04ef72009-07-30 16:03:45 -0600503 * the funky header so we know where in the file to load, and away we go!
504 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000505static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700506{
Rusty Russell43d33b22007-10-22 11:29:57 +1000507 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000508 int r;
509 /* Modern bzImages get loaded at 1M. */
510 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700511
Rusty Russell2e04ef72009-07-30 16:03:45 -0600512 /*
513 * Go back to the start of the file and read the header. It should be
Paul Bolle395cf962011-08-15 02:02:26 +0200514 * a Linux boot header (see Documentation/x86/boot.txt)
Rusty Russell2e04ef72009-07-30 16:03:45 -0600515 */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000516 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000517 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000518
Rusty Russell43d33b22007-10-22 11:29:57 +1000519 /* Inside the setup_hdr, we expect the magic "HdrS" */
520 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000521 errx(1, "This doesn't look like a bzImage to me");
522
Rusty Russell43d33b22007-10-22 11:29:57 +1000523 /* Skip over the extra sectors of the header. */
524 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000525
526 /* Now read everything into memory. in nice big chunks. */
527 while ((r = read(fd, p, 65536)) > 0)
528 p += r;
529
Rusty Russell43d33b22007-10-22 11:29:57 +1000530 /* Finally, code32_start tells us where to enter the kernel. */
531 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700532}
533
Rusty Russell2e04ef72009-07-30 16:03:45 -0600534/*L:140
535 * Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000536 * come wrapped up in the self-decompressing "bzImage" format. With a little
Rusty Russell2e04ef72009-07-30 16:03:45 -0600537 * work, we can load those, too.
538 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000539static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700540{
541 Elf32_Ehdr hdr;
542
Rusty Russelldde79782007-07-26 10:41:03 -0700543 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700544 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
545 err(1, "Reading kernel");
546
Rusty Russelldde79782007-07-26 10:41:03 -0700547 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700548 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000549 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700550
Rusty Russella6bd8e12008-03-28 11:05:53 -0500551 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000552 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700553}
554
Rusty Russell2e04ef72009-07-30 16:03:45 -0600555/*
556 * This is a trivial little helper to align pages. Andi Kleen hated it because
Rusty Russelldde79782007-07-26 10:41:03 -0700557 * it calls getpagesize() twice: "it's dumb code."
558 *
559 * Kernel guys get really het up about optimization, even when it's not
Rusty Russell2e04ef72009-07-30 16:03:45 -0600560 * necessary. I leave this code as a reaction against that.
561 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700562static inline unsigned long page_align(unsigned long addr)
563{
Rusty Russelldde79782007-07-26 10:41:03 -0700564 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700565 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
566}
567
Rusty Russell2e04ef72009-07-30 16:03:45 -0600568/*L:180
569 * An "initial ram disk" is a disk image loaded into memory along with the
570 * kernel which the kernel can use to boot from without needing any drivers.
571 * Most distributions now use this as standard: the initrd contains the code to
572 * load the appropriate driver modules for the current machine.
Rusty Russelldde79782007-07-26 10:41:03 -0700573 *
574 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600575 * kernels. He sent me this (and tells me when I break it).
576 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700577static unsigned long load_initrd(const char *name, unsigned long mem)
578{
579 int ifd;
580 struct stat st;
581 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700582
583 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700584 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700585 if (fstat(ifd, &st) < 0)
586 err(1, "fstat() on initrd '%s'", name);
587
Rusty Russell2e04ef72009-07-30 16:03:45 -0600588 /*
589 * We map the initrd at the top of memory, but mmap wants it to be
590 * page-aligned, so we round the size up for that.
591 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700592 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000593 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600594 /*
595 * Once a file is mapped, you can close the file descriptor. It's a
596 * little odd, but quite useful.
597 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700598 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700599 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700600
601 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700602 return len;
603}
Rusty Russelle1e72962007-10-25 15:02:50 +1000604/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700605
Rusty Russell2e04ef72009-07-30 16:03:45 -0600606/*
607 * Simple routine to roll all the commandline arguments together with spaces
608 * between them.
609 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700610static void concat(char *dst, char *args[])
611{
612 unsigned int i, len = 0;
613
614 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100615 if (i) {
616 strcat(dst+len, " ");
617 len++;
618 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700619 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100620 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700621 }
622 /* In case it's empty. */
623 dst[len] = '\0';
624}
625
Rusty Russell2e04ef72009-07-30 16:03:45 -0600626/*L:185
627 * This is where we actually tell the kernel to initialize the Guest. We
Rusty Russelle1e72962007-10-25 15:02:50 +1000628 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300629 * the base of Guest "physical" memory, the top physical page to allow and the
Rusty Russell2e04ef72009-07-30 16:03:45 -0600630 * entry point for the Guest.
631 */
Rusty Russell56739c802009-06-12 22:26:59 -0600632static void tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700633{
Jes Sorensen511801d2007-10-22 11:03:31 +1000634 unsigned long args[] = { LHREQ_INITIALIZE,
635 (unsigned long)guest_base,
Rusty Russell7313d522015-02-11 15:15:10 +1030636 guest_limit / getpagesize(), start,
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030637 (guest_mmio+getpagesize()-1) / getpagesize() };
638 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
639 guest_base, guest_base + guest_limit,
640 guest_limit, guest_mmio);
Rusty Russell56739c802009-06-12 22:26:59 -0600641 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
642 if (write(lguest_fd, args, sizeof(args)) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700643 err(1, "Writing to /dev/lguest");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700644}
Rusty Russelldde79782007-07-26 10:41:03 -0700645/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700646
Rusty Russella91d74a2009-07-30 16:03:45 -0600647/*L:200
Rusty Russelldde79782007-07-26 10:41:03 -0700648 * Device Handling.
649 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000650 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700651 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000652 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700653 * if something funny is going on:
654 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700655static void *_check_pointer(unsigned long addr, unsigned int size,
656 unsigned int line)
657{
Rusty Russell2e04ef72009-07-30 16:03:45 -0600658 /*
Philip Sanderson5230ff02011-01-20 21:37:28 -0600659 * Check if the requested address and size exceeds the allocated memory,
660 * or addr + size wraps around.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600661 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600662 if ((addr + size) > guest_limit || (addr + size) < addr)
Rusty Russell17cbca22007-10-22 11:24:22 +1000663 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600664 /*
665 * We return a pointer for the caller's convenience, now we know it's
666 * safe to use.
667 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000668 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700669}
Rusty Russelldde79782007-07-26 10:41:03 -0700670/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700671#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
672
Rusty Russell2e04ef72009-07-30 16:03:45 -0600673/*
674 * Each buffer in the virtqueues is actually a chain of descriptors. This
Rusty Russelle1e72962007-10-25 15:02:50 +1000675 * function returns the next descriptor in the chain, or vq->vring.num if we're
Rusty Russell2e04ef72009-07-30 16:03:45 -0600676 * at the end.
677 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100678static unsigned next_desc(struct vring_desc *desc,
679 unsigned int i, unsigned int max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000680{
681 unsigned int next;
682
683 /* If this descriptor says it doesn't chain, we're done. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100684 if (!(desc[i].flags & VRING_DESC_F_NEXT))
685 return max;
Rusty Russell17cbca22007-10-22 11:24:22 +1000686
687 /* Check they're not leading us off end of descriptors. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100688 next = desc[i].next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000689 /* Make sure compiler knows to grab that: we don't want it changing! */
690 wmb();
691
Mark McLoughlind1f01322009-05-11 18:11:46 +0100692 if (next >= max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000693 errx(1, "Desc next is %u", next);
694
695 return next;
696}
697
Rusty Russella91d74a2009-07-30 16:03:45 -0600698/*
699 * This actually sends the interrupt for this virtqueue, if we've used a
700 * buffer.
701 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600702static void trigger_irq(struct virtqueue *vq)
703{
704 unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
705
Rusty Russell95c517c2009-06-12 22:27:11 -0600706 /* Don't inform them if nothing used. */
707 if (!vq->pending_used)
708 return;
709 vq->pending_used = 0;
710
Rusty Russellca60a422009-09-23 22:26:47 -0600711 /* If they don't want an interrupt, don't send one... */
712 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
Rusty Russell990c91f2011-05-30 11:14:12 -0600713 return;
Rusty Russellca60a422009-09-23 22:26:47 -0600714 }
Rusty Russell38bc2b82009-06-12 22:27:11 -0600715
Rusty Russell93153072015-02-11 15:15:11 +1030716 /* For a PCI device, set isr to 1 (queue interrupt pending) */
717 if (vq->dev->mmio)
718 vq->dev->mmio->isr = 0x1;
719
Rusty Russell38bc2b82009-06-12 22:27:11 -0600720 /* Send the Guest an interrupt tell them we used something up. */
721 if (write(lguest_fd, buf, sizeof(buf)) != 0)
722 err(1, "Triggering irq %i", vq->config.irq);
723}
724
Rusty Russell2e04ef72009-07-30 16:03:45 -0600725/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600726 * This looks in the virtqueue for the first available buffer, and converts
Rusty Russell17cbca22007-10-22 11:24:22 +1000727 * it to an iovec for convenient access. Since descriptors consist of some
728 * number of output then some number of input descriptors, it's actually two
729 * iovecs, but we pack them into one and note how many of each there were.
730 *
Rusty Russella91d74a2009-07-30 16:03:45 -0600731 * This function waits if necessary, and returns the descriptor number found.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600732 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600733static unsigned wait_for_vq_desc(struct virtqueue *vq,
734 struct iovec iov[],
735 unsigned int *out_num, unsigned int *in_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000736{
Mark McLoughlind1f01322009-05-11 18:11:46 +0100737 unsigned int i, head, max;
738 struct vring_desc *desc;
Rusty Russell659a0e62009-06-12 22:27:10 -0600739 u16 last_avail = lg_last_avail(vq);
740
Rusty Russella91d74a2009-07-30 16:03:45 -0600741 /* There's nothing available? */
Rusty Russell659a0e62009-06-12 22:27:10 -0600742 while (last_avail == vq->vring.avail->idx) {
743 u64 event;
744
Rusty Russella91d74a2009-07-30 16:03:45 -0600745 /*
746 * Since we're about to sleep, now is a good time to tell the
747 * Guest about what we've used up to now.
748 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600749 trigger_irq(vq);
750
Rusty Russellb60da132009-06-12 22:27:12 -0600751 /* OK, now we need to know about added descriptors. */
752 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
753
Rusty Russell2e04ef72009-07-30 16:03:45 -0600754 /*
755 * They could have slipped one in as we were doing that: make
756 * sure it's written, then check again.
757 */
Rusty Russellb60da132009-06-12 22:27:12 -0600758 mb();
759 if (last_avail != vq->vring.avail->idx) {
760 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
761 break;
762 }
763
Rusty Russell659a0e62009-06-12 22:27:10 -0600764 /* Nothing new? Wait for eventfd to tell us they refilled. */
765 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
766 errx(1, "Event read failed?");
Rusty Russellb60da132009-06-12 22:27:12 -0600767
768 /* We don't need to be notified again. */
769 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russell659a0e62009-06-12 22:27:10 -0600770 }
Rusty Russell17cbca22007-10-22 11:24:22 +1000771
772 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500773 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000774 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500775 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000776
Rusty Russell8fd9a632013-07-02 15:35:13 +0930777 /*
778 * Make sure we read the descriptor number *after* we read the ring
779 * update; don't let the cpu or compiler change the order.
780 */
781 rmb();
782
Rusty Russell2e04ef72009-07-30 16:03:45 -0600783 /*
784 * Grab the next descriptor number they're advertising, and increment
785 * the index we've seen.
786 */
Rusty Russellb5111792008-07-29 09:58:34 -0500787 head = vq->vring.avail->ring[last_avail % vq->vring.num];
788 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000789
790 /* If their number is silly, that's a fatal mistake. */
791 if (head >= vq->vring.num)
792 errx(1, "Guest says index %u is available", head);
793
794 /* When we start there are none of either input nor output. */
795 *out_num = *in_num = 0;
796
Mark McLoughlind1f01322009-05-11 18:11:46 +0100797 max = vq->vring.num;
798 desc = vq->vring.desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000799 i = head;
Mark McLoughlind1f01322009-05-11 18:11:46 +0100800
Rusty Russell2e04ef72009-07-30 16:03:45 -0600801 /*
Rusty Russell8fd9a632013-07-02 15:35:13 +0930802 * We have to read the descriptor after we read the descriptor number,
803 * but there's a data dependency there so the CPU shouldn't reorder
804 * that: no rmb() required.
805 */
806
807 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -0600808 * If this is an indirect entry, then this buffer contains a descriptor
809 * table which we handle as if it's any normal descriptor chain.
810 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100811 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
812 if (desc[i].len % sizeof(struct vring_desc))
813 errx(1, "Invalid size for indirect buffer table");
814
815 max = desc[i].len / sizeof(struct vring_desc);
816 desc = check_pointer(desc[i].addr, desc[i].len);
817 i = 0;
818 }
819
Rusty Russell17cbca22007-10-22 11:24:22 +1000820 do {
821 /* Grab the first descriptor, and check it's OK. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100822 iov[*out_num + *in_num].iov_len = desc[i].len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000823 iov[*out_num + *in_num].iov_base
Mark McLoughlind1f01322009-05-11 18:11:46 +0100824 = check_pointer(desc[i].addr, desc[i].len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000825 /* If this is an input descriptor, increment that count. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100826 if (desc[i].flags & VRING_DESC_F_WRITE)
Rusty Russell17cbca22007-10-22 11:24:22 +1000827 (*in_num)++;
828 else {
Rusty Russell2e04ef72009-07-30 16:03:45 -0600829 /*
830 * If it's an output descriptor, they're all supposed
831 * to come before any input descriptors.
832 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000833 if (*in_num)
834 errx(1, "Descriptor has out after in");
835 (*out_num)++;
836 }
837
838 /* If we've got too many, that implies a descriptor loop. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100839 if (*out_num + *in_num > max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000840 errx(1, "Looped descriptor");
Mark McLoughlind1f01322009-05-11 18:11:46 +0100841 } while ((i = next_desc(desc, i, max)) != max);
Rusty Russell17cbca22007-10-22 11:24:22 +1000842
843 return head;
844}
845
Rusty Russell2e04ef72009-07-30 16:03:45 -0600846/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600847 * After we've used one of their buffers, we tell the Guest about it. Sometime
848 * later we'll want to send them an interrupt using trigger_irq(); note that
849 * wait_for_vq_desc() does that for us if it has to wait.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600850 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000851static void add_used(struct virtqueue *vq, unsigned int head, int len)
852{
853 struct vring_used_elem *used;
854
Rusty Russell2e04ef72009-07-30 16:03:45 -0600855 /*
856 * The virtqueue contains a ring of used buffers. Get a pointer to the
857 * next entry in that used ring.
858 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000859 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
860 used->id = head;
861 used->len = len;
862 /* Make sure buffer is written before we update index. */
863 wmb();
864 vq->vring.used->idx++;
Rusty Russell95c517c2009-06-12 22:27:11 -0600865 vq->pending_used++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000866}
867
Rusty Russell17cbca22007-10-22 11:24:22 +1000868/* And here's the combo meal deal. Supersize me! */
Rusty Russell56739c802009-06-12 22:26:59 -0600869static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
Rusty Russell17cbca22007-10-22 11:24:22 +1000870{
871 add_used(vq, head, len);
Rusty Russell56739c802009-06-12 22:26:59 -0600872 trigger_irq(vq);
Rusty Russell17cbca22007-10-22 11:24:22 +1000873}
874
Rusty Russelle1e72962007-10-25 15:02:50 +1000875/*
876 * The Console
877 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600878 * We associate some data with the console for our exit hack.
879 */
Rusty Russell1842f232009-07-30 16:03:46 -0600880struct console_abort {
Rusty Russelldde79782007-07-26 10:41:03 -0700881 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700882 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700883 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700884 struct timeval start;
885};
886
Rusty Russelldde79782007-07-26 10:41:03 -0700887/* This is the routine which handles console input (ie. stdin). */
Rusty Russell659a0e62009-06-12 22:27:10 -0600888static void console_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700889{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700890 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000891 unsigned int head, in_num, out_num;
Rusty Russell659a0e62009-06-12 22:27:10 -0600892 struct console_abort *abort = vq->dev->priv;
893 struct iovec iov[vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700894
Rusty Russella91d74a2009-07-30 16:03:45 -0600895 /* Make sure there's a descriptor available. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600896 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000897 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000898 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700899
Rusty Russella91d74a2009-07-30 16:03:45 -0600900 /* Read into it. This is where we usually wait. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600901 len = readv(STDIN_FILENO, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700902 if (len <= 0) {
Rusty Russell659a0e62009-06-12 22:27:10 -0600903 /* Ran out of input? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700904 warnx("Failed to get console input, ignoring console.");
Rusty Russell2e04ef72009-07-30 16:03:45 -0600905 /*
906 * For simplicity, dying threads kill the whole Launcher. So
907 * just nap here.
908 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600909 for (;;)
910 pause();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700911 }
912
Rusty Russella91d74a2009-07-30 16:03:45 -0600913 /* Tell the Guest we used a buffer. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600914 add_used_and_trigger(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700915
Rusty Russell2e04ef72009-07-30 16:03:45 -0600916 /*
917 * Three ^C within one second? Exit.
Rusty Russelldde79782007-07-26 10:41:03 -0700918 *
Rusty Russell659a0e62009-06-12 22:27:10 -0600919 * This is such a hack, but works surprisingly well. Each ^C has to
920 * be in a buffer by itself, so they can't be too fast. But we check
921 * that we get three within about a second, so they can't be too
Rusty Russell2e04ef72009-07-30 16:03:45 -0600922 * slow.
923 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600924 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700925 abort->count = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -0600926 return;
927 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700928
Rusty Russell659a0e62009-06-12 22:27:10 -0600929 abort->count++;
930 if (abort->count == 1)
931 gettimeofday(&abort->start, NULL);
932 else if (abort->count == 3) {
933 struct timeval now;
934 gettimeofday(&now, NULL);
935 /* Kill all Launcher processes with SIGINT, like normal ^C */
936 if (now.tv_sec <= abort->start.tv_sec+1)
937 kill(0, SIGINT);
938 abort->count = 0;
939 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700940}
941
Rusty Russell659a0e62009-06-12 22:27:10 -0600942/* This is the routine which handles console output (ie. stdout). */
943static void console_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700944{
Rusty Russell17cbca22007-10-22 11:24:22 +1000945 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000946 struct iovec iov[vq->vring.num];
947
Rusty Russella91d74a2009-07-30 16:03:45 -0600948 /* We usually wait in here, for the Guest to give us something. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600949 head = wait_for_vq_desc(vq, iov, &out, &in);
950 if (in)
951 errx(1, "Input buffers in console output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600952
953 /* writev can return a partial write, so we loop here. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600954 while (!iov_empty(iov, out)) {
955 int len = writev(STDOUT_FILENO, iov, out);
Sakari Ailuse0377e22011-06-26 19:36:46 +0300956 if (len <= 0) {
957 warn("Write to stdout gave %i (%d)", len, errno);
958 break;
959 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030960 iov_consume(iov, out, NULL, len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000961 }
Rusty Russella91d74a2009-07-30 16:03:45 -0600962
963 /*
964 * We're finished with that buffer: if we're going to sleep,
965 * wait_for_vq_desc() will prod the Guest with an interrupt.
966 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600967 add_used(vq, head, 0);
Rusty Russella1618832008-07-29 09:58:35 -0500968}
969
Rusty Russelle1e72962007-10-25 15:02:50 +1000970/*
971 * The Network
972 *
973 * Handling output for network is also simple: we get all the output buffers
Rusty Russell659a0e62009-06-12 22:27:10 -0600974 * and write them to /dev/net/tun.
Rusty Russella6bd8e12008-03-28 11:05:53 -0500975 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600976struct net_info {
977 int tunfd;
978};
979
980static void net_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700981{
Rusty Russell659a0e62009-06-12 22:27:10 -0600982 struct net_info *net_info = vq->dev->priv;
983 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000984 struct iovec iov[vq->vring.num];
985
Rusty Russella91d74a2009-07-30 16:03:45 -0600986 /* We usually wait in here for the Guest to give us a packet. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600987 head = wait_for_vq_desc(vq, iov, &out, &in);
988 if (in)
989 errx(1, "Input buffers in net output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600990 /*
991 * Send the whole thing through to /dev/net/tun. It expects the exact
992 * same format: what a coincidence!
993 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600994 if (writev(net_info->tunfd, iov, out) < 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +0300995 warnx("Write to tun failed (%d)?", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -0600996
997 /*
998 * Done with that one; wait_for_vq_desc() will send the interrupt if
999 * all packets are processed.
1000 */
Rusty Russell38bc2b82009-06-12 22:27:11 -06001001 add_used(vq, head, 0);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001002}
1003
Rusty Russella91d74a2009-07-30 16:03:45 -06001004/*
1005 * Handling network input is a bit trickier, because I've tried to optimize it.
1006 *
1007 * First we have a helper routine which tells is if from this file descriptor
1008 * (ie. the /dev/net/tun device) will block:
1009 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001010static bool will_block(int fd)
1011{
1012 fd_set fdset;
1013 struct timeval zero = { 0, 0 };
1014 FD_ZERO(&fdset);
1015 FD_SET(fd, &fdset);
1016 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
1017}
1018
Rusty Russella91d74a2009-07-30 16:03:45 -06001019/*
1020 * This handles packets coming in from the tun device to our Guest. Like all
1021 * service routines, it gets called again as soon as it returns, so you don't
1022 * see a while(1) loop here.
1023 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001024static void net_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001025{
Rusty Russell8ca47e02007-07-19 01:49:29 -07001026 int len;
Rusty Russell659a0e62009-06-12 22:27:10 -06001027 unsigned int head, out, in;
1028 struct iovec iov[vq->vring.num];
1029 struct net_info *net_info = vq->dev->priv;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001030
Rusty Russella91d74a2009-07-30 16:03:45 -06001031 /*
1032 * Get a descriptor to write an incoming packet into. This will also
1033 * send an interrupt if they're out of descriptors.
1034 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001035 head = wait_for_vq_desc(vq, iov, &out, &in);
1036 if (out)
1037 errx(1, "Output buffers in net input queue?");
Rusty Russell4a8962e2009-06-12 22:27:12 -06001038
Rusty Russella91d74a2009-07-30 16:03:45 -06001039 /*
1040 * If it looks like we'll block reading from the tun device, send them
1041 * an interrupt.
1042 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001043 if (vq->pending_used && will_block(net_info->tunfd))
1044 trigger_irq(vq);
1045
Rusty Russella91d74a2009-07-30 16:03:45 -06001046 /*
1047 * Read in the packet. This is where we normally wait (when there's no
1048 * incoming network traffic).
1049 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001050 len = readv(net_info->tunfd, iov, in);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001051 if (len <= 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +03001052 warn("Failed to read from tun (%d).", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -06001053
1054 /*
1055 * Mark that packet buffer as used, but don't interrupt here. We want
1056 * to wait until we've done as much work as we can.
1057 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001058 add_used(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001059}
Rusty Russella91d74a2009-07-30 16:03:45 -06001060/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001061
Rusty Russella91d74a2009-07-30 16:03:45 -06001062/* This is the helper to create threads: run the service routine in a loop. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001063static int do_thread(void *_vq)
Rusty Russell56ae43d2007-10-22 11:24:23 +10001064{
Rusty Russell659a0e62009-06-12 22:27:10 -06001065 struct virtqueue *vq = _vq;
1066
1067 for (;;)
1068 vq->service(vq);
1069 return 0;
Rusty Russell56ae43d2007-10-22 11:24:23 +10001070}
1071
Rusty Russell2e04ef72009-07-30 16:03:45 -06001072/*
1073 * When a child dies, we kill our entire process group with SIGTERM. This
1074 * also has the side effect that the shell restores the console for us!
1075 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001076static void kill_launcher(int signal)
Rusty Russell5dae7852008-07-29 09:58:35 -05001077{
Rusty Russell659a0e62009-06-12 22:27:10 -06001078 kill(0, SIGTERM);
1079}
1080
1081static void reset_device(struct device *dev)
1082{
1083 struct virtqueue *vq;
1084
1085 verbose("Resetting device %s\n", dev->name);
1086
1087 /* Clear any features they've acked. */
1088 memset(get_feature_bits(dev) + dev->feature_len, 0, dev->feature_len);
1089
1090 /* We're going to be explicitly killing threads, so ignore them. */
1091 signal(SIGCHLD, SIG_IGN);
1092
1093 /* Zero out the virtqueues, get rid of their threads */
1094 for (vq = dev->vq; vq; vq = vq->next) {
1095 if (vq->thread != (pid_t)-1) {
1096 kill(vq->thread, SIGTERM);
1097 waitpid(vq->thread, NULL, 0);
1098 vq->thread = (pid_t)-1;
1099 }
1100 memset(vq->vring.desc, 0,
1101 vring_size(vq->config.num, LGUEST_VRING_ALIGN));
1102 lg_last_avail(vq) = 0;
1103 }
1104 dev->running = false;
1105
1106 /* Now we care if threads die. */
1107 signal(SIGCHLD, (void *)kill_launcher);
1108}
1109
Rusty Russella91d74a2009-07-30 16:03:45 -06001110/*L:216
1111 * This actually creates the thread which services the virtqueue for a device.
1112 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001113static void create_thread(struct virtqueue *vq)
1114{
Rusty Russell2e04ef72009-07-30 16:03:45 -06001115 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06001116 * Create stack for thread. Since the stack grows upwards, we point
1117 * the stack pointer to the end of this region.
Rusty Russell2e04ef72009-07-30 16:03:45 -06001118 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001119 char *stack = malloc(32768);
1120 unsigned long args[] = { LHREQ_EVENTFD,
1121 vq->config.pfn*getpagesize(), 0 };
1122
1123 /* Create a zero-initialized eventfd. */
1124 vq->eventfd = eventfd(0, 0);
1125 if (vq->eventfd < 0)
1126 err(1, "Creating eventfd");
1127 args[2] = vq->eventfd;
1128
Rusty Russella91d74a2009-07-30 16:03:45 -06001129 /*
1130 * Attach an eventfd to this virtqueue: it will go off when the Guest
1131 * does an LHCALL_NOTIFY for this vq.
1132 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001133 if (write(lguest_fd, &args, sizeof(args)) != 0)
1134 err(1, "Attaching eventfd");
1135
Rusty Russella91d74a2009-07-30 16:03:45 -06001136 /*
1137 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1138 * we get a signal if it dies.
1139 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001140 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1141 if (vq->thread == (pid_t)-1)
1142 err(1, "Creating clone");
Rusty Russella91d74a2009-07-30 16:03:45 -06001143
1144 /* We close our local copy now the child has it. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001145 close(vq->eventfd);
1146}
1147
1148static void start_device(struct device *dev)
1149{
1150 unsigned int i;
1151 struct virtqueue *vq;
1152
1153 verbose("Device %s OK: offered", dev->name);
1154 for (i = 0; i < dev->feature_len; i++)
1155 verbose(" %02x", get_feature_bits(dev)[i]);
1156 verbose(", accepted");
1157 for (i = 0; i < dev->feature_len; i++)
1158 verbose(" %02x", get_feature_bits(dev)
1159 [dev->feature_len+i]);
1160
1161 for (vq = dev->vq; vq; vq = vq->next) {
1162 if (vq->service)
1163 create_thread(vq);
1164 }
1165 dev->running = true;
1166}
1167
1168static void cleanup_devices(void)
1169{
1170 struct device *dev;
1171
1172 for (dev = devices.dev; dev; dev = dev->next)
1173 reset_device(dev);
1174
1175 /* If we saved off the original terminal settings, restore them now. */
1176 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1177 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
Rusty Russell5dae7852008-07-29 09:58:35 -05001178}
1179
Rusty Russella007a752008-05-02 21:50:53 -05001180/* When the Guest tells us they updated the status field, we handle it. */
1181static void update_device_status(struct device *dev)
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001182{
Rusty Russell659a0e62009-06-12 22:27:10 -06001183 /* A zero status is a reset, otherwise it's a set of flags. */
1184 if (dev->desc->status == 0)
1185 reset_device(dev);
1186 else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
Rusty Russella007a752008-05-02 21:50:53 -05001187 warnx("Device %s configuration FAILED", dev->name);
Rusty Russell659a0e62009-06-12 22:27:10 -06001188 if (dev->running)
1189 reset_device(dev);
Rusty Russell3c3ed482011-07-22 14:39:49 +09301190 } else {
1191 if (dev->running)
1192 err(1, "Device %s features finalized twice", dev->name);
1193 start_device(dev);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001194 }
1195}
1196
Rusty Russella91d74a2009-07-30 16:03:45 -06001197/*L:215
1198 * This is the generic routine we call when the Guest uses LHCALL_NOTIFY. In
1199 * particular, it's used to notify us of device status changes during boot.
1200 */
Rusty Russell56739c802009-06-12 22:26:59 -06001201static void handle_output(unsigned long addr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001202{
1203 struct device *i;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001204
Rusty Russell659a0e62009-06-12 22:27:10 -06001205 /* Check each device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001206 for (i = devices.dev; i; i = i->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001207 struct virtqueue *vq;
1208
Rusty Russella91d74a2009-07-30 16:03:45 -06001209 /*
1210 * Notifications to device descriptors mean they updated the
1211 * device status.
1212 */
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001213 if (from_guest_phys(addr) == i->desc) {
Rusty Russella007a752008-05-02 21:50:53 -05001214 update_device_status(i);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001215 return;
1216 }
1217
Rusty Russell3c3ed482011-07-22 14:39:49 +09301218 /* Devices should not be used before features are finalized. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001219 for (vq = i->vq; vq; vq = vq->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001220 if (addr != vq->config.pfn*getpagesize())
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001221 continue;
Rusty Russell3c3ed482011-07-22 14:39:49 +09301222 errx(1, "Notification on %s before setup!", i->name);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001223 }
1224 }
Rusty Russelldde79782007-07-26 10:41:03 -07001225
Rusty Russell2e04ef72009-07-30 16:03:45 -06001226 /*
1227 * Early console write is done using notify on a nul-terminated string
1228 * in Guest memory. It's also great for hacking debugging messages
1229 * into a Guest.
1230 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001231 if (addr >= guest_limit)
1232 errx(1, "Bad NOTIFY %#lx", addr);
1233
1234 write(STDOUT_FILENO, from_guest_phys(addr),
1235 strnlen(from_guest_phys(addr), guest_limit - addr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001236}
1237
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301238/*L:217
1239 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1240 * code.
1241 */
1242
Rusty Russell8e709462015-02-11 15:15:12 +10301243/* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1244static struct device pci_host_bridge;
1245
1246static void init_pci_host_bridge(void)
1247{
1248 pci_host_bridge.name = "PCI Host Bridge";
1249 pci_host_bridge.config.class = 0x06; /* bridge */
1250 pci_host_bridge.config.subclass = 0; /* host bridge */
1251 devices.pci[0] = &pci_host_bridge;
1252}
1253
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301254/* The IO ports used to read the PCI config space. */
1255#define PCI_CONFIG_ADDR 0xCF8
1256#define PCI_CONFIG_DATA 0xCFC
1257
1258/*
1259 * Not really portable, but does help readability: this is what the Guest
1260 * writes to the PCI_CONFIG_ADDR IO port.
1261 */
1262union pci_config_addr {
1263 struct {
1264 unsigned mbz: 2;
1265 unsigned offset: 6;
1266 unsigned funcnum: 3;
1267 unsigned devnum: 5;
1268 unsigned busnum: 8;
1269 unsigned reserved: 7;
1270 unsigned enabled : 1;
1271 } bits;
1272 u32 val;
1273};
1274
1275/*
1276 * We cache what they wrote to the address port, so we know what they're
1277 * talking about when they access the data port.
1278 */
1279static union pci_config_addr pci_config_addr;
1280
1281static struct device *find_pci_device(unsigned int index)
1282{
1283 return devices.pci[index];
1284}
1285
1286/* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1287static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1288{
1289 assert(off < 4);
1290 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1291 *val = (v >> (off * 8)) & mask;
1292}
1293
1294/* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1295static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1296{
1297 assert(off < 4);
1298 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1299 *dst &= ~(mask << (off * 8));
1300 *dst |= (v & mask) << (off * 8);
1301}
1302
1303/*
1304 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1305 * PCI_CONFIG_ADDR.
1306 */
1307static struct device *dev_and_reg(u32 *reg)
1308{
1309 if (!pci_config_addr.bits.enabled)
1310 return NULL;
1311
1312 if (pci_config_addr.bits.funcnum != 0)
1313 return NULL;
1314
1315 if (pci_config_addr.bits.busnum != 0)
1316 return NULL;
1317
1318 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1319 return NULL;
1320
1321 *reg = pci_config_addr.bits.offset;
1322 return find_pci_device(pci_config_addr.bits.devnum);
1323}
1324
1325/* Is this accessing the PCI config address port?. */
1326static bool is_pci_addr_port(u16 port)
1327{
1328 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1329}
1330
1331static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1332{
1333 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1334 &pci_config_addr.val);
1335 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1336 pci_config_addr.bits.enabled ? "" : " DISABLED",
1337 val, mask,
1338 pci_config_addr.bits.busnum,
1339 pci_config_addr.bits.devnum,
1340 pci_config_addr.bits.funcnum,
1341 pci_config_addr.bits.offset);
1342 return true;
1343}
1344
1345static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1346{
1347 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1348}
1349
1350/* Is this accessing the PCI config data port?. */
1351static bool is_pci_data_port(u16 port)
1352{
1353 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1354}
1355
1356static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1357{
1358 u32 reg, portoff;
1359 struct device *d = dev_and_reg(&reg);
1360
1361 /* Complain if they don't belong to a device. */
1362 if (!d)
1363 return false;
1364
1365 /* They can do 1 byte writes, etc. */
1366 portoff = port - PCI_CONFIG_DATA;
1367
1368 /*
1369 * PCI uses a weird way to determine the BAR size: the OS
1370 * writes all 1's, and sees which ones stick.
1371 */
1372 if (&d->config_words[reg] == &d->config.bar[0]) {
1373 int i;
1374
1375 iowrite(portoff, val, mask, &d->config.bar[0]);
1376 for (i = 0; (1 << i) < d->mmio_size; i++)
1377 d->config.bar[0] &= ~(1 << i);
1378 return true;
1379 } else if ((&d->config_words[reg] > &d->config.bar[0]
1380 && &d->config_words[reg] <= &d->config.bar[6])
1381 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1382 /* Allow writing to any other BAR, or expansion ROM */
1383 iowrite(portoff, val, mask, &d->config_words[reg]);
1384 return true;
1385 /* We let them overide latency timer and cacheline size */
1386 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1387 /* Only let them change the first two fields. */
1388 if (mask == 0xFFFFFFFF)
1389 mask = 0xFFFF;
1390 iowrite(portoff, val, mask, &d->config_words[reg]);
1391 return true;
1392 } else if (&d->config_words[reg] == (void *)&d->config.command
1393 && mask == 0xFFFF) {
1394 /* Ignore command writes. */
1395 return true;
1396 }
1397
1398 /* Complain about other writes. */
1399 return false;
1400}
1401
1402static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1403{
1404 u32 reg;
1405 struct device *d = dev_and_reg(&reg);
1406
1407 if (!d)
1408 return;
1409 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1410}
1411
Rusty Russellc565650b2015-02-11 15:15:10 +10301412/*L:216
1413 * This is where we emulate a handful of Guest instructions. It's ugly
1414 * and we used to do it in the kernel but it grew over time.
1415 */
1416
1417/*
1418 * We use the ptrace syscall's pt_regs struct to talk about registers
1419 * to lguest: these macros convert the names to the offsets.
1420 */
1421#define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1422#define setreg(name, val) \
1423 setreg_off(offsetof(struct user_regs_struct, name), (val))
1424
1425static u32 getreg_off(size_t offset)
1426{
1427 u32 r;
1428 unsigned long args[] = { LHREQ_GETREG, offset };
1429
1430 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1431 err(1, "Getting register %u", offset);
1432 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1433 err(1, "Reading register %u", offset);
1434
1435 return r;
1436}
1437
1438static void setreg_off(size_t offset, u32 val)
1439{
1440 unsigned long args[] = { LHREQ_SETREG, offset, val };
1441
1442 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1443 err(1, "Setting register %u", offset);
1444}
1445
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301446/* Get register by instruction encoding */
1447static u32 getreg_num(unsigned regnum, u32 mask)
1448{
1449 /* 8 bit ops use regnums 4-7 for high parts of word */
1450 if (mask == 0xFF && (regnum & 0x4))
1451 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1452
1453 switch (regnum) {
1454 case 0: return getreg(eax) & mask;
1455 case 1: return getreg(ecx) & mask;
1456 case 2: return getreg(edx) & mask;
1457 case 3: return getreg(ebx) & mask;
1458 case 4: return getreg(esp) & mask;
1459 case 5: return getreg(ebp) & mask;
1460 case 6: return getreg(esi) & mask;
1461 case 7: return getreg(edi) & mask;
1462 }
1463 abort();
1464}
1465
1466/* Set register by instruction encoding */
1467static void setreg_num(unsigned regnum, u32 val, u32 mask)
1468{
1469 /* Don't try to set bits out of range */
1470 assert(~(val & ~mask));
1471
1472 /* 8 bit ops use regnums 4-7 for high parts of word */
1473 if (mask == 0xFF && (regnum & 0x4)) {
1474 /* Construct the 16 bits we want. */
1475 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1476 setreg_num(regnum & 0x3, val, 0xFFFF);
1477 return;
1478 }
1479
1480 switch (regnum) {
1481 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1482 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1483 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1484 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1485 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1486 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1487 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1488 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1489 }
1490 abort();
1491}
1492
1493/* Get bytes of displacement appended to instruction, from r/m encoding */
1494static u32 insn_displacement_len(u8 mod_reg_rm)
1495{
1496 /* Switch on the mod bits */
1497 switch (mod_reg_rm >> 6) {
1498 case 0:
1499 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1500 if ((mod_reg_rm & 0x7) == 0x5)
1501 return 2;
1502 /* Normally, mod == 0 means no literal displacement */
1503 return 0;
1504 case 1:
1505 /* One byte displacement */
1506 return 1;
1507 case 2:
1508 /* Four byte displacement */
1509 return 4;
1510 case 3:
1511 /* Register mode */
1512 return 0;
1513 }
1514 abort();
1515}
1516
Rusty Russellc565650b2015-02-11 15:15:10 +10301517static void emulate_insn(const u8 insn[])
1518{
1519 unsigned long args[] = { LHREQ_TRAP, 13 };
1520 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1521 unsigned int eax, port, mask;
1522 /*
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301523 * Default is to return all-ones on IO port reads, which traditionally
Rusty Russellc565650b2015-02-11 15:15:10 +10301524 * means "there's nothing there".
1525 */
1526 u32 val = 0xFFFFFFFF;
1527
1528 /*
1529 * This must be the Guest kernel trying to do something, not userspace!
1530 * The bottom two bits of the CS segment register are the privilege
1531 * level.
1532 */
1533 if ((getreg(xcs) & 3) != 0x1)
1534 goto no_emulate;
1535
1536 /* Decoding x86 instructions is icky. */
1537
1538 /*
1539 * Around 2.6.33, the kernel started using an emulation for the
1540 * cmpxchg8b instruction in early boot on many configurations. This
1541 * code isn't paravirtualized, and it tries to disable interrupts.
1542 * Ignore it, which will Mostly Work.
1543 */
1544 if (insn[insnlen] == 0xfa) {
1545 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1546 insnlen = 1;
1547 goto skip_insn;
1548 }
1549
1550 /*
1551 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1552 */
1553 if (insn[insnlen] == 0x66) {
1554 small_operand = 1;
1555 /* The instruction is 1 byte so far, read the next byte. */
1556 insnlen = 1;
1557 }
1558
1559 /* If the lower bit isn't set, it's a single byte access */
1560 byte_access = !(insn[insnlen] & 1);
1561
1562 /*
1563 * Now we can ignore the lower bit and decode the 4 opcodes
1564 * we need to emulate.
1565 */
1566 switch (insn[insnlen] & 0xFE) {
1567 case 0xE4: /* in <next byte>,%al */
1568 port = insn[insnlen+1];
1569 insnlen += 2;
1570 in = 1;
1571 break;
1572 case 0xEC: /* in (%dx),%al */
1573 port = getreg(edx) & 0xFFFF;
1574 insnlen += 1;
1575 in = 1;
1576 break;
1577 case 0xE6: /* out %al,<next byte> */
1578 port = insn[insnlen+1];
1579 insnlen += 2;
1580 break;
1581 case 0xEE: /* out %al,(%dx) */
1582 port = getreg(edx) & 0xFFFF;
1583 insnlen += 1;
1584 break;
1585 default:
1586 /* OK, we don't know what this is, can't emulate. */
1587 goto no_emulate;
1588 }
1589
1590 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1591 if (byte_access)
1592 mask = 0xFF;
1593 else if (small_operand)
1594 mask = 0xFFFF;
1595 else
1596 mask = 0xFFFFFFFF;
1597
1598 /*
1599 * If it was an "IN" instruction, they expect the result to be read
1600 * into %eax, so we change %eax.
1601 */
1602 eax = getreg(eax);
1603
1604 if (in) {
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301605 /* This is the PS/2 keyboard status; 1 means ready for output */
1606 if (port == 0x64)
1607 val = 1;
1608 else if (is_pci_addr_port(port))
1609 pci_addr_ioread(port, mask, &val);
1610 else if (is_pci_data_port(port))
1611 pci_data_ioread(port, mask, &val);
1612
Rusty Russellc565650b2015-02-11 15:15:10 +10301613 /* Clear the bits we're about to read */
1614 eax &= ~mask;
1615 /* Copy bits in from val. */
1616 eax |= val & mask;
1617 /* Now update the register. */
1618 setreg(eax, eax);
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301619 } else {
1620 if (is_pci_addr_port(port)) {
1621 if (!pci_addr_iowrite(port, mask, eax))
1622 goto bad_io;
1623 } else if (is_pci_data_port(port)) {
1624 if (!pci_data_iowrite(port, mask, eax))
1625 goto bad_io;
1626 }
1627 /* There are many other ports, eg. CMOS clock, serial
1628 * and parallel ports, so we ignore them all. */
Rusty Russellc565650b2015-02-11 15:15:10 +10301629 }
1630
1631 verbose("IO %s of %x to %u: %#08x\n",
1632 in ? "IN" : "OUT", mask, port, eax);
1633skip_insn:
1634 /* Finally, we've "done" the instruction, so move past it. */
1635 setreg(eip, getreg(eip) + insnlen);
1636 return;
1637
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301638bad_io:
1639 warnx("Attempt to %s port %u (%#x mask)",
1640 in ? "read from" : "write to", port, mask);
1641
Rusty Russellc565650b2015-02-11 15:15:10 +10301642no_emulate:
1643 /* Inject trap into Guest. */
1644 if (write(lguest_fd, args, sizeof(args)) < 0)
1645 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1646}
1647
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301648static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1649{
1650 unsigned int i;
1651
1652 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1653 struct device *d = devices.pci[i];
1654
1655 if (!d)
1656 continue;
1657 if (paddr < d->mmio_addr)
1658 continue;
1659 if (paddr >= d->mmio_addr + d->mmio_size)
1660 continue;
1661 *off = paddr - d->mmio_addr;
1662 return d;
1663 }
1664 return NULL;
1665}
1666
Rusty Russell93153072015-02-11 15:15:11 +10301667/* FIXME: Use vq array. */
1668static struct virtqueue *vq_by_num(struct device *d, u32 num)
1669{
1670 struct virtqueue *vq = d->vq;
1671
1672 while (num-- && vq)
1673 vq = vq->next;
1674
1675 return vq;
1676}
1677
1678static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1679 struct virtqueue *vq)
1680{
1681 vq->pci_config = *cfg;
1682}
1683
1684static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1685 struct virtqueue *vq)
1686{
1687 /* Only restore the per-vq part */
1688 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1689
1690 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1691 sizeof(*cfg) - off);
1692}
1693
1694/*
1695 * When they enable the virtqueue, we check that their setup is valid.
1696 */
1697static void enable_virtqueue(struct device *d, struct virtqueue *vq)
1698{
1699 /*
1700 * Create stack for thread. Since the stack grows upwards, we point
1701 * the stack pointer to the end of this region.
1702 */
1703 char *stack = malloc(32768);
1704
1705 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1706 if (vq->pci_config.queue_desc_hi
1707 || vq->pci_config.queue_avail_hi
1708 || vq->pci_config.queue_used_hi)
1709 errx(1, "%s: invalid 64-bit queue address", d->name);
1710
1711 /* Initialize the virtqueue and check they're all in range. */
1712 vq->vring.num = vq->pci_config.queue_size;
1713 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1714 sizeof(*vq->vring.desc) * vq->vring.num);
1715 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1716 sizeof(*vq->vring.avail)
1717 + (sizeof(vq->vring.avail->ring[0])
1718 * vq->vring.num));
1719 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1720 sizeof(*vq->vring.used)
1721 + (sizeof(vq->vring.used->ring[0])
1722 * vq->vring.num));
1723
1724
1725 /* Create a zero-initialized eventfd. */
1726 vq->eventfd = eventfd(0, 0);
1727 if (vq->eventfd < 0)
1728 err(1, "Creating eventfd");
1729
1730 /*
1731 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1732 * we get a signal if it dies.
1733 */
1734 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1735 if (vq->thread == (pid_t)-1)
1736 err(1, "Creating clone");
1737}
1738
1739static void reset_pci_device(struct device *dev)
1740{
1741 /* FIXME */
1742}
1743
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301744static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1745{
Rusty Russell93153072015-02-11 15:15:11 +10301746 struct virtqueue *vq;
1747
1748 switch (off) {
1749 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1750 if (val == 0)
1751 d->mmio->cfg.device_feature = d->features;
1752 else if (val == 1)
1753 d->mmio->cfg.device_feature = (d->features >> 32);
1754 else
1755 d->mmio->cfg.device_feature = 0;
1756 goto write_through32;
1757 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1758 if (val > 1)
1759 errx(1, "%s: Unexpected driver select %u",
1760 d->name, val);
1761 goto write_through32;
1762 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1763 if (d->mmio->cfg.guest_feature_select == 0) {
1764 d->features_accepted &= ~((u64)0xFFFFFFFF);
1765 d->features_accepted |= val;
1766 } else {
1767 assert(d->mmio->cfg.guest_feature_select == 1);
1768 d->features_accepted &= ((u64)0xFFFFFFFF << 32);
1769 d->features_accepted |= ((u64)val) << 32;
1770 }
1771 if (d->features_accepted & ~d->features)
1772 errx(1, "%s: over-accepted features %#llx of %#llx",
1773 d->name, d->features_accepted, d->features);
1774 goto write_through32;
1775 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1776 verbose("%s: device status -> %#x\n", d->name, val);
1777 if (val == 0)
1778 reset_pci_device(d);
1779 goto write_through8;
1780 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1781 vq = vq_by_num(d, val);
1782 /* Out of range? Return size 0 */
1783 if (!vq) {
1784 d->mmio->cfg.queue_size = 0;
1785 goto write_through16;
1786 }
1787 /* Save registers for old vq, if it was a valid vq */
1788 if (d->mmio->cfg.queue_size)
1789 save_vq_config(&d->mmio->cfg,
1790 vq_by_num(d, d->mmio->cfg.queue_select));
1791 /* Restore the registers for the queue they asked for */
1792 restore_vq_config(&d->mmio->cfg, vq);
1793 goto write_through16;
1794 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
1795 if (val & (val-1))
1796 errx(1, "%s: invalid queue size %u\n", d->name, val);
1797 if (d->mmio->cfg.queue_enable)
1798 errx(1, "%s: changing queue size on live device",
1799 d->name);
1800 goto write_through16;
1801 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
1802 errx(1, "%s: attempt to set MSIX vector to %u",
1803 d->name, val);
1804 case offsetof(struct virtio_pci_mmio, cfg.queue_enable):
1805 if (val != 1)
1806 errx(1, "%s: setting queue_enable to %u", d->name, val);
1807 d->mmio->cfg.queue_enable = val;
1808 save_vq_config(&d->mmio->cfg,
1809 vq_by_num(d, d->mmio->cfg.queue_select));
1810 enable_virtqueue(d, vq_by_num(d, d->mmio->cfg.queue_select));
1811 goto write_through16;
1812 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
1813 errx(1, "%s: attempt to write to queue_notify_off", d->name);
1814 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
1815 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
1816 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
1817 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
1818 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
1819 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
1820 if (d->mmio->cfg.queue_enable)
1821 errx(1, "%s: changing queue on live device",
1822 d->name);
1823 goto write_through32;
1824 case offsetof(struct virtio_pci_mmio, notify):
1825 vq = vq_by_num(d, val);
1826 if (!vq)
1827 errx(1, "Invalid vq notification on %u", val);
1828 /* Notify the process handling this vq by adding 1 to eventfd */
1829 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
1830 goto write_through16;
1831 case offsetof(struct virtio_pci_mmio, isr):
1832 errx(1, "%s: Unexpected write to isr", d->name);
1833 default:
1834 errx(1, "%s: Unexpected write to offset %u", d->name, off);
1835 }
1836
1837write_through32:
1838 if (mask != 0xFFFFFFFF) {
1839 errx(1, "%s: non-32-bit write to offset %u (%#x)",
1840 d->name, off, getreg(eip));
1841 return;
1842 }
1843 memcpy((char *)d->mmio + off, &val, 4);
1844 return;
1845
1846write_through16:
1847 if (mask != 0xFFFF)
1848 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
1849 d->name, mask, off, getreg(eip));
1850 memcpy((char *)d->mmio + off, &val, 2);
1851 return;
1852
1853write_through8:
1854 if (mask != 0xFF)
1855 errx(1, "%s: non-8-bit write to offset %u (%#x)",
1856 d->name, off, getreg(eip));
1857 memcpy((char *)d->mmio + off, &val, 1);
1858 return;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301859}
1860
1861static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
1862{
Rusty Russell93153072015-02-11 15:15:11 +10301863 u8 isr;
1864 u32 val = 0;
1865
1866 switch (off) {
1867 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1868 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
1869 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1870 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1871 goto read_through32;
1872 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
1873 errx(1, "%s: read of msix_config", d->name);
1874 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
1875 goto read_through16;
1876 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1877 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
1878 goto read_through8;
1879 case offsetof(struct virtio_pci_mmio, notify):
1880 goto read_through16;
1881 case offsetof(struct virtio_pci_mmio, isr):
1882 if (mask != 0xFF)
1883 errx(1, "%s: non-8-bit read from offset %u (%#x)",
1884 d->name, off, getreg(eip));
1885 /* Read resets the isr */
1886 isr = d->mmio->isr;
1887 d->mmio->isr = 0;
1888 return isr;
1889 case offsetof(struct virtio_pci_mmio, padding):
1890 errx(1, "%s: read from padding (%#x)",
1891 d->name, getreg(eip));
1892 default:
1893 /* Read from device config space, beware unaligned overflow */
1894 if (off > d->mmio_size - 4)
1895 errx(1, "%s: read past end (%#x)",
1896 d->name, getreg(eip));
1897 if (mask == 0xFFFFFFFF)
1898 goto read_through32;
1899 else if (mask == 0xFFFF)
1900 goto read_through16;
1901 else
1902 goto read_through8;
1903 }
1904
1905read_through32:
1906 if (mask != 0xFFFFFFFF)
1907 errx(1, "%s: non-32-bit read to offset %u (%#x)",
1908 d->name, off, getreg(eip));
1909 memcpy(&val, (char *)d->mmio + off, 4);
1910 return val;
1911
1912read_through16:
1913 if (mask != 0xFFFF)
1914 errx(1, "%s: non-16-bit read to offset %u (%#x)",
1915 d->name, off, getreg(eip));
1916 memcpy(&val, (char *)d->mmio + off, 2);
1917 return val;
1918
1919read_through8:
1920 if (mask != 0xFF)
1921 errx(1, "%s: non-8-bit read to offset %u (%#x)",
1922 d->name, off, getreg(eip));
1923 memcpy(&val, (char *)d->mmio + off, 1);
1924 return val;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301925}
1926
1927static void emulate_mmio(unsigned long paddr, const u8 *insn)
1928{
1929 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
1930 struct device *d = find_mmio_region(paddr, &off);
1931 unsigned long args[] = { LHREQ_TRAP, 14 };
1932
1933 if (!d) {
1934 warnx("MMIO touching %#08lx (not a device)", paddr);
1935 goto reinject;
1936 }
1937
1938 /* Prefix makes it a 16 bit op */
1939 if (insn[0] == 0x66) {
1940 mask = 0xFFFF;
1941 insnlen++;
1942 }
1943
1944 /* iowrite */
1945 if (insn[insnlen] == 0x89) {
1946 /* Next byte is r/m byte: bits 3-5 are register. */
1947 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
1948 emulate_mmio_write(d, off, val, mask);
1949 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1950 } else if (insn[insnlen] == 0x8b) { /* ioread */
1951 /* Next byte is r/m byte: bits 3-5 are register. */
1952 val = emulate_mmio_read(d, off, mask);
1953 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
1954 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1955 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
1956 mask = 0xff;
1957 /* Next byte is r/m byte: bits 3-5 are register. */
1958 val = getreg_num((insn[1] >> 3) & 0x7, mask);
1959 emulate_mmio_write(d, off, val, mask);
1960 insnlen = 2 + insn_displacement_len(insn[1]);
1961 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
1962 mask = 0xff;
1963 val = emulate_mmio_read(d, off, mask);
1964 setreg_num((insn[1] >> 3) & 0x7, val, mask);
1965 insnlen = 2 + insn_displacement_len(insn[1]);
1966 } else {
1967 warnx("Unknown MMIO instruction touching %#08lx:"
1968 " %02x %02x %02x %02x at %u",
1969 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
1970 reinject:
1971 /* Inject trap into Guest. */
1972 if (write(lguest_fd, args, sizeof(args)) < 0)
1973 err(1, "Reinjecting trap 14 for fault at %#x",
1974 getreg(eip));
1975 return;
1976 }
1977
1978 /* Finally, we've "done" the instruction, so move past it. */
1979 setreg(eip, getreg(eip) + insnlen);
1980}
Rusty Russellc565650b2015-02-11 15:15:10 +10301981
Rusty Russelldde79782007-07-26 10:41:03 -07001982/*L:190
1983 * Device Setup
1984 *
1985 * All devices need a descriptor so the Guest knows it exists, and a "struct
1986 * device" so the Launcher can keep track of it. We have common helper
Rusty Russella6bd8e12008-03-28 11:05:53 -05001987 * routines to allocate and manage them.
1988 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001989
Rusty Russell2e04ef72009-07-30 16:03:45 -06001990/*
1991 * The layout of the device page is a "struct lguest_device_desc" followed by a
Rusty Russella586d4f2008-02-04 23:49:56 -05001992 * number of virtqueue descriptors, then two sets of feature bits, then an
1993 * array of configuration bytes. This routine returns the configuration
Rusty Russell2e04ef72009-07-30 16:03:45 -06001994 * pointer.
1995 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001996static u8 *device_config(const struct device *dev)
1997{
1998 return (void *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -06001999 + dev->num_vq * sizeof(struct lguest_vqconfig)
2000 + dev->feature_len * 2;
Rusty Russella586d4f2008-02-04 23:49:56 -05002001}
2002
Rusty Russell2e04ef72009-07-30 16:03:45 -06002003/*
2004 * This routine allocates a new "struct lguest_device_desc" from descriptor
Rusty Russella586d4f2008-02-04 23:49:56 -05002005 * table page just above the Guest's normal memory. It returns a pointer to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002006 * that descriptor.
2007 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002008static struct lguest_device_desc *new_dev_desc(u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002009{
Rusty Russella586d4f2008-02-04 23:49:56 -05002010 struct lguest_device_desc d = { .type = type };
2011 void *p;
2012
2013 /* Figure out where the next device config is, based on the last one. */
2014 if (devices.lastdev)
2015 p = device_config(devices.lastdev)
2016 + devices.lastdev->desc->config_len;
2017 else
2018 p = devices.descpage;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002019
Rusty Russell17cbca22007-10-22 11:24:22 +10002020 /* We only have one page for all the descriptors. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002021 if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
Rusty Russell17cbca22007-10-22 11:24:22 +10002022 errx(1, "Too many devices");
2023
Rusty Russella586d4f2008-02-04 23:49:56 -05002024 /* p might not be aligned, so we memcpy in. */
2025 return memcpy(p, &d, sizeof(d));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002026}
2027
Rusty Russell2e04ef72009-07-30 16:03:45 -06002028/*
2029 * Each device descriptor is followed by the description of its virtqueues. We
2030 * specify how many descriptors the virtqueue is to have.
2031 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002032static void add_virtqueue(struct device *dev, unsigned int num_descs,
Rusty Russell659a0e62009-06-12 22:27:10 -06002033 void (*service)(struct virtqueue *))
Rusty Russell17cbca22007-10-22 11:24:22 +10002034{
2035 unsigned int pages;
2036 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2037 void *p;
2038
Rusty Russella6bd8e12008-03-28 11:05:53 -05002039 /* First we need some memory for this virtqueue. */
Rusty Russell2966af72008-12-30 09:25:58 -06002040 pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
Rusty Russell42b36cc2007-11-12 13:39:18 +11002041 / getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002042 p = get_pages(pages);
2043
Rusty Russelld1c856e2007-11-19 11:20:40 -05002044 /* Initialize the virtqueue */
2045 vq->next = NULL;
2046 vq->last_avail_idx = 0;
2047 vq->dev = dev;
Rusty Russella91d74a2009-07-30 16:03:45 -06002048
2049 /*
2050 * This is the routine the service thread will run, and its Process ID
2051 * once it's running.
2052 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002053 vq->service = service;
2054 vq->thread = (pid_t)-1;
Rusty Russelld1c856e2007-11-19 11:20:40 -05002055
Rusty Russell17cbca22007-10-22 11:24:22 +10002056 /* Initialize the configuration. */
2057 vq->config.num = num_descs;
2058 vq->config.irq = devices.next_irq++;
2059 vq->config.pfn = to_guest_phys(p) / getpagesize();
2060
2061 /* Initialize the vring. */
Rusty Russell2966af72008-12-30 09:25:58 -06002062 vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
Rusty Russell17cbca22007-10-22 11:24:22 +10002063
Rusty Russell2e04ef72009-07-30 16:03:45 -06002064 /*
2065 * Append virtqueue to this device's descriptor. We use
Rusty Russella586d4f2008-02-04 23:49:56 -05002066 * device_config() to get the end of the device's current virtqueues;
2067 * we check that we haven't added any config or feature information
Rusty Russell2e04ef72009-07-30 16:03:45 -06002068 * yet, otherwise we'd be overwriting them.
2069 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002070 assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
2071 memcpy(device_config(dev), &vq->config, sizeof(vq->config));
Rusty Russell713b15b2009-06-12 22:26:58 -06002072 dev->num_vq++;
Rusty Russella586d4f2008-02-04 23:49:56 -05002073 dev->desc->num_vq++;
2074
2075 verbose("Virtqueue page %#lx\n", to_guest_phys(p));
Rusty Russell17cbca22007-10-22 11:24:22 +10002076
Rusty Russell2e04ef72009-07-30 16:03:45 -06002077 /*
2078 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2079 * second.
2080 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002081 for (i = &dev->vq; *i; i = &(*i)->next);
2082 *i = vq;
Rusty Russell17cbca22007-10-22 11:24:22 +10002083}
2084
Rusty Russell93153072015-02-11 15:15:11 +10302085static void add_pci_virtqueue(struct device *dev,
2086 void (*service)(struct virtqueue *))
2087{
2088 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2089
2090 /* Initialize the virtqueue */
2091 vq->next = NULL;
2092 vq->last_avail_idx = 0;
2093 vq->dev = dev;
2094
2095 /*
2096 * This is the routine the service thread will run, and its Process ID
2097 * once it's running.
2098 */
2099 vq->service = service;
2100 vq->thread = (pid_t)-1;
2101
2102 /* Initialize the configuration. */
2103 vq->pci_config.queue_size = VIRTQUEUE_NUM;
2104 vq->pci_config.queue_enable = 0;
2105 vq->pci_config.queue_notify_off = 0;
2106
2107 /* Add one to the number of queues */
2108 vq->dev->mmio->cfg.num_queues++;
2109
2110 /* FIXME: Do irq per virtqueue, not per device. */
2111 vq->config.irq = vq->dev->config.irq_line;
2112
2113 /*
2114 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2115 * second.
2116 */
2117 for (i = &dev->vq; *i; i = &(*i)->next);
2118 *i = vq;
2119}
2120
Rusty Russell2e04ef72009-07-30 16:03:45 -06002121/*
2122 * The first half of the feature bitmask is for us to advertise features. The
2123 * second half is for the Guest to accept features.
2124 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002125static void add_feature(struct device *dev, unsigned bit)
2126{
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05002127 u8 *features = get_feature_bits(dev);
Rusty Russella586d4f2008-02-04 23:49:56 -05002128
2129 /* We can't extend the feature bits once we've added config bytes */
2130 if (dev->desc->feature_len <= bit / CHAR_BIT) {
2131 assert(dev->desc->config_len == 0);
Rusty Russell713b15b2009-06-12 22:26:58 -06002132 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
Rusty Russella586d4f2008-02-04 23:49:56 -05002133 }
2134
Rusty Russella586d4f2008-02-04 23:49:56 -05002135 features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
2136}
2137
Rusty Russell93153072015-02-11 15:15:11 +10302138static void add_pci_feature(struct device *dev, unsigned bit)
2139{
2140 dev->features |= (1ULL << bit);
2141}
2142
Rusty Russell2e04ef72009-07-30 16:03:45 -06002143/*
2144 * This routine sets the configuration fields for an existing device's
Rusty Russella586d4f2008-02-04 23:49:56 -05002145 * descriptor. It only works for the last device, but that's OK because that's
Rusty Russell2e04ef72009-07-30 16:03:45 -06002146 * how we use it.
2147 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002148static void set_config(struct device *dev, unsigned len, const void *conf)
2149{
2150 /* Check we haven't overflowed our single page. */
2151 if (device_config(dev) + len > devices.descpage + getpagesize())
2152 errx(1, "Too many devices");
2153
2154 /* Copy in the config information, and store the length. */
2155 memcpy(device_config(dev), conf, len);
2156 dev->desc->config_len = len;
Rusty Russell8ef562d2009-07-30 16:03:43 -06002157
2158 /* Size must fit in config_len field (8 bits)! */
2159 assert(dev->desc->config_len == len);
Rusty Russella586d4f2008-02-04 23:49:56 -05002160}
2161
Rusty Russell93153072015-02-11 15:15:11 +10302162/* For devices with no config. */
2163static void no_device_config(struct device *dev)
2164{
2165 dev->mmio_addr = get_mmio_region(dev->mmio_size);
2166
2167 dev->config.bar[0] = dev->mmio_addr;
2168 /* Bottom 4 bits must be zero */
2169 assert(~(dev->config.bar[0] & 0xF));
2170}
2171
2172/* This puts the device config into BAR0 */
2173static void set_device_config(struct device *dev, const void *conf, size_t len)
2174{
2175 /* Set up BAR 0 */
2176 dev->mmio_size += len;
2177 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2178 memcpy(dev->mmio + 1, conf, len);
2179
2180 /* Hook up device cfg */
2181 dev->config.cfg_access.cap.cap_next
2182 = offsetof(struct pci_config, device);
2183
2184 /* Fix up device cfg field length. */
2185 dev->config.device.length = len;
2186
2187 /* The rest is the same as the no-config case */
2188 no_device_config(dev);
2189}
2190
2191static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2192 size_t bar_offset, size_t bar_bytes, u8 next)
2193{
2194 cap->cap_vndr = PCI_CAP_ID_VNDR;
2195 cap->cap_next = next;
2196 cap->cap_len = caplen;
2197 cap->cfg_type = type;
2198 cap->bar = 0;
2199 memset(cap->padding, 0, sizeof(cap->padding));
2200 cap->offset = bar_offset;
2201 cap->length = bar_bytes;
2202}
2203
2204/*
2205 * This sets up the pci_config structure, as defined in the virtio 1.0
2206 * standard (and PCI standard).
2207 */
2208static void init_pci_config(struct pci_config *pci, u16 type,
2209 u8 class, u8 subclass)
2210{
2211 size_t bar_offset, bar_len;
2212
2213 /* Save typing: most thing are happy being zero. */
2214 memset(pci, 0, sizeof(*pci));
2215
2216 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2217 pci->vendor_id = 0x1AF4;
2218 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2219 pci->device_id = 0x1040 + type;
2220
2221 /*
2222 * PCI have specific codes for different types of devices.
2223 * Linux doesn't care, but it's a good clue for people looking
2224 * at the device.
Rusty Russell93153072015-02-11 15:15:11 +10302225 */
2226 pci->class = class;
2227 pci->subclass = subclass;
2228
2229 /*
2230 * 4.1.2.1 Non-transitional devices SHOULD have a PCI Revision
2231 * ID of 1 or higher
2232 */
2233 pci->revid = 1;
2234
2235 /*
2236 * 4.1.2.1 Non-transitional devices SHOULD have a PCI
2237 * Subsystem Device ID of 0x40 or higher.
2238 */
2239 pci->subsystem_device_id = 0x40;
2240
2241 /* We use our dummy interrupt controller, and irq_line is the irq */
2242 pci->irq_line = devices.next_irq++;
2243 pci->irq_pin = 0;
2244
2245 /* Support for extended capabilities. */
2246 pci->status = (1 << 4);
2247
2248 /* Link them in. */
2249 pci->capabilities = offsetof(struct pci_config, common);
2250
2251 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2252 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2253 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2254 bar_offset, bar_len,
2255 offsetof(struct pci_config, notify));
2256
2257 bar_offset += bar_len;
2258 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2259 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2260 init_cap(&pci->notify.cap, sizeof(pci->notify),
2261 VIRTIO_PCI_CAP_NOTIFY_CFG,
2262 bar_offset, bar_len,
2263 offsetof(struct pci_config, isr));
2264
2265 bar_offset += bar_len;
2266 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2267 init_cap(&pci->isr, sizeof(pci->isr),
2268 VIRTIO_PCI_CAP_ISR_CFG,
2269 bar_offset, bar_len,
2270 offsetof(struct pci_config, cfg_access));
2271
2272 /* This doesn't have any presence in the BAR */
2273 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2274 VIRTIO_PCI_CAP_PCI_CFG,
2275 0, 0, 0);
2276
2277 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2278 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2279
2280 /*
2281 * This gets sewn in and length set in set_device_config().
2282 * Some devices don't have a device configuration interface, so
2283 * we never expose this if we don't call set_device_config().
2284 */
2285 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2286 bar_offset, 0, 0);
2287}
2288
Rusty Russell2e04ef72009-07-30 16:03:45 -06002289/*
2290 * This routine does all the creation and setup of a new device, including
Rusty Russella91d74a2009-07-30 16:03:45 -06002291 * calling new_dev_desc() to allocate the descriptor and device memory. We
2292 * don't actually start the service threads until later.
Rusty Russella6bd8e12008-03-28 11:05:53 -05002293 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002294 * See what I mean about userspace being boring?
2295 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002296static struct device *new_device(const char *name, u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002297{
2298 struct device *dev = malloc(sizeof(*dev));
2299
Rusty Russelldde79782007-07-26 10:41:03 -07002300 /* Now we populate the fields one at a time. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002301 dev->desc = new_dev_desc(type);
Rusty Russell17cbca22007-10-22 11:24:22 +10002302 dev->name = name;
Rusty Russelld1c856e2007-11-19 11:20:40 -05002303 dev->vq = NULL;
Rusty Russell713b15b2009-06-12 22:26:58 -06002304 dev->feature_len = 0;
2305 dev->num_vq = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002306 dev->running = false;
Rusty Russellca16f582012-10-04 12:03:25 +09302307 dev->next = NULL;
Rusty Russella586d4f2008-02-04 23:49:56 -05002308
Rusty Russell2e04ef72009-07-30 16:03:45 -06002309 /*
2310 * Append to device list. Prepending to a single-linked list is
Rusty Russella586d4f2008-02-04 23:49:56 -05002311 * easier, but the user expects the devices to be arranged on the bus
2312 * in command-line order. The first network device on the command line
Rusty Russell2e04ef72009-07-30 16:03:45 -06002313 * is eth0, the first block device /dev/vda, etc.
2314 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002315 if (devices.lastdev)
2316 devices.lastdev->next = dev;
2317 else
2318 devices.dev = dev;
2319 devices.lastdev = dev;
2320
Rusty Russell8ca47e02007-07-19 01:49:29 -07002321 return dev;
2322}
2323
Rusty Russell93153072015-02-11 15:15:11 +10302324static struct device *new_pci_device(const char *name, u16 type,
2325 u8 class, u8 subclass)
2326{
2327 struct device *dev = malloc(sizeof(*dev));
2328
2329 /* Now we populate the fields one at a time. */
2330 dev->desc = NULL;
2331 dev->name = name;
2332 dev->vq = NULL;
2333 dev->feature_len = 0;
2334 dev->num_vq = 0;
2335 dev->running = false;
2336 dev->next = NULL;
2337 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2338 dev->mmio = calloc(1, dev->mmio_size);
2339 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2340 dev->features_accepted = 0;
2341
2342 if (devices.device_num + 1 >= 32)
2343 errx(1, "Can only handle 31 PCI devices");
2344
2345 init_pci_config(&dev->config, type, class, subclass);
2346 assert(!devices.pci[devices.device_num+1]);
2347 devices.pci[++devices.device_num] = dev;
2348
2349 return dev;
2350}
2351
Rusty Russell2e04ef72009-07-30 16:03:45 -06002352/*
2353 * Our first setup routine is the console. It's a fairly simple device, but
2354 * UNIX tty handling makes it uglier than it could be.
2355 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002356static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002357{
2358 struct device *dev;
2359
Rusty Russelldde79782007-07-26 10:41:03 -07002360 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002361 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2362 struct termios term = orig_term;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002363 /*
2364 * Then we turn off echo, line buffering and ^C etc: We want a
2365 * raw input stream to the Guest.
2366 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002367 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2368 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002369 }
2370
Rusty Russellebff0112015-02-11 15:18:01 +10302371 dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002372
Rusty Russelldde79782007-07-26 10:41:03 -07002373 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002374 dev->priv = malloc(sizeof(struct console_abort));
2375 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002376
Rusty Russell2e04ef72009-07-30 16:03:45 -06002377 /*
2378 * The console needs two virtqueues: the input then the output. When
Rusty Russell56ae43d2007-10-22 11:24:23 +10002379 * they put something the input queue, we make sure we're listening to
2380 * stdin. When they put something in the output queue, we write it to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002381 * stdout.
2382 */
Rusty Russellebff0112015-02-11 15:18:01 +10302383 add_pci_virtqueue(dev, console_input);
2384 add_pci_virtqueue(dev, console_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002385
Rusty Russellebff0112015-02-11 15:18:01 +10302386 /* There's no configuration area for this device. */
2387 no_device_config(dev);
2388
2389 verbose("device %u: console\n", devices.device_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002390}
Rusty Russelldde79782007-07-26 10:41:03 -07002391/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002392
Rusty Russell2e04ef72009-07-30 16:03:45 -06002393/*M:010
2394 * Inter-guest networking is an interesting area. Simplest is to have a
Rusty Russell17cbca22007-10-22 11:24:22 +10002395 * --sharenet=<name> option which opens or creates a named pipe. This can be
2396 * used to send packets to another guest in a 1:1 manner.
2397 *
Rusty Russell9f542882011-07-22 14:39:50 +09302398 * More sophisticated is to use one of the tools developed for project like UML
Rusty Russell17cbca22007-10-22 11:24:22 +10002399 * to do networking.
2400 *
2401 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2402 * completely generic ("here's my vring, attach to your vring") and would work
2403 * for any traffic. Of course, namespace and permissions issues need to be
2404 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2405 * multiple inter-guest channels behind one interface, although it would
2406 * require some manner of hotplugging new virtio channels.
2407 *
Rusty Russell9f542882011-07-22 14:39:50 +09302408 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002409:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002410
Rusty Russell8ca47e02007-07-19 01:49:29 -07002411static u32 str2ip(const char *ipaddr)
2412{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002413 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002414
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002415 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2416 errx(1, "Failed to parse IP address '%s'", ipaddr);
2417 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2418}
2419
2420static void str2mac(const char *macaddr, unsigned char mac[6])
2421{
2422 unsigned int m[6];
2423 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2424 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2425 errx(1, "Failed to parse mac address '%s'", macaddr);
2426 mac[0] = m[0];
2427 mac[1] = m[1];
2428 mac[2] = m[2];
2429 mac[3] = m[3];
2430 mac[4] = m[4];
2431 mac[5] = m[5];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002432}
2433
Rusty Russell2e04ef72009-07-30 16:03:45 -06002434/*
2435 * This code is "adapted" from libbridge: it attaches the Host end of the
Rusty Russelldde79782007-07-26 10:41:03 -07002436 * network device to the bridge device specified by the command line.
2437 *
2438 * This is yet another James Morris contribution (I'm an IP-level guy, so I
Rusty Russell2e04ef72009-07-30 16:03:45 -06002439 * dislike bridging), and I just try not to break it.
2440 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002441static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2442{
2443 int ifidx;
2444 struct ifreq ifr;
2445
2446 if (!*br_name)
2447 errx(1, "must specify bridge name");
2448
2449 ifidx = if_nametoindex(if_name);
2450 if (!ifidx)
2451 errx(1, "interface %s does not exist!", if_name);
2452
2453 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002454 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07002455 ifr.ifr_ifindex = ifidx;
2456 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2457 err(1, "can't add %s to bridge %s", if_name, br_name);
2458}
2459
Rusty Russell2e04ef72009-07-30 16:03:45 -06002460/*
2461 * This sets up the Host end of the network device with an IP address, brings
Rusty Russelldde79782007-07-26 10:41:03 -07002462 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell2e04ef72009-07-30 16:03:45 -06002463 * pointer.
2464 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002465static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002466{
2467 struct ifreq ifr;
Rusty Russellf8466192010-08-27 08:39:48 -06002468 struct sockaddr_in sin;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002469
2470 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002471 strcpy(ifr.ifr_name, tapif);
2472
2473 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russellf8466192010-08-27 08:39:48 -06002474 sin.sin_family = AF_INET;
2475 sin.sin_addr.s_addr = htonl(ipaddr);
2476 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002477 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002478 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002479 ifr.ifr_flags = IFF_UP;
2480 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002481 err(1, "Bringing interface %s up", tapif);
2482}
2483
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002484static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07002485{
Rusty Russell8ca47e02007-07-19 01:49:29 -07002486 struct ifreq ifr;
Rusty Russellbf6d4032015-02-11 15:16:01 +10302487 int vnet_hdr_sz;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002488 int netfd;
2489
2490 /* Start with this zeroed. Messy but sure. */
2491 memset(&ifr, 0, sizeof(ifr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002492
Rusty Russell2e04ef72009-07-30 16:03:45 -06002493 /*
2494 * We open the /dev/net/tun device and tell it we want a tap device. A
Rusty Russelldde79782007-07-26 10:41:03 -07002495 * tap device is like a tun device, only somehow different. To tell
2496 * the truth, I completely blundered my way through this code, but it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002497 * works now!
2498 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002499 netfd = open_or_die("/dev/net/tun", O_RDWR);
Rusty Russell398f1872008-07-29 09:58:37 -05002500 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002501 strcpy(ifr.ifr_name, "tap%d");
2502 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2503 err(1, "configuring /dev/net/tun");
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002504
Rusty Russell398f1872008-07-29 09:58:37 -05002505 if (ioctl(netfd, TUNSETOFFLOAD,
2506 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2507 err(1, "Could not set features for tun device");
2508
Rusty Russell2e04ef72009-07-30 16:03:45 -06002509 /*
2510 * We don't need checksums calculated for packets coming in this
2511 * device: trust us!
2512 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002513 ioctl(netfd, TUNSETNOCSUM, 1);
2514
Rusty Russellbf6d4032015-02-11 15:16:01 +10302515 /*
2516 * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2517 * field at the end of the network header iff
2518 * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
2519 * that became the norm, but we need to tell the tun device
2520 * about our expanded header (which is called
2521 * virtio_net_hdr_mrg_rxbuf in the legacy system).
2522 */
2523 vnet_hdr_sz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2524 if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
2525 err(1, "Setting tun header size to %u", vnet_hdr_sz);
2526
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002527 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2528 return netfd;
2529}
2530
Rusty Russell2e04ef72009-07-30 16:03:45 -06002531/*L:195
2532 * Our network is a Host<->Guest network. This can either use bridging or
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002533 * routing, but the principle is the same: it uses the "tun" device to inject
2534 * packets into the Host as if they came in from a normal network card. We
Rusty Russell2e04ef72009-07-30 16:03:45 -06002535 * just shunt packets between the Guest and the tun device.
2536 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002537static void setup_tun_net(char *arg)
2538{
2539 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002540 struct net_info *net_info = malloc(sizeof(*net_info));
2541 int ipfd;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002542 u32 ip = INADDR_ANY;
2543 bool bridging = false;
2544 char tapif[IFNAMSIZ], *p;
2545 struct virtio_net_config conf;
2546
Rusty Russell659a0e62009-06-12 22:27:10 -06002547 net_info->tunfd = get_tun_device(tapif);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002548
Rusty Russell17cbca22007-10-22 11:24:22 +10002549 /* First we create a new network device. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302550 dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002551 dev->priv = net_info;
Rusty Russelldde79782007-07-26 10:41:03 -07002552
Rusty Russell2e04ef72009-07-30 16:03:45 -06002553 /* Network devices need a recv and a send queue, just like console. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302554 add_pci_virtqueue(dev, net_input);
2555 add_pci_virtqueue(dev, net_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002556
Rusty Russell2e04ef72009-07-30 16:03:45 -06002557 /*
2558 * We need a socket to perform the magic network ioctls to bring up the
2559 * tap interface, connect to the bridge etc. Any socket will do!
2560 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002561 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2562 if (ipfd < 0)
2563 err(1, "opening IP socket");
2564
Rusty Russelldde79782007-07-26 10:41:03 -07002565 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002566 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002567 arg += strlen(BRIDGE_PFX);
2568 bridging = true;
2569 }
2570
2571 /* A mac address may follow the bridge name or IP address */
2572 p = strchr(arg, ':');
2573 if (p) {
2574 str2mac(p+1, conf.mac);
Rusty Russellbf6d4032015-02-11 15:16:01 +10302575 add_pci_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002576 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002577 }
2578
2579 /* arg is now either an IP address or a bridge name */
2580 if (bridging)
2581 add_to_bridge(ipfd, tapif, arg);
2582 else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002583 ip = str2ip(arg);
2584
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002585 /* Set up the tun device. */
2586 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002587
Rusty Russell398f1872008-07-29 09:58:37 -05002588 /* Expect Guest to handle everything except UFO */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302589 add_pci_feature(dev, VIRTIO_NET_F_CSUM);
2590 add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2591 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2592 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2593 add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2594 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2595 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2596 add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
Mark McLoughlind1f01322009-05-11 18:11:46 +01002597 /* We handle indirect ring entries */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302598 add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2599 set_device_config(dev, &conf, sizeof(conf));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002600
Rusty Russella586d4f2008-02-04 23:49:56 -05002601 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002602 close(ipfd);
2603
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002604 if (bridging)
2605 verbose("device %u: tun %s attached to bridge: %s\n",
2606 devices.device_num, tapif, arg);
2607 else
2608 verbose("device %u: tun %s: %s\n",
2609 devices.device_num, tapif, arg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002610}
Rusty Russella91d74a2009-07-30 16:03:45 -06002611/*:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002612
Rusty Russelle1e72962007-10-25 15:02:50 +10002613/* This hangs off device->priv. */
Rusty Russell1842f232009-07-30 16:03:46 -06002614struct vblk_info {
Rusty Russell17cbca22007-10-22 11:24:22 +10002615 /* The size of the file. */
2616 off64_t len;
2617
2618 /* The file descriptor for the file. */
2619 int fd;
2620
Rusty Russell17cbca22007-10-22 11:24:22 +10002621};
2622
Rusty Russelle1e72962007-10-25 15:02:50 +10002623/*L:210
2624 * The Disk
2625 *
Rusty Russella91d74a2009-07-30 16:03:45 -06002626 * The disk only has one virtqueue, so it only has one thread. It is really
2627 * simple: the Guest asks for a block number and we read or write that position
2628 * in the file.
2629 *
2630 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2631 * slow: the Guest waits until the read is finished before running anything
2632 * else, even if it could have been doing useful work.
2633 *
2634 * We could have used async I/O, except it's reputed to suck so hard that
2635 * characters actually go missing from your code when you try to use it.
Rusty Russelle1e72962007-10-25 15:02:50 +10002636 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002637static void blk_request(struct virtqueue *vq)
Rusty Russell17cbca22007-10-22 11:24:22 +10002638{
Rusty Russell659a0e62009-06-12 22:27:10 -06002639 struct vblk_info *vblk = vq->dev->priv;
Rusty Russell17cbca22007-10-22 11:24:22 +10002640 unsigned int head, out_num, in_num, wlen;
Rusty Russellc0316a92012-10-16 23:56:13 +10302641 int ret, i;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002642 u8 *in;
Rusty Russellc0316a92012-10-16 23:56:13 +10302643 struct virtio_blk_outhdr out;
Rusty Russell659a0e62009-06-12 22:27:10 -06002644 struct iovec iov[vq->vring.num];
Rusty Russell17cbca22007-10-22 11:24:22 +10002645 off64_t off;
2646
Rusty Russella91d74a2009-07-30 16:03:45 -06002647 /*
2648 * Get the next request, where we normally wait. It triggers the
2649 * interrupt to acknowledge previously serviced requests (if any).
2650 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002651 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002652
Rusty Russellc0316a92012-10-16 23:56:13 +10302653 /* Copy the output header from the front of the iov (adjusts iov) */
2654 iov_consume(iov, out_num, &out, sizeof(out));
Rusty Russell17cbca22007-10-22 11:24:22 +10002655
Rusty Russellc0316a92012-10-16 23:56:13 +10302656 /* Find and trim end of iov input array, for our status byte. */
2657 in = NULL;
2658 for (i = out_num + in_num - 1; i >= out_num; i--) {
2659 if (iov[i].iov_len > 0) {
2660 in = iov[i].iov_base + iov[i].iov_len - 1;
2661 iov[i].iov_len--;
2662 break;
2663 }
2664 }
2665 if (!in)
2666 errx(1, "Bad virtblk cmd with no room for status");
2667
Rusty Russella91d74a2009-07-30 16:03:45 -06002668 /*
2669 * For historical reasons, block operations are expressed in 512 byte
2670 * "sectors".
2671 */
Rusty Russellc0316a92012-10-16 23:56:13 +10302672 off = out.sector * 512;
Rusty Russell17cbca22007-10-22 11:24:22 +10002673
Rusty Russell50516542015-02-11 15:15:12 +10302674 if (out.type & VIRTIO_BLK_T_OUT) {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002675 /*
2676 * Write
2677 *
2678 * Move to the right location in the block file. This can fail
2679 * if they try to write past end.
2680 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002681 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302682 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002683
Rusty Russellc0316a92012-10-16 23:56:13 +10302684 ret = writev(vblk->fd, iov, out_num);
2685 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
Rusty Russell17cbca22007-10-22 11:24:22 +10002686
Rusty Russell2e04ef72009-07-30 16:03:45 -06002687 /*
2688 * Grr... Now we know how long the descriptor they sent was, we
Rusty Russell17cbca22007-10-22 11:24:22 +10002689 * make sure they didn't try to write over the end of the block
Rusty Russell2e04ef72009-07-30 16:03:45 -06002690 * file (possibly extending it).
2691 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002692 if (ret > 0 && off + ret > vblk->len) {
2693 /* Trim it back to the correct length */
2694 ftruncate64(vblk->fd, vblk->len);
2695 /* Die, bad Guest, die. */
2696 errx(1, "Write past end %llu+%u", off, ret);
2697 }
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002698
2699 wlen = sizeof(*in);
2700 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russellc0316a92012-10-16 23:56:13 +10302701 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002702 /* Flush */
2703 ret = fdatasync(vblk->fd);
2704 verbose("FLUSH fdatasync: %i\n", ret);
Anthony Liguori1200e642007-11-08 21:13:44 -06002705 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002706 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10002707 } else {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002708 /*
2709 * Read
2710 *
2711 * Move to the right location in the block file. This can fail
2712 * if they try to read past end.
2713 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002714 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302715 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002716
Rusty Russellc0316a92012-10-16 23:56:13 +10302717 ret = readv(vblk->fd, iov + out_num, in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002718 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06002719 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002720 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10002721 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06002722 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002723 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10002724 }
2725 }
2726
Rusty Russella91d74a2009-07-30 16:03:45 -06002727 /* Finished that request. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002728 add_used(vq, head, wlen);
Rusty Russell17cbca22007-10-22 11:24:22 +10002729}
2730
Rusty Russelle1e72962007-10-25 15:02:50 +10002731/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002732static void setup_block_file(const char *filename)
2733{
Rusty Russell17cbca22007-10-22 11:24:22 +10002734 struct device *dev;
2735 struct vblk_info *vblk;
Rusty Russella586d4f2008-02-04 23:49:56 -05002736 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10002737
Rusty Russell50516542015-02-11 15:15:12 +10302738 /* Create the device. */
2739 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
Rusty Russell17cbca22007-10-22 11:24:22 +10002740
Rusty Russelle1e72962007-10-25 15:02:50 +10002741 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell50516542015-02-11 15:15:12 +10302742 add_pci_virtqueue(dev, blk_request);
Rusty Russell17cbca22007-10-22 11:24:22 +10002743
2744 /* Allocate the room for our own bookkeeping */
2745 vblk = dev->priv = malloc(sizeof(*vblk));
2746
2747 /* First we open the file and store the length. */
2748 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
2749 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
2750
2751 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002752 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10002753
Rusty Russell2e04ef72009-07-30 16:03:45 -06002754 /*
2755 * Tell Guest not to put in too many descriptors at once: two are used
2756 * for the in and out elements.
2757 */
Rusty Russell50516542015-02-11 15:15:12 +10302758 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
Rusty Russella586d4f2008-02-04 23:49:56 -05002759 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2760
Rusty Russell50516542015-02-11 15:15:12 +10302761 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
Rusty Russell17cbca22007-10-22 11:24:22 +10002762
Rusty Russell17cbca22007-10-22 11:24:22 +10002763 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell50516542015-02-11 15:15:12 +10302764 devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10002765}
Rusty Russell28fd6d72008-07-29 09:58:33 -05002766
Rusty Russell2e04ef72009-07-30 16:03:45 -06002767/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10302768 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05002769 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10302770 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05002771 * console is the reverse.
2772 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002773 * The same logic applies, however.
2774 */
2775struct rng_info {
2776 int rfd;
2777};
2778
Rusty Russell659a0e62009-06-12 22:27:10 -06002779static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05002780{
2781 int len;
2782 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002783 struct rng_info *rng_info = vq->dev->priv;
2784 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05002785
2786 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002787 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002788 if (out_num)
2789 errx(1, "Output buffers in rng?");
2790
Rusty Russell2e04ef72009-07-30 16:03:45 -06002791 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06002792 * Just like the console write, we loop to cover the whole iovec.
2793 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002794 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002795 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06002796 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002797 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10302798 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10302799 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002800 totlen += len;
2801 }
2802
2803 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002804 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002805}
2806
Rusty Russell2e04ef72009-07-30 16:03:45 -06002807/*L:199
2808 * This creates a "hardware" random number device for the Guest.
2809 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002810static void setup_rng(void)
2811{
2812 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002813 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05002814
Rusty Russella454bb32015-02-11 15:15:09 +10302815 /* Our device's private info simply contains the /dev/urandom fd. */
2816 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002817
Rusty Russell2e04ef72009-07-30 16:03:45 -06002818 /* Create the new device. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302819 dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
Rusty Russell659a0e62009-06-12 22:27:10 -06002820 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002821
2822 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302823 add_pci_virtqueue(dev, rng_input);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002824
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302825 /* We don't have any configuration space */
2826 no_device_config(dev);
2827
2828 verbose("device %u: rng\n", devices.device_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002829}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002830/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05302831
Rusty Russella6bd8e12008-03-28 11:05:53 -05002832/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05302833static void __attribute__((noreturn)) restart_guest(void)
2834{
2835 unsigned int i;
2836
Rusty Russell2e04ef72009-07-30 16:03:45 -06002837 /*
2838 * Since we don't track all open fds, we simply close everything beyond
2839 * stderr.
2840 */
Balaji Raoec04b132007-12-28 14:26:24 +05302841 for (i = 3; i < FD_SETSIZE; i++)
2842 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05002843
Rusty Russell659a0e62009-06-12 22:27:10 -06002844 /* Reset all the devices (kills all threads). */
2845 cleanup_devices();
2846
Balaji Raoec04b132007-12-28 14:26:24 +05302847 execv(main_args[0], main_args);
2848 err(1, "Could not exec %s", main_args[0]);
2849}
Rusty Russell8ca47e02007-07-19 01:49:29 -07002850
Rusty Russell2e04ef72009-07-30 16:03:45 -06002851/*L:220
2852 * Finally we reach the core of the Launcher which runs the Guest, serves
2853 * its input and output, and finally, lays it to rest.
2854 */
Rusty Russell56739c802009-06-12 22:26:59 -06002855static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002856{
2857 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10302858 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002859 int readval;
2860
2861 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302862 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002863
Rusty Russell17cbca22007-10-22 11:24:22 +10002864 /* One unsigned long means the Guest did HCALL_NOTIFY */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302865 if (readval == sizeof(notify)) {
2866 if (notify.trap == 0x1F) {
2867 verbose("Notify on address %#08x\n",
2868 notify.addr);
2869 handle_output(notify.addr);
Rusty Russellc565650b2015-02-11 15:15:10 +10302870 } else if (notify.trap == 13) {
2871 verbose("Emulating instruction at %#x\n",
2872 getreg(eip));
2873 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302874 } else if (notify.trap == 14) {
2875 verbose("Emulating MMIO at %#x\n",
2876 getreg(eip));
2877 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302878 } else
2879 errx(1, "Unknown trap %i addr %#08x\n",
2880 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07002881 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002882 } else if (errno == ENOENT) {
2883 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002884 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002885 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05302886 /* ERESTART means that we need to reboot the guest */
2887 } else if (errno == ERESTART) {
2888 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06002889 /* Anything else means a bug or incompatible change. */
2890 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002891 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002892 }
2893}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002894/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10002895 * This is the end of the Launcher. The good news: we are over halfway
2896 * through! The bad news: the most fiendish part of the code still lies ahead
2897 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07002898 *
Rusty Russelle1e72962007-10-25 15:02:50 +10002899 * Are you ready? Take a deep breath and join me in the core of the Host, in
2900 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06002901:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002902
2903static struct option opts[] = {
2904 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002905 { "tunnet", 1, NULL, 't' },
2906 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05002907 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002908 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002909 { "username", 1, NULL, 'u' },
2910 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002911 { NULL },
2912};
2913static void usage(void)
2914{
2915 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002916 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07002917 "|--block=<filename>|--initrd=<filename>]...\n"
2918 "<mem-in-mb> vmlinux [args...]");
2919}
2920
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002921/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002922int main(int argc, char *argv[])
2923{
Rusty Russell2e04ef72009-07-30 16:03:45 -06002924 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002925 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06002926 /* Two temporaries. */
2927 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002928 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002929 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07002930 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002931 const char *initrd_name = NULL;
2932
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002933 /* Password structure for initgroups/setres[gu]id */
2934 struct passwd *user_details = NULL;
2935
2936 /* Directory to chroot to */
2937 char *chroot_path = NULL;
2938
Balaji Raoec04b132007-12-28 14:26:24 +05302939 /* Save the args: we "reboot" by execing ourselves again. */
2940 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05302941
Rusty Russell2e04ef72009-07-30 16:03:45 -06002942 /*
2943 * First we initialize the device list. We keep a pointer to the last
Rusty Russell659a0e62009-06-12 22:27:10 -06002944 * device, and the next interrupt number to use for devices (1:
Rusty Russell2e04ef72009-07-30 16:03:45 -06002945 * remember that 0 is used by the timer).
2946 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002947 devices.lastdev = NULL;
Rusty Russell17cbca22007-10-22 11:24:22 +10002948 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002949
Rusty Russella91d74a2009-07-30 16:03:45 -06002950 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002951 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06002952
Rusty Russell2e04ef72009-07-30 16:03:45 -06002953 /*
2954 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07002955 * descriptor and memory pages for the devices as we parse the command
2956 * line. So we quickly look through the arguments to find the amount
Rusty Russell2e04ef72009-07-30 16:03:45 -06002957 * of memory now.
2958 */
Rusty Russell6570c45992007-07-23 18:43:56 -07002959 for (i = 1; i < argc; i++) {
2960 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002961 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002962 /*
2963 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002964 * guest-physical memory range. This fills it with 0,
2965 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002966 * tries to access it.
2967 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002968 guest_base = map_zeroed_pages(mem / getpagesize()
2969 + DEVICE_PAGES);
2970 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10302971 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002972 devices.descpage = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07002973 break;
2974 }
2975 }
Rusty Russelldde79782007-07-26 10:41:03 -07002976
2977 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002978 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2979 switch (c) {
2980 case 'v':
2981 verbose = true;
2982 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002983 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10002984 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002985 break;
2986 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10002987 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002988 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002989 case 'r':
2990 setup_rng();
2991 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002992 case 'i':
2993 initrd_name = optarg;
2994 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002995 case 'u':
2996 user_details = getpwnam(optarg);
2997 if (!user_details)
2998 err(1, "getpwnam failed, incorrect username?");
2999 break;
3000 case 'c':
3001 chroot_path = optarg;
3002 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003003 default:
3004 warnx("Unknown argument %s", argv[optind]);
3005 usage();
3006 }
3007 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06003008 /*
3009 * After the other arguments we expect memory and kernel image name,
3010 * followed by command line arguments for the kernel.
3011 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003012 if (optind + 2 > argc)
3013 usage();
3014
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003015 verbose("Guest base is at %p\n", guest_base);
3016
Rusty Russelldde79782007-07-26 10:41:03 -07003017 /* We always have a console device */
Rusty Russell17cbca22007-10-22 11:24:22 +10003018 setup_console();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003019
Rusty Russell8e709462015-02-11 15:15:12 +10303020 /* Initialize the (fake) PCI host bridge device. */
3021 init_pci_host_bridge();
3022
Rusty Russell8ca47e02007-07-19 01:49:29 -07003023 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10003024 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07003025
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003026 /* Boot information is stashed at physical address 0 */
3027 boot = from_guest_phys(0);
3028
Rusty Russelldde79782007-07-26 10:41:03 -07003029 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003030 if (initrd_name) {
3031 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06003032 /*
3033 * These are the location in the Linux boot header where the
3034 * start and size of the initrd are expected to be found.
3035 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003036 boot->hdr.ramdisk_image = mem - initrd_size;
3037 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07003038 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003039 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003040 }
3041
Rusty Russell2e04ef72009-07-30 16:03:45 -06003042 /*
3043 * The Linux boot header contains an "E820" memory map: ours is a
3044 * simple, single region.
3045 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003046 boot->e820_entries = 1;
3047 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06003048 /*
3049 * The boot header contains a command line pointer: we put the command
3050 * line after the boot header.
3051 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003052 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10003053 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003054 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07003055
Rusty Russelle22a5392011-08-15 10:15:10 +09303056 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3057 boot->hdr.kernel_alignment = 0x1000000;
3058
Rusty Russell814a0e52007-10-22 11:29:44 +10003059 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003060 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10003061
3062 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003063 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10003064
Rusty Russell43d33b22007-10-22 11:29:57 +10003065 /* Tell the entry path not to try to reload segment registers. */
3066 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003067
Rusty Russell9f542882011-07-22 14:39:50 +09303068 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06003069 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07003070
Rusty Russella91d74a2009-07-30 16:03:45 -06003071 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06003072 signal(SIGCHLD, kill_launcher);
3073
3074 /* If we exit via err(), this kills all the threads, restores tty. */
3075 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003076
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003077 /* If requested, chroot to a directory */
3078 if (chroot_path) {
3079 if (chroot(chroot_path) != 0)
3080 err(1, "chroot(\"%s\") failed", chroot_path);
3081
3082 if (chdir("/") != 0)
3083 err(1, "chdir(\"/\") failed");
3084
3085 verbose("chroot done\n");
3086 }
3087
3088 /* If requested, drop privileges */
3089 if (user_details) {
3090 uid_t u;
3091 gid_t g;
3092
3093 u = user_details->pw_uid;
3094 g = user_details->pw_gid;
3095
3096 if (initgroups(user_details->pw_name, g) != 0)
3097 err(1, "initgroups failed");
3098
3099 if (setresgid(g, g, g) != 0)
3100 err(1, "setresgid failed");
3101
3102 if (setresuid(u, u, u) != 0)
3103 err(1, "setresuid failed");
3104
3105 verbose("Dropping privileges completed\n");
3106 }
3107
Rusty Russelldde79782007-07-26 10:41:03 -07003108 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06003109 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003110}
Rusty Russellf56a3842007-07-26 10:41:05 -07003111/*:*/
3112
3113/*M:999
3114 * Mastery is done: you now know everything I do.
3115 *
3116 * But surely you have seen code, features and bugs in your wanderings which
3117 * you now yearn to attack? That is the real game, and I look forward to you
3118 * patching and forking lguest into the Your-Name-Here-visor.
3119 *
3120 * Farewell, and good coding!
3121 * Rusty Russell.
3122 */