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