blob: d4a79f6ddfbd5dfc38c0714d44cbc025691429e9 [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
Rusty Russell50516542015-02-11 15:15:12 +103067#define VIRTIO_BLK_NO_LEGACY
Rusty Russell93153072015-02-11 15:15:11 +103068
69/* Use in-kernel ones, which defines VIRTIO_F_VERSION_1 */
70#include "../../include/uapi/linux/virtio_config.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093071#include <linux/virtio_net.h>
Rusty Russell50516542015-02-11 15:15:12 +103072#include "../../include/uapi/linux/virtio_blk.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093073#include <linux/virtio_console.h>
74#include <linux/virtio_rng.h>
75#include <linux/virtio_ring.h>
Rusty Russell93153072015-02-11 15:15:11 +103076#include "../../include/uapi/linux/virtio_pci.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093077#include <asm/bootparam.h>
78#include "../../include/linux/lguest_launcher.h"
79
Rusty Russell8ca47e02007-07-19 01:49:29 -070080#define BRIDGE_PFX "bridge:"
81#ifndef SIOCBRADDIF
82#define SIOCBRADDIF 0x89a2 /* add interface to bridge */
83#endif
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100084/* We can have up to 256 pages for devices. */
85#define DEVICE_PAGES 256
Rusty Russell0f0c4fa2008-07-29 09:58:37 -050086/* This will occupy 3 pages: it must be a power of 2. */
87#define VIRTQUEUE_NUM 256
Rusty Russell8ca47e02007-07-19 01:49:29 -070088
Rusty Russell2e04ef72009-07-30 16:03:45 -060089/*L:120
90 * verbose is both a global flag and a macro. The C preprocessor allows
91 * this, and although I wouldn't recommend it, it works quite nicely here.
92 */
Rusty Russell8ca47e02007-07-19 01:49:29 -070093static bool verbose;
94#define verbose(args...) \
95 do { if (verbose) printf(args); } while(0)
Rusty Russelldde79782007-07-26 10:41:03 -070096/*:*/
97
Rusty Russell3c6b5bf2007-10-22 11:03:26 +100098/* The pointer to the start of guest memory. */
99static void *guest_base;
100/* The maximum guest physical address allowed, and maximum possible. */
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030101static unsigned long guest_limit, guest_max, guest_mmio;
Rusty Russell56739c802009-06-12 22:26:59 -0600102/* The /dev/lguest file descriptor. */
103static int lguest_fd;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700104
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -0200105/* a per-cpu variable indicating whose vcpu is currently running */
106static unsigned int __thread cpu_id;
107
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030108/* 5 bit device number in the PCI_CONFIG_ADDR => 32 only */
109#define MAX_PCI_DEVICES 32
110
Rusty Russelldde79782007-07-26 10:41:03 -0700111/* This is our list of devices. */
Rusty Russell1842f232009-07-30 16:03:46 -0600112struct device_list {
Rusty Russell17cbca22007-10-22 11:24:22 +1000113 /* Counter to assign interrupt numbers. */
114 unsigned int next_irq;
115
116 /* Counter to print out convenient device numbers. */
117 unsigned int device_num;
118
Rusty Russelldde79782007-07-26 10:41:03 -0700119 /* The descriptor page for the devices. */
Rusty Russell17cbca22007-10-22 11:24:22 +1000120 u8 *descpage;
121
Rusty Russelldde79782007-07-26 10:41:03 -0700122 /* A single linked list of devices. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700123 struct device *dev;
Rusty Russell2e04ef72009-07-30 16:03:45 -0600124 /* And a pointer to the last device for easy append. */
Rusty Russella586d4f2008-02-04 23:49:56 -0500125 struct device *lastdev;
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030126
127 /* PCI devices. */
128 struct device *pci[MAX_PCI_DEVICES];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700129};
130
Rusty Russell17cbca22007-10-22 11:24:22 +1000131/* The list of Guest devices, based on command line arguments. */
132static struct device_list devices;
133
Rusty Russell93153072015-02-11 15:15:11 +1030134struct virtio_pci_cfg_cap {
135 struct virtio_pci_cap cap;
136 u32 window; /* Data for BAR access. */
137};
138
139struct virtio_pci_mmio {
140 struct virtio_pci_common_cfg cfg;
141 u16 notify;
142 u8 isr;
143 u8 padding;
144 /* Device-specific configuration follows this. */
145};
146
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030147/* This is the layout (little-endian) of the PCI config space. */
148struct pci_config {
149 u16 vendor_id, device_id;
150 u16 command, status;
151 u8 revid, prog_if, subclass, class;
152 u8 cacheline_size, lat_timer, header_type, bist;
153 u32 bar[6];
154 u32 cardbus_cis_ptr;
155 u16 subsystem_vendor_id, subsystem_device_id;
156 u32 expansion_rom_addr;
157 u8 capabilities, reserved1[3];
158 u32 reserved2;
159 u8 irq_line, irq_pin, min_grant, max_latency;
Rusty Russell93153072015-02-11 15:15:11 +1030160
161 /* Now, this is the linked capability list. */
162 struct virtio_pci_cap common;
163 struct virtio_pci_notify_cap notify;
164 struct virtio_pci_cap isr;
165 struct virtio_pci_cap device;
166 /* FIXME: Implement this! */
167 struct virtio_pci_cfg_cap cfg_access;
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030168};
169
Rusty Russelldde79782007-07-26 10:41:03 -0700170/* The device structure describes a single device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600171struct device {
Rusty Russelldde79782007-07-26 10:41:03 -0700172 /* The linked-list pointer. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700173 struct device *next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000174
Rusty Russell713b15b2009-06-12 22:26:58 -0600175 /* The device's descriptor, as mapped into the Guest. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700176 struct lguest_device_desc *desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000177
Rusty Russell713b15b2009-06-12 22:26:58 -0600178 /* We can't trust desc values once Guest has booted: we use these. */
179 unsigned int feature_len;
180 unsigned int num_vq;
181
Rusty Russell17cbca22007-10-22 11:24:22 +1000182 /* The name of this device, for --verbose. */
183 const char *name;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700184
Rusty Russell17cbca22007-10-22 11:24:22 +1000185 /* Any queues attached to this device */
186 struct virtqueue *vq;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700187
Rusty Russell659a0e62009-06-12 22:27:10 -0600188 /* Is it operational */
189 bool running;
Rusty Russella007a752008-05-02 21:50:53 -0500190
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030191 /* PCI configuration */
192 union {
193 struct pci_config config;
194 u32 config_words[sizeof(struct pci_config) / sizeof(u32)];
195 };
196
Rusty Russell93153072015-02-11 15:15:11 +1030197 /* Features we offer, and those accepted. */
198 u64 features, features_accepted;
199
Rusty Russelld7fbf6e2015-02-11 15:15:11 +1030200 /* Device-specific config hangs off the end of this. */
201 struct virtio_pci_mmio *mmio;
202
Rusty Russell6a54f9a2015-02-11 15:15:11 +1030203 /* PCI MMIO resources (all in BAR0) */
204 size_t mmio_size;
205 u32 mmio_addr;
206
Rusty Russell8ca47e02007-07-19 01:49:29 -0700207 /* Device-specific data. */
208 void *priv;
209};
210
Rusty Russell17cbca22007-10-22 11:24:22 +1000211/* The virtqueue structure describes a queue attached to a device. */
Rusty Russell1842f232009-07-30 16:03:46 -0600212struct virtqueue {
Rusty Russell17cbca22007-10-22 11:24:22 +1000213 struct virtqueue *next;
214
215 /* Which device owns me. */
216 struct device *dev;
217
218 /* The configuration for this queue. */
219 struct lguest_vqconfig config;
220
221 /* The actual ring of buffers. */
222 struct vring vring;
223
Rusty Russell93153072015-02-11 15:15:11 +1030224 /* The information about this virtqueue (we only use queue_size on) */
225 struct virtio_pci_common_cfg pci_config;
226
Rusty Russell17cbca22007-10-22 11:24:22 +1000227 /* Last available index we saw. */
228 u16 last_avail_idx;
229
Rusty Russell95c517c2009-06-12 22:27:11 -0600230 /* How many are used since we sent last irq? */
231 unsigned int pending_used;
232
Rusty Russell659a0e62009-06-12 22:27:10 -0600233 /* Eventfd where Guest notifications arrive. */
234 int eventfd;
Rusty Russell20887612008-05-30 15:09:46 -0500235
Rusty Russell659a0e62009-06-12 22:27:10 -0600236 /* Function for the thread which is servicing this virtqueue. */
237 void (*service)(struct virtqueue *vq);
238 pid_t thread;
Rusty Russell17cbca22007-10-22 11:24:22 +1000239};
240
Balaji Raoec04b132007-12-28 14:26:24 +0530241/* Remember the arguments to the program so we can "reboot" */
242static char **main_args;
243
Rusty Russell659a0e62009-06-12 22:27:10 -0600244/* The original tty settings to restore on exit. */
245static struct termios orig_term;
246
Rusty Russell2e04ef72009-07-30 16:03:45 -0600247/*
248 * We have to be careful with barriers: our devices are all run in separate
Rusty Russellf7027c62009-06-12 22:27:00 -0600249 * threads and so we need to make sure that changes visible to the Guest happen
Rusty Russell2e04ef72009-07-30 16:03:45 -0600250 * in precise order.
251 */
Rusty Russellf7027c62009-06-12 22:27:00 -0600252#define wmb() __asm__ __volatile__("" : : : "memory")
Rusty Russell0d69a652013-07-02 15:35:14 +0930253#define rmb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
254#define mb() __asm__ __volatile__("lock; addl $0,0(%%esp)" : : : "memory")
Rusty Russell17cbca22007-10-22 11:24:22 +1000255
Rusty Russellb5111792008-07-29 09:58:34 -0500256/* Wrapper for the last available index. Makes it easier to change. */
257#define lg_last_avail(vq) ((vq)->last_avail_idx)
258
Rusty Russell2e04ef72009-07-30 16:03:45 -0600259/*
260 * The virtio configuration space is defined to be little-endian. x86 is
261 * little-endian too, but it's nice to be explicit so we have these helpers.
262 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000263#define cpu_to_le16(v16) (v16)
264#define cpu_to_le32(v32) (v32)
265#define cpu_to_le64(v64) (v64)
266#define le16_to_cpu(v16) (v16)
267#define le32_to_cpu(v32) (v32)
Rusty Russella586d4f2008-02-04 23:49:56 -0500268#define le64_to_cpu(v64) (v64)
Rusty Russell17cbca22007-10-22 11:24:22 +1000269
Rusty Russell28fd6d72008-07-29 09:58:33 -0500270/* Is this iovec empty? */
271static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
272{
273 unsigned int i;
274
275 for (i = 0; i < num_iov; i++)
276 if (iov[i].iov_len)
277 return false;
278 return true;
279}
280
281/* Take len bytes from the front of this iovec. */
Rusty Russellc0316a92012-10-16 23:56:13 +1030282static void iov_consume(struct iovec iov[], unsigned num_iov,
283 void *dest, unsigned len)
Rusty Russell28fd6d72008-07-29 09:58:33 -0500284{
285 unsigned int i;
286
287 for (i = 0; i < num_iov; i++) {
288 unsigned int used;
289
290 used = iov[i].iov_len < len ? iov[i].iov_len : len;
Rusty Russellc0316a92012-10-16 23:56:13 +1030291 if (dest) {
292 memcpy(dest, iov[i].iov_base, used);
293 dest += used;
294 }
Rusty Russell28fd6d72008-07-29 09:58:33 -0500295 iov[i].iov_base += used;
296 iov[i].iov_len -= used;
297 len -= used;
298 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030299 if (len != 0)
300 errx(1, "iovec too short!");
Rusty Russell28fd6d72008-07-29 09:58:33 -0500301}
302
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500303/* The device virtqueue descriptors are followed by feature bitmasks. */
304static u8 *get_feature_bits(struct device *dev)
305{
306 return (u8 *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -0600307 + dev->num_vq * sizeof(struct lguest_vqconfig);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -0500308}
309
Rusty Russell2e04ef72009-07-30 16:03:45 -0600310/*L:100
311 * The Launcher code itself takes us out into userspace, that scary place where
312 * pointers run wild and free! Unfortunately, like most userspace programs,
313 * it's quite boring (which is why everyone likes to hack on the kernel!).
314 * Perhaps if you make up an Lguest Drinking Game at this point, it will get
315 * you through this section. Or, maybe not.
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000316 *
317 * The Launcher sets up a big chunk of memory to be the Guest's "physical"
318 * memory and stores it in "guest_base". In other words, Guest physical ==
319 * Launcher virtual with an offset.
320 *
321 * This can be tough to get your head around, but usually it just means that we
Francis Galieguea33f3222010-04-23 00:08:02 +0200322 * use these trivial conversion functions when the Guest gives us its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600323 * "physical" addresses:
324 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000325static void *from_guest_phys(unsigned long addr)
326{
327 return guest_base + addr;
328}
329
330static unsigned long to_guest_phys(const void *addr)
331{
332 return (addr - guest_base);
333}
334
Rusty Russelldde79782007-07-26 10:41:03 -0700335/*L:130
336 * Loading the Kernel.
337 *
338 * We start with couple of simple helper routines. open_or_die() avoids
Rusty Russell2e04ef72009-07-30 16:03:45 -0600339 * error-checking code cluttering the callers:
340 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700341static int open_or_die(const char *name, int flags)
342{
343 int fd = open(name, flags);
344 if (fd < 0)
345 err(1, "Failed to open %s", name);
346 return fd;
347}
348
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000349/* map_zeroed_pages() takes a number of pages. */
350static void *map_zeroed_pages(unsigned int num)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700351{
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000352 int fd = open_or_die("/dev/zero", O_RDONLY);
353 void *addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700354
Rusty Russell2e04ef72009-07-30 16:03:45 -0600355 /*
356 * We use a private mapping (ie. if we write to the page, it will be
Philip Sanderson5230ff02011-01-20 21:37:28 -0600357 * copied). We allocate an extra two pages PROT_NONE to act as guard
358 * pages against read/write attempts that exceed allocated space.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600359 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600360 addr = mmap(NULL, getpagesize() * (num+2),
361 PROT_NONE, MAP_PRIVATE, fd, 0);
362
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000363 if (addr == MAP_FAILED)
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200364 err(1, "Mmapping %u pages of /dev/zero", num);
Rusty Russella91d74a2009-07-30 16:03:45 -0600365
Philip Sanderson5230ff02011-01-20 21:37:28 -0600366 if (mprotect(addr + getpagesize(), getpagesize() * num,
367 PROT_READ|PROT_WRITE) == -1)
368 err(1, "mprotect rw %u pages failed", num);
369
Rusty Russella91d74a2009-07-30 16:03:45 -0600370 /*
371 * One neat mmap feature is that you can close the fd, and it
372 * stays mapped.
373 */
Mark McLoughlin34bdaab2008-06-13 14:04:58 +0100374 close(fd);
Rusty Russelldde79782007-07-26 10:41:03 -0700375
Philip Sanderson5230ff02011-01-20 21:37:28 -0600376 /* Return address after PROT_NONE page */
377 return addr + getpagesize();
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000378}
379
380/* Get some more pages for a device. */
381static void *get_pages(unsigned int num)
382{
383 void *addr = from_guest_phys(guest_limit);
384
385 guest_limit += num * getpagesize();
386 if (guest_limit > guest_max)
387 errx(1, "Not enough memory for devices");
388 return addr;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700389}
390
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030391/* Get some bytes which won't be mapped into the guest. */
392static unsigned long get_mmio_region(size_t size)
393{
394 unsigned long addr = guest_mmio;
395 size_t i;
396
397 if (!size)
398 return addr;
399
400 /* Size has to be a power of 2 (and multiple of 16) */
401 for (i = 1; i < size; i <<= 1);
402
403 guest_mmio += i;
404
405 return addr;
406}
407
Rusty Russell2e04ef72009-07-30 16:03:45 -0600408/*
409 * This routine is used to load the kernel or initrd. It tries mmap, but if
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700410 * that fails (Plan 9's kernel file isn't nicely aligned on page boundaries),
Rusty Russell2e04ef72009-07-30 16:03:45 -0600411 * it falls back to reading the memory in.
412 */
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700413static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
414{
415 ssize_t r;
416
Rusty Russell2e04ef72009-07-30 16:03:45 -0600417 /*
418 * We map writable even though for some segments are marked read-only.
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700419 * The kernel really wants to be writable: it patches its own
420 * instructions.
421 *
422 * MAP_PRIVATE means that the page won't be copied until a write is
423 * done to it. This allows us to share untouched memory between
Rusty Russell2e04ef72009-07-30 16:03:45 -0600424 * Guests.
425 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600426 if (mmap(addr, len, PROT_READ|PROT_WRITE,
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700427 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
428 return;
429
430 /* pread does a seek and a read in one shot: saves a few lines. */
431 r = pread(fd, addr, len, offset);
432 if (r != len)
433 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
434}
435
Rusty Russell2e04ef72009-07-30 16:03:45 -0600436/*
437 * This routine takes an open vmlinux image, which is in ELF, and maps it into
Rusty Russelldde79782007-07-26 10:41:03 -0700438 * the Guest memory. ELF = Embedded Linking Format, which is the format used
439 * by all modern binaries on Linux including the kernel.
440 *
441 * The ELF headers give *two* addresses: a physical address, and a virtual
Rusty Russell47436aa2007-10-22 11:03:36 +1000442 * address. We use the physical address; the Guest will map itself to the
443 * virtual address.
Rusty Russelldde79782007-07-26 10:41:03 -0700444 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600445 * We return the starting address.
446 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000447static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700448{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700449 Elf32_Phdr phdr[ehdr->e_phnum];
450 unsigned int i;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700451
Rusty Russell2e04ef72009-07-30 16:03:45 -0600452 /*
453 * Sanity checks on the main ELF header: an x86 executable with a
454 * reasonable number of correctly-sized program headers.
455 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700456 if (ehdr->e_type != ET_EXEC
457 || ehdr->e_machine != EM_386
458 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
459 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
460 errx(1, "Malformed elf header");
461
Rusty Russell2e04ef72009-07-30 16:03:45 -0600462 /*
463 * An ELF executable contains an ELF header and a number of "program"
Rusty Russelldde79782007-07-26 10:41:03 -0700464 * headers which indicate which parts ("segments") of the program to
Rusty Russell2e04ef72009-07-30 16:03:45 -0600465 * load where.
466 */
Rusty Russelldde79782007-07-26 10:41:03 -0700467
468 /* We read in all the program headers at once: */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700469 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
470 err(1, "Seeking to program headers");
471 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
472 err(1, "Reading program headers");
473
Rusty Russell2e04ef72009-07-30 16:03:45 -0600474 /*
475 * Try all the headers: there are usually only three. A read-only one,
476 * a read-write one, and a "note" section which we don't load.
477 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700478 for (i = 0; i < ehdr->e_phnum; i++) {
Rusty Russelldde79782007-07-26 10:41:03 -0700479 /* If this isn't a loadable segment, we ignore it */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700480 if (phdr[i].p_type != PT_LOAD)
481 continue;
482
483 verbose("Section %i: size %i addr %p\n",
484 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
485
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700486 /* We map this section of the file at its physical address. */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000487 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700488 phdr[i].p_offset, phdr[i].p_filesz);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700489 }
490
Rusty Russell814a0e52007-10-22 11:29:44 +1000491 /* The entry point is given in the ELF header. */
492 return ehdr->e_entry;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700493}
494
Rusty Russell2e04ef72009-07-30 16:03:45 -0600495/*L:150
496 * A bzImage, unlike an ELF file, is not meant to be loaded. You're supposed
497 * to jump into it and it will unpack itself. We used to have to perform some
498 * hairy magic because the unpacking code scared me.
Rusty Russelldde79782007-07-26 10:41:03 -0700499 *
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000500 * Fortunately, Jeremy Fitzhardinge convinced me it wasn't that hard and wrote
501 * a small patch to jump over the tricky bits in the Guest, so now we just read
Rusty Russell2e04ef72009-07-30 16:03:45 -0600502 * the funky header so we know where in the file to load, and away we go!
503 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000504static unsigned long load_bzimage(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700505{
Rusty Russell43d33b22007-10-22 11:29:57 +1000506 struct boot_params boot;
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000507 int r;
508 /* Modern bzImages get loaded at 1M. */
509 void *p = from_guest_phys(0x100000);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700510
Rusty Russell2e04ef72009-07-30 16:03:45 -0600511 /*
512 * Go back to the start of the file and read the header. It should be
Paul Bolle395cf962011-08-15 02:02:26 +0200513 * a Linux boot header (see Documentation/x86/boot.txt)
Rusty Russell2e04ef72009-07-30 16:03:45 -0600514 */
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000515 lseek(fd, 0, SEEK_SET);
Rusty Russell43d33b22007-10-22 11:29:57 +1000516 read(fd, &boot, sizeof(boot));
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000517
Rusty Russell43d33b22007-10-22 11:29:57 +1000518 /* Inside the setup_hdr, we expect the magic "HdrS" */
519 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000520 errx(1, "This doesn't look like a bzImage to me");
521
Rusty Russell43d33b22007-10-22 11:29:57 +1000522 /* Skip over the extra sectors of the header. */
523 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
Rusty Russell5bbf89f2007-10-22 11:29:56 +1000524
525 /* Now read everything into memory. in nice big chunks. */
526 while ((r = read(fd, p, 65536)) > 0)
527 p += r;
528
Rusty Russell43d33b22007-10-22 11:29:57 +1000529 /* Finally, code32_start tells us where to enter the kernel. */
530 return boot.hdr.code32_start;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700531}
532
Rusty Russell2e04ef72009-07-30 16:03:45 -0600533/*L:140
534 * Loading the kernel is easy when it's a "vmlinux", but most kernels
Rusty Russelle1e72962007-10-25 15:02:50 +1000535 * come wrapped up in the self-decompressing "bzImage" format. With a little
Rusty Russell2e04ef72009-07-30 16:03:45 -0600536 * work, we can load those, too.
537 */
Rusty Russell47436aa2007-10-22 11:03:36 +1000538static unsigned long load_kernel(int fd)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700539{
540 Elf32_Ehdr hdr;
541
Rusty Russelldde79782007-07-26 10:41:03 -0700542 /* Read in the first few bytes. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700543 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
544 err(1, "Reading kernel");
545
Rusty Russelldde79782007-07-26 10:41:03 -0700546 /* If it's an ELF file, it starts with "\177ELF" */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700547 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
Rusty Russell47436aa2007-10-22 11:03:36 +1000548 return map_elf(fd, &hdr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700549
Rusty Russella6bd8e12008-03-28 11:05:53 -0500550 /* Otherwise we assume it's a bzImage, and try to load it. */
Rusty Russell47436aa2007-10-22 11:03:36 +1000551 return load_bzimage(fd);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700552}
553
Rusty Russell2e04ef72009-07-30 16:03:45 -0600554/*
555 * This is a trivial little helper to align pages. Andi Kleen hated it because
Rusty Russelldde79782007-07-26 10:41:03 -0700556 * it calls getpagesize() twice: "it's dumb code."
557 *
558 * Kernel guys get really het up about optimization, even when it's not
Rusty Russell2e04ef72009-07-30 16:03:45 -0600559 * necessary. I leave this code as a reaction against that.
560 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700561static inline unsigned long page_align(unsigned long addr)
562{
Rusty Russelldde79782007-07-26 10:41:03 -0700563 /* Add upwards and truncate downwards. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700564 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
565}
566
Rusty Russell2e04ef72009-07-30 16:03:45 -0600567/*L:180
568 * An "initial ram disk" is a disk image loaded into memory along with the
569 * kernel which the kernel can use to boot from without needing any drivers.
570 * Most distributions now use this as standard: the initrd contains the code to
571 * load the appropriate driver modules for the current machine.
Rusty Russelldde79782007-07-26 10:41:03 -0700572 *
573 * Importantly, James Morris works for RedHat, and Fedora uses initrds for its
Rusty Russell2e04ef72009-07-30 16:03:45 -0600574 * kernels. He sent me this (and tells me when I break it).
575 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700576static unsigned long load_initrd(const char *name, unsigned long mem)
577{
578 int ifd;
579 struct stat st;
580 unsigned long len;
Rusty Russell8ca47e02007-07-19 01:49:29 -0700581
582 ifd = open_or_die(name, O_RDONLY);
Rusty Russelldde79782007-07-26 10:41:03 -0700583 /* fstat() is needed to get the file size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700584 if (fstat(ifd, &st) < 0)
585 err(1, "fstat() on initrd '%s'", name);
586
Rusty Russell2e04ef72009-07-30 16:03:45 -0600587 /*
588 * We map the initrd at the top of memory, but mmap wants it to be
589 * page-aligned, so we round the size up for that.
590 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700591 len = page_align(st.st_size);
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000592 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600593 /*
594 * Once a file is mapped, you can close the file descriptor. It's a
595 * little odd, but quite useful.
596 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700597 close(ifd);
Ronald G. Minnich6649bb72007-08-28 14:35:59 -0700598 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
Rusty Russelldde79782007-07-26 10:41:03 -0700599
600 /* We return the initrd size. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700601 return len;
602}
Rusty Russelle1e72962007-10-25 15:02:50 +1000603/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700604
Rusty Russell2e04ef72009-07-30 16:03:45 -0600605/*
606 * Simple routine to roll all the commandline arguments together with spaces
607 * between them.
608 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700609static void concat(char *dst, char *args[])
610{
611 unsigned int i, len = 0;
612
613 for (i = 0; args[i]; i++) {
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100614 if (i) {
615 strcat(dst+len, " ");
616 len++;
617 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700618 strcpy(dst+len, args[i]);
Paul Bolle1ef36fa2008-03-10 16:39:03 +0100619 len += strlen(args[i]);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700620 }
621 /* In case it's empty. */
622 dst[len] = '\0';
623}
624
Rusty Russell2e04ef72009-07-30 16:03:45 -0600625/*L:185
626 * This is where we actually tell the kernel to initialize the Guest. We
Rusty Russelle1e72962007-10-25 15:02:50 +1000627 * saw the arguments it expects when we looked at initialize() in lguest_user.c:
Matias Zabaljauregui58a24562008-09-29 01:40:07 -0300628 * the base of Guest "physical" memory, the top physical page to allow and the
Rusty Russell2e04ef72009-07-30 16:03:45 -0600629 * entry point for the Guest.
630 */
Rusty Russell56739c802009-06-12 22:26:59 -0600631static void tell_kernel(unsigned long start)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700632{
Jes Sorensen511801d2007-10-22 11:03:31 +1000633 unsigned long args[] = { LHREQ_INITIALIZE,
634 (unsigned long)guest_base,
Rusty Russell7313d522015-02-11 15:15:10 +1030635 guest_limit / getpagesize(), start,
Rusty Russell0a6bcc12015-02-11 15:15:11 +1030636 (guest_mmio+getpagesize()-1) / getpagesize() };
637 verbose("Guest: %p - %p (%#lx, MMIO %#lx)\n",
638 guest_base, guest_base + guest_limit,
639 guest_limit, guest_mmio);
Rusty Russell56739c802009-06-12 22:26:59 -0600640 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
641 if (write(lguest_fd, args, sizeof(args)) < 0)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700642 err(1, "Writing to /dev/lguest");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700643}
Rusty Russelldde79782007-07-26 10:41:03 -0700644/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -0700645
Rusty Russella91d74a2009-07-30 16:03:45 -0600646/*L:200
Rusty Russelldde79782007-07-26 10:41:03 -0700647 * Device Handling.
648 *
Rusty Russelle1e72962007-10-25 15:02:50 +1000649 * When the Guest gives us a buffer, it sends an array of addresses and sizes.
Rusty Russelldde79782007-07-26 10:41:03 -0700650 * We need to make sure it's not trying to reach into the Launcher itself, so
Rusty Russelle1e72962007-10-25 15:02:50 +1000651 * we have a convenient routine which checks it and exits with an error message
Rusty Russelldde79782007-07-26 10:41:03 -0700652 * if something funny is going on:
653 */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700654static void *_check_pointer(unsigned long addr, unsigned int size,
655 unsigned int line)
656{
Rusty Russell2e04ef72009-07-30 16:03:45 -0600657 /*
Philip Sanderson5230ff02011-01-20 21:37:28 -0600658 * Check if the requested address and size exceeds the allocated memory,
659 * or addr + size wraps around.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600660 */
Philip Sanderson5230ff02011-01-20 21:37:28 -0600661 if ((addr + size) > guest_limit || (addr + size) < addr)
Rusty Russell17cbca22007-10-22 11:24:22 +1000662 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
Rusty Russell2e04ef72009-07-30 16:03:45 -0600663 /*
664 * We return a pointer for the caller's convenience, now we know it's
665 * safe to use.
666 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +1000667 return from_guest_phys(addr);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700668}
Rusty Russelldde79782007-07-26 10:41:03 -0700669/* A macro which transparently hands the line number to the real function. */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700670#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
671
Rusty Russell2e04ef72009-07-30 16:03:45 -0600672/*
673 * Each buffer in the virtqueues is actually a chain of descriptors. This
Rusty Russelle1e72962007-10-25 15:02:50 +1000674 * function returns the next descriptor in the chain, or vq->vring.num if we're
Rusty Russell2e04ef72009-07-30 16:03:45 -0600675 * at the end.
676 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100677static unsigned next_desc(struct vring_desc *desc,
678 unsigned int i, unsigned int max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000679{
680 unsigned int next;
681
682 /* If this descriptor says it doesn't chain, we're done. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100683 if (!(desc[i].flags & VRING_DESC_F_NEXT))
684 return max;
Rusty Russell17cbca22007-10-22 11:24:22 +1000685
686 /* Check they're not leading us off end of descriptors. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100687 next = desc[i].next;
Rusty Russell17cbca22007-10-22 11:24:22 +1000688 /* Make sure compiler knows to grab that: we don't want it changing! */
689 wmb();
690
Mark McLoughlind1f01322009-05-11 18:11:46 +0100691 if (next >= max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000692 errx(1, "Desc next is %u", next);
693
694 return next;
695}
696
Rusty Russella91d74a2009-07-30 16:03:45 -0600697/*
698 * This actually sends the interrupt for this virtqueue, if we've used a
699 * buffer.
700 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600701static void trigger_irq(struct virtqueue *vq)
702{
703 unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
704
Rusty Russell95c517c2009-06-12 22:27:11 -0600705 /* Don't inform them if nothing used. */
706 if (!vq->pending_used)
707 return;
708 vq->pending_used = 0;
709
Rusty Russellca60a422009-09-23 22:26:47 -0600710 /* If they don't want an interrupt, don't send one... */
711 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
Rusty Russell990c91f2011-05-30 11:14:12 -0600712 return;
Rusty Russellca60a422009-09-23 22:26:47 -0600713 }
Rusty Russell38bc2b82009-06-12 22:27:11 -0600714
Rusty Russell93153072015-02-11 15:15:11 +1030715 /* For a PCI device, set isr to 1 (queue interrupt pending) */
716 if (vq->dev->mmio)
717 vq->dev->mmio->isr = 0x1;
718
Rusty Russell38bc2b82009-06-12 22:27:11 -0600719 /* Send the Guest an interrupt tell them we used something up. */
720 if (write(lguest_fd, buf, sizeof(buf)) != 0)
721 err(1, "Triggering irq %i", vq->config.irq);
722}
723
Rusty Russell2e04ef72009-07-30 16:03:45 -0600724/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600725 * This looks in the virtqueue for the first available buffer, and converts
Rusty Russell17cbca22007-10-22 11:24:22 +1000726 * it to an iovec for convenient access. Since descriptors consist of some
727 * number of output then some number of input descriptors, it's actually two
728 * iovecs, but we pack them into one and note how many of each there were.
729 *
Rusty Russella91d74a2009-07-30 16:03:45 -0600730 * This function waits if necessary, and returns the descriptor number found.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600731 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600732static unsigned wait_for_vq_desc(struct virtqueue *vq,
733 struct iovec iov[],
734 unsigned int *out_num, unsigned int *in_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000735{
Mark McLoughlind1f01322009-05-11 18:11:46 +0100736 unsigned int i, head, max;
737 struct vring_desc *desc;
Rusty Russell659a0e62009-06-12 22:27:10 -0600738 u16 last_avail = lg_last_avail(vq);
739
Rusty Russella91d74a2009-07-30 16:03:45 -0600740 /* There's nothing available? */
Rusty Russell659a0e62009-06-12 22:27:10 -0600741 while (last_avail == vq->vring.avail->idx) {
742 u64 event;
743
Rusty Russella91d74a2009-07-30 16:03:45 -0600744 /*
745 * Since we're about to sleep, now is a good time to tell the
746 * Guest about what we've used up to now.
747 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600748 trigger_irq(vq);
749
Rusty Russellb60da132009-06-12 22:27:12 -0600750 /* OK, now we need to know about added descriptors. */
751 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
752
Rusty Russell2e04ef72009-07-30 16:03:45 -0600753 /*
754 * They could have slipped one in as we were doing that: make
755 * sure it's written, then check again.
756 */
Rusty Russellb60da132009-06-12 22:27:12 -0600757 mb();
758 if (last_avail != vq->vring.avail->idx) {
759 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
760 break;
761 }
762
Rusty Russell659a0e62009-06-12 22:27:10 -0600763 /* Nothing new? Wait for eventfd to tell us they refilled. */
764 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
765 errx(1, "Event read failed?");
Rusty Russellb60da132009-06-12 22:27:12 -0600766
767 /* We don't need to be notified again. */
768 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
Rusty Russell659a0e62009-06-12 22:27:10 -0600769 }
Rusty Russell17cbca22007-10-22 11:24:22 +1000770
771 /* Check it isn't doing very strange things with descriptor numbers. */
Rusty Russellb5111792008-07-29 09:58:34 -0500772 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000773 errx(1, "Guest moved used index from %u to %u",
Rusty Russellb5111792008-07-29 09:58:34 -0500774 last_avail, vq->vring.avail->idx);
Rusty Russell17cbca22007-10-22 11:24:22 +1000775
Rusty Russell8fd9a632013-07-02 15:35:13 +0930776 /*
777 * Make sure we read the descriptor number *after* we read the ring
778 * update; don't let the cpu or compiler change the order.
779 */
780 rmb();
781
Rusty Russell2e04ef72009-07-30 16:03:45 -0600782 /*
783 * Grab the next descriptor number they're advertising, and increment
784 * the index we've seen.
785 */
Rusty Russellb5111792008-07-29 09:58:34 -0500786 head = vq->vring.avail->ring[last_avail % vq->vring.num];
787 lg_last_avail(vq)++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000788
789 /* If their number is silly, that's a fatal mistake. */
790 if (head >= vq->vring.num)
791 errx(1, "Guest says index %u is available", head);
792
793 /* When we start there are none of either input nor output. */
794 *out_num = *in_num = 0;
795
Mark McLoughlind1f01322009-05-11 18:11:46 +0100796 max = vq->vring.num;
797 desc = vq->vring.desc;
Rusty Russell17cbca22007-10-22 11:24:22 +1000798 i = head;
Mark McLoughlind1f01322009-05-11 18:11:46 +0100799
Rusty Russell2e04ef72009-07-30 16:03:45 -0600800 /*
Rusty Russell8fd9a632013-07-02 15:35:13 +0930801 * We have to read the descriptor after we read the descriptor number,
802 * but there's a data dependency there so the CPU shouldn't reorder
803 * that: no rmb() required.
804 */
805
806 /*
Rusty Russell2e04ef72009-07-30 16:03:45 -0600807 * If this is an indirect entry, then this buffer contains a descriptor
808 * table which we handle as if it's any normal descriptor chain.
809 */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100810 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
811 if (desc[i].len % sizeof(struct vring_desc))
812 errx(1, "Invalid size for indirect buffer table");
813
814 max = desc[i].len / sizeof(struct vring_desc);
815 desc = check_pointer(desc[i].addr, desc[i].len);
816 i = 0;
817 }
818
Rusty Russell17cbca22007-10-22 11:24:22 +1000819 do {
820 /* Grab the first descriptor, and check it's OK. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100821 iov[*out_num + *in_num].iov_len = desc[i].len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000822 iov[*out_num + *in_num].iov_base
Mark McLoughlind1f01322009-05-11 18:11:46 +0100823 = check_pointer(desc[i].addr, desc[i].len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000824 /* If this is an input descriptor, increment that count. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100825 if (desc[i].flags & VRING_DESC_F_WRITE)
Rusty Russell17cbca22007-10-22 11:24:22 +1000826 (*in_num)++;
827 else {
Rusty Russell2e04ef72009-07-30 16:03:45 -0600828 /*
829 * If it's an output descriptor, they're all supposed
830 * to come before any input descriptors.
831 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000832 if (*in_num)
833 errx(1, "Descriptor has out after in");
834 (*out_num)++;
835 }
836
837 /* If we've got too many, that implies a descriptor loop. */
Mark McLoughlind1f01322009-05-11 18:11:46 +0100838 if (*out_num + *in_num > max)
Rusty Russell17cbca22007-10-22 11:24:22 +1000839 errx(1, "Looped descriptor");
Mark McLoughlind1f01322009-05-11 18:11:46 +0100840 } while ((i = next_desc(desc, i, max)) != max);
Rusty Russell17cbca22007-10-22 11:24:22 +1000841
842 return head;
843}
844
Rusty Russell2e04ef72009-07-30 16:03:45 -0600845/*
Rusty Russella91d74a2009-07-30 16:03:45 -0600846 * After we've used one of their buffers, we tell the Guest about it. Sometime
847 * later we'll want to send them an interrupt using trigger_irq(); note that
848 * wait_for_vq_desc() does that for us if it has to wait.
Rusty Russell2e04ef72009-07-30 16:03:45 -0600849 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000850static void add_used(struct virtqueue *vq, unsigned int head, int len)
851{
852 struct vring_used_elem *used;
853
Rusty Russell2e04ef72009-07-30 16:03:45 -0600854 /*
855 * The virtqueue contains a ring of used buffers. Get a pointer to the
856 * next entry in that used ring.
857 */
Rusty Russell17cbca22007-10-22 11:24:22 +1000858 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
859 used->id = head;
860 used->len = len;
861 /* Make sure buffer is written before we update index. */
862 wmb();
863 vq->vring.used->idx++;
Rusty Russell95c517c2009-06-12 22:27:11 -0600864 vq->pending_used++;
Rusty Russell17cbca22007-10-22 11:24:22 +1000865}
866
Rusty Russell17cbca22007-10-22 11:24:22 +1000867/* And here's the combo meal deal. Supersize me! */
Rusty Russell56739c802009-06-12 22:26:59 -0600868static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
Rusty Russell17cbca22007-10-22 11:24:22 +1000869{
870 add_used(vq, head, len);
Rusty Russell56739c802009-06-12 22:26:59 -0600871 trigger_irq(vq);
Rusty Russell17cbca22007-10-22 11:24:22 +1000872}
873
Rusty Russelle1e72962007-10-25 15:02:50 +1000874/*
875 * The Console
876 *
Rusty Russell2e04ef72009-07-30 16:03:45 -0600877 * We associate some data with the console for our exit hack.
878 */
Rusty Russell1842f232009-07-30 16:03:46 -0600879struct console_abort {
Rusty Russelldde79782007-07-26 10:41:03 -0700880 /* How many times have they hit ^C? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700881 int count;
Rusty Russelldde79782007-07-26 10:41:03 -0700882 /* When did they start? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700883 struct timeval start;
884};
885
Rusty Russelldde79782007-07-26 10:41:03 -0700886/* This is the routine which handles console input (ie. stdin). */
Rusty Russell659a0e62009-06-12 22:27:10 -0600887static void console_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700888{
Rusty Russell8ca47e02007-07-19 01:49:29 -0700889 int len;
Rusty Russell17cbca22007-10-22 11:24:22 +1000890 unsigned int head, in_num, out_num;
Rusty Russell659a0e62009-06-12 22:27:10 -0600891 struct console_abort *abort = vq->dev->priv;
892 struct iovec iov[vq->vring.num];
Rusty Russell8ca47e02007-07-19 01:49:29 -0700893
Rusty Russella91d74a2009-07-30 16:03:45 -0600894 /* Make sure there's a descriptor available. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600895 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell56ae43d2007-10-22 11:24:23 +1000896 if (out_num)
Rusty Russell17cbca22007-10-22 11:24:22 +1000897 errx(1, "Output buffers in console in queue?");
Rusty Russell8ca47e02007-07-19 01:49:29 -0700898
Rusty Russella91d74a2009-07-30 16:03:45 -0600899 /* Read into it. This is where we usually wait. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600900 len = readv(STDIN_FILENO, iov, in_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700901 if (len <= 0) {
Rusty Russell659a0e62009-06-12 22:27:10 -0600902 /* Ran out of input? */
Rusty Russell8ca47e02007-07-19 01:49:29 -0700903 warnx("Failed to get console input, ignoring console.");
Rusty Russell2e04ef72009-07-30 16:03:45 -0600904 /*
905 * For simplicity, dying threads kill the whole Launcher. So
906 * just nap here.
907 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600908 for (;;)
909 pause();
Rusty Russell8ca47e02007-07-19 01:49:29 -0700910 }
911
Rusty Russella91d74a2009-07-30 16:03:45 -0600912 /* Tell the Guest we used a buffer. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600913 add_used_and_trigger(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -0700914
Rusty Russell2e04ef72009-07-30 16:03:45 -0600915 /*
916 * Three ^C within one second? Exit.
Rusty Russelldde79782007-07-26 10:41:03 -0700917 *
Rusty Russell659a0e62009-06-12 22:27:10 -0600918 * This is such a hack, but works surprisingly well. Each ^C has to
919 * be in a buffer by itself, so they can't be too fast. But we check
920 * that we get three within about a second, so they can't be too
Rusty Russell2e04ef72009-07-30 16:03:45 -0600921 * slow.
922 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600923 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
Rusty Russell8ca47e02007-07-19 01:49:29 -0700924 abort->count = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -0600925 return;
926 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700927
Rusty Russell659a0e62009-06-12 22:27:10 -0600928 abort->count++;
929 if (abort->count == 1)
930 gettimeofday(&abort->start, NULL);
931 else if (abort->count == 3) {
932 struct timeval now;
933 gettimeofday(&now, NULL);
934 /* Kill all Launcher processes with SIGINT, like normal ^C */
935 if (now.tv_sec <= abort->start.tv_sec+1)
936 kill(0, SIGINT);
937 abort->count = 0;
938 }
Rusty Russell8ca47e02007-07-19 01:49:29 -0700939}
940
Rusty Russell659a0e62009-06-12 22:27:10 -0600941/* This is the routine which handles console output (ie. stdout). */
942static void console_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700943{
Rusty Russell17cbca22007-10-22 11:24:22 +1000944 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000945 struct iovec iov[vq->vring.num];
946
Rusty Russella91d74a2009-07-30 16:03:45 -0600947 /* We usually wait in here, for the Guest to give us something. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600948 head = wait_for_vq_desc(vq, iov, &out, &in);
949 if (in)
950 errx(1, "Input buffers in console output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600951
952 /* writev can return a partial write, so we loop here. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600953 while (!iov_empty(iov, out)) {
954 int len = writev(STDOUT_FILENO, iov, out);
Sakari Ailuse0377e22011-06-26 19:36:46 +0300955 if (len <= 0) {
956 warn("Write to stdout gave %i (%d)", len, errno);
957 break;
958 }
Rusty Russellc0316a92012-10-16 23:56:13 +1030959 iov_consume(iov, out, NULL, len);
Rusty Russell17cbca22007-10-22 11:24:22 +1000960 }
Rusty Russella91d74a2009-07-30 16:03:45 -0600961
962 /*
963 * We're finished with that buffer: if we're going to sleep,
964 * wait_for_vq_desc() will prod the Guest with an interrupt.
965 */
Rusty Russell38bc2b82009-06-12 22:27:11 -0600966 add_used(vq, head, 0);
Rusty Russella1618832008-07-29 09:58:35 -0500967}
968
Rusty Russelle1e72962007-10-25 15:02:50 +1000969/*
970 * The Network
971 *
972 * Handling output for network is also simple: we get all the output buffers
Rusty Russell659a0e62009-06-12 22:27:10 -0600973 * and write them to /dev/net/tun.
Rusty Russella6bd8e12008-03-28 11:05:53 -0500974 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600975struct net_info {
976 int tunfd;
977};
978
979static void net_output(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -0700980{
Rusty Russell659a0e62009-06-12 22:27:10 -0600981 struct net_info *net_info = vq->dev->priv;
982 unsigned int head, out, in;
Rusty Russell17cbca22007-10-22 11:24:22 +1000983 struct iovec iov[vq->vring.num];
984
Rusty Russella91d74a2009-07-30 16:03:45 -0600985 /* We usually wait in here for the Guest to give us a packet. */
Rusty Russell659a0e62009-06-12 22:27:10 -0600986 head = wait_for_vq_desc(vq, iov, &out, &in);
987 if (in)
988 errx(1, "Input buffers in net output queue?");
Rusty Russella91d74a2009-07-30 16:03:45 -0600989 /*
990 * Send the whole thing through to /dev/net/tun. It expects the exact
991 * same format: what a coincidence!
992 */
Rusty Russell659a0e62009-06-12 22:27:10 -0600993 if (writev(net_info->tunfd, iov, out) < 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +0300994 warnx("Write to tun failed (%d)?", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -0600995
996 /*
997 * Done with that one; wait_for_vq_desc() will send the interrupt if
998 * all packets are processed.
999 */
Rusty Russell38bc2b82009-06-12 22:27:11 -06001000 add_used(vq, head, 0);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001001}
1002
Rusty Russella91d74a2009-07-30 16:03:45 -06001003/*
1004 * Handling network input is a bit trickier, because I've tried to optimize it.
1005 *
1006 * First we have a helper routine which tells is if from this file descriptor
1007 * (ie. the /dev/net/tun device) will block:
1008 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001009static bool will_block(int fd)
1010{
1011 fd_set fdset;
1012 struct timeval zero = { 0, 0 };
1013 FD_ZERO(&fdset);
1014 FD_SET(fd, &fdset);
1015 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
1016}
1017
Rusty Russella91d74a2009-07-30 16:03:45 -06001018/*
1019 * This handles packets coming in from the tun device to our Guest. Like all
1020 * service routines, it gets called again as soon as it returns, so you don't
1021 * see a while(1) loop here.
1022 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001023static void net_input(struct virtqueue *vq)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001024{
Rusty Russell8ca47e02007-07-19 01:49:29 -07001025 int len;
Rusty Russell659a0e62009-06-12 22:27:10 -06001026 unsigned int head, out, in;
1027 struct iovec iov[vq->vring.num];
1028 struct net_info *net_info = vq->dev->priv;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001029
Rusty Russella91d74a2009-07-30 16:03:45 -06001030 /*
1031 * Get a descriptor to write an incoming packet into. This will also
1032 * send an interrupt if they're out of descriptors.
1033 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001034 head = wait_for_vq_desc(vq, iov, &out, &in);
1035 if (out)
1036 errx(1, "Output buffers in net input queue?");
Rusty Russell4a8962e2009-06-12 22:27:12 -06001037
Rusty Russella91d74a2009-07-30 16:03:45 -06001038 /*
1039 * If it looks like we'll block reading from the tun device, send them
1040 * an interrupt.
1041 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001042 if (vq->pending_used && will_block(net_info->tunfd))
1043 trigger_irq(vq);
1044
Rusty Russella91d74a2009-07-30 16:03:45 -06001045 /*
1046 * Read in the packet. This is where we normally wait (when there's no
1047 * incoming network traffic).
1048 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001049 len = readv(net_info->tunfd, iov, in);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001050 if (len <= 0)
Sakari Ailuse0377e22011-06-26 19:36:46 +03001051 warn("Failed to read from tun (%d).", errno);
Rusty Russella91d74a2009-07-30 16:03:45 -06001052
1053 /*
1054 * Mark that packet buffer as used, but don't interrupt here. We want
1055 * to wait until we've done as much work as we can.
1056 */
Rusty Russell4a8962e2009-06-12 22:27:12 -06001057 add_used(vq, head, len);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001058}
Rusty Russella91d74a2009-07-30 16:03:45 -06001059/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07001060
Rusty Russella91d74a2009-07-30 16:03:45 -06001061/* This is the helper to create threads: run the service routine in a loop. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001062static int do_thread(void *_vq)
Rusty Russell56ae43d2007-10-22 11:24:23 +10001063{
Rusty Russell659a0e62009-06-12 22:27:10 -06001064 struct virtqueue *vq = _vq;
1065
1066 for (;;)
1067 vq->service(vq);
1068 return 0;
Rusty Russell56ae43d2007-10-22 11:24:23 +10001069}
1070
Rusty Russell2e04ef72009-07-30 16:03:45 -06001071/*
1072 * When a child dies, we kill our entire process group with SIGTERM. This
1073 * also has the side effect that the shell restores the console for us!
1074 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001075static void kill_launcher(int signal)
Rusty Russell5dae7852008-07-29 09:58:35 -05001076{
Rusty Russell659a0e62009-06-12 22:27:10 -06001077 kill(0, SIGTERM);
1078}
1079
1080static void reset_device(struct device *dev)
1081{
1082 struct virtqueue *vq;
1083
1084 verbose("Resetting device %s\n", dev->name);
1085
1086 /* Clear any features they've acked. */
1087 memset(get_feature_bits(dev) + dev->feature_len, 0, dev->feature_len);
1088
1089 /* We're going to be explicitly killing threads, so ignore them. */
1090 signal(SIGCHLD, SIG_IGN);
1091
1092 /* Zero out the virtqueues, get rid of their threads */
1093 for (vq = dev->vq; vq; vq = vq->next) {
1094 if (vq->thread != (pid_t)-1) {
1095 kill(vq->thread, SIGTERM);
1096 waitpid(vq->thread, NULL, 0);
1097 vq->thread = (pid_t)-1;
1098 }
1099 memset(vq->vring.desc, 0,
1100 vring_size(vq->config.num, LGUEST_VRING_ALIGN));
1101 lg_last_avail(vq) = 0;
1102 }
1103 dev->running = false;
1104
1105 /* Now we care if threads die. */
1106 signal(SIGCHLD, (void *)kill_launcher);
1107}
1108
Rusty Russella91d74a2009-07-30 16:03:45 -06001109/*L:216
1110 * This actually creates the thread which services the virtqueue for a device.
1111 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001112static void create_thread(struct virtqueue *vq)
1113{
Rusty Russell2e04ef72009-07-30 16:03:45 -06001114 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06001115 * Create stack for thread. Since the stack grows upwards, we point
1116 * the stack pointer to the end of this region.
Rusty Russell2e04ef72009-07-30 16:03:45 -06001117 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001118 char *stack = malloc(32768);
1119 unsigned long args[] = { LHREQ_EVENTFD,
1120 vq->config.pfn*getpagesize(), 0 };
1121
1122 /* Create a zero-initialized eventfd. */
1123 vq->eventfd = eventfd(0, 0);
1124 if (vq->eventfd < 0)
1125 err(1, "Creating eventfd");
1126 args[2] = vq->eventfd;
1127
Rusty Russella91d74a2009-07-30 16:03:45 -06001128 /*
1129 * Attach an eventfd to this virtqueue: it will go off when the Guest
1130 * does an LHCALL_NOTIFY for this vq.
1131 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001132 if (write(lguest_fd, &args, sizeof(args)) != 0)
1133 err(1, "Attaching eventfd");
1134
Rusty Russella91d74a2009-07-30 16:03:45 -06001135 /*
1136 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1137 * we get a signal if it dies.
1138 */
Rusty Russell659a0e62009-06-12 22:27:10 -06001139 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1140 if (vq->thread == (pid_t)-1)
1141 err(1, "Creating clone");
Rusty Russella91d74a2009-07-30 16:03:45 -06001142
1143 /* We close our local copy now the child has it. */
Rusty Russell659a0e62009-06-12 22:27:10 -06001144 close(vq->eventfd);
1145}
1146
1147static void start_device(struct device *dev)
1148{
1149 unsigned int i;
1150 struct virtqueue *vq;
1151
1152 verbose("Device %s OK: offered", dev->name);
1153 for (i = 0; i < dev->feature_len; i++)
1154 verbose(" %02x", get_feature_bits(dev)[i]);
1155 verbose(", accepted");
1156 for (i = 0; i < dev->feature_len; i++)
1157 verbose(" %02x", get_feature_bits(dev)
1158 [dev->feature_len+i]);
1159
1160 for (vq = dev->vq; vq; vq = vq->next) {
1161 if (vq->service)
1162 create_thread(vq);
1163 }
1164 dev->running = true;
1165}
1166
1167static void cleanup_devices(void)
1168{
1169 struct device *dev;
1170
1171 for (dev = devices.dev; dev; dev = dev->next)
1172 reset_device(dev);
1173
1174 /* If we saved off the original terminal settings, restore them now. */
1175 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1176 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
Rusty Russell5dae7852008-07-29 09:58:35 -05001177}
1178
Rusty Russella007a752008-05-02 21:50:53 -05001179/* When the Guest tells us they updated the status field, we handle it. */
1180static void update_device_status(struct device *dev)
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001181{
Rusty Russell659a0e62009-06-12 22:27:10 -06001182 /* A zero status is a reset, otherwise it's a set of flags. */
1183 if (dev->desc->status == 0)
1184 reset_device(dev);
1185 else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
Rusty Russella007a752008-05-02 21:50:53 -05001186 warnx("Device %s configuration FAILED", dev->name);
Rusty Russell659a0e62009-06-12 22:27:10 -06001187 if (dev->running)
1188 reset_device(dev);
Rusty Russell3c3ed482011-07-22 14:39:49 +09301189 } else {
1190 if (dev->running)
1191 err(1, "Device %s features finalized twice", dev->name);
1192 start_device(dev);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001193 }
1194}
1195
Rusty Russella91d74a2009-07-30 16:03:45 -06001196/*L:215
1197 * This is the generic routine we call when the Guest uses LHCALL_NOTIFY. In
1198 * particular, it's used to notify us of device status changes during boot.
1199 */
Rusty Russell56739c802009-06-12 22:26:59 -06001200static void handle_output(unsigned long addr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07001201{
1202 struct device *i;
Rusty Russell8ca47e02007-07-19 01:49:29 -07001203
Rusty Russell659a0e62009-06-12 22:27:10 -06001204 /* Check each device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001205 for (i = devices.dev; i; i = i->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001206 struct virtqueue *vq;
1207
Rusty Russella91d74a2009-07-30 16:03:45 -06001208 /*
1209 * Notifications to device descriptors mean they updated the
1210 * device status.
1211 */
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001212 if (from_guest_phys(addr) == i->desc) {
Rusty Russella007a752008-05-02 21:50:53 -05001213 update_device_status(i);
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001214 return;
1215 }
1216
Rusty Russell3c3ed482011-07-22 14:39:49 +09301217 /* Devices should not be used before features are finalized. */
Rusty Russell17cbca22007-10-22 11:24:22 +10001218 for (vq = i->vq; vq; vq = vq->next) {
Rusty Russell659a0e62009-06-12 22:27:10 -06001219 if (addr != vq->config.pfn*getpagesize())
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05001220 continue;
Rusty Russell3c3ed482011-07-22 14:39:49 +09301221 errx(1, "Notification on %s before setup!", i->name);
Rusty Russell8ca47e02007-07-19 01:49:29 -07001222 }
1223 }
Rusty Russelldde79782007-07-26 10:41:03 -07001224
Rusty Russell2e04ef72009-07-30 16:03:45 -06001225 /*
1226 * Early console write is done using notify on a nul-terminated string
1227 * in Guest memory. It's also great for hacking debugging messages
1228 * into a Guest.
1229 */
Rusty Russell17cbca22007-10-22 11:24:22 +10001230 if (addr >= guest_limit)
1231 errx(1, "Bad NOTIFY %#lx", addr);
1232
1233 write(STDOUT_FILENO, from_guest_phys(addr),
1234 strnlen(from_guest_phys(addr), guest_limit - addr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07001235}
1236
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301237/*L:217
1238 * We do PCI. This is mainly done to let us test the kernel virtio PCI
1239 * code.
1240 */
1241
Rusty Russell8e709462015-02-11 15:15:12 +10301242/* Linux expects a PCI host bridge: ours is a dummy, and first on the bus. */
1243static struct device pci_host_bridge;
1244
1245static void init_pci_host_bridge(void)
1246{
1247 pci_host_bridge.name = "PCI Host Bridge";
1248 pci_host_bridge.config.class = 0x06; /* bridge */
1249 pci_host_bridge.config.subclass = 0; /* host bridge */
1250 devices.pci[0] = &pci_host_bridge;
1251}
1252
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301253/* The IO ports used to read the PCI config space. */
1254#define PCI_CONFIG_ADDR 0xCF8
1255#define PCI_CONFIG_DATA 0xCFC
1256
1257/*
1258 * Not really portable, but does help readability: this is what the Guest
1259 * writes to the PCI_CONFIG_ADDR IO port.
1260 */
1261union pci_config_addr {
1262 struct {
1263 unsigned mbz: 2;
1264 unsigned offset: 6;
1265 unsigned funcnum: 3;
1266 unsigned devnum: 5;
1267 unsigned busnum: 8;
1268 unsigned reserved: 7;
1269 unsigned enabled : 1;
1270 } bits;
1271 u32 val;
1272};
1273
1274/*
1275 * We cache what they wrote to the address port, so we know what they're
1276 * talking about when they access the data port.
1277 */
1278static union pci_config_addr pci_config_addr;
1279
1280static struct device *find_pci_device(unsigned int index)
1281{
1282 return devices.pci[index];
1283}
1284
1285/* PCI can do 1, 2 and 4 byte reads; we handle that here. */
1286static void ioread(u16 off, u32 v, u32 mask, u32 *val)
1287{
1288 assert(off < 4);
1289 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1290 *val = (v >> (off * 8)) & mask;
1291}
1292
1293/* PCI can do 1, 2 and 4 byte writes; we handle that here. */
1294static void iowrite(u16 off, u32 v, u32 mask, u32 *dst)
1295{
1296 assert(off < 4);
1297 assert(mask == 0xFF || mask == 0xFFFF || mask == 0xFFFFFFFF);
1298 *dst &= ~(mask << (off * 8));
1299 *dst |= (v & mask) << (off * 8);
1300}
1301
1302/*
1303 * Where PCI_CONFIG_DATA accesses depends on the previous write to
1304 * PCI_CONFIG_ADDR.
1305 */
1306static struct device *dev_and_reg(u32 *reg)
1307{
1308 if (!pci_config_addr.bits.enabled)
1309 return NULL;
1310
1311 if (pci_config_addr.bits.funcnum != 0)
1312 return NULL;
1313
1314 if (pci_config_addr.bits.busnum != 0)
1315 return NULL;
1316
1317 if (pci_config_addr.bits.offset * 4 >= sizeof(struct pci_config))
1318 return NULL;
1319
1320 *reg = pci_config_addr.bits.offset;
1321 return find_pci_device(pci_config_addr.bits.devnum);
1322}
1323
1324/* Is this accessing the PCI config address port?. */
1325static bool is_pci_addr_port(u16 port)
1326{
1327 return port >= PCI_CONFIG_ADDR && port < PCI_CONFIG_ADDR + 4;
1328}
1329
1330static bool pci_addr_iowrite(u16 port, u32 mask, u32 val)
1331{
1332 iowrite(port - PCI_CONFIG_ADDR, val, mask,
1333 &pci_config_addr.val);
1334 verbose("PCI%s: %#x/%x: bus %u dev %u func %u reg %u\n",
1335 pci_config_addr.bits.enabled ? "" : " DISABLED",
1336 val, mask,
1337 pci_config_addr.bits.busnum,
1338 pci_config_addr.bits.devnum,
1339 pci_config_addr.bits.funcnum,
1340 pci_config_addr.bits.offset);
1341 return true;
1342}
1343
1344static void pci_addr_ioread(u16 port, u32 mask, u32 *val)
1345{
1346 ioread(port - PCI_CONFIG_ADDR, pci_config_addr.val, mask, val);
1347}
1348
1349/* Is this accessing the PCI config data port?. */
1350static bool is_pci_data_port(u16 port)
1351{
1352 return port >= PCI_CONFIG_DATA && port < PCI_CONFIG_DATA + 4;
1353}
1354
1355static bool pci_data_iowrite(u16 port, u32 mask, u32 val)
1356{
1357 u32 reg, portoff;
1358 struct device *d = dev_and_reg(&reg);
1359
1360 /* Complain if they don't belong to a device. */
1361 if (!d)
1362 return false;
1363
1364 /* They can do 1 byte writes, etc. */
1365 portoff = port - PCI_CONFIG_DATA;
1366
1367 /*
1368 * PCI uses a weird way to determine the BAR size: the OS
1369 * writes all 1's, and sees which ones stick.
1370 */
1371 if (&d->config_words[reg] == &d->config.bar[0]) {
1372 int i;
1373
1374 iowrite(portoff, val, mask, &d->config.bar[0]);
1375 for (i = 0; (1 << i) < d->mmio_size; i++)
1376 d->config.bar[0] &= ~(1 << i);
1377 return true;
1378 } else if ((&d->config_words[reg] > &d->config.bar[0]
1379 && &d->config_words[reg] <= &d->config.bar[6])
1380 || &d->config_words[reg] == &d->config.expansion_rom_addr) {
1381 /* Allow writing to any other BAR, or expansion ROM */
1382 iowrite(portoff, val, mask, &d->config_words[reg]);
1383 return true;
1384 /* We let them overide latency timer and cacheline size */
1385 } else if (&d->config_words[reg] == (void *)&d->config.cacheline_size) {
1386 /* Only let them change the first two fields. */
1387 if (mask == 0xFFFFFFFF)
1388 mask = 0xFFFF;
1389 iowrite(portoff, val, mask, &d->config_words[reg]);
1390 return true;
1391 } else if (&d->config_words[reg] == (void *)&d->config.command
1392 && mask == 0xFFFF) {
1393 /* Ignore command writes. */
1394 return true;
1395 }
1396
1397 /* Complain about other writes. */
1398 return false;
1399}
1400
1401static void pci_data_ioread(u16 port, u32 mask, u32 *val)
1402{
1403 u32 reg;
1404 struct device *d = dev_and_reg(&reg);
1405
1406 if (!d)
1407 return;
1408 ioread(port - PCI_CONFIG_DATA, d->config_words[reg], mask, val);
1409}
1410
Rusty Russellc565650b2015-02-11 15:15:10 +10301411/*L:216
1412 * This is where we emulate a handful of Guest instructions. It's ugly
1413 * and we used to do it in the kernel but it grew over time.
1414 */
1415
1416/*
1417 * We use the ptrace syscall's pt_regs struct to talk about registers
1418 * to lguest: these macros convert the names to the offsets.
1419 */
1420#define getreg(name) getreg_off(offsetof(struct user_regs_struct, name))
1421#define setreg(name, val) \
1422 setreg_off(offsetof(struct user_regs_struct, name), (val))
1423
1424static u32 getreg_off(size_t offset)
1425{
1426 u32 r;
1427 unsigned long args[] = { LHREQ_GETREG, offset };
1428
1429 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1430 err(1, "Getting register %u", offset);
1431 if (pread(lguest_fd, &r, sizeof(r), cpu_id) != sizeof(r))
1432 err(1, "Reading register %u", offset);
1433
1434 return r;
1435}
1436
1437static void setreg_off(size_t offset, u32 val)
1438{
1439 unsigned long args[] = { LHREQ_SETREG, offset, val };
1440
1441 if (pwrite(lguest_fd, args, sizeof(args), cpu_id) < 0)
1442 err(1, "Setting register %u", offset);
1443}
1444
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301445/* Get register by instruction encoding */
1446static u32 getreg_num(unsigned regnum, u32 mask)
1447{
1448 /* 8 bit ops use regnums 4-7 for high parts of word */
1449 if (mask == 0xFF && (regnum & 0x4))
1450 return getreg_num(regnum & 0x3, 0xFFFF) >> 8;
1451
1452 switch (regnum) {
1453 case 0: return getreg(eax) & mask;
1454 case 1: return getreg(ecx) & mask;
1455 case 2: return getreg(edx) & mask;
1456 case 3: return getreg(ebx) & mask;
1457 case 4: return getreg(esp) & mask;
1458 case 5: return getreg(ebp) & mask;
1459 case 6: return getreg(esi) & mask;
1460 case 7: return getreg(edi) & mask;
1461 }
1462 abort();
1463}
1464
1465/* Set register by instruction encoding */
1466static void setreg_num(unsigned regnum, u32 val, u32 mask)
1467{
1468 /* Don't try to set bits out of range */
1469 assert(~(val & ~mask));
1470
1471 /* 8 bit ops use regnums 4-7 for high parts of word */
1472 if (mask == 0xFF && (regnum & 0x4)) {
1473 /* Construct the 16 bits we want. */
1474 val = (val << 8) | getreg_num(regnum & 0x3, 0xFF);
1475 setreg_num(regnum & 0x3, val, 0xFFFF);
1476 return;
1477 }
1478
1479 switch (regnum) {
1480 case 0: setreg(eax, val | (getreg(eax) & ~mask)); return;
1481 case 1: setreg(ecx, val | (getreg(ecx) & ~mask)); return;
1482 case 2: setreg(edx, val | (getreg(edx) & ~mask)); return;
1483 case 3: setreg(ebx, val | (getreg(ebx) & ~mask)); return;
1484 case 4: setreg(esp, val | (getreg(esp) & ~mask)); return;
1485 case 5: setreg(ebp, val | (getreg(ebp) & ~mask)); return;
1486 case 6: setreg(esi, val | (getreg(esi) & ~mask)); return;
1487 case 7: setreg(edi, val | (getreg(edi) & ~mask)); return;
1488 }
1489 abort();
1490}
1491
1492/* Get bytes of displacement appended to instruction, from r/m encoding */
1493static u32 insn_displacement_len(u8 mod_reg_rm)
1494{
1495 /* Switch on the mod bits */
1496 switch (mod_reg_rm >> 6) {
1497 case 0:
1498 /* If mod == 0, and r/m == 101, 16-bit displacement follows */
1499 if ((mod_reg_rm & 0x7) == 0x5)
1500 return 2;
1501 /* Normally, mod == 0 means no literal displacement */
1502 return 0;
1503 case 1:
1504 /* One byte displacement */
1505 return 1;
1506 case 2:
1507 /* Four byte displacement */
1508 return 4;
1509 case 3:
1510 /* Register mode */
1511 return 0;
1512 }
1513 abort();
1514}
1515
Rusty Russellc565650b2015-02-11 15:15:10 +10301516static void emulate_insn(const u8 insn[])
1517{
1518 unsigned long args[] = { LHREQ_TRAP, 13 };
1519 unsigned int insnlen = 0, in = 0, small_operand = 0, byte_access;
1520 unsigned int eax, port, mask;
1521 /*
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301522 * Default is to return all-ones on IO port reads, which traditionally
Rusty Russellc565650b2015-02-11 15:15:10 +10301523 * means "there's nothing there".
1524 */
1525 u32 val = 0xFFFFFFFF;
1526
1527 /*
1528 * This must be the Guest kernel trying to do something, not userspace!
1529 * The bottom two bits of the CS segment register are the privilege
1530 * level.
1531 */
1532 if ((getreg(xcs) & 3) != 0x1)
1533 goto no_emulate;
1534
1535 /* Decoding x86 instructions is icky. */
1536
1537 /*
1538 * Around 2.6.33, the kernel started using an emulation for the
1539 * cmpxchg8b instruction in early boot on many configurations. This
1540 * code isn't paravirtualized, and it tries to disable interrupts.
1541 * Ignore it, which will Mostly Work.
1542 */
1543 if (insn[insnlen] == 0xfa) {
1544 /* "cli", or Clear Interrupt Enable instruction. Skip it. */
1545 insnlen = 1;
1546 goto skip_insn;
1547 }
1548
1549 /*
1550 * 0x66 is an "operand prefix". It means a 16, not 32 bit in/out.
1551 */
1552 if (insn[insnlen] == 0x66) {
1553 small_operand = 1;
1554 /* The instruction is 1 byte so far, read the next byte. */
1555 insnlen = 1;
1556 }
1557
1558 /* If the lower bit isn't set, it's a single byte access */
1559 byte_access = !(insn[insnlen] & 1);
1560
1561 /*
1562 * Now we can ignore the lower bit and decode the 4 opcodes
1563 * we need to emulate.
1564 */
1565 switch (insn[insnlen] & 0xFE) {
1566 case 0xE4: /* in <next byte>,%al */
1567 port = insn[insnlen+1];
1568 insnlen += 2;
1569 in = 1;
1570 break;
1571 case 0xEC: /* in (%dx),%al */
1572 port = getreg(edx) & 0xFFFF;
1573 insnlen += 1;
1574 in = 1;
1575 break;
1576 case 0xE6: /* out %al,<next byte> */
1577 port = insn[insnlen+1];
1578 insnlen += 2;
1579 break;
1580 case 0xEE: /* out %al,(%dx) */
1581 port = getreg(edx) & 0xFFFF;
1582 insnlen += 1;
1583 break;
1584 default:
1585 /* OK, we don't know what this is, can't emulate. */
1586 goto no_emulate;
1587 }
1588
1589 /* Set a mask of the 1, 2 or 4 bytes, depending on size of IO */
1590 if (byte_access)
1591 mask = 0xFF;
1592 else if (small_operand)
1593 mask = 0xFFFF;
1594 else
1595 mask = 0xFFFFFFFF;
1596
1597 /*
1598 * If it was an "IN" instruction, they expect the result to be read
1599 * into %eax, so we change %eax.
1600 */
1601 eax = getreg(eax);
1602
1603 if (in) {
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301604 /* This is the PS/2 keyboard status; 1 means ready for output */
1605 if (port == 0x64)
1606 val = 1;
1607 else if (is_pci_addr_port(port))
1608 pci_addr_ioread(port, mask, &val);
1609 else if (is_pci_data_port(port))
1610 pci_data_ioread(port, mask, &val);
1611
Rusty Russellc565650b2015-02-11 15:15:10 +10301612 /* Clear the bits we're about to read */
1613 eax &= ~mask;
1614 /* Copy bits in from val. */
1615 eax |= val & mask;
1616 /* Now update the register. */
1617 setreg(eax, eax);
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301618 } else {
1619 if (is_pci_addr_port(port)) {
1620 if (!pci_addr_iowrite(port, mask, eax))
1621 goto bad_io;
1622 } else if (is_pci_data_port(port)) {
1623 if (!pci_data_iowrite(port, mask, eax))
1624 goto bad_io;
1625 }
1626 /* There are many other ports, eg. CMOS clock, serial
1627 * and parallel ports, so we ignore them all. */
Rusty Russellc565650b2015-02-11 15:15:10 +10301628 }
1629
1630 verbose("IO %s of %x to %u: %#08x\n",
1631 in ? "IN" : "OUT", mask, port, eax);
1632skip_insn:
1633 /* Finally, we've "done" the instruction, so move past it. */
1634 setreg(eip, getreg(eip) + insnlen);
1635 return;
1636
Rusty Russelld7fbf6e2015-02-11 15:15:11 +10301637bad_io:
1638 warnx("Attempt to %s port %u (%#x mask)",
1639 in ? "read from" : "write to", port, mask);
1640
Rusty Russellc565650b2015-02-11 15:15:10 +10301641no_emulate:
1642 /* Inject trap into Guest. */
1643 if (write(lguest_fd, args, sizeof(args)) < 0)
1644 err(1, "Reinjecting trap 13 for fault at %#x", getreg(eip));
1645}
1646
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301647static struct device *find_mmio_region(unsigned long paddr, u32 *off)
1648{
1649 unsigned int i;
1650
1651 for (i = 1; i < MAX_PCI_DEVICES; i++) {
1652 struct device *d = devices.pci[i];
1653
1654 if (!d)
1655 continue;
1656 if (paddr < d->mmio_addr)
1657 continue;
1658 if (paddr >= d->mmio_addr + d->mmio_size)
1659 continue;
1660 *off = paddr - d->mmio_addr;
1661 return d;
1662 }
1663 return NULL;
1664}
1665
Rusty Russell93153072015-02-11 15:15:11 +10301666/* FIXME: Use vq array. */
1667static struct virtqueue *vq_by_num(struct device *d, u32 num)
1668{
1669 struct virtqueue *vq = d->vq;
1670
1671 while (num-- && vq)
1672 vq = vq->next;
1673
1674 return vq;
1675}
1676
1677static void save_vq_config(const struct virtio_pci_common_cfg *cfg,
1678 struct virtqueue *vq)
1679{
1680 vq->pci_config = *cfg;
1681}
1682
1683static void restore_vq_config(struct virtio_pci_common_cfg *cfg,
1684 struct virtqueue *vq)
1685{
1686 /* Only restore the per-vq part */
1687 size_t off = offsetof(struct virtio_pci_common_cfg, queue_size);
1688
1689 memcpy((void *)cfg + off, (void *)&vq->pci_config + off,
1690 sizeof(*cfg) - off);
1691}
1692
1693/*
1694 * When they enable the virtqueue, we check that their setup is valid.
1695 */
1696static void enable_virtqueue(struct device *d, struct virtqueue *vq)
1697{
1698 /*
1699 * Create stack for thread. Since the stack grows upwards, we point
1700 * the stack pointer to the end of this region.
1701 */
1702 char *stack = malloc(32768);
1703
1704 /* Because lguest is 32 bit, all the descriptor high bits must be 0 */
1705 if (vq->pci_config.queue_desc_hi
1706 || vq->pci_config.queue_avail_hi
1707 || vq->pci_config.queue_used_hi)
1708 errx(1, "%s: invalid 64-bit queue address", d->name);
1709
1710 /* Initialize the virtqueue and check they're all in range. */
1711 vq->vring.num = vq->pci_config.queue_size;
1712 vq->vring.desc = check_pointer(vq->pci_config.queue_desc_lo,
1713 sizeof(*vq->vring.desc) * vq->vring.num);
1714 vq->vring.avail = check_pointer(vq->pci_config.queue_avail_lo,
1715 sizeof(*vq->vring.avail)
1716 + (sizeof(vq->vring.avail->ring[0])
1717 * vq->vring.num));
1718 vq->vring.used = check_pointer(vq->pci_config.queue_used_lo,
1719 sizeof(*vq->vring.used)
1720 + (sizeof(vq->vring.used->ring[0])
1721 * vq->vring.num));
1722
1723
1724 /* Create a zero-initialized eventfd. */
1725 vq->eventfd = eventfd(0, 0);
1726 if (vq->eventfd < 0)
1727 err(1, "Creating eventfd");
1728
1729 /*
1730 * CLONE_VM: because it has to access the Guest memory, and SIGCHLD so
1731 * we get a signal if it dies.
1732 */
1733 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1734 if (vq->thread == (pid_t)-1)
1735 err(1, "Creating clone");
1736}
1737
1738static void reset_pci_device(struct device *dev)
1739{
1740 /* FIXME */
1741}
1742
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301743static void emulate_mmio_write(struct device *d, u32 off, u32 val, u32 mask)
1744{
Rusty Russell93153072015-02-11 15:15:11 +10301745 struct virtqueue *vq;
1746
1747 switch (off) {
1748 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1749 if (val == 0)
1750 d->mmio->cfg.device_feature = d->features;
1751 else if (val == 1)
1752 d->mmio->cfg.device_feature = (d->features >> 32);
1753 else
1754 d->mmio->cfg.device_feature = 0;
1755 goto write_through32;
1756 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1757 if (val > 1)
1758 errx(1, "%s: Unexpected driver select %u",
1759 d->name, val);
1760 goto write_through32;
1761 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1762 if (d->mmio->cfg.guest_feature_select == 0) {
1763 d->features_accepted &= ~((u64)0xFFFFFFFF);
1764 d->features_accepted |= val;
1765 } else {
1766 assert(d->mmio->cfg.guest_feature_select == 1);
1767 d->features_accepted &= ((u64)0xFFFFFFFF << 32);
1768 d->features_accepted |= ((u64)val) << 32;
1769 }
1770 if (d->features_accepted & ~d->features)
1771 errx(1, "%s: over-accepted features %#llx of %#llx",
1772 d->name, d->features_accepted, d->features);
1773 goto write_through32;
1774 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1775 verbose("%s: device status -> %#x\n", d->name, val);
1776 if (val == 0)
1777 reset_pci_device(d);
1778 goto write_through8;
1779 case offsetof(struct virtio_pci_mmio, cfg.queue_select):
1780 vq = vq_by_num(d, val);
1781 /* Out of range? Return size 0 */
1782 if (!vq) {
1783 d->mmio->cfg.queue_size = 0;
1784 goto write_through16;
1785 }
1786 /* Save registers for old vq, if it was a valid vq */
1787 if (d->mmio->cfg.queue_size)
1788 save_vq_config(&d->mmio->cfg,
1789 vq_by_num(d, d->mmio->cfg.queue_select));
1790 /* Restore the registers for the queue they asked for */
1791 restore_vq_config(&d->mmio->cfg, vq);
1792 goto write_through16;
1793 case offsetof(struct virtio_pci_mmio, cfg.queue_size):
1794 if (val & (val-1))
1795 errx(1, "%s: invalid queue size %u\n", d->name, val);
1796 if (d->mmio->cfg.queue_enable)
1797 errx(1, "%s: changing queue size on live device",
1798 d->name);
1799 goto write_through16;
1800 case offsetof(struct virtio_pci_mmio, cfg.queue_msix_vector):
1801 errx(1, "%s: attempt to set MSIX vector to %u",
1802 d->name, val);
1803 case offsetof(struct virtio_pci_mmio, cfg.queue_enable):
1804 if (val != 1)
1805 errx(1, "%s: setting queue_enable to %u", d->name, val);
1806 d->mmio->cfg.queue_enable = val;
1807 save_vq_config(&d->mmio->cfg,
1808 vq_by_num(d, d->mmio->cfg.queue_select));
1809 enable_virtqueue(d, vq_by_num(d, d->mmio->cfg.queue_select));
1810 goto write_through16;
1811 case offsetof(struct virtio_pci_mmio, cfg.queue_notify_off):
1812 errx(1, "%s: attempt to write to queue_notify_off", d->name);
1813 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_lo):
1814 case offsetof(struct virtio_pci_mmio, cfg.queue_desc_hi):
1815 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_lo):
1816 case offsetof(struct virtio_pci_mmio, cfg.queue_avail_hi):
1817 case offsetof(struct virtio_pci_mmio, cfg.queue_used_lo):
1818 case offsetof(struct virtio_pci_mmio, cfg.queue_used_hi):
1819 if (d->mmio->cfg.queue_enable)
1820 errx(1, "%s: changing queue on live device",
1821 d->name);
1822 goto write_through32;
1823 case offsetof(struct virtio_pci_mmio, notify):
1824 vq = vq_by_num(d, val);
1825 if (!vq)
1826 errx(1, "Invalid vq notification on %u", val);
1827 /* Notify the process handling this vq by adding 1 to eventfd */
1828 write(vq->eventfd, "\1\0\0\0\0\0\0\0", 8);
1829 goto write_through16;
1830 case offsetof(struct virtio_pci_mmio, isr):
1831 errx(1, "%s: Unexpected write to isr", d->name);
1832 default:
1833 errx(1, "%s: Unexpected write to offset %u", d->name, off);
1834 }
1835
1836write_through32:
1837 if (mask != 0xFFFFFFFF) {
1838 errx(1, "%s: non-32-bit write to offset %u (%#x)",
1839 d->name, off, getreg(eip));
1840 return;
1841 }
1842 memcpy((char *)d->mmio + off, &val, 4);
1843 return;
1844
1845write_through16:
1846 if (mask != 0xFFFF)
1847 errx(1, "%s: non-16-bit (%#x) write to offset %u (%#x)",
1848 d->name, mask, off, getreg(eip));
1849 memcpy((char *)d->mmio + off, &val, 2);
1850 return;
1851
1852write_through8:
1853 if (mask != 0xFF)
1854 errx(1, "%s: non-8-bit write to offset %u (%#x)",
1855 d->name, off, getreg(eip));
1856 memcpy((char *)d->mmio + off, &val, 1);
1857 return;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301858}
1859
1860static u32 emulate_mmio_read(struct device *d, u32 off, u32 mask)
1861{
Rusty Russell93153072015-02-11 15:15:11 +10301862 u8 isr;
1863 u32 val = 0;
1864
1865 switch (off) {
1866 case offsetof(struct virtio_pci_mmio, cfg.device_feature_select):
1867 case offsetof(struct virtio_pci_mmio, cfg.device_feature):
1868 case offsetof(struct virtio_pci_mmio, cfg.guest_feature_select):
1869 case offsetof(struct virtio_pci_mmio, cfg.guest_feature):
1870 goto read_through32;
1871 case offsetof(struct virtio_pci_mmio, cfg.msix_config):
1872 errx(1, "%s: read of msix_config", d->name);
1873 case offsetof(struct virtio_pci_mmio, cfg.num_queues):
1874 goto read_through16;
1875 case offsetof(struct virtio_pci_mmio, cfg.device_status):
1876 case offsetof(struct virtio_pci_mmio, cfg.config_generation):
1877 goto read_through8;
1878 case offsetof(struct virtio_pci_mmio, notify):
1879 goto read_through16;
1880 case offsetof(struct virtio_pci_mmio, isr):
1881 if (mask != 0xFF)
1882 errx(1, "%s: non-8-bit read from offset %u (%#x)",
1883 d->name, off, getreg(eip));
1884 /* Read resets the isr */
1885 isr = d->mmio->isr;
1886 d->mmio->isr = 0;
1887 return isr;
1888 case offsetof(struct virtio_pci_mmio, padding):
1889 errx(1, "%s: read from padding (%#x)",
1890 d->name, getreg(eip));
1891 default:
1892 /* Read from device config space, beware unaligned overflow */
1893 if (off > d->mmio_size - 4)
1894 errx(1, "%s: read past end (%#x)",
1895 d->name, getreg(eip));
1896 if (mask == 0xFFFFFFFF)
1897 goto read_through32;
1898 else if (mask == 0xFFFF)
1899 goto read_through16;
1900 else
1901 goto read_through8;
1902 }
1903
1904read_through32:
1905 if (mask != 0xFFFFFFFF)
1906 errx(1, "%s: non-32-bit read to offset %u (%#x)",
1907 d->name, off, getreg(eip));
1908 memcpy(&val, (char *)d->mmio + off, 4);
1909 return val;
1910
1911read_through16:
1912 if (mask != 0xFFFF)
1913 errx(1, "%s: non-16-bit read to offset %u (%#x)",
1914 d->name, off, getreg(eip));
1915 memcpy(&val, (char *)d->mmio + off, 2);
1916 return val;
1917
1918read_through8:
1919 if (mask != 0xFF)
1920 errx(1, "%s: non-8-bit read to offset %u (%#x)",
1921 d->name, off, getreg(eip));
1922 memcpy(&val, (char *)d->mmio + off, 1);
1923 return val;
Rusty Russell6a54f9a2015-02-11 15:15:11 +10301924}
1925
1926static void emulate_mmio(unsigned long paddr, const u8 *insn)
1927{
1928 u32 val, off, mask = 0xFFFFFFFF, insnlen = 0;
1929 struct device *d = find_mmio_region(paddr, &off);
1930 unsigned long args[] = { LHREQ_TRAP, 14 };
1931
1932 if (!d) {
1933 warnx("MMIO touching %#08lx (not a device)", paddr);
1934 goto reinject;
1935 }
1936
1937 /* Prefix makes it a 16 bit op */
1938 if (insn[0] == 0x66) {
1939 mask = 0xFFFF;
1940 insnlen++;
1941 }
1942
1943 /* iowrite */
1944 if (insn[insnlen] == 0x89) {
1945 /* Next byte is r/m byte: bits 3-5 are register. */
1946 val = getreg_num((insn[insnlen+1] >> 3) & 0x7, mask);
1947 emulate_mmio_write(d, off, val, mask);
1948 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1949 } else if (insn[insnlen] == 0x8b) { /* ioread */
1950 /* Next byte is r/m byte: bits 3-5 are register. */
1951 val = emulate_mmio_read(d, off, mask);
1952 setreg_num((insn[insnlen+1] >> 3) & 0x7, val, mask);
1953 insnlen += 2 + insn_displacement_len(insn[insnlen+1]);
1954 } else if (insn[0] == 0x88) { /* 8-bit iowrite */
1955 mask = 0xff;
1956 /* Next byte is r/m byte: bits 3-5 are register. */
1957 val = getreg_num((insn[1] >> 3) & 0x7, mask);
1958 emulate_mmio_write(d, off, val, mask);
1959 insnlen = 2 + insn_displacement_len(insn[1]);
1960 } else if (insn[0] == 0x8a) { /* 8-bit ioread */
1961 mask = 0xff;
1962 val = emulate_mmio_read(d, off, mask);
1963 setreg_num((insn[1] >> 3) & 0x7, val, mask);
1964 insnlen = 2 + insn_displacement_len(insn[1]);
1965 } else {
1966 warnx("Unknown MMIO instruction touching %#08lx:"
1967 " %02x %02x %02x %02x at %u",
1968 paddr, insn[0], insn[1], insn[2], insn[3], getreg(eip));
1969 reinject:
1970 /* Inject trap into Guest. */
1971 if (write(lguest_fd, args, sizeof(args)) < 0)
1972 err(1, "Reinjecting trap 14 for fault at %#x",
1973 getreg(eip));
1974 return;
1975 }
1976
1977 /* Finally, we've "done" the instruction, so move past it. */
1978 setreg(eip, getreg(eip) + insnlen);
1979}
Rusty Russellc565650b2015-02-11 15:15:10 +10301980
Rusty Russelldde79782007-07-26 10:41:03 -07001981/*L:190
1982 * Device Setup
1983 *
1984 * All devices need a descriptor so the Guest knows it exists, and a "struct
1985 * device" so the Launcher can keep track of it. We have common helper
Rusty Russella6bd8e12008-03-28 11:05:53 -05001986 * routines to allocate and manage them.
1987 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001988
Rusty Russell2e04ef72009-07-30 16:03:45 -06001989/*
1990 * The layout of the device page is a "struct lguest_device_desc" followed by a
Rusty Russella586d4f2008-02-04 23:49:56 -05001991 * number of virtqueue descriptors, then two sets of feature bits, then an
1992 * array of configuration bytes. This routine returns the configuration
Rusty Russell2e04ef72009-07-30 16:03:45 -06001993 * pointer.
1994 */
Rusty Russella586d4f2008-02-04 23:49:56 -05001995static u8 *device_config(const struct device *dev)
1996{
1997 return (void *)(dev->desc + 1)
Rusty Russell713b15b2009-06-12 22:26:58 -06001998 + dev->num_vq * sizeof(struct lguest_vqconfig)
1999 + dev->feature_len * 2;
Rusty Russella586d4f2008-02-04 23:49:56 -05002000}
2001
Rusty Russell2e04ef72009-07-30 16:03:45 -06002002/*
2003 * This routine allocates a new "struct lguest_device_desc" from descriptor
Rusty Russella586d4f2008-02-04 23:49:56 -05002004 * table page just above the Guest's normal memory. It returns a pointer to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002005 * that descriptor.
2006 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002007static struct lguest_device_desc *new_dev_desc(u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002008{
Rusty Russella586d4f2008-02-04 23:49:56 -05002009 struct lguest_device_desc d = { .type = type };
2010 void *p;
2011
2012 /* Figure out where the next device config is, based on the last one. */
2013 if (devices.lastdev)
2014 p = device_config(devices.lastdev)
2015 + devices.lastdev->desc->config_len;
2016 else
2017 p = devices.descpage;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002018
Rusty Russell17cbca22007-10-22 11:24:22 +10002019 /* We only have one page for all the descriptors. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002020 if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
Rusty Russell17cbca22007-10-22 11:24:22 +10002021 errx(1, "Too many devices");
2022
Rusty Russella586d4f2008-02-04 23:49:56 -05002023 /* p might not be aligned, so we memcpy in. */
2024 return memcpy(p, &d, sizeof(d));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002025}
2026
Rusty Russell2e04ef72009-07-30 16:03:45 -06002027/*
2028 * Each device descriptor is followed by the description of its virtqueues. We
2029 * specify how many descriptors the virtqueue is to have.
2030 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002031static void add_virtqueue(struct device *dev, unsigned int num_descs,
Rusty Russell659a0e62009-06-12 22:27:10 -06002032 void (*service)(struct virtqueue *))
Rusty Russell17cbca22007-10-22 11:24:22 +10002033{
2034 unsigned int pages;
2035 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2036 void *p;
2037
Rusty Russella6bd8e12008-03-28 11:05:53 -05002038 /* First we need some memory for this virtqueue. */
Rusty Russell2966af72008-12-30 09:25:58 -06002039 pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
Rusty Russell42b36cc2007-11-12 13:39:18 +11002040 / getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002041 p = get_pages(pages);
2042
Rusty Russelld1c856e2007-11-19 11:20:40 -05002043 /* Initialize the virtqueue */
2044 vq->next = NULL;
2045 vq->last_avail_idx = 0;
2046 vq->dev = dev;
Rusty Russella91d74a2009-07-30 16:03:45 -06002047
2048 /*
2049 * This is the routine the service thread will run, and its Process ID
2050 * once it's running.
2051 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002052 vq->service = service;
2053 vq->thread = (pid_t)-1;
Rusty Russelld1c856e2007-11-19 11:20:40 -05002054
Rusty Russell17cbca22007-10-22 11:24:22 +10002055 /* Initialize the configuration. */
2056 vq->config.num = num_descs;
2057 vq->config.irq = devices.next_irq++;
2058 vq->config.pfn = to_guest_phys(p) / getpagesize();
2059
2060 /* Initialize the vring. */
Rusty Russell2966af72008-12-30 09:25:58 -06002061 vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
Rusty Russell17cbca22007-10-22 11:24:22 +10002062
Rusty Russell2e04ef72009-07-30 16:03:45 -06002063 /*
2064 * Append virtqueue to this device's descriptor. We use
Rusty Russella586d4f2008-02-04 23:49:56 -05002065 * device_config() to get the end of the device's current virtqueues;
2066 * we check that we haven't added any config or feature information
Rusty Russell2e04ef72009-07-30 16:03:45 -06002067 * yet, otherwise we'd be overwriting them.
2068 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002069 assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
2070 memcpy(device_config(dev), &vq->config, sizeof(vq->config));
Rusty Russell713b15b2009-06-12 22:26:58 -06002071 dev->num_vq++;
Rusty Russella586d4f2008-02-04 23:49:56 -05002072 dev->desc->num_vq++;
2073
2074 verbose("Virtqueue page %#lx\n", to_guest_phys(p));
Rusty Russell17cbca22007-10-22 11:24:22 +10002075
Rusty Russell2e04ef72009-07-30 16:03:45 -06002076 /*
2077 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2078 * second.
2079 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002080 for (i = &dev->vq; *i; i = &(*i)->next);
2081 *i = vq;
Rusty Russell17cbca22007-10-22 11:24:22 +10002082}
2083
Rusty Russell93153072015-02-11 15:15:11 +10302084static void add_pci_virtqueue(struct device *dev,
2085 void (*service)(struct virtqueue *))
2086{
2087 struct virtqueue **i, *vq = malloc(sizeof(*vq));
2088
2089 /* Initialize the virtqueue */
2090 vq->next = NULL;
2091 vq->last_avail_idx = 0;
2092 vq->dev = dev;
2093
2094 /*
2095 * This is the routine the service thread will run, and its Process ID
2096 * once it's running.
2097 */
2098 vq->service = service;
2099 vq->thread = (pid_t)-1;
2100
2101 /* Initialize the configuration. */
2102 vq->pci_config.queue_size = VIRTQUEUE_NUM;
2103 vq->pci_config.queue_enable = 0;
2104 vq->pci_config.queue_notify_off = 0;
2105
2106 /* Add one to the number of queues */
2107 vq->dev->mmio->cfg.num_queues++;
2108
2109 /* FIXME: Do irq per virtqueue, not per device. */
2110 vq->config.irq = vq->dev->config.irq_line;
2111
2112 /*
2113 * Add to tail of list, so dev->vq is first vq, dev->vq->next is
2114 * second.
2115 */
2116 for (i = &dev->vq; *i; i = &(*i)->next);
2117 *i = vq;
2118}
2119
Rusty Russell2e04ef72009-07-30 16:03:45 -06002120/*
2121 * The first half of the feature bitmask is for us to advertise features. The
2122 * second half is for the Guest to accept features.
2123 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002124static void add_feature(struct device *dev, unsigned bit)
2125{
Rusty Russell6e5aa7e2008-02-04 23:50:03 -05002126 u8 *features = get_feature_bits(dev);
Rusty Russella586d4f2008-02-04 23:49:56 -05002127
2128 /* We can't extend the feature bits once we've added config bytes */
2129 if (dev->desc->feature_len <= bit / CHAR_BIT) {
2130 assert(dev->desc->config_len == 0);
Rusty Russell713b15b2009-06-12 22:26:58 -06002131 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
Rusty Russella586d4f2008-02-04 23:49:56 -05002132 }
2133
Rusty Russella586d4f2008-02-04 23:49:56 -05002134 features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
2135}
2136
Rusty Russell93153072015-02-11 15:15:11 +10302137static void add_pci_feature(struct device *dev, unsigned bit)
2138{
2139 dev->features |= (1ULL << bit);
2140}
2141
Rusty Russell2e04ef72009-07-30 16:03:45 -06002142/*
2143 * This routine sets the configuration fields for an existing device's
Rusty Russella586d4f2008-02-04 23:49:56 -05002144 * descriptor. It only works for the last device, but that's OK because that's
Rusty Russell2e04ef72009-07-30 16:03:45 -06002145 * how we use it.
2146 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002147static void set_config(struct device *dev, unsigned len, const void *conf)
2148{
2149 /* Check we haven't overflowed our single page. */
2150 if (device_config(dev) + len > devices.descpage + getpagesize())
2151 errx(1, "Too many devices");
2152
2153 /* Copy in the config information, and store the length. */
2154 memcpy(device_config(dev), conf, len);
2155 dev->desc->config_len = len;
Rusty Russell8ef562d2009-07-30 16:03:43 -06002156
2157 /* Size must fit in config_len field (8 bits)! */
2158 assert(dev->desc->config_len == len);
Rusty Russella586d4f2008-02-04 23:49:56 -05002159}
2160
Rusty Russell93153072015-02-11 15:15:11 +10302161/* For devices with no config. */
2162static void no_device_config(struct device *dev)
2163{
2164 dev->mmio_addr = get_mmio_region(dev->mmio_size);
2165
2166 dev->config.bar[0] = dev->mmio_addr;
2167 /* Bottom 4 bits must be zero */
2168 assert(~(dev->config.bar[0] & 0xF));
2169}
2170
2171/* This puts the device config into BAR0 */
2172static void set_device_config(struct device *dev, const void *conf, size_t len)
2173{
2174 /* Set up BAR 0 */
2175 dev->mmio_size += len;
2176 dev->mmio = realloc(dev->mmio, dev->mmio_size);
2177 memcpy(dev->mmio + 1, conf, len);
2178
2179 /* Hook up device cfg */
2180 dev->config.cfg_access.cap.cap_next
2181 = offsetof(struct pci_config, device);
2182
2183 /* Fix up device cfg field length. */
2184 dev->config.device.length = len;
2185
2186 /* The rest is the same as the no-config case */
2187 no_device_config(dev);
2188}
2189
2190static void init_cap(struct virtio_pci_cap *cap, size_t caplen, int type,
2191 size_t bar_offset, size_t bar_bytes, u8 next)
2192{
2193 cap->cap_vndr = PCI_CAP_ID_VNDR;
2194 cap->cap_next = next;
2195 cap->cap_len = caplen;
2196 cap->cfg_type = type;
2197 cap->bar = 0;
2198 memset(cap->padding, 0, sizeof(cap->padding));
2199 cap->offset = bar_offset;
2200 cap->length = bar_bytes;
2201}
2202
2203/*
2204 * This sets up the pci_config structure, as defined in the virtio 1.0
2205 * standard (and PCI standard).
2206 */
2207static void init_pci_config(struct pci_config *pci, u16 type,
2208 u8 class, u8 subclass)
2209{
2210 size_t bar_offset, bar_len;
2211
2212 /* Save typing: most thing are happy being zero. */
2213 memset(pci, 0, sizeof(*pci));
2214
2215 /* 4.1.2.1: Devices MUST have the PCI Vendor ID 0x1AF4 */
2216 pci->vendor_id = 0x1AF4;
2217 /* 4.1.2.1: ... PCI Device ID calculated by adding 0x1040 ... */
2218 pci->device_id = 0x1040 + type;
2219
2220 /*
2221 * PCI have specific codes for different types of devices.
2222 * Linux doesn't care, but it's a good clue for people looking
2223 * at the device.
2224 *
2225 * eg :
2226 * VIRTIO_ID_CONSOLE: class = 0x07, subclass = 0x00
2227 * VIRTIO_ID_NET: class = 0x02, subclass = 0x00
Rusty Russell93153072015-02-11 15:15:11 +10302228 * 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 Russell50516542015-02-11 15:15:12 +10302666 if (out.type & VIRTIO_BLK_T_OUT) {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002667 /*
2668 * Write
2669 *
2670 * Move to the right location in the block file. This can fail
2671 * if they try to write past end.
2672 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002673 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302674 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002675
Rusty Russellc0316a92012-10-16 23:56:13 +10302676 ret = writev(vblk->fd, iov, out_num);
2677 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
Rusty Russell17cbca22007-10-22 11:24:22 +10002678
Rusty Russell2e04ef72009-07-30 16:03:45 -06002679 /*
2680 * Grr... Now we know how long the descriptor they sent was, we
Rusty Russell17cbca22007-10-22 11:24:22 +10002681 * make sure they didn't try to write over the end of the block
Rusty Russell2e04ef72009-07-30 16:03:45 -06002682 * file (possibly extending it).
2683 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002684 if (ret > 0 && off + ret > vblk->len) {
2685 /* Trim it back to the correct length */
2686 ftruncate64(vblk->fd, vblk->len);
2687 /* Die, bad Guest, die. */
2688 errx(1, "Write past end %llu+%u", off, ret);
2689 }
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002690
2691 wlen = sizeof(*in);
2692 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russellc0316a92012-10-16 23:56:13 +10302693 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002694 /* Flush */
2695 ret = fdatasync(vblk->fd);
2696 verbose("FLUSH fdatasync: %i\n", ret);
Anthony Liguori1200e642007-11-08 21:13:44 -06002697 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002698 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10002699 } else {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002700 /*
2701 * Read
2702 *
2703 * Move to the right location in the block file. This can fail
2704 * if they try to read past end.
2705 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002706 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302707 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002708
Rusty Russellc0316a92012-10-16 23:56:13 +10302709 ret = readv(vblk->fd, iov + out_num, in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002710 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06002711 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002712 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10002713 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06002714 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002715 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10002716 }
2717 }
2718
Rusty Russella91d74a2009-07-30 16:03:45 -06002719 /* Finished that request. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002720 add_used(vq, head, wlen);
Rusty Russell17cbca22007-10-22 11:24:22 +10002721}
2722
Rusty Russelle1e72962007-10-25 15:02:50 +10002723/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002724static void setup_block_file(const char *filename)
2725{
Rusty Russell17cbca22007-10-22 11:24:22 +10002726 struct device *dev;
2727 struct vblk_info *vblk;
Rusty Russella586d4f2008-02-04 23:49:56 -05002728 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10002729
Rusty Russell50516542015-02-11 15:15:12 +10302730 /* Create the device. */
2731 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
Rusty Russell17cbca22007-10-22 11:24:22 +10002732
Rusty Russelle1e72962007-10-25 15:02:50 +10002733 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell50516542015-02-11 15:15:12 +10302734 add_pci_virtqueue(dev, blk_request);
Rusty Russell17cbca22007-10-22 11:24:22 +10002735
2736 /* Allocate the room for our own bookkeeping */
2737 vblk = dev->priv = malloc(sizeof(*vblk));
2738
2739 /* First we open the file and store the length. */
2740 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
2741 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
2742
2743 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002744 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10002745
Rusty Russell2e04ef72009-07-30 16:03:45 -06002746 /*
2747 * Tell Guest not to put in too many descriptors at once: two are used
2748 * for the in and out elements.
2749 */
Rusty Russell50516542015-02-11 15:15:12 +10302750 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
Rusty Russella586d4f2008-02-04 23:49:56 -05002751 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2752
Rusty Russell50516542015-02-11 15:15:12 +10302753 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
Rusty Russell17cbca22007-10-22 11:24:22 +10002754
Rusty Russell17cbca22007-10-22 11:24:22 +10002755 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell50516542015-02-11 15:15:12 +10302756 devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10002757}
Rusty Russell28fd6d72008-07-29 09:58:33 -05002758
Rusty Russell2e04ef72009-07-30 16:03:45 -06002759/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10302760 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05002761 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10302762 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05002763 * console is the reverse.
2764 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002765 * The same logic applies, however.
2766 */
2767struct rng_info {
2768 int rfd;
2769};
2770
Rusty Russell659a0e62009-06-12 22:27:10 -06002771static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05002772{
2773 int len;
2774 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002775 struct rng_info *rng_info = vq->dev->priv;
2776 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05002777
2778 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002779 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002780 if (out_num)
2781 errx(1, "Output buffers in rng?");
2782
Rusty Russell2e04ef72009-07-30 16:03:45 -06002783 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06002784 * Just like the console write, we loop to cover the whole iovec.
2785 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002786 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002787 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06002788 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002789 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10302790 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10302791 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002792 totlen += len;
2793 }
2794
2795 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002796 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002797}
2798
Rusty Russell2e04ef72009-07-30 16:03:45 -06002799/*L:199
2800 * This creates a "hardware" random number device for the Guest.
2801 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002802static void setup_rng(void)
2803{
2804 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002805 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05002806
Rusty Russella454bb32015-02-11 15:15:09 +10302807 /* Our device's private info simply contains the /dev/urandom fd. */
2808 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002809
Rusty Russell2e04ef72009-07-30 16:03:45 -06002810 /* Create the new device. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002811 dev = new_device("rng", VIRTIO_ID_RNG);
2812 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002813
2814 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002815 add_virtqueue(dev, VIRTQUEUE_NUM, rng_input);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002816
2817 verbose("device %u: rng\n", devices.device_num++);
2818}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002819/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05302820
Rusty Russella6bd8e12008-03-28 11:05:53 -05002821/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05302822static void __attribute__((noreturn)) restart_guest(void)
2823{
2824 unsigned int i;
2825
Rusty Russell2e04ef72009-07-30 16:03:45 -06002826 /*
2827 * Since we don't track all open fds, we simply close everything beyond
2828 * stderr.
2829 */
Balaji Raoec04b132007-12-28 14:26:24 +05302830 for (i = 3; i < FD_SETSIZE; i++)
2831 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05002832
Rusty Russell659a0e62009-06-12 22:27:10 -06002833 /* Reset all the devices (kills all threads). */
2834 cleanup_devices();
2835
Balaji Raoec04b132007-12-28 14:26:24 +05302836 execv(main_args[0], main_args);
2837 err(1, "Could not exec %s", main_args[0]);
2838}
Rusty Russell8ca47e02007-07-19 01:49:29 -07002839
Rusty Russell2e04ef72009-07-30 16:03:45 -06002840/*L:220
2841 * Finally we reach the core of the Launcher which runs the Guest, serves
2842 * its input and output, and finally, lays it to rest.
2843 */
Rusty Russell56739c802009-06-12 22:26:59 -06002844static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002845{
2846 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10302847 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002848 int readval;
2849
2850 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302851 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002852
Rusty Russell17cbca22007-10-22 11:24:22 +10002853 /* One unsigned long means the Guest did HCALL_NOTIFY */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302854 if (readval == sizeof(notify)) {
2855 if (notify.trap == 0x1F) {
2856 verbose("Notify on address %#08x\n",
2857 notify.addr);
2858 handle_output(notify.addr);
Rusty Russellc565650b2015-02-11 15:15:10 +10302859 } else if (notify.trap == 13) {
2860 verbose("Emulating instruction at %#x\n",
2861 getreg(eip));
2862 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302863 } else if (notify.trap == 14) {
2864 verbose("Emulating MMIO at %#x\n",
2865 getreg(eip));
2866 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302867 } else
2868 errx(1, "Unknown trap %i addr %#08x\n",
2869 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07002870 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002871 } else if (errno == ENOENT) {
2872 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002873 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002874 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05302875 /* ERESTART means that we need to reboot the guest */
2876 } else if (errno == ERESTART) {
2877 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06002878 /* Anything else means a bug or incompatible change. */
2879 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002880 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002881 }
2882}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002883/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10002884 * This is the end of the Launcher. The good news: we are over halfway
2885 * through! The bad news: the most fiendish part of the code still lies ahead
2886 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07002887 *
Rusty Russelle1e72962007-10-25 15:02:50 +10002888 * Are you ready? Take a deep breath and join me in the core of the Host, in
2889 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06002890:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002891
2892static struct option opts[] = {
2893 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002894 { "tunnet", 1, NULL, 't' },
2895 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05002896 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002897 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002898 { "username", 1, NULL, 'u' },
2899 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002900 { NULL },
2901};
2902static void usage(void)
2903{
2904 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002905 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07002906 "|--block=<filename>|--initrd=<filename>]...\n"
2907 "<mem-in-mb> vmlinux [args...]");
2908}
2909
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002910/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002911int main(int argc, char *argv[])
2912{
Rusty Russell2e04ef72009-07-30 16:03:45 -06002913 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002914 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06002915 /* Two temporaries. */
2916 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002917 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002918 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07002919 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002920 const char *initrd_name = NULL;
2921
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002922 /* Password structure for initgroups/setres[gu]id */
2923 struct passwd *user_details = NULL;
2924
2925 /* Directory to chroot to */
2926 char *chroot_path = NULL;
2927
Balaji Raoec04b132007-12-28 14:26:24 +05302928 /* Save the args: we "reboot" by execing ourselves again. */
2929 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05302930
Rusty Russell2e04ef72009-07-30 16:03:45 -06002931 /*
2932 * First we initialize the device list. We keep a pointer to the last
Rusty Russell659a0e62009-06-12 22:27:10 -06002933 * device, and the next interrupt number to use for devices (1:
Rusty Russell2e04ef72009-07-30 16:03:45 -06002934 * remember that 0 is used by the timer).
2935 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002936 devices.lastdev = NULL;
Rusty Russell17cbca22007-10-22 11:24:22 +10002937 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002938
Rusty Russella91d74a2009-07-30 16:03:45 -06002939 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002940 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06002941
Rusty Russell2e04ef72009-07-30 16:03:45 -06002942 /*
2943 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07002944 * descriptor and memory pages for the devices as we parse the command
2945 * line. So we quickly look through the arguments to find the amount
Rusty Russell2e04ef72009-07-30 16:03:45 -06002946 * of memory now.
2947 */
Rusty Russell6570c45992007-07-23 18:43:56 -07002948 for (i = 1; i < argc; i++) {
2949 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002950 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002951 /*
2952 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002953 * guest-physical memory range. This fills it with 0,
2954 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002955 * tries to access it.
2956 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002957 guest_base = map_zeroed_pages(mem / getpagesize()
2958 + DEVICE_PAGES);
2959 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10302960 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002961 devices.descpage = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07002962 break;
2963 }
2964 }
Rusty Russelldde79782007-07-26 10:41:03 -07002965
2966 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002967 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2968 switch (c) {
2969 case 'v':
2970 verbose = true;
2971 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002972 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10002973 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002974 break;
2975 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10002976 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002977 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002978 case 'r':
2979 setup_rng();
2980 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002981 case 'i':
2982 initrd_name = optarg;
2983 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002984 case 'u':
2985 user_details = getpwnam(optarg);
2986 if (!user_details)
2987 err(1, "getpwnam failed, incorrect username?");
2988 break;
2989 case 'c':
2990 chroot_path = optarg;
2991 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002992 default:
2993 warnx("Unknown argument %s", argv[optind]);
2994 usage();
2995 }
2996 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06002997 /*
2998 * After the other arguments we expect memory and kernel image name,
2999 * followed by command line arguments for the kernel.
3000 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003001 if (optind + 2 > argc)
3002 usage();
3003
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003004 verbose("Guest base is at %p\n", guest_base);
3005
Rusty Russelldde79782007-07-26 10:41:03 -07003006 /* We always have a console device */
Rusty Russell17cbca22007-10-22 11:24:22 +10003007 setup_console();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003008
Rusty Russell8e709462015-02-11 15:15:12 +10303009 /* Initialize the (fake) PCI host bridge device. */
3010 init_pci_host_bridge();
3011
Rusty Russell8ca47e02007-07-19 01:49:29 -07003012 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10003013 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07003014
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003015 /* Boot information is stashed at physical address 0 */
3016 boot = from_guest_phys(0);
3017
Rusty Russelldde79782007-07-26 10:41:03 -07003018 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003019 if (initrd_name) {
3020 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06003021 /*
3022 * These are the location in the Linux boot header where the
3023 * start and size of the initrd are expected to be found.
3024 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003025 boot->hdr.ramdisk_image = mem - initrd_size;
3026 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07003027 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003028 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003029 }
3030
Rusty Russell2e04ef72009-07-30 16:03:45 -06003031 /*
3032 * The Linux boot header contains an "E820" memory map: ours is a
3033 * simple, single region.
3034 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003035 boot->e820_entries = 1;
3036 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06003037 /*
3038 * The boot header contains a command line pointer: we put the command
3039 * line after the boot header.
3040 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003041 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10003042 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003043 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07003044
Rusty Russelle22a5392011-08-15 10:15:10 +09303045 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3046 boot->hdr.kernel_alignment = 0x1000000;
3047
Rusty Russell814a0e52007-10-22 11:29:44 +10003048 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003049 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10003050
3051 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003052 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10003053
Rusty Russell43d33b22007-10-22 11:29:57 +10003054 /* Tell the entry path not to try to reload segment registers. */
3055 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003056
Rusty Russell9f542882011-07-22 14:39:50 +09303057 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06003058 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07003059
Rusty Russella91d74a2009-07-30 16:03:45 -06003060 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06003061 signal(SIGCHLD, kill_launcher);
3062
3063 /* If we exit via err(), this kills all the threads, restores tty. */
3064 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003065
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003066 /* If requested, chroot to a directory */
3067 if (chroot_path) {
3068 if (chroot(chroot_path) != 0)
3069 err(1, "chroot(\"%s\") failed", chroot_path);
3070
3071 if (chdir("/") != 0)
3072 err(1, "chdir(\"/\") failed");
3073
3074 verbose("chroot done\n");
3075 }
3076
3077 /* If requested, drop privileges */
3078 if (user_details) {
3079 uid_t u;
3080 gid_t g;
3081
3082 u = user_details->pw_uid;
3083 g = user_details->pw_gid;
3084
3085 if (initgroups(user_details->pw_name, g) != 0)
3086 err(1, "initgroups failed");
3087
3088 if (setresgid(g, g, g) != 0)
3089 err(1, "setresgid failed");
3090
3091 if (setresuid(u, u, u) != 0)
3092 err(1, "setresuid failed");
3093
3094 verbose("Dropping privileges completed\n");
3095 }
3096
Rusty Russelldde79782007-07-26 10:41:03 -07003097 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06003098 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003099}
Rusty Russellf56a3842007-07-26 10:41:05 -07003100/*:*/
3101
3102/*M:999
3103 * Mastery is done: you now know everything I do.
3104 *
3105 * But surely you have seen code, features and bugs in your wanderings which
3106 * you now yearn to attack? That is the real game, and I look forward to you
3107 * patching and forking lguest into the Your-Name-Here-visor.
3108 *
3109 * Farewell, and good coding!
3110 * Rusty Russell.
3111 */