qemu/hw/vfio/common.c
<<
>>
Prefs
   1/*
   2 * generic functions used by VFIO devices
   3 *
   4 * Copyright Red Hat, Inc. 2012
   5 *
   6 * Authors:
   7 *  Alex Williamson <alex.williamson@redhat.com>
   8 *
   9 * This work is licensed under the terms of the GNU GPL, version 2.  See
  10 * the COPYING file in the top-level directory.
  11 *
  12 * Based on qemu-kvm device-assignment:
  13 *  Adapted for KVM by Qumranet.
  14 *  Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
  15 *  Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
  16 *  Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
  17 *  Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
  18 *  Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
  19 */
  20
  21#include "qemu/osdep.h"
  22#include <sys/ioctl.h>
  23#ifdef CONFIG_KVM
  24#include <linux/kvm.h>
  25#endif
  26#include <linux/vfio.h>
  27
  28#include "hw/vfio/vfio-common.h"
  29#include "hw/vfio/vfio.h"
  30#include "exec/address-spaces.h"
  31#include "exec/memory.h"
  32#include "hw/hw.h"
  33#include "qemu/error-report.h"
  34#include "qemu/range.h"
  35#include "sysemu/kvm.h"
  36#include "trace.h"
  37#include "qapi/error.h"
  38
  39struct vfio_group_head vfio_group_list =
  40    QLIST_HEAD_INITIALIZER(vfio_group_list);
  41struct vfio_as_head vfio_address_spaces =
  42    QLIST_HEAD_INITIALIZER(vfio_address_spaces);
  43
  44#ifdef CONFIG_KVM
  45/*
  46 * We have a single VFIO pseudo device per KVM VM.  Once created it lives
  47 * for the life of the VM.  Closing the file descriptor only drops our
  48 * reference to it and the device's reference to kvm.  Therefore once
  49 * initialized, this file descriptor is only released on QEMU exit and
  50 * we'll re-use it should another vfio device be attached before then.
  51 */
  52static int vfio_kvm_device_fd = -1;
  53#endif
  54
  55/*
  56 * Common VFIO interrupt disable
  57 */
  58void vfio_disable_irqindex(VFIODevice *vbasedev, int index)
  59{
  60    struct vfio_irq_set irq_set = {
  61        .argsz = sizeof(irq_set),
  62        .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
  63        .index = index,
  64        .start = 0,
  65        .count = 0,
  66    };
  67
  68    ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  69}
  70
  71void vfio_unmask_single_irqindex(VFIODevice *vbasedev, int index)
  72{
  73    struct vfio_irq_set irq_set = {
  74        .argsz = sizeof(irq_set),
  75        .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
  76        .index = index,
  77        .start = 0,
  78        .count = 1,
  79    };
  80
  81    ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  82}
  83
  84void vfio_mask_single_irqindex(VFIODevice *vbasedev, int index)
  85{
  86    struct vfio_irq_set irq_set = {
  87        .argsz = sizeof(irq_set),
  88        .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
  89        .index = index,
  90        .start = 0,
  91        .count = 1,
  92    };
  93
  94    ioctl(vbasedev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
  95}
  96
  97/*
  98 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
  99 */
 100void vfio_region_write(void *opaque, hwaddr addr,
 101                       uint64_t data, unsigned size)
 102{
 103    VFIORegion *region = opaque;
 104    VFIODevice *vbasedev = region->vbasedev;
 105    union {
 106        uint8_t byte;
 107        uint16_t word;
 108        uint32_t dword;
 109        uint64_t qword;
 110    } buf;
 111
 112    switch (size) {
 113    case 1:
 114        buf.byte = data;
 115        break;
 116    case 2:
 117        buf.word = cpu_to_le16(data);
 118        break;
 119    case 4:
 120        buf.dword = cpu_to_le32(data);
 121        break;
 122    case 8:
 123        buf.qword = cpu_to_le64(data);
 124        break;
 125    default:
 126        hw_error("vfio: unsupported write size, %d bytes", size);
 127        break;
 128    }
 129
 130    if (pwrite(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
 131        error_report("%s(%s:region%d+0x%"HWADDR_PRIx", 0x%"PRIx64
 132                     ",%d) failed: %m",
 133                     __func__, vbasedev->name, region->nr,
 134                     addr, data, size);
 135    }
 136
 137    trace_vfio_region_write(vbasedev->name, region->nr, addr, data, size);
 138
 139    /*
 140     * A read or write to a BAR always signals an INTx EOI.  This will
 141     * do nothing if not pending (including not in INTx mode).  We assume
 142     * that a BAR access is in response to an interrupt and that BAR
 143     * accesses will service the interrupt.  Unfortunately, we don't know
 144     * which access will service the interrupt, so we're potentially
 145     * getting quite a few host interrupts per guest interrupt.
 146     */
 147    vbasedev->ops->vfio_eoi(vbasedev);
 148}
 149
 150uint64_t vfio_region_read(void *opaque,
 151                          hwaddr addr, unsigned size)
 152{
 153    VFIORegion *region = opaque;
 154    VFIODevice *vbasedev = region->vbasedev;
 155    union {
 156        uint8_t byte;
 157        uint16_t word;
 158        uint32_t dword;
 159        uint64_t qword;
 160    } buf;
 161    uint64_t data = 0;
 162
 163    if (pread(vbasedev->fd, &buf, size, region->fd_offset + addr) != size) {
 164        error_report("%s(%s:region%d+0x%"HWADDR_PRIx", %d) failed: %m",
 165                     __func__, vbasedev->name, region->nr,
 166                     addr, size);
 167        return (uint64_t)-1;
 168    }
 169    switch (size) {
 170    case 1:
 171        data = buf.byte;
 172        break;
 173    case 2:
 174        data = le16_to_cpu(buf.word);
 175        break;
 176    case 4:
 177        data = le32_to_cpu(buf.dword);
 178        break;
 179    case 8:
 180        data = le64_to_cpu(buf.qword);
 181        break;
 182    default:
 183        hw_error("vfio: unsupported read size, %d bytes", size);
 184        break;
 185    }
 186
 187    trace_vfio_region_read(vbasedev->name, region->nr, addr, size, data);
 188
 189    /* Same as write above */
 190    vbasedev->ops->vfio_eoi(vbasedev);
 191
 192    return data;
 193}
 194
 195const MemoryRegionOps vfio_region_ops = {
 196    .read = vfio_region_read,
 197    .write = vfio_region_write,
 198    .endianness = DEVICE_LITTLE_ENDIAN,
 199    .valid = {
 200        .min_access_size = 1,
 201        .max_access_size = 8,
 202    },
 203    .impl = {
 204        .min_access_size = 1,
 205        .max_access_size = 8,
 206    },
 207};
 208
 209/*
 210 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
 211 */
 212static int vfio_dma_unmap(VFIOContainer *container,
 213                          hwaddr iova, ram_addr_t size)
 214{
 215    struct vfio_iommu_type1_dma_unmap unmap = {
 216        .argsz = sizeof(unmap),
 217        .flags = 0,
 218        .iova = iova,
 219        .size = size,
 220    };
 221
 222    if (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
 223        error_report("VFIO_UNMAP_DMA: %d", -errno);
 224        return -errno;
 225    }
 226
 227    return 0;
 228}
 229
 230static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
 231                        ram_addr_t size, void *vaddr, bool readonly)
 232{
 233    struct vfio_iommu_type1_dma_map map = {
 234        .argsz = sizeof(map),
 235        .flags = VFIO_DMA_MAP_FLAG_READ,
 236        .vaddr = (__u64)(uintptr_t)vaddr,
 237        .iova = iova,
 238        .size = size,
 239    };
 240
 241    if (!readonly) {
 242        map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
 243    }
 244
 245    /*
 246     * Try the mapping, if it fails with EBUSY, unmap the region and try
 247     * again.  This shouldn't be necessary, but we sometimes see it in
 248     * the VGA ROM space.
 249     */
 250    if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
 251        (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
 252         ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
 253        return 0;
 254    }
 255
 256    error_report("VFIO_MAP_DMA: %d", -errno);
 257    return -errno;
 258}
 259
 260static void vfio_host_win_add(VFIOContainer *container,
 261                              hwaddr min_iova, hwaddr max_iova,
 262                              uint64_t iova_pgsizes)
 263{
 264    VFIOHostDMAWindow *hostwin;
 265
 266    QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
 267        if (ranges_overlap(hostwin->min_iova,
 268                           hostwin->max_iova - hostwin->min_iova + 1,
 269                           min_iova,
 270                           max_iova - min_iova + 1)) {
 271            hw_error("%s: Overlapped IOMMU are not enabled", __func__);
 272        }
 273    }
 274
 275    hostwin = g_malloc0(sizeof(*hostwin));
 276
 277    hostwin->min_iova = min_iova;
 278    hostwin->max_iova = max_iova;
 279    hostwin->iova_pgsizes = iova_pgsizes;
 280    QLIST_INSERT_HEAD(&container->hostwin_list, hostwin, hostwin_next);
 281}
 282
 283static int vfio_host_win_del(VFIOContainer *container, hwaddr min_iova,
 284                             hwaddr max_iova)
 285{
 286    VFIOHostDMAWindow *hostwin;
 287
 288    QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
 289        if (hostwin->min_iova == min_iova && hostwin->max_iova == max_iova) {
 290            QLIST_REMOVE(hostwin, hostwin_next);
 291            return 0;
 292        }
 293    }
 294
 295    return -1;
 296}
 297
 298static bool vfio_listener_skipped_section(MemoryRegionSection *section)
 299{
 300    return (!memory_region_is_ram(section->mr) &&
 301            !memory_region_is_iommu(section->mr)) ||
 302           /*
 303            * Sizing an enabled 64-bit BAR can cause spurious mappings to
 304            * addresses in the upper part of the 64-bit address space.  These
 305            * are never accessed by the CPU and beyond the address width of
 306            * some IOMMU hardware.  TODO: VFIO should tell us the IOMMU width.
 307            */
 308           section->offset_within_address_space & (1ULL << 63);
 309}
 310
 311/* Called with rcu_read_lock held.  */
 312static bool vfio_get_vaddr(IOMMUTLBEntry *iotlb, void **vaddr,
 313                           bool *read_only)
 314{
 315    MemoryRegion *mr;
 316    hwaddr xlat;
 317    hwaddr len = iotlb->addr_mask + 1;
 318    bool writable = iotlb->perm & IOMMU_WO;
 319
 320    /*
 321     * The IOMMU TLB entry we have just covers translation through
 322     * this IOMMU to its immediate target.  We need to translate
 323     * it the rest of the way through to memory.
 324     */
 325    mr = address_space_translate(&address_space_memory,
 326                                 iotlb->translated_addr,
 327                                 &xlat, &len, writable);
 328    if (!memory_region_is_ram(mr)) {
 329        error_report("iommu map to non memory area %"HWADDR_PRIx"",
 330                     xlat);
 331        return false;
 332    }
 333
 334    /*
 335     * Translation truncates length to the IOMMU page size,
 336     * check that it did not truncate too much.
 337     */
 338    if (len & iotlb->addr_mask) {
 339        error_report("iommu has granularity incompatible with target AS");
 340        return false;
 341    }
 342
 343    *vaddr = memory_region_get_ram_ptr(mr) + xlat;
 344    *read_only = !writable || mr->readonly;
 345
 346    return true;
 347}
 348
 349static void vfio_iommu_map_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
 350{
 351    VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);
 352    VFIOContainer *container = giommu->container;
 353    hwaddr iova = iotlb->iova + giommu->iommu_offset;
 354    bool read_only;
 355    void *vaddr;
 356    int ret;
 357
 358    trace_vfio_iommu_map_notify(iotlb->perm == IOMMU_NONE ? "UNMAP" : "MAP",
 359                                iova, iova + iotlb->addr_mask);
 360
 361    if (iotlb->target_as != &address_space_memory) {
 362        error_report("Wrong target AS \"%s\", only system memory is allowed",
 363                     iotlb->target_as->name ? iotlb->target_as->name : "none");
 364        return;
 365    }
 366
 367    rcu_read_lock();
 368
 369    if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {
 370        if (!vfio_get_vaddr(iotlb, &vaddr, &read_only)) {
 371            goto out;
 372        }
 373        /*
 374         * vaddr is only valid until rcu_read_unlock(). But after
 375         * vfio_dma_map has set up the mapping the pages will be
 376         * pinned by the kernel. This makes sure that the RAM backend
 377         * of vaddr will always be there, even if the memory object is
 378         * destroyed and its backing memory munmap-ed.
 379         */
 380        ret = vfio_dma_map(container, iova,
 381                           iotlb->addr_mask + 1, vaddr,
 382                           read_only);
 383        if (ret) {
 384            error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
 385                         "0x%"HWADDR_PRIx", %p) = %d (%m)",
 386                         container, iova,
 387                         iotlb->addr_mask + 1, vaddr, ret);
 388        }
 389    } else {
 390        ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1);
 391        if (ret) {
 392            error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
 393                         "0x%"HWADDR_PRIx") = %d (%m)",
 394                         container, iova,
 395                         iotlb->addr_mask + 1, ret);
 396        }
 397    }
 398out:
 399    rcu_read_unlock();
 400}
 401
 402static void vfio_listener_region_add(MemoryListener *listener,
 403                                     MemoryRegionSection *section)
 404{
 405    VFIOContainer *container = container_of(listener, VFIOContainer, listener);
 406    hwaddr iova, end;
 407    Int128 llend, llsize;
 408    void *vaddr;
 409    int ret;
 410    VFIOHostDMAWindow *hostwin;
 411    bool hostwin_found;
 412
 413    if (vfio_listener_skipped_section(section)) {
 414        trace_vfio_listener_region_add_skip(
 415                section->offset_within_address_space,
 416                section->offset_within_address_space +
 417                int128_get64(int128_sub(section->size, int128_one())));
 418        return;
 419    }
 420
 421    if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
 422                 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
 423        error_report("%s received unaligned region", __func__);
 424        return;
 425    }
 426
 427    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
 428    llend = int128_make64(section->offset_within_address_space);
 429    llend = int128_add(llend, section->size);
 430    llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
 431
 432    if (int128_ge(int128_make64(iova), llend)) {
 433        return;
 434    }
 435    end = int128_get64(int128_sub(llend, int128_one()));
 436
 437    if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
 438        hwaddr pgsize = 0;
 439
 440        /* For now intersections are not allowed, we may relax this later */
 441        QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
 442            if (ranges_overlap(hostwin->min_iova,
 443                               hostwin->max_iova - hostwin->min_iova + 1,
 444                               section->offset_within_address_space,
 445                               int128_get64(section->size))) {
 446                ret = -1;
 447                goto fail;
 448            }
 449        }
 450
 451        ret = vfio_spapr_create_window(container, section, &pgsize);
 452        if (ret) {
 453            goto fail;
 454        }
 455
 456        vfio_host_win_add(container, section->offset_within_address_space,
 457                          section->offset_within_address_space +
 458                          int128_get64(section->size) - 1, pgsize);
 459#ifdef CONFIG_KVM
 460        if (kvm_enabled()) {
 461            VFIOGroup *group;
 462            IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
 463            struct kvm_vfio_spapr_tce param;
 464            struct kvm_device_attr attr = {
 465                .group = KVM_DEV_VFIO_GROUP,
 466                .attr = KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE,
 467                .addr = (uint64_t)(unsigned long)&param,
 468            };
 469
 470            if (!memory_region_iommu_get_attr(iommu_mr, IOMMU_ATTR_SPAPR_TCE_FD,
 471                                              &param.tablefd)) {
 472                QLIST_FOREACH(group, &container->group_list, container_next) {
 473                    param.groupfd = group->fd;
 474                    if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
 475                        error_report("vfio: failed to setup fd %d "
 476                                     "for a group with fd %d: %s",
 477                                     param.tablefd, param.groupfd,
 478                                     strerror(errno));
 479                        return;
 480                    }
 481                    trace_vfio_spapr_group_attach(param.groupfd, param.tablefd);
 482                }
 483            }
 484        }
 485#endif
 486    }
 487
 488    hostwin_found = false;
 489    QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
 490        if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
 491            hostwin_found = true;
 492            break;
 493        }
 494    }
 495
 496    if (!hostwin_found) {
 497        error_report("vfio: IOMMU container %p can't map guest IOVA region"
 498                     " 0x%"HWADDR_PRIx"..0x%"HWADDR_PRIx,
 499                     container, iova, end);
 500        ret = -EFAULT;
 501        goto fail;
 502    }
 503
 504    memory_region_ref(section->mr);
 505
 506    if (memory_region_is_iommu(section->mr)) {
 507        VFIOGuestIOMMU *giommu;
 508        IOMMUMemoryRegion *iommu_mr = IOMMU_MEMORY_REGION(section->mr);
 509
 510        trace_vfio_listener_region_add_iommu(iova, end);
 511        /*
 512         * FIXME: For VFIO iommu types which have KVM acceleration to
 513         * avoid bouncing all map/unmaps through qemu this way, this
 514         * would be the right place to wire that up (tell the KVM
 515         * device emulation the VFIO iommu handles to use).
 516         */
 517        giommu = g_malloc0(sizeof(*giommu));
 518        giommu->iommu = iommu_mr;
 519        giommu->iommu_offset = section->offset_within_address_space -
 520                               section->offset_within_region;
 521        giommu->container = container;
 522        llend = int128_add(int128_make64(section->offset_within_region),
 523                           section->size);
 524        llend = int128_sub(llend, int128_one());
 525        iommu_notifier_init(&giommu->n, vfio_iommu_map_notify,
 526                            IOMMU_NOTIFIER_ALL,
 527                            section->offset_within_region,
 528                            int128_get64(llend));
 529        QLIST_INSERT_HEAD(&container->giommu_list, giommu, giommu_next);
 530
 531        memory_region_register_iommu_notifier(section->mr, &giommu->n);
 532        memory_region_iommu_replay(giommu->iommu, &giommu->n);
 533
 534        return;
 535    }
 536
 537    /* Here we assume that memory_region_is_ram(section->mr)==true */
 538
 539    vaddr = memory_region_get_ram_ptr(section->mr) +
 540            section->offset_within_region +
 541            (iova - section->offset_within_address_space);
 542
 543    trace_vfio_listener_region_add_ram(iova, end, vaddr);
 544
 545    llsize = int128_sub(llend, int128_make64(iova));
 546
 547    if (memory_region_is_ram_device(section->mr)) {
 548        hwaddr pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
 549
 550        if ((iova & pgmask) || (int128_get64(llsize) & pgmask)) {
 551            trace_vfio_listener_region_add_no_dma_map(
 552                memory_region_name(section->mr),
 553                section->offset_within_address_space,
 554                int128_getlo(section->size),
 555                pgmask + 1);
 556            return;
 557        }
 558    }
 559
 560    ret = vfio_dma_map(container, iova, int128_get64(llsize),
 561                       vaddr, section->readonly);
 562    if (ret) {
 563        error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
 564                     "0x%"HWADDR_PRIx", %p) = %d (%m)",
 565                     container, iova, int128_get64(llsize), vaddr, ret);
 566        if (memory_region_is_ram_device(section->mr)) {
 567            /* Allow unexpected mappings not to be fatal for RAM devices */
 568            return;
 569        }
 570        goto fail;
 571    }
 572
 573    return;
 574
 575fail:
 576    if (memory_region_is_ram_device(section->mr)) {
 577        error_report("failed to vfio_dma_map. pci p2p may not work");
 578        return;
 579    }
 580    /*
 581     * On the initfn path, store the first error in the container so we
 582     * can gracefully fail.  Runtime, there's not much we can do other
 583     * than throw a hardware error.
 584     */
 585    if (!container->initialized) {
 586        if (!container->error) {
 587            container->error = ret;
 588        }
 589    } else {
 590        hw_error("vfio: DMA mapping failed, unable to continue");
 591    }
 592}
 593
 594static void vfio_listener_region_del(MemoryListener *listener,
 595                                     MemoryRegionSection *section)
 596{
 597    VFIOContainer *container = container_of(listener, VFIOContainer, listener);
 598    hwaddr iova, end;
 599    Int128 llend, llsize;
 600    int ret;
 601    bool try_unmap = true;
 602
 603    if (vfio_listener_skipped_section(section)) {
 604        trace_vfio_listener_region_del_skip(
 605                section->offset_within_address_space,
 606                section->offset_within_address_space +
 607                int128_get64(int128_sub(section->size, int128_one())));
 608        return;
 609    }
 610
 611    if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
 612                 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
 613        error_report("%s received unaligned region", __func__);
 614        return;
 615    }
 616
 617    if (memory_region_is_iommu(section->mr)) {
 618        VFIOGuestIOMMU *giommu;
 619
 620        QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {
 621            if (MEMORY_REGION(giommu->iommu) == section->mr &&
 622                giommu->n.start == section->offset_within_region) {
 623                memory_region_unregister_iommu_notifier(section->mr,
 624                                                        &giommu->n);
 625                QLIST_REMOVE(giommu, giommu_next);
 626                g_free(giommu);
 627                break;
 628            }
 629        }
 630
 631        /*
 632         * FIXME: We assume the one big unmap below is adequate to
 633         * remove any individual page mappings in the IOMMU which
 634         * might have been copied into VFIO. This works for a page table
 635         * based IOMMU where a big unmap flattens a large range of IO-PTEs.
 636         * That may not be true for all IOMMU types.
 637         */
 638    }
 639
 640    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
 641    llend = int128_make64(section->offset_within_address_space);
 642    llend = int128_add(llend, section->size);
 643    llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
 644
 645    if (int128_ge(int128_make64(iova), llend)) {
 646        return;
 647    }
 648    end = int128_get64(int128_sub(llend, int128_one()));
 649
 650    llsize = int128_sub(llend, int128_make64(iova));
 651
 652    trace_vfio_listener_region_del(iova, end);
 653
 654    if (memory_region_is_ram_device(section->mr)) {
 655        hwaddr pgmask;
 656        VFIOHostDMAWindow *hostwin;
 657        bool hostwin_found = false;
 658
 659        QLIST_FOREACH(hostwin, &container->hostwin_list, hostwin_next) {
 660            if (hostwin->min_iova <= iova && end <= hostwin->max_iova) {
 661                hostwin_found = true;
 662                break;
 663            }
 664        }
 665        assert(hostwin_found); /* or region_add() would have failed */
 666
 667        pgmask = (1ULL << ctz64(hostwin->iova_pgsizes)) - 1;
 668        try_unmap = !((iova & pgmask) || (int128_get64(llsize) & pgmask));
 669    }
 670
 671    if (try_unmap) {
 672        ret = vfio_dma_unmap(container, iova, int128_get64(llsize));
 673        if (ret) {
 674            error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
 675                         "0x%"HWADDR_PRIx") = %d (%m)",
 676                         container, iova, int128_get64(llsize), ret);
 677        }
 678    }
 679
 680    memory_region_unref(section->mr);
 681
 682    if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
 683        vfio_spapr_remove_window(container,
 684                                 section->offset_within_address_space);
 685        if (vfio_host_win_del(container,
 686                              section->offset_within_address_space,
 687                              section->offset_within_address_space +
 688                              int128_get64(section->size) - 1) < 0) {
 689            hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,
 690                     __func__, section->offset_within_address_space);
 691        }
 692    }
 693}
 694
 695static const MemoryListener vfio_memory_listener = {
 696    .region_add = vfio_listener_region_add,
 697    .region_del = vfio_listener_region_del,
 698};
 699
 700static void vfio_listener_release(VFIOContainer *container)
 701{
 702    memory_listener_unregister(&container->listener);
 703    if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {
 704        memory_listener_unregister(&container->prereg_listener);
 705    }
 706}
 707
 708static struct vfio_info_cap_header *
 709vfio_get_region_info_cap(struct vfio_region_info *info, uint16_t id)
 710{
 711    struct vfio_info_cap_header *hdr;
 712    void *ptr = info;
 713
 714    if (!(info->flags & VFIO_REGION_INFO_FLAG_CAPS)) {
 715        return NULL;
 716    }
 717
 718    for (hdr = ptr + info->cap_offset; hdr != ptr; hdr = ptr + hdr->next) {
 719        if (hdr->id == id) {
 720            return hdr;
 721        }
 722    }
 723
 724    return NULL;
 725}
 726
 727static int vfio_setup_region_sparse_mmaps(VFIORegion *region,
 728                                          struct vfio_region_info *info)
 729{
 730    struct vfio_info_cap_header *hdr;
 731    struct vfio_region_info_cap_sparse_mmap *sparse;
 732    int i, j;
 733
 734    hdr = vfio_get_region_info_cap(info, VFIO_REGION_INFO_CAP_SPARSE_MMAP);
 735    if (!hdr) {
 736        return -ENODEV;
 737    }
 738
 739    sparse = container_of(hdr, struct vfio_region_info_cap_sparse_mmap, header);
 740
 741    trace_vfio_region_sparse_mmap_header(region->vbasedev->name,
 742                                         region->nr, sparse->nr_areas);
 743
 744    region->mmaps = g_new0(VFIOMmap, sparse->nr_areas);
 745
 746    for (i = 0, j = 0; i < sparse->nr_areas; i++) {
 747        trace_vfio_region_sparse_mmap_entry(i, sparse->areas[i].offset,
 748                                            sparse->areas[i].offset +
 749                                            sparse->areas[i].size);
 750
 751        if (sparse->areas[i].size) {
 752            region->mmaps[j].offset = sparse->areas[i].offset;
 753            region->mmaps[j].size = sparse->areas[i].size;
 754            j++;
 755        }
 756    }
 757
 758    region->nr_mmaps = j;
 759    region->mmaps = g_realloc(region->mmaps, j * sizeof(VFIOMmap));
 760
 761    return 0;
 762}
 763
 764int vfio_region_setup(Object *obj, VFIODevice *vbasedev, VFIORegion *region,
 765                      int index, const char *name)
 766{
 767    struct vfio_region_info *info;
 768    int ret;
 769
 770    ret = vfio_get_region_info(vbasedev, index, &info);
 771    if (ret) {
 772        return ret;
 773    }
 774
 775    region->vbasedev = vbasedev;
 776    region->flags = info->flags;
 777    region->size = info->size;
 778    region->fd_offset = info->offset;
 779    region->nr = index;
 780
 781    if (region->size) {
 782        region->mem = g_new0(MemoryRegion, 1);
 783        memory_region_init_io(region->mem, obj, &vfio_region_ops,
 784                              region, name, region->size);
 785
 786        if (!vbasedev->no_mmap &&
 787            region->flags & VFIO_REGION_INFO_FLAG_MMAP) {
 788
 789            ret = vfio_setup_region_sparse_mmaps(region, info);
 790
 791            if (ret) {
 792                region->nr_mmaps = 1;
 793                region->mmaps = g_new0(VFIOMmap, region->nr_mmaps);
 794                region->mmaps[0].offset = 0;
 795                region->mmaps[0].size = region->size;
 796            }
 797        }
 798    }
 799
 800    g_free(info);
 801
 802    trace_vfio_region_setup(vbasedev->name, index, name,
 803                            region->flags, region->fd_offset, region->size);
 804    return 0;
 805}
 806
 807int vfio_region_mmap(VFIORegion *region)
 808{
 809    int i, prot = 0;
 810    char *name;
 811
 812    if (!region->mem) {
 813        return 0;
 814    }
 815
 816    prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;
 817    prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;
 818
 819    for (i = 0; i < region->nr_mmaps; i++) {
 820        region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,
 821                                     MAP_SHARED, region->vbasedev->fd,
 822                                     region->fd_offset +
 823                                     region->mmaps[i].offset);
 824        if (region->mmaps[i].mmap == MAP_FAILED) {
 825            int ret = -errno;
 826
 827            trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,
 828                                         region->fd_offset +
 829                                         region->mmaps[i].offset,
 830                                         region->fd_offset +
 831                                         region->mmaps[i].offset +
 832                                         region->mmaps[i].size - 1, ret);
 833
 834            region->mmaps[i].mmap = NULL;
 835
 836            for (i--; i >= 0; i--) {
 837                memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
 838                munmap(region->mmaps[i].mmap, region->mmaps[i].size);
 839                object_unparent(OBJECT(&region->mmaps[i].mem));
 840                region->mmaps[i].mmap = NULL;
 841            }
 842
 843            return ret;
 844        }
 845
 846        name = g_strdup_printf("%s mmaps[%d]",
 847                               memory_region_name(region->mem), i);
 848        memory_region_init_ram_device_ptr(&region->mmaps[i].mem,
 849                                          memory_region_owner(region->mem),
 850                                          name, region->mmaps[i].size,
 851                                          region->mmaps[i].mmap);
 852        g_free(name);
 853        memory_region_add_subregion(region->mem, region->mmaps[i].offset,
 854                                    &region->mmaps[i].mem);
 855
 856        trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),
 857                               region->mmaps[i].offset,
 858                               region->mmaps[i].offset +
 859                               region->mmaps[i].size - 1);
 860    }
 861
 862    return 0;
 863}
 864
 865void vfio_region_exit(VFIORegion *region)
 866{
 867    int i;
 868
 869    if (!region->mem) {
 870        return;
 871    }
 872
 873    for (i = 0; i < region->nr_mmaps; i++) {
 874        if (region->mmaps[i].mmap) {
 875            memory_region_del_subregion(region->mem, &region->mmaps[i].mem);
 876        }
 877    }
 878
 879    trace_vfio_region_exit(region->vbasedev->name, region->nr);
 880}
 881
 882void vfio_region_finalize(VFIORegion *region)
 883{
 884    int i;
 885
 886    if (!region->mem) {
 887        return;
 888    }
 889
 890    for (i = 0; i < region->nr_mmaps; i++) {
 891        if (region->mmaps[i].mmap) {
 892            munmap(region->mmaps[i].mmap, region->mmaps[i].size);
 893            object_unparent(OBJECT(&region->mmaps[i].mem));
 894        }
 895    }
 896
 897    object_unparent(OBJECT(region->mem));
 898
 899    g_free(region->mem);
 900    g_free(region->mmaps);
 901
 902    trace_vfio_region_finalize(region->vbasedev->name, region->nr);
 903
 904    region->mem = NULL;
 905    region->mmaps = NULL;
 906    region->nr_mmaps = 0;
 907    region->size = 0;
 908    region->flags = 0;
 909    region->nr = 0;
 910}
 911
 912void vfio_region_mmaps_set_enabled(VFIORegion *region, bool enabled)
 913{
 914    int i;
 915
 916    if (!region->mem) {
 917        return;
 918    }
 919
 920    for (i = 0; i < region->nr_mmaps; i++) {
 921        if (region->mmaps[i].mmap) {
 922            memory_region_set_enabled(&region->mmaps[i].mem, enabled);
 923        }
 924    }
 925
 926    trace_vfio_region_mmaps_set_enabled(memory_region_name(region->mem),
 927                                        enabled);
 928}
 929
 930void vfio_reset_handler(void *opaque)
 931{
 932    VFIOGroup *group;
 933    VFIODevice *vbasedev;
 934
 935    QLIST_FOREACH(group, &vfio_group_list, next) {
 936        QLIST_FOREACH(vbasedev, &group->device_list, next) {
 937            if (vbasedev->dev->realized) {
 938                vbasedev->ops->vfio_compute_needs_reset(vbasedev);
 939            }
 940        }
 941    }
 942
 943    QLIST_FOREACH(group, &vfio_group_list, next) {
 944        QLIST_FOREACH(vbasedev, &group->device_list, next) {
 945            if (vbasedev->dev->realized && vbasedev->needs_reset) {
 946                vbasedev->ops->vfio_hot_reset_multi(vbasedev);
 947            }
 948        }
 949    }
 950}
 951
 952static void vfio_kvm_device_add_group(VFIOGroup *group)
 953{
 954#ifdef CONFIG_KVM
 955    struct kvm_device_attr attr = {
 956        .group = KVM_DEV_VFIO_GROUP,
 957        .attr = KVM_DEV_VFIO_GROUP_ADD,
 958        .addr = (uint64_t)(unsigned long)&group->fd,
 959    };
 960
 961    if (!kvm_enabled()) {
 962        return;
 963    }
 964
 965    if (vfio_kvm_device_fd < 0) {
 966        struct kvm_create_device cd = {
 967            .type = KVM_DEV_TYPE_VFIO,
 968        };
 969
 970        if (kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd)) {
 971            error_report("Failed to create KVM VFIO device: %m");
 972            return;
 973        }
 974
 975        vfio_kvm_device_fd = cd.fd;
 976    }
 977
 978    if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
 979        error_report("Failed to add group %d to KVM VFIO device: %m",
 980                     group->groupid);
 981    }
 982#endif
 983}
 984
 985static void vfio_kvm_device_del_group(VFIOGroup *group)
 986{
 987#ifdef CONFIG_KVM
 988    struct kvm_device_attr attr = {
 989        .group = KVM_DEV_VFIO_GROUP,
 990        .attr = KVM_DEV_VFIO_GROUP_DEL,
 991        .addr = (uint64_t)(unsigned long)&group->fd,
 992    };
 993
 994    if (vfio_kvm_device_fd < 0) {
 995        return;
 996    }
 997
 998    if (ioctl(vfio_kvm_device_fd, KVM_SET_DEVICE_ATTR, &attr)) {
 999        error_report("Failed to remove group %d from KVM VFIO device: %m",
1000                     group->groupid);
1001    }
1002#endif
1003}
1004
1005static VFIOAddressSpace *vfio_get_address_space(AddressSpace *as)
1006{
1007    VFIOAddressSpace *space;
1008
1009    QLIST_FOREACH(space, &vfio_address_spaces, list) {
1010        if (space->as == as) {
1011            return space;
1012        }
1013    }
1014
1015    /* No suitable VFIOAddressSpace, create a new one */
1016    space = g_malloc0(sizeof(*space));
1017    space->as = as;
1018    QLIST_INIT(&space->containers);
1019
1020    QLIST_INSERT_HEAD(&vfio_address_spaces, space, list);
1021
1022    return space;
1023}
1024
1025static void vfio_put_address_space(VFIOAddressSpace *space)
1026{
1027    if (QLIST_EMPTY(&space->containers)) {
1028        QLIST_REMOVE(space, list);
1029        g_free(space);
1030    }
1031}
1032
1033static int vfio_connect_container(VFIOGroup *group, AddressSpace *as,
1034                                  Error **errp)
1035{
1036    VFIOContainer *container;
1037    int ret, fd;
1038    VFIOAddressSpace *space;
1039
1040    space = vfio_get_address_space(as);
1041
1042    QLIST_FOREACH(container, &space->containers, next) {
1043        if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
1044            group->container = container;
1045            QLIST_INSERT_HEAD(&container->group_list, group, container_next);
1046            vfio_kvm_device_add_group(group);
1047            return 0;
1048        }
1049    }
1050
1051    fd = qemu_open("/dev/vfio/vfio", O_RDWR);
1052    if (fd < 0) {
1053        error_setg_errno(errp, errno, "failed to open /dev/vfio/vfio");
1054        ret = -errno;
1055        goto put_space_exit;
1056    }
1057
1058    ret = ioctl(fd, VFIO_GET_API_VERSION);
1059    if (ret != VFIO_API_VERSION) {
1060        error_setg(errp, "supported vfio version: %d, "
1061                   "reported version: %d", VFIO_API_VERSION, ret);
1062        ret = -EINVAL;
1063        goto close_fd_exit;
1064    }
1065
1066    container = g_malloc0(sizeof(*container));
1067    container->space = space;
1068    container->fd = fd;
1069    QLIST_INIT(&container->giommu_list);
1070    QLIST_INIT(&container->hostwin_list);
1071    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) ||
1072        ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU)) {
1073        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU);
1074        struct vfio_iommu_type1_info info;
1075
1076        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
1077        if (ret) {
1078            error_setg_errno(errp, errno, "failed to set group container");
1079            ret = -errno;
1080            goto free_container_exit;
1081        }
1082
1083        container->iommu_type = v2 ? VFIO_TYPE1v2_IOMMU : VFIO_TYPE1_IOMMU;
1084        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
1085        if (ret) {
1086            error_setg_errno(errp, errno, "failed to set iommu for container");
1087            ret = -errno;
1088            goto free_container_exit;
1089        }
1090
1091        /*
1092         * FIXME: This assumes that a Type1 IOMMU can map any 64-bit
1093         * IOVA whatsoever.  That's not actually true, but the current
1094         * kernel interface doesn't tell us what it can map, and the
1095         * existing Type1 IOMMUs generally support any IOVA we're
1096         * going to actually try in practice.
1097         */
1098        info.argsz = sizeof(info);
1099        ret = ioctl(fd, VFIO_IOMMU_GET_INFO, &info);
1100        /* Ignore errors */
1101        if (ret || !(info.flags & VFIO_IOMMU_INFO_PGSIZES)) {
1102            /* Assume 4k IOVA page size */
1103            info.iova_pgsizes = 4096;
1104        }
1105        vfio_host_win_add(container, 0, (hwaddr)-1, info.iova_pgsizes);
1106    } else if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_IOMMU) ||
1107               ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU)) {
1108        struct vfio_iommu_spapr_tce_info info;
1109        bool v2 = !!ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_SPAPR_TCE_v2_IOMMU);
1110
1111        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
1112        if (ret) {
1113            error_setg_errno(errp, errno, "failed to set group container");
1114            ret = -errno;
1115            goto free_container_exit;
1116        }
1117        container->iommu_type =
1118            v2 ? VFIO_SPAPR_TCE_v2_IOMMU : VFIO_SPAPR_TCE_IOMMU;
1119        ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
1120        if (ret) {
1121            container->iommu_type = VFIO_SPAPR_TCE_IOMMU;
1122            v2 = false;
1123            ret = ioctl(fd, VFIO_SET_IOMMU, container->iommu_type);
1124        }
1125        if (ret) {
1126            error_setg_errno(errp, errno, "failed to set iommu for container");
1127            ret = -errno;
1128            goto free_container_exit;
1129        }
1130
1131        /*
1132         * The host kernel code implementing VFIO_IOMMU_DISABLE is called
1133         * when container fd is closed so we do not call it explicitly
1134         * in this file.
1135         */
1136        if (!v2) {
1137            ret = ioctl(fd, VFIO_IOMMU_ENABLE);
1138            if (ret) {
1139                error_setg_errno(errp, errno, "failed to enable container");
1140                ret = -errno;
1141                goto free_container_exit;
1142            }
1143        } else {
1144            container->prereg_listener = vfio_prereg_listener;
1145
1146            memory_listener_register(&container->prereg_listener,
1147                                     &address_space_memory);
1148            if (container->error) {
1149                memory_listener_unregister(&container->prereg_listener);
1150                ret = container->error;
1151                error_setg(errp,
1152                    "RAM memory listener initialization failed for container");
1153                goto free_container_exit;
1154            }
1155        }
1156
1157        info.argsz = sizeof(info);
1158        ret = ioctl(fd, VFIO_IOMMU_SPAPR_TCE_GET_INFO, &info);
1159        if (ret) {
1160            error_setg_errno(errp, errno,
1161                             "VFIO_IOMMU_SPAPR_TCE_GET_INFO failed");
1162            ret = -errno;
1163            if (v2) {
1164                memory_listener_unregister(&container->prereg_listener);
1165            }
1166            goto free_container_exit;
1167        }
1168
1169        if (v2) {
1170            /*
1171             * There is a default window in just created container.
1172             * To make region_add/del simpler, we better remove this
1173             * window now and let those iommu_listener callbacks
1174             * create/remove them when needed.
1175             */
1176            ret = vfio_spapr_remove_window(container, info.dma32_window_start);
1177            if (ret) {
1178                error_setg_errno(errp, -ret,
1179                                 "failed to remove existing window");
1180                goto free_container_exit;
1181            }
1182        } else {
1183            /* The default table uses 4K pages */
1184            vfio_host_win_add(container, info.dma32_window_start,
1185                              info.dma32_window_start +
1186                              info.dma32_window_size - 1,
1187                              0x1000);
1188        }
1189    } else {
1190        error_setg(errp, "No available IOMMU models");
1191        ret = -EINVAL;
1192        goto free_container_exit;
1193    }
1194
1195    vfio_kvm_device_add_group(group);
1196
1197    QLIST_INIT(&container->group_list);
1198    QLIST_INSERT_HEAD(&space->containers, container, next);
1199
1200    group->container = container;
1201    QLIST_INSERT_HEAD(&container->group_list, group, container_next);
1202
1203    container->listener = vfio_memory_listener;
1204
1205    memory_listener_register(&container->listener, container->space->as);
1206
1207    if (container->error) {
1208        ret = container->error;
1209        error_setg_errno(errp, -ret,
1210                         "memory listener initialization failed for container");
1211        goto listener_release_exit;
1212    }
1213
1214    container->initialized = true;
1215
1216    return 0;
1217listener_release_exit:
1218    QLIST_REMOVE(group, container_next);
1219    QLIST_REMOVE(container, next);
1220    vfio_kvm_device_del_group(group);
1221    vfio_listener_release(container);
1222
1223free_container_exit:
1224    g_free(container);
1225
1226close_fd_exit:
1227    close(fd);
1228
1229put_space_exit:
1230    vfio_put_address_space(space);
1231
1232    return ret;
1233}
1234
1235static void vfio_disconnect_container(VFIOGroup *group)
1236{
1237    VFIOContainer *container = group->container;
1238
1239    QLIST_REMOVE(group, container_next);
1240    group->container = NULL;
1241
1242    /*
1243     * Explicitly release the listener first before unset container,
1244     * since unset may destroy the backend container if it's the last
1245     * group.
1246     */
1247    if (QLIST_EMPTY(&container->group_list)) {
1248        vfio_listener_release(container);
1249    }
1250
1251    if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
1252        error_report("vfio: error disconnecting group %d from container",
1253                     group->groupid);
1254    }
1255
1256    if (QLIST_EMPTY(&container->group_list)) {
1257        VFIOAddressSpace *space = container->space;
1258        VFIOGuestIOMMU *giommu, *tmp;
1259
1260        QLIST_REMOVE(container, next);
1261
1262        QLIST_FOREACH_SAFE(giommu, &container->giommu_list, giommu_next, tmp) {
1263            memory_region_unregister_iommu_notifier(
1264                    MEMORY_REGION(giommu->iommu), &giommu->n);
1265            QLIST_REMOVE(giommu, giommu_next);
1266            g_free(giommu);
1267        }
1268
1269        trace_vfio_disconnect_container(container->fd);
1270        close(container->fd);
1271        g_free(container);
1272
1273        vfio_put_address_space(space);
1274    }
1275}
1276
1277VFIOGroup *vfio_get_group(int groupid, AddressSpace *as, Error **errp)
1278{
1279    VFIOGroup *group;
1280    char path[32];
1281    struct vfio_group_status status = { .argsz = sizeof(status) };
1282
1283    QLIST_FOREACH(group, &vfio_group_list, next) {
1284        if (group->groupid == groupid) {
1285            /* Found it.  Now is it already in the right context? */
1286            if (group->container->space->as == as) {
1287                return group;
1288            } else {
1289                error_setg(errp, "group %d used in multiple address spaces",
1290                           group->groupid);
1291                return NULL;
1292            }
1293        }
1294    }
1295
1296    group = g_malloc0(sizeof(*group));
1297
1298    snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
1299    group->fd = qemu_open(path, O_RDWR);
1300    if (group->fd < 0) {
1301        error_setg_errno(errp, errno, "failed to open %s", path);
1302        goto free_group_exit;
1303    }
1304
1305    if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
1306        error_setg_errno(errp, errno, "failed to get group %d status", groupid);
1307        goto close_fd_exit;
1308    }
1309
1310    if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
1311        error_setg(errp, "group %d is not viable", groupid);
1312        error_append_hint(errp,
1313                          "Please ensure all devices within the iommu_group "
1314                          "are bound to their vfio bus driver.\n");
1315        goto close_fd_exit;
1316    }
1317
1318    group->groupid = groupid;
1319    QLIST_INIT(&group->device_list);
1320
1321    if (vfio_connect_container(group, as, errp)) {
1322        error_prepend(errp, "failed to setup container for group %d: ",
1323                      groupid);
1324        goto close_fd_exit;
1325    }
1326
1327    if (QLIST_EMPTY(&vfio_group_list)) {
1328        qemu_register_reset(vfio_reset_handler, NULL);
1329    }
1330
1331    QLIST_INSERT_HEAD(&vfio_group_list, group, next);
1332
1333    return group;
1334
1335close_fd_exit:
1336    close(group->fd);
1337
1338free_group_exit:
1339    g_free(group);
1340
1341    return NULL;
1342}
1343
1344void vfio_put_group(VFIOGroup *group)
1345{
1346    if (!group || !QLIST_EMPTY(&group->device_list)) {
1347        return;
1348    }
1349
1350    vfio_kvm_device_del_group(group);
1351    vfio_disconnect_container(group);
1352    QLIST_REMOVE(group, next);
1353    trace_vfio_put_group(group->fd);
1354    close(group->fd);
1355    g_free(group);
1356
1357    if (QLIST_EMPTY(&vfio_group_list)) {
1358        qemu_unregister_reset(vfio_reset_handler, NULL);
1359    }
1360}
1361
1362int vfio_get_device(VFIOGroup *group, const char *name,
1363                    VFIODevice *vbasedev, Error **errp)
1364{
1365    struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
1366    int ret, fd;
1367
1368    fd = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
1369    if (fd < 0) {
1370        error_setg_errno(errp, errno, "error getting device from group %d",
1371                         group->groupid);
1372        error_append_hint(errp,
1373                      "Verify all devices in group %d are bound to vfio-<bus> "
1374                      "or pci-stub and not already in use\n", group->groupid);
1375        return fd;
1376    }
1377
1378    ret = ioctl(fd, VFIO_DEVICE_GET_INFO, &dev_info);
1379    if (ret) {
1380        error_setg_errno(errp, errno, "error getting device info");
1381        close(fd);
1382        return ret;
1383    }
1384
1385    vbasedev->fd = fd;
1386    vbasedev->group = group;
1387    QLIST_INSERT_HEAD(&group->device_list, vbasedev, next);
1388
1389    vbasedev->num_irqs = dev_info.num_irqs;
1390    vbasedev->num_regions = dev_info.num_regions;
1391    vbasedev->flags = dev_info.flags;
1392
1393    trace_vfio_get_device(name, dev_info.flags, dev_info.num_regions,
1394                          dev_info.num_irqs);
1395
1396    vbasedev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
1397    return 0;
1398}
1399
1400void vfio_put_base_device(VFIODevice *vbasedev)
1401{
1402    if (!vbasedev->group) {
1403        return;
1404    }
1405    QLIST_REMOVE(vbasedev, next);
1406    vbasedev->group = NULL;
1407    trace_vfio_put_base_device(vbasedev->fd);
1408    close(vbasedev->fd);
1409}
1410
1411int vfio_get_region_info(VFIODevice *vbasedev, int index,
1412                         struct vfio_region_info **info)
1413{
1414    size_t argsz = sizeof(struct vfio_region_info);
1415
1416    *info = g_malloc0(argsz);
1417
1418    (*info)->index = index;
1419retry:
1420    (*info)->argsz = argsz;
1421
1422    if (ioctl(vbasedev->fd, VFIO_DEVICE_GET_REGION_INFO, *info)) {
1423        g_free(*info);
1424        *info = NULL;
1425        return -errno;
1426    }
1427
1428    if ((*info)->argsz > argsz) {
1429        argsz = (*info)->argsz;
1430        *info = g_realloc(*info, argsz);
1431
1432        goto retry;
1433    }
1434
1435    return 0;
1436}
1437
1438int vfio_get_dev_region_info(VFIODevice *vbasedev, uint32_t type,
1439                             uint32_t subtype, struct vfio_region_info **info)
1440{
1441    int i;
1442
1443    for (i = 0; i < vbasedev->num_regions; i++) {
1444        struct vfio_info_cap_header *hdr;
1445        struct vfio_region_info_cap_type *cap_type;
1446
1447        if (vfio_get_region_info(vbasedev, i, info)) {
1448            continue;
1449        }
1450
1451        hdr = vfio_get_region_info_cap(*info, VFIO_REGION_INFO_CAP_TYPE);
1452        if (!hdr) {
1453            g_free(*info);
1454            continue;
1455        }
1456
1457        cap_type = container_of(hdr, struct vfio_region_info_cap_type, header);
1458
1459        trace_vfio_get_dev_region(vbasedev->name, i,
1460                                  cap_type->type, cap_type->subtype);
1461
1462        if (cap_type->type == type && cap_type->subtype == subtype) {
1463            return 0;
1464        }
1465
1466        g_free(*info);
1467    }
1468
1469    *info = NULL;
1470    return -ENODEV;
1471}
1472
1473bool vfio_has_region_cap(VFIODevice *vbasedev, int region, uint16_t cap_type)
1474{
1475    struct vfio_region_info *info = NULL;
1476    bool ret = false;
1477
1478    if (!vfio_get_region_info(vbasedev, region, &info)) {
1479        if (vfio_get_region_info_cap(info, cap_type)) {
1480            ret = true;
1481        }
1482        g_free(info);
1483    }
1484
1485    return ret;
1486}
1487
1488/*
1489 * Interfaces for IBM EEH (Enhanced Error Handling)
1490 */
1491static bool vfio_eeh_container_ok(VFIOContainer *container)
1492{
1493    /*
1494     * As of 2016-03-04 (linux-4.5) the host kernel EEH/VFIO
1495     * implementation is broken if there are multiple groups in a
1496     * container.  The hardware works in units of Partitionable
1497     * Endpoints (== IOMMU groups) and the EEH operations naively
1498     * iterate across all groups in the container, without any logic
1499     * to make sure the groups have their state synchronized.  For
1500     * certain operations (ENABLE) that might be ok, until an error
1501     * occurs, but for others (GET_STATE) it's clearly broken.
1502     */
1503
1504    /*
1505     * XXX Once fixed kernels exist, test for them here
1506     */
1507
1508    if (QLIST_EMPTY(&container->group_list)) {
1509        return false;
1510    }
1511
1512    if (QLIST_NEXT(QLIST_FIRST(&container->group_list), container_next)) {
1513        return false;
1514    }
1515
1516    return true;
1517}
1518
1519static int vfio_eeh_container_op(VFIOContainer *container, uint32_t op)
1520{
1521    struct vfio_eeh_pe_op pe_op = {
1522        .argsz = sizeof(pe_op),
1523        .op = op,
1524    };
1525    int ret;
1526
1527    if (!vfio_eeh_container_ok(container)) {
1528        error_report("vfio/eeh: EEH_PE_OP 0x%x: "
1529                     "kernel requires a container with exactly one group", op);
1530        return -EPERM;
1531    }
1532
1533    ret = ioctl(container->fd, VFIO_EEH_PE_OP, &pe_op);
1534    if (ret < 0) {
1535        error_report("vfio/eeh: EEH_PE_OP 0x%x failed: %m", op);
1536        return -errno;
1537    }
1538
1539    return ret;
1540}
1541
1542static VFIOContainer *vfio_eeh_as_container(AddressSpace *as)
1543{
1544    VFIOAddressSpace *space = vfio_get_address_space(as);
1545    VFIOContainer *container = NULL;
1546
1547    if (QLIST_EMPTY(&space->containers)) {
1548        /* No containers to act on */
1549        goto out;
1550    }
1551
1552    container = QLIST_FIRST(&space->containers);
1553
1554    if (QLIST_NEXT(container, next)) {
1555        /* We don't yet have logic to synchronize EEH state across
1556         * multiple containers */
1557        container = NULL;
1558        goto out;
1559    }
1560
1561out:
1562    vfio_put_address_space(space);
1563    return container;
1564}
1565
1566bool vfio_eeh_as_ok(AddressSpace *as)
1567{
1568    VFIOContainer *container = vfio_eeh_as_container(as);
1569
1570    return (container != NULL) && vfio_eeh_container_ok(container);
1571}
1572
1573int vfio_eeh_as_op(AddressSpace *as, uint32_t op)
1574{
1575    VFIOContainer *container = vfio_eeh_as_container(as);
1576
1577    if (!container) {
1578        return -ENODEV;
1579    }
1580    return vfio_eeh_container_op(container, op);
1581}
1582