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