]> git.proxmox.com Git - mirror_qemu.git/blame - accel/kvm/kvm-all.c
kvm: Fix crash due to access uninitialized kvm_state
[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>
b4420f19 18#include <poll.h>
05330448
AL
19
20#include <linux/kvm.h>
21
1de7afc9
PB
22#include "qemu/atomic.h"
23#include "qemu/option.h"
24#include "qemu/config-file.h"
4b3cfe72 25#include "qemu/error-report.h"
556969e9 26#include "qapi/error.h"
a2cb15b0 27#include "hw/pci/msi.h"
d1f6af6a 28#include "hw/pci/msix.h"
d426d9fb 29#include "hw/s390x/adapter.h"
022c62cb 30#include "exec/gdbstub.h"
8571ed35 31#include "sysemu/kvm_int.h"
54d31236 32#include "sysemu/runstate.h"
d2528bdc 33#include "sysemu/cpus.h"
f39b7d2b 34#include "sysemu/accel-blocker.h"
1de7afc9 35#include "qemu/bswap.h"
022c62cb 36#include "exec/memory.h"
747afd5b 37#include "exec/ram_addr.h"
1de7afc9 38#include "qemu/event_notifier.h"
db725815 39#include "qemu/main-loop.h"
92229a57 40#include "trace.h"
197e3524 41#include "hw/irq.h"
23b0898e 42#include "qapi/visitor.h"
11bc4a13
PB
43#include "qapi/qapi-types-common.h"
44#include "qapi/qapi-visit-common.h"
6b552b9b 45#include "sysemu/reset.h"
57038a92
CF
46#include "qemu/guest-random.h"
47#include "sysemu/hw_accel.h"
48#include "kvm-cpus.h"
baa60983 49#include "sysemu/dirtylimit.h"
f39b7d2b 50#include "qemu/range.h"
05330448 51
135a129a 52#include "hw/boards.h"
aa09b3d5 53#include "sysemu/stats.h"
135a129a 54
d2f2b8a7
SH
55/* This check must be after config-host.h is included */
56#ifdef CONFIG_EVENTFD
57#include <sys/eventfd.h>
58#endif
59
bc92e4e9
AJ
60/* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
61 * need to use the real host PAGE_SIZE, as that's what KVM will use.
62 */
eb8b1a79
JY
63#ifdef PAGE_SIZE
64#undef PAGE_SIZE
65#endif
8e3b0cbb 66#define PAGE_SIZE qemu_real_host_page_size()
f65ed4c1 67
fd2ddd16
ML
68#ifndef KVM_GUESTDBG_BLOCKIRQ
69#define KVM_GUESTDBG_BLOCKIRQ 0
70#endif
71
05330448
AL
72//#define DEBUG_KVM
73
74#ifdef DEBUG_KVM
8c0d577e 75#define DPRINTF(fmt, ...) \
05330448
AL
76 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
77#else
8c0d577e 78#define DPRINTF(fmt, ...) \
05330448
AL
79 do { } while (0)
80#endif
81
4c055ab5
GZ
82struct KVMParkedVcpu {
83 unsigned long vcpu_id;
84 int kvm_fd;
85 QLIST_ENTRY(KVMParkedVcpu) node;
86};
87
6a7af8cb 88KVMState *kvm_state;
3d4b2649 89bool kvm_kernel_irqchip;
15eafc2e 90bool kvm_split_irqchip;
7ae26bd4 91bool kvm_async_interrupts_allowed;
215e79c0 92bool kvm_halt_in_kernel_allowed;
69e03ae6 93bool kvm_eventfds_allowed;
cc7e0ddf 94bool kvm_irqfds_allowed;
f41389ae 95bool kvm_resamplefds_allowed;
614e41bc 96bool kvm_msi_via_irqfd_allowed;
f3e1bed8 97bool kvm_gsi_routing_allowed;
76fe21de 98bool kvm_gsi_direct_mapping;
13eed94e 99bool kvm_allowed;
df9c8b75 100bool kvm_readonly_mem_allowed;
d0a073a1 101bool kvm_vm_attributes_allowed;
50bf31b9 102bool kvm_direct_msi_allowed;
35108223 103bool kvm_ioeventfd_any_length_allowed;
767a554a 104bool kvm_msi_use_devid;
12bc5b4c 105bool kvm_has_guest_debug;
3b7a9388 106static int kvm_sstep_flags;
cf0f7cf9 107static bool kvm_immediate_exit;
023ae9a8 108static hwaddr kvm_max_slot_size = ~0;
05330448 109
94a8d39a
JK
110static const KVMCapabilityInfo kvm_required_capabilites[] = {
111 KVM_CAP_INFO(USER_MEMORY),
112 KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
89de4b91 113 KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
94a8d39a
JK
114 KVM_CAP_LAST_INFO
115};
116
3607715a
DG
117static NotifierList kvm_irqchip_change_notifiers =
118 NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
119
c82d9d43
PX
120struct KVMResampleFd {
121 int gsi;
122 EventNotifier *resample_event;
123 QLIST_ENTRY(KVMResampleFd) node;
124};
125typedef struct KVMResampleFd KVMResampleFd;
126
127/*
128 * Only used with split irqchip where we need to do the resample fd
129 * kick for the kernel from userspace.
130 */
131static QLIST_HEAD(, KVMResampleFd) kvm_resample_fd_list =
132 QLIST_HEAD_INITIALIZER(kvm_resample_fd_list);
133
a2f77862
PX
134static QemuMutex kml_slots_lock;
135
136#define kvm_slots_lock() qemu_mutex_lock(&kml_slots_lock)
137#define kvm_slots_unlock() qemu_mutex_unlock(&kml_slots_lock)
36adac49 138
ea776d15
PX
139static void kvm_slot_init_dirty_bitmap(KVMSlot *mem);
140
c82d9d43
PX
141static inline void kvm_resample_fd_remove(int gsi)
142{
143 KVMResampleFd *rfd;
144
145 QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
146 if (rfd->gsi == gsi) {
147 QLIST_REMOVE(rfd, node);
148 g_free(rfd);
149 break;
150 }
151 }
152}
153
154static inline void kvm_resample_fd_insert(int gsi, EventNotifier *event)
155{
156 KVMResampleFd *rfd = g_new0(KVMResampleFd, 1);
157
158 rfd->gsi = gsi;
159 rfd->resample_event = event;
160
161 QLIST_INSERT_HEAD(&kvm_resample_fd_list, rfd, node);
162}
163
164void kvm_resample_fd_notify(int gsi)
165{
166 KVMResampleFd *rfd;
167
168 QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
169 if (rfd->gsi == gsi) {
170 event_notifier_set(rfd->resample_event);
171 trace_kvm_resample_fd_notify(gsi);
172 return;
173 }
174 }
175}
176
44f2e6c1
BR
177int kvm_get_max_memslots(void)
178{
4f7f5893 179 KVMState *s = KVM_STATE(current_accel());
44f2e6c1
BR
180
181 return s->nr_slots;
182}
183
36adac49 184/* Called with KVMMemoryListener.slots_lock held */
7bbda04c 185static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
05330448 186{
7bbda04c 187 KVMState *s = kvm_state;
05330448
AL
188 int i;
189
fb541ca5 190 for (i = 0; i < s->nr_slots; i++) {
7bbda04c
PB
191 if (kml->slots[i].memory_size == 0) {
192 return &kml->slots[i];
a426e122 193 }
05330448
AL
194 }
195
b8865591
IM
196 return NULL;
197}
198
199bool kvm_has_free_slot(MachineState *ms)
200{
7bbda04c 201 KVMState *s = KVM_STATE(ms->accelerator);
36adac49
PX
202 bool result;
203 KVMMemoryListener *kml = &s->memory_listener;
204
a2f77862 205 kvm_slots_lock();
36adac49 206 result = !!kvm_get_free_slot(kml);
a2f77862 207 kvm_slots_unlock();
7bbda04c 208
36adac49 209 return result;
b8865591
IM
210}
211
36adac49 212/* Called with KVMMemoryListener.slots_lock held */
7bbda04c 213static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
b8865591 214{
7bbda04c 215 KVMSlot *slot = kvm_get_free_slot(kml);
b8865591
IM
216
217 if (slot) {
218 return slot;
219 }
220
d3f8d37f
AL
221 fprintf(stderr, "%s: no free slot available\n", __func__);
222 abort();
223}
224
7bbda04c 225static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
a8170e5e 226 hwaddr start_addr,
2747e716 227 hwaddr size)
d3f8d37f 228{
7bbda04c 229 KVMState *s = kvm_state;
d3f8d37f
AL
230 int i;
231
fb541ca5 232 for (i = 0; i < s->nr_slots; i++) {
7bbda04c 233 KVMSlot *mem = &kml->slots[i];
d3f8d37f 234
2747e716 235 if (start_addr == mem->start_addr && size == mem->memory_size) {
d3f8d37f
AL
236 return mem;
237 }
238 }
239
05330448
AL
240 return NULL;
241}
242
5ea69c2e
DH
243/*
244 * Calculate and align the start address and the size of the section.
245 * Return the size. If the size is 0, the aligned section is empty.
246 */
247static hwaddr kvm_align_section(MemoryRegionSection *section,
248 hwaddr *start)
249{
250 hwaddr size = int128_get64(section->size);
a6ffc423 251 hwaddr delta, aligned;
5ea69c2e
DH
252
253 /* kvm works in page size chunks, but the function may be called
254 with sub-page size and unaligned start address. Pad the start
255 address to next and truncate size to previous page boundary. */
a6ffc423 256 aligned = ROUND_UP(section->offset_within_address_space,
8e3b0cbb 257 qemu_real_host_page_size());
a6ffc423
DH
258 delta = aligned - section->offset_within_address_space;
259 *start = aligned;
5ea69c2e
DH
260 if (delta > size) {
261 return 0;
262 }
5ea69c2e 263
8e3b0cbb 264 return (size - delta) & qemu_real_host_page_mask();
5ea69c2e
DH
265}
266
9f213ed9 267int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
a8170e5e 268 hwaddr *phys_addr)
983dfc3b 269{
7bbda04c 270 KVMMemoryListener *kml = &s->memory_listener;
36adac49 271 int i, ret = 0;
983dfc3b 272
a2f77862 273 kvm_slots_lock();
fb541ca5 274 for (i = 0; i < s->nr_slots; i++) {
7bbda04c 275 KVMSlot *mem = &kml->slots[i];
983dfc3b 276
9f213ed9
AK
277 if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
278 *phys_addr = mem->start_addr + (ram - mem->ram);
36adac49
PX
279 ret = 1;
280 break;
983dfc3b
HY
281 }
282 }
a2f77862 283 kvm_slots_unlock();
983dfc3b 284
36adac49 285 return ret;
983dfc3b
HY
286}
287
6c090d4a 288static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
5832d1f2 289{
7bbda04c 290 KVMState *s = kvm_state;
5832d1f2 291 struct kvm_userspace_memory_region mem;
fe29141b 292 int ret;
5832d1f2 293
38bfe691 294 mem.slot = slot->slot | (kml->as_id << 16);
5832d1f2 295 mem.guest_phys_addr = slot->start_addr;
9f213ed9 296 mem.userspace_addr = (unsigned long)slot->ram;
5832d1f2 297 mem.flags = slot->flags;
651eb0f4 298
6c090d4a 299 if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
235e8982
JJ
300 /* Set the slot size to 0 before setting the slot to the desired
301 * value. This is needed based on KVM commit 75d61fbc. */
302 mem.memory_size = 0;
88cd34ee
PMD
303 ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
304 if (ret < 0) {
305 goto err;
306 }
235e8982
JJ
307 }
308 mem.memory_size = slot->memory_size;
fe29141b 309 ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
6c090d4a 310 slot->old_flags = mem.flags;
88cd34ee 311err:
fe29141b
AK
312 trace_kvm_set_user_memory(mem.slot, mem.flags, mem.guest_phys_addr,
313 mem.memory_size, mem.userspace_addr, ret);
88cd34ee
PMD
314 if (ret < 0) {
315 error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
316 " start=0x%" PRIx64 ", size=0x%" PRIx64 ": %s",
317 __func__, mem.slot, slot->start_addr,
318 (uint64_t)mem.memory_size, strerror(errno));
319 }
fe29141b 320 return ret;
5832d1f2
AL
321}
322
57038a92 323static int do_kvm_destroy_vcpu(CPUState *cpu)
4c055ab5
GZ
324{
325 KVMState *s = kvm_state;
326 long mmap_size;
327 struct KVMParkedVcpu *vcpu = NULL;
328 int ret = 0;
329
330 DPRINTF("kvm_destroy_vcpu\n");
331
b1115c99
LA
332 ret = kvm_arch_destroy_vcpu(cpu);
333 if (ret < 0) {
334 goto err;
335 }
336
4c055ab5
GZ
337 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
338 if (mmap_size < 0) {
339 ret = mmap_size;
340 DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
341 goto err;
342 }
343
344 ret = munmap(cpu->kvm_run, mmap_size);
345 if (ret < 0) {
346 goto err;
347 }
348
b4420f19 349 if (cpu->kvm_dirty_gfns) {
dcafa248 350 ret = munmap(cpu->kvm_dirty_gfns, s->kvm_dirty_ring_bytes);
b4420f19
PX
351 if (ret < 0) {
352 goto err;
353 }
354 }
355
4c055ab5
GZ
356 vcpu = g_malloc0(sizeof(*vcpu));
357 vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
358 vcpu->kvm_fd = cpu->kvm_fd;
359 QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
360err:
361 return ret;
362}
363
57038a92
CF
364void kvm_destroy_vcpu(CPUState *cpu)
365{
366 if (do_kvm_destroy_vcpu(cpu) < 0) {
367 error_report("kvm_destroy_vcpu failed");
368 exit(EXIT_FAILURE);
369 }
370}
371
4c055ab5
GZ
372static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
373{
374 struct KVMParkedVcpu *cpu;
375
376 QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
377 if (cpu->vcpu_id == vcpu_id) {
378 int kvm_fd;
379
380 QLIST_REMOVE(cpu, node);
381 kvm_fd = cpu->kvm_fd;
382 g_free(cpu);
383 return kvm_fd;
384 }
385 }
386
387 return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
388}
389
d0a92b35 390int kvm_init_vcpu(CPUState *cpu, Error **errp)
05330448
AL
391{
392 KVMState *s = kvm_state;
393 long mmap_size;
394 int ret;
395
d0a92b35 396 trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
05330448 397
4c055ab5 398 ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
05330448 399 if (ret < 0) {
d0a92b35
DDAG
400 error_setg_errno(errp, -ret, "kvm_init_vcpu: kvm_get_vcpu failed (%lu)",
401 kvm_arch_vcpu_id(cpu));
05330448
AL
402 goto err;
403 }
404
8737c51c 405 cpu->kvm_fd = ret;
a60f24b5 406 cpu->kvm_state = s;
99f31832 407 cpu->vcpu_dirty = true;
7786ae40 408 cpu->dirty_pages = 0;
baa60983 409 cpu->throttle_us_per_full = 0;
05330448
AL
410
411 mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
412 if (mmap_size < 0) {
748a680b 413 ret = mmap_size;
d0a92b35
DDAG
414 error_setg_errno(errp, -mmap_size,
415 "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
05330448
AL
416 goto err;
417 }
418
f7575c96 419 cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
8737c51c 420 cpu->kvm_fd, 0);
f7575c96 421 if (cpu->kvm_run == MAP_FAILED) {
05330448 422 ret = -errno;
d0a92b35
DDAG
423 error_setg_errno(errp, ret,
424 "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
425 kvm_arch_vcpu_id(cpu));
05330448
AL
426 goto err;
427 }
428
a426e122
JK
429 if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
430 s->coalesced_mmio_ring =
f7575c96 431 (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
a426e122 432 }
62a2744c 433
b4420f19
PX
434 if (s->kvm_dirty_ring_size) {
435 /* Use MAP_SHARED to share pages with the kernel */
dcafa248 436 cpu->kvm_dirty_gfns = mmap(NULL, s->kvm_dirty_ring_bytes,
b4420f19
PX
437 PROT_READ | PROT_WRITE, MAP_SHARED,
438 cpu->kvm_fd,
439 PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
440 if (cpu->kvm_dirty_gfns == MAP_FAILED) {
441 ret = -errno;
442 DPRINTF("mmap'ing vcpu dirty gfns failed: %d\n", ret);
443 goto err;
444 }
445 }
446
20d695a9 447 ret = kvm_arch_init_vcpu(cpu);
d0a92b35
DDAG
448 if (ret < 0) {
449 error_setg_errno(errp, -ret,
450 "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
451 kvm_arch_vcpu_id(cpu));
452 }
3b6f4852
MT
453 cpu->kvm_vcpu_stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
454
05330448
AL
455err:
456 return ret;
457}
458
5832d1f2
AL
459/*
460 * dirty pages logging control
461 */
25254bbc 462
d6ff5cbc 463static int kvm_mem_flags(MemoryRegion *mr)
25254bbc 464{
d6ff5cbc 465 bool readonly = mr->readonly || memory_region_is_romd(mr);
235e8982 466 int flags = 0;
d6ff5cbc
AJ
467
468 if (memory_region_get_dirty_log_mask(mr) != 0) {
469 flags |= KVM_MEM_LOG_DIRTY_PAGES;
470 }
235e8982
JJ
471 if (readonly && kvm_readonly_mem_allowed) {
472 flags |= KVM_MEM_READONLY;
473 }
474 return flags;
25254bbc
MT
475}
476
36adac49 477/* Called with KVMMemoryListener.slots_lock held */
7bbda04c
PB
478static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
479 MemoryRegion *mr)
5832d1f2 480{
d6ff5cbc 481 mem->flags = kvm_mem_flags(mr);
5832d1f2 482
4495d6a7 483 /* If nothing changed effectively, no need to issue ioctl */
6c090d4a 484 if (mem->flags == mem->old_flags) {
25254bbc 485 return 0;
4495d6a7
JK
486 }
487
ea776d15 488 kvm_slot_init_dirty_bitmap(mem);
6c090d4a 489 return kvm_set_user_memory_region(kml, mem, false);
5832d1f2
AL
490}
491
7bbda04c
PB
492static int kvm_section_update_flags(KVMMemoryListener *kml,
493 MemoryRegionSection *section)
25254bbc 494{
023ae9a8 495 hwaddr start_addr, size, slot_size;
343562e8 496 KVMSlot *mem;
36adac49 497 int ret = 0;
25254bbc 498
343562e8
DH
499 size = kvm_align_section(section, &start_addr);
500 if (!size) {
ea8cb1a8 501 return 0;
25254bbc 502 }
343562e8 503
a2f77862 504 kvm_slots_lock();
36adac49 505
023ae9a8
IM
506 while (size && !ret) {
507 slot_size = MIN(kvm_max_slot_size, size);
508 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
509 if (!mem) {
510 /* We don't have a slot if we want to trap every access. */
511 goto out;
512 }
343562e8 513
023ae9a8
IM
514 ret = kvm_slot_update_flags(kml, mem, section->mr);
515 start_addr += slot_size;
516 size -= slot_size;
517 }
36adac49
PX
518
519out:
a2f77862 520 kvm_slots_unlock();
36adac49 521 return ret;
25254bbc
MT
522}
523
a01672d3 524static void kvm_log_start(MemoryListener *listener,
b2dfd71c
PB
525 MemoryRegionSection *section,
526 int old, int new)
5832d1f2 527{
7bbda04c 528 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
a01672d3
AK
529 int r;
530
b2dfd71c
PB
531 if (old != 0) {
532 return;
533 }
534
7bbda04c 535 r = kvm_section_update_flags(kml, section);
a01672d3
AK
536 if (r < 0) {
537 abort();
538 }
5832d1f2
AL
539}
540
a01672d3 541static void kvm_log_stop(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 (new != 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
8369e01c 558/* get kvm's dirty pages bitmap and update qemu's */
2c20b27e 559static void kvm_slot_sync_dirty_pages(KVMSlot *slot)
96c1606b 560{
2c20b27e 561 ram_addr_t start = slot->ram_start_offset;
8e3b0cbb 562 ram_addr_t pages = slot->memory_size / qemu_real_host_page_size();
5ff7fb77 563
2c20b27e 564 cpu_physical_memory_set_dirty_lebitmap(slot->dirty_bmap, start, pages);
96c1606b
AG
565}
566
b4420f19
PX
567static void kvm_slot_reset_dirty_pages(KVMSlot *slot)
568{
569 memset(slot->dirty_bmap, 0, slot->dirty_bmap_size);
570}
571
8369e01c
MT
572#define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
573
9b3a31c7 574/* Allocate the dirty bitmap for a slot */
ea776d15 575static void kvm_slot_init_dirty_bitmap(KVMSlot *mem)
9b3a31c7 576{
ea776d15
PX
577 if (!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) || mem->dirty_bmap) {
578 return;
579 }
580
9b3a31c7
DDAG
581 /*
582 * XXX bad kernel interface alert
583 * For dirty bitmap, kernel allocates array of size aligned to
584 * bits-per-long. But for case when the kernel is 64bits and
585 * the userspace is 32bits, userspace can't align to the same
586 * bits-per-long, since sizeof(long) is different between kernel
587 * and user space. This way, userspace will provide buffer which
588 * may be 4 bytes less than the kernel will use, resulting in
589 * userspace memory corruption (which is not detectable by valgrind
590 * too, in most cases).
591 * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
592 * a hope that sizeof(long) won't become >8 any time soon.
e0a8f993
KZ
593 *
594 * Note: the granule of kvm dirty log is qemu_real_host_page_size.
595 * And mem->memory_size is aligned to it (otherwise this mem can't
596 * be registered to KVM).
9b3a31c7 597 */
8e3b0cbb 598 hwaddr bitmap_size = ALIGN(mem->memory_size / qemu_real_host_page_size(),
9b3a31c7
DDAG
599 /*HOST_LONG_BITS*/ 64) / 8;
600 mem->dirty_bmap = g_malloc0(bitmap_size);
563d32ba 601 mem->dirty_bmap_size = bitmap_size;
9b3a31c7
DDAG
602}
603
e65e5f50
PX
604/*
605 * Sync dirty bitmap from kernel to KVMSlot.dirty_bmap, return true if
606 * succeeded, false otherwise
607 */
608static bool kvm_slot_get_dirty_log(KVMState *s, KVMSlot *slot)
609{
610 struct kvm_dirty_log d = {};
611 int ret;
612
613 d.dirty_bitmap = slot->dirty_bmap;
614 d.slot = slot->slot | (slot->as_id << 16);
615 ret = kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d);
616
617 if (ret == -ENOENT) {
618 /* kernel does not have dirty bitmap in this slot */
619 ret = 0;
620 }
621 if (ret) {
622 error_report_once("%s: KVM_GET_DIRTY_LOG failed with %d",
623 __func__, ret);
624 }
625 return ret == 0;
626}
627
b4420f19
PX
628/* Should be with all slots_lock held for the address spaces. */
629static void kvm_dirty_ring_mark_page(KVMState *s, uint32_t as_id,
630 uint32_t slot_id, uint64_t offset)
631{
632 KVMMemoryListener *kml;
633 KVMSlot *mem;
634
635 if (as_id >= s->nr_as) {
636 return;
637 }
638
639 kml = s->as[as_id].ml;
640 mem = &kml->slots[slot_id];
641
642 if (!mem->memory_size || offset >=
8e3b0cbb 643 (mem->memory_size / qemu_real_host_page_size())) {
b4420f19
PX
644 return;
645 }
646
647 set_bit(offset, mem->dirty_bmap);
648}
649
650static bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
651{
4802bf91
PB
652 /*
653 * Read the flags before the value. Pairs with barrier in
654 * KVM's kvm_dirty_ring_push() function.
655 */
656 return qatomic_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;
b4420f19
PX
657}
658
659static void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
660{
52281c6d
PB
661 /*
662 * Use a store-release so that the CPU that executes KVM_RESET_DIRTY_RINGS
663 * sees the full content of the ring:
664 *
665 * CPU0 CPU1 CPU2
666 * ------------------------------------------------------------------------------
667 * fill gfn0
668 * store-rel flags for gfn0
669 * load-acq flags for gfn0
670 * store-rel RESET for gfn0
671 * ioctl(RESET_RINGS)
672 * load-acq flags for gfn0
673 * check if flags have RESET
674 *
675 * The synchronization goes from CPU2 to CPU0 to CPU1.
676 */
677 qatomic_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);
b4420f19
PX
678}
679
680/*
681 * Should be with all slots_lock held for the address spaces. It returns the
682 * dirty page we've collected on this dirty ring.
683 */
684static uint32_t kvm_dirty_ring_reap_one(KVMState *s, CPUState *cpu)
685{
686 struct kvm_dirty_gfn *dirty_gfns = cpu->kvm_dirty_gfns, *cur;
687 uint32_t ring_size = s->kvm_dirty_ring_size;
688 uint32_t count = 0, fetch = cpu->kvm_fetch_index;
689
56adee40
PX
690 /*
691 * It's possible that we race with vcpu creation code where the vcpu is
692 * put onto the vcpus list but not yet initialized the dirty ring
693 * structures. If so, skip it.
694 */
695 if (!cpu->created) {
696 return 0;
697 }
698
b4420f19
PX
699 assert(dirty_gfns && ring_size);
700 trace_kvm_dirty_ring_reap_vcpu(cpu->cpu_index);
701
702 while (true) {
703 cur = &dirty_gfns[fetch % ring_size];
704 if (!dirty_gfn_is_dirtied(cur)) {
705 break;
706 }
707 kvm_dirty_ring_mark_page(s, cur->slot >> 16, cur->slot & 0xffff,
708 cur->offset);
709 dirty_gfn_set_collected(cur);
710 trace_kvm_dirty_ring_page(cpu->cpu_index, fetch, cur->offset);
711 fetch++;
712 count++;
713 }
714 cpu->kvm_fetch_index = fetch;
7786ae40 715 cpu->dirty_pages += count;
b4420f19
PX
716
717 return count;
718}
719
720/* Must be with slots_lock held */
1667e2b9 721static uint64_t kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
b4420f19
PX
722{
723 int ret;
b4420f19
PX
724 uint64_t total = 0;
725 int64_t stamp;
726
727 stamp = get_clock();
728
1667e2b9
HH
729 if (cpu) {
730 total = kvm_dirty_ring_reap_one(s, cpu);
731 } else {
732 CPU_FOREACH(cpu) {
733 total += kvm_dirty_ring_reap_one(s, cpu);
734 }
b4420f19
PX
735 }
736
737 if (total) {
738 ret = kvm_vm_ioctl(s, KVM_RESET_DIRTY_RINGS);
739 assert(ret == total);
740 }
741
742 stamp = get_clock() - stamp;
743
744 if (total) {
745 trace_kvm_dirty_ring_reap(total, stamp / 1000);
746 }
747
748 return total;
749}
750
751/*
752 * Currently for simplicity, we must hold BQL before calling this. We can
753 * consider to drop the BQL if we're clear with all the race conditions.
754 */
1667e2b9 755static uint64_t kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
b4420f19
PX
756{
757 uint64_t total;
758
759 /*
760 * We need to lock all kvm slots for all address spaces here,
761 * because:
762 *
763 * (1) We need to mark dirty for dirty bitmaps in multiple slots
764 * and for tons of pages, so it's better to take the lock here
765 * once rather than once per page. And more importantly,
766 *
767 * (2) We must _NOT_ publish dirty bits to the other threads
768 * (e.g., the migration thread) via the kvm memory slot dirty
769 * bitmaps before correctly re-protect those dirtied pages.
770 * Otherwise we can have potential risk of data corruption if
771 * the page data is read in the other thread before we do
772 * reset below.
773 */
774 kvm_slots_lock();
1667e2b9 775 total = kvm_dirty_ring_reap_locked(s, cpu);
b4420f19
PX
776 kvm_slots_unlock();
777
778 return total;
779}
780
781static void do_kvm_cpu_synchronize_kick(CPUState *cpu, run_on_cpu_data arg)
782{
783 /* No need to do anything */
784}
785
786/*
787 * Kick all vcpus out in a synchronized way. When returned, we
788 * guarantee that every vcpu has been kicked and at least returned to
789 * userspace once.
790 */
791static void kvm_cpu_synchronize_kick_all(void)
792{
793 CPUState *cpu;
794
795 CPU_FOREACH(cpu) {
796 run_on_cpu(cpu, do_kvm_cpu_synchronize_kick, RUN_ON_CPU_NULL);
797 }
798}
799
800/*
801 * Flush all the existing dirty pages to the KVM slot buffers. When
802 * this call returns, we guarantee that all the touched dirty pages
803 * before calling this function have been put into the per-kvmslot
804 * dirty bitmap.
805 *
806 * This function must be called with BQL held.
807 */
808static void kvm_dirty_ring_flush(void)
809{
810 trace_kvm_dirty_ring_flush(0);
811 /*
812 * The function needs to be serialized. Since this function
813 * should always be with BQL held, serialization is guaranteed.
814 * However, let's be sure of it.
815 */
816 assert(qemu_mutex_iothread_locked());
817 /*
818 * First make sure to flush the hardware buffers by kicking all
819 * vcpus out in a synchronous way.
820 */
821 kvm_cpu_synchronize_kick_all();
1667e2b9 822 kvm_dirty_ring_reap(kvm_state, NULL);
b4420f19
PX
823 trace_kvm_dirty_ring_flush(1);
824}
825
5832d1f2 826/**
4a12a11a 827 * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
5832d1f2 828 *
4a12a11a
PX
829 * This function will first try to fetch dirty bitmap from the kernel,
830 * and then updates qemu's dirty bitmap.
831 *
36adac49
PX
832 * NOTE: caller must be with kml->slots_lock held.
833 *
4a12a11a
PX
834 * @kml: the KVM memory listener object
835 * @section: the memory section to sync the dirty bitmap with
5832d1f2 836 */
e65e5f50
PX
837static void kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
838 MemoryRegionSection *section)
5832d1f2
AL
839{
840 KVMState *s = kvm_state;
151f7749 841 KVMSlot *mem;
67548f09 842 hwaddr start_addr, size;
2c20b27e 843 hwaddr slot_size;
67548f09
DH
844
845 size = kvm_align_section(section, &start_addr);
023ae9a8 846 while (size) {
023ae9a8
IM
847 slot_size = MIN(kvm_max_slot_size, size);
848 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
67548f09 849 if (!mem) {
e377e87c 850 /* We don't have a slot if we want to trap every access. */
e65e5f50 851 return;
151f7749 852 }
e65e5f50 853 if (kvm_slot_get_dirty_log(s, mem)) {
2c20b27e 854 kvm_slot_sync_dirty_pages(mem);
151f7749 855 }
023ae9a8
IM
856 start_addr += slot_size;
857 size -= slot_size;
5832d1f2 858 }
5832d1f2
AL
859}
860
ff4aa114
PX
861/* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
862#define KVM_CLEAR_LOG_SHIFT 6
8e3b0cbb 863#define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size() << KVM_CLEAR_LOG_SHIFT)
ff4aa114
PX
864#define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
865
4222147d
PB
866static int kvm_log_clear_one_slot(KVMSlot *mem, int as_id, uint64_t start,
867 uint64_t size)
ff4aa114
PX
868{
869 KVMState *s = kvm_state;
4222147d 870 uint64_t end, bmap_start, start_delta, bmap_npages;
ff4aa114 871 struct kvm_clear_dirty_log d;
8e3b0cbb 872 unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size();
4222147d 873 int ret;
ff4aa114
PX
874
875 /*
876 * We need to extend either the start or the size or both to
877 * satisfy the KVM interface requirement. Firstly, do the start
878 * page alignment on 64 host pages
879 */
84516e5b
PB
880 bmap_start = start & KVM_CLEAR_LOG_MASK;
881 start_delta = start - bmap_start;
ff4aa114
PX
882 bmap_start /= psize;
883
884 /*
885 * The kernel interface has restriction on the size too, that either:
886 *
887 * (1) the size is 64 host pages aligned (just like the start), or
888 * (2) the size fills up until the end of the KVM memslot.
889 */
890 bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
891 << KVM_CLEAR_LOG_SHIFT;
892 end = mem->memory_size / psize;
893 if (bmap_npages > end - bmap_start) {
894 bmap_npages = end - bmap_start;
895 }
896 start_delta /= psize;
897
898 /*
899 * Prepare the bitmap to clear dirty bits. Here we must guarantee
900 * that we won't clear any unknown dirty bits otherwise we might
901 * accidentally clear some set bits which are not yet synced from
902 * the kernel into QEMU's bitmap, then we'll lose track of the
903 * guest modifications upon those pages (which can directly lead
904 * to guest data loss or panic after migration).
905 *
906 * Layout of the KVMSlot.dirty_bmap:
907 *
908 * |<-------- bmap_npages -----------..>|
909 * [1]
910 * start_delta size
911 * |----------------|-------------|------------------|------------|
912 * ^ ^ ^ ^
913 * | | | |
914 * start bmap_start (start) end
915 * of memslot of memslot
916 *
917 * [1] bmap_npages can be aligned to either 64 pages or the end of slot
918 */
919
920 assert(bmap_start % BITS_PER_LONG == 0);
921 /* We should never do log_clear before log_sync */
922 assert(mem->dirty_bmap);
4054adbd 923 if (start_delta || bmap_npages - size / psize) {
ff4aa114
PX
924 /* Slow path - we need to manipulate a temp bitmap */
925 bmap_clear = bitmap_new(bmap_npages);
926 bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
927 bmap_start, start_delta + size / psize);
928 /*
929 * We need to fill the holes at start because that was not
930 * specified by the caller and we extended the bitmap only for
931 * 64 pages alignment
932 */
933 bitmap_clear(bmap_clear, 0, start_delta);
934 d.dirty_bitmap = bmap_clear;
935 } else {
4054adbd
ZY
936 /*
937 * Fast path - both start and size align well with BITS_PER_LONG
938 * (or the end of memory slot)
939 */
ff4aa114
PX
940 d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
941 }
942
943 d.first_page = bmap_start;
944 /* It should never overflow. If it happens, say something */
945 assert(bmap_npages <= UINT32_MAX);
946 d.num_pages = bmap_npages;
4222147d 947 d.slot = mem->slot | (as_id << 16);
ff4aa114 948
38e0b790
TH
949 ret = kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d);
950 if (ret < 0 && ret != -ENOENT) {
ff4aa114
PX
951 error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
952 "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
953 __func__, d.slot, (uint64_t)d.first_page,
954 (uint32_t)d.num_pages, ret);
955 } else {
956 ret = 0;
957 trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
958 }
959
960 /*
961 * After we have updated the remote dirty bitmap, we update the
962 * cached bitmap as well for the memslot, then if another user
963 * clears the same region we know we shouldn't clear it again on
964 * the remote otherwise it's data loss as well.
965 */
966 bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
967 size / psize);
968 /* This handles the NULL case well */
969 g_free(bmap_clear);
4222147d
PB
970 return ret;
971}
972
973
974/**
975 * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
976 *
977 * NOTE: this will be a no-op if we haven't enabled manual dirty log
978 * protection in the host kernel because in that case this operation
979 * will be done within log_sync().
980 *
981 * @kml: the kvm memory listener
982 * @section: the memory range to clear dirty bitmap
983 */
984static int kvm_physical_log_clear(KVMMemoryListener *kml,
985 MemoryRegionSection *section)
986{
987 KVMState *s = kvm_state;
84516e5b
PB
988 uint64_t start, size, offset, count;
989 KVMSlot *mem;
87287ac0 990 int ret = 0, i;
4222147d
PB
991
992 if (!s->manual_dirty_log_protect) {
993 /* No need to do explicit clear */
87287ac0 994 return ret;
4222147d
PB
995 }
996
997 start = section->offset_within_address_space;
998 size = int128_get64(section->size);
999
1000 if (!size) {
1001 /* Nothing more we can do... */
87287ac0 1002 return ret;
4222147d
PB
1003 }
1004
a2f77862 1005 kvm_slots_lock();
4222147d 1006
4222147d
PB
1007 for (i = 0; i < s->nr_slots; i++) {
1008 mem = &kml->slots[i];
84516e5b
PB
1009 /* Discard slots that are empty or do not overlap the section */
1010 if (!mem->memory_size ||
1011 mem->start_addr > start + size - 1 ||
1012 start > mem->start_addr + mem->memory_size - 1) {
1013 continue;
1014 }
1015
1016 if (start >= mem->start_addr) {
1017 /* The slot starts before section or is aligned to it. */
1018 offset = start - mem->start_addr;
1019 count = MIN(mem->memory_size - offset, size);
1020 } else {
1021 /* The slot starts after section. */
1022 offset = 0;
1023 count = MIN(mem->memory_size, size - (mem->start_addr - start));
1024 }
1025 ret = kvm_log_clear_one_slot(mem, kml->as_id, offset, count);
1026 if (ret < 0) {
4222147d
PB
1027 break;
1028 }
1029 }
1030
a2f77862 1031 kvm_slots_unlock();
ff4aa114
PX
1032
1033 return ret;
1034}
1035
95d2994a
AK
1036static void kvm_coalesce_mmio_region(MemoryListener *listener,
1037 MemoryRegionSection *secion,
a8170e5e 1038 hwaddr start, hwaddr size)
f65ed4c1 1039{
f65ed4c1
AL
1040 KVMState *s = kvm_state;
1041
1042 if (s->coalesced_mmio) {
1043 struct kvm_coalesced_mmio_zone zone;
1044
1045 zone.addr = start;
1046 zone.size = size;
7e680753 1047 zone.pad = 0;
f65ed4c1 1048
95d2994a 1049 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
f65ed4c1 1050 }
f65ed4c1
AL
1051}
1052
95d2994a
AK
1053static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
1054 MemoryRegionSection *secion,
a8170e5e 1055 hwaddr start, hwaddr size)
f65ed4c1 1056{
f65ed4c1
AL
1057 KVMState *s = kvm_state;
1058
1059 if (s->coalesced_mmio) {
1060 struct kvm_coalesced_mmio_zone zone;
1061
1062 zone.addr = start;
1063 zone.size = size;
7e680753 1064 zone.pad = 0;
f65ed4c1 1065
95d2994a 1066 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
f65ed4c1 1067 }
f65ed4c1
AL
1068}
1069
e6d34aee
PH
1070static void kvm_coalesce_pio_add(MemoryListener *listener,
1071 MemoryRegionSection *section,
1072 hwaddr start, hwaddr size)
1073{
1074 KVMState *s = kvm_state;
1075
1076 if (s->coalesced_pio) {
1077 struct kvm_coalesced_mmio_zone zone;
1078
1079 zone.addr = start;
1080 zone.size = size;
1081 zone.pio = 1;
1082
1083 (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
1084 }
1085}
1086
1087static void kvm_coalesce_pio_del(MemoryListener *listener,
1088 MemoryRegionSection *section,
1089 hwaddr start, hwaddr size)
1090{
1091 KVMState *s = kvm_state;
1092
1093 if (s->coalesced_pio) {
1094 struct kvm_coalesced_mmio_zone zone;
1095
1096 zone.addr = start;
1097 zone.size = size;
1098 zone.pio = 1;
1099
1100 (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
1101 }
1102}
1103
1104static MemoryListener kvm_coalesced_pio_listener = {
142518bd 1105 .name = "kvm-coalesced-pio",
e6d34aee
PH
1106 .coalesced_io_add = kvm_coalesce_pio_add,
1107 .coalesced_io_del = kvm_coalesce_pio_del,
14a868c6 1108 .priority = MEMORY_LISTENER_PRIORITY_MIN,
e6d34aee
PH
1109};
1110
ad7b8b33
AL
1111int kvm_check_extension(KVMState *s, unsigned int extension)
1112{
1113 int ret;
1114
1115 ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
1116 if (ret < 0) {
1117 ret = 0;
1118 }
1119
1120 return ret;
1121}
1122
7d0a07fa
AG
1123int kvm_vm_check_extension(KVMState *s, unsigned int extension)
1124{
1125 int ret;
1126
1127 ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
1128 if (ret < 0) {
1129 /* VM wide version not implemented, use global one instead */
1130 ret = kvm_check_extension(s, extension);
1131 }
1132
1133 return ret;
1134}
1135
6b552b9b
DG
1136typedef struct HWPoisonPage {
1137 ram_addr_t ram_addr;
1138 QLIST_ENTRY(HWPoisonPage) list;
1139} HWPoisonPage;
1140
1141static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
1142 QLIST_HEAD_INITIALIZER(hwpoison_page_list);
1143
1144static void kvm_unpoison_all(void *param)
1145{
1146 HWPoisonPage *page, *next_page;
1147
1148 QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
1149 QLIST_REMOVE(page, list);
1150 qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
1151 g_free(page);
1152 }
1153}
1154
1155void kvm_hwpoison_page_add(ram_addr_t ram_addr)
1156{
1157 HWPoisonPage *page;
1158
1159 QLIST_FOREACH(page, &hwpoison_page_list, list) {
1160 if (page->ram_addr == ram_addr) {
1161 return;
1162 }
1163 }
1164 page = g_new(HWPoisonPage, 1);
1165 page->ram_addr = ram_addr;
1166 QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
1167}
1168
b680c5ba
GK
1169static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
1170{
ee3eb3a7 1171#if HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN
e03b5686 1172 /* The kernel expects ioeventfd values in HOST_BIG_ENDIAN
b680c5ba
GK
1173 * endianness, but the memory core hands them in target endianness.
1174 * For example, PPC is always treated as big-endian even if running
1175 * on KVM and on PPC64LE. Correct here.
1176 */
1177 switch (size) {
1178 case 2:
1179 val = bswap16(val);
1180 break;
1181 case 4:
1182 val = bswap32(val);
1183 break;
1184 }
1185#endif
1186 return val;
1187}
1188
584f2be7 1189static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
41cb62c2 1190 bool assign, uint32_t size, bool datamatch)
500ffd4a
MT
1191{
1192 int ret;
03a96b83
TH
1193 struct kvm_ioeventfd iofd = {
1194 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
1195 .addr = addr,
1196 .len = size,
1197 .flags = 0,
1198 .fd = fd,
1199 };
500ffd4a 1200
876d16cd
DDAG
1201 trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
1202 datamatch);
500ffd4a
MT
1203 if (!kvm_enabled()) {
1204 return -ENOSYS;
1205 }
1206
41cb62c2
MT
1207 if (datamatch) {
1208 iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1209 }
500ffd4a
MT
1210 if (!assign) {
1211 iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1212 }
1213
1214 ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
1215
1216 if (ret < 0) {
1217 return -errno;
1218 }
1219
1220 return 0;
1221}
1222
44c3f8f7 1223static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
41cb62c2 1224 bool assign, uint32_t size, bool datamatch)
500ffd4a
MT
1225{
1226 struct kvm_ioeventfd kick = {
b680c5ba 1227 .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
500ffd4a 1228 .addr = addr,
41cb62c2 1229 .flags = KVM_IOEVENTFD_FLAG_PIO,
44c3f8f7 1230 .len = size,
500ffd4a
MT
1231 .fd = fd,
1232 };
1233 int r;
876d16cd 1234 trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
500ffd4a
MT
1235 if (!kvm_enabled()) {
1236 return -ENOSYS;
1237 }
41cb62c2
MT
1238 if (datamatch) {
1239 kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
1240 }
500ffd4a
MT
1241 if (!assign) {
1242 kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
1243 }
1244 r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
1245 if (r < 0) {
1246 return r;
1247 }
1248 return 0;
1249}
1250
1251
d2f2b8a7
SH
1252static int kvm_check_many_ioeventfds(void)
1253{
d0dcac83
SH
1254 /* Userspace can use ioeventfd for io notification. This requires a host
1255 * that supports eventfd(2) and an I/O thread; since eventfd does not
1256 * support SIGIO it cannot interrupt the vcpu.
1257 *
1258 * Older kernels have a 6 device limit on the KVM io bus. Find out so we
d2f2b8a7
SH
1259 * can avoid creating too many ioeventfds.
1260 */
12d4536f 1261#if defined(CONFIG_EVENTFD)
d2f2b8a7
SH
1262 int ioeventfds[7];
1263 int i, ret = 0;
1264 for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
1265 ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
1266 if (ioeventfds[i] < 0) {
1267 break;
1268 }
41cb62c2 1269 ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
d2f2b8a7
SH
1270 if (ret < 0) {
1271 close(ioeventfds[i]);
1272 break;
1273 }
1274 }
1275
1276 /* Decide whether many devices are supported or not */
1277 ret = i == ARRAY_SIZE(ioeventfds);
1278
1279 while (i-- > 0) {
41cb62c2 1280 kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
d2f2b8a7
SH
1281 close(ioeventfds[i]);
1282 }
1283 return ret;
1284#else
1285 return 0;
1286#endif
1287}
1288
94a8d39a
JK
1289static const KVMCapabilityInfo *
1290kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
1291{
1292 while (list->name) {
1293 if (!kvm_check_extension(s, list->value)) {
1294 return list;
1295 }
1296 list++;
1297 }
1298 return NULL;
1299}
1300
023ae9a8
IM
1301void kvm_set_max_memslot_size(hwaddr max_slot_size)
1302{
1303 g_assert(
8e3b0cbb 1304 ROUND_UP(max_slot_size, qemu_real_host_page_size()) == max_slot_size
023ae9a8
IM
1305 );
1306 kvm_max_slot_size = max_slot_size;
1307}
1308
f39b7d2b 1309/* Called with KVMMemoryListener.slots_lock held */
7bbda04c
PB
1310static void kvm_set_phys_mem(KVMMemoryListener *kml,
1311 MemoryRegionSection *section, bool add)
46dbef6a 1312{
f357f564 1313 KVMSlot *mem;
46dbef6a 1314 int err;
a01672d3 1315 MemoryRegion *mr = section->mr;
9323e79f 1316 bool writable = !mr->readonly && !mr->rom_device;
2c20b27e
PX
1317 hwaddr start_addr, size, slot_size, mr_offset;
1318 ram_addr_t ram_start_offset;
5ea69c2e 1319 void *ram;
46dbef6a 1320
a01672d3 1321 if (!memory_region_is_ram(mr)) {
9323e79f 1322 if (writable || !kvm_readonly_mem_allowed) {
235e8982
JJ
1323 return;
1324 } else if (!mr->romd_mode) {
1325 /* If the memory device is not in romd_mode, then we actually want
1326 * to remove the kvm memory slot so all accesses will trap. */
1327 add = false;
1328 }
9f213ed9
AK
1329 }
1330
5ea69c2e
DH
1331 size = kvm_align_section(section, &start_addr);
1332 if (!size) {
1333 return;
1334 }
1335
2c20b27e
PX
1336 /* The offset of the kvmslot within the memory region */
1337 mr_offset = section->offset_within_region + start_addr -
1338 section->offset_within_address_space;
1339
1340 /* use aligned delta to align the ram address and offset */
1341 ram = memory_region_get_ram_ptr(mr) + mr_offset;
1342 ram_start_offset = memory_region_get_ram_addr(mr) + mr_offset;
a01672d3 1343
f357f564 1344 if (!add) {
023ae9a8
IM
1345 do {
1346 slot_size = MIN(kvm_max_slot_size, size);
1347 mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
1348 if (!mem) {
f39b7d2b 1349 return;
023ae9a8
IM
1350 }
1351 if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
b4420f19
PX
1352 /*
1353 * NOTE: We should be aware of the fact that here we're only
1354 * doing a best effort to sync dirty bits. No matter whether
1355 * we're using dirty log or dirty ring, we ignored two facts:
1356 *
1357 * (1) dirty bits can reside in hardware buffers (PML)
1358 *
1359 * (2) after we collected dirty bits here, pages can be dirtied
1360 * again before we do the final KVM_SET_USER_MEMORY_REGION to
1361 * remove the slot.
1362 *
1363 * Not easy. Let's cross the fingers until it's fixed.
1364 */
1365 if (kvm_state->kvm_dirty_ring_size) {
1667e2b9 1366 kvm_dirty_ring_reap_locked(kvm_state, NULL);
b20cc776
GS
1367 if (kvm_state->kvm_dirty_ring_with_bitmap) {
1368 kvm_slot_sync_dirty_pages(mem);
1369 kvm_slot_get_dirty_log(kvm_state, mem);
1370 }
b4420f19
PX
1371 } else {
1372 kvm_slot_get_dirty_log(kvm_state, mem);
1373 }
29b7e8be 1374 kvm_slot_sync_dirty_pages(mem);
023ae9a8 1375 }
3fbffb62 1376
023ae9a8
IM
1377 /* unregister the slot */
1378 g_free(mem->dirty_bmap);
1379 mem->dirty_bmap = NULL;
1380 mem->memory_size = 0;
1381 mem->flags = 0;
1382 err = kvm_set_user_memory_region(kml, mem, false);
1383 if (err) {
1384 fprintf(stderr, "%s: error unregistering slot: %s\n",
1385 __func__, strerror(-err));
1386 abort();
1387 }
1388 start_addr += slot_size;
1389 size -= slot_size;
1390 } while (size);
f39b7d2b 1391 return;
46dbef6a
MT
1392 }
1393
f357f564 1394 /* register the new slot */
023ae9a8
IM
1395 do {
1396 slot_size = MIN(kvm_max_slot_size, size);
1397 mem = kvm_alloc_slot(kml);
e65e5f50 1398 mem->as_id = kml->as_id;
023ae9a8
IM
1399 mem->memory_size = slot_size;
1400 mem->start_addr = start_addr;
2c20b27e 1401 mem->ram_start_offset = ram_start_offset;
023ae9a8
IM
1402 mem->ram = ram;
1403 mem->flags = kvm_mem_flags(mr);
ea776d15 1404 kvm_slot_init_dirty_bitmap(mem);
023ae9a8
IM
1405 err = kvm_set_user_memory_region(kml, mem, true);
1406 if (err) {
1407 fprintf(stderr, "%s: error registering slot: %s\n", __func__,
1408 strerror(-err));
1409 abort();
1410 }
1411 start_addr += slot_size;
2c20b27e 1412 ram_start_offset += slot_size;
023ae9a8
IM
1413 ram += slot_size;
1414 size -= slot_size;
1415 } while (size);
46dbef6a
MT
1416}
1417
b4420f19
PX
1418static void *kvm_dirty_ring_reaper_thread(void *data)
1419{
1420 KVMState *s = data;
1421 struct KVMDirtyRingReaper *r = &s->reaper;
1422
1423 rcu_register_thread();
1424
1425 trace_kvm_dirty_ring_reaper("init");
1426
1427 while (true) {
1428 r->reaper_state = KVM_DIRTY_RING_REAPER_WAIT;
1429 trace_kvm_dirty_ring_reaper("wait");
1430 /*
1431 * TODO: provide a smarter timeout rather than a constant?
1432 */
1433 sleep(1);
1434
baa60983
HH
1435 /* keep sleeping so that dirtylimit not be interfered by reaper */
1436 if (dirtylimit_in_service()) {
1437 continue;
1438 }
1439
b4420f19
PX
1440 trace_kvm_dirty_ring_reaper("wakeup");
1441 r->reaper_state = KVM_DIRTY_RING_REAPER_REAPING;
1442
1443 qemu_mutex_lock_iothread();
1667e2b9 1444 kvm_dirty_ring_reap(s, NULL);
b4420f19
PX
1445 qemu_mutex_unlock_iothread();
1446
1447 r->reaper_iteration++;
1448 }
1449
1450 trace_kvm_dirty_ring_reaper("exit");
1451
1452 rcu_unregister_thread();
1453
1454 return NULL;
1455}
1456
1457static int kvm_dirty_ring_reaper_init(KVMState *s)
1458{
1459 struct KVMDirtyRingReaper *r = &s->reaper;
1460
1461 qemu_thread_create(&r->reaper_thr, "kvm-reaper",
1462 kvm_dirty_ring_reaper_thread,
1463 s, QEMU_THREAD_JOINABLE);
1464
1465 return 0;
1466}
1467
3794cb94
GS
1468static int kvm_dirty_ring_init(KVMState *s)
1469{
1470 uint32_t ring_size = s->kvm_dirty_ring_size;
1471 uint64_t ring_bytes = ring_size * sizeof(struct kvm_dirty_gfn);
856e23a0 1472 unsigned int capability = KVM_CAP_DIRTY_LOG_RING;
3794cb94
GS
1473 int ret;
1474
1475 s->kvm_dirty_ring_size = 0;
1476 s->kvm_dirty_ring_bytes = 0;
1477
1478 /* Bail if the dirty ring size isn't specified */
1479 if (!ring_size) {
1480 return 0;
1481 }
1482
1483 /*
1484 * Read the max supported pages. Fall back to dirty logging mode
1485 * if the dirty ring isn't supported.
1486 */
856e23a0
GS
1487 ret = kvm_vm_check_extension(s, capability);
1488 if (ret <= 0) {
1489 capability = KVM_CAP_DIRTY_LOG_RING_ACQ_REL;
1490 ret = kvm_vm_check_extension(s, capability);
1491 }
1492
3794cb94
GS
1493 if (ret <= 0) {
1494 warn_report("KVM dirty ring not available, using bitmap method");
1495 return 0;
1496 }
1497
1498 if (ring_bytes > ret) {
1499 error_report("KVM dirty ring size %" PRIu32 " too big "
1500 "(maximum is %ld). Please use a smaller value.",
1501 ring_size, (long)ret / sizeof(struct kvm_dirty_gfn));
1502 return -EINVAL;
1503 }
1504
856e23a0 1505 ret = kvm_vm_enable_cap(s, capability, 0, ring_bytes);
3794cb94
GS
1506 if (ret) {
1507 error_report("Enabling of KVM dirty ring failed: %s. "
1508 "Suggested minimum value is 1024.", strerror(-ret));
1509 return -EIO;
1510 }
1511
856e23a0
GS
1512 /* Enable the backup bitmap if it is supported */
1513 ret = kvm_vm_check_extension(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP);
1514 if (ret > 0) {
1515 ret = kvm_vm_enable_cap(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP, 0);
1516 if (ret) {
1517 error_report("Enabling of KVM dirty ring's backup bitmap failed: "
1518 "%s. ", strerror(-ret));
1519 return -EIO;
1520 }
1521
1522 s->kvm_dirty_ring_with_bitmap = true;
1523 }
1524
3794cb94
GS
1525 s->kvm_dirty_ring_size = ring_size;
1526 s->kvm_dirty_ring_bytes = ring_bytes;
1527
1528 return 0;
1529}
1530
a01672d3
AK
1531static void kvm_region_add(MemoryListener *listener,
1532 MemoryRegionSection *section)
1533{
7bbda04c 1534 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
f39b7d2b
DH
1535 KVMMemoryUpdate *update;
1536
1537 update = g_new0(KVMMemoryUpdate, 1);
1538 update->section = *section;
7bbda04c 1539
f39b7d2b 1540 QSIMPLEQ_INSERT_TAIL(&kml->transaction_add, update, next);
a01672d3
AK
1541}
1542
1543static void kvm_region_del(MemoryListener *listener,
1544 MemoryRegionSection *section)
1545{
7bbda04c 1546 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
f39b7d2b
DH
1547 KVMMemoryUpdate *update;
1548
1549 update = g_new0(KVMMemoryUpdate, 1);
1550 update->section = *section;
1551
1552 QSIMPLEQ_INSERT_TAIL(&kml->transaction_del, update, next);
1553}
1554
1555static void kvm_region_commit(MemoryListener *listener)
1556{
1557 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener,
1558 listener);
1559 KVMMemoryUpdate *u1, *u2;
1560 bool need_inhibit = false;
1561
1562 if (QSIMPLEQ_EMPTY(&kml->transaction_add) &&
1563 QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1564 return;
1565 }
1566
1567 /*
1568 * We have to be careful when regions to add overlap with ranges to remove.
1569 * We have to simulate atomic KVM memslot updates by making sure no ioctl()
1570 * is currently active.
1571 *
1572 * The lists are order by addresses, so it's easy to find overlaps.
1573 */
1574 u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1575 u2 = QSIMPLEQ_FIRST(&kml->transaction_add);
1576 while (u1 && u2) {
1577 Range r1, r2;
1578
1579 range_init_nofail(&r1, u1->section.offset_within_address_space,
1580 int128_get64(u1->section.size));
1581 range_init_nofail(&r2, u2->section.offset_within_address_space,
1582 int128_get64(u2->section.size));
1583
1584 if (range_overlaps_range(&r1, &r2)) {
1585 need_inhibit = true;
1586 break;
1587 }
1588 if (range_lob(&r1) < range_lob(&r2)) {
1589 u1 = QSIMPLEQ_NEXT(u1, next);
1590 } else {
1591 u2 = QSIMPLEQ_NEXT(u2, next);
1592 }
1593 }
1594
1595 kvm_slots_lock();
1596 if (need_inhibit) {
1597 accel_ioctl_inhibit_begin();
1598 }
1599
1600 /* Remove all memslots before adding the new ones. */
1601 while (!QSIMPLEQ_EMPTY(&kml->transaction_del)) {
1602 u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
1603 QSIMPLEQ_REMOVE_HEAD(&kml->transaction_del, next);
7bbda04c 1604
f39b7d2b
DH
1605 kvm_set_phys_mem(kml, &u1->section, false);
1606 memory_region_unref(u1->section.mr);
1607
1608 g_free(u1);
1609 }
1610 while (!QSIMPLEQ_EMPTY(&kml->transaction_add)) {
1611 u1 = QSIMPLEQ_FIRST(&kml->transaction_add);
1612 QSIMPLEQ_REMOVE_HEAD(&kml->transaction_add, next);
1613
1614 memory_region_ref(u1->section.mr);
1615 kvm_set_phys_mem(kml, &u1->section, true);
1616
1617 g_free(u1);
1618 }
1619
1620 if (need_inhibit) {
1621 accel_ioctl_inhibit_end();
1622 }
1623 kvm_slots_unlock();
a01672d3
AK
1624}
1625
1626static void kvm_log_sync(MemoryListener *listener,
1627 MemoryRegionSection *section)
7b8f3b78 1628{
7bbda04c 1629 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
a01672d3 1630
a2f77862 1631 kvm_slots_lock();
e65e5f50 1632 kvm_physical_sync_dirty_bitmap(kml, section);
a2f77862 1633 kvm_slots_unlock();
7b8f3b78
MT
1634}
1635
1e493be5 1636static void kvm_log_sync_global(MemoryListener *l, bool last_stage)
b4420f19
PX
1637{
1638 KVMMemoryListener *kml = container_of(l, KVMMemoryListener, listener);
1639 KVMState *s = kvm_state;
1640 KVMSlot *mem;
1641 int i;
1642
1643 /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
1644 kvm_dirty_ring_flush();
1645
1646 /*
1647 * TODO: make this faster when nr_slots is big while there are
1648 * only a few used slots (small VMs).
1649 */
1650 kvm_slots_lock();
1651 for (i = 0; i < s->nr_slots; i++) {
1652 mem = &kml->slots[i];
1653 if (mem->memory_size && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
1654 kvm_slot_sync_dirty_pages(mem);
b20cc776
GS
1655
1656 if (s->kvm_dirty_ring_with_bitmap && last_stage &&
1657 kvm_slot_get_dirty_log(s, mem)) {
1658 kvm_slot_sync_dirty_pages(mem);
1659 }
1660
b4420f19
PX
1661 /*
1662 * This is not needed by KVM_GET_DIRTY_LOG because the
1663 * ioctl will unconditionally overwrite the whole region.
1664 * However kvm dirty ring has no such side effect.
1665 */
1666 kvm_slot_reset_dirty_pages(mem);
1667 }
1668 }
1669 kvm_slots_unlock();
1670}
1671
ff4aa114
PX
1672static void kvm_log_clear(MemoryListener *listener,
1673 MemoryRegionSection *section)
1674{
1675 KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
1676 int r;
1677
1678 r = kvm_physical_log_clear(kml, section);
1679 if (r < 0) {
1680 error_report_once("%s: kvm log clear failed: mr=%s "
1681 "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
1682 section->mr->name, section->offset_within_region,
1683 int128_get64(section->size));
1684 abort();
1685 }
1686}
1687
d22b096e
AK
1688static void kvm_mem_ioeventfd_add(MemoryListener *listener,
1689 MemoryRegionSection *section,
1690 bool match_data, uint64_t data,
1691 EventNotifier *e)
1692{
1693 int fd = event_notifier_get_fd(e);
80a1ea37
AK
1694 int r;
1695
4b8f1c88 1696 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
052e87b0
PB
1697 data, true, int128_get64(section->size),
1698 match_data);
80a1ea37 1699 if (r < 0) {
e346bcbf
YK
1700 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1701 __func__, strerror(-r), -r);
80a1ea37
AK
1702 abort();
1703 }
1704}
1705
d22b096e
AK
1706static void kvm_mem_ioeventfd_del(MemoryListener *listener,
1707 MemoryRegionSection *section,
1708 bool match_data, uint64_t data,
1709 EventNotifier *e)
80a1ea37 1710{
d22b096e 1711 int fd = event_notifier_get_fd(e);
80a1ea37
AK
1712 int r;
1713
4b8f1c88 1714 r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
052e87b0
PB
1715 data, false, int128_get64(section->size),
1716 match_data);
80a1ea37 1717 if (r < 0) {
e346bcbf
YK
1718 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1719 __func__, strerror(-r), -r);
80a1ea37
AK
1720 abort();
1721 }
1722}
1723
d22b096e
AK
1724static void kvm_io_ioeventfd_add(MemoryListener *listener,
1725 MemoryRegionSection *section,
1726 bool match_data, uint64_t data,
1727 EventNotifier *e)
80a1ea37 1728{
d22b096e 1729 int fd = event_notifier_get_fd(e);
80a1ea37
AK
1730 int r;
1731
44c3f8f7 1732 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
052e87b0
PB
1733 data, true, int128_get64(section->size),
1734 match_data);
80a1ea37 1735 if (r < 0) {
e346bcbf
YK
1736 fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
1737 __func__, strerror(-r), -r);
80a1ea37
AK
1738 abort();
1739 }
1740}
1741
d22b096e
AK
1742static void kvm_io_ioeventfd_del(MemoryListener *listener,
1743 MemoryRegionSection *section,
1744 bool match_data, uint64_t data,
1745 EventNotifier *e)
80a1ea37
AK
1746
1747{
d22b096e 1748 int fd = event_notifier_get_fd(e);
80a1ea37
AK
1749 int r;
1750
44c3f8f7 1751 r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
052e87b0
PB
1752 data, false, int128_get64(section->size),
1753 match_data);
80a1ea37 1754 if (r < 0) {
e346bcbf
YK
1755 fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
1756 __func__, strerror(-r), -r);
80a1ea37
AK
1757 abort();
1758 }
1759}
1760
38bfe691 1761void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
142518bd 1762 AddressSpace *as, int as_id, const char *name)
7bbda04c
PB
1763{
1764 int i;
1765
b21e2380 1766 kml->slots = g_new0(KVMSlot, s->nr_slots);
38bfe691 1767 kml->as_id = as_id;
7bbda04c
PB
1768
1769 for (i = 0; i < s->nr_slots; i++) {
1770 kml->slots[i].slot = i;
1771 }
1772
f39b7d2b
DH
1773 QSIMPLEQ_INIT(&kml->transaction_add);
1774 QSIMPLEQ_INIT(&kml->transaction_del);
1775
7bbda04c
PB
1776 kml->listener.region_add = kvm_region_add;
1777 kml->listener.region_del = kvm_region_del;
f39b7d2b 1778 kml->listener.commit = kvm_region_commit;
7bbda04c
PB
1779 kml->listener.log_start = kvm_log_start;
1780 kml->listener.log_stop = kvm_log_stop;
5369a36c 1781 kml->listener.priority = MEMORY_LISTENER_PRIORITY_ACCEL;
142518bd 1782 kml->listener.name = name;
7bbda04c 1783
b4420f19
PX
1784 if (s->kvm_dirty_ring_size) {
1785 kml->listener.log_sync_global = kvm_log_sync_global;
1786 } else {
1787 kml->listener.log_sync = kvm_log_sync;
1788 kml->listener.log_clear = kvm_log_clear;
1789 }
1790
7bbda04c 1791 memory_listener_register(&kml->listener, as);
8072aae3
AK
1792
1793 for (i = 0; i < s->nr_as; ++i) {
1794 if (!s->as[i].as) {
1795 s->as[i].as = as;
1796 s->as[i].ml = kml;
1797 break;
1798 }
1799 }
7bbda04c 1800}
d22b096e
AK
1801
1802static MemoryListener kvm_io_listener = {
142518bd 1803 .name = "kvm-io",
d22b096e
AK
1804 .eventfd_add = kvm_io_ioeventfd_add,
1805 .eventfd_del = kvm_io_ioeventfd_del,
8be0461d 1806 .priority = MEMORY_LISTENER_PRIORITY_DEV_BACKEND,
7b8f3b78
MT
1807};
1808
3889c3fa 1809int kvm_set_irq(KVMState *s, int irq, int level)
84b058d7
JK
1810{
1811 struct kvm_irq_level event;
1812 int ret;
1813
7ae26bd4 1814 assert(kvm_async_interrupts_enabled());
84b058d7
JK
1815
1816 event.level = level;
1817 event.irq = irq;
e333cd69 1818 ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
84b058d7 1819 if (ret < 0) {
3889c3fa 1820 perror("kvm_set_irq");
84b058d7
JK
1821 abort();
1822 }
1823
e333cd69 1824 return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
84b058d7
JK
1825}
1826
1827#ifdef KVM_CAP_IRQ_ROUTING
d3d3bef0
JK
1828typedef struct KVMMSIRoute {
1829 struct kvm_irq_routing_entry kroute;
1830 QTAILQ_ENTRY(KVMMSIRoute) entry;
1831} KVMMSIRoute;
1832
84b058d7
JK
1833static void set_gsi(KVMState *s, unsigned int gsi)
1834{
8269fb70 1835 set_bit(gsi, s->used_gsi_bitmap);
84b058d7
JK
1836}
1837
04fa27f5
JK
1838static void clear_gsi(KVMState *s, unsigned int gsi)
1839{
8269fb70 1840 clear_bit(gsi, s->used_gsi_bitmap);
04fa27f5
JK
1841}
1842
7b774593 1843void kvm_init_irq_routing(KVMState *s)
84b058d7 1844{
04fa27f5 1845 int gsi_count, i;
84b058d7 1846
00008418 1847 gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
84b058d7 1848 if (gsi_count > 0) {
84b058d7 1849 /* Round up so we can search ints using ffs */
8269fb70 1850 s->used_gsi_bitmap = bitmap_new(gsi_count);
4e2e4e63 1851 s->gsi_count = gsi_count;
84b058d7
JK
1852 }
1853
1854 s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
1855 s->nr_allocated_irq_routes = 0;
1856
50bf31b9 1857 if (!kvm_direct_msi_allowed) {
4a3adebb
JK
1858 for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
1859 QTAILQ_INIT(&s->msi_hashtab[i]);
1860 }
04fa27f5
JK
1861 }
1862
84b058d7
JK
1863 kvm_arch_init_irq_routing(s);
1864}
1865
cb925cf9 1866void kvm_irqchip_commit_routes(KVMState *s)
e7b20308
JK
1867{
1868 int ret;
1869
7005f7f8
PX
1870 if (kvm_gsi_direct_mapping()) {
1871 return;
1872 }
1873
1874 if (!kvm_gsi_routing_enabled()) {
1875 return;
1876 }
1877
e7b20308 1878 s->irq_routes->flags = 0;
54a6c11b 1879 trace_kvm_irqchip_commit_routes();
e7b20308
JK
1880 ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1881 assert(ret == 0);
1882}
1883
84b058d7
JK
1884static void kvm_add_routing_entry(KVMState *s,
1885 struct kvm_irq_routing_entry *entry)
1886{
1887 struct kvm_irq_routing_entry *new;
1888 int n, size;
1889
1890 if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1891 n = s->nr_allocated_irq_routes * 2;
1892 if (n < 64) {
1893 n = 64;
1894 }
1895 size = sizeof(struct kvm_irq_routing);
1896 size += n * sizeof(*new);
1897 s->irq_routes = g_realloc(s->irq_routes, size);
1898 s->nr_allocated_irq_routes = n;
1899 }
1900 n = s->irq_routes->nr++;
1901 new = &s->irq_routes->entries[n];
0fbc2074
MT
1902
1903 *new = *entry;
84b058d7
JK
1904
1905 set_gsi(s, entry->gsi);
1906}
1907
cc57407e
JK
1908static int kvm_update_routing_entry(KVMState *s,
1909 struct kvm_irq_routing_entry *new_entry)
1910{
1911 struct kvm_irq_routing_entry *entry;
1912 int n;
1913
1914 for (n = 0; n < s->irq_routes->nr; n++) {
1915 entry = &s->irq_routes->entries[n];
1916 if (entry->gsi != new_entry->gsi) {
1917 continue;
1918 }
1919
40509f7f
MT
1920 if(!memcmp(entry, new_entry, sizeof *entry)) {
1921 return 0;
1922 }
1923
0fbc2074 1924 *entry = *new_entry;
cc57407e 1925
cc57407e
JK
1926 return 0;
1927 }
1928
1929 return -ESRCH;
1930}
1931
1df186df 1932void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
84b058d7 1933{
0fbc2074 1934 struct kvm_irq_routing_entry e = {};
84b058d7 1935
4e2e4e63
JK
1936 assert(pin < s->gsi_count);
1937
84b058d7
JK
1938 e.gsi = irq;
1939 e.type = KVM_IRQ_ROUTING_IRQCHIP;
1940 e.flags = 0;
1941 e.u.irqchip.irqchip = irqchip;
1942 e.u.irqchip.pin = pin;
1943 kvm_add_routing_entry(s, &e);
1944}
1945
1e2aa8be 1946void kvm_irqchip_release_virq(KVMState *s, int virq)
04fa27f5
JK
1947{
1948 struct kvm_irq_routing_entry *e;
1949 int i;
1950
76fe21de
AK
1951 if (kvm_gsi_direct_mapping()) {
1952 return;
1953 }
1954
04fa27f5
JK
1955 for (i = 0; i < s->irq_routes->nr; i++) {
1956 e = &s->irq_routes->entries[i];
1957 if (e->gsi == virq) {
1958 s->irq_routes->nr--;
1959 *e = s->irq_routes->entries[s->irq_routes->nr];
1960 }
1961 }
1962 clear_gsi(s, virq);
38d87493 1963 kvm_arch_release_virq_post(virq);
9ba35d0b 1964 trace_kvm_irqchip_release_virq(virq);
04fa27f5
JK
1965}
1966
3607715a
DG
1967void kvm_irqchip_add_change_notifier(Notifier *n)
1968{
1969 notifier_list_add(&kvm_irqchip_change_notifiers, n);
1970}
1971
1972void kvm_irqchip_remove_change_notifier(Notifier *n)
1973{
1974 notifier_remove(n);
1975}
1976
1977void kvm_irqchip_change_notify(void)
1978{
1979 notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
1980}
1981
04fa27f5
JK
1982static unsigned int kvm_hash_msi(uint32_t data)
1983{
1984 /* This is optimized for IA32 MSI layout. However, no other arch shall
1985 * repeat the mistake of not providing a direct MSI injection API. */
1986 return data & 0xff;
1987}
1988
1989static void kvm_flush_dynamic_msi_routes(KVMState *s)
1990{
1991 KVMMSIRoute *route, *next;
1992 unsigned int hash;
1993
1994 for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1995 QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1996 kvm_irqchip_release_virq(s, route->kroute.gsi);
1997 QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1998 g_free(route);
1999 }
2000 }
2001}
2002
2003static int kvm_irqchip_get_virq(KVMState *s)
2004{
8269fb70 2005 int next_virq;
04fa27f5 2006
bdf02631
WM
2007 /*
2008 * PIC and IOAPIC share the first 16 GSI numbers, thus the available
2009 * GSI numbers are more than the number of IRQ route. Allocating a GSI
2010 * number can succeed even though a new route entry cannot be added.
2011 * When this happens, flush dynamic MSI entries to free IRQ route entries.
2012 */
50bf31b9 2013 if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
bdf02631
WM
2014 kvm_flush_dynamic_msi_routes(s);
2015 }
2016
04fa27f5 2017 /* Return the lowest unused GSI in the bitmap */
8269fb70
WY
2018 next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
2019 if (next_virq >= s->gsi_count) {
2020 return -ENOSPC;
2021 } else {
2022 return next_virq;
04fa27f5 2023 }
04fa27f5
JK
2024}
2025
2026static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
2027{
2028 unsigned int hash = kvm_hash_msi(msg.data);
2029 KVMMSIRoute *route;
2030
2031 QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
2032 if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
2033 route->kroute.u.msi.address_hi == (msg.address >> 32) &&
d07cc1f1 2034 route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
04fa27f5
JK
2035 return route;
2036 }
2037 }
2038 return NULL;
2039}
2040
2041int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
2042{
4a3adebb 2043 struct kvm_msi msi;
04fa27f5
JK
2044 KVMMSIRoute *route;
2045
50bf31b9 2046 if (kvm_direct_msi_allowed) {
4a3adebb
JK
2047 msi.address_lo = (uint32_t)msg.address;
2048 msi.address_hi = msg.address >> 32;
d07cc1f1 2049 msi.data = le32_to_cpu(msg.data);
4a3adebb
JK
2050 msi.flags = 0;
2051 memset(msi.pad, 0, sizeof(msi.pad));
2052
2053 return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
2054 }
2055
04fa27f5
JK
2056 route = kvm_lookup_msi_route(s, msg);
2057 if (!route) {
e7b20308 2058 int virq;
04fa27f5
JK
2059
2060 virq = kvm_irqchip_get_virq(s);
2061 if (virq < 0) {
2062 return virq;
2063 }
2064
b21e2380 2065 route = g_new0(KVMMSIRoute, 1);
04fa27f5
JK
2066 route->kroute.gsi = virq;
2067 route->kroute.type = KVM_IRQ_ROUTING_MSI;
2068 route->kroute.flags = 0;
2069 route->kroute.u.msi.address_lo = (uint32_t)msg.address;
2070 route->kroute.u.msi.address_hi = msg.address >> 32;
d07cc1f1 2071 route->kroute.u.msi.data = le32_to_cpu(msg.data);
04fa27f5
JK
2072
2073 kvm_add_routing_entry(s, &route->kroute);
cb925cf9 2074 kvm_irqchip_commit_routes(s);
04fa27f5
JK
2075
2076 QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
2077 entry);
04fa27f5
JK
2078 }
2079
2080 assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
2081
3889c3fa 2082 return kvm_set_irq(s, route->kroute.gsi, 1);
04fa27f5
JK
2083}
2084
def4c557 2085int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
92b4e489 2086{
0fbc2074 2087 struct kvm_irq_routing_entry kroute = {};
92b4e489 2088 int virq;
def4c557 2089 KVMState *s = c->s;
d1f6af6a
PX
2090 MSIMessage msg = {0, 0};
2091
88c725c7 2092 if (pci_available && dev) {
e1d4fb2d 2093 msg = pci_get_msi_message(dev, vector);
d1f6af6a 2094 }
92b4e489 2095
76fe21de 2096 if (kvm_gsi_direct_mapping()) {
1850b6b7 2097 return kvm_arch_msi_data_to_gsi(msg.data);
76fe21de
AK
2098 }
2099
f3e1bed8 2100 if (!kvm_gsi_routing_enabled()) {
92b4e489
JK
2101 return -ENOSYS;
2102 }
2103
2104 virq = kvm_irqchip_get_virq(s);
2105 if (virq < 0) {
2106 return virq;
2107 }
2108
2109 kroute.gsi = virq;
2110 kroute.type = KVM_IRQ_ROUTING_MSI;
2111 kroute.flags = 0;
2112 kroute.u.msi.address_lo = (uint32_t)msg.address;
2113 kroute.u.msi.address_hi = msg.address >> 32;
d07cc1f1 2114 kroute.u.msi.data = le32_to_cpu(msg.data);
88c725c7 2115 if (pci_available && kvm_msi_devid_required()) {
767a554a
PF
2116 kroute.flags = KVM_MSI_VALID_DEVID;
2117 kroute.u.msi.devid = pci_requester_id(dev);
2118 }
dc9f06ca 2119 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
9e03a040
FB
2120 kvm_irqchip_release_virq(s, virq);
2121 return -EINVAL;
2122 }
92b4e489 2123
9ba35d0b
PX
2124 trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
2125 vector, virq);
54a6c11b 2126
92b4e489 2127 kvm_add_routing_entry(s, &kroute);
38d87493 2128 kvm_arch_add_msi_route_post(&kroute, vector, dev);
def4c557 2129 c->changes++;
92b4e489
JK
2130
2131 return virq;
2132}
2133
dc9f06ca
PF
2134int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
2135 PCIDevice *dev)
cc57407e 2136{
0fbc2074 2137 struct kvm_irq_routing_entry kroute = {};
cc57407e 2138
76fe21de
AK
2139 if (kvm_gsi_direct_mapping()) {
2140 return 0;
2141 }
2142
cc57407e
JK
2143 if (!kvm_irqchip_in_kernel()) {
2144 return -ENOSYS;
2145 }
2146
2147 kroute.gsi = virq;
2148 kroute.type = KVM_IRQ_ROUTING_MSI;
2149 kroute.flags = 0;
2150 kroute.u.msi.address_lo = (uint32_t)msg.address;
2151 kroute.u.msi.address_hi = msg.address >> 32;
d07cc1f1 2152 kroute.u.msi.data = le32_to_cpu(msg.data);
88c725c7 2153 if (pci_available && kvm_msi_devid_required()) {
767a554a
PF
2154 kroute.flags = KVM_MSI_VALID_DEVID;
2155 kroute.u.msi.devid = pci_requester_id(dev);
2156 }
dc9f06ca 2157 if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
9e03a040
FB
2158 return -EINVAL;
2159 }
cc57407e 2160
54a6c11b
PX
2161 trace_kvm_irqchip_update_msi_route(virq);
2162
cc57407e
JK
2163 return kvm_update_routing_entry(s, &kroute);
2164}
2165
ff66ba87
PX
2166static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2167 EventNotifier *resample, int virq,
ca916d37 2168 bool assign)
39853bbc 2169{
ff66ba87
PX
2170 int fd = event_notifier_get_fd(event);
2171 int rfd = resample ? event_notifier_get_fd(resample) : -1;
2172
39853bbc
JK
2173 struct kvm_irqfd irqfd = {
2174 .fd = fd,
2175 .gsi = virq,
2176 .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
2177 };
2178
ca916d37 2179 if (rfd != -1) {
c82d9d43
PX
2180 assert(assign);
2181 if (kvm_irqchip_is_split()) {
2182 /*
2183 * When the slow irqchip (e.g. IOAPIC) is in the
2184 * userspace, KVM kernel resamplefd will not work because
2185 * the EOI of the interrupt will be delivered to userspace
2186 * instead, so the KVM kernel resamplefd kick will be
2187 * skipped. The userspace here mimics what the kernel
2188 * provides with resamplefd, remember the resamplefd and
2189 * kick it when we receive EOI of this IRQ.
2190 *
2191 * This is hackery because IOAPIC is mostly bypassed
2192 * (except EOI broadcasts) when irqfd is used. However
2193 * this can bring much performance back for split irqchip
2194 * with INTx IRQs (for VFIO, this gives 93% perf of the
2195 * full fast path, which is 46% perf boost comparing to
2196 * the INTx slow path).
2197 */
2198 kvm_resample_fd_insert(virq, resample);
2199 } else {
2200 irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
2201 irqfd.resamplefd = rfd;
2202 }
2203 } else if (!assign) {
2204 if (kvm_irqchip_is_split()) {
2205 kvm_resample_fd_remove(virq);
2206 }
ca916d37
VM
2207 }
2208
cc7e0ddf 2209 if (!kvm_irqfds_enabled()) {
39853bbc
JK
2210 return -ENOSYS;
2211 }
2212
2213 return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
2214}
2215
d426d9fb
CH
2216int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
2217{
e9af2fef 2218 struct kvm_irq_routing_entry kroute = {};
d426d9fb
CH
2219 int virq;
2220
2221 if (!kvm_gsi_routing_enabled()) {
2222 return -ENOSYS;
2223 }
2224
2225 virq = kvm_irqchip_get_virq(s);
2226 if (virq < 0) {
2227 return virq;
2228 }
2229
2230 kroute.gsi = virq;
2231 kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
2232 kroute.flags = 0;
2233 kroute.u.adapter.summary_addr = adapter->summary_addr;
2234 kroute.u.adapter.ind_addr = adapter->ind_addr;
2235 kroute.u.adapter.summary_offset = adapter->summary_offset;
2236 kroute.u.adapter.ind_offset = adapter->ind_offset;
2237 kroute.u.adapter.adapter_id = adapter->adapter_id;
2238
2239 kvm_add_routing_entry(s, &kroute);
d426d9fb
CH
2240
2241 return virq;
2242}
2243
977a8d9c
AS
2244int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
2245{
2246 struct kvm_irq_routing_entry kroute = {};
2247 int virq;
2248
2249 if (!kvm_gsi_routing_enabled()) {
2250 return -ENOSYS;
2251 }
2252 if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
2253 return -ENOSYS;
2254 }
2255 virq = kvm_irqchip_get_virq(s);
2256 if (virq < 0) {
2257 return virq;
2258 }
2259
2260 kroute.gsi = virq;
2261 kroute.type = KVM_IRQ_ROUTING_HV_SINT;
2262 kroute.flags = 0;
2263 kroute.u.hv_sint.vcpu = vcpu;
2264 kroute.u.hv_sint.sint = sint;
2265
2266 kvm_add_routing_entry(s, &kroute);
2267 kvm_irqchip_commit_routes(s);
2268
2269 return virq;
2270}
2271
84b058d7
JK
2272#else /* !KVM_CAP_IRQ_ROUTING */
2273
7b774593 2274void kvm_init_irq_routing(KVMState *s)
84b058d7
JK
2275{
2276}
04fa27f5 2277
d3d3bef0
JK
2278void kvm_irqchip_release_virq(KVMState *s, int virq)
2279{
2280}
2281
04fa27f5
JK
2282int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
2283{
2284 abort();
2285}
92b4e489 2286
def4c557 2287int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
92b4e489 2288{
df410675 2289 return -ENOSYS;
92b4e489 2290}
39853bbc 2291
d426d9fb
CH
2292int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
2293{
2294 return -ENOSYS;
2295}
2296
977a8d9c
AS
2297int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
2298{
2299 return -ENOSYS;
2300}
2301
ff66ba87
PX
2302static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
2303 EventNotifier *resample, int virq,
2304 bool assign)
39853bbc
JK
2305{
2306 abort();
2307}
dabe3143
MT
2308
2309int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
2310{
2311 return -ENOSYS;
2312}
84b058d7
JK
2313#endif /* !KVM_CAP_IRQ_ROUTING */
2314
1c9b71a7
EA
2315int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2316 EventNotifier *rn, int virq)
39853bbc 2317{
ff66ba87 2318 return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
39853bbc
JK
2319}
2320
1c9b71a7
EA
2321int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
2322 int virq)
15b2bd18 2323{
ff66ba87 2324 return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
15b2bd18
PB
2325}
2326
197e3524
EA
2327int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
2328 EventNotifier *rn, qemu_irq irq)
2329{
2330 gpointer key, gsi;
2331 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2332
2333 if (!found) {
2334 return -ENXIO;
2335 }
2336 return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
2337}
2338
2339int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
2340 qemu_irq irq)
2341{
2342 gpointer key, gsi;
2343 gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
2344
2345 if (!found) {
2346 return -ENXIO;
2347 }
2348 return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
2349}
2350
2351void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
2352{
2353 g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
2354}
2355
4376c40d 2356static void kvm_irqchip_create(KVMState *s)
84b058d7 2357{
84b058d7
JK
2358 int ret;
2359
d1972be1 2360 assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
8db4936b
PB
2361 if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
2362 ;
2363 } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
2364 ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
2365 if (ret < 0) {
2366 fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
2367 exit(1);
2368 }
2369 } else {
2370 return;
84b058d7
JK
2371 }
2372
d6032e06
CD
2373 /* First probe and see if there's a arch-specific hook to create the
2374 * in-kernel irqchip for us */
4376c40d 2375 ret = kvm_arch_irqchip_create(s);
8db4936b 2376 if (ret == 0) {
d1972be1 2377 if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
47c182fe 2378 error_report("Split IRQ chip mode not supported.");
15eafc2e
PB
2379 exit(1);
2380 } else {
2381 ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
2382 }
8db4936b
PB
2383 }
2384 if (ret < 0) {
2385 fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
2386 exit(1);
84b058d7
JK
2387 }
2388
3d4b2649 2389 kvm_kernel_irqchip = true;
7ae26bd4
PM
2390 /* If we have an in-kernel IRQ chip then we must have asynchronous
2391 * interrupt delivery (though the reverse is not necessarily true)
2392 */
2393 kvm_async_interrupts_allowed = true;
215e79c0 2394 kvm_halt_in_kernel_allowed = true;
84b058d7
JK
2395
2396 kvm_init_irq_routing(s);
2397
197e3524 2398 s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
84b058d7
JK
2399}
2400
670436ce
AJ
2401/* Find number of supported CPUs using the recommended
2402 * procedure from the kernel API documentation to cope with
2403 * older kernels that may be missing capabilities.
2404 */
2405static int kvm_recommended_vcpus(KVMState *s)
3ed444e9 2406{
11748ba7 2407 int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
670436ce
AJ
2408 return (ret) ? ret : 4;
2409}
3ed444e9 2410
670436ce
AJ
2411static int kvm_max_vcpus(KVMState *s)
2412{
2413 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
2414 return (ret) ? ret : kvm_recommended_vcpus(s);
3ed444e9
DH
2415}
2416
f31e3266
GK
2417static int kvm_max_vcpu_id(KVMState *s)
2418{
2419 int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
2420 return (ret) ? ret : kvm_max_vcpus(s);
2421}
2422
41264b38
GK
2423bool kvm_vcpu_id_is_valid(int vcpu_id)
2424{
4f7f5893 2425 KVMState *s = KVM_STATE(current_accel());
f31e3266 2426 return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
41264b38
GK
2427}
2428
7786ae40
HH
2429bool kvm_dirty_ring_enabled(void)
2430{
2431 return kvm_state->kvm_dirty_ring_size ? true : false;
2432}
2433
467ef823 2434static void query_stats_cb(StatsResultList **result, StatsTarget target,
cf7405bc 2435 strList *names, strList *targets, Error **errp);
cc01a3f4
MK
2436static void query_stats_schemas_cb(StatsSchemaList **result, Error **errp);
2437
4a06a7cc
HH
2438uint32_t kvm_dirty_ring_size(void)
2439{
2440 return kvm_state->kvm_dirty_ring_size;
2441}
2442
f6a1ef64 2443static int kvm_init(MachineState *ms)
05330448 2444{
f6a1ef64 2445 MachineClass *mc = MACHINE_GET_CLASS(ms);
168ccc11
JK
2446 static const char upgrade_note[] =
2447 "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
2448 "(see http://sourceforge.net/projects/kvm).\n";
2459d420 2449 const struct {
670436ce
AJ
2450 const char *name;
2451 int num;
2452 } num_cpus[] = {
5cc8767d
LX
2453 { "SMP", ms->smp.cpus },
2454 { "hotpluggable", ms->smp.max_cpus },
2459d420 2455 { /* end of list */ }
670436ce
AJ
2456 }, *nc = num_cpus;
2457 int soft_vcpus_limit, hard_vcpus_limit;
05330448 2458 KVMState *s;
94a8d39a 2459 const KVMCapabilityInfo *missing_cap;
05330448 2460 int ret;
7bbda04c 2461 int type = 0;
494cd11d 2462 uint64_t dirty_log_manual_caps;
05330448 2463
a2f77862
PX
2464 qemu_mutex_init(&kml_slots_lock);
2465
fc02086b 2466 s = KVM_STATE(ms->accelerator);
05330448 2467
3145fcb6
DG
2468 /*
2469 * On systems where the kernel can support different base page
2470 * sizes, host page size may be different from TARGET_PAGE_SIZE,
2471 * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
2472 * page size for the system though.
2473 */
8e3b0cbb 2474 assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size());
3145fcb6 2475
aed6efb9 2476 s->sigmask_len = 8;
a27dd2de 2477 accel_blocker_init();
aed6efb9 2478
e22a25c9 2479#ifdef KVM_CAP_SET_GUEST_DEBUG
72cf2d4f 2480 QTAILQ_INIT(&s->kvm_sw_breakpoints);
e22a25c9 2481#endif
4c055ab5 2482 QLIST_INIT(&s->kvm_parked_vcpus);
448058aa 2483 s->fd = qemu_open_old("/dev/kvm", O_RDWR);
05330448
AL
2484 if (s->fd == -1) {
2485 fprintf(stderr, "Could not access KVM kernel module: %m\n");
2486 ret = -errno;
2487 goto err;
2488 }
2489
2490 ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
2491 if (ret < KVM_API_VERSION) {
0e1dac6c 2492 if (ret >= 0) {
05330448 2493 ret = -EINVAL;
a426e122 2494 }
05330448
AL
2495 fprintf(stderr, "kvm version too old\n");
2496 goto err;
2497 }
2498
2499 if (ret > KVM_API_VERSION) {
2500 ret = -EINVAL;
2501 fprintf(stderr, "kvm version not supported\n");
2502 goto err;
2503 }
2504
cf0f7cf9 2505 kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
fb541ca5
AW
2506 s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
2507
2508 /* If unspecified, use the default value */
2509 if (!s->nr_slots) {
2510 s->nr_slots = 32;
2511 }
2512
8072aae3
AK
2513 s->nr_as = kvm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
2514 if (s->nr_as <= 1) {
2515 s->nr_as = 1;
2516 }
2517 s->as = g_new0(struct KVMAs, s->nr_as);
2518
f2ce39b4
PB
2519 if (object_property_find(OBJECT(current_machine), "kvm-type")) {
2520 g_autofree char *kvm_type = object_property_get_str(OBJECT(current_machine),
2521 "kvm-type",
2522 &error_abort);
dc0ca80e 2523 type = mc->kvm_type(ms, kvm_type);
516fc0a0
AJ
2524 } else if (mc->kvm_type) {
2525 type = mc->kvm_type(ms, NULL);
135a129a
AK
2526 }
2527
94ccff13 2528 do {
135a129a 2529 ret = kvm_ioctl(s, KVM_CREATE_VM, type);
94ccff13
TK
2530 } while (ret == -EINTR);
2531
2532 if (ret < 0) {
521f438e 2533 fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
94ccff13
TK
2534 strerror(-ret));
2535
0104dcac 2536#ifdef TARGET_S390X
2c80e996
CH
2537 if (ret == -EINVAL) {
2538 fprintf(stderr,
2539 "Host kernel setup problem detected. Please verify:\n");
2540 fprintf(stderr, "- for kernels supporting the switch_amode or"
2541 " user_mode parameters, whether\n");
2542 fprintf(stderr,
2543 " user space is running in primary address space\n");
2544 fprintf(stderr,
2545 "- for kernels supporting the vm.allocate_pgste sysctl, "
2546 "whether it is enabled\n");
2547 }
380e4929
FR
2548#elif defined(TARGET_PPC)
2549 if (ret == -EINVAL) {
2550 fprintf(stderr,
2551 "PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
2552 (type == 2) ? "pr" : "hv");
2553 }
0104dcac 2554#endif
05330448 2555 goto err;
0104dcac 2556 }
05330448 2557
94ccff13 2558 s->vmfd = ret;
11748ba7
GK
2559
2560 /* check the vcpu limits */
2561 soft_vcpus_limit = kvm_recommended_vcpus(s);
2562 hard_vcpus_limit = kvm_max_vcpus(s);
2563
2564 while (nc->name) {
2565 if (nc->num > soft_vcpus_limit) {
2566 warn_report("Number of %s cpus requested (%d) exceeds "
2567 "the recommended cpus supported by KVM (%d)",
2568 nc->name, nc->num, soft_vcpus_limit);
2569
2570 if (nc->num > hard_vcpus_limit) {
2571 fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
2572 "the maximum cpus supported by KVM (%d)\n",
2573 nc->name, nc->num, hard_vcpus_limit);
2574 exit(1);
2575 }
2576 }
2577 nc++;
2578 }
2579
94a8d39a
JK
2580 missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
2581 if (!missing_cap) {
2582 missing_cap =
2583 kvm_check_extension_list(s, kvm_arch_required_capabilities);
05330448 2584 }
94a8d39a 2585 if (missing_cap) {
ad7b8b33 2586 ret = -EINVAL;
94a8d39a
JK
2587 fprintf(stderr, "kvm does not support %s\n%s",
2588 missing_cap->name, upgrade_note);
d85dc283
AL
2589 goto err;
2590 }
2591
ad7b8b33 2592 s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
e6d34aee
PH
2593 s->coalesced_pio = s->coalesced_mmio &&
2594 kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
f65ed4c1 2595
b4420f19
PX
2596 /*
2597 * Enable KVM dirty ring if supported, otherwise fall back to
2598 * dirty logging mode
2599 */
3794cb94
GS
2600 ret = kvm_dirty_ring_init(s);
2601 if (ret < 0) {
2602 goto err;
b4420f19
PX
2603 }
2604
a81a5926
PX
2605 /*
2606 * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
2607 * enabled. More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
2608 * page is wr-protected initially, which is against how kvm dirty ring is
2609 * usage - kvm dirty ring requires all pages are wr-protected at the very
2610 * beginning. Enabling this feature for dirty ring causes data corruption.
b4420f19
PX
2611 *
2612 * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
2613 * we may expect a higher stall time when starting the migration. In the
2614 * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
2615 * instead of clearing dirty bit, it can be a way to explicitly wr-protect
2616 * guest pages.
a81a5926
PX
2617 */
2618 if (!s->kvm_dirty_ring_size) {
2619 dirty_log_manual_caps =
2620 kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
2621 dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
2622 KVM_DIRTY_LOG_INITIALLY_SET);
2623 s->manual_dirty_log_protect = dirty_log_manual_caps;
2624 if (dirty_log_manual_caps) {
2625 ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
2626 dirty_log_manual_caps);
2627 if (ret) {
2628 warn_report("Trying to enable capability %"PRIu64" of "
2629 "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
2630 "Falling back to the legacy mode. ",
2631 dirty_log_manual_caps);
2632 s->manual_dirty_log_protect = 0;
2633 }
ff4aa114
PX
2634 }
2635 }
2636
a0fb002c
JK
2637#ifdef KVM_CAP_VCPU_EVENTS
2638 s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
2639#endif
2640
b0b1d690
JK
2641 s->robust_singlestep =
2642 kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
b0b1d690 2643
ff44f1a3
JK
2644#ifdef KVM_CAP_DEBUGREGS
2645 s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
2646#endif
2647
ebbfef2f
LA
2648 s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
2649
d3d3bef0 2650#ifdef KVM_CAP_IRQ_ROUTING
50bf31b9 2651 kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
d3d3bef0 2652#endif
4a3adebb 2653
3ab73842
JK
2654 s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
2655
e333cd69 2656 s->irq_set_ioctl = KVM_IRQ_LINE;
8732fbd2 2657 if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
e333cd69 2658 s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
8732fbd2
PM
2659 }
2660
df9c8b75
JJ
2661 kvm_readonly_mem_allowed =
2662 (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
df9c8b75 2663
69e03ae6
NN
2664 kvm_eventfds_allowed =
2665 (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
2666
f41389ae
EA
2667 kvm_irqfds_allowed =
2668 (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
2669
2670 kvm_resamplefds_allowed =
2671 (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
2672
d0a073a1
DD
2673 kvm_vm_attributes_allowed =
2674 (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
2675
35108223
JW
2676 kvm_ioeventfd_any_length_allowed =
2677 (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
2678
12bc5b4c
ML
2679#ifdef KVM_CAP_SET_GUEST_DEBUG
2680 kvm_has_guest_debug =
2681 (kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG) > 0);
2682#endif
2683
2684 kvm_sstep_flags = 0;
2685 if (kvm_has_guest_debug) {
2686 kvm_sstep_flags = SSTEP_ENABLE;
fd2ddd16
ML
2687
2688#if defined KVM_CAP_SET_GUEST_DEBUG2
2689 int guest_debug_flags =
2690 kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG2);
2691
2692 if (guest_debug_flags & KVM_GUESTDBG_BLOCKIRQ) {
2693 kvm_sstep_flags |= SSTEP_NOIRQ;
2694 }
2695#endif
12bc5b4c
ML
2696 }
2697
d870cfde
GA
2698 kvm_state = s;
2699
b16565b3 2700 ret = kvm_arch_init(ms, s);
a426e122 2701 if (ret < 0) {
05330448 2702 goto err;
a426e122 2703 }
05330448 2704
d1972be1
XL
2705 if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
2706 s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2707 }
2708
6b552b9b
DG
2709 qemu_register_reset(kvm_unpoison_all, NULL);
2710
11bc4a13 2711 if (s->kernel_irqchip_allowed) {
4376c40d 2712 kvm_irqchip_create(s);
84b058d7
JK
2713 }
2714
8c56c1a5
PF
2715 if (kvm_eventfds_allowed) {
2716 s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
2717 s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
2718 }
e6d34aee
PH
2719 s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
2720 s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
7bbda04c
PB
2721
2722 kvm_memory_listener_register(s, &s->memory_listener,
142518bd 2723 &address_space_memory, 0, "kvm-memory");
f9b49088
EA
2724 if (kvm_eventfds_allowed) {
2725 memory_listener_register(&kvm_io_listener,
2726 &address_space_io);
2727 }
e6d34aee
PH
2728 memory_listener_register(&kvm_coalesced_pio_listener,
2729 &address_space_io);
05330448 2730
d2f2b8a7
SH
2731 s->many_ioeventfds = kvm_check_many_ioeventfds();
2732
62dd4eda 2733 s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
f5948942 2734 if (!s->sync_mmu) {
956b109f
DH
2735 ret = ram_block_discard_disable(true);
2736 assert(!ret);
f5948942 2737 }
b4420f19
PX
2738
2739 if (s->kvm_dirty_ring_size) {
2740 ret = kvm_dirty_ring_reaper_init(s);
2741 if (ret) {
2742 goto err;
2743 }
2744 }
2745
cc01a3f4 2746 if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
068cc51d
PB
2747 add_stats_callbacks(STATS_PROVIDER_KVM, query_stats_cb,
2748 query_stats_schemas_cb);
cc01a3f4
MK
2749 }
2750
05330448
AL
2751 return 0;
2752
2753err:
0e1dac6c 2754 assert(ret < 0);
6d1cc321
SW
2755 if (s->vmfd >= 0) {
2756 close(s->vmfd);
2757 }
2758 if (s->fd != -1) {
2759 close(s->fd);
05330448 2760 }
7bbda04c 2761 g_free(s->memory_listener.slots);
05330448
AL
2762
2763 return ret;
2764}
2765
aed6efb9
JH
2766void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
2767{
2768 s->sigmask_len = sigmask_len;
2769}
2770
4c663752
PB
2771static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
2772 int size, uint32_t count)
05330448
AL
2773{
2774 int i;
2775 uint8_t *ptr = data;
2776
2777 for (i = 0; i < count; i++) {
4c663752 2778 address_space_rw(&address_space_io, port, attrs,
5c9eb028 2779 ptr, size,
354678c5 2780 direction == KVM_EXIT_IO_OUT);
05330448
AL
2781 ptr += size;
2782 }
05330448
AL
2783}
2784
5326ab55 2785static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
7c80eef8 2786{
977c7b6d
RK
2787 fprintf(stderr, "KVM internal error. Suberror: %d\n",
2788 run->internal.suberror);
2789
7c80eef8
MT
2790 if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
2791 int i;
2792
7c80eef8 2793 for (i = 0; i < run->internal.ndata; ++i) {
56567da3 2794 fprintf(stderr, "extra data[%d]: 0x%016"PRIx64"\n",
7c80eef8
MT
2795 i, (uint64_t)run->internal.data[i]);
2796 }
2797 }
7c80eef8
MT
2798 if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
2799 fprintf(stderr, "emulation failure\n");
20d695a9 2800 if (!kvm_arch_stop_on_emulation_error(cpu)) {
90c84c56 2801 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
d73cd8f4 2802 return EXCP_INTERRUPT;
a426e122 2803 }
7c80eef8
MT
2804 }
2805 /* FIXME: Should trigger a qmp message to let management know
2806 * something went wrong.
2807 */
73aaec4a 2808 return -1;
7c80eef8 2809}
7c80eef8 2810
62a2744c 2811void kvm_flush_coalesced_mmio_buffer(void)
f65ed4c1 2812{
f65ed4c1 2813 KVMState *s = kvm_state;
1cae88b9 2814
fe6bda58 2815 if (!s || s->coalesced_flush_in_progress) {
1cae88b9
AK
2816 return;
2817 }
2818
2819 s->coalesced_flush_in_progress = true;
2820
62a2744c
SY
2821 if (s->coalesced_mmio_ring) {
2822 struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
f65ed4c1
AL
2823 while (ring->first != ring->last) {
2824 struct kvm_coalesced_mmio *ent;
2825
2826 ent = &ring->coalesced_mmio[ring->first];
2827
e6d34aee 2828 if (ent->pio == 1) {
19f70347
PM
2829 address_space_write(&address_space_io, ent->phys_addr,
2830 MEMTXATTRS_UNSPECIFIED, ent->data,
2831 ent->len);
e6d34aee
PH
2832 } else {
2833 cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
2834 }
85199474 2835 smp_wmb();
f65ed4c1
AL
2836 ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
2837 }
2838 }
1cae88b9
AK
2839
2840 s->coalesced_flush_in_progress = false;
f65ed4c1
AL
2841}
2842
92a5199b
TL
2843bool kvm_cpu_check_are_resettable(void)
2844{
2845 return kvm_arch_cpu_check_are_resettable();
2846}
2847
14e6fe12 2848static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
4c0960c0 2849{
99f31832 2850 if (!cpu->vcpu_dirty) {
20d695a9 2851 kvm_arch_get_registers(cpu);
99f31832 2852 cpu->vcpu_dirty = true;
4c0960c0
AK
2853 }
2854}
2855
dd1750d7 2856void kvm_cpu_synchronize_state(CPUState *cpu)
2705d56a 2857{
99f31832 2858 if (!cpu->vcpu_dirty) {
14e6fe12 2859 run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
a426e122 2860 }
2705d56a
JK
2861}
2862
14e6fe12 2863static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
ea375f9a 2864{
20d695a9 2865 kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
99f31832 2866 cpu->vcpu_dirty = false;
ea375f9a
JK
2867}
2868
c8e2085d
DH
2869void kvm_cpu_synchronize_post_reset(CPUState *cpu)
2870{
14e6fe12 2871 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
c8e2085d
DH
2872}
2873
14e6fe12 2874static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
ea375f9a 2875{
20d695a9 2876 kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
99f31832 2877 cpu->vcpu_dirty = false;
ea375f9a
JK
2878}
2879
c8e2085d
DH
2880void kvm_cpu_synchronize_post_init(CPUState *cpu)
2881{
14e6fe12 2882 run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
c8e2085d
DH
2883}
2884
75e972da
DG
2885static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
2886{
99f31832 2887 cpu->vcpu_dirty = true;
75e972da
DG
2888}
2889
2890void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
2891{
2892 run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
2893}
2894
2ae41db2
PB
2895#ifdef KVM_HAVE_MCE_INJECTION
2896static __thread void *pending_sigbus_addr;
2897static __thread int pending_sigbus_code;
2898static __thread bool have_sigbus_pending;
2899#endif
2900
cf0f7cf9
PB
2901static void kvm_cpu_kick(CPUState *cpu)
2902{
d73415a3 2903 qatomic_set(&cpu->kvm_run->immediate_exit, 1);
cf0f7cf9
PB
2904}
2905
2906static void kvm_cpu_kick_self(void)
2907{
2908 if (kvm_immediate_exit) {
2909 kvm_cpu_kick(current_cpu);
2910 } else {
2911 qemu_cpu_kick_self();
2912 }
2913}
2914
18268b60
PB
2915static void kvm_eat_signals(CPUState *cpu)
2916{
2917 struct timespec ts = { 0, 0 };
2918 siginfo_t siginfo;
2919 sigset_t waitset;
2920 sigset_t chkset;
2921 int r;
2922
cf0f7cf9 2923 if (kvm_immediate_exit) {
d73415a3 2924 qatomic_set(&cpu->kvm_run->immediate_exit, 0);
cf0f7cf9
PB
2925 /* Write kvm_run->immediate_exit before the cpu->exit_request
2926 * write in kvm_cpu_exec.
2927 */
2928 smp_wmb();
2929 return;
2930 }
2931
18268b60
PB
2932 sigemptyset(&waitset);
2933 sigaddset(&waitset, SIG_IPI);
2934
2935 do {
2936 r = sigtimedwait(&waitset, &siginfo, &ts);
2937 if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
2938 perror("sigtimedwait");
2939 exit(1);
2940 }
2941
2942 r = sigpending(&chkset);
2943 if (r == -1) {
2944 perror("sigpending");
2945 exit(1);
2946 }
2947 } while (sigismember(&chkset, SIG_IPI));
2948}
2949
1458c363 2950int kvm_cpu_exec(CPUState *cpu)
05330448 2951{
f7575c96 2952 struct kvm_run *run = cpu->kvm_run;
7cbb533f 2953 int ret, run_ret;
05330448 2954
8c0d577e 2955 DPRINTF("kvm_cpu_exec()\n");
05330448 2956
20d695a9 2957 if (kvm_arch_process_async_events(cpu)) {
d73415a3 2958 qatomic_set(&cpu->exit_request, 0);
6792a57b 2959 return EXCP_HLT;
9ccfac9e 2960 }
0af691d7 2961
4b8523ee 2962 qemu_mutex_unlock_iothread();
1d78a3c3 2963 cpu_exec_start(cpu);
4b8523ee 2964
9ccfac9e 2965 do {
4c663752
PB
2966 MemTxAttrs attrs;
2967
99f31832 2968 if (cpu->vcpu_dirty) {
20d695a9 2969 kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
99f31832 2970 cpu->vcpu_dirty = false;
4c0960c0
AK
2971 }
2972
20d695a9 2973 kvm_arch_pre_run(cpu, run);
d73415a3 2974 if (qatomic_read(&cpu->exit_request)) {
9ccfac9e
JK
2975 DPRINTF("interrupt exit requested\n");
2976 /*
2977 * KVM requires us to reenter the kernel after IO exits to complete
2978 * instruction emulation. This self-signal will ensure that we
2979 * leave ASAP again.
2980 */
cf0f7cf9 2981 kvm_cpu_kick_self();
9ccfac9e 2982 }
9ccfac9e 2983
cf0f7cf9
PB
2984 /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
2985 * Matching barrier in kvm_eat_signals.
2986 */
2987 smp_rmb();
2988
1bc22652 2989 run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
9ccfac9e 2990
4c663752 2991 attrs = kvm_arch_post_run(cpu, run);
05330448 2992
2ae41db2
PB
2993#ifdef KVM_HAVE_MCE_INJECTION
2994 if (unlikely(have_sigbus_pending)) {
2995 qemu_mutex_lock_iothread();
2996 kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
2997 pending_sigbus_addr);
2998 have_sigbus_pending = false;
2999 qemu_mutex_unlock_iothread();
3000 }
3001#endif
3002
7cbb533f 3003 if (run_ret < 0) {
dc77d341
JK
3004 if (run_ret == -EINTR || run_ret == -EAGAIN) {
3005 DPRINTF("io window exit\n");
18268b60 3006 kvm_eat_signals(cpu);
d73cd8f4 3007 ret = EXCP_INTERRUPT;
dc77d341
JK
3008 break;
3009 }
7b011fbc
ME
3010 fprintf(stderr, "error: kvm run failed %s\n",
3011 strerror(-run_ret));
dae02ba5
LV
3012#ifdef TARGET_PPC
3013 if (run_ret == -EBUSY) {
3014 fprintf(stderr,
3015 "This is probably because your SMT is enabled.\n"
3016 "VCPU can only run on primary threads with all "
3017 "secondary threads offline.\n");
3018 }
3019#endif
a85e130e
PB
3020 ret = -1;
3021 break;
05330448
AL
3022 }
3023
b76ac80a 3024 trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
05330448
AL
3025 switch (run->exit_reason) {
3026 case KVM_EXIT_IO:
8c0d577e 3027 DPRINTF("handle_io\n");
80b7d2ef 3028 /* Called outside BQL */
4c663752 3029 kvm_handle_io(run->io.port, attrs,
b30e93e9
JK
3030 (uint8_t *)run + run->io.data_offset,
3031 run->io.direction,
3032 run->io.size,
3033 run->io.count);
d73cd8f4 3034 ret = 0;
05330448
AL
3035 break;
3036 case KVM_EXIT_MMIO:
8c0d577e 3037 DPRINTF("handle_mmio\n");
de7ea885 3038 /* Called outside BQL */
4c663752
PB
3039 address_space_rw(&address_space_memory,
3040 run->mmio.phys_addr, attrs,
3041 run->mmio.data,
3042 run->mmio.len,
3043 run->mmio.is_write);
d73cd8f4 3044 ret = 0;
05330448
AL
3045 break;
3046 case KVM_EXIT_IRQ_WINDOW_OPEN:
8c0d577e 3047 DPRINTF("irq_window_open\n");
d73cd8f4 3048 ret = EXCP_INTERRUPT;
05330448
AL
3049 break;
3050 case KVM_EXIT_SHUTDOWN:
8c0d577e 3051 DPRINTF("shutdown\n");
cf83f140 3052 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
d73cd8f4 3053 ret = EXCP_INTERRUPT;
05330448
AL
3054 break;
3055 case KVM_EXIT_UNKNOWN:
bb44e0d1
JK
3056 fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
3057 (uint64_t)run->hw.hardware_exit_reason);
73aaec4a 3058 ret = -1;
05330448 3059 break;
7c80eef8 3060 case KVM_EXIT_INTERNAL_ERROR:
5326ab55 3061 ret = kvm_handle_internal_error(cpu, run);
7c80eef8 3062 break;
b4420f19
PX
3063 case KVM_EXIT_DIRTY_RING_FULL:
3064 /*
3065 * We shouldn't continue if the dirty ring of this vcpu is
3066 * still full. Got kicked by KVM_RESET_DIRTY_RINGS.
3067 */
3068 trace_kvm_dirty_ring_full(cpu->cpu_index);
3069 qemu_mutex_lock_iothread();
baa60983
HH
3070 /*
3071 * We throttle vCPU by making it sleep once it exit from kernel
3072 * due to dirty ring full. In the dirtylimit scenario, reaping
3073 * all vCPUs after a single vCPU dirty ring get full result in
3074 * the miss of sleep, so just reap the ring-fulled vCPU.
3075 */
3076 if (dirtylimit_in_service()) {
3077 kvm_dirty_ring_reap(kvm_state, cpu);
3078 } else {
3079 kvm_dirty_ring_reap(kvm_state, NULL);
3080 }
b4420f19 3081 qemu_mutex_unlock_iothread();
baa60983 3082 dirtylimit_vcpu_execute(cpu);
b4420f19
PX
3083 ret = 0;
3084 break;
99040447
PS
3085 case KVM_EXIT_SYSTEM_EVENT:
3086 switch (run->system_event.type) {
3087 case KVM_SYSTEM_EVENT_SHUTDOWN:
cf83f140 3088 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
99040447
PS
3089 ret = EXCP_INTERRUPT;
3090 break;
3091 case KVM_SYSTEM_EVENT_RESET:
cf83f140 3092 qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
99040447
PS
3093 ret = EXCP_INTERRUPT;
3094 break;
7c207b90 3095 case KVM_SYSTEM_EVENT_CRASH:
d187e08d 3096 kvm_cpu_synchronize_state(cpu);
7c207b90 3097 qemu_mutex_lock_iothread();
c86f106b 3098 qemu_system_guest_panicked(cpu_get_crash_info(cpu));
7c207b90
AS
3099 qemu_mutex_unlock_iothread();
3100 ret = 0;
3101 break;
99040447
PS
3102 default:
3103 DPRINTF("kvm_arch_handle_exit\n");
3104 ret = kvm_arch_handle_exit(cpu, run);
3105 break;
3106 }
3107 break;
05330448 3108 default:
8c0d577e 3109 DPRINTF("kvm_arch_handle_exit\n");
20d695a9 3110 ret = kvm_arch_handle_exit(cpu, run);
05330448
AL
3111 break;
3112 }
d73cd8f4 3113 } while (ret == 0);
05330448 3114
1d78a3c3 3115 cpu_exec_end(cpu);
4b8523ee
JK
3116 qemu_mutex_lock_iothread();
3117
73aaec4a 3118 if (ret < 0) {
90c84c56 3119 cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
0461d5a6 3120 vm_stop(RUN_STATE_INTERNAL_ERROR);
becfc390
AL
3121 }
3122
d73415a3 3123 qatomic_set(&cpu->exit_request, 0);
05330448
AL
3124 return ret;
3125}
3126
984b5181 3127int kvm_ioctl(KVMState *s, int type, ...)
05330448
AL
3128{
3129 int ret;
984b5181
AL
3130 void *arg;
3131 va_list ap;
05330448 3132
984b5181
AL
3133 va_start(ap, type);
3134 arg = va_arg(ap, void *);
3135 va_end(ap);
3136
9c775729 3137 trace_kvm_ioctl(type, arg);
984b5181 3138 ret = ioctl(s->fd, type, arg);
a426e122 3139 if (ret == -1) {
05330448 3140 ret = -errno;
a426e122 3141 }
05330448
AL
3142 return ret;
3143}
3144
984b5181 3145int kvm_vm_ioctl(KVMState *s, int type, ...)
05330448
AL
3146{
3147 int ret;
984b5181
AL
3148 void *arg;
3149 va_list ap;
3150
3151 va_start(ap, type);
3152 arg = va_arg(ap, void *);
3153 va_end(ap);
05330448 3154
9c775729 3155 trace_kvm_vm_ioctl(type, arg);
a27dd2de 3156 accel_ioctl_begin();
984b5181 3157 ret = ioctl(s->vmfd, type, arg);
a27dd2de 3158 accel_ioctl_end();
a426e122 3159 if (ret == -1) {
05330448 3160 ret = -errno;
a426e122 3161 }
05330448
AL
3162 return ret;
3163}
3164
1bc22652 3165int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
05330448
AL
3166{
3167 int ret;
984b5181
AL
3168 void *arg;
3169 va_list ap;
3170
3171 va_start(ap, type);
3172 arg = va_arg(ap, void *);
3173 va_end(ap);
05330448 3174
9c775729 3175 trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
a27dd2de 3176 accel_cpu_ioctl_begin(cpu);
8737c51c 3177 ret = ioctl(cpu->kvm_fd, type, arg);
a27dd2de 3178 accel_cpu_ioctl_end(cpu);
a426e122 3179 if (ret == -1) {
05330448 3180 ret = -errno;
a426e122 3181 }
05330448
AL
3182 return ret;
3183}
bd322087 3184
0a6a7cca
CD
3185int kvm_device_ioctl(int fd, int type, ...)
3186{
3187 int ret;
3188 void *arg;
3189 va_list ap;
3190
3191 va_start(ap, type);
3192 arg = va_arg(ap, void *);
3193 va_end(ap);
3194
3195 trace_kvm_device_ioctl(fd, type, arg);
a27dd2de 3196 accel_ioctl_begin();
0a6a7cca 3197 ret = ioctl(fd, type, arg);
a27dd2de 3198 accel_ioctl_end();
0a6a7cca
CD
3199 if (ret == -1) {
3200 ret = -errno;
3201 }
3202 return ret;
3203}
3204
d0a073a1
DD
3205int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
3206{
3207 int ret;
3208 struct kvm_device_attr attribute = {
3209 .group = group,
3210 .attr = attr,
3211 };
3212
3213 if (!kvm_vm_attributes_allowed) {
3214 return 0;
3215 }
3216
3217 ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
3218 /* kvm returns 0 on success for HAS_DEVICE_ATTR */
3219 return ret ? 0 : 1;
3220}
3221
4b3cfe72
PF
3222int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
3223{
3224 struct kvm_device_attr attribute = {
3225 .group = group,
3226 .attr = attr,
3227 .flags = 0,
3228 };
3229
3230 return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
3231}
3232
556969e9
EA
3233int kvm_device_access(int fd, int group, uint64_t attr,
3234 void *val, bool write, Error **errp)
4b3cfe72
PF
3235{
3236 struct kvm_device_attr kvmattr;
3237 int err;
3238
3239 kvmattr.flags = 0;
3240 kvmattr.group = group;
3241 kvmattr.attr = attr;
3242 kvmattr.addr = (uintptr_t)val;
3243
3244 err = kvm_device_ioctl(fd,
3245 write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
3246 &kvmattr);
3247 if (err < 0) {
556969e9
EA
3248 error_setg_errno(errp, -err,
3249 "KVM_%s_DEVICE_ATTR failed: Group %d "
3250 "attr 0x%016" PRIx64,
3251 write ? "SET" : "GET", group, attr);
4b3cfe72 3252 }
556969e9 3253 return err;
4b3cfe72
PF
3254}
3255
62dd4eda 3256bool kvm_has_sync_mmu(void)
bd322087 3257{
62dd4eda 3258 return kvm_state->sync_mmu;
bd322087 3259}
e22a25c9 3260
a0fb002c
JK
3261int kvm_has_vcpu_events(void)
3262{
3263 return kvm_state->vcpu_events;
3264}
3265
b0b1d690
JK
3266int kvm_has_robust_singlestep(void)
3267{
3268 return kvm_state->robust_singlestep;
3269}
3270
ff44f1a3
JK
3271int kvm_has_debugregs(void)
3272{
3273 return kvm_state->debugregs;
3274}
3275
ebbfef2f
LA
3276int kvm_max_nested_state_length(void)
3277{
3278 return kvm_state->max_nested_state_len;
3279}
3280
d2f2b8a7
SH
3281int kvm_has_many_ioeventfds(void)
3282{
3283 if (!kvm_enabled()) {
3284 return 0;
3285 }
3286 return kvm_state->many_ioeventfds;
3287}
3288
84b058d7
JK
3289int kvm_has_gsi_routing(void)
3290{
a9c5eb0d 3291#ifdef KVM_CAP_IRQ_ROUTING
84b058d7 3292 return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
a9c5eb0d
AG
3293#else
3294 return false;
3295#endif
84b058d7
JK
3296}
3297
3ab73842
JK
3298int kvm_has_intx_set_mask(void)
3299{
3300 return kvm_state->intx_set_mask;
3301}
3302
5d721b78
AG
3303bool kvm_arm_supports_user_irq(void)
3304{
3305 return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
3306}
3307
e22a25c9 3308#ifdef KVM_CAP_SET_GUEST_DEBUG
a60f24b5 3309struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
e22a25c9
AL
3310 target_ulong pc)
3311{
3312 struct kvm_sw_breakpoint *bp;
3313
a60f24b5 3314 QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
a426e122 3315 if (bp->pc == pc) {
e22a25c9 3316 return bp;
a426e122 3317 }
e22a25c9
AL
3318 }
3319 return NULL;
3320}
3321
a60f24b5 3322int kvm_sw_breakpoints_active(CPUState *cpu)
e22a25c9 3323{
a60f24b5 3324 return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
e22a25c9
AL
3325}
3326
452e4751
GC
3327struct kvm_set_guest_debug_data {
3328 struct kvm_guest_debug dbg;
452e4751
GC
3329 int err;
3330};
3331
14e6fe12 3332static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
452e4751 3333{
14e6fe12
PB
3334 struct kvm_set_guest_debug_data *dbg_data =
3335 (struct kvm_set_guest_debug_data *) data.host_ptr;
b3807725 3336
3c0ed2a3 3337 dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
a60f24b5 3338 &dbg_data->dbg);
452e4751
GC
3339}
3340
38e478ec 3341int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
e22a25c9 3342{
452e4751 3343 struct kvm_set_guest_debug_data data;
e22a25c9 3344
b0b1d690 3345 data.dbg.control = reinject_trap;
e22a25c9 3346
ed2803da 3347 if (cpu->singlestep_enabled) {
b0b1d690 3348 data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
fd2ddd16
ML
3349
3350 if (cpu->singlestep_enabled & SSTEP_NOIRQ) {
3351 data.dbg.control |= KVM_GUESTDBG_BLOCKIRQ;
3352 }
b0b1d690 3353 }
20d695a9 3354 kvm_arch_update_guest_debug(cpu, &data.dbg);
e22a25c9 3355
14e6fe12
PB
3356 run_on_cpu(cpu, kvm_invoke_set_guest_debug,
3357 RUN_ON_CPU_HOST_PTR(&data));
452e4751 3358 return data.err;
e22a25c9
AL
3359}
3360
a48e7d9e
AB
3361bool kvm_supports_guest_debug(void)
3362{
3363 /* probed during kvm_init() */
3364 return kvm_has_guest_debug;
3365}
3366
55b5b8e9 3367int kvm_insert_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
e22a25c9
AL
3368{
3369 struct kvm_sw_breakpoint *bp;
e22a25c9
AL
3370 int err;
3371
3372 if (type == GDB_BREAKPOINT_SW) {
80b7cd73 3373 bp = kvm_find_sw_breakpoint(cpu, addr);
e22a25c9
AL
3374 if (bp) {
3375 bp->use_count++;
3376 return 0;
3377 }
3378
b21e2380 3379 bp = g_new(struct kvm_sw_breakpoint, 1);
e22a25c9
AL
3380 bp->pc = addr;
3381 bp->use_count = 1;
80b7cd73 3382 err = kvm_arch_insert_sw_breakpoint(cpu, bp);
e22a25c9 3383 if (err) {
7267c094 3384 g_free(bp);
e22a25c9
AL
3385 return err;
3386 }
3387
80b7cd73 3388 QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
e22a25c9
AL
3389 } else {
3390 err = kvm_arch_insert_hw_breakpoint(addr, len, type);
a426e122 3391 if (err) {
e22a25c9 3392 return err;
a426e122 3393 }
e22a25c9
AL
3394 }
3395
bdc44640 3396 CPU_FOREACH(cpu) {
38e478ec 3397 err = kvm_update_guest_debug(cpu, 0);
a426e122 3398 if (err) {
e22a25c9 3399 return err;
a426e122 3400 }
e22a25c9
AL
3401 }
3402 return 0;
3403}
3404
55b5b8e9 3405int kvm_remove_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
e22a25c9
AL
3406{
3407 struct kvm_sw_breakpoint *bp;
e22a25c9
AL
3408 int err;
3409
3410 if (type == GDB_BREAKPOINT_SW) {
80b7cd73 3411 bp = kvm_find_sw_breakpoint(cpu, addr);
a426e122 3412 if (!bp) {
e22a25c9 3413 return -ENOENT;
a426e122 3414 }
e22a25c9
AL
3415
3416 if (bp->use_count > 1) {
3417 bp->use_count--;
3418 return 0;
3419 }
3420
80b7cd73 3421 err = kvm_arch_remove_sw_breakpoint(cpu, bp);
a426e122 3422 if (err) {
e22a25c9 3423 return err;
a426e122 3424 }
e22a25c9 3425
80b7cd73 3426 QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
7267c094 3427 g_free(bp);
e22a25c9
AL
3428 } else {
3429 err = kvm_arch_remove_hw_breakpoint(addr, len, type);
a426e122 3430 if (err) {
e22a25c9 3431 return err;
a426e122 3432 }
e22a25c9
AL
3433 }
3434
bdc44640 3435 CPU_FOREACH(cpu) {
38e478ec 3436 err = kvm_update_guest_debug(cpu, 0);
a426e122 3437 if (err) {
e22a25c9 3438 return err;
a426e122 3439 }
e22a25c9
AL
3440 }
3441 return 0;
3442}
3443
1d5791f4 3444void kvm_remove_all_breakpoints(CPUState *cpu)
e22a25c9
AL
3445{
3446 struct kvm_sw_breakpoint *bp, *next;
80b7cd73 3447 KVMState *s = cpu->kvm_state;
dc54e252 3448 CPUState *tmpcpu;
e22a25c9 3449
72cf2d4f 3450 QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
80b7cd73 3451 if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
e22a25c9 3452 /* Try harder to find a CPU that currently sees the breakpoint. */
dc54e252
CG
3453 CPU_FOREACH(tmpcpu) {
3454 if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
e22a25c9 3455 break;
a426e122 3456 }
e22a25c9
AL
3457 }
3458 }
78021d6d
JK
3459 QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
3460 g_free(bp);
e22a25c9
AL
3461 }
3462 kvm_arch_remove_all_hw_breakpoints();
3463
bdc44640 3464 CPU_FOREACH(cpu) {
38e478ec 3465 kvm_update_guest_debug(cpu, 0);
a426e122 3466 }
e22a25c9
AL
3467}
3468
e22a25c9 3469#endif /* !KVM_CAP_SET_GUEST_DEBUG */
cc84de95 3470
18268b60 3471static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
cc84de95 3472{
aed6efb9 3473 KVMState *s = kvm_state;
cc84de95
MT
3474 struct kvm_signal_mask *sigmask;
3475 int r;
3476
7267c094 3477 sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
cc84de95 3478
aed6efb9 3479 sigmask->len = s->sigmask_len;
cc84de95 3480 memcpy(sigmask->sigset, sigset, sizeof(*sigset));
1bc22652 3481 r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
7267c094 3482 g_free(sigmask);
cc84de95
MT
3483
3484 return r;
3485}
4d39892c 3486
cf0f7cf9 3487static void kvm_ipi_signal(int sig)
18268b60 3488{
cf0f7cf9
PB
3489 if (current_cpu) {
3490 assert(kvm_immediate_exit);
3491 kvm_cpu_kick(current_cpu);
3492 }
18268b60
PB
3493}
3494
3495void kvm_init_cpu_signals(CPUState *cpu)
3496{
3497 int r;
3498 sigset_t set;
3499 struct sigaction sigact;
3500
3501 memset(&sigact, 0, sizeof(sigact));
cf0f7cf9 3502 sigact.sa_handler = kvm_ipi_signal;
18268b60
PB
3503 sigaction(SIG_IPI, &sigact, NULL);
3504
3505 pthread_sigmask(SIG_BLOCK, NULL, &set);
3506#if defined KVM_HAVE_MCE_INJECTION
3507 sigdelset(&set, SIGBUS);
3508 pthread_sigmask(SIG_SETMASK, &set, NULL);
3509#endif
3510 sigdelset(&set, SIG_IPI);
cf0f7cf9
PB
3511 if (kvm_immediate_exit) {
3512 r = pthread_sigmask(SIG_SETMASK, &set, NULL);
3513 } else {
3514 r = kvm_set_signal_mask(cpu, &set);
3515 }
18268b60
PB
3516 if (r) {
3517 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
3518 exit(1);
3519 }
3520}
3521
2ae41db2 3522/* Called asynchronously in VCPU thread. */
290adf38 3523int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
a1b87fe0 3524{
2ae41db2
PB
3525#ifdef KVM_HAVE_MCE_INJECTION
3526 if (have_sigbus_pending) {
3527 return 1;
3528 }
3529 have_sigbus_pending = true;
3530 pending_sigbus_addr = addr;
3531 pending_sigbus_code = code;
d73415a3 3532 qatomic_set(&cpu->exit_request, 1);
2ae41db2
PB
3533 return 0;
3534#else
3535 return 1;
3536#endif
a1b87fe0
JK
3537}
3538
2ae41db2 3539/* Called synchronously (via signalfd) in main thread. */
a1b87fe0
JK
3540int kvm_on_sigbus(int code, void *addr)
3541{
2ae41db2 3542#ifdef KVM_HAVE_MCE_INJECTION
4d39892c
PB
3543 /* Action required MCE kills the process if SIGBUS is blocked. Because
3544 * that's what happens in the I/O thread, where we handle MCE via signalfd,
3545 * we can only get action optional here.
3546 */
3547 assert(code != BUS_MCEERR_AR);
3548 kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
3549 return 0;
2ae41db2
PB
3550#else
3551 return 1;
3552#endif
a1b87fe0 3553}
0a6a7cca
CD
3554
3555int kvm_create_device(KVMState *s, uint64_t type, bool test)
3556{
3557 int ret;
3558 struct kvm_create_device create_dev;
3559
3560 create_dev.type = type;
3561 create_dev.fd = -1;
3562 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
3563
3564 if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
3565 return -ENOTSUP;
3566 }
3567
3568 ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
3569 if (ret) {
3570 return ret;
3571 }
3572
3573 return test ? 0 : create_dev.fd;
3574}
ada4135f 3575
29039acf
PX
3576bool kvm_device_supported(int vmfd, uint64_t type)
3577{
3578 struct kvm_create_device create_dev = {
3579 .type = type,
3580 .fd = -1,
3581 .flags = KVM_CREATE_DEVICE_TEST,
3582 };
3583
3584 if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
3585 return false;
3586 }
3587
3588 return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
3589}
3590
ada4135f
CH
3591int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
3592{
3593 struct kvm_one_reg reg;
3594 int r;
3595
3596 reg.id = id;
3597 reg.addr = (uintptr_t) source;
3598 r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
3599 if (r) {
844a3d34 3600 trace_kvm_failed_reg_set(id, strerror(-r));
ada4135f
CH
3601 }
3602 return r;
3603}
3604
3605int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
3606{
3607 struct kvm_one_reg reg;
3608 int r;
3609
3610 reg.id = id;
3611 reg.addr = (uintptr_t) target;
3612 r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
3613 if (r) {
844a3d34 3614 trace_kvm_failed_reg_get(id, strerror(-r));
ada4135f
CH
3615 }
3616 return r;
3617}
782c3f29 3618
8072aae3
AK
3619static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
3620 hwaddr start_addr, hwaddr size)
3621{
3622 KVMState *kvm = KVM_STATE(ms->accelerator);
3623 int i;
3624
3625 for (i = 0; i < kvm->nr_as; ++i) {
3626 if (kvm->as[i].as == as && kvm->as[i].ml) {
023ae9a8 3627 size = MIN(kvm_max_slot_size, size);
8072aae3
AK
3628 return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
3629 start_addr, size);
3630 }
3631 }
3632
3633 return false;
3634}
3635
23b0898e
PB
3636static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
3637 const char *name, void *opaque,
3638 Error **errp)
3639{
3640 KVMState *s = KVM_STATE(obj);
3641 int64_t value = s->kvm_shadow_mem;
3642
3643 visit_type_int(v, name, &value, errp);
3644}
3645
3646static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
3647 const char *name, void *opaque,
3648 Error **errp)
3649{
3650 KVMState *s = KVM_STATE(obj);
23b0898e
PB
3651 int64_t value;
3652
70cbae42
PB
3653 if (s->fd != -1) {
3654 error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3655 return;
3656 }
3657
668f62ec 3658 if (!visit_type_int(v, name, &value, errp)) {
23b0898e
PB
3659 return;
3660 }
3661
3662 s->kvm_shadow_mem = value;
3663}
3664
11bc4a13
PB
3665static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
3666 const char *name, void *opaque,
3667 Error **errp)
3668{
11bc4a13
PB
3669 KVMState *s = KVM_STATE(obj);
3670 OnOffSplit mode;
3671
70cbae42
PB
3672 if (s->fd != -1) {
3673 error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3674 return;
3675 }
3676
14217038 3677 if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
11bc4a13 3678 return;
14217038
MA
3679 }
3680 switch (mode) {
3681 case ON_OFF_SPLIT_ON:
3682 s->kernel_irqchip_allowed = true;
3683 s->kernel_irqchip_required = true;
3684 s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3685 break;
3686 case ON_OFF_SPLIT_OFF:
3687 s->kernel_irqchip_allowed = false;
3688 s->kernel_irqchip_required = false;
3689 s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
3690 break;
3691 case ON_OFF_SPLIT_SPLIT:
3692 s->kernel_irqchip_allowed = true;
3693 s->kernel_irqchip_required = true;
3694 s->kernel_irqchip_split = ON_OFF_AUTO_ON;
3695 break;
3696 default:
3697 /* The value was checked in visit_type_OnOffSplit() above. If
3698 * we get here, then something is wrong in QEMU.
3699 */
3700 abort();
11bc4a13
PB
3701 }
3702}
3703
4376c40d
PB
3704bool kvm_kernel_irqchip_allowed(void)
3705{
11bc4a13 3706 return kvm_state->kernel_irqchip_allowed;
4376c40d
PB
3707}
3708
3709bool kvm_kernel_irqchip_required(void)
3710{
11bc4a13 3711 return kvm_state->kernel_irqchip_required;
4376c40d
PB
3712}
3713
3714bool kvm_kernel_irqchip_split(void)
3715{
d1972be1 3716 return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
4376c40d
PB
3717}
3718
2ea5cb0a
PX
3719static void kvm_get_dirty_ring_size(Object *obj, Visitor *v,
3720 const char *name, void *opaque,
3721 Error **errp)
3722{
3723 KVMState *s = KVM_STATE(obj);
3724 uint32_t value = s->kvm_dirty_ring_size;
3725
3726 visit_type_uint32(v, name, &value, errp);
3727}
3728
3729static void kvm_set_dirty_ring_size(Object *obj, Visitor *v,
3730 const char *name, void *opaque,
3731 Error **errp)
3732{
3733 KVMState *s = KVM_STATE(obj);
2ea5cb0a
PX
3734 uint32_t value;
3735
3736 if (s->fd != -1) {
3737 error_setg(errp, "Cannot set properties after the accelerator has been initialized");
3738 return;
3739 }
3740
d1c81c34 3741 if (!visit_type_uint32(v, name, &value, errp)) {
2ea5cb0a
PX
3742 return;
3743 }
3744 if (value & (value - 1)) {
3745 error_setg(errp, "dirty-ring-size must be a power of two.");
3746 return;
3747 }
3748
3749 s->kvm_dirty_ring_size = value;
3750}
3751
23b0898e
PB
3752static void kvm_accel_instance_init(Object *obj)
3753{
3754 KVMState *s = KVM_STATE(obj);
3755
70cbae42
PB
3756 s->fd = -1;
3757 s->vmfd = -1;
23b0898e 3758 s->kvm_shadow_mem = -1;
d1972be1
XL
3759 s->kernel_irqchip_allowed = true;
3760 s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
2ea5cb0a
PX
3761 /* KVM dirty ring is by default off */
3762 s->kvm_dirty_ring_size = 0;
b20cc776 3763 s->kvm_dirty_ring_with_bitmap = false;
e2e69f6b
CQ
3764 s->notify_vmexit = NOTIFY_VMEXIT_OPTION_RUN;
3765 s->notify_window = 0;
61491cf4 3766 s->xen_version = 0;
6f43f2ee 3767 s->xen_gnttab_max_frames = 64;
e16aff4c 3768 s->xen_evtchn_max_pirq = 256;
23b0898e
PB
3769}
3770
3b7a9388
AB
3771/**
3772 * kvm_gdbstub_sstep_flags():
3773 *
3774 * Returns: SSTEP_* flags that KVM supports for guest debug. The
3775 * support is probed during kvm_init()
3776 */
3777static int kvm_gdbstub_sstep_flags(void)
3778{
3779 return kvm_sstep_flags;
3780}
3781
782c3f29
EH
3782static void kvm_accel_class_init(ObjectClass *oc, void *data)
3783{
3784 AccelClass *ac = ACCEL_CLASS(oc);
3785 ac->name = "KVM";
0d15da8e 3786 ac->init_machine = kvm_init;
8072aae3 3787 ac->has_memory = kvm_accel_has_memory;
782c3f29 3788 ac->allowed = &kvm_allowed;
3b7a9388 3789 ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
23b0898e 3790
11bc4a13
PB
3791 object_class_property_add(oc, "kernel-irqchip", "on|off|split",
3792 NULL, kvm_set_kernel_irqchip,
d2623129 3793 NULL, NULL);
11bc4a13 3794 object_class_property_set_description(oc, "kernel-irqchip",
7eecec7d 3795 "Configure KVM in-kernel irqchip");
11bc4a13 3796
23b0898e
PB
3797 object_class_property_add(oc, "kvm-shadow-mem", "int",
3798 kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
d2623129 3799 NULL, NULL);
23b0898e 3800 object_class_property_set_description(oc, "kvm-shadow-mem",
7eecec7d 3801 "KVM shadow MMU size");
2ea5cb0a
PX
3802
3803 object_class_property_add(oc, "dirty-ring-size", "uint32",
3804 kvm_get_dirty_ring_size, kvm_set_dirty_ring_size,
3805 NULL, NULL);
3806 object_class_property_set_description(oc, "dirty-ring-size",
3807 "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
3dba0a33
PB
3808
3809 kvm_arch_accel_class_init(oc);
782c3f29
EH
3810}
3811
3812static const TypeInfo kvm_accel_type = {
3813 .name = TYPE_KVM_ACCEL,
3814 .parent = TYPE_ACCEL,
23b0898e 3815 .instance_init = kvm_accel_instance_init,
782c3f29 3816 .class_init = kvm_accel_class_init,
fc02086b 3817 .instance_size = sizeof(KVMState),
782c3f29
EH
3818};
3819
3820static void kvm_type_init(void)
3821{
3822 type_register_static(&kvm_accel_type);
3823}
3824
3825type_init(kvm_type_init);
cc01a3f4
MK
3826
3827typedef struct StatsArgs {
3828 union StatsResultsType {
3829 StatsResultList **stats;
3830 StatsSchemaList **schema;
3831 } result;
cf7405bc 3832 strList *names;
cc01a3f4
MK
3833 Error **errp;
3834} StatsArgs;
3835
3836static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
3837 uint64_t *stats_data,
3838 StatsList *stats_list,
3839 Error **errp)
3840{
3841
3842 Stats *stats;
3843 uint64List *val_list = NULL;
3844
3845 /* Only add stats that we understand. */
3846 switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
3847 case KVM_STATS_TYPE_CUMULATIVE:
3848 case KVM_STATS_TYPE_INSTANT:
3849 case KVM_STATS_TYPE_PEAK:
3850 case KVM_STATS_TYPE_LINEAR_HIST:
3851 case KVM_STATS_TYPE_LOG_HIST:
3852 break;
3853 default:
3854 return stats_list;
3855 }
3856
3857 switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
3858 case KVM_STATS_UNIT_NONE:
3859 case KVM_STATS_UNIT_BYTES:
3860 case KVM_STATS_UNIT_CYCLES:
3861 case KVM_STATS_UNIT_SECONDS:
105bb7cd 3862 case KVM_STATS_UNIT_BOOLEAN:
cc01a3f4
MK
3863 break;
3864 default:
3865 return stats_list;
3866 }
3867
3868 switch (pdesc->flags & KVM_STATS_BASE_MASK) {
3869 case KVM_STATS_BASE_POW10:
3870 case KVM_STATS_BASE_POW2:
3871 break;
3872 default:
3873 return stats_list;
3874 }
3875
3876 /* Alloc and populate data list */
3877 stats = g_new0(Stats, 1);
3878 stats->name = g_strdup(pdesc->name);
3879 stats->value = g_new0(StatsValue, 1);;
3880
105bb7cd
PB
3881 if ((pdesc->flags & KVM_STATS_UNIT_MASK) == KVM_STATS_UNIT_BOOLEAN) {
3882 stats->value->u.boolean = *stats_data;
3883 stats->value->type = QTYPE_QBOOL;
3884 } else if (pdesc->size == 1) {
cc01a3f4
MK
3885 stats->value->u.scalar = *stats_data;
3886 stats->value->type = QTYPE_QNUM;
3887 } else {
3888 int i;
3889 for (i = 0; i < pdesc->size; i++) {
3890 QAPI_LIST_PREPEND(val_list, stats_data[i]);
3891 }
3892 stats->value->u.list = val_list;
3893 stats->value->type = QTYPE_QLIST;
3894 }
3895
3896 QAPI_LIST_PREPEND(stats_list, stats);
3897 return stats_list;
3898}
3899
3900static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
3901 StatsSchemaValueList *list,
3902 Error **errp)
3903{
3904 StatsSchemaValueList *schema_entry = g_new0(StatsSchemaValueList, 1);
3905 schema_entry->value = g_new0(StatsSchemaValue, 1);
3906
3907 switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
3908 case KVM_STATS_TYPE_CUMULATIVE:
3909 schema_entry->value->type = STATS_TYPE_CUMULATIVE;
3910 break;
3911 case KVM_STATS_TYPE_INSTANT:
3912 schema_entry->value->type = STATS_TYPE_INSTANT;
3913 break;
3914 case KVM_STATS_TYPE_PEAK:
3915 schema_entry->value->type = STATS_TYPE_PEAK;
3916 break;
3917 case KVM_STATS_TYPE_LINEAR_HIST:
3918 schema_entry->value->type = STATS_TYPE_LINEAR_HISTOGRAM;
3919 schema_entry->value->bucket_size = pdesc->bucket_size;
3920 schema_entry->value->has_bucket_size = true;
3921 break;
3922 case KVM_STATS_TYPE_LOG_HIST:
3923 schema_entry->value->type = STATS_TYPE_LOG2_HISTOGRAM;
3924 break;
3925 default:
3926 goto exit;
3927 }
3928
3929 switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
3930 case KVM_STATS_UNIT_NONE:
3931 break;
105bb7cd
PB
3932 case KVM_STATS_UNIT_BOOLEAN:
3933 schema_entry->value->has_unit = true;
3934 schema_entry->value->unit = STATS_UNIT_BOOLEAN;
3935 break;
cc01a3f4
MK
3936 case KVM_STATS_UNIT_BYTES:
3937 schema_entry->value->has_unit = true;
3938 schema_entry->value->unit = STATS_UNIT_BYTES;
3939 break;
3940 case KVM_STATS_UNIT_CYCLES:
3941 schema_entry->value->has_unit = true;
3942 schema_entry->value->unit = STATS_UNIT_CYCLES;
3943 break;
3944 case KVM_STATS_UNIT_SECONDS:
3945 schema_entry->value->has_unit = true;
3946 schema_entry->value->unit = STATS_UNIT_SECONDS;
3947 break;
3948 default:
3949 goto exit;
3950 }
3951
3952 schema_entry->value->exponent = pdesc->exponent;
3953 if (pdesc->exponent) {
3954 switch (pdesc->flags & KVM_STATS_BASE_MASK) {
3955 case KVM_STATS_BASE_POW10:
3956 schema_entry->value->has_base = true;
3957 schema_entry->value->base = 10;
3958 break;
3959 case KVM_STATS_BASE_POW2:
3960 schema_entry->value->has_base = true;
3961 schema_entry->value->base = 2;
3962 break;
3963 default:
3964 goto exit;
3965 }
3966 }
3967
3968 schema_entry->value->name = g_strdup(pdesc->name);
3969 schema_entry->next = list;
3970 return schema_entry;
3971exit:
3972 g_free(schema_entry->value);
3973 g_free(schema_entry);
3974 return list;
3975}
3976
3977/* Cached stats descriptors */
3978typedef struct StatsDescriptors {
3979 const char *ident; /* cache key, currently the StatsTarget */
3980 struct kvm_stats_desc *kvm_stats_desc;
21adec30 3981 struct kvm_stats_header kvm_stats_header;
cc01a3f4
MK
3982 QTAILQ_ENTRY(StatsDescriptors) next;
3983} StatsDescriptors;
3984
3985static QTAILQ_HEAD(, StatsDescriptors) stats_descriptors =
3986 QTAILQ_HEAD_INITIALIZER(stats_descriptors);
3987
3988/*
3989 * Return the descriptors for 'target', that either have already been read
3990 * or are retrieved from 'stats_fd'.
3991 */
3992static StatsDescriptors *find_stats_descriptors(StatsTarget target, int stats_fd,
3993 Error **errp)
3994{
3995 StatsDescriptors *descriptors;
3996 const char *ident;
3997 struct kvm_stats_desc *kvm_stats_desc;
3998 struct kvm_stats_header *kvm_stats_header;
3999 size_t size_desc;
4000 ssize_t ret;
4001
4002 ident = StatsTarget_str(target);
4003 QTAILQ_FOREACH(descriptors, &stats_descriptors, next) {
4004 if (g_str_equal(descriptors->ident, ident)) {
4005 return descriptors;
4006 }
4007 }
4008
4009 descriptors = g_new0(StatsDescriptors, 1);
4010
4011 /* Read stats header */
21adec30 4012 kvm_stats_header = &descriptors->kvm_stats_header;
3b6f4852 4013 ret = pread(stats_fd, kvm_stats_header, sizeof(*kvm_stats_header), 0);
cc01a3f4
MK
4014 if (ret != sizeof(*kvm_stats_header)) {
4015 error_setg(errp, "KVM stats: failed to read stats header: "
4016 "expected %zu actual %zu",
4017 sizeof(*kvm_stats_header), ret);
f696b74b 4018 g_free(descriptors);
cc01a3f4
MK
4019 return NULL;
4020 }
4021 size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4022
4023 /* Read stats descriptors */
4024 kvm_stats_desc = g_malloc0_n(kvm_stats_header->num_desc, size_desc);
4025 ret = pread(stats_fd, kvm_stats_desc,
4026 size_desc * kvm_stats_header->num_desc,
4027 kvm_stats_header->desc_offset);
4028
4029 if (ret != size_desc * kvm_stats_header->num_desc) {
4030 error_setg(errp, "KVM stats: failed to read stats descriptors: "
4031 "expected %zu actual %zu",
4032 size_desc * kvm_stats_header->num_desc, ret);
4033 g_free(descriptors);
4034 g_free(kvm_stats_desc);
4035 return NULL;
4036 }
cc01a3f4
MK
4037 descriptors->kvm_stats_desc = kvm_stats_desc;
4038 descriptors->ident = ident;
4039 QTAILQ_INSERT_TAIL(&stats_descriptors, descriptors, next);
4040 return descriptors;
4041}
4042
4043static void query_stats(StatsResultList **result, StatsTarget target,
3b6f4852
MT
4044 strList *names, int stats_fd, CPUState *cpu,
4045 Error **errp)
cc01a3f4
MK
4046{
4047 struct kvm_stats_desc *kvm_stats_desc;
4048 struct kvm_stats_header *kvm_stats_header;
4049 StatsDescriptors *descriptors;
4050 g_autofree uint64_t *stats_data = NULL;
4051 struct kvm_stats_desc *pdesc;
4052 StatsList *stats_list = NULL;
4053 size_t size_desc, size_data = 0;
4054 ssize_t ret;
4055 int i;
4056
4057 descriptors = find_stats_descriptors(target, stats_fd, errp);
4058 if (!descriptors) {
4059 return;
4060 }
4061
21adec30 4062 kvm_stats_header = &descriptors->kvm_stats_header;
cc01a3f4
MK
4063 kvm_stats_desc = descriptors->kvm_stats_desc;
4064 size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4065
4066 /* Tally the total data size; read schema data */
4067 for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4068 pdesc = (void *)kvm_stats_desc + i * size_desc;
4069 size_data += pdesc->size * sizeof(*stats_data);
4070 }
4071
4072 stats_data = g_malloc0(size_data);
4073 ret = pread(stats_fd, stats_data, size_data, kvm_stats_header->data_offset);
4074
4075 if (ret != size_data) {
4076 error_setg(errp, "KVM stats: failed to read data: "
4077 "expected %zu actual %zu", size_data, ret);
4078 return;
4079 }
4080
4081 for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4082 uint64_t *stats;
4083 pdesc = (void *)kvm_stats_desc + i * size_desc;
4084
4085 /* Add entry to the list */
4086 stats = (void *)stats_data + pdesc->offset;
cf7405bc
PB
4087 if (!apply_str_list_filter(pdesc->name, names)) {
4088 continue;
4089 }
cc01a3f4
MK
4090 stats_list = add_kvmstat_entry(pdesc, stats, stats_list, errp);
4091 }
4092
4093 if (!stats_list) {
4094 return;
4095 }
4096
4097 switch (target) {
4098 case STATS_TARGET_VM:
4099 add_stats_entry(result, STATS_PROVIDER_KVM, NULL, stats_list);
4100 break;
4101 case STATS_TARGET_VCPU:
4102 add_stats_entry(result, STATS_PROVIDER_KVM,
3b6f4852 4103 cpu->parent_obj.canonical_path,
cc01a3f4
MK
4104 stats_list);
4105 break;
4106 default:
d12dd9c7 4107 g_assert_not_reached();
cc01a3f4
MK
4108 }
4109}
4110
4111static void query_stats_schema(StatsSchemaList **result, StatsTarget target,
4112 int stats_fd, Error **errp)
4113{
4114 struct kvm_stats_desc *kvm_stats_desc;
4115 struct kvm_stats_header *kvm_stats_header;
4116 StatsDescriptors *descriptors;
4117 struct kvm_stats_desc *pdesc;
4118 StatsSchemaValueList *stats_list = NULL;
4119 size_t size_desc;
4120 int i;
4121
4122 descriptors = find_stats_descriptors(target, stats_fd, errp);
4123 if (!descriptors) {
4124 return;
4125 }
4126
21adec30 4127 kvm_stats_header = &descriptors->kvm_stats_header;
cc01a3f4
MK
4128 kvm_stats_desc = descriptors->kvm_stats_desc;
4129 size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
4130
4131 /* Tally the total data size; read schema data */
4132 for (i = 0; i < kvm_stats_header->num_desc; ++i) {
4133 pdesc = (void *)kvm_stats_desc + i * size_desc;
4134 stats_list = add_kvmschema_entry(pdesc, stats_list, errp);
4135 }
4136
4137 add_stats_schema(result, STATS_PROVIDER_KVM, target, stats_list);
4138}
4139
3b6f4852 4140static void query_stats_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
cc01a3f4 4141{
3b6f4852 4142 int stats_fd = cpu->kvm_vcpu_stats_fd;
cc01a3f4
MK
4143 Error *local_err = NULL;
4144
4145 if (stats_fd == -1) {
4146 error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4147 error_propagate(kvm_stats_args->errp, local_err);
4148 return;
4149 }
cf7405bc 4150 query_stats(kvm_stats_args->result.stats, STATS_TARGET_VCPU,
3b6f4852
MT
4151 kvm_stats_args->names, stats_fd, cpu,
4152 kvm_stats_args->errp);
cc01a3f4
MK
4153}
4154
3b6f4852 4155static void query_stats_schema_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
cc01a3f4 4156{
3b6f4852 4157 int stats_fd = cpu->kvm_vcpu_stats_fd;
cc01a3f4
MK
4158 Error *local_err = NULL;
4159
4160 if (stats_fd == -1) {
4161 error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
4162 error_propagate(kvm_stats_args->errp, local_err);
4163 return;
4164 }
4165 query_stats_schema(kvm_stats_args->result.schema, STATS_TARGET_VCPU, stats_fd,
4166 kvm_stats_args->errp);
cc01a3f4
MK
4167}
4168
467ef823 4169static void query_stats_cb(StatsResultList **result, StatsTarget target,
cf7405bc 4170 strList *names, strList *targets, Error **errp)
cc01a3f4
MK
4171{
4172 KVMState *s = kvm_state;
4173 CPUState *cpu;
4174 int stats_fd;
4175
4176 switch (target) {
4177 case STATS_TARGET_VM:
4178 {
4179 stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4180 if (stats_fd == -1) {
4181 error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4182 return;
4183 }
3b6f4852 4184 query_stats(result, target, names, stats_fd, NULL, errp);
cc01a3f4
MK
4185 close(stats_fd);
4186 break;
4187 }
4188 case STATS_TARGET_VCPU:
4189 {
4190 StatsArgs stats_args;
4191 stats_args.result.stats = result;
cf7405bc 4192 stats_args.names = names;
cc01a3f4
MK
4193 stats_args.errp = errp;
4194 CPU_FOREACH(cpu) {
467ef823
PB
4195 if (!apply_str_list_filter(cpu->parent_obj.canonical_path, targets)) {
4196 continue;
4197 }
3b6f4852 4198 query_stats_vcpu(cpu, &stats_args);
cc01a3f4
MK
4199 }
4200 break;
4201 }
4202 default:
4203 break;
4204 }
4205}
4206
4207void query_stats_schemas_cb(StatsSchemaList **result, Error **errp)
4208{
4209 StatsArgs stats_args;
4210 KVMState *s = kvm_state;
4211 int stats_fd;
4212
4213 stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
4214 if (stats_fd == -1) {
4215 error_setg_errno(errp, errno, "KVM stats: ioctl failed");
4216 return;
4217 }
4218 query_stats_schema(result, STATS_TARGET_VM, stats_fd, errp);
4219 close(stats_fd);
4220
a9197ad2
PB
4221 if (first_cpu) {
4222 stats_args.result.schema = result;
4223 stats_args.errp = errp;
3b6f4852 4224 query_stats_schema_vcpu(first_cpu, &stats_args);
a9197ad2 4225 }
cc01a3f4 4226}