]> git.ipfire.org Git - thirdparty/qemu.git/blame - kvm-all.c
vfio: use kvm_resamplefds_enabled()
[thirdparty/qemu.git] / kvm-all.c
CommitLineData
05330448
AL
1/*
2 * QEMU KVM support
3 *
4 * Copyright IBM, Corp. 2008
5832d1f2 5 * Red Hat, Inc. 2008
05330448
AL
6 *
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
5832d1f2 9 * Glauber Costa <gcosta@redhat.com>
05330448
AL
10 *
11 * This work is licensed under the terms of the GNU GPL, version 2 or later.
12 * See the COPYING file in the top-level directory.
13 *
14 */
15
16#include <sys/types.h>
17#include <sys/ioctl.h>
18#include <sys/mman.h>
984b5181 19#include <stdarg.h>
05330448
AL
20
21#include <linux/kvm.h>
22
23#include "qemu-common.h"
1de7afc9
PB
24#include "qemu/atomic.h"
25#include "qemu/option.h"
26#include "qemu/config-file.h"
9c17d615 27#include "sysemu/sysemu.h"
782c3f29 28#include "sysemu/accel.h"
d33a1810 29#include "hw/hw.h"
a2cb15b0 30#include "hw/pci/msi.h"
d426d9fb 31#include "hw/s390x/adapter.h"
022c62cb 32#include "exec/gdbstub.h"
9c17d615 33#include "sysemu/kvm.h"
1de7afc9 34#include "qemu/bswap.h"
022c62cb 35#include "exec/memory.h"
747afd5b 36#include "exec/ram_addr.h"
022c62cb 37#include "exec/address-spaces.h"
1de7afc9 38#include "qemu/event_notifier.h"
9c775729 39#include "trace.h"
05330448 40
135a129a
AK
41#include "hw/boards.h"
42
d2f2b8a7
SH
43/* This check must be after config-host.h is included */
44#ifdef CONFIG_EVENTFD
45#include <sys/eventfd.h>
46#endif
47
93148aa5 48/* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
f65ed4c1
AL
49#define PAGE_SIZE TARGET_PAGE_SIZE
50
05330448
AL
51//#define DEBUG_KVM
52
53#ifdef DEBUG_KVM
8c0d577e 54#define DPRINTF(fmt, ...) \
05330448
AL
55 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
56#else
8c0d577e 57#define DPRINTF(fmt, ...) \
05330448
AL
58 do { } while (0)
59#endif
60
04fa27f5
JK
61#define KVM_MSI_HASHTAB_SIZE 256
62
34fc643f
AL
63typedef struct KVMSlot
64{
a8170e5e 65 hwaddr start_addr;
c227f099 66 ram_addr_t memory_size;
9f213ed9 67 void *ram;
34fc643f
AL
68 int slot;
69 int flags;
70} KVMSlot;
05330448 71
5832d1f2
AL
72typedef struct kvm_dirty_log KVMDirtyLog;
73
9d1c35df 74struct KVMState
05330448 75{
fc02086b
EH
76 AccelState parent_obj;
77
fb541ca5
AW
78 KVMSlot *slots;
79 int nr_slots;
05330448
AL
80 int fd;
81 int vmfd;
f65ed4c1 82 int coalesced_mmio;
62a2744c 83 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
1cae88b9 84 bool coalesced_flush_in_progress;
e69917e2 85 int broken_set_mem_region;
4495d6a7 86 int migration_log;
a0fb002c 87 int vcpu_events;
b0b1d690 88 int robust_singlestep;
ff44f1a3 89 int debugregs;
e22a25c9
AL
90#ifdef KVM_CAP_SET_GUEST_DEBUG
91 struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
92#endif
8a7c7393 93 int pit_state2;
f1665b21 94 int xsave, xcrs;
d2f2b8a7 95 int many_ioeventfds;
3ab73842 96 int intx_set_mask;
92e4b519
DG
97 /* The man page (and posix) say ioctl numbers are signed int, but
98 * they're not. Linux, glibc and *BSD all treat ioctl numbers as
99 * unsigned, and treating them as signed here can break things */
e333cd69 100 unsigned irq_set_ioctl;
aed6efb9 101 unsigned int sigmask_len;
84b058d7
JK
102#ifdef KVM_CAP_IRQ_ROUTING
103 struct kvm_irq_routing *irq_routes;
104 int nr_allocated_irq_routes;
105 uint32_t *used_gsi_bitmap;
4e2e4e63 106 unsigned int gsi_count;
04fa27f5 107 QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
4a3adebb 108 bool direct_msi;
84b058d7 109#endif
9d1c35df 110};
05330448 111
782c3f29
EH
112#define TYPE_KVM_ACCEL ACCEL_CLASS_NAME("kvm")
113
fc02086b
EH
114#define KVM_STATE(obj) \
115 OBJECT_CHECK(KVMState, (obj), TYPE_KVM_ACCEL)
116
6a7af8cb 117KVMState *kvm_state;
3d4b2649 118bool kvm_kernel_irqchip;
7ae26bd4 119bool kvm_async_interrupts_allowed;
215e79c0 120bool kvm_halt_in_kernel_allowed;
69e03ae6 121bool kvm_eventfds_allowed;
cc7e0ddf 122bool kvm_irqfds_allowed;
f41389ae 123bool kvm_resamplefds_allowed;
614e41bc 124bool kvm_msi_via_irqfd_allowed;
f3e1bed8 125bool kvm_gsi_routing_allowed;
76fe21de 126bool kvm_gsi_direct_mapping;
13eed94e 127bool kvm_allowed;
df9c8b75 128bool kvm_readonly_mem_allowed;
05330448 129
94a8d39a
JK
130static const KVMCapabilityInfo kvm_required_capabilites[] = {
131 KVM_CAP_INFO(USER_MEMORY),
132 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
133 KVM_CAP_LAST_INFO
134};
135
b8865591 136static KVMSlot *kvm_get_free_slot(KVMState *s)
05330448
AL
137{
138 int i;
139
fb541ca5 140 for (i = 0; i < s->nr_slots; i++) {
a426e122 141 if (s->slots[i].memory_size == 0) {
05330448 142 return &s->slots[i];
a426e122 143 }
05330448
AL
144 }
145
b8865591
IM
146 return NULL;
147}
148
149bool kvm_has_free_slot(MachineState *ms)
150{
151 return kvm_get_free_slot(KVM_STATE(ms->accelerator));
152}
153
154static KVMSlot *kvm_alloc_slot(KVMState *s)
155{
156 KVMSlot *slot = kvm_get_free_slot(s);
157
158 if (slot) {
159 return slot;
160 }
161
d3f8d37f
AL
162 fprintf(stderr, "%s: no free slot available\n", __func__);
163 abort();
164}
165
166static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
a8170e5e
AK
167 hwaddr start_addr,
168 hwaddr end_addr)
d3f8d37f
AL
169{
170 int i;
171
fb541ca5 172 for (i = 0; i < s->nr_slots; i++) {
d3f8d37f
AL
173 KVMSlot *mem = &s->slots[i];
174
175 if (start_addr == mem->start_addr &&
176 end_addr == mem->start_addr + mem->memory_size) {
177 return mem;
178 }
179 }
180
05330448
AL
181 return NULL;
182}
183
6152e2ae
AL
184/*
185 * Find overlapping slot with lowest start address
186 */
187static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
a8170e5e
AK
188 hwaddr start_addr,
189 hwaddr end_addr)
05330448 190{
6152e2ae 191 KVMSlot *found = NULL;
05330448
AL
192 int i;
193
fb541ca5 194 for (i = 0; i < s->nr_slots; i++) {
05330448
AL
195 KVMSlot *mem = &s->slots[i];
196
6152e2ae
AL
197 if (mem->memory_size == 0 ||
198 (found && found->start_addr < mem->start_addr)) {
199 continue;
200 }
201
202 if (end_addr > mem->start_addr &&
203 start_addr < mem->start_addr + mem->memory_size) {
204 found = mem;
205 }
05330448
AL
206 }
207
6152e2ae 208 return found;
05330448
AL
209}
210
9f213ed9 211int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
a8170e5e 212 hwaddr *phys_addr)
983dfc3b
HY
213{
214 int i;
215
fb541ca5 216 for (i = 0; i < s->nr_slots; i++) {
983dfc3b
HY
217 KVMSlot *mem = &s->slots[i];
218
9f213ed9
AK
219 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
220 *phys_addr = mem->start_addr + (ram - mem->ram);
983dfc3b
HY
221 return 1;
222 }
223 }
224
225 return 0;
226}
227
5832d1f2
AL
228static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
229{
230 struct kvm_userspace_memory_region mem;
231
232 mem.slot = slot->slot;
233 mem.guest_phys_addr = slot->start_addr;
9f213ed9 234 mem.userspace_addr = (unsigned long)slot->ram;
5832d1f2 235 mem.flags = slot->flags;
4495d6a7
JK
236 if (s->migration_log) {
237 mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
238 }
651eb0f4
XG
239
240 if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
235e8982
JJ
241 /* Set the slot size to 0 before setting the slot to the desired
242 * value. This is needed based on KVM commit 75d61fbc. */
243 mem.memory_size = 0;
244 kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
245 }
246 mem.memory_size = slot->memory_size;
5832d1f2
AL
247 return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
248}
249
504134d2 250int kvm_init_vcpu(CPUState *cpu)
05330448
AL
251{
252 KVMState *s = kvm_state;
253 long mmap_size;
254 int ret;
255
8c0d577e 256 DPRINTF("kvm_init_vcpu\n");
05330448 257
b164e48e 258 ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)kvm_arch_vcpu_id(cpu));
05330448 259 if (ret < 0) {
8c0d577e 260 DPRINTF("kvm_create_vcpu failed\n");
05330448
AL
261 goto err;
262 }
263
8737c51c 264 cpu->kvm_fd = ret;
a60f24b5 265 cpu->kvm_state = s;
20d695a9 266 cpu->kvm_vcpu_dirty = true;
05330448
AL
267
268 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
269 if (mmap_size < 0) {
748a680b 270 ret = mmap_size;
8c0d577e 271 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
05330448
AL
272 goto err;
273 }
274
f7575c96 275 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
8737c51c 276 cpu->kvm_fd, 0);
f7575c96 277 if (cpu->kvm_run == MAP_FAILED) {
05330448 278 ret = -errno;
8c0d577e 279 DPRINTF("mmap'ing vcpu state failed\n");
05330448
AL
280 goto err;
281 }
282
a426e122
JK
283 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
284 s->coalesced_mmio_ring =
f7575c96 285 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
a426e122 286 }
62a2744c 287
20d695a9 288 ret = kvm_arch_init_vcpu(cpu);
05330448
AL
289err:
290 return ret;
291}
292
5832d1f2
AL
293/*
294 * dirty pages logging control
295 */
25254bbc 296
235e8982 297static int kvm_mem_flags(KVMState *s, bool log_dirty, bool readonly)
25254bbc 298{
235e8982
JJ
299 int flags = 0;
300 flags = log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
301 if (readonly && kvm_readonly_mem_allowed) {
302 flags |= KVM_MEM_READONLY;
303 }
304 return flags;
25254bbc
MT
305}
306
307static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
5832d1f2
AL
308{
309 KVMState *s = kvm_state;
25254bbc 310 int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
4495d6a7
JK
311 int old_flags;
312
4495d6a7 313 old_flags = mem->flags;
5832d1f2 314
235e8982 315 flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty, false);
5832d1f2
AL
316 mem->flags = flags;
317
4495d6a7
JK
318 /* If nothing changed effectively, no need to issue ioctl */
319 if (s->migration_log) {
320 flags |= KVM_MEM_LOG_DIRTY_PAGES;
321 }
25254bbc 322
4495d6a7 323 if (flags == old_flags) {
25254bbc 324 return 0;
4495d6a7
JK
325 }
326
5832d1f2
AL
327 return kvm_set_user_memory_region(s, mem);
328}
329
a8170e5e 330static int kvm_dirty_pages_log_change(hwaddr phys_addr,
25254bbc
MT
331 ram_addr_t size, bool log_dirty)
332{
333 KVMState *s = kvm_state;
334 KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
335
336 if (mem == NULL) {
337 fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
338 TARGET_FMT_plx "\n", __func__, phys_addr,
a8170e5e 339 (hwaddr)(phys_addr + size - 1));
25254bbc
MT
340 return -EINVAL;
341 }
342 return kvm_slot_dirty_pages_log_change(mem, log_dirty);
343}
344
a01672d3
AK
345static void kvm_log_start(MemoryListener *listener,
346 MemoryRegionSection *section)
5832d1f2 347{
a01672d3
AK
348 int r;
349
350 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
052e87b0 351 int128_get64(section->size), true);
a01672d3
AK
352 if (r < 0) {
353 abort();
354 }
5832d1f2
AL
355}
356
a01672d3
AK
357static void kvm_log_stop(MemoryListener *listener,
358 MemoryRegionSection *section)
5832d1f2 359{
a01672d3
AK
360 int r;
361
362 r = kvm_dirty_pages_log_change(section->offset_within_address_space,
052e87b0 363 int128_get64(section->size), false);
a01672d3
AK
364 if (r < 0) {
365 abort();
366 }
5832d1f2
AL
367}
368
7b8f3b78 369static int kvm_set_migration_log(int enable)
4495d6a7
JK
370{
371 KVMState *s = kvm_state;
372 KVMSlot *mem;
373 int i, err;
374
375 s->migration_log = enable;
376
fb541ca5 377 for (i = 0; i < s->nr_slots; i++) {
4495d6a7
JK
378 mem = &s->slots[i];
379
70fedd76
AW
380 if (!mem->memory_size) {
381 continue;
382 }
4495d6a7
JK
383 if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
384 continue;
385 }
386 err = kvm_set_user_memory_region(s, mem);
387 if (err) {
388 return err;
389 }
390 }
391 return 0;
392}
393
8369e01c 394/* get kvm's dirty pages bitmap and update qemu's */
ffcde12f
AK
395static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
396 unsigned long *bitmap)
96c1606b 397{
c9dd46fc 398 ram_addr_t start = section->offset_within_region + section->mr->ram_addr;
5ff7fb77
JQ
399 ram_addr_t pages = int128_get64(section->size) / getpagesize();
400
401 cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
8369e01c 402 return 0;
96c1606b
AG
403}
404
8369e01c
MT
405#define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
406
5832d1f2
AL
407/**
408 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
fd4aa979
BS
409 * This function updates qemu's dirty bitmap using
410 * memory_region_set_dirty(). This means all bits are set
411 * to dirty.
5832d1f2 412 *
d3f8d37f 413 * @start_add: start of logged region.
5832d1f2
AL
414 * @end_addr: end of logged region.
415 */
ffcde12f 416static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
5832d1f2
AL
417{
418 KVMState *s = kvm_state;
151f7749 419 unsigned long size, allocated_size = 0;
151f7749
JK
420 KVMDirtyLog d;
421 KVMSlot *mem;
422 int ret = 0;
a8170e5e 423 hwaddr start_addr = section->offset_within_address_space;
052e87b0 424 hwaddr end_addr = start_addr + int128_get64(section->size);
5832d1f2 425
151f7749
JK
426 d.dirty_bitmap = NULL;
427 while (start_addr < end_addr) {
428 mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
429 if (mem == NULL) {
430 break;
431 }
5832d1f2 432
51b0c606
MT
433 /* XXX bad kernel interface alert
434 * For dirty bitmap, kernel allocates array of size aligned to
435 * bits-per-long. But for case when the kernel is 64bits and
436 * the userspace is 32bits, userspace can't align to the same
437 * bits-per-long, since sizeof(long) is different between kernel
438 * and user space. This way, userspace will provide buffer which
439 * may be 4 bytes less than the kernel will use, resulting in
440 * userspace memory corruption (which is not detectable by valgrind
441 * too, in most cases).
442 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
443 * a hope that sizeof(long) wont become >8 any time soon.
444 */
445 size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
446 /*HOST_LONG_BITS*/ 64) / 8;
151f7749 447 if (!d.dirty_bitmap) {
7267c094 448 d.dirty_bitmap = g_malloc(size);
151f7749 449 } else if (size > allocated_size) {
7267c094 450 d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
151f7749
JK
451 }
452 allocated_size = size;
453 memset(d.dirty_bitmap, 0, allocated_size);
5832d1f2 454
151f7749 455 d.slot = mem->slot;
5832d1f2 456
50212d63 457 if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
8c0d577e 458 DPRINTF("ioctl failed %d\n", errno);
151f7749
JK
459 ret = -1;
460 break;
461 }
5832d1f2 462
ffcde12f 463 kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
8369e01c 464 start_addr = mem->start_addr + mem->memory_size;
5832d1f2 465 }
7267c094 466 g_free(d.dirty_bitmap);
151f7749
JK
467
468 return ret;
5832d1f2
AL
469}
470
95d2994a
AK
471static void kvm_coalesce_mmio_region(MemoryListener *listener,
472 MemoryRegionSection *secion,
a8170e5e 473 hwaddr start, hwaddr size)
f65ed4c1 474{
f65ed4c1
AL
475 KVMState *s = kvm_state;
476
477 if (s->coalesced_mmio) {
478 struct kvm_coalesced_mmio_zone zone;
479
480 zone.addr = start;
481 zone.size = size;
7e680753 482 zone.pad = 0;
f65ed4c1 483
95d2994a 484 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
f65ed4c1 485 }
f65ed4c1
AL
486}
487
95d2994a
AK
488static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
489 MemoryRegionSection *secion,
a8170e5e 490 hwaddr start, hwaddr size)
f65ed4c1 491{
f65ed4c1
AL
492 KVMState *s = kvm_state;
493
494 if (s->coalesced_mmio) {
495 struct kvm_coalesced_mmio_zone zone;
496
497 zone.addr = start;
498 zone.size = size;
7e680753 499 zone.pad = 0;
f65ed4c1 500
95d2994a 501 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
f65ed4c1 502 }
f65ed4c1
AL
503}
504
ad7b8b33
AL
505int kvm_check_extension(KVMState *s, unsigned int extension)
506{
507 int ret;
508
509 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
510 if (ret < 0) {
511 ret = 0;
512 }
513
514 return ret;
515}
516
7d0a07fa
AG
517int kvm_vm_check_extension(KVMState *s, unsigned int extension)
518{
519 int ret;
520
521 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
522 if (ret < 0) {
523 /* VM wide version not implemented, use global one instead */
524 ret = kvm_check_extension(s, extension);
525 }
526
527 return ret;
528}
529
584f2be7 530static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
41cb62c2 531 bool assign, uint32_t size, bool datamatch)
500ffd4a
MT
532{
533 int ret;
534 struct kvm_ioeventfd iofd;
535
41cb62c2 536 iofd.datamatch = datamatch ? val : 0;
500ffd4a
MT
537 iofd.addr = addr;
538 iofd.len = size;
41cb62c2 539 iofd.flags = 0;
500ffd4a
MT
540 iofd.fd = fd;
541
542 if (!kvm_enabled()) {
543 return -ENOSYS;
544 }
545
41cb62c2
MT
546 if (datamatch) {
547 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
548 }
500ffd4a
MT
549 if (!assign) {
550 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
551 }
552
553 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
554
555 if (ret < 0) {
556 return -errno;
557 }
558
559 return 0;
560}
561
44c3f8f7 562static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
41cb62c2 563 bool assign, uint32_t size, bool datamatch)
500ffd4a
MT
564{
565 struct kvm_ioeventfd kick = {
41cb62c2 566 .datamatch = datamatch ? val : 0,
500ffd4a 567 .addr = addr,
41cb62c2 568 .flags = KVM_IOEVENTFD_FLAG_PIO,
44c3f8f7 569 .len = size,
500ffd4a
MT
570 .fd = fd,
571 };
572 int r;
573 if (!kvm_enabled()) {
574 return -ENOSYS;
575 }
41cb62c2
MT
576 if (datamatch) {
577 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
578 }
500ffd4a
MT
579 if (!assign) {
580 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
581 }
582 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
583 if (r < 0) {
584 return r;
585 }
586 return 0;
587}
588
589
d2f2b8a7
SH
590static int kvm_check_many_ioeventfds(void)
591{
d0dcac83
SH
592 /* Userspace can use ioeventfd for io notification. This requires a host
593 * that supports eventfd(2) and an I/O thread; since eventfd does not
594 * support SIGIO it cannot interrupt the vcpu.
595 *
596 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
d2f2b8a7
SH
597 * can avoid creating too many ioeventfds.
598 */
12d4536f 599#if defined(CONFIG_EVENTFD)
d2f2b8a7
SH
600 int ioeventfds[7];
601 int i, ret = 0;
602 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
603 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
604 if (ioeventfds[i] < 0) {
605 break;
606 }
41cb62c2 607 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
d2f2b8a7
SH
608 if (ret < 0) {
609 close(ioeventfds[i]);
610 break;
611 }
612 }
613
614 /* Decide whether many devices are supported or not */
615 ret = i == ARRAY_SIZE(ioeventfds);
616
617 while (i-- > 0) {
41cb62c2 618 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
d2f2b8a7
SH
619 close(ioeventfds[i]);
620 }
621 return ret;
622#else
623 return 0;
624#endif
625}
626
94a8d39a
JK
627static const KVMCapabilityInfo *
628kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
629{
630 while (list->name) {
631 if (!kvm_check_extension(s, list->value)) {
632 return list;
633 }
634 list++;
635 }
636 return NULL;
637}
638
a01672d3 639static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
46dbef6a
MT
640{
641 KVMState *s = kvm_state;
46dbef6a
MT
642 KVMSlot *mem, old;
643 int err;
a01672d3
AK
644 MemoryRegion *mr = section->mr;
645 bool log_dirty = memory_region_is_logging(mr);
235e8982
JJ
646 bool writeable = !mr->readonly && !mr->rom_device;
647 bool readonly_flag = mr->readonly || memory_region_is_romd(mr);
a8170e5e 648 hwaddr start_addr = section->offset_within_address_space;
052e87b0 649 ram_addr_t size = int128_get64(section->size);
9f213ed9 650 void *ram = NULL;
8f6f962b 651 unsigned delta;
46dbef6a 652
14542fea 653 /* kvm works in page size chunks, but the function may be called
f2a64032
AG
654 with sub-page size and unaligned start address. Pad the start
655 address to next and truncate size to previous page boundary. */
656 delta = (TARGET_PAGE_SIZE - (start_addr & ~TARGET_PAGE_MASK));
657 delta &= ~TARGET_PAGE_MASK;
8f6f962b
AK
658 if (delta > size) {
659 return;
660 }
661 start_addr += delta;
662 size -= delta;
663 size &= TARGET_PAGE_MASK;
664 if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
665 return;
666 }
46dbef6a 667
a01672d3 668 if (!memory_region_is_ram(mr)) {
235e8982
JJ
669 if (writeable || !kvm_readonly_mem_allowed) {
670 return;
671 } else if (!mr->romd_mode) {
672 /* If the memory device is not in romd_mode, then we actually want
673 * to remove the kvm memory slot so all accesses will trap. */
674 add = false;
675 }
9f213ed9
AK
676 }
677
8f6f962b 678 ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
a01672d3 679
46dbef6a
MT
680 while (1) {
681 mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
682 if (!mem) {
683 break;
684 }
685
a01672d3 686 if (add && start_addr >= mem->start_addr &&
46dbef6a 687 (start_addr + size <= mem->start_addr + mem->memory_size) &&
9f213ed9 688 (ram - start_addr == mem->ram - mem->start_addr)) {
46dbef6a 689 /* The new slot fits into the existing one and comes with
25254bbc
MT
690 * identical parameters - update flags and done. */
691 kvm_slot_dirty_pages_log_change(mem, log_dirty);
46dbef6a
MT
692 return;
693 }
694
695 old = *mem;
696
3fbffb62
AK
697 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
698 kvm_physical_sync_dirty_bitmap(section);
699 }
700
46dbef6a
MT
701 /* unregister the overlapping slot */
702 mem->memory_size = 0;
703 err = kvm_set_user_memory_region(s, mem);
704 if (err) {
705 fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
706 __func__, strerror(-err));
707 abort();
708 }
709
710 /* Workaround for older KVM versions: we can't join slots, even not by
711 * unregistering the previous ones and then registering the larger
712 * slot. We have to maintain the existing fragmentation. Sigh.
713 *
714 * This workaround assumes that the new slot starts at the same
715 * address as the first existing one. If not or if some overlapping
716 * slot comes around later, we will fail (not seen in practice so far)
717 * - and actually require a recent KVM version. */
718 if (s->broken_set_mem_region &&
a01672d3 719 old.start_addr == start_addr && old.memory_size < size && add) {
46dbef6a
MT
720 mem = kvm_alloc_slot(s);
721 mem->memory_size = old.memory_size;
722 mem->start_addr = old.start_addr;
9f213ed9 723 mem->ram = old.ram;
235e8982 724 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
46dbef6a
MT
725
726 err = kvm_set_user_memory_region(s, mem);
727 if (err) {
728 fprintf(stderr, "%s: error updating slot: %s\n", __func__,
729 strerror(-err));
730 abort();
731 }
732
733 start_addr += old.memory_size;
9f213ed9 734 ram += old.memory_size;
46dbef6a
MT
735 size -= old.memory_size;
736 continue;
737 }
738
739 /* register prefix slot */
740 if (old.start_addr < start_addr) {
741 mem = kvm_alloc_slot(s);
742 mem->memory_size = start_addr - old.start_addr;
743 mem->start_addr = old.start_addr;
9f213ed9 744 mem->ram = old.ram;
235e8982 745 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
46dbef6a
MT
746
747 err = kvm_set_user_memory_region(s, mem);
748 if (err) {
749 fprintf(stderr, "%s: error registering prefix slot: %s\n",
750 __func__, strerror(-err));
d4d6868f
AG
751#ifdef TARGET_PPC
752 fprintf(stderr, "%s: This is probably because your kernel's " \
753 "PAGE_SIZE is too big. Please try to use 4k " \
754 "PAGE_SIZE!\n", __func__);
755#endif
46dbef6a
MT
756 abort();
757 }
758 }
759
760 /* register suffix slot */
761 if (old.start_addr + old.memory_size > start_addr + size) {
762 ram_addr_t size_delta;
763
764 mem = kvm_alloc_slot(s);
765 mem->start_addr = start_addr + size;
766 size_delta = mem->start_addr - old.start_addr;
767 mem->memory_size = old.memory_size - size_delta;
9f213ed9 768 mem->ram = old.ram + size_delta;
235e8982 769 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
46dbef6a
MT
770
771 err = kvm_set_user_memory_region(s, mem);
772 if (err) {
773 fprintf(stderr, "%s: error registering suffix slot: %s\n",
774 __func__, strerror(-err));
775 abort();
776 }
777 }
778 }
779
780 /* in case the KVM bug workaround already "consumed" the new slot */
a426e122 781 if (!size) {
46dbef6a 782 return;
a426e122 783 }
a01672d3 784 if (!add) {
46dbef6a 785 return;
a426e122 786 }
46dbef6a
MT
787 mem = kvm_alloc_slot(s);
788 mem->memory_size = size;
789 mem->start_addr = start_addr;
9f213ed9 790 mem->ram = ram;
235e8982 791 mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
46dbef6a
MT
792
793 err = kvm_set_user_memory_region(s, mem);
794 if (err) {
795 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
796 strerror(-err));
797 abort();
798 }
799}
800
a01672d3
AK
801static void kvm_region_add(MemoryListener *listener,
802 MemoryRegionSection *section)
803{
dfde4e6e 804 memory_region_ref(section->mr);
a01672d3
AK
805 kvm_set_phys_mem(section, true);
806}
807
808static void kvm_region_del(MemoryListener *listener,
809 MemoryRegionSection *section)
810{
811 kvm_set_phys_mem(section, false);
dfde4e6e 812 memory_region_unref(section->mr);
a01672d3
AK
813}
814
815static void kvm_log_sync(MemoryListener *listener,
816 MemoryRegionSection *section)
7b8f3b78 817{
a01672d3
AK
818 int r;
819
ffcde12f 820 r = kvm_physical_sync_dirty_bitmap(section);
a01672d3
AK
821 if (r < 0) {
822 abort();
823 }
7b8f3b78
MT
824}
825
a01672d3 826static void kvm_log_global_start(struct MemoryListener *listener)
7b8f3b78 827{
a01672d3
AK
828 int r;
829
830 r = kvm_set_migration_log(1);
831 assert(r >= 0);
7b8f3b78
MT
832}
833
a01672d3 834static void kvm_log_global_stop(struct MemoryListener *listener)
7b8f3b78 835{
a01672d3
AK
836 int r;
837
838 r = kvm_set_migration_log(0);
839 assert(r >= 0);
7b8f3b78
MT
840}
841
d22b096e
AK
842static void kvm_mem_ioeventfd_add(MemoryListener *listener,
843 MemoryRegionSection *section,
844 bool match_data, uint64_t data,
845 EventNotifier *e)
846{
847 int fd = event_notifier_get_fd(e);
80a1ea37
AK
848 int r;
849
4b8f1c88 850 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
052e87b0
PB
851 data, true, int128_get64(section->size),
852 match_data);
80a1ea37 853 if (r < 0) {
fa4ba923
AK
854 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
855 __func__, strerror(-r));
80a1ea37
AK
856 abort();
857 }
858}
859
d22b096e
AK
860static void kvm_mem_ioeventfd_del(MemoryListener *listener,
861 MemoryRegionSection *section,
862 bool match_data, uint64_t data,
863 EventNotifier *e)
80a1ea37 864{
d22b096e 865 int fd = event_notifier_get_fd(e);
80a1ea37
AK
866 int r;
867
4b8f1c88 868 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
052e87b0
PB
869 data, false, int128_get64(section->size),
870 match_data);
80a1ea37
AK
871 if (r < 0) {
872 abort();
873 }
874}
875
d22b096e
AK
876static void kvm_io_ioeventfd_add(MemoryListener *listener,
877 MemoryRegionSection *section,
878 bool match_data, uint64_t data,
879 EventNotifier *e)
80a1ea37 880{
d22b096e 881 int fd = event_notifier_get_fd(e);
80a1ea37
AK
882 int r;
883
44c3f8f7 884 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
052e87b0
PB
885 data, true, int128_get64(section->size),
886 match_data);
80a1ea37 887 if (r < 0) {
fa4ba923
AK
888 fprintf(stderr, "%s: error adding ioeventfd: %s\n",
889 __func__, strerror(-r));
80a1ea37
AK
890 abort();
891 }
892}
893
d22b096e
AK
894static void kvm_io_ioeventfd_del(MemoryListener *listener,
895 MemoryRegionSection *section,
896 bool match_data, uint64_t data,
897 EventNotifier *e)
80a1ea37
AK
898
899{
d22b096e 900 int fd = event_notifier_get_fd(e);
80a1ea37
AK
901 int r;
902
44c3f8f7 903 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
052e87b0
PB
904 data, false, int128_get64(section->size),
905 match_data);
80a1ea37
AK
906 if (r < 0) {
907 abort();
908 }
909}
910
a01672d3
AK
911static MemoryListener kvm_memory_listener = {
912 .region_add = kvm_region_add,
913 .region_del = kvm_region_del,
e5896b12
AP
914 .log_start = kvm_log_start,
915 .log_stop = kvm_log_stop,
a01672d3
AK
916 .log_sync = kvm_log_sync,
917 .log_global_start = kvm_log_global_start,
918 .log_global_stop = kvm_log_global_stop,
d22b096e
AK
919 .eventfd_add = kvm_mem_ioeventfd_add,
920 .eventfd_del = kvm_mem_ioeventfd_del,
95d2994a
AK
921 .coalesced_mmio_add = kvm_coalesce_mmio_region,
922 .coalesced_mmio_del = kvm_uncoalesce_mmio_region,
d22b096e
AK
923 .priority = 10,
924};
925
926static MemoryListener kvm_io_listener = {
d22b096e
AK
927 .eventfd_add = kvm_io_ioeventfd_add,
928 .eventfd_del = kvm_io_ioeventfd_del,
72e22d2f 929 .priority = 10,
7b8f3b78
MT
930};
931
c3affe56 932static void kvm_handle_interrupt(CPUState *cpu, int mask)
aa7f74d1 933{
259186a7 934 cpu->interrupt_request |= mask;
aa7f74d1 935
60e82579 936 if (!qemu_cpu_is_self(cpu)) {
c08d7424 937 qemu_cpu_kick(cpu);
aa7f74d1
JK
938 }
939}
940
3889c3fa 941int kvm_set_irq(KVMState *s, int irq, int level)
84b058d7
JK
942{
943 struct kvm_irq_level event;
944 int ret;
945
7ae26bd4 946 assert(kvm_async_interrupts_enabled());
84b058d7
JK
947
948 event.level = level;
949 event.irq = irq;
e333cd69 950 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
84b058d7 951 if (ret < 0) {
3889c3fa 952 perror("kvm_set_irq");
84b058d7
JK
953 abort();
954 }
955
e333cd69 956 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
84b058d7
JK
957}
958
959#ifdef KVM_CAP_IRQ_ROUTING
d3d3bef0
JK
960typedef struct KVMMSIRoute {
961 struct kvm_irq_routing_entry kroute;
962 QTAILQ_ENTRY(KVMMSIRoute) entry;
963} KVMMSIRoute;
964
84b058d7
JK
965static void set_gsi(KVMState *s, unsigned int gsi)
966{
84b058d7
JK
967 s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
968}
969
04fa27f5
JK
970static void clear_gsi(KVMState *s, unsigned int gsi)
971{
972 s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
973}
974
7b774593 975void kvm_init_irq_routing(KVMState *s)
84b058d7 976{
04fa27f5 977 int gsi_count, i;
84b058d7 978
00008418 979 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
84b058d7
JK
980 if (gsi_count > 0) {
981 unsigned int gsi_bits, i;
982
983 /* Round up so we can search ints using ffs */
bc8c6788 984 gsi_bits = ALIGN(gsi_count, 32);
84b058d7 985 s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
4e2e4e63 986 s->gsi_count = gsi_count;
84b058d7
JK
987
988 /* Mark any over-allocated bits as already in use */
989 for (i = gsi_count; i < gsi_bits; i++) {
990 set_gsi(s, i);
991 }
992 }
993
994 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
995 s->nr_allocated_irq_routes = 0;
996
4a3adebb
JK
997 if (!s->direct_msi) {
998 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
999 QTAILQ_INIT(&s->msi_hashtab[i]);
1000 }
04fa27f5
JK
1001 }
1002
84b058d7
JK
1003 kvm_arch_init_irq_routing(s);
1004}
1005
cb925cf9 1006void kvm_irqchip_commit_routes(KVMState *s)
e7b20308
JK
1007{
1008 int ret;
1009
1010 s->irq_routes->flags = 0;
1011 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1012 assert(ret == 0);
1013}
1014
84b058d7
JK
1015static void kvm_add_routing_entry(KVMState *s,
1016 struct kvm_irq_routing_entry *entry)
1017{
1018 struct kvm_irq_routing_entry *new;
1019 int n, size;
1020
1021 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1022 n = s->nr_allocated_irq_routes * 2;
1023 if (n < 64) {
1024 n = 64;
1025 }
1026 size = sizeof(struct kvm_irq_routing);
1027 size += n * sizeof(*new);
1028 s->irq_routes = g_realloc(s->irq_routes, size);
1029 s->nr_allocated_irq_routes = n;
1030 }
1031 n = s->irq_routes->nr++;
1032 new = &s->irq_routes->entries[n];
0fbc2074
MT
1033
1034 *new = *entry;
84b058d7
JK
1035
1036 set_gsi(s, entry->gsi);
1037}
1038
cc57407e
JK
1039static int kvm_update_routing_entry(KVMState *s,
1040 struct kvm_irq_routing_entry *new_entry)
1041{
1042 struct kvm_irq_routing_entry *entry;
1043 int n;
1044
1045 for (n = 0; n < s->irq_routes->nr; n++) {
1046 entry = &s->irq_routes->entries[n];
1047 if (entry->gsi != new_entry->gsi) {
1048 continue;
1049 }
1050
40509f7f
MT
1051 if(!memcmp(entry, new_entry, sizeof *entry)) {
1052 return 0;
1053 }
1054
0fbc2074 1055 *entry = *new_entry;
cc57407e
JK
1056
1057 kvm_irqchip_commit_routes(s);
1058
1059 return 0;
1060 }
1061
1062 return -ESRCH;
1063}
1064
1df186df 1065void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
84b058d7 1066{
0fbc2074 1067 struct kvm_irq_routing_entry e = {};
84b058d7 1068
4e2e4e63
JK
1069 assert(pin < s->gsi_count);
1070
84b058d7
JK
1071 e.gsi = irq;
1072 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1073 e.flags = 0;
1074 e.u.irqchip.irqchip = irqchip;
1075 e.u.irqchip.pin = pin;
1076 kvm_add_routing_entry(s, &e);
1077}
1078
1e2aa8be 1079void kvm_irqchip_release_virq(KVMState *s, int virq)
04fa27f5
JK
1080{
1081 struct kvm_irq_routing_entry *e;
1082 int i;
1083
76fe21de
AK
1084 if (kvm_gsi_direct_mapping()) {
1085 return;
1086 }
1087
04fa27f5
JK
1088 for (i = 0; i < s->irq_routes->nr; i++) {
1089 e = &s->irq_routes->entries[i];
1090 if (e->gsi == virq) {
1091 s->irq_routes->nr--;
1092 *e = s->irq_routes->entries[s->irq_routes->nr];
1093 }
1094 }
1095 clear_gsi(s, virq);
1096}
1097
1098static unsigned int kvm_hash_msi(uint32_t data)
1099{
1100 /* This is optimized for IA32 MSI layout. However, no other arch shall
1101 * repeat the mistake of not providing a direct MSI injection API. */
1102 return data & 0xff;
1103}
1104
1105static void kvm_flush_dynamic_msi_routes(KVMState *s)
1106{
1107 KVMMSIRoute *route, *next;
1108 unsigned int hash;
1109
1110 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1111 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1112 kvm_irqchip_release_virq(s, route->kroute.gsi);
1113 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1114 g_free(route);
1115 }
1116 }
1117}
1118
1119static int kvm_irqchip_get_virq(KVMState *s)
1120{
1121 uint32_t *word = s->used_gsi_bitmap;
1122 int max_words = ALIGN(s->gsi_count, 32) / 32;
1123 int i, bit;
1124 bool retry = true;
1125
1126again:
1127 /* Return the lowest unused GSI in the bitmap */
1128 for (i = 0; i < max_words; i++) {
1129 bit = ffs(~word[i]);
1130 if (!bit) {
1131 continue;
1132 }
1133
1134 return bit - 1 + i * 32;
1135 }
4a3adebb 1136 if (!s->direct_msi && retry) {
04fa27f5
JK
1137 retry = false;
1138 kvm_flush_dynamic_msi_routes(s);
1139 goto again;
1140 }
1141 return -ENOSPC;
1142
1143}
1144
1145static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1146{
1147 unsigned int hash = kvm_hash_msi(msg.data);
1148 KVMMSIRoute *route;
1149
1150 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1151 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1152 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
d07cc1f1 1153 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
04fa27f5
JK
1154 return route;
1155 }
1156 }
1157 return NULL;
1158}
1159
1160int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1161{
4a3adebb 1162 struct kvm_msi msi;
04fa27f5
JK
1163 KVMMSIRoute *route;
1164
4a3adebb
JK
1165 if (s->direct_msi) {
1166 msi.address_lo = (uint32_t)msg.address;
1167 msi.address_hi = msg.address >> 32;
d07cc1f1 1168 msi.data = le32_to_cpu(msg.data);
4a3adebb
JK
1169 msi.flags = 0;
1170 memset(msi.pad, 0, sizeof(msi.pad));
1171
1172 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1173 }
1174
04fa27f5
JK
1175 route = kvm_lookup_msi_route(s, msg);
1176 if (!route) {
e7b20308 1177 int virq;
04fa27f5
JK
1178
1179 virq = kvm_irqchip_get_virq(s);
1180 if (virq < 0) {
1181 return virq;
1182 }
1183
0fbc2074 1184 route = g_malloc0(sizeof(KVMMSIRoute));
04fa27f5
JK
1185 route->kroute.gsi = virq;
1186 route->kroute.type = KVM_IRQ_ROUTING_MSI;
1187 route->kroute.flags = 0;
1188 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1189 route->kroute.u.msi.address_hi = msg.address >> 32;
d07cc1f1 1190 route->kroute.u.msi.data = le32_to_cpu(msg.data);
04fa27f5
JK
1191
1192 kvm_add_routing_entry(s, &route->kroute);
cb925cf9 1193 kvm_irqchip_commit_routes(s);
04fa27f5
JK
1194
1195 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1196 entry);
04fa27f5
JK
1197 }
1198
1199 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1200
3889c3fa 1201 return kvm_set_irq(s, route->kroute.gsi, 1);
04fa27f5
JK
1202}
1203
92b4e489
JK
1204int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1205{
0fbc2074 1206 struct kvm_irq_routing_entry kroute = {};
92b4e489
JK
1207 int virq;
1208
76fe21de
AK
1209 if (kvm_gsi_direct_mapping()) {
1210 return msg.data & 0xffff;
1211 }
1212
f3e1bed8 1213 if (!kvm_gsi_routing_enabled()) {
92b4e489
JK
1214 return -ENOSYS;
1215 }
1216
1217 virq = kvm_irqchip_get_virq(s);
1218 if (virq < 0) {
1219 return virq;
1220 }
1221
1222 kroute.gsi = virq;
1223 kroute.type = KVM_IRQ_ROUTING_MSI;
1224 kroute.flags = 0;
1225 kroute.u.msi.address_lo = (uint32_t)msg.address;
1226 kroute.u.msi.address_hi = msg.address >> 32;
d07cc1f1 1227 kroute.u.msi.data = le32_to_cpu(msg.data);
92b4e489
JK
1228
1229 kvm_add_routing_entry(s, &kroute);
cb925cf9 1230 kvm_irqchip_commit_routes(s);
92b4e489
JK
1231
1232 return virq;
1233}
1234
cc57407e
JK
1235int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1236{
0fbc2074 1237 struct kvm_irq_routing_entry kroute = {};
cc57407e 1238
76fe21de
AK
1239 if (kvm_gsi_direct_mapping()) {
1240 return 0;
1241 }
1242
cc57407e
JK
1243 if (!kvm_irqchip_in_kernel()) {
1244 return -ENOSYS;
1245 }
1246
1247 kroute.gsi = virq;
1248 kroute.type = KVM_IRQ_ROUTING_MSI;
1249 kroute.flags = 0;
1250 kroute.u.msi.address_lo = (uint32_t)msg.address;
1251 kroute.u.msi.address_hi = msg.address >> 32;
d07cc1f1 1252 kroute.u.msi.data = le32_to_cpu(msg.data);
cc57407e
JK
1253
1254 return kvm_update_routing_entry(s, &kroute);
1255}
1256
ca916d37
VM
1257static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1258 bool assign)
39853bbc
JK
1259{
1260 struct kvm_irqfd irqfd = {
1261 .fd = fd,
1262 .gsi = virq,
1263 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1264 };
1265
ca916d37
VM
1266 if (rfd != -1) {
1267 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1268 irqfd.resamplefd = rfd;
1269 }
1270
cc7e0ddf 1271 if (!kvm_irqfds_enabled()) {
39853bbc
JK
1272 return -ENOSYS;
1273 }
1274
1275 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1276}
1277
d426d9fb
CH
1278int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1279{
1280 struct kvm_irq_routing_entry kroute;
1281 int virq;
1282
1283 if (!kvm_gsi_routing_enabled()) {
1284 return -ENOSYS;
1285 }
1286
1287 virq = kvm_irqchip_get_virq(s);
1288 if (virq < 0) {
1289 return virq;
1290 }
1291
1292 kroute.gsi = virq;
1293 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1294 kroute.flags = 0;
1295 kroute.u.adapter.summary_addr = adapter->summary_addr;
1296 kroute.u.adapter.ind_addr = adapter->ind_addr;
1297 kroute.u.adapter.summary_offset = adapter->summary_offset;
1298 kroute.u.adapter.ind_offset = adapter->ind_offset;
1299 kroute.u.adapter.adapter_id = adapter->adapter_id;
1300
1301 kvm_add_routing_entry(s, &kroute);
1302 kvm_irqchip_commit_routes(s);
1303
1304 return virq;
1305}
1306
84b058d7
JK
1307#else /* !KVM_CAP_IRQ_ROUTING */
1308
7b774593 1309void kvm_init_irq_routing(KVMState *s)
84b058d7
JK
1310{
1311}
04fa27f5 1312
d3d3bef0
JK
1313void kvm_irqchip_release_virq(KVMState *s, int virq)
1314{
1315}
1316
04fa27f5
JK
1317int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1318{
1319 abort();
1320}
92b4e489
JK
1321
1322int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1323{
df410675 1324 return -ENOSYS;
92b4e489 1325}
39853bbc 1326
d426d9fb
CH
1327int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1328{
1329 return -ENOSYS;
1330}
1331
39853bbc
JK
1332static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1333{
1334 abort();
1335}
dabe3143
MT
1336
1337int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1338{
1339 return -ENOSYS;
1340}
84b058d7
JK
1341#endif /* !KVM_CAP_IRQ_ROUTING */
1342
ca916d37
VM
1343int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1344 EventNotifier *rn, int virq)
39853bbc 1345{
ca916d37
VM
1346 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1347 rn ? event_notifier_get_fd(rn) : -1, virq, true);
39853bbc
JK
1348}
1349
b131c74a 1350int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
15b2bd18 1351{
ca916d37
VM
1352 return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1353 false);
15b2bd18
PB
1354}
1355
84b058d7
JK
1356static int kvm_irqchip_create(KVMState *s)
1357{
84b058d7
JK
1358 int ret;
1359
36ad0e94 1360 if (!qemu_opt_get_bool(qemu_get_machine_opts(), "kernel_irqchip", true) ||
d426d9fb
CH
1361 (!kvm_check_extension(s, KVM_CAP_IRQCHIP) &&
1362 (kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0) < 0))) {
84b058d7
JK
1363 return 0;
1364 }
1365
d6032e06
CD
1366 /* First probe and see if there's a arch-specific hook to create the
1367 * in-kernel irqchip for us */
1368 ret = kvm_arch_irqchip_create(s);
84b058d7 1369 if (ret < 0) {
84b058d7 1370 return ret;
d6032e06
CD
1371 } else if (ret == 0) {
1372 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1373 if (ret < 0) {
1374 fprintf(stderr, "Create kernel irqchip failed\n");
1375 return ret;
1376 }
84b058d7
JK
1377 }
1378
3d4b2649 1379 kvm_kernel_irqchip = true;
7ae26bd4
PM
1380 /* If we have an in-kernel IRQ chip then we must have asynchronous
1381 * interrupt delivery (though the reverse is not necessarily true)
1382 */
1383 kvm_async_interrupts_allowed = true;
215e79c0 1384 kvm_halt_in_kernel_allowed = true;
84b058d7
JK
1385
1386 kvm_init_irq_routing(s);
1387
1388 return 0;
1389}
1390
670436ce
AJ
1391/* Find number of supported CPUs using the recommended
1392 * procedure from the kernel API documentation to cope with
1393 * older kernels that may be missing capabilities.
1394 */
1395static int kvm_recommended_vcpus(KVMState *s)
3ed444e9 1396{
670436ce
AJ
1397 int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1398 return (ret) ? ret : 4;
1399}
3ed444e9 1400
670436ce
AJ
1401static int kvm_max_vcpus(KVMState *s)
1402{
1403 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1404 return (ret) ? ret : kvm_recommended_vcpus(s);
3ed444e9
DH
1405}
1406
f6a1ef64 1407static int kvm_init(MachineState *ms)
05330448 1408{
f6a1ef64 1409 MachineClass *mc = MACHINE_GET_CLASS(ms);
168ccc11
JK
1410 static const char upgrade_note[] =
1411 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1412 "(see http://sourceforge.net/projects/kvm).\n";
670436ce
AJ
1413 struct {
1414 const char *name;
1415 int num;
1416 } num_cpus[] = {
1417 { "SMP", smp_cpus },
1418 { "hotpluggable", max_cpus },
1419 { NULL, }
1420 }, *nc = num_cpus;
1421 int soft_vcpus_limit, hard_vcpus_limit;
05330448 1422 KVMState *s;
94a8d39a 1423 const KVMCapabilityInfo *missing_cap;
05330448 1424 int ret;
135a129a
AK
1425 int i, type = 0;
1426 const char *kvm_type;
05330448 1427
fc02086b 1428 s = KVM_STATE(ms->accelerator);
05330448 1429
3145fcb6
DG
1430 /*
1431 * On systems where the kernel can support different base page
1432 * sizes, host page size may be different from TARGET_PAGE_SIZE,
1433 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
1434 * page size for the system though.
1435 */
1436 assert(TARGET_PAGE_SIZE <= getpagesize());
47c16ed5 1437 page_size_init();
3145fcb6 1438
aed6efb9
JH
1439 s->sigmask_len = 8;
1440
e22a25c9 1441#ifdef KVM_CAP_SET_GUEST_DEBUG
72cf2d4f 1442 QTAILQ_INIT(&s->kvm_sw_breakpoints);
e22a25c9 1443#endif
05330448 1444 s->vmfd = -1;
40ff6d7e 1445 s->fd = qemu_open("/dev/kvm", O_RDWR);
05330448
AL
1446 if (s->fd == -1) {
1447 fprintf(stderr, "Could not access KVM kernel module: %m\n");
1448 ret = -errno;
1449 goto err;
1450 }
1451
1452 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1453 if (ret < KVM_API_VERSION) {
0e1dac6c 1454 if (ret >= 0) {
05330448 1455 ret = -EINVAL;
a426e122 1456 }
05330448
AL
1457 fprintf(stderr, "kvm version too old\n");
1458 goto err;
1459 }
1460
1461 if (ret > KVM_API_VERSION) {
1462 ret = -EINVAL;
1463 fprintf(stderr, "kvm version not supported\n");
1464 goto err;
1465 }
1466
fb541ca5
AW
1467 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1468
1469 /* If unspecified, use the default value */
1470 if (!s->nr_slots) {
1471 s->nr_slots = 32;
1472 }
1473
1474 s->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1475
1476 for (i = 0; i < s->nr_slots; i++) {
1477 s->slots[i].slot = i;
1478 }
1479
670436ce
AJ
1480 /* check the vcpu limits */
1481 soft_vcpus_limit = kvm_recommended_vcpus(s);
1482 hard_vcpus_limit = kvm_max_vcpus(s);
3ed444e9 1483
670436ce
AJ
1484 while (nc->name) {
1485 if (nc->num > soft_vcpus_limit) {
1486 fprintf(stderr,
1487 "Warning: Number of %s cpus requested (%d) exceeds "
1488 "the recommended cpus supported by KVM (%d)\n",
1489 nc->name, nc->num, soft_vcpus_limit);
1490
1491 if (nc->num > hard_vcpus_limit) {
670436ce
AJ
1492 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1493 "the maximum cpus supported by KVM (%d)\n",
1494 nc->name, nc->num, hard_vcpus_limit);
9ba3cf54 1495 exit(1);
670436ce
AJ
1496 }
1497 }
1498 nc++;
7dc52526
MT
1499 }
1500
135a129a 1501 kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
f1e29879
MA
1502 if (mc->kvm_type) {
1503 type = mc->kvm_type(kvm_type);
135a129a 1504 } else if (kvm_type) {
0e1dac6c 1505 ret = -EINVAL;
135a129a
AK
1506 fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1507 goto err;
1508 }
1509
94ccff13 1510 do {
135a129a 1511 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
94ccff13
TK
1512 } while (ret == -EINTR);
1513
1514 if (ret < 0) {
521f438e 1515 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
94ccff13
TK
1516 strerror(-ret));
1517
0104dcac
AG
1518#ifdef TARGET_S390X
1519 fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1520 "your host kernel command line\n");
1521#endif
05330448 1522 goto err;
0104dcac 1523 }
05330448 1524
94ccff13 1525 s->vmfd = ret;
94a8d39a
JK
1526 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1527 if (!missing_cap) {
1528 missing_cap =
1529 kvm_check_extension_list(s, kvm_arch_required_capabilities);
05330448 1530 }
94a8d39a 1531 if (missing_cap) {
ad7b8b33 1532 ret = -EINVAL;
94a8d39a
JK
1533 fprintf(stderr, "kvm does not support %s\n%s",
1534 missing_cap->name, upgrade_note);
d85dc283
AL
1535 goto err;
1536 }
1537
ad7b8b33 1538 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
f65ed4c1 1539
e69917e2 1540 s->broken_set_mem_region = 1;
14a09518 1541 ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
e69917e2
JK
1542 if (ret > 0) {
1543 s->broken_set_mem_region = 0;
1544 }
e69917e2 1545
a0fb002c
JK
1546#ifdef KVM_CAP_VCPU_EVENTS
1547 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1548#endif
1549
b0b1d690
JK
1550 s->robust_singlestep =
1551 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
b0b1d690 1552
ff44f1a3
JK
1553#ifdef KVM_CAP_DEBUGREGS
1554 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1555#endif
1556
f1665b21
SY
1557#ifdef KVM_CAP_XSAVE
1558 s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1559#endif
1560
f1665b21
SY
1561#ifdef KVM_CAP_XCRS
1562 s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1563#endif
1564
8a7c7393
JK
1565#ifdef KVM_CAP_PIT_STATE2
1566 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1567#endif
1568
d3d3bef0 1569#ifdef KVM_CAP_IRQ_ROUTING
4a3adebb 1570 s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
d3d3bef0 1571#endif
4a3adebb 1572
3ab73842
JK
1573 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1574
e333cd69 1575 s->irq_set_ioctl = KVM_IRQ_LINE;
8732fbd2 1576 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
e333cd69 1577 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
8732fbd2
PM
1578 }
1579
df9c8b75
JJ
1580#ifdef KVM_CAP_READONLY_MEM
1581 kvm_readonly_mem_allowed =
1582 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1583#endif
1584
69e03ae6
NN
1585 kvm_eventfds_allowed =
1586 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1587
f41389ae
EA
1588 kvm_irqfds_allowed =
1589 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
1590
1591 kvm_resamplefds_allowed =
1592 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
1593
cad1e282 1594 ret = kvm_arch_init(s);
a426e122 1595 if (ret < 0) {
05330448 1596 goto err;
a426e122 1597 }
05330448 1598
84b058d7
JK
1599 ret = kvm_irqchip_create(s);
1600 if (ret < 0) {
1601 goto err;
1602 }
1603
05330448 1604 kvm_state = s;
f6790af6
AK
1605 memory_listener_register(&kvm_memory_listener, &address_space_memory);
1606 memory_listener_register(&kvm_io_listener, &address_space_io);
05330448 1607
d2f2b8a7
SH
1608 s->many_ioeventfds = kvm_check_many_ioeventfds();
1609
aa7f74d1
JK
1610 cpu_interrupt_handler = kvm_handle_interrupt;
1611
05330448
AL
1612 return 0;
1613
1614err:
0e1dac6c 1615 assert(ret < 0);
6d1cc321
SW
1616 if (s->vmfd >= 0) {
1617 close(s->vmfd);
1618 }
1619 if (s->fd != -1) {
1620 close(s->fd);
05330448 1621 }
fb541ca5 1622 g_free(s->slots);
05330448
AL
1623
1624 return ret;
1625}
1626
aed6efb9
JH
1627void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1628{
1629 s->sigmask_len = sigmask_len;
1630}
1631
b30e93e9
JK
1632static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1633 uint32_t count)
05330448
AL
1634{
1635 int i;
1636 uint8_t *ptr = data;
1637
1638 for (i = 0; i < count; i++) {
354678c5
JK
1639 address_space_rw(&address_space_io, port, ptr, size,
1640 direction == KVM_EXIT_IO_OUT);
05330448
AL
1641 ptr += size;
1642 }
05330448
AL
1643}
1644
5326ab55 1645static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
7c80eef8 1646{
977c7b6d
RK
1647 fprintf(stderr, "KVM internal error. Suberror: %d\n",
1648 run->internal.suberror);
1649
7c80eef8
MT
1650 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1651 int i;
1652
7c80eef8
MT
1653 for (i = 0; i < run->internal.ndata; ++i) {
1654 fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1655 i, (uint64_t)run->internal.data[i]);
1656 }
1657 }
7c80eef8
MT
1658 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1659 fprintf(stderr, "emulation failure\n");
20d695a9 1660 if (!kvm_arch_stop_on_emulation_error(cpu)) {
878096ee 1661 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
d73cd8f4 1662 return EXCP_INTERRUPT;
a426e122 1663 }
7c80eef8
MT
1664 }
1665 /* FIXME: Should trigger a qmp message to let management know
1666 * something went wrong.
1667 */
73aaec4a 1668 return -1;
7c80eef8 1669}
7c80eef8 1670
62a2744c 1671void kvm_flush_coalesced_mmio_buffer(void)
f65ed4c1 1672{
f65ed4c1 1673 KVMState *s = kvm_state;
1cae88b9
AK
1674
1675 if (s->coalesced_flush_in_progress) {
1676 return;
1677 }
1678
1679 s->coalesced_flush_in_progress = true;
1680
62a2744c
SY
1681 if (s->coalesced_mmio_ring) {
1682 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
f65ed4c1
AL
1683 while (ring->first != ring->last) {
1684 struct kvm_coalesced_mmio *ent;
1685
1686 ent = &ring->coalesced_mmio[ring->first];
1687
1688 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
85199474 1689 smp_wmb();
f65ed4c1
AL
1690 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1691 }
1692 }
1cae88b9
AK
1693
1694 s->coalesced_flush_in_progress = false;
f65ed4c1
AL
1695}
1696
20d695a9 1697static void do_kvm_cpu_synchronize_state(void *arg)
4c0960c0 1698{
20d695a9 1699 CPUState *cpu = arg;
2705d56a 1700
20d695a9
AF
1701 if (!cpu->kvm_vcpu_dirty) {
1702 kvm_arch_get_registers(cpu);
1703 cpu->kvm_vcpu_dirty = true;
4c0960c0
AK
1704 }
1705}
1706
dd1750d7 1707void kvm_cpu_synchronize_state(CPUState *cpu)
2705d56a 1708{
20d695a9
AF
1709 if (!cpu->kvm_vcpu_dirty) {
1710 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
a426e122 1711 }
2705d56a
JK
1712}
1713
c8e2085d 1714static void do_kvm_cpu_synchronize_post_reset(void *arg)
ea375f9a 1715{
c8e2085d
DH
1716 CPUState *cpu = arg;
1717
20d695a9
AF
1718 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1719 cpu->kvm_vcpu_dirty = false;
ea375f9a
JK
1720}
1721
c8e2085d
DH
1722void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1723{
1724 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, cpu);
1725}
1726
1727static void do_kvm_cpu_synchronize_post_init(void *arg)
ea375f9a 1728{
c8e2085d
DH
1729 CPUState *cpu = arg;
1730
20d695a9
AF
1731 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1732 cpu->kvm_vcpu_dirty = false;
ea375f9a
JK
1733}
1734
c8e2085d
DH
1735void kvm_cpu_synchronize_post_init(CPUState *cpu)
1736{
1737 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, cpu);
1738}
1739
de9d61e8
MT
1740void kvm_cpu_clean_state(CPUState *cpu)
1741{
1742 cpu->kvm_vcpu_dirty = false;
1743}
1744
1458c363 1745int kvm_cpu_exec(CPUState *cpu)
05330448 1746{
f7575c96 1747 struct kvm_run *run = cpu->kvm_run;
7cbb533f 1748 int ret, run_ret;
05330448 1749
8c0d577e 1750 DPRINTF("kvm_cpu_exec()\n");
05330448 1751
20d695a9 1752 if (kvm_arch_process_async_events(cpu)) {
fcd7d003 1753 cpu->exit_request = 0;
6792a57b 1754 return EXCP_HLT;
9ccfac9e 1755 }
0af691d7 1756
9ccfac9e 1757 do {
20d695a9
AF
1758 if (cpu->kvm_vcpu_dirty) {
1759 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1760 cpu->kvm_vcpu_dirty = false;
4c0960c0
AK
1761 }
1762
20d695a9 1763 kvm_arch_pre_run(cpu, run);
fcd7d003 1764 if (cpu->exit_request) {
9ccfac9e
JK
1765 DPRINTF("interrupt exit requested\n");
1766 /*
1767 * KVM requires us to reenter the kernel after IO exits to complete
1768 * instruction emulation. This self-signal will ensure that we
1769 * leave ASAP again.
1770 */
1771 qemu_cpu_kick_self();
1772 }
d549db5a 1773 qemu_mutex_unlock_iothread();
9ccfac9e 1774
1bc22652 1775 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
9ccfac9e 1776
d549db5a 1777 qemu_mutex_lock_iothread();
20d695a9 1778 kvm_arch_post_run(cpu, run);
05330448 1779
7cbb533f 1780 if (run_ret < 0) {
dc77d341
JK
1781 if (run_ret == -EINTR || run_ret == -EAGAIN) {
1782 DPRINTF("io window exit\n");
d73cd8f4 1783 ret = EXCP_INTERRUPT;
dc77d341
JK
1784 break;
1785 }
7b011fbc
ME
1786 fprintf(stderr, "error: kvm run failed %s\n",
1787 strerror(-run_ret));
a85e130e
PB
1788 ret = -1;
1789 break;
05330448
AL
1790 }
1791
b76ac80a 1792 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
05330448
AL
1793 switch (run->exit_reason) {
1794 case KVM_EXIT_IO:
8c0d577e 1795 DPRINTF("handle_io\n");
b30e93e9
JK
1796 kvm_handle_io(run->io.port,
1797 (uint8_t *)run + run->io.data_offset,
1798 run->io.direction,
1799 run->io.size,
1800 run->io.count);
d73cd8f4 1801 ret = 0;
05330448
AL
1802 break;
1803 case KVM_EXIT_MMIO:
8c0d577e 1804 DPRINTF("handle_mmio\n");
05330448
AL
1805 cpu_physical_memory_rw(run->mmio.phys_addr,
1806 run->mmio.data,
1807 run->mmio.len,
1808 run->mmio.is_write);
d73cd8f4 1809 ret = 0;
05330448
AL
1810 break;
1811 case KVM_EXIT_IRQ_WINDOW_OPEN:
8c0d577e 1812 DPRINTF("irq_window_open\n");
d73cd8f4 1813 ret = EXCP_INTERRUPT;
05330448
AL
1814 break;
1815 case KVM_EXIT_SHUTDOWN:
8c0d577e 1816 DPRINTF("shutdown\n");
05330448 1817 qemu_system_reset_request();
d73cd8f4 1818 ret = EXCP_INTERRUPT;
05330448
AL
1819 break;
1820 case KVM_EXIT_UNKNOWN:
bb44e0d1
JK
1821 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1822 (uint64_t)run->hw.hardware_exit_reason);
73aaec4a 1823 ret = -1;
05330448 1824 break;
7c80eef8 1825 case KVM_EXIT_INTERNAL_ERROR:
5326ab55 1826 ret = kvm_handle_internal_error(cpu, run);
7c80eef8 1827 break;
99040447
PS
1828 case KVM_EXIT_SYSTEM_EVENT:
1829 switch (run->system_event.type) {
1830 case KVM_SYSTEM_EVENT_SHUTDOWN:
1831 qemu_system_shutdown_request();
1832 ret = EXCP_INTERRUPT;
1833 break;
1834 case KVM_SYSTEM_EVENT_RESET:
1835 qemu_system_reset_request();
1836 ret = EXCP_INTERRUPT;
1837 break;
1838 default:
1839 DPRINTF("kvm_arch_handle_exit\n");
1840 ret = kvm_arch_handle_exit(cpu, run);
1841 break;
1842 }
1843 break;
05330448 1844 default:
8c0d577e 1845 DPRINTF("kvm_arch_handle_exit\n");
20d695a9 1846 ret = kvm_arch_handle_exit(cpu, run);
05330448
AL
1847 break;
1848 }
d73cd8f4 1849 } while (ret == 0);
05330448 1850
73aaec4a 1851 if (ret < 0) {
878096ee 1852 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
0461d5a6 1853 vm_stop(RUN_STATE_INTERNAL_ERROR);
becfc390
AL
1854 }
1855
fcd7d003 1856 cpu->exit_request = 0;
05330448
AL
1857 return ret;
1858}
1859
984b5181 1860int kvm_ioctl(KVMState *s, int type, ...)
05330448
AL
1861{
1862 int ret;
984b5181
AL
1863 void *arg;
1864 va_list ap;
05330448 1865
984b5181
AL
1866 va_start(ap, type);
1867 arg = va_arg(ap, void *);
1868 va_end(ap);
1869
9c775729 1870 trace_kvm_ioctl(type, arg);
984b5181 1871 ret = ioctl(s->fd, type, arg);
a426e122 1872 if (ret == -1) {
05330448 1873 ret = -errno;
a426e122 1874 }
05330448
AL
1875 return ret;
1876}
1877
984b5181 1878int kvm_vm_ioctl(KVMState *s, int type, ...)
05330448
AL
1879{
1880 int ret;
984b5181
AL
1881 void *arg;
1882 va_list ap;
1883
1884 va_start(ap, type);
1885 arg = va_arg(ap, void *);
1886 va_end(ap);
05330448 1887
9c775729 1888 trace_kvm_vm_ioctl(type, arg);
984b5181 1889 ret = ioctl(s->vmfd, type, arg);
a426e122 1890 if (ret == -1) {
05330448 1891 ret = -errno;
a426e122 1892 }
05330448
AL
1893 return ret;
1894}
1895
1bc22652 1896int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
05330448
AL
1897{
1898 int ret;
984b5181
AL
1899 void *arg;
1900 va_list ap;
1901
1902 va_start(ap, type);
1903 arg = va_arg(ap, void *);
1904 va_end(ap);
05330448 1905
9c775729 1906 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
8737c51c 1907 ret = ioctl(cpu->kvm_fd, type, arg);
a426e122 1908 if (ret == -1) {
05330448 1909 ret = -errno;
a426e122 1910 }
05330448
AL
1911 return ret;
1912}
bd322087 1913
0a6a7cca
CD
1914int kvm_device_ioctl(int fd, int type, ...)
1915{
1916 int ret;
1917 void *arg;
1918 va_list ap;
1919
1920 va_start(ap, type);
1921 arg = va_arg(ap, void *);
1922 va_end(ap);
1923
1924 trace_kvm_device_ioctl(fd, type, arg);
1925 ret = ioctl(fd, type, arg);
1926 if (ret == -1) {
1927 ret = -errno;
1928 }
1929 return ret;
1930}
1931
bd322087
AL
1932int kvm_has_sync_mmu(void)
1933{
94a8d39a 1934 return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
bd322087 1935}
e22a25c9 1936
a0fb002c
JK
1937int kvm_has_vcpu_events(void)
1938{
1939 return kvm_state->vcpu_events;
1940}
1941
b0b1d690
JK
1942int kvm_has_robust_singlestep(void)
1943{
1944 return kvm_state->robust_singlestep;
1945}
1946
ff44f1a3
JK
1947int kvm_has_debugregs(void)
1948{
1949 return kvm_state->debugregs;
1950}
1951
f1665b21
SY
1952int kvm_has_xsave(void)
1953{
1954 return kvm_state->xsave;
1955}
1956
1957int kvm_has_xcrs(void)
1958{
1959 return kvm_state->xcrs;
1960}
1961
8a7c7393
JK
1962int kvm_has_pit_state2(void)
1963{
1964 return kvm_state->pit_state2;
1965}
1966
d2f2b8a7
SH
1967int kvm_has_many_ioeventfds(void)
1968{
1969 if (!kvm_enabled()) {
1970 return 0;
1971 }
1972 return kvm_state->many_ioeventfds;
1973}
1974
84b058d7
JK
1975int kvm_has_gsi_routing(void)
1976{
a9c5eb0d 1977#ifdef KVM_CAP_IRQ_ROUTING
84b058d7 1978 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
a9c5eb0d
AG
1979#else
1980 return false;
1981#endif
84b058d7
JK
1982}
1983
3ab73842
JK
1984int kvm_has_intx_set_mask(void)
1985{
1986 return kvm_state->intx_set_mask;
1987}
1988
6f0437e8
JK
1989void kvm_setup_guest_memory(void *start, size_t size)
1990{
1991 if (!kvm_has_sync_mmu()) {
e78815a5 1992 int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
6f0437e8
JK
1993
1994 if (ret) {
e78815a5
AF
1995 perror("qemu_madvise");
1996 fprintf(stderr,
1997 "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
6f0437e8
JK
1998 exit(1);
1999 }
6f0437e8
JK
2000 }
2001}
2002
e22a25c9 2003#ifdef KVM_CAP_SET_GUEST_DEBUG
a60f24b5 2004struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
e22a25c9
AL
2005 target_ulong pc)
2006{
2007 struct kvm_sw_breakpoint *bp;
2008
a60f24b5 2009 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
a426e122 2010 if (bp->pc == pc) {
e22a25c9 2011 return bp;
a426e122 2012 }
e22a25c9
AL
2013 }
2014 return NULL;
2015}
2016
a60f24b5 2017int kvm_sw_breakpoints_active(CPUState *cpu)
e22a25c9 2018{
a60f24b5 2019 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
e22a25c9
AL
2020}
2021
452e4751
GC
2022struct kvm_set_guest_debug_data {
2023 struct kvm_guest_debug dbg;
a60f24b5 2024 CPUState *cpu;
452e4751
GC
2025 int err;
2026};
2027
2028static void kvm_invoke_set_guest_debug(void *data)
2029{
2030 struct kvm_set_guest_debug_data *dbg_data = data;
b3807725 2031
a60f24b5
AF
2032 dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
2033 &dbg_data->dbg);
452e4751
GC
2034}
2035
38e478ec 2036int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
e22a25c9 2037{
452e4751 2038 struct kvm_set_guest_debug_data data;
e22a25c9 2039
b0b1d690 2040 data.dbg.control = reinject_trap;
e22a25c9 2041
ed2803da 2042 if (cpu->singlestep_enabled) {
b0b1d690
JK
2043 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2044 }
20d695a9 2045 kvm_arch_update_guest_debug(cpu, &data.dbg);
a60f24b5 2046 data.cpu = cpu;
e22a25c9 2047
f100f0b3 2048 run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
452e4751 2049 return data.err;
e22a25c9
AL
2050}
2051
62278814 2052int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
e22a25c9
AL
2053 target_ulong len, int type)
2054{
2055 struct kvm_sw_breakpoint *bp;
e22a25c9
AL
2056 int err;
2057
2058 if (type == GDB_BREAKPOINT_SW) {
80b7cd73 2059 bp = kvm_find_sw_breakpoint(cpu, addr);
e22a25c9
AL
2060 if (bp) {
2061 bp->use_count++;
2062 return 0;
2063 }
2064
7267c094 2065 bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
a426e122 2066 if (!bp) {
e22a25c9 2067 return -ENOMEM;
a426e122 2068 }
e22a25c9
AL
2069
2070 bp->pc = addr;
2071 bp->use_count = 1;
80b7cd73 2072 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
e22a25c9 2073 if (err) {
7267c094 2074 g_free(bp);
e22a25c9
AL
2075 return err;
2076 }
2077
80b7cd73 2078 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
e22a25c9
AL
2079 } else {
2080 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
a426e122 2081 if (err) {
e22a25c9 2082 return err;
a426e122 2083 }
e22a25c9
AL
2084 }
2085
bdc44640 2086 CPU_FOREACH(cpu) {
38e478ec 2087 err = kvm_update_guest_debug(cpu, 0);
a426e122 2088 if (err) {
e22a25c9 2089 return err;
a426e122 2090 }
e22a25c9
AL
2091 }
2092 return 0;
2093}
2094
62278814 2095int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
e22a25c9
AL
2096 target_ulong len, int type)
2097{
2098 struct kvm_sw_breakpoint *bp;
e22a25c9
AL
2099 int err;
2100
2101 if (type == GDB_BREAKPOINT_SW) {
80b7cd73 2102 bp = kvm_find_sw_breakpoint(cpu, addr);
a426e122 2103 if (!bp) {
e22a25c9 2104 return -ENOENT;
a426e122 2105 }
e22a25c9
AL
2106
2107 if (bp->use_count > 1) {
2108 bp->use_count--;
2109 return 0;
2110 }
2111
80b7cd73 2112 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
a426e122 2113 if (err) {
e22a25c9 2114 return err;
a426e122 2115 }
e22a25c9 2116
80b7cd73 2117 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
7267c094 2118 g_free(bp);
e22a25c9
AL
2119 } else {
2120 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
a426e122 2121 if (err) {
e22a25c9 2122 return err;
a426e122 2123 }
e22a25c9
AL
2124 }
2125
bdc44640 2126 CPU_FOREACH(cpu) {
38e478ec 2127 err = kvm_update_guest_debug(cpu, 0);
a426e122 2128 if (err) {
e22a25c9 2129 return err;
a426e122 2130 }
e22a25c9
AL
2131 }
2132 return 0;
2133}
2134
1d5791f4 2135void kvm_remove_all_breakpoints(CPUState *cpu)
e22a25c9
AL
2136{
2137 struct kvm_sw_breakpoint *bp, *next;
80b7cd73 2138 KVMState *s = cpu->kvm_state;
dc54e252 2139 CPUState *tmpcpu;
e22a25c9 2140
72cf2d4f 2141 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
80b7cd73 2142 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
e22a25c9 2143 /* Try harder to find a CPU that currently sees the breakpoint. */
dc54e252
CG
2144 CPU_FOREACH(tmpcpu) {
2145 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
e22a25c9 2146 break;
a426e122 2147 }
e22a25c9
AL
2148 }
2149 }
78021d6d
JK
2150 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2151 g_free(bp);
e22a25c9
AL
2152 }
2153 kvm_arch_remove_all_hw_breakpoints();
2154
bdc44640 2155 CPU_FOREACH(cpu) {
38e478ec 2156 kvm_update_guest_debug(cpu, 0);
a426e122 2157 }
e22a25c9
AL
2158}
2159
2160#else /* !KVM_CAP_SET_GUEST_DEBUG */
2161
38e478ec 2162int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
e22a25c9
AL
2163{
2164 return -EINVAL;
2165}
2166
62278814 2167int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
e22a25c9
AL
2168 target_ulong len, int type)
2169{
2170 return -EINVAL;
2171}
2172
62278814 2173int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
e22a25c9
AL
2174 target_ulong len, int type)
2175{
2176 return -EINVAL;
2177}
2178
1d5791f4 2179void kvm_remove_all_breakpoints(CPUState *cpu)
e22a25c9
AL
2180{
2181}
2182#endif /* !KVM_CAP_SET_GUEST_DEBUG */
cc84de95 2183
491d6e80 2184int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
cc84de95 2185{
aed6efb9 2186 KVMState *s = kvm_state;
cc84de95
MT
2187 struct kvm_signal_mask *sigmask;
2188 int r;
2189
a426e122 2190 if (!sigset) {
1bc22652 2191 return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
a426e122 2192 }
cc84de95 2193
7267c094 2194 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
cc84de95 2195
aed6efb9 2196 sigmask->len = s->sigmask_len;
cc84de95 2197 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1bc22652 2198 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
7267c094 2199 g_free(sigmask);
cc84de95
MT
2200
2201 return r;
2202}
290adf38 2203int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
a1b87fe0 2204{
20d695a9 2205 return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
a1b87fe0
JK
2206}
2207
2208int kvm_on_sigbus(int code, void *addr)
2209{
2210 return kvm_arch_on_sigbus(code, addr);
2211}
0a6a7cca
CD
2212
2213int kvm_create_device(KVMState *s, uint64_t type, bool test)
2214{
2215 int ret;
2216 struct kvm_create_device create_dev;
2217
2218 create_dev.type = type;
2219 create_dev.fd = -1;
2220 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2221
2222 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2223 return -ENOTSUP;
2224 }
2225
2226 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2227 if (ret) {
2228 return ret;
2229 }
2230
2231 return test ? 0 : create_dev.fd;
2232}
ada4135f
CH
2233
2234int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2235{
2236 struct kvm_one_reg reg;
2237 int r;
2238
2239 reg.id = id;
2240 reg.addr = (uintptr_t) source;
2241 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2242 if (r) {
2243 trace_kvm_failed_reg_set(id, strerror(r));
2244 }
2245 return r;
2246}
2247
2248int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2249{
2250 struct kvm_one_reg reg;
2251 int r;
2252
2253 reg.id = id;
2254 reg.addr = (uintptr_t) target;
2255 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2256 if (r) {
2257 trace_kvm_failed_reg_get(id, strerror(r));
2258 }
2259 return r;
2260}
782c3f29
EH
2261
2262static void kvm_accel_class_init(ObjectClass *oc, void *data)
2263{
2264 AccelClass *ac = ACCEL_CLASS(oc);
2265 ac->name = "KVM";
0d15da8e 2266 ac->init_machine = kvm_init;
782c3f29
EH
2267 ac->allowed = &kvm_allowed;
2268}
2269
2270static const TypeInfo kvm_accel_type = {
2271 .name = TYPE_KVM_ACCEL,
2272 .parent = TYPE_ACCEL,
2273 .class_init = kvm_accel_class_init,
fc02086b 2274 .instance_size = sizeof(KVMState),
782c3f29
EH
2275};
2276
2277static void kvm_type_init(void)
2278{
2279 type_register_static(&kvm_accel_type);
2280}
2281
2282type_init(kvm_type_init);