blob: c8930bc5ce996c6c404af71f3834cbdab248083c [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 Russell93153072015-02-11 15:15:11 +103066#define VIRTIO_PCI_NO_LEGACY
67
68/* Use in-kernel ones, which defines VIRTIO_F_VERSION_1 */
69#include "../../include/uapi/linux/virtio_config.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093070#include <linux/virtio_net.h>
71#include <linux/virtio_blk.h>
72#include <linux/virtio_console.h>
73#include <linux/virtio_rng.h>
74#include <linux/virtio_ring.h>
Rusty Russell93153072015-02-11 15:15:11 +103075#include "../../include/uapi/linux/virtio_pci.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093076#include <asm/bootparam.h>
77#include "../../include/linux/lguest_launcher.h"
78
Rusty Russell8ca47e02007-07-19 01:49:29 -070079#define BRIDGE_PFX "bridge:"
80#ifndef SIOCBRADDIF
81#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
82#endif
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100083/* We can have up to 256 pages for devices. */
84#define DEVICE_PAGES 256
Rusty Russell0f0c4fa2008-07-29 09:58:37 -050085/* This will occupy 3 pages: it must be a power of 2. */
86#define VIRTQUEUE_NUM 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070087
Rusty Russell2e04ef72009-07-30 16:03:45 -060088/*L:120
89 * verbose is both a global flag and a macro. The C preprocessor allows
90 * this, and although I wouldn't recommend it, it works quite nicely here.
91 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070092static bool verbose;
93#define verbose(args...) \
94 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070095/*:*/
96
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100097/* The pointer to the start of guest memory. */
98static void *guest_base;
99/* The maximum guest physical address allowed, and maximum possible. */
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030100static unsigned long guest_limit, guest_max, guest_mmio;
Rusty Russell56739c802009-06-12 22:26:59 -0600101/* The /dev/lguest file descriptor. */
102static int lguest_fd;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700103
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -0200104/* a per-cpu variable indicating whose vcpu is currently running */
105static unsigned int __thread cpu_id;
106
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030107/* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
108#define MAX_PCI_DEVICES 32
109
Rusty Russelldde79782007-07-26 10:41:03 -0700110/* This is our list of devices. */
Rusty Russell1842f232009-07-30 16:03:46 -0600111struct device_list {
Rusty Russell17cbca22007-10-22 11:24:22 +1000112 /* Counter to assign interrupt numbers. */
113 unsigned int next_irq;
114
115 /* Counter to print out convenient device numbers. */
116 unsigned int device_num;
117
Rusty Russelldde79782007-07-26 10:41:03 -0700118 /* The descriptor page for the devices. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000119 u8 *descpage;
120
Rusty Russelldde79782007-07-26 10:41:03 -0700121 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700122 struct device *dev;
Rusty Russell2e04ef72009-07-30 16:03:45 -0600123 /* And a pointer to the last device for easy append. */
Rusty Russella586d4f2008-02-04 23:49:56 -0500124 struct device *lastdev;
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030125
126 /* PCI devices. */
127 struct device *pci[MAX_PCI_DEVICES];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700128};
129
Rusty Russell17cbca22007-10-22 11:24:22 +1000130/* The list of Guest devices, based on command line arguments. */
131static struct device_list devices;
132
Rusty Russell93153072015-02-11 15:15:11 +1030133struct virtio_pci_cfg_cap {
134 struct virtio_pci_cap cap;
135 u32 window; /* Data for BAR access. */
136};
137
138struct virtio_pci_mmio {
139 struct virtio_pci_common_cfg cfg;
140 u16 notify;
141 u8 isr;
142 u8 padding;
143 /* Device-specific configuration follows this. */
144};
145
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030146/* This is the layout (little-endian) of the PCI config space. */
147struct pci_config {
148 u16 vendor_id, device_id;
149 u16 command, status;
150 u8 revid, prog_if, subclass, class;
151 u8 cacheline_size, lat_timer, header_type, bist;
152 u32 bar[6];
153 u32 cardbus_cis_ptr;
154 u16 subsystem_vendor_id, subsystem_device_id;
155 u32 expansion_rom_addr;
156 u8 capabilities, reserved1[3];
157 u32 reserved2;
158 u8 irq_line, irq_pin, min_grant, max_latency;
Rusty Russell93153072015-02-11 15:15:11 +1030159
160 /* Now, this is the linked capability list. */
161 struct virtio_pci_cap common;
162 struct virtio_pci_notify_cap notify;
163 struct virtio_pci_cap isr;
164 struct virtio_pci_cap device;
165 /* FIXME: Implement this! */
166 struct virtio_pci_cfg_cap cfg_access;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030167};
168
Rusty Russelldde79782007-07-26 10:41:03 -0700169/* The device structure describes a single device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600170struct device {
Rusty Russelldde79782007-07-26 10:41:03 -0700171 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700172 struct device *next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000173
Rusty Russell713b15b2009-06-12 22:26:58 -0600174 /* The device's descriptor, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700175 struct lguest_device_desc *desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000176
Rusty Russell713b15b2009-06-12 22:26:58 -0600177 /* We can't trust desc values once Guest has booted: we use these. */
178 unsigned int feature_len;
179 unsigned int num_vq;
180
Rusty Russell17cbca22007-10-22 11:24:22 +1000181 /* The name of this device, for --verbose. */
182 const char *name;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700183
Rusty Russell17cbca22007-10-22 11:24:22 +1000184 /* Any queues attached to this device */
185 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700186
Rusty Russell659a0e62009-06-12 22:27:10 -0600187 /* Is it operational */
188 bool running;
Rusty Russella007a752008-05-02 21:50:53 -0500189
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030190 /* PCI configuration */
191 union {
192 struct pci_config config;
193 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
194 };
195
Rusty Russell93153072015-02-11 15:15:11 +1030196 /* Features we offer, and those accepted. */
197 u64 features, features_accepted;
198
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030199 /* Device-specific config hangs off the end of this. */
200 struct virtio_pci_mmio *mmio;
201
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030202 /* PCI MMIO resources (all in BAR0) */
203 size_t mmio_size;
204 u32 mmio_addr;
205
Rusty Russell8ca47e02007-07-19 01:49:29 -0700206 /* Device-specific data. */
207 void *priv;
208};
209
Rusty Russell17cbca22007-10-22 11:24:22 +1000210/* The virtqueue structure describes a queue attached to a device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600211struct virtqueue {
Rusty Russell17cbca22007-10-22 11:24:22 +1000212 struct virtqueue *next;
213
214 /* Which device owns me. */
215 struct device *dev;
216
217 /* The configuration for this queue. */
218 struct lguest_vqconfig config;
219
220 /* The actual ring of buffers. */
221 struct vring vring;
222
Rusty Russell93153072015-02-11 15:15:11 +1030223 /* The information about this virtqueue (we only use queue_size on) */
224 struct virtio_pci_common_cfg pci_config;
225
Rusty Russell17cbca22007-10-22 11:24:22 +1000226 /* Last available index we saw. */
227 u16 last_avail_idx;
228
Rusty Russell95c517c2009-06-12 22:27:11 -0600229 /* How many are used since we sent last irq? */
230 unsigned int pending_used;
231
Rusty Russell659a0e62009-06-12 22:27:10 -0600232 /* Eventfd where Guest notifications arrive. */
233 int eventfd;
Rusty Russell20887612008-05-30 15:09:46 -0500234
Rusty Russell659a0e62009-06-12 22:27:10 -0600235 /* Function for the thread which is servicing this virtqueue. */
236 void (*service)(struct virtqueue *vq);
237 pid_t thread;
Rusty Russell17cbca22007-10-22 11:24:22 +1000238};
239
Balaji Raoec04b132007-12-28 14:26:24 +0530240/* Remember the arguments to the program so we can "reboot" */
241static char **main_args;
242
Rusty Russell659a0e62009-06-12 22:27:10 -0600243/* The original tty settings to restore on exit. */
244static struct termios orig_term;
245
Rusty Russell2e04ef72009-07-30 16:03:45 -0600246/*
247 * We have to be careful with barriers: our devices are all run in separate
Rusty Russellf7027c62009-06-12 22:27:00 -0600248 * threads and so we need to make sure that changes visible to the Guest happen
Rusty Russell2e04ef72009-07-30 16:03:45 -0600249 * in precise order.
250 */
Rusty Russellf7027c62009-06-12 22:27:00 -0600251#define wmb() __asm__ __volatile__("" : : : "memory")
Rusty Russell0d69a652013-07-02 15:35:14 +0930252#define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
253#define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
Rusty Russell17cbca22007-10-22 11:24:22 +1000254
Rusty Russellb5111792008-07-29 09:58:34 -0500255/* Wrapper for the last available index. Makes it easier to change. */
256#define lg_last_avail(vq) ((vq)->last_avail_idx)
257
Rusty Russell2e04ef72009-07-30 16:03:45 -0600258/*
259 * The virtio configuration space is defined to be little-endian. x86 is
260 * little-endian too, but it's nice to be explicit so we have these helpers.
261 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000262#define cpu_to_le16(v16) (v16)
263#define cpu_to_le32(v32) (v32)
264#define cpu_to_le64(v64) (v64)
265#define le16_to_cpu(v16) (v16)
266#define le32_to_cpu(v32) (v32)
Rusty Russella586d4f2008-02-04 23:49:56 -0500267#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000268
Rusty Russell28fd6d72008-07-29 09:58:33 -0500269/* Is this iovec empty? */
270static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
271{
272 unsigned int i;
273
274 for (i = 0; i < num_iov; i++)
275 if (iov[i].iov_len)
276 return false;
277 return true;
278}
279
280/* Take len bytes from the front of this iovec. */
Rusty Russellc0316a92012-10-16 23:56:13 +1030281static void iov_consume(struct iovec iov[], unsigned num_iov,
282 void *dest, unsigned len)
Rusty Russell28fd6d72008-07-29 09:58:33 -0500283{
284 unsigned int i;
285
286 for (i = 0; i < num_iov; i++) {
287 unsigned int used;
288
289 used = iov[i].iov_len < len ? iov[i].iov_len : len;
Rusty Russellc0316a92012-10-16 23:56:13 +1030290 if (dest) {
291 memcpy(dest, iov[i].iov_base, used);
292 dest += used;
293 }
Rusty Russell28fd6d72008-07-29 09:58:33 -0500294 iov[i].iov_base += used;
295 iov[i].iov_len -= used;
296 len -= used;
297 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030298 if (len != 0)
299 errx(1, "iovec too short!");
Rusty Russell28fd6d72008-07-29 09:58:33 -0500300}
301
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500302/* The device virtqueue descriptors are followed by feature bitmasks. */
303static u8 *get_feature_bits(struct device *dev)
304{
305 return (u8 *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -0600306 + dev->num_vq * sizeof(struct lguest_vqconfig);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500307}
308
Rusty Russell2e04ef72009-07-30 16:03:45 -0600309/*L:100
310 * The Launcher code itself takes us out into userspace, that scary place where
311 * pointers run wild and free! Unfortunately, like most userspace programs,
312 * it's quite boring (which is why everyone likes to hack on the kernel!).
313 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
314 * you through this section. Or, maybe not.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000315 *
316 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
317 * memory and stores it in "guest_base". In other words, Guest physical ==
318 * Launcher virtual with an offset.
319 *
320 * This can be tough to get your head around, but usually it just means that we
Francis Galieguea33f3222010-04-23 00:08:02 +0200321 * use these trivial conversion functions when the Guest gives us its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600322 * "physical" addresses:
323 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000324static void *from_guest_phys(unsigned long addr)
325{
326 return guest_base + addr;
327}
328
329static unsigned long to_guest_phys(const void *addr)
330{
331 return (addr - guest_base);
332}
333
Rusty Russelldde79782007-07-26 10:41:03 -0700334/*L:130
335 * Loading the Kernel.
336 *
337 * We start with couple of simple helper routines. open_or_die() avoids
Rusty Russell2e04ef72009-07-30 16:03:45 -0600338 * error-checking code cluttering the callers:
339 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700340static int open_or_die(const char *name, int flags)
341{
342 int fd = open(name, flags);
343 if (fd < 0)
344 err(1, "Failed to open %s", name);
345 return fd;
346}
347
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000348/* map_zeroed_pages() takes a number of pages. */
349static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700350{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000351 int fd = open_or_die("/dev/zero", O_RDONLY);
352 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700353
Rusty Russell2e04ef72009-07-30 16:03:45 -0600354 /*
355 * We use a private mapping (ie. if we write to the page, it will be
Philip Sanderson5230ff02011-01-20 21:37:28 -0600356 * copied). We allocate an extra two pages PROT_NONE to act as guard
357 * pages against read/write attempts that exceed allocated space.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600358 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600359 addr = mmap(NULL, getpagesize() * (num+2),
360 PROT_NONE, MAP_PRIVATE, fd, 0);
361
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000362 if (addr == MAP_FAILED)
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200363 err(1, "Mmapping %u pages of /dev/zero", num);
Rusty Russella91d74a2009-07-30 16:03:45 -0600364
Philip Sanderson5230ff02011-01-20 21:37:28 -0600365 if (mprotect(addr + getpagesize(), getpagesize() * num,
366 PROT_READ|PROT_WRITE) == -1)
367 err(1, "mprotect rw %u pages failed", num);
368
Rusty Russella91d74a2009-07-30 16:03:45 -0600369 /*
370 * One neat mmap feature is that you can close the fd, and it
371 * stays mapped.
372 */
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100373 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700374
Philip Sanderson5230ff02011-01-20 21:37:28 -0600375 /* Return address after PROT_NONE page */
376 return addr + getpagesize();
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000377}
378
379/* Get some more pages for a device. */
380static void *get_pages(unsigned int num)
381{
382 void *addr = from_guest_phys(guest_limit);
383
384 guest_limit += num * getpagesize();
385 if (guest_limit > guest_max)
386 errx(1, "Not enough memory for devices");
387 return addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700388}
389
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030390/* Get some bytes which won't be mapped into the guest. */
391static unsigned long get_mmio_region(size_t size)
392{
393 unsigned long addr = guest_mmio;
394 size_t i;
395
396 if (!size)
397 return addr;
398
399 /* Size has to be a power of 2 (and multiple of 16) */
400 for (i = 1; i < size; i <<= 1);
401
402 guest_mmio += i;
403
404 return addr;
405}
406
Rusty Russell2e04ef72009-07-30 16:03:45 -0600407/*
408 * This routine is used to load the kernel or initrd. It tries mmap, but if
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700409 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
Rusty Russell2e04ef72009-07-30 16:03:45 -0600410 * it falls back to reading the memory in.
411 */
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700412static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
413{
414 ssize_t r;
415
Rusty Russell2e04ef72009-07-30 16:03:45 -0600416 /*
417 * We map writable even though for some segments are marked read-only.
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700418 * The kernel really wants to be writable: it patches its own
419 * instructions.
420 *
421 * MAP_PRIVATE means that the page won't be copied until a write is
422 * done to it. This allows us to share untouched memory between
Rusty Russell2e04ef72009-07-30 16:03:45 -0600423 * Guests.
424 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600425 if (mmap(addr, len, PROT_READ|PROT_WRITE,
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700426 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
427 return;
428
429 /* pread does a seek and a read in one shot: saves a few lines. */
430 r = pread(fd, addr, len, offset);
431 if (r != len)
432 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
433}
434
Rusty Russell2e04ef72009-07-30 16:03:45 -0600435/*
436 * This routine takes an open vmlinux image, which is in ELF, and maps it into
Rusty Russelldde79782007-07-26 10:41:03 -0700437 * the Guest memory. ELF = Embedded Linking Format, which is the format used
438 * by all modern binaries on Linux including the kernel.
439 *
440 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000441 * address. We use the physical address; the Guest will map itself to the
442 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700443 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600444 * We return the starting address.
445 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000446static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700447{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700448 Elf32_Phdr phdr[ehdr->e_phnum];
449 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700450
Rusty Russell2e04ef72009-07-30 16:03:45 -0600451 /*
452 * Sanity checks on the main ELF header: an x86 executable with a
453 * reasonable number of correctly-sized program headers.
454 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700455 if (ehdr->e_type != ET_EXEC
456 || ehdr->e_machine != EM_386
457 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
458 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
459 errx(1, "Malformed elf header");
460
Rusty Russell2e04ef72009-07-30 16:03:45 -0600461 /*
462 * An ELF executable contains an ELF header and a number of "program"
Rusty Russelldde79782007-07-26 10:41:03 -0700463 * headers which indicate which parts ("segments") of the program to
Rusty Russell2e04ef72009-07-30 16:03:45 -0600464 * load where.
465 */
Rusty Russelldde79782007-07-26 10:41:03 -0700466
467 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700468 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
469 err(1, "Seeking to program headers");
470 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
471 err(1, "Reading program headers");
472
Rusty Russell2e04ef72009-07-30 16:03:45 -0600473 /*
474 * Try all the headers: there are usually only three. A read-only one,
475 * a read-write one, and a "note" section which we don't load.
476 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700477 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700478 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700479 if (phdr[i].p_type != PT_LOAD)
480 continue;
481
482 verbose("Section %i: size %i addr %p\n",
483 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
484
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700485 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000486 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700487 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700488 }
489
Rusty Russell814a0e52007-10-22 11:29:44 +1000490 /* The entry point is given in the ELF header. */
491 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700492}
493
Rusty Russell2e04ef72009-07-30 16:03:45 -0600494/*L:150
495 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
496 * to jump into it and it will unpack itself. We used to have to perform some
497 * hairy magic because the unpacking code scared me.
Rusty Russelldde79782007-07-26 10:41:03 -0700498 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000499 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
500 * a small patch to jump over the tricky bits in the Guest, so now we just read
Rusty Russell2e04ef72009-07-30 16:03:45 -0600501 * the funky header so we know where in the file to load, and away we go!
502 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000503static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700504{
Rusty Russell43d33b22007-10-22 11:29:57 +1000505 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000506 int r;
507 /* Modern bzImages get loaded at 1M. */
508 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700509
Rusty Russell2e04ef72009-07-30 16:03:45 -0600510 /*
511 * Go back to the start of the file and read the header. It should be
Paul Bolle395cf962011-08-15 02:02:26 +0200512 * a Linux boot header (see Documentation/x86/boot.txt)
Rusty Russell2e04ef72009-07-30 16:03:45 -0600513 */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000514 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000515 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000516
Rusty Russell43d33b22007-10-22 11:29:57 +1000517 /* Inside the setup_hdr, we expect the magic "HdrS" */
518 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000519 errx(1, "This doesn't look like a bzImage to me");
520
Rusty Russell43d33b22007-10-22 11:29:57 +1000521 /* Skip over the extra sectors of the header. */
522 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000523
524 /* Now read everything into memory. in nice big chunks. */
525 while ((r = read(fd, p, 65536)) > 0)
526 p += r;
527
Rusty Russell43d33b22007-10-22 11:29:57 +1000528 /* Finally, code32_start tells us where to enter the kernel. */
529 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700530}
531
Rusty Russell2e04ef72009-07-30 16:03:45 -0600532/*L:140
533 * Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000534 * come wrapped up in the self-decompressing "bzImage" format. With a little
Rusty Russell2e04ef72009-07-30 16:03:45 -0600535 * work, we can load those, too.
536 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000537static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700538{
539 Elf32_Ehdr hdr;
540
Rusty Russelldde79782007-07-26 10:41:03 -0700541 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700542 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
543 err(1, "Reading kernel");
544
Rusty Russelldde79782007-07-26 10:41:03 -0700545 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700546 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000547 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700548
Rusty Russella6bd8e12008-03-28 11:05:53 -0500549 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000550 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700551}
552
Rusty Russell2e04ef72009-07-30 16:03:45 -0600553/*
554 * This is a trivial little helper to align pages. Andi Kleen hated it because
Rusty Russelldde79782007-07-26 10:41:03 -0700555 * it calls getpagesize() twice: "it's dumb code."
556 *
557 * Kernel guys get really het up about optimization, even when it's not
Rusty Russell2e04ef72009-07-30 16:03:45 -0600558 * necessary. I leave this code as a reaction against that.
559 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700560static inline unsigned long page_align(unsigned long addr)
561{
Rusty Russelldde79782007-07-26 10:41:03 -0700562 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700563 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
564}
565
Rusty Russell2e04ef72009-07-30 16:03:45 -0600566/*L:180
567 * An "initial ram disk" is a disk image loaded into memory along with the
568 * kernel which the kernel can use to boot from without needing any drivers.
569 * Most distributions now use this as standard: the initrd contains the code to
570 * load the appropriate driver modules for the current machine.
Rusty Russelldde79782007-07-26 10:41:03 -0700571 *
572 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600573 * kernels. He sent me this (and tells me when I break it).
574 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700575static unsigned long load_initrd(const char *name, unsigned long mem)
576{
577 int ifd;
578 struct stat st;
579 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700580
581 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700582 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700583 if (fstat(ifd, &st) < 0)
584 err(1, "fstat() on initrd '%s'", name);
585
Rusty Russell2e04ef72009-07-30 16:03:45 -0600586 /*
587 * We map the initrd at the top of memory, but mmap wants it to be
588 * page-aligned, so we round the size up for that.
589 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700590 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000591 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600592 /*
593 * Once a file is mapped, you can close the file descriptor. It's a
594 * little odd, but quite useful.
595 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700596 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700597 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700598
599 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700600 return len;
601}
Rusty Russelle1e72962007-10-25 15:02:50 +1000602/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700603
Rusty Russell2e04ef72009-07-30 16:03:45 -0600604/*
605 * Simple routine to roll all the commandline arguments together with spaces
606 * between them.
607 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700608static void concat(char *dst, char *args[])
609{
610 unsigned int i, len = 0;
611
612 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100613 if (i) {
614 strcat(dst+len, " ");
615 len++;
616 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700617 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100618 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700619 }
620 /* In case it's empty. */
621 dst[len] = '\0';
622}
623
Rusty Russell2e04ef72009-07-30 16:03:45 -0600624/*L:185
625 * This is where we actually tell the kernel to initialize the Guest. We
Rusty Russelle1e72962007-10-25 15:02:50 +1000626 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300627 * the base of Guest "physical" memory, the top physical page to allow and the
Rusty Russell2e04ef72009-07-30 16:03:45 -0600628 * entry point for the Guest.
629 */
Rusty Russell56739c802009-06-12 22:26:59 -0600630static void tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700631{
Jes Sorensen511801d2007-10-22 11:03:31 +1000632 unsigned long args[] = { LHREQ_INITIALIZE,
633 (unsigned long)guest_base,
Rusty Russell7313d522015-02-11 15:15:10 +1030634 guest_limit / getpagesize(), start,
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030635 (guest_mmio+getpagesize()-1) / getpagesize() };
636 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
637 guest_base, guest_base + guest_limit,
638 guest_limit, guest_mmio);
Rusty Russell56739c802009-06-12 22:26:59 -0600639 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
640 if (write(lguest_fd, args, sizeof(args)) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700641 err(1, "Writing to /dev/lguest");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700642}
Rusty Russelldde79782007-07-26 10:41:03 -0700643/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700644
Rusty Russella91d74a2009-07-30 16:03:45 -0600645/*L:200
Rusty Russelldde79782007-07-26 10:41:03 -0700646 * Device Handling.
647 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000648 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700649 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000650 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700651 * if something funny is going on:
652 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700653static void *_check_pointer(unsigned long addr, unsigned int size,
654 unsigned int line)
655{
Rusty Russell2e04ef72009-07-30 16:03:45 -0600656 /*
Philip Sanderson5230ff02011-01-20 21:37:28 -0600657 * Check if the requested address and size exceeds the allocated memory,
658 * or addr + size wraps around.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600659 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600660 if ((addr + size) > guest_limit || (addr + size) < addr)
Rusty Russell17cbca22007-10-22 11:24:22 +1000661 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600662 /*
663 * We return a pointer for the caller's convenience, now we know it's
664 * safe to use.
665 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000666 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700667}
Rusty Russelldde79782007-07-26 10:41:03 -0700668/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700669#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
670
Rusty Russell2e04ef72009-07-30 16:03:45 -0600671/*
672 * Each buffer in the virtqueues is actually a chain of descriptors. This
Rusty Russelle1e72962007-10-25 15:02:50 +1000673 * function returns the next descriptor in the chain, or vq->vring.num if we're
Rusty Russell2e04ef72009-07-30 16:03:45 -0600674 * at the end.
675 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100676static unsigned next_desc(struct vring_desc *desc,
677 unsigned int i, unsigned int max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000678{
679 unsigned int next;
680
681 /* If this descriptor says it doesn't chain, we're done. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100682 if (!(desc[i].flags & VRING_DESC_F_NEXT))
683 return max;
Rusty Russell17cbca22007-10-22 11:24:22 +1000684
685 /* Check they're not leading us off end of descriptors. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100686 next = desc[i].next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000687 /* Make sure compiler knows to grab that: we don't want it changing! */
688 wmb();
689
Mark McLoughlind1f01322009-05-11 18:11:46 +0100690 if (next >= max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000691 errx(1, "Desc next is %u", next);
692
693 return next;
694}
695
Rusty Russella91d74a2009-07-30 16:03:45 -0600696/*
697 * This actually sends the interrupt for this virtqueue, if we've used a
698 * buffer.
699 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600700static void trigger_irq(struct virtqueue *vq)
701{
702 unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
703
Rusty Russell95c517c2009-06-12 22:27:11 -0600704 /* Don't inform them if nothing used. */
705 if (!vq->pending_used)
706 return;
707 vq->pending_used = 0;
708
Rusty Russellca60a422009-09-23 22:26:47 -0600709 /* If they don't want an interrupt, don't send one... */
710 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
Rusty Russell990c91f2011-05-30 11:14:12 -0600711 return;
Rusty Russellca60a422009-09-23 22:26:47 -0600712 }
Rusty Russell38bc2b82009-06-12 22:27:11 -0600713
Rusty Russell93153072015-02-11 15:15:11 +1030714 /* For a PCI device, set isr to 1 (queue interrupt pending) */
715 if (vq->dev->mmio)
716 vq->dev->mmio->isr = 0x1;
717
Rusty Russell38bc2b82009-06-12 22:27:11 -0600718 /* Send the Guest an interrupt tell them we used something up. */
719 if (write(lguest_fd, buf, sizeof(buf)) != 0)
720 err(1, "Triggering irq %i", vq->config.irq);
721}
722
Rusty Russell2e04ef72009-07-30 16:03:45 -0600723/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600724 * This looks in the virtqueue for the first available buffer, and converts
Rusty Russell17cbca22007-10-22 11:24:22 +1000725 * it to an iovec for convenient access. Since descriptors consist of some
726 * number of output then some number of input descriptors, it's actually two
727 * iovecs, but we pack them into one and note how many of each there were.
728 *
Rusty Russella91d74a2009-07-30 16:03:45 -0600729 * This function waits if necessary, and returns the descriptor number found.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600730 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600731static unsigned wait_for_vq_desc(struct virtqueue *vq,
732 struct iovec iov[],
733 unsigned int *out_num, unsigned int *in_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000734{
Mark McLoughlind1f01322009-05-11 18:11:46 +0100735 unsigned int i, head, max;
736 struct vring_desc *desc;
Rusty Russell659a0e62009-06-12 22:27:10 -0600737 u16 last_avail = lg_last_avail(vq);
738
Rusty Russella91d74a2009-07-30 16:03:45 -0600739 /* There's nothing available? */
Rusty Russell659a0e62009-06-12 22:27:10 -0600740 while (last_avail == vq->vring.avail->idx) {
741 u64 event;
742
Rusty Russella91d74a2009-07-30 16:03:45 -0600743 /*
744 * Since we're about to sleep, now is a good time to tell the
745 * Guest about what we've used up to now.
746 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600747 trigger_irq(vq);
748
Rusty Russellb60da132009-06-12 22:27:12 -0600749 /* OK, now we need to know about added descriptors. */
750 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
751
Rusty Russell2e04ef72009-07-30 16:03:45 -0600752 /*
753 * They could have slipped one in as we were doing that: make
754 * sure it's written, then check again.
755 */
Rusty Russellb60da132009-06-12 22:27:12 -0600756 mb();
757 if (last_avail != vq->vring.avail->idx) {
758 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
759 break;
760 }
761
Rusty Russell659a0e62009-06-12 22:27:10 -0600762 /* Nothing new? Wait for eventfd to tell us they refilled. */
763 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
764 errx(1, "Event read failed?");
Rusty Russellb60da132009-06-12 22:27:12 -0600765
766 /* We don't need to be notified again. */
767 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russell659a0e62009-06-12 22:27:10 -0600768 }
Rusty Russell17cbca22007-10-22 11:24:22 +1000769
770 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500771 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000772 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500773 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000774
Rusty Russell8fd9a632013-07-02 15:35:13 +0930775 /*
776 * Make sure we read the descriptor number *after* we read the ring
777 * update; don't let the cpu or compiler change the order.
778 */
779 rmb();
780
Rusty Russell2e04ef72009-07-30 16:03:45 -0600781 /*
782 * Grab the next descriptor number they're advertising, and increment
783 * the index we've seen.
784 */
Rusty Russellb5111792008-07-29 09:58:34 -0500785 head = vq->vring.avail->ring[last_avail % vq->vring.num];
786 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000787
788 /* If their number is silly, that's a fatal mistake. */
789 if (head >= vq->vring.num)
790 errx(1, "Guest says index %u is available", head);
791
792 /* When we start there are none of either input nor output. */
793 *out_num = *in_num = 0;
794
Mark McLoughlind1f01322009-05-11 18:11:46 +0100795 max = vq->vring.num;
796 desc = vq->vring.desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000797 i = head;
Mark McLoughlind1f01322009-05-11 18:11:46 +0100798
Rusty Russell2e04ef72009-07-30 16:03:45 -0600799 /*
Rusty Russell8fd9a632013-07-02 15:35:13 +0930800 * We have to read the descriptor after we read the descriptor number,
801 * but there's a data dependency there so the CPU shouldn't reorder
802 * that: no rmb() required.
803 */
804
805 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -0600806 * If this is an indirect entry, then this buffer contains a descriptor
807 * table which we handle as if it's any normal descriptor chain.
808 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100809 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
810 if (desc[i].len % sizeof(struct vring_desc))
811 errx(1, "Invalid size for indirect buffer table");
812
813 max = desc[i].len / sizeof(struct vring_desc);
814 desc = check_pointer(desc[i].addr, desc[i].len);
815 i = 0;
816 }
817
Rusty Russell17cbca22007-10-22 11:24:22 +1000818 do {
819 /* Grab the first descriptor, and check it's OK. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100820 iov[*out_num + *in_num].iov_len = desc[i].len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000821 iov[*out_num + *in_num].iov_base
Mark McLoughlind1f01322009-05-11 18:11:46 +0100822 = check_pointer(desc[i].addr, desc[i].len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000823 /* If this is an input descriptor, increment that count. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100824 if (desc[i].flags & VRING_DESC_F_WRITE)
Rusty Russell17cbca22007-10-22 11:24:22 +1000825 (*in_num)++;
826 else {
Rusty Russell2e04ef72009-07-30 16:03:45 -0600827 /*
828 * If it's an output descriptor, they're all supposed
829 * to come before any input descriptors.
830 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000831 if (*in_num)
832 errx(1, "Descriptor has out after in");
833 (*out_num)++;
834 }
835
836 /* If we've got too many, that implies a descriptor loop. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100837 if (*out_num + *in_num > max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000838 errx(1, "Looped descriptor");
Mark McLoughlind1f01322009-05-11 18:11:46 +0100839 } while ((i = next_desc(desc, i, max)) != max);
Rusty Russell17cbca22007-10-22 11:24:22 +1000840
841 return head;
842}
843
Rusty Russell2e04ef72009-07-30 16:03:45 -0600844/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600845 * After we've used one of their buffers, we tell the Guest about it. Sometime
846 * later we'll want to send them an interrupt using trigger_irq(); note that
847 * wait_for_vq_desc() does that for us if it has to wait.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600848 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000849static void add_used(struct virtqueue *vq, unsigned int head, int len)
850{
851 struct vring_used_elem *used;
852
Rusty Russell2e04ef72009-07-30 16:03:45 -0600853 /*
854 * The virtqueue contains a ring of used buffers. Get a pointer to the
855 * next entry in that used ring.
856 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000857 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
858 used->id = head;
859 used->len = len;
860 /* Make sure buffer is written before we update index. */
861 wmb();
862 vq->vring.used->idx++;
Rusty Russell95c517c2009-06-12 22:27:11 -0600863 vq->pending_used++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000864}
865
Rusty Russell17cbca22007-10-22 11:24:22 +1000866/* And here's the combo meal deal. Supersize me! */
Rusty Russell56739c802009-06-12 22:26:59 -0600867static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
Rusty Russell17cbca22007-10-22 11:24:22 +1000868{
869 add_used(vq, head, len);
Rusty Russell56739c802009-06-12 22:26:59 -0600870 trigger_irq(vq);
Rusty Russell17cbca22007-10-22 11:24:22 +1000871}
872
Rusty Russelle1e72962007-10-25 15:02:50 +1000873/*
874 * The Console
875 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600876 * We associate some data with the console for our exit hack.
877 */
Rusty Russell1842f232009-07-30 16:03:46 -0600878struct console_abort {
Rusty Russelldde79782007-07-26 10:41:03 -0700879 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700880 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700881 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700882 struct timeval start;
883};
884
Rusty Russelldde79782007-07-26 10:41:03 -0700885/* This is the routine which handles console input (ie. stdin). */
Rusty Russell659a0e62009-06-12 22:27:10 -0600886static void console_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700887{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700888 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000889 unsigned int head, in_num, out_num;
Rusty Russell659a0e62009-06-12 22:27:10 -0600890 struct console_abort *abort = vq->dev->priv;
891 struct iovec iov[vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700892
Rusty Russella91d74a2009-07-30 16:03:45 -0600893 /* Make sure there's a descriptor available. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600894 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000895 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000896 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700897
Rusty Russella91d74a2009-07-30 16:03:45 -0600898 /* Read into it. This is where we usually wait. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600899 len = readv(STDIN_FILENO, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700900 if (len <= 0) {
Rusty Russell659a0e62009-06-12 22:27:10 -0600901 /* Ran out of input? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700902 warnx("Failed to get console input, ignoring console.");
Rusty Russell2e04ef72009-07-30 16:03:45 -0600903 /*
904 * For simplicity, dying threads kill the whole Launcher. So
905 * just nap here.
906 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600907 for (;;)
908 pause();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700909 }
910
Rusty Russella91d74a2009-07-30 16:03:45 -0600911 /* Tell the Guest we used a buffer. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600912 add_used_and_trigger(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700913
Rusty Russell2e04ef72009-07-30 16:03:45 -0600914 /*
915 * Three ^C within one second? Exit.
Rusty Russelldde79782007-07-26 10:41:03 -0700916 *
Rusty Russell659a0e62009-06-12 22:27:10 -0600917 * This is such a hack, but works surprisingly well. Each ^C has to
918 * be in a buffer by itself, so they can't be too fast. But we check
919 * that we get three within about a second, so they can't be too
Rusty Russell2e04ef72009-07-30 16:03:45 -0600920 * slow.
921 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600922 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700923 abort->count = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -0600924 return;
925 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700926
Rusty Russell659a0e62009-06-12 22:27:10 -0600927 abort->count++;
928 if (abort->count == 1)
929 gettimeofday(&abort->start, NULL);
930 else if (abort->count == 3) {
931 struct timeval now;
932 gettimeofday(&now, NULL);
933 /* Kill all Launcher processes with SIGINT, like normal ^C */
934 if (now.tv_sec <= abort->start.tv_sec+1)
935 kill(0, SIGINT);
936 abort->count = 0;
937 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700938}
939
Rusty Russell659a0e62009-06-12 22:27:10 -0600940/* This is the routine which handles console output (ie. stdout). */
941static void console_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700942{
Rusty Russell17cbca22007-10-22 11:24:22 +1000943 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000944 struct iovec iov[vq->vring.num];
945
Rusty Russella91d74a2009-07-30 16:03:45 -0600946 /* We usually wait in here, for the Guest to give us something. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600947 head = wait_for_vq_desc(vq, iov, &out, &in);
948 if (in)
949 errx(1, "Input buffers in console output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600950
951 /* writev can return a partial write, so we loop here. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600952 while (!iov_empty(iov, out)) {
953 int len = writev(STDOUT_FILENO, iov, out);
Sakari Ailuse0377e22011-06-26 19:36:46 +0300954 if (len <= 0) {
955 warn("Write to stdout gave %i (%d)", len, errno);
956 break;
957 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030958 iov_consume(iov, out, NULL, len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000959 }
Rusty Russella91d74a2009-07-30 16:03:45 -0600960
961 /*
962 * We're finished with that buffer: if we're going to sleep,
963 * wait_for_vq_desc() will prod the Guest with an interrupt.
964 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600965 add_used(vq, head, 0);
Rusty Russella1618832008-07-29 09:58:35 -0500966}
967
Rusty Russelle1e72962007-10-25 15:02:50 +1000968/*
969 * The Network
970 *
971 * Handling output for network is also simple: we get all the output buffers
Rusty Russell659a0e62009-06-12 22:27:10 -0600972 * and write them to /dev/net/tun.
Rusty Russella6bd8e12008-03-28 11:05:53 -0500973 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600974struct net_info {
975 int tunfd;
976};
977
978static void net_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700979{
Rusty Russell659a0e62009-06-12 22:27:10 -0600980 struct net_info *net_info = vq->dev->priv;
981 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000982 struct iovec iov[vq->vring.num];
983
Rusty Russella91d74a2009-07-30 16:03:45 -0600984 /* We usually wait in here for the Guest to give us a packet. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600985 head = wait_for_vq_desc(vq, iov, &out, &in);
986 if (in)
987 errx(1, "Input buffers in net output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600988 /*
989 * Send the whole thing through to /dev/net/tun. It expects the exact
990 * same format: what a coincidence!
991 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600992 if (writev(net_info->tunfd, iov, out) < 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +0300993 warnx("Write to tun failed (%d)?", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -0600994
995 /*
996 * Done with that one; wait_for_vq_desc() will send the interrupt if
997 * all packets are processed.
998 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600999 add_used(vq, head, 0);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001000}
1001
Rusty Russella91d74a2009-07-30 16:03:45 -06001002/*
1003 * Handling network input is a bit trickier, because I've tried to optimize it.
1004 *
1005 * First we have a helper routine which tells is if from this file descriptor
1006 * (ie. the /dev/net/tun device) will block:
1007 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001008static bool will_block(int fd)
1009{
1010 fd_set fdset;
1011 struct timeval zero = { 0, 0 };
1012 FD_ZERO(&fdset);
1013 FD_SET(fd, &fdset);
1014 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
1015}
1016
Rusty Russella91d74a2009-07-30 16:03:45 -06001017/*
1018 * This handles packets coming in from the tun device to our Guest. Like all
1019 * service routines, it gets called again as soon as it returns, so you don't
1020 * see a while(1) loop here.
1021 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001022static void net_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001023{
Rusty Russell8ca47e02007-07-19 01:49:29 -07001024 int len;
Rusty Russell659a0e62009-06-12 22:27:10 -06001025 unsigned int head, out, in;
1026 struct iovec iov[vq->vring.num];
1027 struct net_info *net_info = vq->dev->priv;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001028
Rusty Russella91d74a2009-07-30 16:03:45 -06001029 /*
1030 * Get a descriptor to write an incoming packet into. This will also
1031 * send an interrupt if they're out of descriptors.
1032 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001033 head = wait_for_vq_desc(vq, iov, &out, &in);
1034 if (out)
1035 errx(1, "Output buffers in net input queue?");
Rusty Russell4a8962e2009-06-12 22:27:12 -06001036
Rusty Russella91d74a2009-07-30 16:03:45 -06001037 /*
1038 * If it looks like we'll block reading from the tun device, send them
1039 * an interrupt.
1040 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001041 if (vq->pending_used && will_block(net_info->tunfd))
1042 trigger_irq(vq);
1043
Rusty Russella91d74a2009-07-30 16:03:45 -06001044 /*
1045 * Read in the packet. This is where we normally wait (when there's no
1046 * incoming network traffic).
1047 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001048 len = readv(net_info->tunfd, iov, in);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001049 if (len <= 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +03001050 warn("Failed to read from tun (%d).", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -06001051
1052 /*
1053 * Mark that packet buffer as used, but don't interrupt here. We want
1054 * to wait until we've done as much work as we can.
1055 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001056 add_used(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001057}
Rusty Russella91d74a2009-07-30 16:03:45 -06001058/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001059
Rusty Russella91d74a2009-07-30 16:03:45 -06001060/* This is the helper to create threads: run the service routine in a loop. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001061static int do_thread(void *_vq)
Rusty Russell56ae43d2007-10-22 11:24:23 +10001062{
Rusty Russell659a0e62009-06-12 22:27:10 -06001063 struct virtqueue *vq = _vq;
1064
1065 for (;;)
1066 vq->service(vq);
1067 return 0;
Rusty Russell56ae43d2007-10-22 11:24:23 +10001068}
1069
Rusty Russell2e04ef72009-07-30 16:03:45 -06001070/*
1071 * When a child dies, we kill our entire process group with SIGTERM. This
1072 * also has the side effect that the shell restores the console for us!
1073 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001074static void kill_launcher(int signal)
Rusty Russell5dae7852008-07-29 09:58:35 -05001075{
Rusty Russell659a0e62009-06-12 22:27:10 -06001076 kill(0, SIGTERM);
1077}
1078
1079static void reset_device(struct device *dev)
1080{
1081 struct virtqueue *vq;
1082
1083 verbose("Resetting device %s\n", dev->name);
1084
1085 /* Clear any features they've acked. */
1086 memset(get_feature_bits(dev) + dev->feature_len, 0, dev->feature_len);
1087
1088 /* We're going to be explicitly killing threads, so ignore them. */
1089 signal(SIGCHLD, SIG_IGN);
1090
1091 /* Zero out the virtqueues, get rid of their threads */
1092 for (vq = dev->vq; vq; vq = vq->next) {
1093 if (vq->thread != (pid_t)-1) {
1094 kill(vq->thread, SIGTERM);
1095 waitpid(vq->thread, NULL, 0);
1096 vq->thread = (pid_t)-1;
1097 }
1098 memset(vq->vring.desc, 0,
1099 vring_size(vq->config.num, LGUEST_VRING_ALIGN));
1100 lg_last_avail(vq) = 0;
1101 }
1102 dev->running = false;
1103
1104 /* Now we care if threads die. */
1105 signal(SIGCHLD, (void *)kill_launcher);
1106}
1107
Rusty Russella91d74a2009-07-30 16:03:45 -06001108/*L:216
1109 * This actually creates the thread which services the virtqueue for a device.
1110 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001111static void create_thread(struct virtqueue *vq)
1112{
Rusty Russell2e04ef72009-07-30 16:03:45 -06001113 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06001114 * Create stack for thread. Since the stack grows upwards, we point
1115 * the stack pointer to the end of this region.
Rusty Russell2e04ef72009-07-30 16:03:45 -06001116 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001117 char *stack = malloc(32768);
1118 unsigned long args[] = { LHREQ_EVENTFD,
1119 vq->config.pfn*getpagesize(), 0 };
1120
1121 /* Create a zero-initialized eventfd. */
1122 vq->eventfd = eventfd(0, 0);
1123 if (vq->eventfd < 0)
1124 err(1, "Creating eventfd");
1125 args[2] = vq->eventfd;
1126
Rusty Russella91d74a2009-07-30 16:03:45 -06001127 /*
1128 * Attach an eventfd to this virtqueue: it will go off when the Guest
1129 * does an LHCALL_NOTIFY for this vq.
1130 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001131 if (write(lguest_fd, &args, sizeof(args)) != 0)
1132 err(1, "Attaching eventfd");
1133
Rusty Russella91d74a2009-07-30 16:03:45 -06001134 /*
1135 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1136 * we get a signal if it dies.
1137 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001138 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1139 if (vq->thread == (pid_t)-1)
1140 err(1, "Creating clone");
Rusty Russella91d74a2009-07-30 16:03:45 -06001141
1142 /* We close our local copy now the child has it. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001143 close(vq->eventfd);
1144}
1145
1146static void start_device(struct device *dev)
1147{
1148 unsigned int i;
1149 struct virtqueue *vq;
1150
1151 verbose("Device %s OK: offered", dev->name);
1152 for (i = 0; i < dev->feature_len; i++)
1153 verbose(" %02x", get_feature_bits(dev)[i]);
1154 verbose(", accepted");
1155 for (i = 0; i < dev->feature_len; i++)
1156 verbose(" %02x", get_feature_bits(dev)
1157 [dev->feature_len+i]);
1158
1159 for (vq = dev->vq; vq; vq = vq->next) {
1160 if (vq->service)
1161 create_thread(vq);
1162 }
1163 dev->running = true;
1164}
1165
1166static void cleanup_devices(void)
1167{
1168 struct device *dev;
1169
1170 for (dev = devices.dev; dev; dev = dev->next)
1171 reset_device(dev);
1172
1173 /* If we saved off the original terminal settings, restore them now. */
1174 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1175 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
Rusty Russell5dae7852008-07-29 09:58:35 -05001176}
1177
Rusty Russella007a752008-05-02 21:50:53 -05001178/* When the Guest tells us they updated the status field, we handle it. */
1179static void update_device_status(struct device *dev)
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001180{
Rusty Russell659a0e62009-06-12 22:27:10 -06001181 /* A zero status is a reset, otherwise it's a set of flags. */
1182 if (dev->desc->status == 0)
1183 reset_device(dev);
1184 else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
Rusty Russella007a752008-05-02 21:50:53 -05001185 warnx("Device %s configuration FAILED", dev->name);
Rusty Russell659a0e62009-06-12 22:27:10 -06001186 if (dev->running)
1187 reset_device(dev);
Rusty Russell3c3ed482011-07-22 14:39:49 +09301188 } else {
1189 if (dev->running)
1190 err(1, "Device %s features finalized twice", dev->name);
1191 start_device(dev);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001192 }
1193}
1194
Rusty Russella91d74a2009-07-30 16:03:45 -06001195/*L:215
1196 * This is the generic routine we call when the Guest uses LHCALL_NOTIFY. In
1197 * particular, it's used to notify us of device status changes during boot.
1198 */
Rusty Russell56739c802009-06-12 22:26:59 -06001199static void handle_output(unsigned long addr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001200{
1201 struct device *i;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001202
Rusty Russell659a0e62009-06-12 22:27:10 -06001203 /* Check each device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001204 for (i = devices.dev; i; i = i->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001205 struct virtqueue *vq;
1206
Rusty Russella91d74a2009-07-30 16:03:45 -06001207 /*
1208 * Notifications to device descriptors mean they updated the
1209 * device status.
1210 */
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001211 if (from_guest_phys(addr) == i->desc) {
Rusty Russella007a752008-05-02 21:50:53 -05001212 update_device_status(i);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001213 return;
1214 }
1215
Rusty Russell3c3ed482011-07-22 14:39:49 +09301216 /* Devices should not be used before features are finalized. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001217 for (vq = i->vq; vq; vq = vq->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001218 if (addr != vq->config.pfn*getpagesize())
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001219 continue;
Rusty Russell3c3ed482011-07-22 14:39:49 +09301220 errx(1, "Notification on %s before setup!", i->name);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001221 }
1222 }
Rusty Russelldde79782007-07-26 10:41:03 -07001223
Rusty Russell2e04ef72009-07-30 16:03:45 -06001224 /*
1225 * Early console write is done using notify on a nul-terminated string
1226 * in Guest memory. It's also great for hacking debugging messages
1227 * into a Guest.
1228 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001229 if (addr >= guest_limit)
1230 errx(1, "Bad NOTIFY %#lx", addr);
1231
1232 write(STDOUT_FILENO, from_guest_phys(addr),
1233 strnlen(from_guest_phys(addr), guest_limit - addr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001234}
1235
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301236/*L:217
1237 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1238 * code.
1239 */
1240
Rusty Russell8e709462015-02-11 15:15:12 +10301241/* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1242static struct device pci_host_bridge;
1243
1244static void init_pci_host_bridge(void)
1245{
1246 pci_host_bridge.name = "PCI Host Bridge";
1247 pci_host_bridge.config.class = 0x06; /* bridge */
1248 pci_host_bridge.config.subclass = 0; /* host bridge */
1249 devices.pci[0] = &pci_host_bridge;
1250}
1251
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301252/* The IO ports used to read the PCI config space. */
1253#define PCI_CONFIG_ADDR 0xCF8
1254#define PCI_CONFIG_DATA 0xCFC
1255
1256/*
1257 * Not really portable, but does help readability: this is what the Guest
1258 * writes to the PCI_CONFIG_ADDR IO port.
1259 */
1260union pci_config_addr {
1261 struct {
1262 unsigned mbz: 2;
1263 unsigned offset: 6;
1264 unsigned funcnum: 3;
1265 unsigned devnum: 5;
1266 unsigned busnum: 8;
1267 unsigned reserved: 7;
1268 unsigned enabled : 1;
1269 } bits;
1270 u32 val;
1271};
1272
1273/*
1274 * We cache what they wrote to the address port, so we know what they're
1275 * talking about when they access the data port.
1276 */
1277static union pci_config_addr pci_config_addr;
1278
1279static struct device *find_pci_device(unsigned int index)
1280{
1281 return devices.pci[index];
1282}
1283
1284/* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1285static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1286{
1287 assert(off < 4);
1288 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1289 *val = (v >> (off * 8)) & mask;
1290}
1291
1292/* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1293static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1294{
1295 assert(off < 4);
1296 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1297 *dst &= ~(mask << (off * 8));
1298 *dst |= (v & mask) << (off * 8);
1299}
1300
1301/*
1302 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1303 * PCI_CONFIG_ADDR.
1304 */
1305static struct device *dev_and_reg(u32 *reg)
1306{
1307 if (!pci_config_addr.bits.enabled)
1308 return NULL;
1309
1310 if (pci_config_addr.bits.funcnum != 0)
1311 return NULL;
1312
1313 if (pci_config_addr.bits.busnum != 0)
1314 return NULL;
1315
1316 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1317 return NULL;
1318
1319 *reg = pci_config_addr.bits.offset;
1320 return find_pci_device(pci_config_addr.bits.devnum);
1321}
1322
1323/* Is this accessing the PCI config address port?. */
1324static bool is_pci_addr_port(u16 port)
1325{
1326 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1327}
1328
1329static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1330{
1331 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1332 &pci_config_addr.val);
1333 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1334 pci_config_addr.bits.enabled ? "" : " DISABLED",
1335 val, mask,
1336 pci_config_addr.bits.busnum,
1337 pci_config_addr.bits.devnum,
1338 pci_config_addr.bits.funcnum,
1339 pci_config_addr.bits.offset);
1340 return true;
1341}
1342
1343static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1344{
1345 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1346}
1347
1348/* Is this accessing the PCI config data port?. */
1349static bool is_pci_data_port(u16 port)
1350{
1351 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1352}
1353
1354static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1355{
1356 u32 reg, portoff;
1357 struct device *d = dev_and_reg(&reg);
1358
1359 /* Complain if they don't belong to a device. */
1360 if (!d)
1361 return false;
1362
1363 /* They can do 1 byte writes, etc. */
1364 portoff = port - PCI_CONFIG_DATA;
1365
1366 /*
1367 * PCI uses a weird way to determine the BAR size: the OS
1368 * writes all 1's, and sees which ones stick.
1369 */
1370 if (&d->config_words[reg] == &d->config.bar[0]) {
1371 int i;
1372
1373 iowrite(portoff, val, mask, &d->config.bar[0]);
1374 for (i = 0; (1 << i) < d->mmio_size; i++)
1375 d->config.bar[0] &= ~(1 << i);
1376 return true;
1377 } else if ((&d->config_words[reg] > &d->config.bar[0]
1378 && &d->config_words[reg] <= &d->config.bar[6])
1379 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1380 /* Allow writing to any other BAR, or expansion ROM */
1381 iowrite(portoff, val, mask, &d->config_words[reg]);
1382 return true;
1383 /* We let them overide latency timer and cacheline size */
1384 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1385 /* Only let them change the first two fields. */
1386 if (mask == 0xFFFFFFFF)
1387 mask = 0xFFFF;
1388 iowrite(portoff, val, mask, &d->config_words[reg]);
1389 return true;
1390 } else if (&d->config_words[reg] == (void *)&d->config.command
1391 && mask == 0xFFFF) {
1392 /* Ignore command writes. */
1393 return true;
1394 }
1395
1396 /* Complain about other writes. */
1397 return false;
1398}
1399
1400static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1401{
1402 u32 reg;
1403 struct device *d = dev_and_reg(&reg);
1404
1405 if (!d)
1406 return;
1407 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1408}
1409
Rusty Russellc565650b2015-02-11 15:15:10 +10301410/*L:216
1411 * This is where we emulate a handful of Guest instructions. It's ugly
1412 * and we used to do it in the kernel but it grew over time.
1413 */
1414
1415/*
1416 * We use the ptrace syscall's pt_regs struct to talk about registers
1417 * to lguest: these macros convert the names to the offsets.
1418 */
1419#define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1420#define setreg(name, val) \
1421 setreg_off(offsetof(struct user_regs_struct, name), (val))
1422
1423static u32 getreg_off(size_t offset)
1424{
1425 u32 r;
1426 unsigned long args[] = { LHREQ_GETREG, offset };
1427
1428 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1429 err(1, "Getting register %u", offset);
1430 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1431 err(1, "Reading register %u", offset);
1432
1433 return r;
1434}
1435
1436static void setreg_off(size_t offset, u32 val)
1437{
1438 unsigned long args[] = { LHREQ_SETREG, offset, val };
1439
1440 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1441 err(1, "Setting register %u", offset);
1442}
1443
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301444/* Get register by instruction encoding */
1445static u32 getreg_num(unsigned regnum, u32 mask)
1446{
1447 /* 8 bit ops use regnums 4-7 for high parts of word */
1448 if (mask == 0xFF && (regnum & 0x4))
1449 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1450
1451 switch (regnum) {
1452 case 0: return getreg(eax) & mask;
1453 case 1: return getreg(ecx) & mask;
1454 case 2: return getreg(edx) & mask;
1455 case 3: return getreg(ebx) & mask;
1456 case 4: return getreg(esp) & mask;
1457 case 5: return getreg(ebp) & mask;
1458 case 6: return getreg(esi) & mask;
1459 case 7: return getreg(edi) & mask;
1460 }
1461 abort();
1462}
1463
1464/* Set register by instruction encoding */
1465static void setreg_num(unsigned regnum, u32 val, u32 mask)
1466{
1467 /* Don't try to set bits out of range */
1468 assert(~(val & ~mask));
1469
1470 /* 8 bit ops use regnums 4-7 for high parts of word */
1471 if (mask == 0xFF && (regnum & 0x4)) {
1472 /* Construct the 16 bits we want. */
1473 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1474 setreg_num(regnum & 0x3, val, 0xFFFF);
1475 return;
1476 }
1477
1478 switch (regnum) {
1479 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1480 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1481 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1482 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1483 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1484 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1485 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1486 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1487 }
1488 abort();
1489}
1490
1491/* Get bytes of displacement appended to instruction, from r/m encoding */
1492static u32 insn_displacement_len(u8 mod_reg_rm)
1493{
1494 /* Switch on the mod bits */
1495 switch (mod_reg_rm >> 6) {
1496 case 0:
1497 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1498 if ((mod_reg_rm & 0x7) == 0x5)
1499 return 2;
1500 /* Normally, mod == 0 means no literal displacement */
1501 return 0;
1502 case 1:
1503 /* One byte displacement */
1504 return 1;
1505 case 2:
1506 /* Four byte displacement */
1507 return 4;
1508 case 3:
1509 /* Register mode */
1510 return 0;
1511 }
1512 abort();
1513}
1514
Rusty Russellc565650b2015-02-11 15:15:10 +10301515static void emulate_insn(const u8 insn[])
1516{
1517 unsigned long args[] = { LHREQ_TRAP, 13 };
1518 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1519 unsigned int eax, port, mask;
1520 /*
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301521 * Default is to return all-ones on IO port reads, which traditionally
Rusty Russellc565650b2015-02-11 15:15:10 +10301522 * means "there's nothing there".
1523 */
1524 u32 val = 0xFFFFFFFF;
1525
1526 /*
1527 * This must be the Guest kernel trying to do something, not userspace!
1528 * The bottom two bits of the CS segment register are the privilege
1529 * level.
1530 */
1531 if ((getreg(xcs) & 3) != 0x1)
1532 goto no_emulate;
1533
1534 /* Decoding x86 instructions is icky. */
1535
1536 /*
1537 * Around 2.6.33, the kernel started using an emulation for the
1538 * cmpxchg8b instruction in early boot on many configurations. This
1539 * code isn't paravirtualized, and it tries to disable interrupts.
1540 * Ignore it, which will Mostly Work.
1541 */
1542 if (insn[insnlen] == 0xfa) {
1543 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1544 insnlen = 1;
1545 goto skip_insn;
1546 }
1547
1548 /*
1549 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1550 */
1551 if (insn[insnlen] == 0x66) {
1552 small_operand = 1;
1553 /* The instruction is 1 byte so far, read the next byte. */
1554 insnlen = 1;
1555 }
1556
1557 /* If the lower bit isn't set, it's a single byte access */
1558 byte_access = !(insn[insnlen] & 1);
1559
1560 /*
1561 * Now we can ignore the lower bit and decode the 4 opcodes
1562 * we need to emulate.
1563 */
1564 switch (insn[insnlen] & 0xFE) {
1565 case 0xE4: /* in <next byte>,%al */
1566 port = insn[insnlen+1];
1567 insnlen += 2;
1568 in = 1;
1569 break;
1570 case 0xEC: /* in (%dx),%al */
1571 port = getreg(edx) & 0xFFFF;
1572 insnlen += 1;
1573 in = 1;
1574 break;
1575 case 0xE6: /* out %al,<next byte> */
1576 port = insn[insnlen+1];
1577 insnlen += 2;
1578 break;
1579 case 0xEE: /* out %al,(%dx) */
1580 port = getreg(edx) & 0xFFFF;
1581 insnlen += 1;
1582 break;
1583 default:
1584 /* OK, we don't know what this is, can't emulate. */
1585 goto no_emulate;
1586 }
1587
1588 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1589 if (byte_access)
1590 mask = 0xFF;
1591 else if (small_operand)
1592 mask = 0xFFFF;
1593 else
1594 mask = 0xFFFFFFFF;
1595
1596 /*
1597 * If it was an "IN" instruction, they expect the result to be read
1598 * into %eax, so we change %eax.
1599 */
1600 eax = getreg(eax);
1601
1602 if (in) {
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301603 /* This is the PS/2 keyboard status; 1 means ready for output */
1604 if (port == 0x64)
1605 val = 1;
1606 else if (is_pci_addr_port(port))
1607 pci_addr_ioread(port, mask, &val);
1608 else if (is_pci_data_port(port))
1609 pci_data_ioread(port, mask, &val);
1610
Rusty Russellc565650b2015-02-11 15:15:10 +10301611 /* Clear the bits we're about to read */
1612 eax &= ~mask;
1613 /* Copy bits in from val. */
1614 eax |= val & mask;
1615 /* Now update the register. */
1616 setreg(eax, eax);
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301617 } else {
1618 if (is_pci_addr_port(port)) {
1619 if (!pci_addr_iowrite(port, mask, eax))
1620 goto bad_io;
1621 } else if (is_pci_data_port(port)) {
1622 if (!pci_data_iowrite(port, mask, eax))
1623 goto bad_io;
1624 }
1625 /* There are many other ports, eg. CMOS clock, serial
1626 * and parallel ports, so we ignore them all. */
Rusty Russellc565650b2015-02-11 15:15:10 +10301627 }
1628
1629 verbose("IO %s of %x to %u: %#08x\n",
1630 in ? "IN" : "OUT", mask, port, eax);
1631skip_insn:
1632 /* Finally, we've "done" the instruction, so move past it. */
1633 setreg(eip, getreg(eip) + insnlen);
1634 return;
1635
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301636bad_io:
1637 warnx("Attempt to %s port %u (%#x mask)",
1638 in ? "read from" : "write to", port, mask);
1639
Rusty Russellc565650b2015-02-11 15:15:10 +10301640no_emulate:
1641 /* Inject trap into Guest. */
1642 if (write(lguest_fd, args, sizeof(args)) < 0)
1643 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1644}
1645
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301646static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1647{
1648 unsigned int i;
1649
1650 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1651 struct device *d = devices.pci[i];
1652
1653 if (!d)
1654 continue;
1655 if (paddr < d->mmio_addr)
1656 continue;
1657 if (paddr >= d->mmio_addr + d->mmio_size)
1658 continue;
1659 *off = paddr - d->mmio_addr;
1660 return d;
1661 }
1662 return NULL;
1663}
1664
Rusty Russell93153072015-02-11 15:15:11 +10301665/* FIXME: Use vq array. */
1666static struct virtqueue *vq_by_num(struct device *d, u32 num)
1667{
1668 struct virtqueue *vq = d->vq;
1669
1670 while (num-- && vq)
1671 vq = vq->next;
1672
1673 return vq;
1674}
1675
1676static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1677 struct virtqueue *vq)
1678{
1679 vq->pci_config = *cfg;
1680}
1681
1682static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1683 struct virtqueue *vq)
1684{
1685 /* Only restore the per-vq part */
1686 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1687
1688 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1689 sizeof(*cfg) - off);
1690}
1691
1692/*
1693 * When they enable the virtqueue, we check that their setup is valid.
1694 */
1695static void enable_virtqueue(struct device *d, struct virtqueue *vq)
1696{
1697 /*
1698 * Create stack for thread. Since the stack grows upwards, we point
1699 * the stack pointer to the end of this region.
1700 */
1701 char *stack = malloc(32768);
1702
1703 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1704 if (vq->pci_config.queue_desc_hi
1705 || vq->pci_config.queue_avail_hi
1706 || vq->pci_config.queue_used_hi)
1707 errx(1, "%s: invalid 64-bit queue address", d->name);
1708
1709 /* Initialize the virtqueue and check they're all in range. */
1710 vq->vring.num = vq->pci_config.queue_size;
1711 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1712 sizeof(*vq->vring.desc) * vq->vring.num);
1713 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1714 sizeof(*vq->vring.avail)
1715 + (sizeof(vq->vring.avail->ring[0])
1716 * vq->vring.num));
1717 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1718 sizeof(*vq->vring.used)
1719 + (sizeof(vq->vring.used->ring[0])
1720 * vq->vring.num));
1721
1722
1723 /* Create a zero-initialized eventfd. */
1724 vq->eventfd = eventfd(0, 0);
1725 if (vq->eventfd < 0)
1726 err(1, "Creating eventfd");
1727
1728 /*
1729 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1730 * we get a signal if it dies.
1731 */
1732 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1733 if (vq->thread == (pid_t)-1)
1734 err(1, "Creating clone");
1735}
1736
1737static void reset_pci_device(struct device *dev)
1738{
1739 /* FIXME */
1740}
1741
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301742static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1743{
Rusty Russell93153072015-02-11 15:15:11 +10301744 struct virtqueue *vq;
1745
1746 switch (off) {
1747 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1748 if (val == 0)
1749 d->mmio->cfg.device_feature = d->features;
1750 else if (val == 1)
1751 d->mmio->cfg.device_feature = (d->features >> 32);
1752 else
1753 d->mmio->cfg.device_feature = 0;
1754 goto write_through32;
1755 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1756 if (val > 1)
1757 errx(1, "%s: Unexpected driver select %u",
1758 d->name, val);
1759 goto write_through32;
1760 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1761 if (d->mmio->cfg.guest_feature_select == 0) {
1762 d->features_accepted &= ~((u64)0xFFFFFFFF);
1763 d->features_accepted |= val;
1764 } else {
1765 assert(d->mmio->cfg.guest_feature_select == 1);
1766 d->features_accepted &= ((u64)0xFFFFFFFF << 32);
1767 d->features_accepted |= ((u64)val) << 32;
1768 }
1769 if (d->features_accepted & ~d->features)
1770 errx(1, "%s: over-accepted features %#llx of %#llx",
1771 d->name, d->features_accepted, d->features);
1772 goto write_through32;
1773 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1774 verbose("%s: device status -> %#x\n", d->name, val);
1775 if (val == 0)
1776 reset_pci_device(d);
1777 goto write_through8;
1778 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1779 vq = vq_by_num(d, val);
1780 /* Out of range? Return size 0 */
1781 if (!vq) {
1782 d->mmio->cfg.queue_size = 0;
1783 goto write_through16;
1784 }
1785 /* Save registers for old vq, if it was a valid vq */
1786 if (d->mmio->cfg.queue_size)
1787 save_vq_config(&d->mmio->cfg,
1788 vq_by_num(d, d->mmio->cfg.queue_select));
1789 /* Restore the registers for the queue they asked for */
1790 restore_vq_config(&d->mmio->cfg, vq);
1791 goto write_through16;
1792 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
1793 if (val & (val-1))
1794 errx(1, "%s: invalid queue size %u\n", d->name, val);
1795 if (d->mmio->cfg.queue_enable)
1796 errx(1, "%s: changing queue size on live device",
1797 d->name);
1798 goto write_through16;
1799 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
1800 errx(1, "%s: attempt to set MSIX vector to %u",
1801 d->name, val);
1802 case offsetof(struct virtio_pci_mmio, cfg.queue_enable):
1803 if (val != 1)
1804 errx(1, "%s: setting queue_enable to %u", d->name, val);
1805 d->mmio->cfg.queue_enable = val;
1806 save_vq_config(&d->mmio->cfg,
1807 vq_by_num(d, d->mmio->cfg.queue_select));
1808 enable_virtqueue(d, vq_by_num(d, d->mmio->cfg.queue_select));
1809 goto write_through16;
1810 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
1811 errx(1, "%s: attempt to write to queue_notify_off", d->name);
1812 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
1813 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
1814 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
1815 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
1816 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
1817 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
1818 if (d->mmio->cfg.queue_enable)
1819 errx(1, "%s: changing queue on live device",
1820 d->name);
1821 goto write_through32;
1822 case offsetof(struct virtio_pci_mmio, notify):
1823 vq = vq_by_num(d, val);
1824 if (!vq)
1825 errx(1, "Invalid vq notification on %u", val);
1826 /* Notify the process handling this vq by adding 1 to eventfd */
1827 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
1828 goto write_through16;
1829 case offsetof(struct virtio_pci_mmio, isr):
1830 errx(1, "%s: Unexpected write to isr", d->name);
1831 default:
1832 errx(1, "%s: Unexpected write to offset %u", d->name, off);
1833 }
1834
1835write_through32:
1836 if (mask != 0xFFFFFFFF) {
1837 errx(1, "%s: non-32-bit write to offset %u (%#x)",
1838 d->name, off, getreg(eip));
1839 return;
1840 }
1841 memcpy((char *)d->mmio + off, &val, 4);
1842 return;
1843
1844write_through16:
1845 if (mask != 0xFFFF)
1846 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
1847 d->name, mask, off, getreg(eip));
1848 memcpy((char *)d->mmio + off, &val, 2);
1849 return;
1850
1851write_through8:
1852 if (mask != 0xFF)
1853 errx(1, "%s: non-8-bit write to offset %u (%#x)",
1854 d->name, off, getreg(eip));
1855 memcpy((char *)d->mmio + off, &val, 1);
1856 return;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301857}
1858
1859static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
1860{
Rusty Russell93153072015-02-11 15:15:11 +10301861 u8 isr;
1862 u32 val = 0;
1863
1864 switch (off) {
1865 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1866 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
1867 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1868 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1869 goto read_through32;
1870 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
1871 errx(1, "%s: read of msix_config", d->name);
1872 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
1873 goto read_through16;
1874 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1875 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
1876 goto read_through8;
1877 case offsetof(struct virtio_pci_mmio, notify):
1878 goto read_through16;
1879 case offsetof(struct virtio_pci_mmio, isr):
1880 if (mask != 0xFF)
1881 errx(1, "%s: non-8-bit read from offset %u (%#x)",
1882 d->name, off, getreg(eip));
1883 /* Read resets the isr */
1884 isr = d->mmio->isr;
1885 d->mmio->isr = 0;
1886 return isr;
1887 case offsetof(struct virtio_pci_mmio, padding):
1888 errx(1, "%s: read from padding (%#x)",
1889 d->name, getreg(eip));
1890 default:
1891 /* Read from device config space, beware unaligned overflow */
1892 if (off > d->mmio_size - 4)
1893 errx(1, "%s: read past end (%#x)",
1894 d->name, getreg(eip));
1895 if (mask == 0xFFFFFFFF)
1896 goto read_through32;
1897 else if (mask == 0xFFFF)
1898 goto read_through16;
1899 else
1900 goto read_through8;
1901 }
1902
1903read_through32:
1904 if (mask != 0xFFFFFFFF)
1905 errx(1, "%s: non-32-bit read to offset %u (%#x)",
1906 d->name, off, getreg(eip));
1907 memcpy(&val, (char *)d->mmio + off, 4);
1908 return val;
1909
1910read_through16:
1911 if (mask != 0xFFFF)
1912 errx(1, "%s: non-16-bit read to offset %u (%#x)",
1913 d->name, off, getreg(eip));
1914 memcpy(&val, (char *)d->mmio + off, 2);
1915 return val;
1916
1917read_through8:
1918 if (mask != 0xFF)
1919 errx(1, "%s: non-8-bit read to offset %u (%#x)",
1920 d->name, off, getreg(eip));
1921 memcpy(&val, (char *)d->mmio + off, 1);
1922 return val;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301923}
1924
1925static void emulate_mmio(unsigned long paddr, const u8 *insn)
1926{
1927 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
1928 struct device *d = find_mmio_region(paddr, &off);
1929 unsigned long args[] = { LHREQ_TRAP, 14 };
1930
1931 if (!d) {
1932 warnx("MMIO touching %#08lx (not a device)", paddr);
1933 goto reinject;
1934 }
1935
1936 /* Prefix makes it a 16 bit op */
1937 if (insn[0] == 0x66) {
1938 mask = 0xFFFF;
1939 insnlen++;
1940 }
1941
1942 /* iowrite */
1943 if (insn[insnlen] == 0x89) {
1944 /* Next byte is r/m byte: bits 3-5 are register. */
1945 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
1946 emulate_mmio_write(d, off, val, mask);
1947 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1948 } else if (insn[insnlen] == 0x8b) { /* ioread */
1949 /* Next byte is r/m byte: bits 3-5 are register. */
1950 val = emulate_mmio_read(d, off, mask);
1951 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
1952 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1953 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
1954 mask = 0xff;
1955 /* Next byte is r/m byte: bits 3-5 are register. */
1956 val = getreg_num((insn[1] >> 3) & 0x7, mask);
1957 emulate_mmio_write(d, off, val, mask);
1958 insnlen = 2 + insn_displacement_len(insn[1]);
1959 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
1960 mask = 0xff;
1961 val = emulate_mmio_read(d, off, mask);
1962 setreg_num((insn[1] >> 3) & 0x7, val, mask);
1963 insnlen = 2 + insn_displacement_len(insn[1]);
1964 } else {
1965 warnx("Unknown MMIO instruction touching %#08lx:"
1966 " %02x %02x %02x %02x at %u",
1967 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
1968 reinject:
1969 /* Inject trap into Guest. */
1970 if (write(lguest_fd, args, sizeof(args)) < 0)
1971 err(1, "Reinjecting trap 14 for fault at %#x",
1972 getreg(eip));
1973 return;
1974 }
1975
1976 /* Finally, we've "done" the instruction, so move past it. */
1977 setreg(eip, getreg(eip) + insnlen);
1978}
Rusty Russellc565650b2015-02-11 15:15:10 +10301979
Rusty Russelldde79782007-07-26 10:41:03 -07001980/*L:190
1981 * Device Setup
1982 *
1983 * All devices need a descriptor so the Guest knows it exists, and a "struct
1984 * device" so the Launcher can keep track of it. We have common helper
Rusty Russella6bd8e12008-03-28 11:05:53 -05001985 * routines to allocate and manage them.
1986 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001987
Rusty Russell2e04ef72009-07-30 16:03:45 -06001988/*
1989 * The layout of the device page is a "struct lguest_device_desc" followed by a
Rusty Russella586d4f2008-02-04 23:49:56 -05001990 * number of virtqueue descriptors, then two sets of feature bits, then an
1991 * array of configuration bytes. This routine returns the configuration
Rusty Russell2e04ef72009-07-30 16:03:45 -06001992 * pointer.
1993 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001994static u8 *device_config(const struct device *dev)
1995{
1996 return (void *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -06001997 + dev->num_vq * sizeof(struct lguest_vqconfig)
1998 + dev->feature_len * 2;
Rusty Russella586d4f2008-02-04 23:49:56 -05001999}
2000
Rusty Russell2e04ef72009-07-30 16:03:45 -06002001/*
2002 * This routine allocates a new "struct lguest_device_desc" from descriptor
Rusty Russella586d4f2008-02-04 23:49:56 -05002003 * table page just above the Guest's normal memory. It returns a pointer to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002004 * that descriptor.
2005 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002006static struct lguest_device_desc *new_dev_desc(u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002007{
Rusty Russella586d4f2008-02-04 23:49:56 -05002008 struct lguest_device_desc d = { .type = type };
2009 void *p;
2010
2011 /* Figure out where the next device config is, based on the last one. */
2012 if (devices.lastdev)
2013 p = device_config(devices.lastdev)
2014 + devices.lastdev->desc->config_len;
2015 else
2016 p = devices.descpage;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002017
Rusty Russell17cbca22007-10-22 11:24:22 +10002018 /* We only have one page for all the descriptors. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002019 if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
Rusty Russell17cbca22007-10-22 11:24:22 +10002020 errx(1, "Too many devices");
2021
Rusty Russella586d4f2008-02-04 23:49:56 -05002022 /* p might not be aligned, so we memcpy in. */
2023 return memcpy(p, &d, sizeof(d));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002024}
2025
Rusty Russell2e04ef72009-07-30 16:03:45 -06002026/*
2027 * Each device descriptor is followed by the description of its virtqueues. We
2028 * specify how many descriptors the virtqueue is to have.
2029 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002030static void add_virtqueue(struct device *dev, unsigned int num_descs,
Rusty Russell659a0e62009-06-12 22:27:10 -06002031 void (*service)(struct virtqueue *))
Rusty Russell17cbca22007-10-22 11:24:22 +10002032{
2033 unsigned int pages;
2034 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2035 void *p;
2036
Rusty Russella6bd8e12008-03-28 11:05:53 -05002037 /* First we need some memory for this virtqueue. */
Rusty Russell2966af72008-12-30 09:25:58 -06002038 pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
Rusty Russell42b36cc2007-11-12 13:39:18 +11002039 / getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002040 p = get_pages(pages);
2041
Rusty Russelld1c856e2007-11-19 11:20:40 -05002042 /* Initialize the virtqueue */
2043 vq->next = NULL;
2044 vq->last_avail_idx = 0;
2045 vq->dev = dev;
Rusty Russella91d74a2009-07-30 16:03:45 -06002046
2047 /*
2048 * This is the routine the service thread will run, and its Process ID
2049 * once it's running.
2050 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002051 vq->service = service;
2052 vq->thread = (pid_t)-1;
Rusty Russelld1c856e2007-11-19 11:20:40 -05002053
Rusty Russell17cbca22007-10-22 11:24:22 +10002054 /* Initialize the configuration. */
2055 vq->config.num = num_descs;
2056 vq->config.irq = devices.next_irq++;
2057 vq->config.pfn = to_guest_phys(p) / getpagesize();
2058
2059 /* Initialize the vring. */
Rusty Russell2966af72008-12-30 09:25:58 -06002060 vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
Rusty Russell17cbca22007-10-22 11:24:22 +10002061
Rusty Russell2e04ef72009-07-30 16:03:45 -06002062 /*
2063 * Append virtqueue to this device's descriptor. We use
Rusty Russella586d4f2008-02-04 23:49:56 -05002064 * device_config() to get the end of the device's current virtqueues;
2065 * we check that we haven't added any config or feature information
Rusty Russell2e04ef72009-07-30 16:03:45 -06002066 * yet, otherwise we'd be overwriting them.
2067 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002068 assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
2069 memcpy(device_config(dev), &vq->config, sizeof(vq->config));
Rusty Russell713b15b2009-06-12 22:26:58 -06002070 dev->num_vq++;
Rusty Russella586d4f2008-02-04 23:49:56 -05002071 dev->desc->num_vq++;
2072
2073 verbose("Virtqueue page %#lx\n", to_guest_phys(p));
Rusty Russell17cbca22007-10-22 11:24:22 +10002074
Rusty Russell2e04ef72009-07-30 16:03:45 -06002075 /*
2076 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2077 * second.
2078 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002079 for (i = &dev->vq; *i; i = &(*i)->next);
2080 *i = vq;
Rusty Russell17cbca22007-10-22 11:24:22 +10002081}
2082
Rusty Russell93153072015-02-11 15:15:11 +10302083static void add_pci_virtqueue(struct device *dev,
2084 void (*service)(struct virtqueue *))
2085{
2086 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2087
2088 /* Initialize the virtqueue */
2089 vq->next = NULL;
2090 vq->last_avail_idx = 0;
2091 vq->dev = dev;
2092
2093 /*
2094 * This is the routine the service thread will run, and its Process ID
2095 * once it's running.
2096 */
2097 vq->service = service;
2098 vq->thread = (pid_t)-1;
2099
2100 /* Initialize the configuration. */
2101 vq->pci_config.queue_size = VIRTQUEUE_NUM;
2102 vq->pci_config.queue_enable = 0;
2103 vq->pci_config.queue_notify_off = 0;
2104
2105 /* Add one to the number of queues */
2106 vq->dev->mmio->cfg.num_queues++;
2107
2108 /* FIXME: Do irq per virtqueue, not per device. */
2109 vq->config.irq = vq->dev->config.irq_line;
2110
2111 /*
2112 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2113 * second.
2114 */
2115 for (i = &dev->vq; *i; i = &(*i)->next);
2116 *i = vq;
2117}
2118
Rusty Russell2e04ef72009-07-30 16:03:45 -06002119/*
2120 * The first half of the feature bitmask is for us to advertise features. The
2121 * second half is for the Guest to accept features.
2122 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002123static void add_feature(struct device *dev, unsigned bit)
2124{
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05002125 u8 *features = get_feature_bits(dev);
Rusty Russella586d4f2008-02-04 23:49:56 -05002126
2127 /* We can't extend the feature bits once we've added config bytes */
2128 if (dev->desc->feature_len <= bit / CHAR_BIT) {
2129 assert(dev->desc->config_len == 0);
Rusty Russell713b15b2009-06-12 22:26:58 -06002130 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
Rusty Russella586d4f2008-02-04 23:49:56 -05002131 }
2132
Rusty Russella586d4f2008-02-04 23:49:56 -05002133 features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
2134}
2135
Rusty Russell93153072015-02-11 15:15:11 +10302136static void add_pci_feature(struct device *dev, unsigned bit)
2137{
2138 dev->features |= (1ULL << bit);
2139}
2140
Rusty Russell2e04ef72009-07-30 16:03:45 -06002141/*
2142 * This routine sets the configuration fields for an existing device's
Rusty Russella586d4f2008-02-04 23:49:56 -05002143 * descriptor. It only works for the last device, but that's OK because that's
Rusty Russell2e04ef72009-07-30 16:03:45 -06002144 * how we use it.
2145 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002146static void set_config(struct device *dev, unsigned len, const void *conf)
2147{
2148 /* Check we haven't overflowed our single page. */
2149 if (device_config(dev) + len > devices.descpage + getpagesize())
2150 errx(1, "Too many devices");
2151
2152 /* Copy in the config information, and store the length. */
2153 memcpy(device_config(dev), conf, len);
2154 dev->desc->config_len = len;
Rusty Russell8ef562d2009-07-30 16:03:43 -06002155
2156 /* Size must fit in config_len field (8 bits)! */
2157 assert(dev->desc->config_len == len);
Rusty Russella586d4f2008-02-04 23:49:56 -05002158}
2159
Rusty Russell93153072015-02-11 15:15:11 +10302160/* For devices with no config. */
2161static void no_device_config(struct device *dev)
2162{
2163 dev->mmio_addr = get_mmio_region(dev->mmio_size);
2164
2165 dev->config.bar[0] = dev->mmio_addr;
2166 /* Bottom 4 bits must be zero */
2167 assert(~(dev->config.bar[0] & 0xF));
2168}
2169
2170/* This puts the device config into BAR0 */
2171static void set_device_config(struct device *dev, const void *conf, size_t len)
2172{
2173 /* Set up BAR 0 */
2174 dev->mmio_size += len;
2175 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2176 memcpy(dev->mmio + 1, conf, len);
2177
2178 /* Hook up device cfg */
2179 dev->config.cfg_access.cap.cap_next
2180 = offsetof(struct pci_config, device);
2181
2182 /* Fix up device cfg field length. */
2183 dev->config.device.length = len;
2184
2185 /* The rest is the same as the no-config case */
2186 no_device_config(dev);
2187}
2188
2189static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2190 size_t bar_offset, size_t bar_bytes, u8 next)
2191{
2192 cap->cap_vndr = PCI_CAP_ID_VNDR;
2193 cap->cap_next = next;
2194 cap->cap_len = caplen;
2195 cap->cfg_type = type;
2196 cap->bar = 0;
2197 memset(cap->padding, 0, sizeof(cap->padding));
2198 cap->offset = bar_offset;
2199 cap->length = bar_bytes;
2200}
2201
2202/*
2203 * This sets up the pci_config structure, as defined in the virtio 1.0
2204 * standard (and PCI standard).
2205 */
2206static void init_pci_config(struct pci_config *pci, u16 type,
2207 u8 class, u8 subclass)
2208{
2209 size_t bar_offset, bar_len;
2210
2211 /* Save typing: most thing are happy being zero. */
2212 memset(pci, 0, sizeof(*pci));
2213
2214 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2215 pci->vendor_id = 0x1AF4;
2216 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2217 pci->device_id = 0x1040 + type;
2218
2219 /*
2220 * PCI have specific codes for different types of devices.
2221 * Linux doesn't care, but it's a good clue for people looking
2222 * at the device.
2223 *
2224 * eg :
2225 * VIRTIO_ID_CONSOLE: class = 0x07, subclass = 0x00
2226 * VIRTIO_ID_NET: class = 0x02, subclass = 0x00
2227 * VIRTIO_ID_BLOCK: class = 0x01, subclass = 0x80
2228 * VIRTIO_ID_RNG: class = 0xff, subclass = 0
2229 */
2230 pci->class = class;
2231 pci->subclass = subclass;
2232
2233 /*
2234 * 4.1.2.1 Non-transitional devices SHOULD have a PCI Revision
2235 * ID of 1 or higher
2236 */
2237 pci->revid = 1;
2238
2239 /*
2240 * 4.1.2.1 Non-transitional devices SHOULD have a PCI
2241 * Subsystem Device ID of 0x40 or higher.
2242 */
2243 pci->subsystem_device_id = 0x40;
2244
2245 /* We use our dummy interrupt controller, and irq_line is the irq */
2246 pci->irq_line = devices.next_irq++;
2247 pci->irq_pin = 0;
2248
2249 /* Support for extended capabilities. */
2250 pci->status = (1 << 4);
2251
2252 /* Link them in. */
2253 pci->capabilities = offsetof(struct pci_config, common);
2254
2255 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2256 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2257 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2258 bar_offset, bar_len,
2259 offsetof(struct pci_config, notify));
2260
2261 bar_offset += bar_len;
2262 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2263 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2264 init_cap(&pci->notify.cap, sizeof(pci->notify),
2265 VIRTIO_PCI_CAP_NOTIFY_CFG,
2266 bar_offset, bar_len,
2267 offsetof(struct pci_config, isr));
2268
2269 bar_offset += bar_len;
2270 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2271 init_cap(&pci->isr, sizeof(pci->isr),
2272 VIRTIO_PCI_CAP_ISR_CFG,
2273 bar_offset, bar_len,
2274 offsetof(struct pci_config, cfg_access));
2275
2276 /* This doesn't have any presence in the BAR */
2277 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2278 VIRTIO_PCI_CAP_PCI_CFG,
2279 0, 0, 0);
2280
2281 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2282 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2283
2284 /*
2285 * This gets sewn in and length set in set_device_config().
2286 * Some devices don't have a device configuration interface, so
2287 * we never expose this if we don't call set_device_config().
2288 */
2289 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2290 bar_offset, 0, 0);
2291}
2292
Rusty Russell2e04ef72009-07-30 16:03:45 -06002293/*
2294 * This routine does all the creation and setup of a new device, including
Rusty Russella91d74a2009-07-30 16:03:45 -06002295 * calling new_dev_desc() to allocate the descriptor and device memory. We
2296 * don't actually start the service threads until later.
Rusty Russella6bd8e12008-03-28 11:05:53 -05002297 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002298 * See what I mean about userspace being boring?
2299 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002300static struct device *new_device(const char *name, u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002301{
2302 struct device *dev = malloc(sizeof(*dev));
2303
Rusty Russelldde79782007-07-26 10:41:03 -07002304 /* Now we populate the fields one at a time. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002305 dev->desc = new_dev_desc(type);
Rusty Russell17cbca22007-10-22 11:24:22 +10002306 dev->name = name;
Rusty Russelld1c856e2007-11-19 11:20:40 -05002307 dev->vq = NULL;
Rusty Russell713b15b2009-06-12 22:26:58 -06002308 dev->feature_len = 0;
2309 dev->num_vq = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002310 dev->running = false;
Rusty Russellca16f582012-10-04 12:03:25 +09302311 dev->next = NULL;
Rusty Russella586d4f2008-02-04 23:49:56 -05002312
Rusty Russell2e04ef72009-07-30 16:03:45 -06002313 /*
2314 * Append to device list. Prepending to a single-linked list is
Rusty Russella586d4f2008-02-04 23:49:56 -05002315 * easier, but the user expects the devices to be arranged on the bus
2316 * in command-line order. The first network device on the command line
Rusty Russell2e04ef72009-07-30 16:03:45 -06002317 * is eth0, the first block device /dev/vda, etc.
2318 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002319 if (devices.lastdev)
2320 devices.lastdev->next = dev;
2321 else
2322 devices.dev = dev;
2323 devices.lastdev = dev;
2324
Rusty Russell8ca47e02007-07-19 01:49:29 -07002325 return dev;
2326}
2327
Rusty Russell93153072015-02-11 15:15:11 +10302328static struct device *new_pci_device(const char *name, u16 type,
2329 u8 class, u8 subclass)
2330{
2331 struct device *dev = malloc(sizeof(*dev));
2332
2333 /* Now we populate the fields one at a time. */
2334 dev->desc = NULL;
2335 dev->name = name;
2336 dev->vq = NULL;
2337 dev->feature_len = 0;
2338 dev->num_vq = 0;
2339 dev->running = false;
2340 dev->next = NULL;
2341 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2342 dev->mmio = calloc(1, dev->mmio_size);
2343 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2344 dev->features_accepted = 0;
2345
2346 if (devices.device_num + 1 >= 32)
2347 errx(1, "Can only handle 31 PCI devices");
2348
2349 init_pci_config(&dev->config, type, class, subclass);
2350 assert(!devices.pci[devices.device_num+1]);
2351 devices.pci[++devices.device_num] = dev;
2352
2353 return dev;
2354}
2355
Rusty Russell2e04ef72009-07-30 16:03:45 -06002356/*
2357 * Our first setup routine is the console. It's a fairly simple device, but
2358 * UNIX tty handling makes it uglier than it could be.
2359 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002360static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002361{
2362 struct device *dev;
2363
Rusty Russelldde79782007-07-26 10:41:03 -07002364 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002365 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2366 struct termios term = orig_term;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002367 /*
2368 * Then we turn off echo, line buffering and ^C etc: We want a
2369 * raw input stream to the Guest.
2370 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002371 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2372 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002373 }
2374
Rusty Russell659a0e62009-06-12 22:27:10 -06002375 dev = new_device("console", VIRTIO_ID_CONSOLE);
2376
Rusty Russelldde79782007-07-26 10:41:03 -07002377 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002378 dev->priv = malloc(sizeof(struct console_abort));
2379 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002380
Rusty Russell2e04ef72009-07-30 16:03:45 -06002381 /*
2382 * The console needs two virtqueues: the input then the output. When
Rusty Russell56ae43d2007-10-22 11:24:23 +10002383 * they put something the input queue, we make sure we're listening to
2384 * stdin. When they put something in the output queue, we write it to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002385 * stdout.
2386 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002387 add_virtqueue(dev, VIRTQUEUE_NUM, console_input);
2388 add_virtqueue(dev, VIRTQUEUE_NUM, console_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002389
Rusty Russell659a0e62009-06-12 22:27:10 -06002390 verbose("device %u: console\n", ++devices.device_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002391}
Rusty Russelldde79782007-07-26 10:41:03 -07002392/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002393
Rusty Russell2e04ef72009-07-30 16:03:45 -06002394/*M:010
2395 * Inter-guest networking is an interesting area. Simplest is to have a
Rusty Russell17cbca22007-10-22 11:24:22 +10002396 * --sharenet=<name> option which opens or creates a named pipe. This can be
2397 * used to send packets to another guest in a 1:1 manner.
2398 *
Rusty Russell9f542882011-07-22 14:39:50 +09302399 * More sophisticated is to use one of the tools developed for project like UML
Rusty Russell17cbca22007-10-22 11:24:22 +10002400 * to do networking.
2401 *
2402 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2403 * completely generic ("here's my vring, attach to your vring") and would work
2404 * for any traffic. Of course, namespace and permissions issues need to be
2405 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2406 * multiple inter-guest channels behind one interface, although it would
2407 * require some manner of hotplugging new virtio channels.
2408 *
Rusty Russell9f542882011-07-22 14:39:50 +09302409 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002410:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002411
Rusty Russell8ca47e02007-07-19 01:49:29 -07002412static u32 str2ip(const char *ipaddr)
2413{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002414 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002415
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002416 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2417 errx(1, "Failed to parse IP address '%s'", ipaddr);
2418 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2419}
2420
2421static void str2mac(const char *macaddr, unsigned char mac[6])
2422{
2423 unsigned int m[6];
2424 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2425 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2426 errx(1, "Failed to parse mac address '%s'", macaddr);
2427 mac[0] = m[0];
2428 mac[1] = m[1];
2429 mac[2] = m[2];
2430 mac[3] = m[3];
2431 mac[4] = m[4];
2432 mac[5] = m[5];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002433}
2434
Rusty Russell2e04ef72009-07-30 16:03:45 -06002435/*
2436 * This code is "adapted" from libbridge: it attaches the Host end of the
Rusty Russelldde79782007-07-26 10:41:03 -07002437 * network device to the bridge device specified by the command line.
2438 *
2439 * This is yet another James Morris contribution (I'm an IP-level guy, so I
Rusty Russell2e04ef72009-07-30 16:03:45 -06002440 * dislike bridging), and I just try not to break it.
2441 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002442static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2443{
2444 int ifidx;
2445 struct ifreq ifr;
2446
2447 if (!*br_name)
2448 errx(1, "must specify bridge name");
2449
2450 ifidx = if_nametoindex(if_name);
2451 if (!ifidx)
2452 errx(1, "interface %s does not exist!", if_name);
2453
2454 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002455 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07002456 ifr.ifr_ifindex = ifidx;
2457 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2458 err(1, "can't add %s to bridge %s", if_name, br_name);
2459}
2460
Rusty Russell2e04ef72009-07-30 16:03:45 -06002461/*
2462 * This sets up the Host end of the network device with an IP address, brings
Rusty Russelldde79782007-07-26 10:41:03 -07002463 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell2e04ef72009-07-30 16:03:45 -06002464 * pointer.
2465 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002466static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002467{
2468 struct ifreq ifr;
Rusty Russellf8466192010-08-27 08:39:48 -06002469 struct sockaddr_in sin;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002470
2471 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002472 strcpy(ifr.ifr_name, tapif);
2473
2474 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russellf8466192010-08-27 08:39:48 -06002475 sin.sin_family = AF_INET;
2476 sin.sin_addr.s_addr = htonl(ipaddr);
2477 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002478 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002479 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002480 ifr.ifr_flags = IFF_UP;
2481 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002482 err(1, "Bringing interface %s up", tapif);
2483}
2484
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002485static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07002486{
Rusty Russell8ca47e02007-07-19 01:49:29 -07002487 struct ifreq ifr;
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
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002515 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2516 return netfd;
2517}
2518
Rusty Russell2e04ef72009-07-30 16:03:45 -06002519/*L:195
2520 * Our network is a Host<->Guest network. This can either use bridging or
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002521 * routing, but the principle is the same: it uses the "tun" device to inject
2522 * packets into the Host as if they came in from a normal network card. We
Rusty Russell2e04ef72009-07-30 16:03:45 -06002523 * just shunt packets between the Guest and the tun device.
2524 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002525static void setup_tun_net(char *arg)
2526{
2527 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002528 struct net_info *net_info = malloc(sizeof(*net_info));
2529 int ipfd;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002530 u32 ip = INADDR_ANY;
2531 bool bridging = false;
2532 char tapif[IFNAMSIZ], *p;
2533 struct virtio_net_config conf;
2534
Rusty Russell659a0e62009-06-12 22:27:10 -06002535 net_info->tunfd = get_tun_device(tapif);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002536
Rusty Russell17cbca22007-10-22 11:24:22 +10002537 /* First we create a new network device. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002538 dev = new_device("net", VIRTIO_ID_NET);
2539 dev->priv = net_info;
Rusty Russelldde79782007-07-26 10:41:03 -07002540
Rusty Russell2e04ef72009-07-30 16:03:45 -06002541 /* Network devices need a recv and a send queue, just like console. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002542 add_virtqueue(dev, VIRTQUEUE_NUM, net_input);
2543 add_virtqueue(dev, VIRTQUEUE_NUM, net_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002544
Rusty Russell2e04ef72009-07-30 16:03:45 -06002545 /*
2546 * We need a socket to perform the magic network ioctls to bring up the
2547 * tap interface, connect to the bridge etc. Any socket will do!
2548 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002549 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2550 if (ipfd < 0)
2551 err(1, "opening IP socket");
2552
Rusty Russelldde79782007-07-26 10:41:03 -07002553 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002554 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002555 arg += strlen(BRIDGE_PFX);
2556 bridging = true;
2557 }
2558
2559 /* A mac address may follow the bridge name or IP address */
2560 p = strchr(arg, ':');
2561 if (p) {
2562 str2mac(p+1, conf.mac);
Rusty Russell40c42072008-08-12 17:52:51 -05002563 add_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002564 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002565 }
2566
2567 /* arg is now either an IP address or a bridge name */
2568 if (bridging)
2569 add_to_bridge(ipfd, tapif, arg);
2570 else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002571 ip = str2ip(arg);
2572
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002573 /* Set up the tun device. */
2574 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002575
Rusty Russell398f1872008-07-29 09:58:37 -05002576 /* Expect Guest to handle everything except UFO */
2577 add_feature(dev, VIRTIO_NET_F_CSUM);
2578 add_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
Rusty Russell398f1872008-07-29 09:58:37 -05002579 add_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2580 add_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2581 add_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2582 add_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2583 add_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2584 add_feature(dev, VIRTIO_NET_F_HOST_ECN);
Mark McLoughlind1f01322009-05-11 18:11:46 +01002585 /* We handle indirect ring entries */
2586 add_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
Rusty Russell927cfb92013-07-15 10:50:13 +09302587 /* We're compliant with the damn spec. */
2588 add_feature(dev, VIRTIO_F_ANY_LAYOUT);
Rusty Russella586d4f2008-02-04 23:49:56 -05002589 set_config(dev, sizeof(conf), &conf);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002590
Rusty Russella586d4f2008-02-04 23:49:56 -05002591 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002592 close(ipfd);
2593
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002594 devices.device_num++;
2595
2596 if (bridging)
2597 verbose("device %u: tun %s attached to bridge: %s\n",
2598 devices.device_num, tapif, arg);
2599 else
2600 verbose("device %u: tun %s: %s\n",
2601 devices.device_num, tapif, arg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002602}
Rusty Russella91d74a2009-07-30 16:03:45 -06002603/*:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002604
Rusty Russelle1e72962007-10-25 15:02:50 +10002605/* This hangs off device->priv. */
Rusty Russell1842f232009-07-30 16:03:46 -06002606struct vblk_info {
Rusty Russell17cbca22007-10-22 11:24:22 +10002607 /* The size of the file. */
2608 off64_t len;
2609
2610 /* The file descriptor for the file. */
2611 int fd;
2612
Rusty Russell17cbca22007-10-22 11:24:22 +10002613};
2614
Rusty Russelle1e72962007-10-25 15:02:50 +10002615/*L:210
2616 * The Disk
2617 *
Rusty Russella91d74a2009-07-30 16:03:45 -06002618 * The disk only has one virtqueue, so it only has one thread. It is really
2619 * simple: the Guest asks for a block number and we read or write that position
2620 * in the file.
2621 *
2622 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2623 * slow: the Guest waits until the read is finished before running anything
2624 * else, even if it could have been doing useful work.
2625 *
2626 * We could have used async I/O, except it's reputed to suck so hard that
2627 * characters actually go missing from your code when you try to use it.
Rusty Russelle1e72962007-10-25 15:02:50 +10002628 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002629static void blk_request(struct virtqueue *vq)
Rusty Russell17cbca22007-10-22 11:24:22 +10002630{
Rusty Russell659a0e62009-06-12 22:27:10 -06002631 struct vblk_info *vblk = vq->dev->priv;
Rusty Russell17cbca22007-10-22 11:24:22 +10002632 unsigned int head, out_num, in_num, wlen;
Rusty Russellc0316a92012-10-16 23:56:13 +10302633 int ret, i;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002634 u8 *in;
Rusty Russellc0316a92012-10-16 23:56:13 +10302635 struct virtio_blk_outhdr out;
Rusty Russell659a0e62009-06-12 22:27:10 -06002636 struct iovec iov[vq->vring.num];
Rusty Russell17cbca22007-10-22 11:24:22 +10002637 off64_t off;
2638
Rusty Russella91d74a2009-07-30 16:03:45 -06002639 /*
2640 * Get the next request, where we normally wait. It triggers the
2641 * interrupt to acknowledge previously serviced requests (if any).
2642 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002643 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002644
Rusty Russellc0316a92012-10-16 23:56:13 +10302645 /* Copy the output header from the front of the iov (adjusts iov) */
2646 iov_consume(iov, out_num, &out, sizeof(out));
Rusty Russell17cbca22007-10-22 11:24:22 +10002647
Rusty Russellc0316a92012-10-16 23:56:13 +10302648 /* Find and trim end of iov input array, for our status byte. */
2649 in = NULL;
2650 for (i = out_num + in_num - 1; i >= out_num; i--) {
2651 if (iov[i].iov_len > 0) {
2652 in = iov[i].iov_base + iov[i].iov_len - 1;
2653 iov[i].iov_len--;
2654 break;
2655 }
2656 }
2657 if (!in)
2658 errx(1, "Bad virtblk cmd with no room for status");
2659
Rusty Russella91d74a2009-07-30 16:03:45 -06002660 /*
2661 * For historical reasons, block operations are expressed in 512 byte
2662 * "sectors".
2663 */
Rusty Russellc0316a92012-10-16 23:56:13 +10302664 off = out.sector * 512;
Rusty Russell17cbca22007-10-22 11:24:22 +10002665
Rusty Russell2e04ef72009-07-30 16:03:45 -06002666 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -06002667 * In general the virtio block driver is allowed to try SCSI commands.
2668 * It'd be nice if we supported eject, for example, but we don't.
2669 */
Rusty Russellc0316a92012-10-16 23:56:13 +10302670 if (out.type & VIRTIO_BLK_T_SCSI_CMD) {
Rusty Russell17cbca22007-10-22 11:24:22 +10002671 fprintf(stderr, "Scsi commands unsupported\n");
Rusty Russellcb38fa22008-05-02 21:50:45 -05002672 *in = VIRTIO_BLK_S_UNSUPP;
Anthony Liguori1200e642007-11-08 21:13:44 -06002673 wlen = sizeof(*in);
Rusty Russellc0316a92012-10-16 23:56:13 +10302674 } else 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 Russell2e04ef72009-07-30 16:03:45 -06002738 /* Creat the device. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002739 dev = new_device("block", VIRTIO_ID_BLOCK);
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 Russell659a0e62009-06-12 22:27:10 -06002742 add_virtqueue(dev, VIRTQUEUE_NUM, 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
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002751 /* We support FLUSH. */
2752 add_feature(dev, VIRTIO_BLK_F_FLUSH);
Rusty Russella586d4f2008-02-04 23:49:56 -05002753
Rusty Russell17cbca22007-10-22 11:24:22 +10002754 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002755 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10002756
Rusty Russell2e04ef72009-07-30 16:03:45 -06002757 /*
2758 * Tell Guest not to put in too many descriptors at once: two are used
2759 * for the in and out elements.
2760 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002761 add_feature(dev, VIRTIO_BLK_F_SEG_MAX);
2762 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2763
Rusty Russell8ef562d2009-07-30 16:03:43 -06002764 /* Don't try to put whole struct: we have 8 bit limit. */
2765 set_config(dev, offsetof(struct virtio_blk_config, geometry), &conf);
Rusty Russell17cbca22007-10-22 11:24:22 +10002766
Rusty Russell17cbca22007-10-22 11:24:22 +10002767 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell659a0e62009-06-12 22:27:10 -06002768 ++devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10002769}
Rusty Russell28fd6d72008-07-29 09:58:33 -05002770
Rusty Russell2e04ef72009-07-30 16:03:45 -06002771/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10302772 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05002773 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10302774 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05002775 * console is the reverse.
2776 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002777 * The same logic applies, however.
2778 */
2779struct rng_info {
2780 int rfd;
2781};
2782
Rusty Russell659a0e62009-06-12 22:27:10 -06002783static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05002784{
2785 int len;
2786 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002787 struct rng_info *rng_info = vq->dev->priv;
2788 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05002789
2790 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002791 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002792 if (out_num)
2793 errx(1, "Output buffers in rng?");
2794
Rusty Russell2e04ef72009-07-30 16:03:45 -06002795 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06002796 * Just like the console write, we loop to cover the whole iovec.
2797 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002798 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002799 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06002800 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002801 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10302802 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10302803 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002804 totlen += len;
2805 }
2806
2807 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002808 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002809}
2810
Rusty Russell2e04ef72009-07-30 16:03:45 -06002811/*L:199
2812 * This creates a "hardware" random number device for the Guest.
2813 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002814static void setup_rng(void)
2815{
2816 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002817 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05002818
Rusty Russella454bb32015-02-11 15:15:09 +10302819 /* Our device's private info simply contains the /dev/urandom fd. */
2820 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002821
Rusty Russell2e04ef72009-07-30 16:03:45 -06002822 /* Create the new device. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002823 dev = new_device("rng", VIRTIO_ID_RNG);
2824 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002825
2826 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002827 add_virtqueue(dev, VIRTQUEUE_NUM, rng_input);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002828
2829 verbose("device %u: rng\n", devices.device_num++);
2830}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002831/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05302832
Rusty Russella6bd8e12008-03-28 11:05:53 -05002833/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05302834static void __attribute__((noreturn)) restart_guest(void)
2835{
2836 unsigned int i;
2837
Rusty Russell2e04ef72009-07-30 16:03:45 -06002838 /*
2839 * Since we don't track all open fds, we simply close everything beyond
2840 * stderr.
2841 */
Balaji Raoec04b132007-12-28 14:26:24 +05302842 for (i = 3; i < FD_SETSIZE; i++)
2843 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05002844
Rusty Russell659a0e62009-06-12 22:27:10 -06002845 /* Reset all the devices (kills all threads). */
2846 cleanup_devices();
2847
Balaji Raoec04b132007-12-28 14:26:24 +05302848 execv(main_args[0], main_args);
2849 err(1, "Could not exec %s", main_args[0]);
2850}
Rusty Russell8ca47e02007-07-19 01:49:29 -07002851
Rusty Russell2e04ef72009-07-30 16:03:45 -06002852/*L:220
2853 * Finally we reach the core of the Launcher which runs the Guest, serves
2854 * its input and output, and finally, lays it to rest.
2855 */
Rusty Russell56739c802009-06-12 22:26:59 -06002856static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002857{
2858 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10302859 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002860 int readval;
2861
2862 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302863 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002864
Rusty Russell17cbca22007-10-22 11:24:22 +10002865 /* One unsigned long means the Guest did HCALL_NOTIFY */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302866 if (readval == sizeof(notify)) {
2867 if (notify.trap == 0x1F) {
2868 verbose("Notify on address %#08x\n",
2869 notify.addr);
2870 handle_output(notify.addr);
Rusty Russellc565650b2015-02-11 15:15:10 +10302871 } else if (notify.trap == 13) {
2872 verbose("Emulating instruction at %#x\n",
2873 getreg(eip));
2874 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302875 } else if (notify.trap == 14) {
2876 verbose("Emulating MMIO at %#x\n",
2877 getreg(eip));
2878 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302879 } else
2880 errx(1, "Unknown trap %i addr %#08x\n",
2881 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07002882 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002883 } else if (errno == ENOENT) {
2884 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002885 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002886 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05302887 /* ERESTART means that we need to reboot the guest */
2888 } else if (errno == ERESTART) {
2889 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06002890 /* Anything else means a bug or incompatible change. */
2891 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002892 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002893 }
2894}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002895/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10002896 * This is the end of the Launcher. The good news: we are over halfway
2897 * through! The bad news: the most fiendish part of the code still lies ahead
2898 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07002899 *
Rusty Russelle1e72962007-10-25 15:02:50 +10002900 * Are you ready? Take a deep breath and join me in the core of the Host, in
2901 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06002902:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002903
2904static struct option opts[] = {
2905 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002906 { "tunnet", 1, NULL, 't' },
2907 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05002908 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002909 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002910 { "username", 1, NULL, 'u' },
2911 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002912 { NULL },
2913};
2914static void usage(void)
2915{
2916 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002917 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07002918 "|--block=<filename>|--initrd=<filename>]...\n"
2919 "<mem-in-mb> vmlinux [args...]");
2920}
2921
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002922/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002923int main(int argc, char *argv[])
2924{
Rusty Russell2e04ef72009-07-30 16:03:45 -06002925 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002926 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06002927 /* Two temporaries. */
2928 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002929 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002930 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07002931 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002932 const char *initrd_name = NULL;
2933
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002934 /* Password structure for initgroups/setres[gu]id */
2935 struct passwd *user_details = NULL;
2936
2937 /* Directory to chroot to */
2938 char *chroot_path = NULL;
2939
Balaji Raoec04b132007-12-28 14:26:24 +05302940 /* Save the args: we "reboot" by execing ourselves again. */
2941 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05302942
Rusty Russell2e04ef72009-07-30 16:03:45 -06002943 /*
2944 * First we initialize the device list. We keep a pointer to the last
Rusty Russell659a0e62009-06-12 22:27:10 -06002945 * device, and the next interrupt number to use for devices (1:
Rusty Russell2e04ef72009-07-30 16:03:45 -06002946 * remember that 0 is used by the timer).
2947 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002948 devices.lastdev = NULL;
Rusty Russell17cbca22007-10-22 11:24:22 +10002949 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002950
Rusty Russella91d74a2009-07-30 16:03:45 -06002951 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002952 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06002953
Rusty Russell2e04ef72009-07-30 16:03:45 -06002954 /*
2955 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07002956 * descriptor and memory pages for the devices as we parse the command
2957 * line. So we quickly look through the arguments to find the amount
Rusty Russell2e04ef72009-07-30 16:03:45 -06002958 * of memory now.
2959 */
Rusty Russell6570c45992007-07-23 18:43:56 -07002960 for (i = 1; i < argc; i++) {
2961 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002962 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002963 /*
2964 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002965 * guest-physical memory range. This fills it with 0,
2966 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002967 * tries to access it.
2968 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002969 guest_base = map_zeroed_pages(mem / getpagesize()
2970 + DEVICE_PAGES);
2971 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10302972 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002973 devices.descpage = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07002974 break;
2975 }
2976 }
Rusty Russelldde79782007-07-26 10:41:03 -07002977
2978 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002979 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2980 switch (c) {
2981 case 'v':
2982 verbose = true;
2983 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002984 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10002985 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002986 break;
2987 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10002988 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002989 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002990 case 'r':
2991 setup_rng();
2992 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002993 case 'i':
2994 initrd_name = optarg;
2995 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002996 case 'u':
2997 user_details = getpwnam(optarg);
2998 if (!user_details)
2999 err(1, "getpwnam failed, incorrect username?");
3000 break;
3001 case 'c':
3002 chroot_path = optarg;
3003 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003004 default:
3005 warnx("Unknown argument %s", argv[optind]);
3006 usage();
3007 }
3008 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06003009 /*
3010 * After the other arguments we expect memory and kernel image name,
3011 * followed by command line arguments for the kernel.
3012 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003013 if (optind + 2 > argc)
3014 usage();
3015
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003016 verbose("Guest base is at %p\n", guest_base);
3017
Rusty Russelldde79782007-07-26 10:41:03 -07003018 /* We always have a console device */
Rusty Russell17cbca22007-10-22 11:24:22 +10003019 setup_console();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003020
Rusty Russell8e709462015-02-11 15:15:12 +10303021 /* Initialize the (fake) PCI host bridge device. */
3022 init_pci_host_bridge();
3023
Rusty Russell8ca47e02007-07-19 01:49:29 -07003024 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10003025 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07003026
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003027 /* Boot information is stashed at physical address 0 */
3028 boot = from_guest_phys(0);
3029
Rusty Russelldde79782007-07-26 10:41:03 -07003030 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003031 if (initrd_name) {
3032 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06003033 /*
3034 * These are the location in the Linux boot header where the
3035 * start and size of the initrd are expected to be found.
3036 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003037 boot->hdr.ramdisk_image = mem - initrd_size;
3038 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07003039 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003040 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003041 }
3042
Rusty Russell2e04ef72009-07-30 16:03:45 -06003043 /*
3044 * The Linux boot header contains an "E820" memory map: ours is a
3045 * simple, single region.
3046 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003047 boot->e820_entries = 1;
3048 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06003049 /*
3050 * The boot header contains a command line pointer: we put the command
3051 * line after the boot header.
3052 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003053 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10003054 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003055 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07003056
Rusty Russelle22a5392011-08-15 10:15:10 +09303057 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3058 boot->hdr.kernel_alignment = 0x1000000;
3059
Rusty Russell814a0e52007-10-22 11:29:44 +10003060 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003061 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10003062
3063 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003064 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10003065
Rusty Russell43d33b22007-10-22 11:29:57 +10003066 /* Tell the entry path not to try to reload segment registers. */
3067 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003068
Rusty Russell9f542882011-07-22 14:39:50 +09303069 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06003070 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07003071
Rusty Russella91d74a2009-07-30 16:03:45 -06003072 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06003073 signal(SIGCHLD, kill_launcher);
3074
3075 /* If we exit via err(), this kills all the threads, restores tty. */
3076 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003077
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003078 /* If requested, chroot to a directory */
3079 if (chroot_path) {
3080 if (chroot(chroot_path) != 0)
3081 err(1, "chroot(\"%s\") failed", chroot_path);
3082
3083 if (chdir("/") != 0)
3084 err(1, "chdir(\"/\") failed");
3085
3086 verbose("chroot done\n");
3087 }
3088
3089 /* If requested, drop privileges */
3090 if (user_details) {
3091 uid_t u;
3092 gid_t g;
3093
3094 u = user_details->pw_uid;
3095 g = user_details->pw_gid;
3096
3097 if (initgroups(user_details->pw_name, g) != 0)
3098 err(1, "initgroups failed");
3099
3100 if (setresgid(g, g, g) != 0)
3101 err(1, "setresgid failed");
3102
3103 if (setresuid(u, u, u) != 0)
3104 err(1, "setresuid failed");
3105
3106 verbose("Dropping privileges completed\n");
3107 }
3108
Rusty Russelldde79782007-07-26 10:41:03 -07003109 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06003110 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003111}
Rusty Russellf56a3842007-07-26 10:41:05 -07003112/*:*/
3113
3114/*M:999
3115 * Mastery is done: you now know everything I do.
3116 *
3117 * But surely you have seen code, features and bugs in your wanderings which
3118 * you now yearn to attack? That is the real game, and I look forward to you
3119 * patching and forking lguest into the Your-Name-Here-visor.
3120 *
3121 * Farewell, and good coding!
3122 * Rusty Russell.
3123 */