blob: fadd5723ba57a203c37219e5009ef6930c383dc3 [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 Russellbf6d4032015-02-11 15:16:01 +103071#include "../../include/uapi/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>
Rusty Russell0d5b5d32015-02-11 15:17:01 +103074#include "../../include/uapi/linux/virtio_rng.h"
Rusty Russelle6dc0412013-07-04 11:22:58 +093075#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.
Rusty Russell93153072015-02-11 15:15:11 +10302224 */
2225 pci->class = class;
2226 pci->subclass = subclass;
2227
2228 /*
2229 * 4.1.2.1 Non-transitional devices SHOULD have a PCI Revision
2230 * ID of 1 or higher
2231 */
2232 pci->revid = 1;
2233
2234 /*
2235 * 4.1.2.1 Non-transitional devices SHOULD have a PCI
2236 * Subsystem Device ID of 0x40 or higher.
2237 */
2238 pci->subsystem_device_id = 0x40;
2239
2240 /* We use our dummy interrupt controller, and irq_line is the irq */
2241 pci->irq_line = devices.next_irq++;
2242 pci->irq_pin = 0;
2243
2244 /* Support for extended capabilities. */
2245 pci->status = (1 << 4);
2246
2247 /* Link them in. */
2248 pci->capabilities = offsetof(struct pci_config, common);
2249
2250 bar_offset = offsetof(struct virtio_pci_mmio, cfg);
2251 bar_len = sizeof(((struct virtio_pci_mmio *)0)->cfg);
2252 init_cap(&pci->common, sizeof(pci->common), VIRTIO_PCI_CAP_COMMON_CFG,
2253 bar_offset, bar_len,
2254 offsetof(struct pci_config, notify));
2255
2256 bar_offset += bar_len;
2257 bar_len = sizeof(((struct virtio_pci_mmio *)0)->notify);
2258 /* FIXME: Use a non-zero notify_off, for per-queue notification? */
2259 init_cap(&pci->notify.cap, sizeof(pci->notify),
2260 VIRTIO_PCI_CAP_NOTIFY_CFG,
2261 bar_offset, bar_len,
2262 offsetof(struct pci_config, isr));
2263
2264 bar_offset += bar_len;
2265 bar_len = sizeof(((struct virtio_pci_mmio *)0)->isr);
2266 init_cap(&pci->isr, sizeof(pci->isr),
2267 VIRTIO_PCI_CAP_ISR_CFG,
2268 bar_offset, bar_len,
2269 offsetof(struct pci_config, cfg_access));
2270
2271 /* This doesn't have any presence in the BAR */
2272 init_cap(&pci->cfg_access.cap, sizeof(pci->cfg_access),
2273 VIRTIO_PCI_CAP_PCI_CFG,
2274 0, 0, 0);
2275
2276 bar_offset += bar_len + sizeof(((struct virtio_pci_mmio *)0)->padding);
2277 assert(bar_offset == sizeof(struct virtio_pci_mmio));
2278
2279 /*
2280 * This gets sewn in and length set in set_device_config().
2281 * Some devices don't have a device configuration interface, so
2282 * we never expose this if we don't call set_device_config().
2283 */
2284 init_cap(&pci->device, sizeof(pci->device), VIRTIO_PCI_CAP_DEVICE_CFG,
2285 bar_offset, 0, 0);
2286}
2287
Rusty Russell2e04ef72009-07-30 16:03:45 -06002288/*
2289 * This routine does all the creation and setup of a new device, including
Rusty Russella91d74a2009-07-30 16:03:45 -06002290 * calling new_dev_desc() to allocate the descriptor and device memory. We
2291 * don't actually start the service threads until later.
Rusty Russella6bd8e12008-03-28 11:05:53 -05002292 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002293 * See what I mean about userspace being boring?
2294 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002295static struct device *new_device(const char *name, u16 type)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002296{
2297 struct device *dev = malloc(sizeof(*dev));
2298
Rusty Russelldde79782007-07-26 10:41:03 -07002299 /* Now we populate the fields one at a time. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002300 dev->desc = new_dev_desc(type);
Rusty Russell17cbca22007-10-22 11:24:22 +10002301 dev->name = name;
Rusty Russelld1c856e2007-11-19 11:20:40 -05002302 dev->vq = NULL;
Rusty Russell713b15b2009-06-12 22:26:58 -06002303 dev->feature_len = 0;
2304 dev->num_vq = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002305 dev->running = false;
Rusty Russellca16f582012-10-04 12:03:25 +09302306 dev->next = NULL;
Rusty Russella586d4f2008-02-04 23:49:56 -05002307
Rusty Russell2e04ef72009-07-30 16:03:45 -06002308 /*
2309 * Append to device list. Prepending to a single-linked list is
Rusty Russella586d4f2008-02-04 23:49:56 -05002310 * easier, but the user expects the devices to be arranged on the bus
2311 * in command-line order. The first network device on the command line
Rusty Russell2e04ef72009-07-30 16:03:45 -06002312 * is eth0, the first block device /dev/vda, etc.
2313 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002314 if (devices.lastdev)
2315 devices.lastdev->next = dev;
2316 else
2317 devices.dev = dev;
2318 devices.lastdev = dev;
2319
Rusty Russell8ca47e02007-07-19 01:49:29 -07002320 return dev;
2321}
2322
Rusty Russell93153072015-02-11 15:15:11 +10302323static struct device *new_pci_device(const char *name, u16 type,
2324 u8 class, u8 subclass)
2325{
2326 struct device *dev = malloc(sizeof(*dev));
2327
2328 /* Now we populate the fields one at a time. */
2329 dev->desc = NULL;
2330 dev->name = name;
2331 dev->vq = NULL;
2332 dev->feature_len = 0;
2333 dev->num_vq = 0;
2334 dev->running = false;
2335 dev->next = NULL;
2336 dev->mmio_size = sizeof(struct virtio_pci_mmio);
2337 dev->mmio = calloc(1, dev->mmio_size);
2338 dev->features = (u64)1 << VIRTIO_F_VERSION_1;
2339 dev->features_accepted = 0;
2340
2341 if (devices.device_num + 1 >= 32)
2342 errx(1, "Can only handle 31 PCI devices");
2343
2344 init_pci_config(&dev->config, type, class, subclass);
2345 assert(!devices.pci[devices.device_num+1]);
2346 devices.pci[++devices.device_num] = dev;
2347
2348 return dev;
2349}
2350
Rusty Russell2e04ef72009-07-30 16:03:45 -06002351/*
2352 * Our first setup routine is the console. It's a fairly simple device, but
2353 * UNIX tty handling makes it uglier than it could be.
2354 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002355static void setup_console(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002356{
2357 struct device *dev;
2358
Rusty Russelldde79782007-07-26 10:41:03 -07002359 /* If we can save the initial standard input settings... */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002360 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
2361 struct termios term = orig_term;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002362 /*
2363 * Then we turn off echo, line buffering and ^C etc: We want a
2364 * raw input stream to the Guest.
2365 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002366 term.c_lflag &= ~(ISIG|ICANON|ECHO);
2367 tcsetattr(STDIN_FILENO, TCSANOW, &term);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002368 }
2369
Rusty Russellebff0112015-02-11 15:18:01 +10302370 dev = new_pci_device("console", VIRTIO_ID_CONSOLE, 0x07, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002371
Rusty Russelldde79782007-07-26 10:41:03 -07002372 /* We store the console state in dev->priv, and initialize it. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002373 dev->priv = malloc(sizeof(struct console_abort));
2374 ((struct console_abort *)dev->priv)->count = 0;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002375
Rusty Russell2e04ef72009-07-30 16:03:45 -06002376 /*
2377 * The console needs two virtqueues: the input then the output. When
Rusty Russell56ae43d2007-10-22 11:24:23 +10002378 * they put something the input queue, we make sure we're listening to
2379 * stdin. When they put something in the output queue, we write it to
Rusty Russell2e04ef72009-07-30 16:03:45 -06002380 * stdout.
2381 */
Rusty Russellebff0112015-02-11 15:18:01 +10302382 add_pci_virtqueue(dev, console_input);
2383 add_pci_virtqueue(dev, console_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002384
Rusty Russellebff0112015-02-11 15:18:01 +10302385 /* There's no configuration area for this device. */
2386 no_device_config(dev);
2387
2388 verbose("device %u: console\n", devices.device_num);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002389}
Rusty Russelldde79782007-07-26 10:41:03 -07002390/*:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002391
Rusty Russell2e04ef72009-07-30 16:03:45 -06002392/*M:010
2393 * Inter-guest networking is an interesting area. Simplest is to have a
Rusty Russell17cbca22007-10-22 11:24:22 +10002394 * --sharenet=<name> option which opens or creates a named pipe. This can be
2395 * used to send packets to another guest in a 1:1 manner.
2396 *
Rusty Russell9f542882011-07-22 14:39:50 +09302397 * More sophisticated is to use one of the tools developed for project like UML
Rusty Russell17cbca22007-10-22 11:24:22 +10002398 * to do networking.
2399 *
2400 * Faster is to do virtio bonding in kernel. Doing this 1:1 would be
2401 * completely generic ("here's my vring, attach to your vring") and would work
2402 * for any traffic. Of course, namespace and permissions issues need to be
2403 * dealt with. A more sophisticated "multi-channel" virtio_net.c could hide
2404 * multiple inter-guest channels behind one interface, although it would
2405 * require some manner of hotplugging new virtio channels.
2406 *
Rusty Russell9f542882011-07-22 14:39:50 +09302407 * Finally, we could use a virtio network switch in the kernel, ie. vhost.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002408:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002409
Rusty Russell8ca47e02007-07-19 01:49:29 -07002410static u32 str2ip(const char *ipaddr)
2411{
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002412 unsigned int b[4];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002413
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002414 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
2415 errx(1, "Failed to parse IP address '%s'", ipaddr);
2416 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
2417}
2418
2419static void str2mac(const char *macaddr, unsigned char mac[6])
2420{
2421 unsigned int m[6];
2422 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
2423 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
2424 errx(1, "Failed to parse mac address '%s'", macaddr);
2425 mac[0] = m[0];
2426 mac[1] = m[1];
2427 mac[2] = m[2];
2428 mac[3] = m[3];
2429 mac[4] = m[4];
2430 mac[5] = m[5];
Rusty Russell8ca47e02007-07-19 01:49:29 -07002431}
2432
Rusty Russell2e04ef72009-07-30 16:03:45 -06002433/*
2434 * This code is "adapted" from libbridge: it attaches the Host end of the
Rusty Russelldde79782007-07-26 10:41:03 -07002435 * network device to the bridge device specified by the command line.
2436 *
2437 * This is yet another James Morris contribution (I'm an IP-level guy, so I
Rusty Russell2e04ef72009-07-30 16:03:45 -06002438 * dislike bridging), and I just try not to break it.
2439 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002440static void add_to_bridge(int fd, const char *if_name, const char *br_name)
2441{
2442 int ifidx;
2443 struct ifreq ifr;
2444
2445 if (!*br_name)
2446 errx(1, "must specify bridge name");
2447
2448 ifidx = if_nametoindex(if_name);
2449 if (!ifidx)
2450 errx(1, "interface %s does not exist!", if_name);
2451
2452 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002453 ifr.ifr_name[IFNAMSIZ-1] = '\0';
Rusty Russell8ca47e02007-07-19 01:49:29 -07002454 ifr.ifr_ifindex = ifidx;
2455 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
2456 err(1, "can't add %s to bridge %s", if_name, br_name);
2457}
2458
Rusty Russell2e04ef72009-07-30 16:03:45 -06002459/*
2460 * This sets up the Host end of the network device with an IP address, brings
Rusty Russelldde79782007-07-26 10:41:03 -07002461 * it up so packets will flow, the copies the MAC address into the hwaddr
Rusty Russell2e04ef72009-07-30 16:03:45 -06002462 * pointer.
2463 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002464static void configure_device(int fd, const char *tapif, u32 ipaddr)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002465{
2466 struct ifreq ifr;
Rusty Russellf8466192010-08-27 08:39:48 -06002467 struct sockaddr_in sin;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002468
2469 memset(&ifr, 0, sizeof(ifr));
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002470 strcpy(ifr.ifr_name, tapif);
2471
2472 /* Don't read these incantations. Just cut & paste them like I did! */
Rusty Russellf8466192010-08-27 08:39:48 -06002473 sin.sin_family = AF_INET;
2474 sin.sin_addr.s_addr = htonl(ipaddr);
2475 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002476 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002477 err(1, "Setting %s interface address", tapif);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002478 ifr.ifr_flags = IFF_UP;
2479 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002480 err(1, "Bringing interface %s up", tapif);
2481}
2482
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002483static int get_tun_device(char tapif[IFNAMSIZ])
Rusty Russell8ca47e02007-07-19 01:49:29 -07002484{
Rusty Russell8ca47e02007-07-19 01:49:29 -07002485 struct ifreq ifr;
Rusty Russellbf6d4032015-02-11 15:16:01 +10302486 int vnet_hdr_sz;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002487 int netfd;
2488
2489 /* Start with this zeroed. Messy but sure. */
2490 memset(&ifr, 0, sizeof(ifr));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002491
Rusty Russell2e04ef72009-07-30 16:03:45 -06002492 /*
2493 * We open the /dev/net/tun device and tell it we want a tap device. A
Rusty Russelldde79782007-07-26 10:41:03 -07002494 * tap device is like a tun device, only somehow different. To tell
2495 * the truth, I completely blundered my way through this code, but it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002496 * works now!
2497 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002498 netfd = open_or_die("/dev/net/tun", O_RDWR);
Rusty Russell398f1872008-07-29 09:58:37 -05002499 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002500 strcpy(ifr.ifr_name, "tap%d");
2501 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
2502 err(1, "configuring /dev/net/tun");
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002503
Rusty Russell398f1872008-07-29 09:58:37 -05002504 if (ioctl(netfd, TUNSETOFFLOAD,
2505 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
2506 err(1, "Could not set features for tun device");
2507
Rusty Russell2e04ef72009-07-30 16:03:45 -06002508 /*
2509 * We don't need checksums calculated for packets coming in this
2510 * device: trust us!
2511 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002512 ioctl(netfd, TUNSETNOCSUM, 1);
2513
Rusty Russellbf6d4032015-02-11 15:16:01 +10302514 /*
2515 * In virtio before 1.0 (aka legacy virtio), we added a 16-bit
2516 * field at the end of the network header iff
2517 * VIRTIO_NET_F_MRG_RXBUF was negotiated. For virtio 1.0,
2518 * that became the norm, but we need to tell the tun device
2519 * about our expanded header (which is called
2520 * virtio_net_hdr_mrg_rxbuf in the legacy system).
2521 */
2522 vnet_hdr_sz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2523 if (ioctl(netfd, TUNSETVNETHDRSZ, &vnet_hdr_sz) != 0)
2524 err(1, "Setting tun header size to %u", vnet_hdr_sz);
2525
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002526 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
2527 return netfd;
2528}
2529
Rusty Russell2e04ef72009-07-30 16:03:45 -06002530/*L:195
2531 * Our network is a Host<->Guest network. This can either use bridging or
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002532 * routing, but the principle is the same: it uses the "tun" device to inject
2533 * packets into the Host as if they came in from a normal network card. We
Rusty Russell2e04ef72009-07-30 16:03:45 -06002534 * just shunt packets between the Guest and the tun device.
2535 */
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002536static void setup_tun_net(char *arg)
2537{
2538 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002539 struct net_info *net_info = malloc(sizeof(*net_info));
2540 int ipfd;
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002541 u32 ip = INADDR_ANY;
2542 bool bridging = false;
2543 char tapif[IFNAMSIZ], *p;
2544 struct virtio_net_config conf;
2545
Rusty Russell659a0e62009-06-12 22:27:10 -06002546 net_info->tunfd = get_tun_device(tapif);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002547
Rusty Russell17cbca22007-10-22 11:24:22 +10002548 /* First we create a new network device. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302549 dev = new_pci_device("net", VIRTIO_ID_NET, 0x02, 0x00);
Rusty Russell659a0e62009-06-12 22:27:10 -06002550 dev->priv = net_info;
Rusty Russelldde79782007-07-26 10:41:03 -07002551
Rusty Russell2e04ef72009-07-30 16:03:45 -06002552 /* Network devices need a recv and a send queue, just like console. */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302553 add_pci_virtqueue(dev, net_input);
2554 add_pci_virtqueue(dev, net_output);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002555
Rusty Russell2e04ef72009-07-30 16:03:45 -06002556 /*
2557 * We need a socket to perform the magic network ioctls to bring up the
2558 * tap interface, connect to the bridge etc. Any socket will do!
2559 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002560 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
2561 if (ipfd < 0)
2562 err(1, "opening IP socket");
2563
Rusty Russelldde79782007-07-26 10:41:03 -07002564 /* If the command line was --tunnet=bridge:<name> do bridging. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002565 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002566 arg += strlen(BRIDGE_PFX);
2567 bridging = true;
2568 }
2569
2570 /* A mac address may follow the bridge name or IP address */
2571 p = strchr(arg, ':');
2572 if (p) {
2573 str2mac(p+1, conf.mac);
Rusty Russellbf6d4032015-02-11 15:16:01 +10302574 add_pci_feature(dev, VIRTIO_NET_F_MAC);
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002575 *p = '\0';
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002576 }
2577
2578 /* arg is now either an IP address or a bridge name */
2579 if (bridging)
2580 add_to_bridge(ipfd, tapif, arg);
2581 else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002582 ip = str2ip(arg);
2583
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002584 /* Set up the tun device. */
2585 configure_device(ipfd, tapif, ip);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002586
Rusty Russell398f1872008-07-29 09:58:37 -05002587 /* Expect Guest to handle everything except UFO */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302588 add_pci_feature(dev, VIRTIO_NET_F_CSUM);
2589 add_pci_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
2590 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
2591 add_pci_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
2592 add_pci_feature(dev, VIRTIO_NET_F_GUEST_ECN);
2593 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO4);
2594 add_pci_feature(dev, VIRTIO_NET_F_HOST_TSO6);
2595 add_pci_feature(dev, VIRTIO_NET_F_HOST_ECN);
Mark McLoughlind1f01322009-05-11 18:11:46 +01002596 /* We handle indirect ring entries */
Rusty Russellbf6d4032015-02-11 15:16:01 +10302597 add_pci_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
2598 set_device_config(dev, &conf, sizeof(conf));
Rusty Russell8ca47e02007-07-19 01:49:29 -07002599
Rusty Russella586d4f2008-02-04 23:49:56 -05002600 /* We don't need the socket any more; setup is done. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002601 close(ipfd);
2602
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002603 if (bridging)
2604 verbose("device %u: tun %s attached to bridge: %s\n",
2605 devices.device_num, tapif, arg);
2606 else
2607 verbose("device %u: tun %s: %s\n",
2608 devices.device_num, tapif, arg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002609}
Rusty Russella91d74a2009-07-30 16:03:45 -06002610/*:*/
Rusty Russell17cbca22007-10-22 11:24:22 +10002611
Rusty Russelle1e72962007-10-25 15:02:50 +10002612/* This hangs off device->priv. */
Rusty Russell1842f232009-07-30 16:03:46 -06002613struct vblk_info {
Rusty Russell17cbca22007-10-22 11:24:22 +10002614 /* The size of the file. */
2615 off64_t len;
2616
2617 /* The file descriptor for the file. */
2618 int fd;
2619
Rusty Russell17cbca22007-10-22 11:24:22 +10002620};
2621
Rusty Russelle1e72962007-10-25 15:02:50 +10002622/*L:210
2623 * The Disk
2624 *
Rusty Russella91d74a2009-07-30 16:03:45 -06002625 * The disk only has one virtqueue, so it only has one thread. It is really
2626 * simple: the Guest asks for a block number and we read or write that position
2627 * in the file.
2628 *
2629 * Before we serviced each virtqueue in a separate thread, that was unacceptably
2630 * slow: the Guest waits until the read is finished before running anything
2631 * else, even if it could have been doing useful work.
2632 *
2633 * We could have used async I/O, except it's reputed to suck so hard that
2634 * characters actually go missing from your code when you try to use it.
Rusty Russelle1e72962007-10-25 15:02:50 +10002635 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002636static void blk_request(struct virtqueue *vq)
Rusty Russell17cbca22007-10-22 11:24:22 +10002637{
Rusty Russell659a0e62009-06-12 22:27:10 -06002638 struct vblk_info *vblk = vq->dev->priv;
Rusty Russell17cbca22007-10-22 11:24:22 +10002639 unsigned int head, out_num, in_num, wlen;
Rusty Russellc0316a92012-10-16 23:56:13 +10302640 int ret, i;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002641 u8 *in;
Rusty Russellc0316a92012-10-16 23:56:13 +10302642 struct virtio_blk_outhdr out;
Rusty Russell659a0e62009-06-12 22:27:10 -06002643 struct iovec iov[vq->vring.num];
Rusty Russell17cbca22007-10-22 11:24:22 +10002644 off64_t off;
2645
Rusty Russella91d74a2009-07-30 16:03:45 -06002646 /*
2647 * Get the next request, where we normally wait. It triggers the
2648 * interrupt to acknowledge previously serviced requests (if any).
2649 */
Rusty Russell659a0e62009-06-12 22:27:10 -06002650 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002651
Rusty Russellc0316a92012-10-16 23:56:13 +10302652 /* Copy the output header from the front of the iov (adjusts iov) */
2653 iov_consume(iov, out_num, &out, sizeof(out));
Rusty Russell17cbca22007-10-22 11:24:22 +10002654
Rusty Russellc0316a92012-10-16 23:56:13 +10302655 /* Find and trim end of iov input array, for our status byte. */
2656 in = NULL;
2657 for (i = out_num + in_num - 1; i >= out_num; i--) {
2658 if (iov[i].iov_len > 0) {
2659 in = iov[i].iov_base + iov[i].iov_len - 1;
2660 iov[i].iov_len--;
2661 break;
2662 }
2663 }
2664 if (!in)
2665 errx(1, "Bad virtblk cmd with no room for status");
2666
Rusty Russella91d74a2009-07-30 16:03:45 -06002667 /*
2668 * For historical reasons, block operations are expressed in 512 byte
2669 * "sectors".
2670 */
Rusty Russellc0316a92012-10-16 23:56:13 +10302671 off = out.sector * 512;
Rusty Russell17cbca22007-10-22 11:24:22 +10002672
Rusty Russell50516542015-02-11 15:15:12 +10302673 if (out.type & VIRTIO_BLK_T_OUT) {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002674 /*
2675 * Write
2676 *
2677 * Move to the right location in the block file. This can fail
2678 * if they try to write past end.
2679 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002680 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302681 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002682
Rusty Russellc0316a92012-10-16 23:56:13 +10302683 ret = writev(vblk->fd, iov, out_num);
2684 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
Rusty Russell17cbca22007-10-22 11:24:22 +10002685
Rusty Russell2e04ef72009-07-30 16:03:45 -06002686 /*
2687 * Grr... Now we know how long the descriptor they sent was, we
Rusty Russell17cbca22007-10-22 11:24:22 +10002688 * make sure they didn't try to write over the end of the block
Rusty Russell2e04ef72009-07-30 16:03:45 -06002689 * file (possibly extending it).
2690 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002691 if (ret > 0 && off + ret > vblk->len) {
2692 /* Trim it back to the correct length */
2693 ftruncate64(vblk->fd, vblk->len);
2694 /* Die, bad Guest, die. */
2695 errx(1, "Write past end %llu+%u", off, ret);
2696 }
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002697
2698 wlen = sizeof(*in);
2699 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russellc0316a92012-10-16 23:56:13 +10302700 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
Tejun Heo7bc9fdd2010-09-03 11:56:18 +02002701 /* Flush */
2702 ret = fdatasync(vblk->fd);
2703 verbose("FLUSH fdatasync: %i\n", ret);
Anthony Liguori1200e642007-11-08 21:13:44 -06002704 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002705 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
Rusty Russell17cbca22007-10-22 11:24:22 +10002706 } else {
Rusty Russell2e04ef72009-07-30 16:03:45 -06002707 /*
2708 * Read
2709 *
2710 * Move to the right location in the block file. This can fail
2711 * if they try to read past end.
2712 */
Rusty Russell17cbca22007-10-22 11:24:22 +10002713 if (lseek64(vblk->fd, off, SEEK_SET) != off)
Rusty Russellc0316a92012-10-16 23:56:13 +10302714 err(1, "Bad seek to sector %llu", out.sector);
Rusty Russell17cbca22007-10-22 11:24:22 +10002715
Rusty Russellc0316a92012-10-16 23:56:13 +10302716 ret = readv(vblk->fd, iov + out_num, in_num);
Rusty Russell17cbca22007-10-22 11:24:22 +10002717 if (ret >= 0) {
Anthony Liguori1200e642007-11-08 21:13:44 -06002718 wlen = sizeof(*in) + ret;
Rusty Russellcb38fa22008-05-02 21:50:45 -05002719 *in = VIRTIO_BLK_S_OK;
Rusty Russell17cbca22007-10-22 11:24:22 +10002720 } else {
Anthony Liguori1200e642007-11-08 21:13:44 -06002721 wlen = sizeof(*in);
Rusty Russellcb38fa22008-05-02 21:50:45 -05002722 *in = VIRTIO_BLK_S_IOERR;
Rusty Russell17cbca22007-10-22 11:24:22 +10002723 }
2724 }
2725
Rusty Russella91d74a2009-07-30 16:03:45 -06002726 /* Finished that request. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002727 add_used(vq, head, wlen);
Rusty Russell17cbca22007-10-22 11:24:22 +10002728}
2729
Rusty Russelle1e72962007-10-25 15:02:50 +10002730/*L:198 This actually sets up a virtual block device. */
Rusty Russell17cbca22007-10-22 11:24:22 +10002731static void setup_block_file(const char *filename)
2732{
Rusty Russell17cbca22007-10-22 11:24:22 +10002733 struct device *dev;
2734 struct vblk_info *vblk;
Rusty Russella586d4f2008-02-04 23:49:56 -05002735 struct virtio_blk_config conf;
Rusty Russell17cbca22007-10-22 11:24:22 +10002736
Rusty Russell50516542015-02-11 15:15:12 +10302737 /* Create the device. */
2738 dev = new_pci_device("block", VIRTIO_ID_BLOCK, 0x01, 0x80);
Rusty Russell17cbca22007-10-22 11:24:22 +10002739
Rusty Russelle1e72962007-10-25 15:02:50 +10002740 /* The device has one virtqueue, where the Guest places requests. */
Rusty Russell50516542015-02-11 15:15:12 +10302741 add_pci_virtqueue(dev, blk_request);
Rusty Russell17cbca22007-10-22 11:24:22 +10002742
2743 /* Allocate the room for our own bookkeeping */
2744 vblk = dev->priv = malloc(sizeof(*vblk));
2745
2746 /* First we open the file and store the length. */
2747 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
2748 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
2749
2750 /* Tell Guest how many sectors this device has. */
Rusty Russella586d4f2008-02-04 23:49:56 -05002751 conf.capacity = cpu_to_le64(vblk->len / 512);
Rusty Russell17cbca22007-10-22 11:24:22 +10002752
Rusty Russell2e04ef72009-07-30 16:03:45 -06002753 /*
2754 * Tell Guest not to put in too many descriptors at once: two are used
2755 * for the in and out elements.
2756 */
Rusty Russell50516542015-02-11 15:15:12 +10302757 add_pci_feature(dev, VIRTIO_BLK_F_SEG_MAX);
Rusty Russella586d4f2008-02-04 23:49:56 -05002758 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
2759
Rusty Russell50516542015-02-11 15:15:12 +10302760 set_device_config(dev, &conf, sizeof(struct virtio_blk_config));
Rusty Russell17cbca22007-10-22 11:24:22 +10002761
Rusty Russell17cbca22007-10-22 11:24:22 +10002762 verbose("device %u: virtblock %llu sectors\n",
Rusty Russell50516542015-02-11 15:15:12 +10302763 devices.device_num, le64_to_cpu(conf.capacity));
Rusty Russell17cbca22007-10-22 11:24:22 +10002764}
Rusty Russell28fd6d72008-07-29 09:58:33 -05002765
Rusty Russell2e04ef72009-07-30 16:03:45 -06002766/*L:211
Rusty Russella454bb32015-02-11 15:15:09 +10302767 * Our random number generator device reads from /dev/urandom into the Guest's
Rusty Russell28fd6d72008-07-29 09:58:33 -05002768 * input buffers. The usual case is that the Guest doesn't want random numbers
Rusty Russella454bb32015-02-11 15:15:09 +10302769 * and so has no buffers although /dev/urandom is still readable, whereas
Rusty Russell28fd6d72008-07-29 09:58:33 -05002770 * console is the reverse.
2771 *
Rusty Russell2e04ef72009-07-30 16:03:45 -06002772 * The same logic applies, however.
2773 */
2774struct rng_info {
2775 int rfd;
2776};
2777
Rusty Russell659a0e62009-06-12 22:27:10 -06002778static void rng_input(struct virtqueue *vq)
Rusty Russell28fd6d72008-07-29 09:58:33 -05002779{
2780 int len;
2781 unsigned int head, in_num, out_num, totlen = 0;
Rusty Russell659a0e62009-06-12 22:27:10 -06002782 struct rng_info *rng_info = vq->dev->priv;
2783 struct iovec iov[vq->vring.num];
Rusty Russell28fd6d72008-07-29 09:58:33 -05002784
2785 /* First we need a buffer from the Guests's virtqueue. */
Rusty Russell659a0e62009-06-12 22:27:10 -06002786 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002787 if (out_num)
2788 errx(1, "Output buffers in rng?");
2789
Rusty Russell2e04ef72009-07-30 16:03:45 -06002790 /*
Rusty Russella91d74a2009-07-30 16:03:45 -06002791 * Just like the console write, we loop to cover the whole iovec.
2792 * In this case, short reads actually happen quite a bit.
Rusty Russell2e04ef72009-07-30 16:03:45 -06002793 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002794 while (!iov_empty(iov, in_num)) {
Rusty Russell659a0e62009-06-12 22:27:10 -06002795 len = readv(rng_info->rfd, iov, in_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002796 if (len <= 0)
Rusty Russella454bb32015-02-11 15:15:09 +10302797 err(1, "Read from /dev/urandom gave %i", len);
Rusty Russellc0316a92012-10-16 23:56:13 +10302798 iov_consume(iov, in_num, NULL, len);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002799 totlen += len;
2800 }
2801
2802 /* Tell the Guest about the new input. */
Rusty Russell38bc2b82009-06-12 22:27:11 -06002803 add_used(vq, head, totlen);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002804}
2805
Rusty Russell2e04ef72009-07-30 16:03:45 -06002806/*L:199
2807 * This creates a "hardware" random number device for the Guest.
2808 */
Rusty Russell28fd6d72008-07-29 09:58:33 -05002809static void setup_rng(void)
2810{
2811 struct device *dev;
Rusty Russell659a0e62009-06-12 22:27:10 -06002812 struct rng_info *rng_info = malloc(sizeof(*rng_info));
Rusty Russell28fd6d72008-07-29 09:58:33 -05002813
Rusty Russella454bb32015-02-11 15:15:09 +10302814 /* Our device's private info simply contains the /dev/urandom fd. */
2815 rng_info->rfd = open_or_die("/dev/urandom", O_RDONLY);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002816
Rusty Russell2e04ef72009-07-30 16:03:45 -06002817 /* Create the new device. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302818 dev = new_pci_device("rng", VIRTIO_ID_RNG, 0xff, 0);
Rusty Russell659a0e62009-06-12 22:27:10 -06002819 dev->priv = rng_info;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002820
2821 /* The device has one virtqueue, where the Guest places inbufs. */
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302822 add_pci_virtqueue(dev, rng_input);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002823
Rusty Russell0d5b5d32015-02-11 15:17:01 +10302824 /* We don't have any configuration space */
2825 no_device_config(dev);
2826
2827 verbose("device %u: rng\n", devices.device_num);
Rusty Russell28fd6d72008-07-29 09:58:33 -05002828}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002829/* That's the end of device setup. */
Balaji Raoec04b132007-12-28 14:26:24 +05302830
Rusty Russella6bd8e12008-03-28 11:05:53 -05002831/*L:230 Reboot is pretty easy: clean up and exec() the Launcher afresh. */
Balaji Raoec04b132007-12-28 14:26:24 +05302832static void __attribute__((noreturn)) restart_guest(void)
2833{
2834 unsigned int i;
2835
Rusty Russell2e04ef72009-07-30 16:03:45 -06002836 /*
2837 * Since we don't track all open fds, we simply close everything beyond
2838 * stderr.
2839 */
Balaji Raoec04b132007-12-28 14:26:24 +05302840 for (i = 3; i < FD_SETSIZE; i++)
2841 close(i);
Rusty Russell8c798732008-07-29 09:58:38 -05002842
Rusty Russell659a0e62009-06-12 22:27:10 -06002843 /* Reset all the devices (kills all threads). */
2844 cleanup_devices();
2845
Balaji Raoec04b132007-12-28 14:26:24 +05302846 execv(main_args[0], main_args);
2847 err(1, "Could not exec %s", main_args[0]);
2848}
Rusty Russell8ca47e02007-07-19 01:49:29 -07002849
Rusty Russell2e04ef72009-07-30 16:03:45 -06002850/*L:220
2851 * Finally we reach the core of the Launcher which runs the Guest, serves
2852 * its input and output, and finally, lays it to rest.
2853 */
Rusty Russell56739c802009-06-12 22:26:59 -06002854static void __attribute__((noreturn)) run_guest(void)
Rusty Russell8ca47e02007-07-19 01:49:29 -07002855{
2856 for (;;) {
Rusty Russell69a09dc2015-02-11 15:15:09 +10302857 struct lguest_pending notify;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002858 int readval;
2859
2860 /* We read from the /dev/lguest device to run the Guest. */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302861 readval = pread(lguest_fd, &notify, sizeof(notify), cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002862
Rusty Russell17cbca22007-10-22 11:24:22 +10002863 /* One unsigned long means the Guest did HCALL_NOTIFY */
Rusty Russell69a09dc2015-02-11 15:15:09 +10302864 if (readval == sizeof(notify)) {
2865 if (notify.trap == 0x1F) {
2866 verbose("Notify on address %#08x\n",
2867 notify.addr);
2868 handle_output(notify.addr);
Rusty Russellc565650b2015-02-11 15:15:10 +10302869 } else if (notify.trap == 13) {
2870 verbose("Emulating instruction at %#x\n",
2871 getreg(eip));
2872 emulate_insn(notify.insn);
Rusty Russell6a54f9a2015-02-11 15:15:11 +10302873 } else if (notify.trap == 14) {
2874 verbose("Emulating MMIO at %#x\n",
2875 getreg(eip));
2876 emulate_mmio(notify.addr, notify.insn);
Rusty Russell69a09dc2015-02-11 15:15:09 +10302877 } else
2878 errx(1, "Unknown trap %i addr %#08x\n",
2879 notify.trap, notify.addr);
Rusty Russelldde79782007-07-26 10:41:03 -07002880 /* ENOENT means the Guest died. Reading tells us why. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002881 } else if (errno == ENOENT) {
2882 char reason[1024] = { 0 };
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002883 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002884 errx(1, "%s", reason);
Balaji Raoec04b132007-12-28 14:26:24 +05302885 /* ERESTART means that we need to reboot the guest */
2886 } else if (errno == ERESTART) {
2887 restart_guest();
Rusty Russell659a0e62009-06-12 22:27:10 -06002888 /* Anything else means a bug or incompatible change. */
2889 } else
Rusty Russell8ca47e02007-07-19 01:49:29 -07002890 err(1, "Running guest failed");
Rusty Russell8ca47e02007-07-19 01:49:29 -07002891 }
2892}
Rusty Russella6bd8e12008-03-28 11:05:53 -05002893/*L:240
Rusty Russelle1e72962007-10-25 15:02:50 +10002894 * This is the end of the Launcher. The good news: we are over halfway
2895 * through! The bad news: the most fiendish part of the code still lies ahead
2896 * of us.
Rusty Russelldde79782007-07-26 10:41:03 -07002897 *
Rusty Russelle1e72962007-10-25 15:02:50 +10002898 * Are you ready? Take a deep breath and join me in the core of the Host, in
2899 * "make Host".
Rusty Russell2e04ef72009-07-30 16:03:45 -06002900:*/
Rusty Russell8ca47e02007-07-19 01:49:29 -07002901
2902static struct option opts[] = {
2903 { "verbose", 0, NULL, 'v' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002904 { "tunnet", 1, NULL, 't' },
2905 { "block", 1, NULL, 'b' },
Rusty Russell28fd6d72008-07-29 09:58:33 -05002906 { "rng", 0, NULL, 'r' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002907 { "initrd", 1, NULL, 'i' },
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002908 { "username", 1, NULL, 'u' },
2909 { "chroot", 1, NULL, 'c' },
Rusty Russell8ca47e02007-07-19 01:49:29 -07002910 { NULL },
2911};
2912static void usage(void)
2913{
2914 errx(1, "Usage: lguest [--verbose] "
Mark McLoughlindec6a2b2008-07-29 09:58:33 -05002915 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
Rusty Russell8ca47e02007-07-19 01:49:29 -07002916 "|--block=<filename>|--initrd=<filename>]...\n"
2917 "<mem-in-mb> vmlinux [args...]");
2918}
2919
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002920/*L:105 The main routine is where the real work begins: */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002921int main(int argc, char *argv[])
2922{
Rusty Russell2e04ef72009-07-30 16:03:45 -06002923 /* Memory, code startpoint and size of the (optional) initrd. */
Matias Zabaljauregui58a24562008-09-29 01:40:07 -03002924 unsigned long mem = 0, start, initrd_size = 0;
Rusty Russell56739c802009-06-12 22:26:59 -06002925 /* Two temporaries. */
2926 int i, c;
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002927 /* The boot information for the Guest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10002928 struct boot_params *boot;
Rusty Russelldde79782007-07-26 10:41:03 -07002929 /* If they specify an initrd file to load. */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002930 const char *initrd_name = NULL;
2931
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002932 /* Password structure for initgroups/setres[gu]id */
2933 struct passwd *user_details = NULL;
2934
2935 /* Directory to chroot to */
2936 char *chroot_path = NULL;
2937
Balaji Raoec04b132007-12-28 14:26:24 +05302938 /* Save the args: we "reboot" by execing ourselves again. */
2939 main_args = argv;
Balaji Raoec04b132007-12-28 14:26:24 +05302940
Rusty Russell2e04ef72009-07-30 16:03:45 -06002941 /*
2942 * First we initialize the device list. We keep a pointer to the last
Rusty Russell659a0e62009-06-12 22:27:10 -06002943 * device, and the next interrupt number to use for devices (1:
Rusty Russell2e04ef72009-07-30 16:03:45 -06002944 * remember that 0 is used by the timer).
2945 */
Rusty Russella586d4f2008-02-04 23:49:56 -05002946 devices.lastdev = NULL;
Rusty Russell17cbca22007-10-22 11:24:22 +10002947 devices.next_irq = 1;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002948
Rusty Russella91d74a2009-07-30 16:03:45 -06002949 /* We're CPU 0. In fact, that's the only CPU possible right now. */
Glauber de Oliveira Costae3283fa2008-01-07 11:05:23 -02002950 cpu_id = 0;
Rusty Russella91d74a2009-07-30 16:03:45 -06002951
Rusty Russell2e04ef72009-07-30 16:03:45 -06002952 /*
2953 * We need to know how much memory so we can set up the device
Rusty Russelldde79782007-07-26 10:41:03 -07002954 * descriptor and memory pages for the devices as we parse the command
2955 * line. So we quickly look through the arguments to find the amount
Rusty Russell2e04ef72009-07-30 16:03:45 -06002956 * of memory now.
2957 */
Rusty Russell6570c45992007-07-23 18:43:56 -07002958 for (i = 1; i < argc; i++) {
2959 if (argv[i][0] != '-') {
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002960 mem = atoi(argv[i]) * 1024 * 1024;
Rusty Russell2e04ef72009-07-30 16:03:45 -06002961 /*
2962 * We start by mapping anonymous pages over all of
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002963 * guest-physical memory range. This fills it with 0,
2964 * and ensures that the Guest won't be killed when it
Rusty Russell2e04ef72009-07-30 16:03:45 -06002965 * tries to access it.
2966 */
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10002967 guest_base = map_zeroed_pages(mem / getpagesize()
2968 + DEVICE_PAGES);
2969 guest_limit = mem;
Rusty Russell0a6bcc12015-02-11 15:15:11 +10302970 guest_max = guest_mmio = mem + DEVICE_PAGES*getpagesize();
Rusty Russell17cbca22007-10-22 11:24:22 +10002971 devices.descpage = get_pages(1);
Rusty Russell6570c45992007-07-23 18:43:56 -07002972 break;
2973 }
2974 }
Rusty Russelldde79782007-07-26 10:41:03 -07002975
2976 /* The options are fairly straight-forward */
Rusty Russell8ca47e02007-07-19 01:49:29 -07002977 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
2978 switch (c) {
2979 case 'v':
2980 verbose = true;
2981 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002982 case 't':
Rusty Russell17cbca22007-10-22 11:24:22 +10002983 setup_tun_net(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002984 break;
2985 case 'b':
Rusty Russell17cbca22007-10-22 11:24:22 +10002986 setup_block_file(optarg);
Rusty Russell8ca47e02007-07-19 01:49:29 -07002987 break;
Rusty Russell28fd6d72008-07-29 09:58:33 -05002988 case 'r':
2989 setup_rng();
2990 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07002991 case 'i':
2992 initrd_name = optarg;
2993 break;
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06002994 case 'u':
2995 user_details = getpwnam(optarg);
2996 if (!user_details)
2997 err(1, "getpwnam failed, incorrect username?");
2998 break;
2999 case 'c':
3000 chroot_path = optarg;
3001 break;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003002 default:
3003 warnx("Unknown argument %s", argv[optind]);
3004 usage();
3005 }
3006 }
Rusty Russell2e04ef72009-07-30 16:03:45 -06003007 /*
3008 * After the other arguments we expect memory and kernel image name,
3009 * followed by command line arguments for the kernel.
3010 */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003011 if (optind + 2 > argc)
3012 usage();
3013
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003014 verbose("Guest base is at %p\n", guest_base);
3015
Rusty Russelldde79782007-07-26 10:41:03 -07003016 /* We always have a console device */
Rusty Russell17cbca22007-10-22 11:24:22 +10003017 setup_console();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003018
Rusty Russell8e709462015-02-11 15:15:12 +10303019 /* Initialize the (fake) PCI host bridge device. */
3020 init_pci_host_bridge();
3021
Rusty Russell8ca47e02007-07-19 01:49:29 -07003022 /* Now we load the kernel */
Rusty Russell47436aa2007-10-22 11:03:36 +10003023 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
Rusty Russell8ca47e02007-07-19 01:49:29 -07003024
Rusty Russell3c6b5bf2007-10-22 11:03:26 +10003025 /* Boot information is stashed at physical address 0 */
3026 boot = from_guest_phys(0);
3027
Rusty Russelldde79782007-07-26 10:41:03 -07003028 /* Map the initrd image if requested (at top of physical memory) */
Rusty Russell8ca47e02007-07-19 01:49:29 -07003029 if (initrd_name) {
3030 initrd_size = load_initrd(initrd_name, mem);
Rusty Russell2e04ef72009-07-30 16:03:45 -06003031 /*
3032 * These are the location in the Linux boot header where the
3033 * start and size of the initrd are expected to be found.
3034 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003035 boot->hdr.ramdisk_image = mem - initrd_size;
3036 boot->hdr.ramdisk_size = initrd_size;
Rusty Russelldde79782007-07-26 10:41:03 -07003037 /* The bootloader type 0xFF means "unknown"; that's OK. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003038 boot->hdr.type_of_loader = 0xFF;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003039 }
3040
Rusty Russell2e04ef72009-07-30 16:03:45 -06003041 /*
3042 * The Linux boot header contains an "E820" memory map: ours is a
3043 * simple, single region.
3044 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003045 boot->e820_entries = 1;
3046 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
Rusty Russell2e04ef72009-07-30 16:03:45 -06003047 /*
3048 * The boot header contains a command line pointer: we put the command
3049 * line after the boot header.
3050 */
Rusty Russell43d33b22007-10-22 11:29:57 +10003051 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
Rusty Russelle1e72962007-10-25 15:02:50 +10003052 /* We use a simple helper to copy the arguments separated by spaces. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003053 concat((char *)(boot + 1), argv+optind+2);
Rusty Russelldde79782007-07-26 10:41:03 -07003054
Rusty Russelle22a5392011-08-15 10:15:10 +09303055 /* Set kernel alignment to 16M (CONFIG_PHYSICAL_ALIGN) */
3056 boot->hdr.kernel_alignment = 0x1000000;
3057
Rusty Russell814a0e52007-10-22 11:29:44 +10003058 /* Boot protocol version: 2.07 supports the fields for lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003059 boot->hdr.version = 0x207;
Rusty Russell814a0e52007-10-22 11:29:44 +10003060
3061 /* The hardware_subarch value of "1" tells the Guest it's an lguest. */
Rusty Russell43d33b22007-10-22 11:29:57 +10003062 boot->hdr.hardware_subarch = 1;
Rusty Russell814a0e52007-10-22 11:29:44 +10003063
Rusty Russell43d33b22007-10-22 11:29:57 +10003064 /* Tell the entry path not to try to reload segment registers. */
3065 boot->hdr.loadflags |= KEEP_SEGMENTS;
Rusty Russell8ca47e02007-07-19 01:49:29 -07003066
Rusty Russell9f542882011-07-22 14:39:50 +09303067 /* We tell the kernel to initialize the Guest. */
Rusty Russell56739c802009-06-12 22:26:59 -06003068 tell_kernel(start);
Rusty Russelldde79782007-07-26 10:41:03 -07003069
Rusty Russella91d74a2009-07-30 16:03:45 -06003070 /* Ensure that we terminate if a device-servicing child dies. */
Rusty Russell659a0e62009-06-12 22:27:10 -06003071 signal(SIGCHLD, kill_launcher);
3072
3073 /* If we exit via err(), this kills all the threads, restores tty. */
3074 atexit(cleanup_devices);
Rusty Russell8ca47e02007-07-19 01:49:29 -07003075
Philip Sanderson8aeb36e2011-01-20 21:37:28 -06003076 /* If requested, chroot to a directory */
3077 if (chroot_path) {
3078 if (chroot(chroot_path) != 0)
3079 err(1, "chroot(\"%s\") failed", chroot_path);
3080
3081 if (chdir("/") != 0)
3082 err(1, "chdir(\"/\") failed");
3083
3084 verbose("chroot done\n");
3085 }
3086
3087 /* If requested, drop privileges */
3088 if (user_details) {
3089 uid_t u;
3090 gid_t g;
3091
3092 u = user_details->pw_uid;
3093 g = user_details->pw_gid;
3094
3095 if (initgroups(user_details->pw_name, g) != 0)
3096 err(1, "initgroups failed");
3097
3098 if (setresgid(g, g, g) != 0)
3099 err(1, "setresgid failed");
3100
3101 if (setresuid(u, u, u) != 0)
3102 err(1, "setresuid failed");
3103
3104 verbose("Dropping privileges completed\n");
3105 }
3106
Rusty Russelldde79782007-07-26 10:41:03 -07003107 /* Finally, run the Guest. This doesn't return. */
Rusty Russell56739c802009-06-12 22:26:59 -06003108 run_guest();
Rusty Russell8ca47e02007-07-19 01:49:29 -07003109}
Rusty Russellf56a3842007-07-26 10:41:05 -07003110/*:*/
3111
3112/*M:999
3113 * Mastery is done: you now know everything I do.
3114 *
3115 * But surely you have seen code, features and bugs in your wanderings which
3116 * you now yearn to attack? That is the real game, and I look forward to you
3117 * patching and forking lguest into the Your-Name-Here-visor.
3118 *
3119 * Farewell, and good coding!
3120 * Rusty Russell.
3121 */