qemu/softmmu/physmem.c
<<
>>
Prefs
   1/*
   2 * RAM allocation and memory access
   3 *
   4 *  Copyright (c) 2003 Fabrice Bellard
   5 *
   6 * This library is free software; you can redistribute it and/or
   7 * modify it under the terms of the GNU Lesser General Public
   8 * License as published by the Free Software Foundation; either
   9 * version 2.1 of the License, or (at your option) any later version.
  10 *
  11 * This library is distributed in the hope that it will be useful,
  12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14 * Lesser General Public License for more details.
  15 *
  16 * You should have received a copy of the GNU Lesser General Public
  17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  18 */
  19
  20#include "qemu/osdep.h"
  21#include "qemu-common.h"
  22#include "qapi/error.h"
  23
  24#include "qemu/cutils.h"
  25#include "cpu.h"
  26#include "exec/exec-all.h"
  27#include "exec/target_page.h"
  28#include "tcg/tcg.h"
  29#include "hw/qdev-core.h"
  30#include "hw/qdev-properties.h"
  31#include "hw/boards.h"
  32#include "hw/xen/xen.h"
  33#include "sysemu/kvm.h"
  34#include "sysemu/sysemu.h"
  35#include "sysemu/tcg.h"
  36#include "sysemu/qtest.h"
  37#include "qemu/timer.h"
  38#include "qemu/config-file.h"
  39#include "qemu/error-report.h"
  40#include "qemu/qemu-print.h"
  41#include "exec/memory.h"
  42#include "exec/ioport.h"
  43#include "sysemu/dma.h"
  44#include "sysemu/hostmem.h"
  45#include "sysemu/hw_accel.h"
  46#include "exec/address-spaces.h"
  47#include "sysemu/xen-mapcache.h"
  48#include "trace/trace-root.h"
  49
  50#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
  51#include <linux/falloc.h>
  52#endif
  53
  54#include "qemu/rcu_queue.h"
  55#include "qemu/main-loop.h"
  56#include "translate-all.h"
  57#include "sysemu/replay.h"
  58
  59#include "exec/memory-internal.h"
  60#include "exec/ram_addr.h"
  61#include "exec/log.h"
  62
  63#include "qemu/pmem.h"
  64
  65#include "migration/vmstate.h"
  66
  67#include "qemu/range.h"
  68#ifndef _WIN32
  69#include "qemu/mmap-alloc.h"
  70#endif
  71
  72#include "monitor/monitor.h"
  73
  74#ifdef CONFIG_LIBDAXCTL
  75#include <daxctl/libdaxctl.h>
  76#endif
  77
  78//#define DEBUG_SUBPAGE
  79
  80/* ram_list is read under rcu_read_lock()/rcu_read_unlock().  Writes
  81 * are protected by the ramlist lock.
  82 */
  83RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
  84
  85static MemoryRegion *system_memory;
  86static MemoryRegion *system_io;
  87
  88AddressSpace address_space_io;
  89AddressSpace address_space_memory;
  90
  91static MemoryRegion io_mem_unassigned;
  92
  93typedef struct PhysPageEntry PhysPageEntry;
  94
  95struct PhysPageEntry {
  96    /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
  97    uint32_t skip : 6;
  98     /* index into phys_sections (!skip) or phys_map_nodes (skip) */
  99    uint32_t ptr : 26;
 100};
 101
 102#define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
 103
 104/* Size of the L2 (and L3, etc) page tables.  */
 105#define ADDR_SPACE_BITS 64
 106
 107#define P_L2_BITS 9
 108#define P_L2_SIZE (1 << P_L2_BITS)
 109
 110#define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
 111
 112typedef PhysPageEntry Node[P_L2_SIZE];
 113
 114typedef struct PhysPageMap {
 115    struct rcu_head rcu;
 116
 117    unsigned sections_nb;
 118    unsigned sections_nb_alloc;
 119    unsigned nodes_nb;
 120    unsigned nodes_nb_alloc;
 121    Node *nodes;
 122    MemoryRegionSection *sections;
 123} PhysPageMap;
 124
 125struct AddressSpaceDispatch {
 126    MemoryRegionSection *mru_section;
 127    /* This is a multi-level map on the physical address space.
 128     * The bottom level has pointers to MemoryRegionSections.
 129     */
 130    PhysPageEntry phys_map;
 131    PhysPageMap map;
 132};
 133
 134#define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
 135typedef struct subpage_t {
 136    MemoryRegion iomem;
 137    FlatView *fv;
 138    hwaddr base;
 139    uint16_t sub_section[];
 140} subpage_t;
 141
 142#define PHYS_SECTION_UNASSIGNED 0
 143
 144static void io_mem_init(void);
 145static void memory_map_init(void);
 146static void tcg_log_global_after_sync(MemoryListener *listener);
 147static void tcg_commit(MemoryListener *listener);
 148
 149/**
 150 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
 151 * @cpu: the CPU whose AddressSpace this is
 152 * @as: the AddressSpace itself
 153 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
 154 * @tcg_as_listener: listener for tracking changes to the AddressSpace
 155 */
 156struct CPUAddressSpace {
 157    CPUState *cpu;
 158    AddressSpace *as;
 159    struct AddressSpaceDispatch *memory_dispatch;
 160    MemoryListener tcg_as_listener;
 161};
 162
 163struct DirtyBitmapSnapshot {
 164    ram_addr_t start;
 165    ram_addr_t end;
 166    unsigned long dirty[];
 167};
 168
 169static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
 170{
 171    static unsigned alloc_hint = 16;
 172    if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
 173        map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
 174        map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
 175        alloc_hint = map->nodes_nb_alloc;
 176    }
 177}
 178
 179static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
 180{
 181    unsigned i;
 182    uint32_t ret;
 183    PhysPageEntry e;
 184    PhysPageEntry *p;
 185
 186    ret = map->nodes_nb++;
 187    p = map->nodes[ret];
 188    assert(ret != PHYS_MAP_NODE_NIL);
 189    assert(ret != map->nodes_nb_alloc);
 190
 191    e.skip = leaf ? 0 : 1;
 192    e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
 193    for (i = 0; i < P_L2_SIZE; ++i) {
 194        memcpy(&p[i], &e, sizeof(e));
 195    }
 196    return ret;
 197}
 198
 199static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
 200                                hwaddr *index, uint64_t *nb, uint16_t leaf,
 201                                int level)
 202{
 203    PhysPageEntry *p;
 204    hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
 205
 206    if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
 207        lp->ptr = phys_map_node_alloc(map, level == 0);
 208    }
 209    p = map->nodes[lp->ptr];
 210    lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
 211
 212    while (*nb && lp < &p[P_L2_SIZE]) {
 213        if ((*index & (step - 1)) == 0 && *nb >= step) {
 214            lp->skip = 0;
 215            lp->ptr = leaf;
 216            *index += step;
 217            *nb -= step;
 218        } else {
 219            phys_page_set_level(map, lp, index, nb, leaf, level - 1);
 220        }
 221        ++lp;
 222    }
 223}
 224
 225static void phys_page_set(AddressSpaceDispatch *d,
 226                          hwaddr index, uint64_t nb,
 227                          uint16_t leaf)
 228{
 229    /* Wildly overreserve - it doesn't matter much. */
 230    phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
 231
 232    phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
 233}
 234
 235/* Compact a non leaf page entry. Simply detect that the entry has a single child,
 236 * and update our entry so we can skip it and go directly to the destination.
 237 */
 238static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
 239{
 240    unsigned valid_ptr = P_L2_SIZE;
 241    int valid = 0;
 242    PhysPageEntry *p;
 243    int i;
 244
 245    if (lp->ptr == PHYS_MAP_NODE_NIL) {
 246        return;
 247    }
 248
 249    p = nodes[lp->ptr];
 250    for (i = 0; i < P_L2_SIZE; i++) {
 251        if (p[i].ptr == PHYS_MAP_NODE_NIL) {
 252            continue;
 253        }
 254
 255        valid_ptr = i;
 256        valid++;
 257        if (p[i].skip) {
 258            phys_page_compact(&p[i], nodes);
 259        }
 260    }
 261
 262    /* We can only compress if there's only one child. */
 263    if (valid != 1) {
 264        return;
 265    }
 266
 267    assert(valid_ptr < P_L2_SIZE);
 268
 269    /* Don't compress if it won't fit in the # of bits we have. */
 270    if (P_L2_LEVELS >= (1 << 6) &&
 271        lp->skip + p[valid_ptr].skip >= (1 << 6)) {
 272        return;
 273    }
 274
 275    lp->ptr = p[valid_ptr].ptr;
 276    if (!p[valid_ptr].skip) {
 277        /* If our only child is a leaf, make this a leaf. */
 278        /* By design, we should have made this node a leaf to begin with so we
 279         * should never reach here.
 280         * But since it's so simple to handle this, let's do it just in case we
 281         * change this rule.
 282         */
 283        lp->skip = 0;
 284    } else {
 285        lp->skip += p[valid_ptr].skip;
 286    }
 287}
 288
 289void address_space_dispatch_compact(AddressSpaceDispatch *d)
 290{
 291    if (d->phys_map.skip) {
 292        phys_page_compact(&d->phys_map, d->map.nodes);
 293    }
 294}
 295
 296static inline bool section_covers_addr(const MemoryRegionSection *section,
 297                                       hwaddr addr)
 298{
 299    /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
 300     * the section must cover the entire address space.
 301     */
 302    return int128_gethi(section->size) ||
 303           range_covers_byte(section->offset_within_address_space,
 304                             int128_getlo(section->size), addr);
 305}
 306
 307static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
 308{
 309    PhysPageEntry lp = d->phys_map, *p;
 310    Node *nodes = d->map.nodes;
 311    MemoryRegionSection *sections = d->map.sections;
 312    hwaddr index = addr >> TARGET_PAGE_BITS;
 313    int i;
 314
 315    for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
 316        if (lp.ptr == PHYS_MAP_NODE_NIL) {
 317            return &sections[PHYS_SECTION_UNASSIGNED];
 318        }
 319        p = nodes[lp.ptr];
 320        lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
 321    }
 322
 323    if (section_covers_addr(&sections[lp.ptr], addr)) {
 324        return &sections[lp.ptr];
 325    } else {
 326        return &sections[PHYS_SECTION_UNASSIGNED];
 327    }
 328}
 329
 330/* Called from RCU critical section */
 331static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
 332                                                        hwaddr addr,
 333                                                        bool resolve_subpage)
 334{
 335    MemoryRegionSection *section = qatomic_read(&d->mru_section);
 336    subpage_t *subpage;
 337
 338    if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
 339        !section_covers_addr(section, addr)) {
 340        section = phys_page_find(d, addr);
 341        qatomic_set(&d->mru_section, section);
 342    }
 343    if (resolve_subpage && section->mr->subpage) {
 344        subpage = container_of(section->mr, subpage_t, iomem);
 345        section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
 346    }
 347    return section;
 348}
 349
 350/* Called from RCU critical section */
 351static MemoryRegionSection *
 352address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
 353                                 hwaddr *plen, bool resolve_subpage)
 354{
 355    MemoryRegionSection *section;
 356    MemoryRegion *mr;
 357    Int128 diff;
 358
 359    section = address_space_lookup_region(d, addr, resolve_subpage);
 360    /* Compute offset within MemoryRegionSection */
 361    addr -= section->offset_within_address_space;
 362
 363    /* Compute offset within MemoryRegion */
 364    *xlat = addr + section->offset_within_region;
 365
 366    mr = section->mr;
 367
 368    /* MMIO registers can be expected to perform full-width accesses based only
 369     * on their address, without considering adjacent registers that could
 370     * decode to completely different MemoryRegions.  When such registers
 371     * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
 372     * regions overlap wildly.  For this reason we cannot clamp the accesses
 373     * here.
 374     *
 375     * If the length is small (as is the case for address_space_ldl/stl),
 376     * everything works fine.  If the incoming length is large, however,
 377     * the caller really has to do the clamping through memory_access_size.
 378     */
 379    if (memory_region_is_ram(mr)) {
 380        diff = int128_sub(section->size, int128_make64(addr));
 381        *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
 382    }
 383    return section;
 384}
 385
 386/**
 387 * address_space_translate_iommu - translate an address through an IOMMU
 388 * memory region and then through the target address space.
 389 *
 390 * @iommu_mr: the IOMMU memory region that we start the translation from
 391 * @addr: the address to be translated through the MMU
 392 * @xlat: the translated address offset within the destination memory region.
 393 *        It cannot be %NULL.
 394 * @plen_out: valid read/write length of the translated address. It
 395 *            cannot be %NULL.
 396 * @page_mask_out: page mask for the translated address. This
 397 *            should only be meaningful for IOMMU translated
 398 *            addresses, since there may be huge pages that this bit
 399 *            would tell. It can be %NULL if we don't care about it.
 400 * @is_write: whether the translation operation is for write
 401 * @is_mmio: whether this can be MMIO, set true if it can
 402 * @target_as: the address space targeted by the IOMMU
 403 * @attrs: transaction attributes
 404 *
 405 * This function is called from RCU critical section.  It is the common
 406 * part of flatview_do_translate and address_space_translate_cached.
 407 */
 408static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
 409                                                         hwaddr *xlat,
 410                                                         hwaddr *plen_out,
 411                                                         hwaddr *page_mask_out,
 412                                                         bool is_write,
 413                                                         bool is_mmio,
 414                                                         AddressSpace **target_as,
 415                                                         MemTxAttrs attrs)
 416{
 417    MemoryRegionSection *section;
 418    hwaddr page_mask = (hwaddr)-1;
 419
 420    do {
 421        hwaddr addr = *xlat;
 422        IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
 423        int iommu_idx = 0;
 424        IOMMUTLBEntry iotlb;
 425
 426        if (imrc->attrs_to_index) {
 427            iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
 428        }
 429
 430        iotlb = imrc->translate(iommu_mr, addr, is_write ?
 431                                IOMMU_WO : IOMMU_RO, iommu_idx);
 432
 433        if (!(iotlb.perm & (1 << is_write))) {
 434            goto unassigned;
 435        }
 436
 437        addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
 438                | (addr & iotlb.addr_mask));
 439        page_mask &= iotlb.addr_mask;
 440        *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
 441        *target_as = iotlb.target_as;
 442
 443        section = address_space_translate_internal(
 444                address_space_to_dispatch(iotlb.target_as), addr, xlat,
 445                plen_out, is_mmio);
 446
 447        iommu_mr = memory_region_get_iommu(section->mr);
 448    } while (unlikely(iommu_mr));
 449
 450    if (page_mask_out) {
 451        *page_mask_out = page_mask;
 452    }
 453    return *section;
 454
 455unassigned:
 456    return (MemoryRegionSection) { .mr = &io_mem_unassigned };
 457}
 458
 459/**
 460 * flatview_do_translate - translate an address in FlatView
 461 *
 462 * @fv: the flat view that we want to translate on
 463 * @addr: the address to be translated in above address space
 464 * @xlat: the translated address offset within memory region. It
 465 *        cannot be @NULL.
 466 * @plen_out: valid read/write length of the translated address. It
 467 *            can be @NULL when we don't care about it.
 468 * @page_mask_out: page mask for the translated address. This
 469 *            should only be meaningful for IOMMU translated
 470 *            addresses, since there may be huge pages that this bit
 471 *            would tell. It can be @NULL if we don't care about it.
 472 * @is_write: whether the translation operation is for write
 473 * @is_mmio: whether this can be MMIO, set true if it can
 474 * @target_as: the address space targeted by the IOMMU
 475 * @attrs: memory transaction attributes
 476 *
 477 * This function is called from RCU critical section
 478 */
 479static MemoryRegionSection flatview_do_translate(FlatView *fv,
 480                                                 hwaddr addr,
 481                                                 hwaddr *xlat,
 482                                                 hwaddr *plen_out,
 483                                                 hwaddr *page_mask_out,
 484                                                 bool is_write,
 485                                                 bool is_mmio,
 486                                                 AddressSpace **target_as,
 487                                                 MemTxAttrs attrs)
 488{
 489    MemoryRegionSection *section;
 490    IOMMUMemoryRegion *iommu_mr;
 491    hwaddr plen = (hwaddr)(-1);
 492
 493    if (!plen_out) {
 494        plen_out = &plen;
 495    }
 496
 497    section = address_space_translate_internal(
 498            flatview_to_dispatch(fv), addr, xlat,
 499            plen_out, is_mmio);
 500
 501    iommu_mr = memory_region_get_iommu(section->mr);
 502    if (unlikely(iommu_mr)) {
 503        return address_space_translate_iommu(iommu_mr, xlat,
 504                                             plen_out, page_mask_out,
 505                                             is_write, is_mmio,
 506                                             target_as, attrs);
 507    }
 508    if (page_mask_out) {
 509        /* Not behind an IOMMU, use default page size. */
 510        *page_mask_out = ~TARGET_PAGE_MASK;
 511    }
 512
 513    return *section;
 514}
 515
 516/* Called from RCU critical section */
 517IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
 518                                            bool is_write, MemTxAttrs attrs)
 519{
 520    MemoryRegionSection section;
 521    hwaddr xlat, page_mask;
 522
 523    /*
 524     * This can never be MMIO, and we don't really care about plen,
 525     * but page mask.
 526     */
 527    section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
 528                                    NULL, &page_mask, is_write, false, &as,
 529                                    attrs);
 530
 531    /* Illegal translation */
 532    if (section.mr == &io_mem_unassigned) {
 533        goto iotlb_fail;
 534    }
 535
 536    /* Convert memory region offset into address space offset */
 537    xlat += section.offset_within_address_space -
 538        section.offset_within_region;
 539
 540    return (IOMMUTLBEntry) {
 541        .target_as = as,
 542        .iova = addr & ~page_mask,
 543        .translated_addr = xlat & ~page_mask,
 544        .addr_mask = page_mask,
 545        /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
 546        .perm = IOMMU_RW,
 547    };
 548
 549iotlb_fail:
 550    return (IOMMUTLBEntry) {0};
 551}
 552
 553/* Called from RCU critical section */
 554MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
 555                                 hwaddr *plen, bool is_write,
 556                                 MemTxAttrs attrs)
 557{
 558    MemoryRegion *mr;
 559    MemoryRegionSection section;
 560    AddressSpace *as = NULL;
 561
 562    /* This can be MMIO, so setup MMIO bit. */
 563    section = flatview_do_translate(fv, addr, xlat, plen, NULL,
 564                                    is_write, true, &as, attrs);
 565    mr = section.mr;
 566
 567    if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
 568        hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
 569        *plen = MIN(page, *plen);
 570    }
 571
 572    return mr;
 573}
 574
 575typedef struct TCGIOMMUNotifier {
 576    IOMMUNotifier n;
 577    MemoryRegion *mr;
 578    CPUState *cpu;
 579    int iommu_idx;
 580    bool active;
 581} TCGIOMMUNotifier;
 582
 583static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
 584{
 585    TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
 586
 587    if (!notifier->active) {
 588        return;
 589    }
 590    tlb_flush(notifier->cpu);
 591    notifier->active = false;
 592    /* We leave the notifier struct on the list to avoid reallocating it later.
 593     * Generally the number of IOMMUs a CPU deals with will be small.
 594     * In any case we can't unregister the iommu notifier from a notify
 595     * callback.
 596     */
 597}
 598
 599static void tcg_register_iommu_notifier(CPUState *cpu,
 600                                        IOMMUMemoryRegion *iommu_mr,
 601                                        int iommu_idx)
 602{
 603    /* Make sure this CPU has an IOMMU notifier registered for this
 604     * IOMMU/IOMMU index combination, so that we can flush its TLB
 605     * when the IOMMU tells us the mappings we've cached have changed.
 606     */
 607    MemoryRegion *mr = MEMORY_REGION(iommu_mr);
 608    TCGIOMMUNotifier *notifier;
 609    int i;
 610
 611    for (i = 0; i < cpu->iommu_notifiers->len; i++) {
 612        notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
 613        if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
 614            break;
 615        }
 616    }
 617    if (i == cpu->iommu_notifiers->len) {
 618        /* Not found, add a new entry at the end of the array */
 619        cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
 620        notifier = g_new0(TCGIOMMUNotifier, 1);
 621        g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
 622
 623        notifier->mr = mr;
 624        notifier->iommu_idx = iommu_idx;
 625        notifier->cpu = cpu;
 626        /* Rather than trying to register interest in the specific part
 627         * of the iommu's address space that we've accessed and then
 628         * expand it later as subsequent accesses touch more of it, we
 629         * just register interest in the whole thing, on the assumption
 630         * that iommu reconfiguration will be rare.
 631         */
 632        iommu_notifier_init(&notifier->n,
 633                            tcg_iommu_unmap_notify,
 634                            IOMMU_NOTIFIER_UNMAP,
 635                            0,
 636                            HWADDR_MAX,
 637                            iommu_idx);
 638        memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
 639                                              &error_fatal);
 640    }
 641
 642    if (!notifier->active) {
 643        notifier->active = true;
 644    }
 645}
 646
 647void tcg_iommu_free_notifier_list(CPUState *cpu)
 648{
 649    /* Destroy the CPU's notifier list */
 650    int i;
 651    TCGIOMMUNotifier *notifier;
 652
 653    for (i = 0; i < cpu->iommu_notifiers->len; i++) {
 654        notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
 655        memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
 656        g_free(notifier);
 657    }
 658    g_array_free(cpu->iommu_notifiers, true);
 659}
 660
 661void tcg_iommu_init_notifier_list(CPUState *cpu)
 662{
 663    cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
 664}
 665
 666/* Called from RCU critical section */
 667MemoryRegionSection *
 668address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
 669                                  hwaddr *xlat, hwaddr *plen,
 670                                  MemTxAttrs attrs, int *prot)
 671{
 672    MemoryRegionSection *section;
 673    IOMMUMemoryRegion *iommu_mr;
 674    IOMMUMemoryRegionClass *imrc;
 675    IOMMUTLBEntry iotlb;
 676    int iommu_idx;
 677    AddressSpaceDispatch *d =
 678        qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
 679
 680    for (;;) {
 681        section = address_space_translate_internal(d, addr, &addr, plen, false);
 682
 683        iommu_mr = memory_region_get_iommu(section->mr);
 684        if (!iommu_mr) {
 685            break;
 686        }
 687
 688        imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
 689
 690        iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
 691        tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
 692        /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
 693         * doesn't short-cut its translation table walk.
 694         */
 695        iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
 696        addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
 697                | (addr & iotlb.addr_mask));
 698        /* Update the caller's prot bits to remove permissions the IOMMU
 699         * is giving us a failure response for. If we get down to no
 700         * permissions left at all we can give up now.
 701         */
 702        if (!(iotlb.perm & IOMMU_RO)) {
 703            *prot &= ~(PAGE_READ | PAGE_EXEC);
 704        }
 705        if (!(iotlb.perm & IOMMU_WO)) {
 706            *prot &= ~PAGE_WRITE;
 707        }
 708
 709        if (!*prot) {
 710            goto translate_fail;
 711        }
 712
 713        d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
 714    }
 715
 716    assert(!memory_region_is_iommu(section->mr));
 717    *xlat = addr;
 718    return section;
 719
 720translate_fail:
 721    return &d->map.sections[PHYS_SECTION_UNASSIGNED];
 722}
 723
 724void cpu_address_space_init(CPUState *cpu, int asidx,
 725                            const char *prefix, MemoryRegion *mr)
 726{
 727    CPUAddressSpace *newas;
 728    AddressSpace *as = g_new0(AddressSpace, 1);
 729    char *as_name;
 730
 731    assert(mr);
 732    as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
 733    address_space_init(as, mr, as_name);
 734    g_free(as_name);
 735
 736    /* Target code should have set num_ases before calling us */
 737    assert(asidx < cpu->num_ases);
 738
 739    if (asidx == 0) {
 740        /* address space 0 gets the convenience alias */
 741        cpu->as = as;
 742    }
 743
 744    /* KVM cannot currently support multiple address spaces. */
 745    assert(asidx == 0 || !kvm_enabled());
 746
 747    if (!cpu->cpu_ases) {
 748        cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
 749    }
 750
 751    newas = &cpu->cpu_ases[asidx];
 752    newas->cpu = cpu;
 753    newas->as = as;
 754    if (tcg_enabled()) {
 755        newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
 756        newas->tcg_as_listener.commit = tcg_commit;
 757        memory_listener_register(&newas->tcg_as_listener, as);
 758    }
 759}
 760
 761AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
 762{
 763    /* Return the AddressSpace corresponding to the specified index */
 764    return cpu->cpu_ases[asidx].as;
 765}
 766
 767/* Add a watchpoint.  */
 768int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
 769                          int flags, CPUWatchpoint **watchpoint)
 770{
 771    CPUWatchpoint *wp;
 772    vaddr in_page;
 773
 774    /* forbid ranges which are empty or run off the end of the address space */
 775    if (len == 0 || (addr + len - 1) < addr) {
 776        error_report("tried to set invalid watchpoint at %"
 777                     VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
 778        return -EINVAL;
 779    }
 780    wp = g_malloc(sizeof(*wp));
 781
 782    wp->vaddr = addr;
 783    wp->len = len;
 784    wp->flags = flags;
 785
 786    /* keep all GDB-injected watchpoints in front */
 787    if (flags & BP_GDB) {
 788        QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
 789    } else {
 790        QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
 791    }
 792
 793    in_page = -(addr | TARGET_PAGE_MASK);
 794    if (len <= in_page) {
 795        tlb_flush_page(cpu, addr);
 796    } else {
 797        tlb_flush(cpu);
 798    }
 799
 800    if (watchpoint)
 801        *watchpoint = wp;
 802    return 0;
 803}
 804
 805/* Remove a specific watchpoint.  */
 806int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
 807                          int flags)
 808{
 809    CPUWatchpoint *wp;
 810
 811    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
 812        if (addr == wp->vaddr && len == wp->len
 813                && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
 814            cpu_watchpoint_remove_by_ref(cpu, wp);
 815            return 0;
 816        }
 817    }
 818    return -ENOENT;
 819}
 820
 821/* Remove a specific watchpoint by reference.  */
 822void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
 823{
 824    QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
 825
 826    tlb_flush_page(cpu, watchpoint->vaddr);
 827
 828    g_free(watchpoint);
 829}
 830
 831/* Remove all matching watchpoints.  */
 832void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
 833{
 834    CPUWatchpoint *wp, *next;
 835
 836    QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
 837        if (wp->flags & mask) {
 838            cpu_watchpoint_remove_by_ref(cpu, wp);
 839        }
 840    }
 841}
 842
 843/* Return true if this watchpoint address matches the specified
 844 * access (ie the address range covered by the watchpoint overlaps
 845 * partially or completely with the address range covered by the
 846 * access).
 847 */
 848static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
 849                                              vaddr addr, vaddr len)
 850{
 851    /* We know the lengths are non-zero, but a little caution is
 852     * required to avoid errors in the case where the range ends
 853     * exactly at the top of the address space and so addr + len
 854     * wraps round to zero.
 855     */
 856    vaddr wpend = wp->vaddr + wp->len - 1;
 857    vaddr addrend = addr + len - 1;
 858
 859    return !(addr > wpend || wp->vaddr > addrend);
 860}
 861
 862/* Return flags for watchpoints that match addr + prot.  */
 863int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
 864{
 865    CPUWatchpoint *wp;
 866    int ret = 0;
 867
 868    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
 869        if (watchpoint_address_matches(wp, addr, len)) {
 870            ret |= wp->flags;
 871        }
 872    }
 873    return ret;
 874}
 875
 876/* Called from RCU critical section */
 877static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
 878{
 879    RAMBlock *block;
 880
 881    block = qatomic_rcu_read(&ram_list.mru_block);
 882    if (block && addr - block->offset < block->max_length) {
 883        return block;
 884    }
 885    RAMBLOCK_FOREACH(block) {
 886        if (addr - block->offset < block->max_length) {
 887            goto found;
 888        }
 889    }
 890
 891    fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
 892    abort();
 893
 894found:
 895    /* It is safe to write mru_block outside the iothread lock.  This
 896     * is what happens:
 897     *
 898     *     mru_block = xxx
 899     *     rcu_read_unlock()
 900     *                                        xxx removed from list
 901     *                  rcu_read_lock()
 902     *                  read mru_block
 903     *                                        mru_block = NULL;
 904     *                                        call_rcu(reclaim_ramblock, xxx);
 905     *                  rcu_read_unlock()
 906     *
 907     * qatomic_rcu_set is not needed here.  The block was already published
 908     * when it was placed into the list.  Here we're just making an extra
 909     * copy of the pointer.
 910     */
 911    ram_list.mru_block = block;
 912    return block;
 913}
 914
 915static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
 916{
 917    CPUState *cpu;
 918    ram_addr_t start1;
 919    RAMBlock *block;
 920    ram_addr_t end;
 921
 922    assert(tcg_enabled());
 923    end = TARGET_PAGE_ALIGN(start + length);
 924    start &= TARGET_PAGE_MASK;
 925
 926    RCU_READ_LOCK_GUARD();
 927    block = qemu_get_ram_block(start);
 928    assert(block == qemu_get_ram_block(end - 1));
 929    start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
 930    CPU_FOREACH(cpu) {
 931        tlb_reset_dirty(cpu, start1, length);
 932    }
 933}
 934
 935/* Note: start and end must be within the same ram block.  */
 936bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
 937                                              ram_addr_t length,
 938                                              unsigned client)
 939{
 940    DirtyMemoryBlocks *blocks;
 941    unsigned long end, page, start_page;
 942    bool dirty = false;
 943    RAMBlock *ramblock;
 944    uint64_t mr_offset, mr_size;
 945
 946    if (length == 0) {
 947        return false;
 948    }
 949
 950    end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
 951    start_page = start >> TARGET_PAGE_BITS;
 952    page = start_page;
 953
 954    WITH_RCU_READ_LOCK_GUARD() {
 955        blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
 956        ramblock = qemu_get_ram_block(start);
 957        /* Range sanity check on the ramblock */
 958        assert(start >= ramblock->offset &&
 959               start + length <= ramblock->offset + ramblock->used_length);
 960
 961        while (page < end) {
 962            unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
 963            unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
 964            unsigned long num = MIN(end - page,
 965                                    DIRTY_MEMORY_BLOCK_SIZE - offset);
 966
 967            dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
 968                                                  offset, num);
 969            page += num;
 970        }
 971
 972        mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
 973        mr_size = (end - start_page) << TARGET_PAGE_BITS;
 974        memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
 975    }
 976
 977    if (dirty && tcg_enabled()) {
 978        tlb_reset_dirty_range_all(start, length);
 979    }
 980
 981    return dirty;
 982}
 983
 984DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
 985    (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
 986{
 987    DirtyMemoryBlocks *blocks;
 988    ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
 989    unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
 990    ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
 991    ram_addr_t last  = QEMU_ALIGN_UP(start + length, align);
 992    DirtyBitmapSnapshot *snap;
 993    unsigned long page, end, dest;
 994
 995    snap = g_malloc0(sizeof(*snap) +
 996                     ((last - first) >> (TARGET_PAGE_BITS + 3)));
 997    snap->start = first;
 998    snap->end   = last;
 999
1000    page = first >> TARGET_PAGE_BITS;
1001    end  = last  >> TARGET_PAGE_BITS;
1002    dest = 0;
1003
1004    WITH_RCU_READ_LOCK_GUARD() {
1005        blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1006
1007        while (page < end) {
1008            unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1009            unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1010            unsigned long num = MIN(end - page,
1011                                    DIRTY_MEMORY_BLOCK_SIZE - offset);
1012
1013            assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1014            assert(QEMU_IS_ALIGNED(num,    (1 << BITS_PER_LEVEL)));
1015            offset >>= BITS_PER_LEVEL;
1016
1017            bitmap_copy_and_clear_atomic(snap->dirty + dest,
1018                                         blocks->blocks[idx] + offset,
1019                                         num);
1020            page += num;
1021            dest += num >> BITS_PER_LEVEL;
1022        }
1023    }
1024
1025    if (tcg_enabled()) {
1026        tlb_reset_dirty_range_all(start, length);
1027    }
1028
1029    memory_region_clear_dirty_bitmap(mr, offset, length);
1030
1031    return snap;
1032}
1033
1034bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1035                                            ram_addr_t start,
1036                                            ram_addr_t length)
1037{
1038    unsigned long page, end;
1039
1040    assert(start >= snap->start);
1041    assert(start + length <= snap->end);
1042
1043    end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1044    page = (start - snap->start) >> TARGET_PAGE_BITS;
1045
1046    while (page < end) {
1047        if (test_bit(page, snap->dirty)) {
1048            return true;
1049        }
1050        page++;
1051    }
1052    return false;
1053}
1054
1055/* Called from RCU critical section */
1056hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1057                                       MemoryRegionSection *section)
1058{
1059    AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1060    return section - d->map.sections;
1061}
1062
1063static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1064                            uint16_t section);
1065static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1066
1067static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1068                               qemu_anon_ram_alloc;
1069
1070/*
1071 * Set a custom physical guest memory alloator.
1072 * Accelerators with unusual needs may need this.  Hopefully, we can
1073 * get rid of it eventually.
1074 */
1075void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1076{
1077    phys_mem_alloc = alloc;
1078}
1079
1080static uint16_t phys_section_add(PhysPageMap *map,
1081                                 MemoryRegionSection *section)
1082{
1083    /* The physical section number is ORed with a page-aligned
1084     * pointer to produce the iotlb entries.  Thus it should
1085     * never overflow into the page-aligned value.
1086     */
1087    assert(map->sections_nb < TARGET_PAGE_SIZE);
1088
1089    if (map->sections_nb == map->sections_nb_alloc) {
1090        map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1091        map->sections = g_renew(MemoryRegionSection, map->sections,
1092                                map->sections_nb_alloc);
1093    }
1094    map->sections[map->sections_nb] = *section;
1095    memory_region_ref(section->mr);
1096    return map->sections_nb++;
1097}
1098
1099static void phys_section_destroy(MemoryRegion *mr)
1100{
1101    bool have_sub_page = mr->subpage;
1102
1103    memory_region_unref(mr);
1104
1105    if (have_sub_page) {
1106        subpage_t *subpage = container_of(mr, subpage_t, iomem);
1107        object_unref(OBJECT(&subpage->iomem));
1108        g_free(subpage);
1109    }
1110}
1111
1112static void phys_sections_free(PhysPageMap *map)
1113{
1114    while (map->sections_nb > 0) {
1115        MemoryRegionSection *section = &map->sections[--map->sections_nb];
1116        phys_section_destroy(section->mr);
1117    }
1118    g_free(map->sections);
1119    g_free(map->nodes);
1120}
1121
1122static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1123{
1124    AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1125    subpage_t *subpage;
1126    hwaddr base = section->offset_within_address_space
1127        & TARGET_PAGE_MASK;
1128    MemoryRegionSection *existing = phys_page_find(d, base);
1129    MemoryRegionSection subsection = {
1130        .offset_within_address_space = base,
1131        .size = int128_make64(TARGET_PAGE_SIZE),
1132    };
1133    hwaddr start, end;
1134
1135    assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1136
1137    if (!(existing->mr->subpage)) {
1138        subpage = subpage_init(fv, base);
1139        subsection.fv = fv;
1140        subsection.mr = &subpage->iomem;
1141        phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1142                      phys_section_add(&d->map, &subsection));
1143    } else {
1144        subpage = container_of(existing->mr, subpage_t, iomem);
1145    }
1146    start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1147    end = start + int128_get64(section->size) - 1;
1148    subpage_register(subpage, start, end,
1149                     phys_section_add(&d->map, section));
1150}
1151
1152
1153static void register_multipage(FlatView *fv,
1154                               MemoryRegionSection *section)
1155{
1156    AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1157    hwaddr start_addr = section->offset_within_address_space;
1158    uint16_t section_index = phys_section_add(&d->map, section);
1159    uint64_t num_pages = int128_get64(int128_rshift(section->size,
1160                                                    TARGET_PAGE_BITS));
1161
1162    assert(num_pages);
1163    phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1164}
1165
1166/*
1167 * The range in *section* may look like this:
1168 *
1169 *      |s|PPPPPPP|s|
1170 *
1171 * where s stands for subpage and P for page.
1172 */
1173void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1174{
1175    MemoryRegionSection remain = *section;
1176    Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1177
1178    /* register first subpage */
1179    if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1180        uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1181                        - remain.offset_within_address_space;
1182
1183        MemoryRegionSection now = remain;
1184        now.size = int128_min(int128_make64(left), now.size);
1185        register_subpage(fv, &now);
1186        if (int128_eq(remain.size, now.size)) {
1187            return;
1188        }
1189        remain.size = int128_sub(remain.size, now.size);
1190        remain.offset_within_address_space += int128_get64(now.size);
1191        remain.offset_within_region += int128_get64(now.size);
1192    }
1193
1194    /* register whole pages */
1195    if (int128_ge(remain.size, page_size)) {
1196        MemoryRegionSection now = remain;
1197        now.size = int128_and(now.size, int128_neg(page_size));
1198        register_multipage(fv, &now);
1199        if (int128_eq(remain.size, now.size)) {
1200            return;
1201        }
1202        remain.size = int128_sub(remain.size, now.size);
1203        remain.offset_within_address_space += int128_get64(now.size);
1204        remain.offset_within_region += int128_get64(now.size);
1205    }
1206
1207    /* register last subpage */
1208    register_subpage(fv, &remain);
1209}
1210
1211void qemu_flush_coalesced_mmio_buffer(void)
1212{
1213    if (kvm_enabled())
1214        kvm_flush_coalesced_mmio_buffer();
1215}
1216
1217void qemu_mutex_lock_ramlist(void)
1218{
1219    qemu_mutex_lock(&ram_list.mutex);
1220}
1221
1222void qemu_mutex_unlock_ramlist(void)
1223{
1224    qemu_mutex_unlock(&ram_list.mutex);
1225}
1226
1227void ram_block_dump(Monitor *mon)
1228{
1229    RAMBlock *block;
1230    char *psize;
1231
1232    RCU_READ_LOCK_GUARD();
1233    monitor_printf(mon, "%24s %8s  %18s %18s %18s\n",
1234                   "Block Name", "PSize", "Offset", "Used", "Total");
1235    RAMBLOCK_FOREACH(block) {
1236        psize = size_to_str(block->page_size);
1237        monitor_printf(mon, "%24s %8s  0x%016" PRIx64 " 0x%016" PRIx64
1238                       " 0x%016" PRIx64 "\n", block->idstr, psize,
1239                       (uint64_t)block->offset,
1240                       (uint64_t)block->used_length,
1241                       (uint64_t)block->max_length);
1242        g_free(psize);
1243    }
1244}
1245
1246#ifdef __linux__
1247/*
1248 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1249 * may or may not name the same files / on the same filesystem now as
1250 * when we actually open and map them.  Iterate over the file
1251 * descriptors instead, and use qemu_fd_getpagesize().
1252 */
1253static int find_min_backend_pagesize(Object *obj, void *opaque)
1254{
1255    long *hpsize_min = opaque;
1256
1257    if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1258        HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1259        long hpsize = host_memory_backend_pagesize(backend);
1260
1261        if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1262            *hpsize_min = hpsize;
1263        }
1264    }
1265
1266    return 0;
1267}
1268
1269static int find_max_backend_pagesize(Object *obj, void *opaque)
1270{
1271    long *hpsize_max = opaque;
1272
1273    if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1274        HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1275        long hpsize = host_memory_backend_pagesize(backend);
1276
1277        if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1278            *hpsize_max = hpsize;
1279        }
1280    }
1281
1282    return 0;
1283}
1284
1285/*
1286 * TODO: We assume right now that all mapped host memory backends are
1287 * used as RAM, however some might be used for different purposes.
1288 */
1289long qemu_minrampagesize(void)
1290{
1291    long hpsize = LONG_MAX;
1292    Object *memdev_root = object_resolve_path("/objects", NULL);
1293
1294    object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1295    return hpsize;
1296}
1297
1298long qemu_maxrampagesize(void)
1299{
1300    long pagesize = 0;
1301    Object *memdev_root = object_resolve_path("/objects", NULL);
1302
1303    object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1304    return pagesize;
1305}
1306#else
1307long qemu_minrampagesize(void)
1308{
1309    return qemu_real_host_page_size;
1310}
1311long qemu_maxrampagesize(void)
1312{
1313    return qemu_real_host_page_size;
1314}
1315#endif
1316
1317#ifdef CONFIG_POSIX
1318static int64_t get_file_size(int fd)
1319{
1320    int64_t size;
1321#if defined(__linux__)
1322    struct stat st;
1323
1324    if (fstat(fd, &st) < 0) {
1325        return -errno;
1326    }
1327
1328    /* Special handling for devdax character devices */
1329    if (S_ISCHR(st.st_mode)) {
1330        g_autofree char *subsystem_path = NULL;
1331        g_autofree char *subsystem = NULL;
1332
1333        subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1334                                         major(st.st_rdev), minor(st.st_rdev));
1335        subsystem = g_file_read_link(subsystem_path, NULL);
1336
1337        if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1338            g_autofree char *size_path = NULL;
1339            g_autofree char *size_str = NULL;
1340
1341            size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1342                                    major(st.st_rdev), minor(st.st_rdev));
1343
1344            if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1345                return g_ascii_strtoll(size_str, NULL, 0);
1346            }
1347        }
1348    }
1349#endif /* defined(__linux__) */
1350
1351    /* st.st_size may be zero for special files yet lseek(2) works */
1352    size = lseek(fd, 0, SEEK_END);
1353    if (size < 0) {
1354        return -errno;
1355    }
1356    return size;
1357}
1358
1359static int64_t get_file_align(int fd)
1360{
1361    int64_t align = -1;
1362#if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1363    struct stat st;
1364
1365    if (fstat(fd, &st) < 0) {
1366        return -errno;
1367    }
1368
1369    /* Special handling for devdax character devices */
1370    if (S_ISCHR(st.st_mode)) {
1371        g_autofree char *path = NULL;
1372        g_autofree char *rpath = NULL;
1373        struct daxctl_ctx *ctx;
1374        struct daxctl_region *region;
1375        int rc = 0;
1376
1377        path = g_strdup_printf("/sys/dev/char/%d:%d",
1378                    major(st.st_rdev), minor(st.st_rdev));
1379        rpath = realpath(path, NULL);
1380
1381        rc = daxctl_new(&ctx);
1382        if (rc) {
1383            return -1;
1384        }
1385
1386        daxctl_region_foreach(ctx, region) {
1387            if (strstr(rpath, daxctl_region_get_path(region))) {
1388                align = daxctl_region_get_align(region);
1389                break;
1390            }
1391        }
1392        daxctl_unref(ctx);
1393    }
1394#endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1395
1396    return align;
1397}
1398
1399static int file_ram_open(const char *path,
1400                         const char *region_name,
1401                         bool *created,
1402                         Error **errp)
1403{
1404    char *filename;
1405    char *sanitized_name;
1406    char *c;
1407    int fd = -1;
1408
1409    *created = false;
1410    for (;;) {
1411        fd = open(path, O_RDWR);
1412        if (fd >= 0) {
1413            /* @path names an existing file, use it */
1414            break;
1415        }
1416        if (errno == ENOENT) {
1417            /* @path names a file that doesn't exist, create it */
1418            fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1419            if (fd >= 0) {
1420                *created = true;
1421                break;
1422            }
1423        } else if (errno == EISDIR) {
1424            /* @path names a directory, create a file there */
1425            /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1426            sanitized_name = g_strdup(region_name);
1427            for (c = sanitized_name; *c != '\0'; c++) {
1428                if (*c == '/') {
1429                    *c = '_';
1430                }
1431            }
1432
1433            filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1434                                       sanitized_name);
1435            g_free(sanitized_name);
1436
1437            fd = mkstemp(filename);
1438            if (fd >= 0) {
1439                unlink(filename);
1440                g_free(filename);
1441                break;
1442            }
1443            g_free(filename);
1444        }
1445        if (errno != EEXIST && errno != EINTR) {
1446            error_setg_errno(errp, errno,
1447                             "can't open backing store %s for guest RAM",
1448                             path);
1449            return -1;
1450        }
1451        /*
1452         * Try again on EINTR and EEXIST.  The latter happens when
1453         * something else creates the file between our two open().
1454         */
1455    }
1456
1457    return fd;
1458}
1459
1460static void *file_ram_alloc(RAMBlock *block,
1461                            ram_addr_t memory,
1462                            int fd,
1463                            bool truncate,
1464                            Error **errp)
1465{
1466    void *area;
1467
1468    block->page_size = qemu_fd_getpagesize(fd);
1469    if (block->mr->align % block->page_size) {
1470        error_setg(errp, "alignment 0x%" PRIx64
1471                   " must be multiples of page size 0x%zx",
1472                   block->mr->align, block->page_size);
1473        return NULL;
1474    } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1475        error_setg(errp, "alignment 0x%" PRIx64
1476                   " must be a power of two", block->mr->align);
1477        return NULL;
1478    }
1479    block->mr->align = MAX(block->page_size, block->mr->align);
1480#if defined(__s390x__)
1481    if (kvm_enabled()) {
1482        block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1483    }
1484#endif
1485
1486    if (memory < block->page_size) {
1487        error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1488                   "or larger than page size 0x%zx",
1489                   memory, block->page_size);
1490        return NULL;
1491    }
1492
1493    memory = ROUND_UP(memory, block->page_size);
1494
1495    /*
1496     * ftruncate is not supported by hugetlbfs in older
1497     * hosts, so don't bother bailing out on errors.
1498     * If anything goes wrong with it under other filesystems,
1499     * mmap will fail.
1500     *
1501     * Do not truncate the non-empty backend file to avoid corrupting
1502     * the existing data in the file. Disabling shrinking is not
1503     * enough. For example, the current vNVDIMM implementation stores
1504     * the guest NVDIMM labels at the end of the backend file. If the
1505     * backend file is later extended, QEMU will not be able to find
1506     * those labels. Therefore, extending the non-empty backend file
1507     * is disabled as well.
1508     */
1509    if (truncate && ftruncate(fd, memory)) {
1510        perror("ftruncate");
1511    }
1512
1513    area = qemu_ram_mmap(fd, memory, block->mr->align,
1514                         block->flags & RAM_SHARED, block->flags & RAM_PMEM);
1515    if (area == MAP_FAILED) {
1516        error_setg_errno(errp, errno,
1517                         "unable to map backing store for guest RAM");
1518        return NULL;
1519    }
1520
1521    block->fd = fd;
1522    return area;
1523}
1524#endif
1525
1526/* Allocate space within the ram_addr_t space that governs the
1527 * dirty bitmaps.
1528 * Called with the ramlist lock held.
1529 */
1530static ram_addr_t find_ram_offset(ram_addr_t size)
1531{
1532    RAMBlock *block, *next_block;
1533    ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1534
1535    assert(size != 0); /* it would hand out same offset multiple times */
1536
1537    if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1538        return 0;
1539    }
1540
1541    RAMBLOCK_FOREACH(block) {
1542        ram_addr_t candidate, next = RAM_ADDR_MAX;
1543
1544        /* Align blocks to start on a 'long' in the bitmap
1545         * which makes the bitmap sync'ing take the fast path.
1546         */
1547        candidate = block->offset + block->max_length;
1548        candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1549
1550        /* Search for the closest following block
1551         * and find the gap.
1552         */
1553        RAMBLOCK_FOREACH(next_block) {
1554            if (next_block->offset >= candidate) {
1555                next = MIN(next, next_block->offset);
1556            }
1557        }
1558
1559        /* If it fits remember our place and remember the size
1560         * of gap, but keep going so that we might find a smaller
1561         * gap to fill so avoiding fragmentation.
1562         */
1563        if (next - candidate >= size && next - candidate < mingap) {
1564            offset = candidate;
1565            mingap = next - candidate;
1566        }
1567
1568        trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1569    }
1570
1571    if (offset == RAM_ADDR_MAX) {
1572        fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1573                (uint64_t)size);
1574        abort();
1575    }
1576
1577    trace_find_ram_offset(size, offset);
1578
1579    return offset;
1580}
1581
1582static unsigned long last_ram_page(void)
1583{
1584    RAMBlock *block;
1585    ram_addr_t last = 0;
1586
1587    RCU_READ_LOCK_GUARD();
1588    RAMBLOCK_FOREACH(block) {
1589        last = MAX(last, block->offset + block->max_length);
1590    }
1591    return last >> TARGET_PAGE_BITS;
1592}
1593
1594static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1595{
1596    int ret;
1597
1598    /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1599    if (!machine_dump_guest_core(current_machine)) {
1600        ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1601        if (ret) {
1602            perror("qemu_madvise");
1603            fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1604                            "but dump_guest_core=off specified\n");
1605        }
1606    }
1607}
1608
1609const char *qemu_ram_get_idstr(RAMBlock *rb)
1610{
1611    return rb->idstr;
1612}
1613
1614void *qemu_ram_get_host_addr(RAMBlock *rb)
1615{
1616    return rb->host;
1617}
1618
1619ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1620{
1621    return rb->offset;
1622}
1623
1624ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1625{
1626    return rb->used_length;
1627}
1628
1629bool qemu_ram_is_shared(RAMBlock *rb)
1630{
1631    return rb->flags & RAM_SHARED;
1632}
1633
1634/* Note: Only set at the start of postcopy */
1635bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1636{
1637    return rb->flags & RAM_UF_ZEROPAGE;
1638}
1639
1640void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1641{
1642    rb->flags |= RAM_UF_ZEROPAGE;
1643}
1644
1645bool qemu_ram_is_migratable(RAMBlock *rb)
1646{
1647    return rb->flags & RAM_MIGRATABLE;
1648}
1649
1650void qemu_ram_set_migratable(RAMBlock *rb)
1651{
1652    rb->flags |= RAM_MIGRATABLE;
1653}
1654
1655void qemu_ram_unset_migratable(RAMBlock *rb)
1656{
1657    rb->flags &= ~RAM_MIGRATABLE;
1658}
1659
1660/* Called with iothread lock held.  */
1661void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1662{
1663    RAMBlock *block;
1664
1665    assert(new_block);
1666    assert(!new_block->idstr[0]);
1667
1668    if (dev) {
1669        char *id = qdev_get_dev_path(dev);
1670        if (id) {
1671            snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1672            g_free(id);
1673        }
1674    }
1675    pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1676
1677    RCU_READ_LOCK_GUARD();
1678    RAMBLOCK_FOREACH(block) {
1679        if (block != new_block &&
1680            !strcmp(block->idstr, new_block->idstr)) {
1681            fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1682                    new_block->idstr);
1683            abort();
1684        }
1685    }
1686}
1687
1688/* Called with iothread lock held.  */
1689void qemu_ram_unset_idstr(RAMBlock *block)
1690{
1691    /* FIXME: arch_init.c assumes that this is not called throughout
1692     * migration.  Ignore the problem since hot-unplug during migration
1693     * does not work anyway.
1694     */
1695    if (block) {
1696        memset(block->idstr, 0, sizeof(block->idstr));
1697    }
1698}
1699
1700size_t qemu_ram_pagesize(RAMBlock *rb)
1701{
1702    return rb->page_size;
1703}
1704
1705/* Returns the largest size of page in use */
1706size_t qemu_ram_pagesize_largest(void)
1707{
1708    RAMBlock *block;
1709    size_t largest = 0;
1710
1711    RAMBLOCK_FOREACH(block) {
1712        largest = MAX(largest, qemu_ram_pagesize(block));
1713    }
1714
1715    return largest;
1716}
1717
1718static int memory_try_enable_merging(void *addr, size_t len)
1719{
1720    if (!machine_mem_merge(current_machine)) {
1721        /* disabled by the user */
1722        return 0;
1723    }
1724
1725    return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1726}
1727
1728/* Only legal before guest might have detected the memory size: e.g. on
1729 * incoming migration, or right after reset.
1730 *
1731 * As memory core doesn't know how is memory accessed, it is up to
1732 * resize callback to update device state and/or add assertions to detect
1733 * misuse, if necessary.
1734 */
1735int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1736{
1737    const ram_addr_t unaligned_size = newsize;
1738
1739    assert(block);
1740
1741    newsize = HOST_PAGE_ALIGN(newsize);
1742
1743    if (block->used_length == newsize) {
1744        /*
1745         * We don't have to resize the ram block (which only knows aligned
1746         * sizes), however, we have to notify if the unaligned size changed.
1747         */
1748        if (unaligned_size != memory_region_size(block->mr)) {
1749            memory_region_set_size(block->mr, unaligned_size);
1750            if (block->resized) {
1751                block->resized(block->idstr, unaligned_size, block->host);
1752            }
1753        }
1754        return 0;
1755    }
1756
1757    if (!(block->flags & RAM_RESIZEABLE)) {
1758        error_setg_errno(errp, EINVAL,
1759                         "Size mismatch: %s: 0x" RAM_ADDR_FMT
1760                         " != 0x" RAM_ADDR_FMT, block->idstr,
1761                         newsize, block->used_length);
1762        return -EINVAL;
1763    }
1764
1765    if (block->max_length < newsize) {
1766        error_setg_errno(errp, EINVAL,
1767                         "Size too large: %s: 0x" RAM_ADDR_FMT
1768                         " > 0x" RAM_ADDR_FMT, block->idstr,
1769                         newsize, block->max_length);
1770        return -EINVAL;
1771    }
1772
1773    cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1774    block->used_length = newsize;
1775    cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1776                                        DIRTY_CLIENTS_ALL);
1777    memory_region_set_size(block->mr, unaligned_size);
1778    if (block->resized) {
1779        block->resized(block->idstr, unaligned_size, block->host);
1780    }
1781    return 0;
1782}
1783
1784/*
1785 * Trigger sync on the given ram block for range [start, start + length]
1786 * with the backing store if one is available.
1787 * Otherwise no-op.
1788 * @Note: this is supposed to be a synchronous op.
1789 */
1790void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1791{
1792    /* The requested range should fit in within the block range */
1793    g_assert((start + length) <= block->used_length);
1794
1795#ifdef CONFIG_LIBPMEM
1796    /* The lack of support for pmem should not block the sync */
1797    if (ramblock_is_pmem(block)) {
1798        void *addr = ramblock_ptr(block, start);
1799        pmem_persist(addr, length);
1800        return;
1801    }
1802#endif
1803    if (block->fd >= 0) {
1804        /**
1805         * Case there is no support for PMEM or the memory has not been
1806         * specified as persistent (or is not one) - use the msync.
1807         * Less optimal but still achieves the same goal
1808         */
1809        void *addr = ramblock_ptr(block, start);
1810        if (qemu_msync(addr, length, block->fd)) {
1811            warn_report("%s: failed to sync memory range: start: "
1812                    RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1813                    __func__, start, length);
1814        }
1815    }
1816}
1817
1818/* Called with ram_list.mutex held */
1819static void dirty_memory_extend(ram_addr_t old_ram_size,
1820                                ram_addr_t new_ram_size)
1821{
1822    ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1823                                             DIRTY_MEMORY_BLOCK_SIZE);
1824    ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1825                                             DIRTY_MEMORY_BLOCK_SIZE);
1826    int i;
1827
1828    /* Only need to extend if block count increased */
1829    if (new_num_blocks <= old_num_blocks) {
1830        return;
1831    }
1832
1833    for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1834        DirtyMemoryBlocks *old_blocks;
1835        DirtyMemoryBlocks *new_blocks;
1836        int j;
1837
1838        old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1839        new_blocks = g_malloc(sizeof(*new_blocks) +
1840                              sizeof(new_blocks->blocks[0]) * new_num_blocks);
1841
1842        if (old_num_blocks) {
1843            memcpy(new_blocks->blocks, old_blocks->blocks,
1844                   old_num_blocks * sizeof(old_blocks->blocks[0]));
1845        }
1846
1847        for (j = old_num_blocks; j < new_num_blocks; j++) {
1848            new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1849        }
1850
1851        qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1852
1853        if (old_blocks) {
1854            g_free_rcu(old_blocks, rcu);
1855        }
1856    }
1857}
1858
1859static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1860{
1861    RAMBlock *block;
1862    RAMBlock *last_block = NULL;
1863    ram_addr_t old_ram_size, new_ram_size;
1864    Error *err = NULL;
1865
1866    old_ram_size = last_ram_page();
1867
1868    qemu_mutex_lock_ramlist();
1869    new_block->offset = find_ram_offset(new_block->max_length);
1870
1871    if (!new_block->host) {
1872        if (xen_enabled()) {
1873            xen_ram_alloc(new_block->offset, new_block->max_length,
1874                          new_block->mr, &err);
1875            if (err) {
1876                error_propagate(errp, err);
1877                qemu_mutex_unlock_ramlist();
1878                return;
1879            }
1880        } else {
1881            new_block->host = phys_mem_alloc(new_block->max_length,
1882                                             &new_block->mr->align, shared);
1883            if (!new_block->host) {
1884                error_setg_errno(errp, errno,
1885                                 "cannot set up guest memory '%s'",
1886                                 memory_region_name(new_block->mr));
1887                qemu_mutex_unlock_ramlist();
1888                return;
1889            }
1890            memory_try_enable_merging(new_block->host, new_block->max_length);
1891        }
1892    }
1893
1894    new_ram_size = MAX(old_ram_size,
1895              (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1896    if (new_ram_size > old_ram_size) {
1897        dirty_memory_extend(old_ram_size, new_ram_size);
1898    }
1899    /* Keep the list sorted from biggest to smallest block.  Unlike QTAILQ,
1900     * QLIST (which has an RCU-friendly variant) does not have insertion at
1901     * tail, so save the last element in last_block.
1902     */
1903    RAMBLOCK_FOREACH(block) {
1904        last_block = block;
1905        if (block->max_length < new_block->max_length) {
1906            break;
1907        }
1908    }
1909    if (block) {
1910        QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1911    } else if (last_block) {
1912        QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1913    } else { /* list is empty */
1914        QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1915    }
1916    ram_list.mru_block = NULL;
1917
1918    /* Write list before version */
1919    smp_wmb();
1920    ram_list.version++;
1921    qemu_mutex_unlock_ramlist();
1922
1923    cpu_physical_memory_set_dirty_range(new_block->offset,
1924                                        new_block->used_length,
1925                                        DIRTY_CLIENTS_ALL);
1926
1927    if (new_block->host) {
1928        qemu_ram_setup_dump(new_block->host, new_block->max_length);
1929        qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1930        /*
1931         * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1932         * Configure it unless the machine is a qtest server, in which case
1933         * KVM is not used and it may be forked (eg for fuzzing purposes).
1934         */
1935        if (!qtest_enabled()) {
1936            qemu_madvise(new_block->host, new_block->max_length,
1937                         QEMU_MADV_DONTFORK);
1938        }
1939        ram_block_notify_add(new_block->host, new_block->max_length);
1940    }
1941}
1942
1943#ifdef CONFIG_POSIX
1944RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
1945                                 uint32_t ram_flags, int fd,
1946                                 Error **errp)
1947{
1948    RAMBlock *new_block;
1949    Error *local_err = NULL;
1950    int64_t file_size, file_align;
1951
1952    /* Just support these ram flags by now. */
1953    assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
1954
1955    if (xen_enabled()) {
1956        error_setg(errp, "-mem-path not supported with Xen");
1957        return NULL;
1958    }
1959
1960    if (kvm_enabled() && !kvm_has_sync_mmu()) {
1961        error_setg(errp,
1962                   "host lacks kvm mmu notifiers, -mem-path unsupported");
1963        return NULL;
1964    }
1965
1966    if (phys_mem_alloc != qemu_anon_ram_alloc) {
1967        /*
1968         * file_ram_alloc() needs to allocate just like
1969         * phys_mem_alloc, but we haven't bothered to provide
1970         * a hook there.
1971         */
1972        error_setg(errp,
1973                   "-mem-path not supported with this accelerator");
1974        return NULL;
1975    }
1976
1977    size = HOST_PAGE_ALIGN(size);
1978    file_size = get_file_size(fd);
1979    if (file_size > 0 && file_size < size) {
1980        error_setg(errp, "backing store size 0x%" PRIx64
1981                   " does not match 'size' option 0x" RAM_ADDR_FMT,
1982                   file_size, size);
1983        return NULL;
1984    }
1985
1986    file_align = get_file_align(fd);
1987    if (file_align > 0 && mr && file_align > mr->align) {
1988        error_setg(errp, "backing store align 0x%" PRIx64
1989                   " is larger than 'align' option 0x%" PRIx64,
1990                   file_align, mr->align);
1991        return NULL;
1992    }
1993
1994    new_block = g_malloc0(sizeof(*new_block));
1995    new_block->mr = mr;
1996    new_block->used_length = size;
1997    new_block->max_length = size;
1998    new_block->flags = ram_flags;
1999    new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2000    if (!new_block->host) {
2001        g_free(new_block);
2002        return NULL;
2003    }
2004
2005    ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2006    if (local_err) {
2007        g_free(new_block);
2008        error_propagate(errp, local_err);
2009        return NULL;
2010    }
2011    return new_block;
2012
2013}
2014
2015
2016RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2017                                   uint32_t ram_flags, const char *mem_path,
2018                                   Error **errp)
2019{
2020    int fd;
2021    bool created;
2022    RAMBlock *block;
2023
2024    fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2025    if (fd < 0) {
2026        return NULL;
2027    }
2028
2029    block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, errp);
2030    if (!block) {
2031        if (created) {
2032            unlink(mem_path);
2033        }
2034        close(fd);
2035        return NULL;
2036    }
2037
2038    return block;
2039}
2040#endif
2041
2042static
2043RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2044                                  void (*resized)(const char*,
2045                                                  uint64_t length,
2046                                                  void *host),
2047                                  void *host, bool resizeable, bool share,
2048                                  MemoryRegion *mr, Error **errp)
2049{
2050    RAMBlock *new_block;
2051    Error *local_err = NULL;
2052
2053    size = HOST_PAGE_ALIGN(size);
2054    max_size = HOST_PAGE_ALIGN(max_size);
2055    new_block = g_malloc0(sizeof(*new_block));
2056    new_block->mr = mr;
2057    new_block->resized = resized;
2058    new_block->used_length = size;
2059    new_block->max_length = max_size;
2060    assert(max_size >= size);
2061    new_block->fd = -1;
2062    new_block->page_size = qemu_real_host_page_size;
2063    new_block->host = host;
2064    if (host) {
2065        new_block->flags |= RAM_PREALLOC;
2066    }
2067    if (resizeable) {
2068        new_block->flags |= RAM_RESIZEABLE;
2069    }
2070    ram_block_add(new_block, &local_err, share);
2071    if (local_err) {
2072        g_free(new_block);
2073        error_propagate(errp, local_err);
2074        return NULL;
2075    }
2076    return new_block;
2077}
2078
2079RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2080                                   MemoryRegion *mr, Error **errp)
2081{
2082    return qemu_ram_alloc_internal(size, size, NULL, host, false,
2083                                   false, mr, errp);
2084}
2085
2086RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2087                         MemoryRegion *mr, Error **errp)
2088{
2089    return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2090                                   share, mr, errp);
2091}
2092
2093RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2094                                     void (*resized)(const char*,
2095                                                     uint64_t length,
2096                                                     void *host),
2097                                     MemoryRegion *mr, Error **errp)
2098{
2099    return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2100                                   false, mr, errp);
2101}
2102
2103static void reclaim_ramblock(RAMBlock *block)
2104{
2105    if (block->flags & RAM_PREALLOC) {
2106        ;
2107    } else if (xen_enabled()) {
2108        xen_invalidate_map_cache_entry(block->host);
2109#ifndef _WIN32
2110    } else if (block->fd >= 0) {
2111        qemu_ram_munmap(block->fd, block->host, block->max_length);
2112        close(block->fd);
2113#endif
2114    } else {
2115        qemu_anon_ram_free(block->host, block->max_length);
2116    }
2117    g_free(block);
2118}
2119
2120void qemu_ram_free(RAMBlock *block)
2121{
2122    if (!block) {
2123        return;
2124    }
2125
2126    if (block->host) {
2127        ram_block_notify_remove(block->host, block->max_length);
2128    }
2129
2130    qemu_mutex_lock_ramlist();
2131    QLIST_REMOVE_RCU(block, next);
2132    ram_list.mru_block = NULL;
2133    /* Write list before version */
2134    smp_wmb();
2135    ram_list.version++;
2136    call_rcu(block, reclaim_ramblock, rcu);
2137    qemu_mutex_unlock_ramlist();
2138}
2139
2140#ifndef _WIN32
2141void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2142{
2143    RAMBlock *block;
2144    ram_addr_t offset;
2145    int flags;
2146    void *area, *vaddr;
2147
2148    RAMBLOCK_FOREACH(block) {
2149        offset = addr - block->offset;
2150        if (offset < block->max_length) {
2151            vaddr = ramblock_ptr(block, offset);
2152            if (block->flags & RAM_PREALLOC) {
2153                ;
2154            } else if (xen_enabled()) {
2155                abort();
2156            } else {
2157                flags = MAP_FIXED;
2158                if (block->fd >= 0) {
2159                    flags |= (block->flags & RAM_SHARED ?
2160                              MAP_SHARED : MAP_PRIVATE);
2161                    area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2162                                flags, block->fd, offset);
2163                } else {
2164                    /*
2165                     * Remap needs to match alloc.  Accelerators that
2166                     * set phys_mem_alloc never remap.  If they did,
2167                     * we'd need a remap hook here.
2168                     */
2169                    assert(phys_mem_alloc == qemu_anon_ram_alloc);
2170
2171                    flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2172                    area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2173                                flags, -1, 0);
2174                }
2175                if (area != vaddr) {
2176                    error_report("Could not remap addr: "
2177                                 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2178                                 length, addr);
2179                    exit(1);
2180                }
2181                memory_try_enable_merging(vaddr, length);
2182                qemu_ram_setup_dump(vaddr, length);
2183            }
2184        }
2185    }
2186}
2187#endif /* !_WIN32 */
2188
2189/* Return a host pointer to ram allocated with qemu_ram_alloc.
2190 * This should not be used for general purpose DMA.  Use address_space_map
2191 * or address_space_rw instead. For local memory (e.g. video ram) that the
2192 * device owns, use memory_region_get_ram_ptr.
2193 *
2194 * Called within RCU critical section.
2195 */
2196void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2197{
2198    RAMBlock *block = ram_block;
2199
2200    if (block == NULL) {
2201        block = qemu_get_ram_block(addr);
2202        addr -= block->offset;
2203    }
2204
2205    if (xen_enabled() && block->host == NULL) {
2206        /* We need to check if the requested address is in the RAM
2207         * because we don't want to map the entire memory in QEMU.
2208         * In that case just map until the end of the page.
2209         */
2210        if (block->offset == 0) {
2211            return xen_map_cache(addr, 0, 0, false);
2212        }
2213
2214        block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2215    }
2216    return ramblock_ptr(block, addr);
2217}
2218
2219/* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2220 * but takes a size argument.
2221 *
2222 * Called within RCU critical section.
2223 */
2224static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2225                                 hwaddr *size, bool lock)
2226{
2227    RAMBlock *block = ram_block;
2228    if (*size == 0) {
2229        return NULL;
2230    }
2231
2232    if (block == NULL) {
2233        block = qemu_get_ram_block(addr);
2234        addr -= block->offset;
2235    }
2236    *size = MIN(*size, block->max_length - addr);
2237
2238    if (xen_enabled() && block->host == NULL) {
2239        /* We need to check if the requested address is in the RAM
2240         * because we don't want to map the entire memory in QEMU.
2241         * In that case just map the requested area.
2242         */
2243        if (block->offset == 0) {
2244            return xen_map_cache(addr, *size, lock, lock);
2245        }
2246
2247        block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2248    }
2249
2250    return ramblock_ptr(block, addr);
2251}
2252
2253/* Return the offset of a hostpointer within a ramblock */
2254ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2255{
2256    ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2257    assert((uintptr_t)host >= (uintptr_t)rb->host);
2258    assert(res < rb->max_length);
2259
2260    return res;
2261}
2262
2263/*
2264 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2265 * in that RAMBlock.
2266 *
2267 * ptr: Host pointer to look up
2268 * round_offset: If true round the result offset down to a page boundary
2269 * *ram_addr: set to result ram_addr
2270 * *offset: set to result offset within the RAMBlock
2271 *
2272 * Returns: RAMBlock (or NULL if not found)
2273 *
2274 * By the time this function returns, the returned pointer is not protected
2275 * by RCU anymore.  If the caller is not within an RCU critical section and
2276 * does not hold the iothread lock, it must have other means of protecting the
2277 * pointer, such as a reference to the region that includes the incoming
2278 * ram_addr_t.
2279 */
2280RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2281                                   ram_addr_t *offset)
2282{
2283    RAMBlock *block;
2284    uint8_t *host = ptr;
2285
2286    if (xen_enabled()) {
2287        ram_addr_t ram_addr;
2288        RCU_READ_LOCK_GUARD();
2289        ram_addr = xen_ram_addr_from_mapcache(ptr);
2290        block = qemu_get_ram_block(ram_addr);
2291        if (block) {
2292            *offset = ram_addr - block->offset;
2293        }
2294        return block;
2295    }
2296
2297    RCU_READ_LOCK_GUARD();
2298    block = qatomic_rcu_read(&ram_list.mru_block);
2299    if (block && block->host && host - block->host < block->max_length) {
2300        goto found;
2301    }
2302
2303    RAMBLOCK_FOREACH(block) {
2304        /* This case append when the block is not mapped. */
2305        if (block->host == NULL) {
2306            continue;
2307        }
2308        if (host - block->host < block->max_length) {
2309            goto found;
2310        }
2311    }
2312
2313    return NULL;
2314
2315found:
2316    *offset = (host - block->host);
2317    if (round_offset) {
2318        *offset &= TARGET_PAGE_MASK;
2319    }
2320    return block;
2321}
2322
2323/*
2324 * Finds the named RAMBlock
2325 *
2326 * name: The name of RAMBlock to find
2327 *
2328 * Returns: RAMBlock (or NULL if not found)
2329 */
2330RAMBlock *qemu_ram_block_by_name(const char *name)
2331{
2332    RAMBlock *block;
2333
2334    RAMBLOCK_FOREACH(block) {
2335        if (!strcmp(name, block->idstr)) {
2336            return block;
2337        }
2338    }
2339
2340    return NULL;
2341}
2342
2343/* Some of the softmmu routines need to translate from a host pointer
2344   (typically a TLB entry) back to a ram offset.  */
2345ram_addr_t qemu_ram_addr_from_host(void *ptr)
2346{
2347    RAMBlock *block;
2348    ram_addr_t offset;
2349
2350    block = qemu_ram_block_from_host(ptr, false, &offset);
2351    if (!block) {
2352        return RAM_ADDR_INVALID;
2353    }
2354
2355    return block->offset + offset;
2356}
2357
2358/* Generate a debug exception if a watchpoint has been hit.  */
2359void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
2360                          MemTxAttrs attrs, int flags, uintptr_t ra)
2361{
2362    CPUClass *cc = CPU_GET_CLASS(cpu);
2363    CPUWatchpoint *wp;
2364
2365    assert(tcg_enabled());
2366    if (cpu->watchpoint_hit) {
2367        /*
2368         * We re-entered the check after replacing the TB.
2369         * Now raise the debug interrupt so that it will
2370         * trigger after the current instruction.
2371         */
2372        qemu_mutex_lock_iothread();
2373        cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2374        qemu_mutex_unlock_iothread();
2375        return;
2376    }
2377
2378    addr = cc->adjust_watchpoint_address(cpu, addr, len);
2379    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2380        if (watchpoint_address_matches(wp, addr, len)
2381            && (wp->flags & flags)) {
2382            if (replay_running_debug()) {
2383                /*
2384                 * Don't process the watchpoints when we are
2385                 * in a reverse debugging operation.
2386                 */
2387                replay_breakpoint();
2388                return;
2389            }
2390            if (flags == BP_MEM_READ) {
2391                wp->flags |= BP_WATCHPOINT_HIT_READ;
2392            } else {
2393                wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2394            }
2395            wp->hitaddr = MAX(addr, wp->vaddr);
2396            wp->hitattrs = attrs;
2397            if (!cpu->watchpoint_hit) {
2398                if (wp->flags & BP_CPU &&
2399                    !cc->debug_check_watchpoint(cpu, wp)) {
2400                    wp->flags &= ~BP_WATCHPOINT_HIT;
2401                    continue;
2402                }
2403                cpu->watchpoint_hit = wp;
2404
2405                mmap_lock();
2406                tb_check_watchpoint(cpu, ra);
2407                if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2408                    cpu->exception_index = EXCP_DEBUG;
2409                    mmap_unlock();
2410                    cpu_loop_exit_restore(cpu, ra);
2411                } else {
2412                    /* Force execution of one insn next time.  */
2413                    cpu->cflags_next_tb = 1 | curr_cflags();
2414                    mmap_unlock();
2415                    if (ra) {
2416                        cpu_restore_state(cpu, ra, true);
2417                    }
2418                    cpu_loop_exit_noexc(cpu);
2419                }
2420            }
2421        } else {
2422            wp->flags &= ~BP_WATCHPOINT_HIT;
2423        }
2424    }
2425}
2426
2427static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2428                                 MemTxAttrs attrs, void *buf, hwaddr len);
2429static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2430                                  const void *buf, hwaddr len);
2431static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2432                                  bool is_write, MemTxAttrs attrs);
2433
2434static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2435                                unsigned len, MemTxAttrs attrs)
2436{
2437    subpage_t *subpage = opaque;
2438    uint8_t buf[8];
2439    MemTxResult res;
2440
2441#if defined(DEBUG_SUBPAGE)
2442    printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2443           subpage, len, addr);
2444#endif
2445    res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2446    if (res) {
2447        return res;
2448    }
2449    *data = ldn_p(buf, len);
2450    return MEMTX_OK;
2451}
2452
2453static MemTxResult subpage_write(void *opaque, hwaddr addr,
2454                                 uint64_t value, unsigned len, MemTxAttrs attrs)
2455{
2456    subpage_t *subpage = opaque;
2457    uint8_t buf[8];
2458
2459#if defined(DEBUG_SUBPAGE)
2460    printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2461           " value %"PRIx64"\n",
2462           __func__, subpage, len, addr, value);
2463#endif
2464    stn_p(buf, len, value);
2465    return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2466}
2467
2468static bool subpage_accepts(void *opaque, hwaddr addr,
2469                            unsigned len, bool is_write,
2470                            MemTxAttrs attrs)
2471{
2472    subpage_t *subpage = opaque;
2473#if defined(DEBUG_SUBPAGE)
2474    printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2475           __func__, subpage, is_write ? 'w' : 'r', len, addr);
2476#endif
2477
2478    return flatview_access_valid(subpage->fv, addr + subpage->base,
2479                                 len, is_write, attrs);
2480}
2481
2482static const MemoryRegionOps subpage_ops = {
2483    .read_with_attrs = subpage_read,
2484    .write_with_attrs = subpage_write,
2485    .impl.min_access_size = 1,
2486    .impl.max_access_size = 8,
2487    .valid.min_access_size = 1,
2488    .valid.max_access_size = 8,
2489    .valid.accepts = subpage_accepts,
2490    .endianness = DEVICE_NATIVE_ENDIAN,
2491};
2492
2493static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2494                            uint16_t section)
2495{
2496    int idx, eidx;
2497
2498    if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2499        return -1;
2500    idx = SUBPAGE_IDX(start);
2501    eidx = SUBPAGE_IDX(end);
2502#if defined(DEBUG_SUBPAGE)
2503    printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2504           __func__, mmio, start, end, idx, eidx, section);
2505#endif
2506    for (; idx <= eidx; idx++) {
2507        mmio->sub_section[idx] = section;
2508    }
2509
2510    return 0;
2511}
2512
2513static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2514{
2515    subpage_t *mmio;
2516
2517    /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2518    mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2519    mmio->fv = fv;
2520    mmio->base = base;
2521    memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2522                          NULL, TARGET_PAGE_SIZE);
2523    mmio->iomem.subpage = true;
2524#if defined(DEBUG_SUBPAGE)
2525    printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2526           mmio, base, TARGET_PAGE_SIZE);
2527#endif
2528
2529    return mmio;
2530}
2531
2532static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2533{
2534    assert(fv);
2535    MemoryRegionSection section = {
2536        .fv = fv,
2537        .mr = mr,
2538        .offset_within_address_space = 0,
2539        .offset_within_region = 0,
2540        .size = int128_2_64(),
2541    };
2542
2543    return phys_section_add(map, &section);
2544}
2545
2546MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2547                                      hwaddr index, MemTxAttrs attrs)
2548{
2549    int asidx = cpu_asidx_from_attrs(cpu, attrs);
2550    CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2551    AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2552    MemoryRegionSection *sections = d->map.sections;
2553
2554    return &sections[index & ~TARGET_PAGE_MASK];
2555}
2556
2557static void io_mem_init(void)
2558{
2559    memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2560                          NULL, UINT64_MAX);
2561}
2562
2563AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2564{
2565    AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2566    uint16_t n;
2567
2568    n = dummy_section(&d->map, fv, &io_mem_unassigned);
2569    assert(n == PHYS_SECTION_UNASSIGNED);
2570
2571    d->phys_map  = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2572
2573    return d;
2574}
2575
2576void address_space_dispatch_free(AddressSpaceDispatch *d)
2577{
2578    phys_sections_free(&d->map);
2579    g_free(d);
2580}
2581
2582static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2583{
2584}
2585
2586static void tcg_log_global_after_sync(MemoryListener *listener)
2587{
2588    CPUAddressSpace *cpuas;
2589
2590    /* Wait for the CPU to end the current TB.  This avoids the following
2591     * incorrect race:
2592     *
2593     *      vCPU                         migration
2594     *      ----------------------       -------------------------
2595     *      TLB check -> slow path
2596     *        notdirty_mem_write
2597     *          write to RAM
2598     *          mark dirty
2599     *                                   clear dirty flag
2600     *      TLB check -> fast path
2601     *                                   read memory
2602     *        write to RAM
2603     *
2604     * by pushing the migration thread's memory read after the vCPU thread has
2605     * written the memory.
2606     */
2607    if (replay_mode == REPLAY_MODE_NONE) {
2608        /*
2609         * VGA can make calls to this function while updating the screen.
2610         * In record/replay mode this causes a deadlock, because
2611         * run_on_cpu waits for rr mutex. Therefore no races are possible
2612         * in this case and no need for making run_on_cpu when
2613         * record/replay is not enabled.
2614         */
2615        cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2616        run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2617    }
2618}
2619
2620static void tcg_commit(MemoryListener *listener)
2621{
2622    CPUAddressSpace *cpuas;
2623    AddressSpaceDispatch *d;
2624
2625    assert(tcg_enabled());
2626    /* since each CPU stores ram addresses in its TLB cache, we must
2627       reset the modified entries */
2628    cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2629    cpu_reloading_memory_map();
2630    /* The CPU and TLB are protected by the iothread lock.
2631     * We reload the dispatch pointer now because cpu_reloading_memory_map()
2632     * may have split the RCU critical section.
2633     */
2634    d = address_space_to_dispatch(cpuas->as);
2635    qatomic_rcu_set(&cpuas->memory_dispatch, d);
2636    tlb_flush(cpuas->cpu);
2637}
2638
2639static void memory_map_init(void)
2640{
2641    system_memory = g_malloc(sizeof(*system_memory));
2642
2643    memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2644    address_space_init(&address_space_memory, system_memory, "memory");
2645
2646    system_io = g_malloc(sizeof(*system_io));
2647    memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2648                          65536);
2649    address_space_init(&address_space_io, system_io, "I/O");
2650}
2651
2652MemoryRegion *get_system_memory(void)
2653{
2654    return system_memory;
2655}
2656
2657MemoryRegion *get_system_io(void)
2658{
2659    return system_io;
2660}
2661
2662static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2663                                     hwaddr length)
2664{
2665    uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2666    addr += memory_region_get_ram_addr(mr);
2667
2668    /* No early return if dirty_log_mask is or becomes 0, because
2669     * cpu_physical_memory_set_dirty_range will still call
2670     * xen_modified_memory.
2671     */
2672    if (dirty_log_mask) {
2673        dirty_log_mask =
2674            cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2675    }
2676    if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2677        assert(tcg_enabled());
2678        tb_invalidate_phys_range(addr, addr + length);
2679        dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2680    }
2681    cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2682}
2683
2684void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2685{
2686    /*
2687     * In principle this function would work on other memory region types too,
2688     * but the ROM device use case is the only one where this operation is
2689     * necessary.  Other memory regions should use the
2690     * address_space_read/write() APIs.
2691     */
2692    assert(memory_region_is_romd(mr));
2693
2694    invalidate_and_set_dirty(mr, addr, size);
2695}
2696
2697static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2698{
2699    unsigned access_size_max = mr->ops->valid.max_access_size;
2700
2701    /* Regions are assumed to support 1-4 byte accesses unless
2702       otherwise specified.  */
2703    if (access_size_max == 0) {
2704        access_size_max = 4;
2705    }
2706
2707    /* Bound the maximum access by the alignment of the address.  */
2708    if (!mr->ops->impl.unaligned) {
2709        unsigned align_size_max = addr & -addr;
2710        if (align_size_max != 0 && align_size_max < access_size_max) {
2711            access_size_max = align_size_max;
2712        }
2713    }
2714
2715    /* Don't attempt accesses larger than the maximum.  */
2716    if (l > access_size_max) {
2717        l = access_size_max;
2718    }
2719    l = pow2floor(l);
2720
2721    return l;
2722}
2723
2724static bool prepare_mmio_access(MemoryRegion *mr)
2725{
2726    bool release_lock = false;
2727
2728    if (!qemu_mutex_iothread_locked()) {
2729        qemu_mutex_lock_iothread();
2730        release_lock = true;
2731    }
2732    if (mr->flush_coalesced_mmio) {
2733        qemu_flush_coalesced_mmio_buffer();
2734    }
2735
2736    return release_lock;
2737}
2738
2739/* Called within RCU critical section.  */
2740static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2741                                           MemTxAttrs attrs,
2742                                           const void *ptr,
2743                                           hwaddr len, hwaddr addr1,
2744                                           hwaddr l, MemoryRegion *mr)
2745{
2746    uint8_t *ram_ptr;
2747    uint64_t val;
2748    MemTxResult result = MEMTX_OK;
2749    bool release_lock = false;
2750    const uint8_t *buf = ptr;
2751
2752    for (;;) {
2753        if (!memory_access_is_direct(mr, true)) {
2754            release_lock |= prepare_mmio_access(mr);
2755            l = memory_access_size(mr, l, addr1);
2756            /* XXX: could force current_cpu to NULL to avoid
2757               potential bugs */
2758            val = ldn_he_p(buf, l);
2759            result |= memory_region_dispatch_write(mr, addr1, val,
2760                                                   size_memop(l), attrs);
2761        } else {
2762            /* RAM case */
2763            ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2764            memcpy(ram_ptr, buf, l);
2765            invalidate_and_set_dirty(mr, addr1, l);
2766        }
2767
2768        if (release_lock) {
2769            qemu_mutex_unlock_iothread();
2770            release_lock = false;
2771        }
2772
2773        len -= l;
2774        buf += l;
2775        addr += l;
2776
2777        if (!len) {
2778            break;
2779        }
2780
2781        l = len;
2782        mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2783    }
2784
2785    return result;
2786}
2787
2788/* Called from RCU critical section.  */
2789static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2790                                  const void *buf, hwaddr len)
2791{
2792    hwaddr l;
2793    hwaddr addr1;
2794    MemoryRegion *mr;
2795    MemTxResult result = MEMTX_OK;
2796
2797    l = len;
2798    mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2799    result = flatview_write_continue(fv, addr, attrs, buf, len,
2800                                     addr1, l, mr);
2801
2802    return result;
2803}
2804
2805/* Called within RCU critical section.  */
2806MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2807                                   MemTxAttrs attrs, void *ptr,
2808                                   hwaddr len, hwaddr addr1, hwaddr l,
2809                                   MemoryRegion *mr)
2810{
2811    uint8_t *ram_ptr;
2812    uint64_t val;
2813    MemTxResult result = MEMTX_OK;
2814    bool release_lock = false;
2815    uint8_t *buf = ptr;
2816
2817    for (;;) {
2818        if (!memory_access_is_direct(mr, false)) {
2819            /* I/O case */
2820            release_lock |= prepare_mmio_access(mr);
2821            l = memory_access_size(mr, l, addr1);
2822            result |= memory_region_dispatch_read(mr, addr1, &val,
2823                                                  size_memop(l), attrs);
2824            stn_he_p(buf, l, val);
2825        } else {
2826            /* RAM case */
2827            fuzz_dma_read_cb(addr, len, mr, false);
2828            ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2829            memcpy(buf, ram_ptr, l);
2830        }
2831
2832        if (release_lock) {
2833            qemu_mutex_unlock_iothread();
2834            release_lock = false;
2835        }
2836
2837        len -= l;
2838        buf += l;
2839        addr += l;
2840
2841        if (!len) {
2842            break;
2843        }
2844
2845        l = len;
2846        mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2847    }
2848
2849    return result;
2850}
2851
2852/* Called from RCU critical section.  */
2853static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2854                                 MemTxAttrs attrs, void *buf, hwaddr len)
2855{
2856    hwaddr l;
2857    hwaddr addr1;
2858    MemoryRegion *mr;
2859
2860    l = len;
2861    mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2862    return flatview_read_continue(fv, addr, attrs, buf, len,
2863                                  addr1, l, mr);
2864}
2865
2866MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2867                                    MemTxAttrs attrs, void *buf, hwaddr len)
2868{
2869    MemTxResult result = MEMTX_OK;
2870    FlatView *fv;
2871
2872    if (len > 0) {
2873        RCU_READ_LOCK_GUARD();
2874        fv = address_space_to_flatview(as);
2875        result = flatview_read(fv, addr, attrs, buf, len);
2876    }
2877
2878    return result;
2879}
2880
2881MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2882                                MemTxAttrs attrs,
2883                                const void *buf, hwaddr len)
2884{
2885    MemTxResult result = MEMTX_OK;
2886    FlatView *fv;
2887
2888    if (len > 0) {
2889        RCU_READ_LOCK_GUARD();
2890        fv = address_space_to_flatview(as);
2891        result = flatview_write(fv, addr, attrs, buf, len);
2892    }
2893
2894    return result;
2895}
2896
2897MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2898                             void *buf, hwaddr len, bool is_write)
2899{
2900    if (is_write) {
2901        return address_space_write(as, addr, attrs, buf, len);
2902    } else {
2903        return address_space_read_full(as, addr, attrs, buf, len);
2904    }
2905}
2906
2907void cpu_physical_memory_rw(hwaddr addr, void *buf,
2908                            hwaddr len, bool is_write)
2909{
2910    address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2911                     buf, len, is_write);
2912}
2913
2914enum write_rom_type {
2915    WRITE_DATA,
2916    FLUSH_CACHE,
2917};
2918
2919static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2920                                                           hwaddr addr,
2921                                                           MemTxAttrs attrs,
2922                                                           const void *ptr,
2923                                                           hwaddr len,
2924                                                           enum write_rom_type type)
2925{
2926    hwaddr l;
2927    uint8_t *ram_ptr;
2928    hwaddr addr1;
2929    MemoryRegion *mr;
2930    const uint8_t *buf = ptr;
2931
2932    RCU_READ_LOCK_GUARD();
2933    while (len > 0) {
2934        l = len;
2935        mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2936
2937        if (!(memory_region_is_ram(mr) ||
2938              memory_region_is_romd(mr))) {
2939            l = memory_access_size(mr, l, addr1);
2940        } else {
2941            /* ROM/RAM case */
2942            ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2943            switch (type) {
2944            case WRITE_DATA:
2945                memcpy(ram_ptr, buf, l);
2946                invalidate_and_set_dirty(mr, addr1, l);
2947                break;
2948            case FLUSH_CACHE:
2949                flush_icache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr + l);
2950                break;
2951            }
2952        }
2953        len -= l;
2954        buf += l;
2955        addr += l;
2956    }
2957    return MEMTX_OK;
2958}
2959
2960/* used for ROM loading : can write in RAM and ROM */
2961MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2962                                    MemTxAttrs attrs,
2963                                    const void *buf, hwaddr len)
2964{
2965    return address_space_write_rom_internal(as, addr, attrs,
2966                                            buf, len, WRITE_DATA);
2967}
2968
2969void cpu_flush_icache_range(hwaddr start, hwaddr len)
2970{
2971    /*
2972     * This function should do the same thing as an icache flush that was
2973     * triggered from within the guest. For TCG we are always cache coherent,
2974     * so there is no need to flush anything. For KVM / Xen we need to flush
2975     * the host's instruction cache at least.
2976     */
2977    if (tcg_enabled()) {
2978        return;
2979    }
2980
2981    address_space_write_rom_internal(&address_space_memory,
2982                                     start, MEMTXATTRS_UNSPECIFIED,
2983                                     NULL, len, FLUSH_CACHE);
2984}
2985
2986typedef struct {
2987    MemoryRegion *mr;
2988    void *buffer;
2989    hwaddr addr;
2990    hwaddr len;
2991    bool in_use;
2992} BounceBuffer;
2993
2994static BounceBuffer bounce;
2995
2996typedef struct MapClient {
2997    QEMUBH *bh;
2998    QLIST_ENTRY(MapClient) link;
2999} MapClient;
3000
3001QemuMutex map_client_list_lock;
3002static QLIST_HEAD(, MapClient) map_client_list
3003    = QLIST_HEAD_INITIALIZER(map_client_list);
3004
3005static void cpu_unregister_map_client_do(MapClient *client)
3006{
3007    QLIST_REMOVE(client, link);
3008    g_free(client);
3009}
3010
3011static void cpu_notify_map_clients_locked(void)
3012{
3013    MapClient *client;
3014
3015    while (!QLIST_EMPTY(&map_client_list)) {
3016        client = QLIST_FIRST(&map_client_list);
3017        qemu_bh_schedule(client->bh);
3018        cpu_unregister_map_client_do(client);
3019    }
3020}
3021
3022void cpu_register_map_client(QEMUBH *bh)
3023{
3024    MapClient *client = g_malloc(sizeof(*client));
3025
3026    qemu_mutex_lock(&map_client_list_lock);
3027    client->bh = bh;
3028    QLIST_INSERT_HEAD(&map_client_list, client, link);
3029    if (!qatomic_read(&bounce.in_use)) {
3030        cpu_notify_map_clients_locked();
3031    }
3032    qemu_mutex_unlock(&map_client_list_lock);
3033}
3034
3035void cpu_exec_init_all(void)
3036{
3037    qemu_mutex_init(&ram_list.mutex);
3038    /* The data structures we set up here depend on knowing the page size,
3039     * so no more changes can be made after this point.
3040     * In an ideal world, nothing we did before we had finished the
3041     * machine setup would care about the target page size, and we could
3042     * do this much later, rather than requiring board models to state
3043     * up front what their requirements are.
3044     */
3045    finalize_target_page_bits();
3046    io_mem_init();
3047    memory_map_init();
3048    qemu_mutex_init(&map_client_list_lock);
3049}
3050
3051void cpu_unregister_map_client(QEMUBH *bh)
3052{
3053    MapClient *client;
3054
3055    qemu_mutex_lock(&map_client_list_lock);
3056    QLIST_FOREACH(client, &map_client_list, link) {
3057        if (client->bh == bh) {
3058            cpu_unregister_map_client_do(client);
3059            break;
3060        }
3061    }
3062    qemu_mutex_unlock(&map_client_list_lock);
3063}
3064
3065static void cpu_notify_map_clients(void)
3066{
3067    qemu_mutex_lock(&map_client_list_lock);
3068    cpu_notify_map_clients_locked();
3069    qemu_mutex_unlock(&map_client_list_lock);
3070}
3071
3072static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3073                                  bool is_write, MemTxAttrs attrs)
3074{
3075    MemoryRegion *mr;
3076    hwaddr l, xlat;
3077
3078    while (len > 0) {
3079        l = len;
3080        mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3081        if (!memory_access_is_direct(mr, is_write)) {
3082            l = memory_access_size(mr, l, addr);
3083            if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3084                return false;
3085            }
3086        }
3087
3088        len -= l;
3089        addr += l;
3090    }
3091    return true;
3092}
3093
3094bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3095                                hwaddr len, bool is_write,
3096                                MemTxAttrs attrs)
3097{
3098    FlatView *fv;
3099    bool result;
3100
3101    RCU_READ_LOCK_GUARD();
3102    fv = address_space_to_flatview(as);
3103    result = flatview_access_valid(fv, addr, len, is_write, attrs);
3104    return result;
3105}
3106
3107static hwaddr
3108flatview_extend_translation(FlatView *fv, hwaddr addr,
3109                            hwaddr target_len,
3110                            MemoryRegion *mr, hwaddr base, hwaddr len,
3111                            bool is_write, MemTxAttrs attrs)
3112{
3113    hwaddr done = 0;
3114    hwaddr xlat;
3115    MemoryRegion *this_mr;
3116
3117    for (;;) {
3118        target_len -= len;
3119        addr += len;
3120        done += len;
3121        if (target_len == 0) {
3122            return done;
3123        }
3124
3125        len = target_len;
3126        this_mr = flatview_translate(fv, addr, &xlat,
3127                                     &len, is_write, attrs);
3128        if (this_mr != mr || xlat != base + done) {
3129            return done;
3130        }
3131    }
3132}
3133
3134/* Map a physical memory region into a host virtual address.
3135 * May map a subset of the requested range, given by and returned in *plen.
3136 * May return NULL if resources needed to perform the mapping are exhausted.
3137 * Use only for reads OR writes - not for read-modify-write operations.
3138 * Use cpu_register_map_client() to know when retrying the map operation is
3139 * likely to succeed.
3140 */
3141void *address_space_map(AddressSpace *as,
3142                        hwaddr addr,
3143                        hwaddr *plen,
3144                        bool is_write,
3145                        MemTxAttrs attrs)
3146{
3147    hwaddr len = *plen;
3148    hwaddr l, xlat;
3149    MemoryRegion *mr;
3150    void *ptr;
3151    FlatView *fv;
3152
3153    if (len == 0) {
3154        return NULL;
3155    }
3156
3157    l = len;
3158    RCU_READ_LOCK_GUARD();
3159    fv = address_space_to_flatview(as);
3160    mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3161
3162    if (!memory_access_is_direct(mr, is_write)) {
3163        if (qatomic_xchg(&bounce.in_use, true)) {
3164            *plen = 0;
3165            return NULL;
3166        }
3167        /* Avoid unbounded allocations */
3168        l = MIN(l, TARGET_PAGE_SIZE);
3169        bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3170        bounce.addr = addr;
3171        bounce.len = l;
3172
3173        memory_region_ref(mr);
3174        bounce.mr = mr;
3175        if (!is_write) {
3176            flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3177                               bounce.buffer, l);
3178        }
3179
3180        *plen = l;
3181        return bounce.buffer;
3182    }
3183
3184
3185    memory_region_ref(mr);
3186    *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3187                                        l, is_write, attrs);
3188    fuzz_dma_read_cb(addr, *plen, mr, is_write);
3189    ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3190
3191    return ptr;
3192}
3193
3194/* Unmaps a memory region previously mapped by address_space_map().
3195 * Will also mark the memory as dirty if is_write is true.  access_len gives
3196 * the amount of memory that was actually read or written by the caller.
3197 */
3198void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3199                         bool is_write, hwaddr access_len)
3200{
3201    if (buffer != bounce.buffer) {
3202        MemoryRegion *mr;
3203        ram_addr_t addr1;
3204
3205        mr = memory_region_from_host(buffer, &addr1);
3206        assert(mr != NULL);
3207        if (is_write) {
3208            invalidate_and_set_dirty(mr, addr1, access_len);
3209        }
3210        if (xen_enabled()) {
3211            xen_invalidate_map_cache_entry(buffer);
3212        }
3213        memory_region_unref(mr);
3214        return;
3215    }
3216    if (is_write) {
3217        address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3218                            bounce.buffer, access_len);
3219    }
3220    qemu_vfree(bounce.buffer);
3221    bounce.buffer = NULL;
3222    memory_region_unref(bounce.mr);
3223    qatomic_mb_set(&bounce.in_use, false);
3224    cpu_notify_map_clients();
3225}
3226
3227void *cpu_physical_memory_map(hwaddr addr,
3228                              hwaddr *plen,
3229                              bool is_write)
3230{
3231    return address_space_map(&address_space_memory, addr, plen, is_write,
3232                             MEMTXATTRS_UNSPECIFIED);
3233}
3234
3235void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3236                               bool is_write, hwaddr access_len)
3237{
3238    return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3239}
3240
3241#define ARG1_DECL                AddressSpace *as
3242#define ARG1                     as
3243#define SUFFIX
3244#define TRANSLATE(...)           address_space_translate(as, __VA_ARGS__)
3245#define RCU_READ_LOCK(...)       rcu_read_lock()
3246#define RCU_READ_UNLOCK(...)     rcu_read_unlock()
3247#include "memory_ldst.c.inc"
3248
3249int64_t address_space_cache_init(MemoryRegionCache *cache,
3250                                 AddressSpace *as,
3251                                 hwaddr addr,
3252                                 hwaddr len,
3253                                 bool is_write)
3254{
3255    AddressSpaceDispatch *d;
3256    hwaddr l;
3257    MemoryRegion *mr;
3258
3259    assert(len > 0);
3260
3261    l = len;
3262    cache->fv = address_space_get_flatview(as);
3263    d = flatview_to_dispatch(cache->fv);
3264    cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3265
3266    mr = cache->mrs.mr;
3267    memory_region_ref(mr);
3268    if (memory_access_is_direct(mr, is_write)) {
3269        /* We don't care about the memory attributes here as we're only
3270         * doing this if we found actual RAM, which behaves the same
3271         * regardless of attributes; so UNSPECIFIED is fine.
3272         */
3273        l = flatview_extend_translation(cache->fv, addr, len, mr,
3274                                        cache->xlat, l, is_write,
3275                                        MEMTXATTRS_UNSPECIFIED);
3276        cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3277    } else {
3278        cache->ptr = NULL;
3279    }
3280
3281    cache->len = l;
3282    cache->is_write = is_write;
3283    return l;
3284}
3285
3286void address_space_cache_invalidate(MemoryRegionCache *cache,
3287                                    hwaddr addr,
3288                                    hwaddr access_len)
3289{
3290    assert(cache->is_write);
3291    if (likely(cache->ptr)) {
3292        invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3293    }
3294}
3295
3296void address_space_cache_destroy(MemoryRegionCache *cache)
3297{
3298    if (!cache->mrs.mr) {
3299        return;
3300    }
3301
3302    if (xen_enabled()) {
3303        xen_invalidate_map_cache_entry(cache->ptr);
3304    }
3305    memory_region_unref(cache->mrs.mr);
3306    flatview_unref(cache->fv);
3307    cache->mrs.mr = NULL;
3308    cache->fv = NULL;
3309}
3310
3311/* Called from RCU critical section.  This function has the same
3312 * semantics as address_space_translate, but it only works on a
3313 * predefined range of a MemoryRegion that was mapped with
3314 * address_space_cache_init.
3315 */
3316static inline MemoryRegion *address_space_translate_cached(
3317    MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3318    hwaddr *plen, bool is_write, MemTxAttrs attrs)
3319{
3320    MemoryRegionSection section;
3321    MemoryRegion *mr;
3322    IOMMUMemoryRegion *iommu_mr;
3323    AddressSpace *target_as;
3324
3325    assert(!cache->ptr);
3326    *xlat = addr + cache->xlat;
3327
3328    mr = cache->mrs.mr;
3329    iommu_mr = memory_region_get_iommu(mr);
3330    if (!iommu_mr) {
3331        /* MMIO region.  */
3332        return mr;
3333    }
3334
3335    section = address_space_translate_iommu(iommu_mr, xlat, plen,
3336                                            NULL, is_write, true,
3337                                            &target_as, attrs);
3338    return section.mr;
3339}
3340
3341/* Called from RCU critical section. address_space_read_cached uses this
3342 * out of line function when the target is an MMIO or IOMMU region.
3343 */
3344MemTxResult
3345address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3346                                   void *buf, hwaddr len)
3347{
3348    hwaddr addr1, l;
3349    MemoryRegion *mr;
3350
3351    l = len;
3352    mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3353                                        MEMTXATTRS_UNSPECIFIED);
3354    return flatview_read_continue(cache->fv,
3355                                  addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3356                                  addr1, l, mr);
3357}
3358
3359/* Called from RCU critical section. address_space_write_cached uses this
3360 * out of line function when the target is an MMIO or IOMMU region.
3361 */
3362MemTxResult
3363address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3364                                    const void *buf, hwaddr len)
3365{
3366    hwaddr addr1, l;
3367    MemoryRegion *mr;
3368
3369    l = len;
3370    mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3371                                        MEMTXATTRS_UNSPECIFIED);
3372    return flatview_write_continue(cache->fv,
3373                                   addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3374                                   addr1, l, mr);
3375}
3376
3377#define ARG1_DECL                MemoryRegionCache *cache
3378#define ARG1                     cache
3379#define SUFFIX                   _cached_slow
3380#define TRANSLATE(...)           address_space_translate_cached(cache, __VA_ARGS__)
3381#define RCU_READ_LOCK()          ((void)0)
3382#define RCU_READ_UNLOCK()        ((void)0)
3383#include "memory_ldst.c.inc"
3384
3385/* virtual memory access for debug (includes writing to ROM) */
3386int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3387                        void *ptr, target_ulong len, bool is_write)
3388{
3389    hwaddr phys_addr;
3390    target_ulong l, page;
3391    uint8_t *buf = ptr;
3392
3393    cpu_synchronize_state(cpu);
3394    while (len > 0) {
3395        int asidx;
3396        MemTxAttrs attrs;
3397        MemTxResult res;
3398
3399        page = addr & TARGET_PAGE_MASK;
3400        phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3401        asidx = cpu_asidx_from_attrs(cpu, attrs);
3402        /* if no physical page mapped, return an error */
3403        if (phys_addr == -1)
3404            return -1;
3405        l = (page + TARGET_PAGE_SIZE) - addr;
3406        if (l > len)
3407            l = len;
3408        phys_addr += (addr & ~TARGET_PAGE_MASK);
3409        if (is_write) {
3410            res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3411                                          attrs, buf, l);
3412        } else {
3413            res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3414                                     attrs, buf, l);
3415        }
3416        if (res != MEMTX_OK) {
3417            return -1;
3418        }
3419        len -= l;
3420        buf += l;
3421        addr += l;
3422    }
3423    return 0;
3424}
3425
3426/*
3427 * Allows code that needs to deal with migration bitmaps etc to still be built
3428 * target independent.
3429 */
3430size_t qemu_target_page_size(void)
3431{
3432    return TARGET_PAGE_SIZE;
3433}
3434
3435int qemu_target_page_bits(void)
3436{
3437    return TARGET_PAGE_BITS;
3438}
3439
3440int qemu_target_page_bits_min(void)
3441{
3442    return TARGET_PAGE_BITS_MIN;
3443}
3444
3445bool cpu_physical_memory_is_io(hwaddr phys_addr)
3446{
3447    MemoryRegion*mr;
3448    hwaddr l = 1;
3449    bool res;
3450
3451    RCU_READ_LOCK_GUARD();
3452    mr = address_space_translate(&address_space_memory,
3453                                 phys_addr, &phys_addr, &l, false,
3454                                 MEMTXATTRS_UNSPECIFIED);
3455
3456    res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3457    return res;
3458}
3459
3460int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3461{
3462    RAMBlock *block;
3463    int ret = 0;
3464
3465    RCU_READ_LOCK_GUARD();
3466    RAMBLOCK_FOREACH(block) {
3467        ret = func(block, opaque);
3468        if (ret) {
3469            break;
3470        }
3471    }
3472    return ret;
3473}
3474
3475/*
3476 * Unmap pages of memory from start to start+length such that
3477 * they a) read as 0, b) Trigger whatever fault mechanism
3478 * the OS provides for postcopy.
3479 * The pages must be unmapped by the end of the function.
3480 * Returns: 0 on success, none-0 on failure
3481 *
3482 */
3483int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3484{
3485    int ret = -1;
3486
3487    uint8_t *host_startaddr = rb->host + start;
3488
3489    if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3490        error_report("ram_block_discard_range: Unaligned start address: %p",
3491                     host_startaddr);
3492        goto err;
3493    }
3494
3495    if ((start + length) <= rb->used_length) {
3496        bool need_madvise, need_fallocate;
3497        if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3498            error_report("ram_block_discard_range: Unaligned length: %zx",
3499                         length);
3500            goto err;
3501        }
3502
3503        errno = ENOTSUP; /* If we are missing MADVISE etc */
3504
3505        /* The logic here is messy;
3506         *    madvise DONTNEED fails for hugepages
3507         *    fallocate works on hugepages and shmem
3508         */
3509        need_madvise = (rb->page_size == qemu_host_page_size);
3510        need_fallocate = rb->fd != -1;
3511        if (need_fallocate) {
3512            /* For a file, this causes the area of the file to be zero'd
3513             * if read, and for hugetlbfs also causes it to be unmapped
3514             * so a userfault will trigger.
3515             */
3516#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3517            ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3518                            start, length);
3519            if (ret) {
3520                ret = -errno;
3521                error_report("ram_block_discard_range: Failed to fallocate "
3522                             "%s:%" PRIx64 " +%zx (%d)",
3523                             rb->idstr, start, length, ret);
3524                goto err;
3525            }
3526#else
3527            ret = -ENOSYS;
3528            error_report("ram_block_discard_range: fallocate not available/file"
3529                         "%s:%" PRIx64 " +%zx (%d)",
3530                         rb->idstr, start, length, ret);
3531            goto err;
3532#endif
3533        }
3534        if (need_madvise) {
3535            /* For normal RAM this causes it to be unmapped,
3536             * for shared memory it causes the local mapping to disappear
3537             * and to fall back on the file contents (which we just
3538             * fallocate'd away).
3539             */
3540#if defined(CONFIG_MADVISE)
3541            ret =  madvise(host_startaddr, length, MADV_DONTNEED);
3542            if (ret) {
3543                ret = -errno;
3544                error_report("ram_block_discard_range: Failed to discard range "
3545                             "%s:%" PRIx64 " +%zx (%d)",
3546                             rb->idstr, start, length, ret);
3547                goto err;
3548            }
3549#else
3550            ret = -ENOSYS;
3551            error_report("ram_block_discard_range: MADVISE not available"
3552                         "%s:%" PRIx64 " +%zx (%d)",
3553                         rb->idstr, start, length, ret);
3554            goto err;
3555#endif
3556        }
3557        trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3558                                      need_madvise, need_fallocate, ret);
3559    } else {
3560        error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3561                     "/%zx/" RAM_ADDR_FMT")",
3562                     rb->idstr, start, length, rb->used_length);
3563    }
3564
3565err:
3566    return ret;
3567}
3568
3569bool ramblock_is_pmem(RAMBlock *rb)
3570{
3571    return rb->flags & RAM_PMEM;
3572}
3573
3574static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3575{
3576    if (start == end - 1) {
3577        qemu_printf("\t%3d      ", start);
3578    } else {
3579        qemu_printf("\t%3d..%-3d ", start, end - 1);
3580    }
3581    qemu_printf(" skip=%d ", skip);
3582    if (ptr == PHYS_MAP_NODE_NIL) {
3583        qemu_printf(" ptr=NIL");
3584    } else if (!skip) {
3585        qemu_printf(" ptr=#%d", ptr);
3586    } else {
3587        qemu_printf(" ptr=[%d]", ptr);
3588    }
3589    qemu_printf("\n");
3590}
3591
3592#define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3593                           int128_sub((size), int128_one())) : 0)
3594
3595void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3596{
3597    int i;
3598
3599    qemu_printf("  Dispatch\n");
3600    qemu_printf("    Physical sections\n");
3601
3602    for (i = 0; i < d->map.sections_nb; ++i) {
3603        MemoryRegionSection *s = d->map.sections + i;
3604        const char *names[] = { " [unassigned]", " [not dirty]",
3605                                " [ROM]", " [watch]" };
3606
3607        qemu_printf("      #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3608                    " %s%s%s%s%s",
3609            i,
3610            s->offset_within_address_space,
3611            s->offset_within_address_space + MR_SIZE(s->mr->size),
3612            s->mr->name ? s->mr->name : "(noname)",
3613            i < ARRAY_SIZE(names) ? names[i] : "",
3614            s->mr == root ? " [ROOT]" : "",
3615            s == d->mru_section ? " [MRU]" : "",
3616            s->mr->is_iommu ? " [iommu]" : "");
3617
3618        if (s->mr->alias) {
3619            qemu_printf(" alias=%s", s->mr->alias->name ?
3620                    s->mr->alias->name : "noname");
3621        }
3622        qemu_printf("\n");
3623    }
3624
3625    qemu_printf("    Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3626               P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3627    for (i = 0; i < d->map.nodes_nb; ++i) {
3628        int j, jprev;
3629        PhysPageEntry prev;
3630        Node *n = d->map.nodes + i;
3631
3632        qemu_printf("      [%d]\n", i);
3633
3634        for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3635            PhysPageEntry *pe = *n + j;
3636
3637            if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3638                continue;
3639            }
3640
3641            mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3642
3643            jprev = j;
3644            prev = *pe;
3645        }
3646
3647        if (jprev != ARRAY_SIZE(*n)) {
3648            mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3649        }
3650    }
3651}
3652
3653/*
3654 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3655 * required to work and cannot be disabled.
3656 */
3657static int ram_block_discard_disabled;
3658
3659int ram_block_discard_disable(bool state)
3660{
3661    int old;
3662
3663    if (!state) {
3664        qatomic_dec(&ram_block_discard_disabled);
3665        return 0;
3666    }
3667
3668    do {
3669        old = qatomic_read(&ram_block_discard_disabled);
3670        if (old < 0) {
3671            return -EBUSY;
3672        }
3673    } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3674                             old, old + 1) != old);
3675    return 0;
3676}
3677
3678int ram_block_discard_require(bool state)
3679{
3680    int old;
3681
3682    if (!state) {
3683        qatomic_inc(&ram_block_discard_disabled);
3684        return 0;
3685    }
3686
3687    do {
3688        old = qatomic_read(&ram_block_discard_disabled);
3689        if (old > 0) {
3690            return -EBUSY;
3691        }
3692    } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3693                             old, old - 1) != old);
3694    return 0;
3695}
3696
3697bool ram_block_discard_is_disabled(void)
3698{
3699    return qatomic_read(&ram_block_discard_disabled) > 0;
3700}
3701
3702bool ram_block_discard_is_required(void)
3703{
3704    return qatomic_read(&ram_block_discard_disabled) < 0;
3705}
3706