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