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