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