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