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