qemu/kvm-all.c
<<
>>
Prefs
   1/*
   2 * QEMU KVM support
   3 *
   4 * Copyright IBM, Corp. 2008
   5 *           Red Hat, Inc. 2008
   6 *
   7 * Authors:
   8 *  Anthony Liguori   <aliguori@us.ibm.com>
   9 *  Glauber Costa     <gcosta@redhat.com>
  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
  16#include <sys/types.h>
  17#include <sys/ioctl.h>
  18#include <sys/mman.h>
  19#include <stdarg.h>
  20
  21#include <linux/kvm.h>
  22
  23#include "qemu-common.h"
  24#include "qemu/atomic.h"
  25#include "qemu/option.h"
  26#include "qemu/config-file.h"
  27#include "sysemu/sysemu.h"
  28#include "sysemu/accel.h"
  29#include "hw/hw.h"
  30#include "hw/pci/msi.h"
  31#include "hw/s390x/adapter.h"
  32#include "exec/gdbstub.h"
  33#include "sysemu/kvm.h"
  34#include "qemu/bswap.h"
  35#include "exec/memory.h"
  36#include "exec/ram_addr.h"
  37#include "exec/address-spaces.h"
  38#include "qemu/event_notifier.h"
  39#include "trace.h"
  40
  41#include "hw/boards.h"
  42
  43/* This check must be after config-host.h is included */
  44#ifdef CONFIG_EVENTFD
  45#include <sys/eventfd.h>
  46#endif
  47
  48/* KVM uses PAGE_SIZE in its definition of COALESCED_MMIO_MAX */
  49#define PAGE_SIZE TARGET_PAGE_SIZE
  50
  51//#define DEBUG_KVM
  52
  53#ifdef DEBUG_KVM
  54#define DPRINTF(fmt, ...) \
  55    do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
  56#else
  57#define DPRINTF(fmt, ...) \
  58    do { } while (0)
  59#endif
  60
  61#define KVM_MSI_HASHTAB_SIZE    256
  62
  63typedef struct KVMSlot
  64{
  65    hwaddr start_addr;
  66    ram_addr_t memory_size;
  67    void *ram;
  68    int slot;
  69    int flags;
  70} KVMSlot;
  71
  72typedef struct kvm_dirty_log KVMDirtyLog;
  73
  74struct KVMState
  75{
  76    AccelState parent_obj;
  77
  78    KVMSlot *slots;
  79    int nr_slots;
  80    int fd;
  81    int vmfd;
  82    int coalesced_mmio;
  83    struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
  84    bool coalesced_flush_in_progress;
  85    int broken_set_mem_region;
  86    int migration_log;
  87    int vcpu_events;
  88    int robust_singlestep;
  89    int debugregs;
  90#ifdef KVM_CAP_SET_GUEST_DEBUG
  91    struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
  92#endif
  93    int pit_state2;
  94    int xsave, xcrs;
  95    int many_ioeventfds;
  96    int intx_set_mask;
  97    /* The man page (and posix) say ioctl numbers are signed int, but
  98     * they're not.  Linux, glibc and *BSD all treat ioctl numbers as
  99     * unsigned, and treating them as signed here can break things */
 100    unsigned irq_set_ioctl;
 101    unsigned int sigmask_len;
 102#ifdef KVM_CAP_IRQ_ROUTING
 103    struct kvm_irq_routing *irq_routes;
 104    int nr_allocated_irq_routes;
 105    uint32_t *used_gsi_bitmap;
 106    unsigned int gsi_count;
 107    QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
 108    bool direct_msi;
 109#endif
 110};
 111
 112#define TYPE_KVM_ACCEL ACCEL_CLASS_NAME("kvm")
 113
 114#define KVM_STATE(obj) \
 115    OBJECT_CHECK(KVMState, (obj), TYPE_KVM_ACCEL)
 116
 117KVMState *kvm_state;
 118bool kvm_kernel_irqchip;
 119bool kvm_async_interrupts_allowed;
 120bool kvm_halt_in_kernel_allowed;
 121bool kvm_eventfds_allowed;
 122bool kvm_irqfds_allowed;
 123bool kvm_msi_via_irqfd_allowed;
 124bool kvm_gsi_routing_allowed;
 125bool kvm_gsi_direct_mapping;
 126bool kvm_allowed;
 127bool kvm_readonly_mem_allowed;
 128
 129static const KVMCapabilityInfo kvm_required_capabilites[] = {
 130    KVM_CAP_INFO(USER_MEMORY),
 131    KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
 132    KVM_CAP_LAST_INFO
 133};
 134
 135static KVMSlot *kvm_get_free_slot(KVMState *s)
 136{
 137    int i;
 138
 139    for (i = 0; i < s->nr_slots; i++) {
 140        if (s->slots[i].memory_size == 0) {
 141            return &s->slots[i];
 142        }
 143    }
 144
 145    return NULL;
 146}
 147
 148bool kvm_has_free_slot(MachineState *ms)
 149{
 150    return kvm_get_free_slot(KVM_STATE(ms->accelerator));
 151}
 152
 153static KVMSlot *kvm_alloc_slot(KVMState *s)
 154{
 155    KVMSlot *slot = kvm_get_free_slot(s);
 156
 157    if (slot) {
 158        return slot;
 159    }
 160
 161    fprintf(stderr, "%s: no free slot available\n", __func__);
 162    abort();
 163}
 164
 165static KVMSlot *kvm_lookup_matching_slot(KVMState *s,
 166                                         hwaddr start_addr,
 167                                         hwaddr end_addr)
 168{
 169    int i;
 170
 171    for (i = 0; i < s->nr_slots; i++) {
 172        KVMSlot *mem = &s->slots[i];
 173
 174        if (start_addr == mem->start_addr &&
 175            end_addr == mem->start_addr + mem->memory_size) {
 176            return mem;
 177        }
 178    }
 179
 180    return NULL;
 181}
 182
 183/*
 184 * Find overlapping slot with lowest start address
 185 */
 186static KVMSlot *kvm_lookup_overlapping_slot(KVMState *s,
 187                                            hwaddr start_addr,
 188                                            hwaddr end_addr)
 189{
 190    KVMSlot *found = NULL;
 191    int i;
 192
 193    for (i = 0; i < s->nr_slots; i++) {
 194        KVMSlot *mem = &s->slots[i];
 195
 196        if (mem->memory_size == 0 ||
 197            (found && found->start_addr < mem->start_addr)) {
 198            continue;
 199        }
 200
 201        if (end_addr > mem->start_addr &&
 202            start_addr < mem->start_addr + mem->memory_size) {
 203            found = mem;
 204        }
 205    }
 206
 207    return found;
 208}
 209
 210int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
 211                                       hwaddr *phys_addr)
 212{
 213    int i;
 214
 215    for (i = 0; i < s->nr_slots; i++) {
 216        KVMSlot *mem = &s->slots[i];
 217
 218        if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
 219            *phys_addr = mem->start_addr + (ram - mem->ram);
 220            return 1;
 221        }
 222    }
 223
 224    return 0;
 225}
 226
 227static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)
 228{
 229    struct kvm_userspace_memory_region mem;
 230
 231    mem.slot = slot->slot;
 232    mem.guest_phys_addr = slot->start_addr;
 233    mem.userspace_addr = (unsigned long)slot->ram;
 234    mem.flags = slot->flags;
 235    if (s->migration_log) {
 236        mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;
 237    }
 238
 239    if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
 240        /* Set the slot size to 0 before setting the slot to the desired
 241         * value. This is needed based on KVM commit 75d61fbc. */
 242        mem.memory_size = 0;
 243        kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
 244    }
 245    mem.memory_size = slot->memory_size;
 246    return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
 247}
 248
 249int kvm_init_vcpu(CPUState *cpu)
 250{
 251    KVMState *s = kvm_state;
 252    long mmap_size;
 253    int ret;
 254
 255    DPRINTF("kvm_init_vcpu\n");
 256
 257    ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)kvm_arch_vcpu_id(cpu));
 258    if (ret < 0) {
 259        DPRINTF("kvm_create_vcpu failed\n");
 260        goto err;
 261    }
 262
 263    cpu->kvm_fd = ret;
 264    cpu->kvm_state = s;
 265    cpu->kvm_vcpu_dirty = true;
 266
 267    mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
 268    if (mmap_size < 0) {
 269        ret = mmap_size;
 270        DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
 271        goto err;
 272    }
 273
 274    cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
 275                        cpu->kvm_fd, 0);
 276    if (cpu->kvm_run == MAP_FAILED) {
 277        ret = -errno;
 278        DPRINTF("mmap'ing vcpu state failed\n");
 279        goto err;
 280    }
 281
 282    if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
 283        s->coalesced_mmio_ring =
 284            (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
 285    }
 286
 287    ret = kvm_arch_init_vcpu(cpu);
 288err:
 289    return ret;
 290}
 291
 292/*
 293 * dirty pages logging control
 294 */
 295
 296static int kvm_mem_flags(KVMState *s, bool log_dirty, bool readonly)
 297{
 298    int flags = 0;
 299    flags = log_dirty ? KVM_MEM_LOG_DIRTY_PAGES : 0;
 300    if (readonly && kvm_readonly_mem_allowed) {
 301        flags |= KVM_MEM_READONLY;
 302    }
 303    return flags;
 304}
 305
 306static int kvm_slot_dirty_pages_log_change(KVMSlot *mem, bool log_dirty)
 307{
 308    KVMState *s = kvm_state;
 309    int flags, mask = KVM_MEM_LOG_DIRTY_PAGES;
 310    int old_flags;
 311
 312    old_flags = mem->flags;
 313
 314    flags = (mem->flags & ~mask) | kvm_mem_flags(s, log_dirty, false);
 315    mem->flags = flags;
 316
 317    /* If nothing changed effectively, no need to issue ioctl */
 318    if (s->migration_log) {
 319        flags |= KVM_MEM_LOG_DIRTY_PAGES;
 320    }
 321
 322    if (flags == old_flags) {
 323        return 0;
 324    }
 325
 326    return kvm_set_user_memory_region(s, mem);
 327}
 328
 329static int kvm_dirty_pages_log_change(hwaddr phys_addr,
 330                                      ram_addr_t size, bool log_dirty)
 331{
 332    KVMState *s = kvm_state;
 333    KVMSlot *mem = kvm_lookup_matching_slot(s, phys_addr, phys_addr + size);
 334
 335    if (mem == NULL)  {
 336        fprintf(stderr, "BUG: %s: invalid parameters " TARGET_FMT_plx "-"
 337                TARGET_FMT_plx "\n", __func__, phys_addr,
 338                (hwaddr)(phys_addr + size - 1));
 339        return -EINVAL;
 340    }
 341    return kvm_slot_dirty_pages_log_change(mem, log_dirty);
 342}
 343
 344static void kvm_log_start(MemoryListener *listener,
 345                          MemoryRegionSection *section)
 346{
 347    int r;
 348
 349    r = kvm_dirty_pages_log_change(section->offset_within_address_space,
 350                                   int128_get64(section->size), true);
 351    if (r < 0) {
 352        abort();
 353    }
 354}
 355
 356static void kvm_log_stop(MemoryListener *listener,
 357                          MemoryRegionSection *section)
 358{
 359    int r;
 360
 361    r = kvm_dirty_pages_log_change(section->offset_within_address_space,
 362                                   int128_get64(section->size), false);
 363    if (r < 0) {
 364        abort();
 365    }
 366}
 367
 368static int kvm_set_migration_log(int enable)
 369{
 370    KVMState *s = kvm_state;
 371    KVMSlot *mem;
 372    int i, err;
 373
 374    s->migration_log = enable;
 375
 376    for (i = 0; i < s->nr_slots; i++) {
 377        mem = &s->slots[i];
 378
 379        if (!mem->memory_size) {
 380            continue;
 381        }
 382        if (!!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) == enable) {
 383            continue;
 384        }
 385        err = kvm_set_user_memory_region(s, mem);
 386        if (err) {
 387            return err;
 388        }
 389    }
 390    return 0;
 391}
 392
 393/* get kvm's dirty pages bitmap and update qemu's */
 394static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
 395                                         unsigned long *bitmap)
 396{
 397    ram_addr_t start = section->offset_within_region + section->mr->ram_addr;
 398    ram_addr_t pages = int128_get64(section->size) / getpagesize();
 399
 400    cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
 401    return 0;
 402}
 403
 404#define ALIGN(x, y)  (((x)+(y)-1) & ~((y)-1))
 405
 406/**
 407 * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
 408 * This function updates qemu's dirty bitmap using
 409 * memory_region_set_dirty().  This means all bits are set
 410 * to dirty.
 411 *
 412 * @start_add: start of logged region.
 413 * @end_addr: end of logged region.
 414 */
 415static int kvm_physical_sync_dirty_bitmap(MemoryRegionSection *section)
 416{
 417    KVMState *s = kvm_state;
 418    unsigned long size, allocated_size = 0;
 419    KVMDirtyLog d;
 420    KVMSlot *mem;
 421    int ret = 0;
 422    hwaddr start_addr = section->offset_within_address_space;
 423    hwaddr end_addr = start_addr + int128_get64(section->size);
 424
 425    d.dirty_bitmap = NULL;
 426    while (start_addr < end_addr) {
 427        mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);
 428        if (mem == NULL) {
 429            break;
 430        }
 431
 432        /* XXX bad kernel interface alert
 433         * For dirty bitmap, kernel allocates array of size aligned to
 434         * bits-per-long.  But for case when the kernel is 64bits and
 435         * the userspace is 32bits, userspace can't align to the same
 436         * bits-per-long, since sizeof(long) is different between kernel
 437         * and user space.  This way, userspace will provide buffer which
 438         * may be 4 bytes less than the kernel will use, resulting in
 439         * userspace memory corruption (which is not detectable by valgrind
 440         * too, in most cases).
 441         * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
 442         * a hope that sizeof(long) wont become >8 any time soon.
 443         */
 444        size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
 445                     /*HOST_LONG_BITS*/ 64) / 8;
 446        if (!d.dirty_bitmap) {
 447            d.dirty_bitmap = g_malloc(size);
 448        } else if (size > allocated_size) {
 449            d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
 450        }
 451        allocated_size = size;
 452        memset(d.dirty_bitmap, 0, allocated_size);
 453
 454        d.slot = mem->slot;
 455
 456        if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
 457            DPRINTF("ioctl failed %d\n", errno);
 458            ret = -1;
 459            break;
 460        }
 461
 462        kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
 463        start_addr = mem->start_addr + mem->memory_size;
 464    }
 465    g_free(d.dirty_bitmap);
 466
 467    return ret;
 468}
 469
 470static void kvm_coalesce_mmio_region(MemoryListener *listener,
 471                                     MemoryRegionSection *secion,
 472                                     hwaddr start, hwaddr size)
 473{
 474    KVMState *s = kvm_state;
 475
 476    if (s->coalesced_mmio) {
 477        struct kvm_coalesced_mmio_zone zone;
 478
 479        zone.addr = start;
 480        zone.size = size;
 481        zone.pad = 0;
 482
 483        (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
 484    }
 485}
 486
 487static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
 488                                       MemoryRegionSection *secion,
 489                                       hwaddr start, hwaddr size)
 490{
 491    KVMState *s = kvm_state;
 492
 493    if (s->coalesced_mmio) {
 494        struct kvm_coalesced_mmio_zone zone;
 495
 496        zone.addr = start;
 497        zone.size = size;
 498        zone.pad = 0;
 499
 500        (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
 501    }
 502}
 503
 504int kvm_check_extension(KVMState *s, unsigned int extension)
 505{
 506    int ret;
 507
 508    ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
 509    if (ret < 0) {
 510        ret = 0;
 511    }
 512
 513    return ret;
 514}
 515
 516int kvm_vm_check_extension(KVMState *s, unsigned int extension)
 517{
 518    int ret;
 519
 520    ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
 521    if (ret < 0) {
 522        /* VM wide version not implemented, use global one instead */
 523        ret = kvm_check_extension(s, extension);
 524    }
 525
 526    return ret;
 527}
 528
 529static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
 530                                  bool assign, uint32_t size, bool datamatch)
 531{
 532    int ret;
 533    struct kvm_ioeventfd iofd;
 534
 535    iofd.datamatch = datamatch ? val : 0;
 536    iofd.addr = addr;
 537    iofd.len = size;
 538    iofd.flags = 0;
 539    iofd.fd = fd;
 540
 541    if (!kvm_enabled()) {
 542        return -ENOSYS;
 543    }
 544
 545    if (datamatch) {
 546        iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
 547    }
 548    if (!assign) {
 549        iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
 550    }
 551
 552    ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
 553
 554    if (ret < 0) {
 555        return -errno;
 556    }
 557
 558    return 0;
 559}
 560
 561static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
 562                                 bool assign, uint32_t size, bool datamatch)
 563{
 564    struct kvm_ioeventfd kick = {
 565        .datamatch = datamatch ? val : 0,
 566        .addr = addr,
 567        .flags = KVM_IOEVENTFD_FLAG_PIO,
 568        .len = size,
 569        .fd = fd,
 570    };
 571    int r;
 572    if (!kvm_enabled()) {
 573        return -ENOSYS;
 574    }
 575    if (datamatch) {
 576        kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
 577    }
 578    if (!assign) {
 579        kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
 580    }
 581    r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
 582    if (r < 0) {
 583        return r;
 584    }
 585    return 0;
 586}
 587
 588
 589static int kvm_check_many_ioeventfds(void)
 590{
 591    /* Userspace can use ioeventfd for io notification.  This requires a host
 592     * that supports eventfd(2) and an I/O thread; since eventfd does not
 593     * support SIGIO it cannot interrupt the vcpu.
 594     *
 595     * Older kernels have a 6 device limit on the KVM io bus.  Find out so we
 596     * can avoid creating too many ioeventfds.
 597     */
 598#if defined(CONFIG_EVENTFD)
 599    int ioeventfds[7];
 600    int i, ret = 0;
 601    for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
 602        ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
 603        if (ioeventfds[i] < 0) {
 604            break;
 605        }
 606        ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
 607        if (ret < 0) {
 608            close(ioeventfds[i]);
 609            break;
 610        }
 611    }
 612
 613    /* Decide whether many devices are supported or not */
 614    ret = i == ARRAY_SIZE(ioeventfds);
 615
 616    while (i-- > 0) {
 617        kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
 618        close(ioeventfds[i]);
 619    }
 620    return ret;
 621#else
 622    return 0;
 623#endif
 624}
 625
 626static const KVMCapabilityInfo *
 627kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
 628{
 629    while (list->name) {
 630        if (!kvm_check_extension(s, list->value)) {
 631            return list;
 632        }
 633        list++;
 634    }
 635    return NULL;
 636}
 637
 638static void kvm_set_phys_mem(MemoryRegionSection *section, bool add)
 639{
 640    KVMState *s = kvm_state;
 641    KVMSlot *mem, old;
 642    int err;
 643    MemoryRegion *mr = section->mr;
 644    bool log_dirty = memory_region_is_logging(mr);
 645    bool writeable = !mr->readonly && !mr->rom_device;
 646    bool readonly_flag = mr->readonly || memory_region_is_romd(mr);
 647    hwaddr start_addr = section->offset_within_address_space;
 648    ram_addr_t size = int128_get64(section->size);
 649    void *ram = NULL;
 650    unsigned delta;
 651
 652    /* kvm works in page size chunks, but the function may be called
 653       with sub-page size and unaligned start address. Pad the start
 654       address to next and truncate size to previous page boundary. */
 655    delta = (TARGET_PAGE_SIZE - (start_addr & ~TARGET_PAGE_MASK));
 656    delta &= ~TARGET_PAGE_MASK;
 657    if (delta > size) {
 658        return;
 659    }
 660    start_addr += delta;
 661    size -= delta;
 662    size &= TARGET_PAGE_MASK;
 663    if (!size || (start_addr & ~TARGET_PAGE_MASK)) {
 664        return;
 665    }
 666
 667    if (!memory_region_is_ram(mr)) {
 668        if (writeable || !kvm_readonly_mem_allowed) {
 669            return;
 670        } else if (!mr->romd_mode) {
 671            /* If the memory device is not in romd_mode, then we actually want
 672             * to remove the kvm memory slot so all accesses will trap. */
 673            add = false;
 674        }
 675    }
 676
 677    ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
 678
 679    while (1) {
 680        mem = kvm_lookup_overlapping_slot(s, start_addr, start_addr + size);
 681        if (!mem) {
 682            break;
 683        }
 684
 685        if (add && start_addr >= mem->start_addr &&
 686            (start_addr + size <= mem->start_addr + mem->memory_size) &&
 687            (ram - start_addr == mem->ram - mem->start_addr)) {
 688            /* The new slot fits into the existing one and comes with
 689             * identical parameters - update flags and done. */
 690            kvm_slot_dirty_pages_log_change(mem, log_dirty);
 691            return;
 692        }
 693
 694        old = *mem;
 695
 696        if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
 697            kvm_physical_sync_dirty_bitmap(section);
 698        }
 699
 700        /* unregister the overlapping slot */
 701        mem->memory_size = 0;
 702        err = kvm_set_user_memory_region(s, mem);
 703        if (err) {
 704            fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
 705                    __func__, strerror(-err));
 706            abort();
 707        }
 708
 709        /* Workaround for older KVM versions: we can't join slots, even not by
 710         * unregistering the previous ones and then registering the larger
 711         * slot. We have to maintain the existing fragmentation. Sigh.
 712         *
 713         * This workaround assumes that the new slot starts at the same
 714         * address as the first existing one. If not or if some overlapping
 715         * slot comes around later, we will fail (not seen in practice so far)
 716         * - and actually require a recent KVM version. */
 717        if (s->broken_set_mem_region &&
 718            old.start_addr == start_addr && old.memory_size < size && add) {
 719            mem = kvm_alloc_slot(s);
 720            mem->memory_size = old.memory_size;
 721            mem->start_addr = old.start_addr;
 722            mem->ram = old.ram;
 723            mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
 724
 725            err = kvm_set_user_memory_region(s, mem);
 726            if (err) {
 727                fprintf(stderr, "%s: error updating slot: %s\n", __func__,
 728                        strerror(-err));
 729                abort();
 730            }
 731
 732            start_addr += old.memory_size;
 733            ram += old.memory_size;
 734            size -= old.memory_size;
 735            continue;
 736        }
 737
 738        /* register prefix slot */
 739        if (old.start_addr < start_addr) {
 740            mem = kvm_alloc_slot(s);
 741            mem->memory_size = start_addr - old.start_addr;
 742            mem->start_addr = old.start_addr;
 743            mem->ram = old.ram;
 744            mem->flags =  kvm_mem_flags(s, log_dirty, readonly_flag);
 745
 746            err = kvm_set_user_memory_region(s, mem);
 747            if (err) {
 748                fprintf(stderr, "%s: error registering prefix slot: %s\n",
 749                        __func__, strerror(-err));
 750#ifdef TARGET_PPC
 751                fprintf(stderr, "%s: This is probably because your kernel's " \
 752                                "PAGE_SIZE is too big. Please try to use 4k " \
 753                                "PAGE_SIZE!\n", __func__);
 754#endif
 755                abort();
 756            }
 757        }
 758
 759        /* register suffix slot */
 760        if (old.start_addr + old.memory_size > start_addr + size) {
 761            ram_addr_t size_delta;
 762
 763            mem = kvm_alloc_slot(s);
 764            mem->start_addr = start_addr + size;
 765            size_delta = mem->start_addr - old.start_addr;
 766            mem->memory_size = old.memory_size - size_delta;
 767            mem->ram = old.ram + size_delta;
 768            mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
 769
 770            err = kvm_set_user_memory_region(s, mem);
 771            if (err) {
 772                fprintf(stderr, "%s: error registering suffix slot: %s\n",
 773                        __func__, strerror(-err));
 774                abort();
 775            }
 776        }
 777    }
 778
 779    /* in case the KVM bug workaround already "consumed" the new slot */
 780    if (!size) {
 781        return;
 782    }
 783    if (!add) {
 784        return;
 785    }
 786    mem = kvm_alloc_slot(s);
 787    mem->memory_size = size;
 788    mem->start_addr = start_addr;
 789    mem->ram = ram;
 790    mem->flags = kvm_mem_flags(s, log_dirty, readonly_flag);
 791
 792    err = kvm_set_user_memory_region(s, mem);
 793    if (err) {
 794        fprintf(stderr, "%s: error registering slot: %s\n", __func__,
 795                strerror(-err));
 796        abort();
 797    }
 798}
 799
 800static void kvm_region_add(MemoryListener *listener,
 801                           MemoryRegionSection *section)
 802{
 803    memory_region_ref(section->mr);
 804    kvm_set_phys_mem(section, true);
 805}
 806
 807static void kvm_region_del(MemoryListener *listener,
 808                           MemoryRegionSection *section)
 809{
 810    kvm_set_phys_mem(section, false);
 811    memory_region_unref(section->mr);
 812}
 813
 814static void kvm_log_sync(MemoryListener *listener,
 815                         MemoryRegionSection *section)
 816{
 817    int r;
 818
 819    r = kvm_physical_sync_dirty_bitmap(section);
 820    if (r < 0) {
 821        abort();
 822    }
 823}
 824
 825static void kvm_log_global_start(struct MemoryListener *listener)
 826{
 827    int r;
 828
 829    r = kvm_set_migration_log(1);
 830    assert(r >= 0);
 831}
 832
 833static void kvm_log_global_stop(struct MemoryListener *listener)
 834{
 835    int r;
 836
 837    r = kvm_set_migration_log(0);
 838    assert(r >= 0);
 839}
 840
 841static void kvm_mem_ioeventfd_add(MemoryListener *listener,
 842                                  MemoryRegionSection *section,
 843                                  bool match_data, uint64_t data,
 844                                  EventNotifier *e)
 845{
 846    int fd = event_notifier_get_fd(e);
 847    int r;
 848
 849    r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
 850                               data, true, int128_get64(section->size),
 851                               match_data);
 852    if (r < 0) {
 853        fprintf(stderr, "%s: error adding ioeventfd: %s\n",
 854                __func__, strerror(-r));
 855        abort();
 856    }
 857}
 858
 859static void kvm_mem_ioeventfd_del(MemoryListener *listener,
 860                                  MemoryRegionSection *section,
 861                                  bool match_data, uint64_t data,
 862                                  EventNotifier *e)
 863{
 864    int fd = event_notifier_get_fd(e);
 865    int r;
 866
 867    r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
 868                               data, false, int128_get64(section->size),
 869                               match_data);
 870    if (r < 0) {
 871        abort();
 872    }
 873}
 874
 875static void kvm_io_ioeventfd_add(MemoryListener *listener,
 876                                 MemoryRegionSection *section,
 877                                 bool match_data, uint64_t data,
 878                                 EventNotifier *e)
 879{
 880    int fd = event_notifier_get_fd(e);
 881    int r;
 882
 883    r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
 884                              data, true, int128_get64(section->size),
 885                              match_data);
 886    if (r < 0) {
 887        fprintf(stderr, "%s: error adding ioeventfd: %s\n",
 888                __func__, strerror(-r));
 889        abort();
 890    }
 891}
 892
 893static void kvm_io_ioeventfd_del(MemoryListener *listener,
 894                                 MemoryRegionSection *section,
 895                                 bool match_data, uint64_t data,
 896                                 EventNotifier *e)
 897
 898{
 899    int fd = event_notifier_get_fd(e);
 900    int r;
 901
 902    r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
 903                              data, false, int128_get64(section->size),
 904                              match_data);
 905    if (r < 0) {
 906        abort();
 907    }
 908}
 909
 910static MemoryListener kvm_memory_listener = {
 911    .region_add = kvm_region_add,
 912    .region_del = kvm_region_del,
 913    .log_start = kvm_log_start,
 914    .log_stop = kvm_log_stop,
 915    .log_sync = kvm_log_sync,
 916    .log_global_start = kvm_log_global_start,
 917    .log_global_stop = kvm_log_global_stop,
 918    .eventfd_add = kvm_mem_ioeventfd_add,
 919    .eventfd_del = kvm_mem_ioeventfd_del,
 920    .coalesced_mmio_add = kvm_coalesce_mmio_region,
 921    .coalesced_mmio_del = kvm_uncoalesce_mmio_region,
 922    .priority = 10,
 923};
 924
 925static MemoryListener kvm_io_listener = {
 926    .eventfd_add = kvm_io_ioeventfd_add,
 927    .eventfd_del = kvm_io_ioeventfd_del,
 928    .priority = 10,
 929};
 930
 931static void kvm_handle_interrupt(CPUState *cpu, int mask)
 932{
 933    cpu->interrupt_request |= mask;
 934
 935    if (!qemu_cpu_is_self(cpu)) {
 936        qemu_cpu_kick(cpu);
 937    }
 938}
 939
 940int kvm_set_irq(KVMState *s, int irq, int level)
 941{
 942    struct kvm_irq_level event;
 943    int ret;
 944
 945    assert(kvm_async_interrupts_enabled());
 946
 947    event.level = level;
 948    event.irq = irq;
 949    ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
 950    if (ret < 0) {
 951        perror("kvm_set_irq");
 952        abort();
 953    }
 954
 955    return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
 956}
 957
 958#ifdef KVM_CAP_IRQ_ROUTING
 959typedef struct KVMMSIRoute {
 960    struct kvm_irq_routing_entry kroute;
 961    QTAILQ_ENTRY(KVMMSIRoute) entry;
 962} KVMMSIRoute;
 963
 964static void set_gsi(KVMState *s, unsigned int gsi)
 965{
 966    s->used_gsi_bitmap[gsi / 32] |= 1U << (gsi % 32);
 967}
 968
 969static void clear_gsi(KVMState *s, unsigned int gsi)
 970{
 971    s->used_gsi_bitmap[gsi / 32] &= ~(1U << (gsi % 32));
 972}
 973
 974void kvm_init_irq_routing(KVMState *s)
 975{
 976    int gsi_count, i;
 977
 978    gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
 979    if (gsi_count > 0) {
 980        unsigned int gsi_bits, i;
 981
 982        /* Round up so we can search ints using ffs */
 983        gsi_bits = ALIGN(gsi_count, 32);
 984        s->used_gsi_bitmap = g_malloc0(gsi_bits / 8);
 985        s->gsi_count = gsi_count;
 986
 987        /* Mark any over-allocated bits as already in use */
 988        for (i = gsi_count; i < gsi_bits; i++) {
 989            set_gsi(s, i);
 990        }
 991    }
 992
 993    s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
 994    s->nr_allocated_irq_routes = 0;
 995
 996    if (!s->direct_msi) {
 997        for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
 998            QTAILQ_INIT(&s->msi_hashtab[i]);
 999        }
1000    }
1001
1002    kvm_arch_init_irq_routing(s);
1003}
1004
1005void kvm_irqchip_commit_routes(KVMState *s)
1006{
1007    int ret;
1008
1009    s->irq_routes->flags = 0;
1010    ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
1011    assert(ret == 0);
1012}
1013
1014static void kvm_add_routing_entry(KVMState *s,
1015                                  struct kvm_irq_routing_entry *entry)
1016{
1017    struct kvm_irq_routing_entry *new;
1018    int n, size;
1019
1020    if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
1021        n = s->nr_allocated_irq_routes * 2;
1022        if (n < 64) {
1023            n = 64;
1024        }
1025        size = sizeof(struct kvm_irq_routing);
1026        size += n * sizeof(*new);
1027        s->irq_routes = g_realloc(s->irq_routes, size);
1028        s->nr_allocated_irq_routes = n;
1029    }
1030    n = s->irq_routes->nr++;
1031    new = &s->irq_routes->entries[n];
1032
1033    *new = *entry;
1034
1035    set_gsi(s, entry->gsi);
1036}
1037
1038static int kvm_update_routing_entry(KVMState *s,
1039                                    struct kvm_irq_routing_entry *new_entry)
1040{
1041    struct kvm_irq_routing_entry *entry;
1042    int n;
1043
1044    for (n = 0; n < s->irq_routes->nr; n++) {
1045        entry = &s->irq_routes->entries[n];
1046        if (entry->gsi != new_entry->gsi) {
1047            continue;
1048        }
1049
1050        if(!memcmp(entry, new_entry, sizeof *entry)) {
1051            return 0;
1052        }
1053
1054        *entry = *new_entry;
1055
1056        kvm_irqchip_commit_routes(s);
1057
1058        return 0;
1059    }
1060
1061    return -ESRCH;
1062}
1063
1064void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
1065{
1066    struct kvm_irq_routing_entry e = {};
1067
1068    assert(pin < s->gsi_count);
1069
1070    e.gsi = irq;
1071    e.type = KVM_IRQ_ROUTING_IRQCHIP;
1072    e.flags = 0;
1073    e.u.irqchip.irqchip = irqchip;
1074    e.u.irqchip.pin = pin;
1075    kvm_add_routing_entry(s, &e);
1076}
1077
1078void kvm_irqchip_release_virq(KVMState *s, int virq)
1079{
1080    struct kvm_irq_routing_entry *e;
1081    int i;
1082
1083    if (kvm_gsi_direct_mapping()) {
1084        return;
1085    }
1086
1087    for (i = 0; i < s->irq_routes->nr; i++) {
1088        e = &s->irq_routes->entries[i];
1089        if (e->gsi == virq) {
1090            s->irq_routes->nr--;
1091            *e = s->irq_routes->entries[s->irq_routes->nr];
1092        }
1093    }
1094    clear_gsi(s, virq);
1095}
1096
1097static unsigned int kvm_hash_msi(uint32_t data)
1098{
1099    /* This is optimized for IA32 MSI layout. However, no other arch shall
1100     * repeat the mistake of not providing a direct MSI injection API. */
1101    return data & 0xff;
1102}
1103
1104static void kvm_flush_dynamic_msi_routes(KVMState *s)
1105{
1106    KVMMSIRoute *route, *next;
1107    unsigned int hash;
1108
1109    for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
1110        QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
1111            kvm_irqchip_release_virq(s, route->kroute.gsi);
1112            QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
1113            g_free(route);
1114        }
1115    }
1116}
1117
1118static int kvm_irqchip_get_virq(KVMState *s)
1119{
1120    uint32_t *word = s->used_gsi_bitmap;
1121    int max_words = ALIGN(s->gsi_count, 32) / 32;
1122    int i, bit;
1123    bool retry = true;
1124
1125again:
1126    /* Return the lowest unused GSI in the bitmap */
1127    for (i = 0; i < max_words; i++) {
1128        bit = ffs(~word[i]);
1129        if (!bit) {
1130            continue;
1131        }
1132
1133        return bit - 1 + i * 32;
1134    }
1135    if (!s->direct_msi && retry) {
1136        retry = false;
1137        kvm_flush_dynamic_msi_routes(s);
1138        goto again;
1139    }
1140    return -ENOSPC;
1141
1142}
1143
1144static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
1145{
1146    unsigned int hash = kvm_hash_msi(msg.data);
1147    KVMMSIRoute *route;
1148
1149    QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
1150        if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
1151            route->kroute.u.msi.address_hi == (msg.address >> 32) &&
1152            route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
1153            return route;
1154        }
1155    }
1156    return NULL;
1157}
1158
1159int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1160{
1161    struct kvm_msi msi;
1162    KVMMSIRoute *route;
1163
1164    if (s->direct_msi) {
1165        msi.address_lo = (uint32_t)msg.address;
1166        msi.address_hi = msg.address >> 32;
1167        msi.data = le32_to_cpu(msg.data);
1168        msi.flags = 0;
1169        memset(msi.pad, 0, sizeof(msi.pad));
1170
1171        return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
1172    }
1173
1174    route = kvm_lookup_msi_route(s, msg);
1175    if (!route) {
1176        int virq;
1177
1178        virq = kvm_irqchip_get_virq(s);
1179        if (virq < 0) {
1180            return virq;
1181        }
1182
1183        route = g_malloc0(sizeof(KVMMSIRoute));
1184        route->kroute.gsi = virq;
1185        route->kroute.type = KVM_IRQ_ROUTING_MSI;
1186        route->kroute.flags = 0;
1187        route->kroute.u.msi.address_lo = (uint32_t)msg.address;
1188        route->kroute.u.msi.address_hi = msg.address >> 32;
1189        route->kroute.u.msi.data = le32_to_cpu(msg.data);
1190
1191        kvm_add_routing_entry(s, &route->kroute);
1192        kvm_irqchip_commit_routes(s);
1193
1194        QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
1195                           entry);
1196    }
1197
1198    assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
1199
1200    return kvm_set_irq(s, route->kroute.gsi, 1);
1201}
1202
1203int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1204{
1205    struct kvm_irq_routing_entry kroute = {};
1206    int virq;
1207
1208    if (kvm_gsi_direct_mapping()) {
1209        return msg.data & 0xffff;
1210    }
1211
1212    if (!kvm_gsi_routing_enabled()) {
1213        return -ENOSYS;
1214    }
1215
1216    virq = kvm_irqchip_get_virq(s);
1217    if (virq < 0) {
1218        return virq;
1219    }
1220
1221    kroute.gsi = virq;
1222    kroute.type = KVM_IRQ_ROUTING_MSI;
1223    kroute.flags = 0;
1224    kroute.u.msi.address_lo = (uint32_t)msg.address;
1225    kroute.u.msi.address_hi = msg.address >> 32;
1226    kroute.u.msi.data = le32_to_cpu(msg.data);
1227
1228    kvm_add_routing_entry(s, &kroute);
1229    kvm_irqchip_commit_routes(s);
1230
1231    return virq;
1232}
1233
1234int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1235{
1236    struct kvm_irq_routing_entry kroute = {};
1237
1238    if (kvm_gsi_direct_mapping()) {
1239        return 0;
1240    }
1241
1242    if (!kvm_irqchip_in_kernel()) {
1243        return -ENOSYS;
1244    }
1245
1246    kroute.gsi = virq;
1247    kroute.type = KVM_IRQ_ROUTING_MSI;
1248    kroute.flags = 0;
1249    kroute.u.msi.address_lo = (uint32_t)msg.address;
1250    kroute.u.msi.address_hi = msg.address >> 32;
1251    kroute.u.msi.data = le32_to_cpu(msg.data);
1252
1253    return kvm_update_routing_entry(s, &kroute);
1254}
1255
1256static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
1257                                    bool assign)
1258{
1259    struct kvm_irqfd irqfd = {
1260        .fd = fd,
1261        .gsi = virq,
1262        .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
1263    };
1264
1265    if (rfd != -1) {
1266        irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
1267        irqfd.resamplefd = rfd;
1268    }
1269
1270    if (!kvm_irqfds_enabled()) {
1271        return -ENOSYS;
1272    }
1273
1274    return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
1275}
1276
1277int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1278{
1279    struct kvm_irq_routing_entry kroute;
1280    int virq;
1281
1282    if (!kvm_gsi_routing_enabled()) {
1283        return -ENOSYS;
1284    }
1285
1286    virq = kvm_irqchip_get_virq(s);
1287    if (virq < 0) {
1288        return virq;
1289    }
1290
1291    kroute.gsi = virq;
1292    kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
1293    kroute.flags = 0;
1294    kroute.u.adapter.summary_addr = adapter->summary_addr;
1295    kroute.u.adapter.ind_addr = adapter->ind_addr;
1296    kroute.u.adapter.summary_offset = adapter->summary_offset;
1297    kroute.u.adapter.ind_offset = adapter->ind_offset;
1298    kroute.u.adapter.adapter_id = adapter->adapter_id;
1299
1300    kvm_add_routing_entry(s, &kroute);
1301    kvm_irqchip_commit_routes(s);
1302
1303    return virq;
1304}
1305
1306#else /* !KVM_CAP_IRQ_ROUTING */
1307
1308void kvm_init_irq_routing(KVMState *s)
1309{
1310}
1311
1312void kvm_irqchip_release_virq(KVMState *s, int virq)
1313{
1314}
1315
1316int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
1317{
1318    abort();
1319}
1320
1321int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)
1322{
1323    return -ENOSYS;
1324}
1325
1326int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
1327{
1328    return -ENOSYS;
1329}
1330
1331static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
1332{
1333    abort();
1334}
1335
1336int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
1337{
1338    return -ENOSYS;
1339}
1340#endif /* !KVM_CAP_IRQ_ROUTING */
1341
1342int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
1343                                   EventNotifier *rn, int virq)
1344{
1345    return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
1346           rn ? event_notifier_get_fd(rn) : -1, virq, true);
1347}
1348
1349int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n, int virq)
1350{
1351    return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
1352           false);
1353}
1354
1355static int kvm_irqchip_create(KVMState *s)
1356{
1357    int ret;
1358
1359    if (!qemu_opt_get_bool(qemu_get_machine_opts(), "kernel_irqchip", true) ||
1360        (!kvm_check_extension(s, KVM_CAP_IRQCHIP) &&
1361         (kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0) < 0))) {
1362        return 0;
1363    }
1364
1365    /* First probe and see if there's a arch-specific hook to create the
1366     * in-kernel irqchip for us */
1367    ret = kvm_arch_irqchip_create(s);
1368    if (ret < 0) {
1369        return ret;
1370    } else if (ret == 0) {
1371        ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
1372        if (ret < 0) {
1373            fprintf(stderr, "Create kernel irqchip failed\n");
1374            return ret;
1375        }
1376    }
1377
1378    kvm_kernel_irqchip = true;
1379    /* If we have an in-kernel IRQ chip then we must have asynchronous
1380     * interrupt delivery (though the reverse is not necessarily true)
1381     */
1382    kvm_async_interrupts_allowed = true;
1383    kvm_halt_in_kernel_allowed = true;
1384
1385    kvm_init_irq_routing(s);
1386
1387    return 0;
1388}
1389
1390/* Find number of supported CPUs using the recommended
1391 * procedure from the kernel API documentation to cope with
1392 * older kernels that may be missing capabilities.
1393 */
1394static int kvm_recommended_vcpus(KVMState *s)
1395{
1396    int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
1397    return (ret) ? ret : 4;
1398}
1399
1400static int kvm_max_vcpus(KVMState *s)
1401{
1402    int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
1403    return (ret) ? ret : kvm_recommended_vcpus(s);
1404}
1405
1406static int kvm_init(MachineState *ms)
1407{
1408    MachineClass *mc = MACHINE_GET_CLASS(ms);
1409    static const char upgrade_note[] =
1410        "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
1411        "(see http://sourceforge.net/projects/kvm).\n";
1412    struct {
1413        const char *name;
1414        int num;
1415    } num_cpus[] = {
1416        { "SMP",          smp_cpus },
1417        { "hotpluggable", max_cpus },
1418        { NULL, }
1419    }, *nc = num_cpus;
1420    int soft_vcpus_limit, hard_vcpus_limit;
1421    KVMState *s;
1422    const KVMCapabilityInfo *missing_cap;
1423    int ret;
1424    int i, type = 0;
1425    const char *kvm_type;
1426
1427    s = KVM_STATE(ms->accelerator);
1428
1429    /*
1430     * On systems where the kernel can support different base page
1431     * sizes, host page size may be different from TARGET_PAGE_SIZE,
1432     * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum
1433     * page size for the system though.
1434     */
1435    assert(TARGET_PAGE_SIZE <= getpagesize());
1436    page_size_init();
1437
1438    s->sigmask_len = 8;
1439
1440#ifdef KVM_CAP_SET_GUEST_DEBUG
1441    QTAILQ_INIT(&s->kvm_sw_breakpoints);
1442#endif
1443    s->vmfd = -1;
1444    s->fd = qemu_open("/dev/kvm", O_RDWR);
1445    if (s->fd == -1) {
1446        fprintf(stderr, "Could not access KVM kernel module: %m\n");
1447        ret = -errno;
1448        goto err;
1449    }
1450
1451    ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
1452    if (ret < KVM_API_VERSION) {
1453        if (ret >= 0) {
1454            ret = -EINVAL;
1455        }
1456        fprintf(stderr, "kvm version too old\n");
1457        goto err;
1458    }
1459
1460    if (ret > KVM_API_VERSION) {
1461        ret = -EINVAL;
1462        fprintf(stderr, "kvm version not supported\n");
1463        goto err;
1464    }
1465
1466    s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
1467
1468    /* If unspecified, use the default value */
1469    if (!s->nr_slots) {
1470        s->nr_slots = 32;
1471    }
1472
1473    s->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
1474
1475    for (i = 0; i < s->nr_slots; i++) {
1476        s->slots[i].slot = i;
1477    }
1478
1479    /* check the vcpu limits */
1480    soft_vcpus_limit = kvm_recommended_vcpus(s);
1481    hard_vcpus_limit = kvm_max_vcpus(s);
1482
1483    while (nc->name) {
1484        if (nc->num > soft_vcpus_limit) {
1485            fprintf(stderr,
1486                    "Warning: Number of %s cpus requested (%d) exceeds "
1487                    "the recommended cpus supported by KVM (%d)\n",
1488                    nc->name, nc->num, soft_vcpus_limit);
1489
1490            if (nc->num > hard_vcpus_limit) {
1491                fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
1492                        "the maximum cpus supported by KVM (%d)\n",
1493                        nc->name, nc->num, hard_vcpus_limit);
1494                exit(1);
1495            }
1496        }
1497        nc++;
1498    }
1499
1500    kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
1501    if (mc->kvm_type) {
1502        type = mc->kvm_type(kvm_type);
1503    } else if (kvm_type) {
1504        ret = -EINVAL;
1505        fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
1506        goto err;
1507    }
1508
1509    do {
1510        ret = kvm_ioctl(s, KVM_CREATE_VM, type);
1511    } while (ret == -EINTR);
1512
1513    if (ret < 0) {
1514        fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
1515                strerror(-ret));
1516
1517#ifdef TARGET_S390X
1518        fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "
1519                        "your host kernel command line\n");
1520#endif
1521        goto err;
1522    }
1523
1524    s->vmfd = ret;
1525    missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
1526    if (!missing_cap) {
1527        missing_cap =
1528            kvm_check_extension_list(s, kvm_arch_required_capabilities);
1529    }
1530    if (missing_cap) {
1531        ret = -EINVAL;
1532        fprintf(stderr, "kvm does not support %s\n%s",
1533                missing_cap->name, upgrade_note);
1534        goto err;
1535    }
1536
1537    s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
1538
1539    s->broken_set_mem_region = 1;
1540    ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
1541    if (ret > 0) {
1542        s->broken_set_mem_region = 0;
1543    }
1544
1545#ifdef KVM_CAP_VCPU_EVENTS
1546    s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
1547#endif
1548
1549    s->robust_singlestep =
1550        kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
1551
1552#ifdef KVM_CAP_DEBUGREGS
1553    s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
1554#endif
1555
1556#ifdef KVM_CAP_XSAVE
1557    s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1558#endif
1559
1560#ifdef KVM_CAP_XCRS
1561    s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1562#endif
1563
1564#ifdef KVM_CAP_PIT_STATE2
1565    s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1566#endif
1567
1568#ifdef KVM_CAP_IRQ_ROUTING
1569    s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
1570#endif
1571
1572    s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
1573
1574    s->irq_set_ioctl = KVM_IRQ_LINE;
1575    if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
1576        s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
1577    }
1578
1579#ifdef KVM_CAP_READONLY_MEM
1580    kvm_readonly_mem_allowed =
1581        (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
1582#endif
1583
1584    kvm_eventfds_allowed =
1585        (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
1586
1587    ret = kvm_arch_init(s);
1588    if (ret < 0) {
1589        goto err;
1590    }
1591
1592    ret = kvm_irqchip_create(s);
1593    if (ret < 0) {
1594        goto err;
1595    }
1596
1597    kvm_state = s;
1598    memory_listener_register(&kvm_memory_listener, &address_space_memory);
1599    memory_listener_register(&kvm_io_listener, &address_space_io);
1600
1601    s->many_ioeventfds = kvm_check_many_ioeventfds();
1602
1603    cpu_interrupt_handler = kvm_handle_interrupt;
1604
1605    return 0;
1606
1607err:
1608    assert(ret < 0);
1609    if (s->vmfd >= 0) {
1610        close(s->vmfd);
1611    }
1612    if (s->fd != -1) {
1613        close(s->fd);
1614    }
1615    g_free(s->slots);
1616
1617    return ret;
1618}
1619
1620void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
1621{
1622    s->sigmask_len = sigmask_len;
1623}
1624
1625static void kvm_handle_io(uint16_t port, void *data, int direction, int size,
1626                          uint32_t count)
1627{
1628    int i;
1629    uint8_t *ptr = data;
1630
1631    for (i = 0; i < count; i++) {
1632        address_space_rw(&address_space_io, port, ptr, size,
1633                         direction == KVM_EXIT_IO_OUT);
1634        ptr += size;
1635    }
1636}
1637
1638static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
1639{
1640    fprintf(stderr, "KVM internal error. Suberror: %d\n",
1641            run->internal.suberror);
1642
1643    if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
1644        int i;
1645
1646        for (i = 0; i < run->internal.ndata; ++i) {
1647            fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
1648                    i, (uint64_t)run->internal.data[i]);
1649        }
1650    }
1651    if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
1652        fprintf(stderr, "emulation failure\n");
1653        if (!kvm_arch_stop_on_emulation_error(cpu)) {
1654            cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1655            return EXCP_INTERRUPT;
1656        }
1657    }
1658    /* FIXME: Should trigger a qmp message to let management know
1659     * something went wrong.
1660     */
1661    return -1;
1662}
1663
1664void kvm_flush_coalesced_mmio_buffer(void)
1665{
1666    KVMState *s = kvm_state;
1667
1668    if (s->coalesced_flush_in_progress) {
1669        return;
1670    }
1671
1672    s->coalesced_flush_in_progress = true;
1673
1674    if (s->coalesced_mmio_ring) {
1675        struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
1676        while (ring->first != ring->last) {
1677            struct kvm_coalesced_mmio *ent;
1678
1679            ent = &ring->coalesced_mmio[ring->first];
1680
1681            cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
1682            smp_wmb();
1683            ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
1684        }
1685    }
1686
1687    s->coalesced_flush_in_progress = false;
1688}
1689
1690static void do_kvm_cpu_synchronize_state(void *arg)
1691{
1692    CPUState *cpu = arg;
1693
1694    if (!cpu->kvm_vcpu_dirty) {
1695        kvm_arch_get_registers(cpu);
1696        cpu->kvm_vcpu_dirty = true;
1697    }
1698}
1699
1700void kvm_cpu_synchronize_state(CPUState *cpu)
1701{
1702    if (!cpu->kvm_vcpu_dirty) {
1703        run_on_cpu(cpu, do_kvm_cpu_synchronize_state, cpu);
1704    }
1705}
1706
1707static void do_kvm_cpu_synchronize_post_reset(void *arg)
1708{
1709    CPUState *cpu = arg;
1710
1711    kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
1712    cpu->kvm_vcpu_dirty = false;
1713}
1714
1715void kvm_cpu_synchronize_post_reset(CPUState *cpu)
1716{
1717    run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, cpu);
1718}
1719
1720static void do_kvm_cpu_synchronize_post_init(void *arg)
1721{
1722    CPUState *cpu = arg;
1723
1724    kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
1725    cpu->kvm_vcpu_dirty = false;
1726}
1727
1728void kvm_cpu_synchronize_post_init(CPUState *cpu)
1729{
1730    run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, cpu);
1731}
1732
1733void kvm_cpu_clean_state(CPUState *cpu)
1734{
1735    cpu->kvm_vcpu_dirty = false;
1736}
1737
1738int kvm_cpu_exec(CPUState *cpu)
1739{
1740    struct kvm_run *run = cpu->kvm_run;
1741    int ret, run_ret;
1742
1743    DPRINTF("kvm_cpu_exec()\n");
1744
1745    if (kvm_arch_process_async_events(cpu)) {
1746        cpu->exit_request = 0;
1747        return EXCP_HLT;
1748    }
1749
1750    do {
1751        if (cpu->kvm_vcpu_dirty) {
1752            kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
1753            cpu->kvm_vcpu_dirty = false;
1754        }
1755
1756        kvm_arch_pre_run(cpu, run);
1757        if (cpu->exit_request) {
1758            DPRINTF("interrupt exit requested\n");
1759            /*
1760             * KVM requires us to reenter the kernel after IO exits to complete
1761             * instruction emulation. This self-signal will ensure that we
1762             * leave ASAP again.
1763             */
1764            qemu_cpu_kick_self();
1765        }
1766        qemu_mutex_unlock_iothread();
1767
1768        run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
1769
1770        qemu_mutex_lock_iothread();
1771        kvm_arch_post_run(cpu, run);
1772
1773        if (run_ret < 0) {
1774            if (run_ret == -EINTR || run_ret == -EAGAIN) {
1775                DPRINTF("io window exit\n");
1776                ret = EXCP_INTERRUPT;
1777                break;
1778            }
1779            fprintf(stderr, "error: kvm run failed %s\n",
1780                    strerror(-run_ret));
1781            ret = -1;
1782            break;
1783        }
1784
1785        trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
1786        switch (run->exit_reason) {
1787        case KVM_EXIT_IO:
1788            DPRINTF("handle_io\n");
1789            kvm_handle_io(run->io.port,
1790                          (uint8_t *)run + run->io.data_offset,
1791                          run->io.direction,
1792                          run->io.size,
1793                          run->io.count);
1794            ret = 0;
1795            break;
1796        case KVM_EXIT_MMIO:
1797            DPRINTF("handle_mmio\n");
1798            cpu_physical_memory_rw(run->mmio.phys_addr,
1799                                   run->mmio.data,
1800                                   run->mmio.len,
1801                                   run->mmio.is_write);
1802            ret = 0;
1803            break;
1804        case KVM_EXIT_IRQ_WINDOW_OPEN:
1805            DPRINTF("irq_window_open\n");
1806            ret = EXCP_INTERRUPT;
1807            break;
1808        case KVM_EXIT_SHUTDOWN:
1809            DPRINTF("shutdown\n");
1810            qemu_system_reset_request();
1811            ret = EXCP_INTERRUPT;
1812            break;
1813        case KVM_EXIT_UNKNOWN:
1814            fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
1815                    (uint64_t)run->hw.hardware_exit_reason);
1816            ret = -1;
1817            break;
1818        case KVM_EXIT_INTERNAL_ERROR:
1819            ret = kvm_handle_internal_error(cpu, run);
1820            break;
1821        case KVM_EXIT_SYSTEM_EVENT:
1822            switch (run->system_event.type) {
1823            case KVM_SYSTEM_EVENT_SHUTDOWN:
1824                qemu_system_shutdown_request();
1825                ret = EXCP_INTERRUPT;
1826                break;
1827            case KVM_SYSTEM_EVENT_RESET:
1828                qemu_system_reset_request();
1829                ret = EXCP_INTERRUPT;
1830                break;
1831            default:
1832                DPRINTF("kvm_arch_handle_exit\n");
1833                ret = kvm_arch_handle_exit(cpu, run);
1834                break;
1835            }
1836            break;
1837        default:
1838            DPRINTF("kvm_arch_handle_exit\n");
1839            ret = kvm_arch_handle_exit(cpu, run);
1840            break;
1841        }
1842    } while (ret == 0);
1843
1844    if (ret < 0) {
1845        cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
1846        vm_stop(RUN_STATE_INTERNAL_ERROR);
1847    }
1848
1849    cpu->exit_request = 0;
1850    return ret;
1851}
1852
1853int kvm_ioctl(KVMState *s, int type, ...)
1854{
1855    int ret;
1856    void *arg;
1857    va_list ap;
1858
1859    va_start(ap, type);
1860    arg = va_arg(ap, void *);
1861    va_end(ap);
1862
1863    trace_kvm_ioctl(type, arg);
1864    ret = ioctl(s->fd, type, arg);
1865    if (ret == -1) {
1866        ret = -errno;
1867    }
1868    return ret;
1869}
1870
1871int kvm_vm_ioctl(KVMState *s, int type, ...)
1872{
1873    int ret;
1874    void *arg;
1875    va_list ap;
1876
1877    va_start(ap, type);
1878    arg = va_arg(ap, void *);
1879    va_end(ap);
1880
1881    trace_kvm_vm_ioctl(type, arg);
1882    ret = ioctl(s->vmfd, type, arg);
1883    if (ret == -1) {
1884        ret = -errno;
1885    }
1886    return ret;
1887}
1888
1889int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
1890{
1891    int ret;
1892    void *arg;
1893    va_list ap;
1894
1895    va_start(ap, type);
1896    arg = va_arg(ap, void *);
1897    va_end(ap);
1898
1899    trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
1900    ret = ioctl(cpu->kvm_fd, type, arg);
1901    if (ret == -1) {
1902        ret = -errno;
1903    }
1904    return ret;
1905}
1906
1907int kvm_device_ioctl(int fd, int type, ...)
1908{
1909    int ret;
1910    void *arg;
1911    va_list ap;
1912
1913    va_start(ap, type);
1914    arg = va_arg(ap, void *);
1915    va_end(ap);
1916
1917    trace_kvm_device_ioctl(fd, type, arg);
1918    ret = ioctl(fd, type, arg);
1919    if (ret == -1) {
1920        ret = -errno;
1921    }
1922    return ret;
1923}
1924
1925int kvm_has_sync_mmu(void)
1926{
1927    return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
1928}
1929
1930int kvm_has_vcpu_events(void)
1931{
1932    return kvm_state->vcpu_events;
1933}
1934
1935int kvm_has_robust_singlestep(void)
1936{
1937    return kvm_state->robust_singlestep;
1938}
1939
1940int kvm_has_debugregs(void)
1941{
1942    return kvm_state->debugregs;
1943}
1944
1945int kvm_has_xsave(void)
1946{
1947    return kvm_state->xsave;
1948}
1949
1950int kvm_has_xcrs(void)
1951{
1952    return kvm_state->xcrs;
1953}
1954
1955int kvm_has_pit_state2(void)
1956{
1957    return kvm_state->pit_state2;
1958}
1959
1960int kvm_has_many_ioeventfds(void)
1961{
1962    if (!kvm_enabled()) {
1963        return 0;
1964    }
1965    return kvm_state->many_ioeventfds;
1966}
1967
1968int kvm_has_gsi_routing(void)
1969{
1970#ifdef KVM_CAP_IRQ_ROUTING
1971    return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
1972#else
1973    return false;
1974#endif
1975}
1976
1977int kvm_has_intx_set_mask(void)
1978{
1979    return kvm_state->intx_set_mask;
1980}
1981
1982void kvm_setup_guest_memory(void *start, size_t size)
1983{
1984    if (!kvm_has_sync_mmu()) {
1985        int ret = qemu_madvise(start, size, QEMU_MADV_DONTFORK);
1986
1987        if (ret) {
1988            perror("qemu_madvise");
1989            fprintf(stderr,
1990                    "Need MADV_DONTFORK in absence of synchronous KVM MMU\n");
1991            exit(1);
1992        }
1993    }
1994}
1995
1996#ifdef KVM_CAP_SET_GUEST_DEBUG
1997struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
1998                                                 target_ulong pc)
1999{
2000    struct kvm_sw_breakpoint *bp;
2001
2002    QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
2003        if (bp->pc == pc) {
2004            return bp;
2005        }
2006    }
2007    return NULL;
2008}
2009
2010int kvm_sw_breakpoints_active(CPUState *cpu)
2011{
2012    return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
2013}
2014
2015struct kvm_set_guest_debug_data {
2016    struct kvm_guest_debug dbg;
2017    CPUState *cpu;
2018    int err;
2019};
2020
2021static void kvm_invoke_set_guest_debug(void *data)
2022{
2023    struct kvm_set_guest_debug_data *dbg_data = data;
2024
2025    dbg_data->err = kvm_vcpu_ioctl(dbg_data->cpu, KVM_SET_GUEST_DEBUG,
2026                                   &dbg_data->dbg);
2027}
2028
2029int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2030{
2031    struct kvm_set_guest_debug_data data;
2032
2033    data.dbg.control = reinject_trap;
2034
2035    if (cpu->singlestep_enabled) {
2036        data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
2037    }
2038    kvm_arch_update_guest_debug(cpu, &data.dbg);
2039    data.cpu = cpu;
2040
2041    run_on_cpu(cpu, kvm_invoke_set_guest_debug, &data);
2042    return data.err;
2043}
2044
2045int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2046                          target_ulong len, int type)
2047{
2048    struct kvm_sw_breakpoint *bp;
2049    int err;
2050
2051    if (type == GDB_BREAKPOINT_SW) {
2052        bp = kvm_find_sw_breakpoint(cpu, addr);
2053        if (bp) {
2054            bp->use_count++;
2055            return 0;
2056        }
2057
2058        bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
2059        if (!bp) {
2060            return -ENOMEM;
2061        }
2062
2063        bp->pc = addr;
2064        bp->use_count = 1;
2065        err = kvm_arch_insert_sw_breakpoint(cpu, bp);
2066        if (err) {
2067            g_free(bp);
2068            return err;
2069        }
2070
2071        QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2072    } else {
2073        err = kvm_arch_insert_hw_breakpoint(addr, len, type);
2074        if (err) {
2075            return err;
2076        }
2077    }
2078
2079    CPU_FOREACH(cpu) {
2080        err = kvm_update_guest_debug(cpu, 0);
2081        if (err) {
2082            return err;
2083        }
2084    }
2085    return 0;
2086}
2087
2088int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2089                          target_ulong len, int type)
2090{
2091    struct kvm_sw_breakpoint *bp;
2092    int err;
2093
2094    if (type == GDB_BREAKPOINT_SW) {
2095        bp = kvm_find_sw_breakpoint(cpu, addr);
2096        if (!bp) {
2097            return -ENOENT;
2098        }
2099
2100        if (bp->use_count > 1) {
2101            bp->use_count--;
2102            return 0;
2103        }
2104
2105        err = kvm_arch_remove_sw_breakpoint(cpu, bp);
2106        if (err) {
2107            return err;
2108        }
2109
2110        QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
2111        g_free(bp);
2112    } else {
2113        err = kvm_arch_remove_hw_breakpoint(addr, len, type);
2114        if (err) {
2115            return err;
2116        }
2117    }
2118
2119    CPU_FOREACH(cpu) {
2120        err = kvm_update_guest_debug(cpu, 0);
2121        if (err) {
2122            return err;
2123        }
2124    }
2125    return 0;
2126}
2127
2128void kvm_remove_all_breakpoints(CPUState *cpu)
2129{
2130    struct kvm_sw_breakpoint *bp, *next;
2131    KVMState *s = cpu->kvm_state;
2132    CPUState *tmpcpu;
2133
2134    QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
2135        if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
2136            /* Try harder to find a CPU that currently sees the breakpoint. */
2137            CPU_FOREACH(tmpcpu) {
2138                if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
2139                    break;
2140                }
2141            }
2142        }
2143        QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
2144        g_free(bp);
2145    }
2146    kvm_arch_remove_all_hw_breakpoints();
2147
2148    CPU_FOREACH(cpu) {
2149        kvm_update_guest_debug(cpu, 0);
2150    }
2151}
2152
2153#else /* !KVM_CAP_SET_GUEST_DEBUG */
2154
2155int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
2156{
2157    return -EINVAL;
2158}
2159
2160int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
2161                          target_ulong len, int type)
2162{
2163    return -EINVAL;
2164}
2165
2166int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
2167                          target_ulong len, int type)
2168{
2169    return -EINVAL;
2170}
2171
2172void kvm_remove_all_breakpoints(CPUState *cpu)
2173{
2174}
2175#endif /* !KVM_CAP_SET_GUEST_DEBUG */
2176
2177int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
2178{
2179    KVMState *s = kvm_state;
2180    struct kvm_signal_mask *sigmask;
2181    int r;
2182
2183    if (!sigset) {
2184        return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
2185    }
2186
2187    sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
2188
2189    sigmask->len = s->sigmask_len;
2190    memcpy(sigmask->sigset, sigset, sizeof(*sigset));
2191    r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
2192    g_free(sigmask);
2193
2194    return r;
2195}
2196int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
2197{
2198    return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
2199}
2200
2201int kvm_on_sigbus(int code, void *addr)
2202{
2203    return kvm_arch_on_sigbus(code, addr);
2204}
2205
2206int kvm_create_device(KVMState *s, uint64_t type, bool test)
2207{
2208    int ret;
2209    struct kvm_create_device create_dev;
2210
2211    create_dev.type = type;
2212    create_dev.fd = -1;
2213    create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2214
2215    if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
2216        return -ENOTSUP;
2217    }
2218
2219    ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
2220    if (ret) {
2221        return ret;
2222    }
2223
2224    return test ? 0 : create_dev.fd;
2225}
2226
2227int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
2228{
2229    struct kvm_one_reg reg;
2230    int r;
2231
2232    reg.id = id;
2233    reg.addr = (uintptr_t) source;
2234    r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
2235    if (r) {
2236        trace_kvm_failed_reg_set(id, strerror(r));
2237    }
2238    return r;
2239}
2240
2241int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
2242{
2243    struct kvm_one_reg reg;
2244    int r;
2245
2246    reg.id = id;
2247    reg.addr = (uintptr_t) target;
2248    r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
2249    if (r) {
2250        trace_kvm_failed_reg_get(id, strerror(r));
2251    }
2252    return r;
2253}
2254
2255static void kvm_accel_class_init(ObjectClass *oc, void *data)
2256{
2257    AccelClass *ac = ACCEL_CLASS(oc);
2258    ac->name = "KVM";
2259    ac->init_machine = kvm_init;
2260    ac->allowed = &kvm_allowed;
2261}
2262
2263static const TypeInfo kvm_accel_type = {
2264    .name = TYPE_KVM_ACCEL,
2265    .parent = TYPE_ACCEL,
2266    .class_init = kvm_accel_class_init,
2267    .instance_size = sizeof(KVMState),
2268};
2269
2270static void kvm_type_init(void)
2271{
2272    type_register_static(&kvm_accel_type);
2273}
2274
2275type_init(kvm_type_init);
2276