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