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