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