memory.c 99 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * Physical memory management
 *
 * Copyright 2011 Red Hat, Inc. and/or its affiliates
 *
 * Authors:
 *  Avi Kivity <avi@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
 *
12 13
 * Contributions after 2012-01-13 are licensed under the terms of the
 * GNU GPL, version 2 or (at your option) any later version.
14 15
 */

Peter Maydell's avatar
Peter Maydell committed
16
#include "qemu/osdep.h"
17
#include "qapi/error.h"
18 19
#include "qemu-common.h"
#include "cpu.h"
20 21 22
#include "exec/memory.h"
#include "exec/address-spaces.h"
#include "exec/ioport.h"
23
#include "qapi/visitor.h"
24
#include "qemu/bitops.h"
Pavel Fedin's avatar
Pavel Fedin committed
25
#include "qemu/error-report.h"
26
#include "qom/object.h"
27
#include "trace-root.h"
28

29
#include "exec/memory-internal.h"
30
#include "exec/ram_addr.h"
Pavel Fedin's avatar
Pavel Fedin committed
31
#include "sysemu/kvm.h"
32
#include "sysemu/sysemu.h"
33 34
#include "hw/misc/mmio_interface.h"
#include "hw/qdev-properties.h"
35
#include "migration/vmstate.h"
36

37 38
//#define DEBUG_UNASSIGNED

39 40
static unsigned memory_region_transaction_depth;
static bool memory_region_update_pending;
41
static bool ioeventfd_update_pending;
42 43
static bool global_dirty_log = false;

44 45
static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
    = QTAILQ_HEAD_INITIALIZER(memory_listeners);
Avi Kivity's avatar
Avi Kivity committed
46

47 48 49
static QTAILQ_HEAD(, AddressSpace) address_spaces
    = QTAILQ_HEAD_INITIALIZER(address_spaces);

50 51
static GHashTable *flat_views;

52 53
typedef struct AddrRange AddrRange;

54
/*
55
 * Note that signed integers are needed for negative offsetting in aliases
56 57
 * (large MemoryRegion::alias_offset).
 */
58
struct AddrRange {
59 60
    Int128 start;
    Int128 size;
61 62
};

63
static AddrRange addrrange_make(Int128 start, Int128 size)
64 65 66 67 68 69
{
    return (AddrRange) { start, size };
}

static bool addrrange_equal(AddrRange r1, AddrRange r2)
{
70
    return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
71 72
}

73
static Int128 addrrange_end(AddrRange r)
74
{
75
    return int128_add(r.start, r.size);
76 77
}

78
static AddrRange addrrange_shift(AddrRange range, Int128 delta)
79
{
80
    int128_addto(&range.start, delta);
81 82 83
    return range;
}

84 85 86 87 88 89
static bool addrrange_contains(AddrRange range, Int128 addr)
{
    return int128_ge(addr, range.start)
        && int128_lt(addr, addrrange_end(range));
}

90 91
static bool addrrange_intersects(AddrRange r1, AddrRange r2)
{
92 93
    return addrrange_contains(r1, r2.start)
        || addrrange_contains(r2, r1.start);
94 95 96 97
}

static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
{
98 99 100
    Int128 start = int128_max(r1.start, r2.start);
    Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
    return addrrange_make(start, int128_sub(end, start));
101 102
}

103 104
enum ListenerDirection { Forward, Reverse };

105
#define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...)    \
106 107 108 109 110 111
    do {                                                                \
        MemoryListener *_listener;                                      \
                                                                        \
        switch (_direction) {                                           \
        case Forward:                                                   \
            QTAILQ_FOREACH(_listener, &memory_listeners, link) {        \
112 113 114
                if (_listener->_callback) {                             \
                    _listener->_callback(_listener, ##_args);           \
                }                                                       \
115 116 117 118 119
            }                                                           \
            break;                                                      \
        case Reverse:                                                   \
            QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners,        \
                                   memory_listeners, link) {            \
120 121 122
                if (_listener->_callback) {                             \
                    _listener->_callback(_listener, ##_args);           \
                }                                                       \
123 124 125 126 127 128 129
            }                                                           \
            break;                                                      \
        default:                                                        \
            abort();                                                    \
        }                                                               \
    } while (0)

130
#define MEMORY_LISTENER_CALL(_as, _callback, _direction, _section, _args...) \
131 132
    do {                                                                \
        MemoryListener *_listener;                                      \
133
        struct memory_listeners_as *list = &(_as)->listeners;           \
134 135 136
                                                                        \
        switch (_direction) {                                           \
        case Forward:                                                   \
137 138
            QTAILQ_FOREACH(_listener, list, link_as) {                  \
                if (_listener->_callback) {                             \
139 140 141 142 143
                    _listener->_callback(_listener, _section, ##_args); \
                }                                                       \
            }                                                           \
            break;                                                      \
        case Reverse:                                                   \
144 145 146
            QTAILQ_FOREACH_REVERSE(_listener, list, memory_listeners_as, \
                                   link_as) {                           \
                if (_listener->_callback) {                             \
147 148 149 150 151 152 153 154 155
                    _listener->_callback(_listener, _section, ##_args); \
                }                                                       \
            }                                                           \
            break;                                                      \
        default:                                                        \
            abort();                                                    \
        }                                                               \
    } while (0)

156
/* No need to ref/unref .mr, the FlatRange keeps it alive.  */
157
#define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...)  \
158
    do {                                                                \
159 160
        MemoryRegionSection mrs = section_from_flat_range(fr,           \
                address_space_to_flatview(as));                         \
161
        MEMORY_LISTENER_CALL(as, callback, dir, &mrs, ##_args);         \
162
    } while(0)
163

164 165 166 167 168
struct CoalescedMemoryRange {
    AddrRange addr;
    QTAILQ_ENTRY(CoalescedMemoryRange) link;
};

169 170 171 172
struct MemoryRegionIoeventfd {
    AddrRange addr;
    bool match_data;
    uint64_t data;
173
    EventNotifier *e;
174 175 176 177 178
};

static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
                                           MemoryRegionIoeventfd b)
{
179
    if (int128_lt(a.addr.start, b.addr.start)) {
180
        return true;
181
    } else if (int128_gt(a.addr.start, b.addr.start)) {
182
        return false;
183
    } else if (int128_lt(a.addr.size, b.addr.size)) {
184
        return true;
185
    } else if (int128_gt(a.addr.size, b.addr.size)) {
186 187 188 189 190 191 192 193 194 195 196 197
        return false;
    } else if (a.match_data < b.match_data) {
        return true;
    } else  if (a.match_data > b.match_data) {
        return false;
    } else if (a.match_data) {
        if (a.data < b.data) {
            return true;
        } else if (a.data > b.data) {
            return false;
        }
    }
198
    if (a.e < b.e) {
199
        return true;
200
    } else if (a.e > b.e) {
201 202 203 204 205 206 207 208 209 210 211 212
        return false;
    }
    return false;
}

static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
                                          MemoryRegionIoeventfd b)
{
    return !memory_region_ioeventfd_before(a, b)
        && !memory_region_ioeventfd_before(b, a);
}

213 214 215
/* Range of memory in the global map.  Addresses are absolute. */
struct FlatRange {
    MemoryRegion *mr;
216
    hwaddr offset_in_region;
217
    AddrRange addr;
218
    uint8_t dirty_log_mask;
219
    bool romd_mode;
220
    bool readonly;
221 222
};

223 224
typedef struct AddressSpaceOps AddressSpaceOps;

225 226 227
#define FOR_EACH_FLAT_RANGE(var, view)          \
    for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)

228
static inline MemoryRegionSection
229
section_from_flat_range(FlatRange *fr, FlatView *fv)
230 231 232
{
    return (MemoryRegionSection) {
        .mr = fr->mr,
233
        .fv = fv,
234 235 236 237 238 239 240
        .offset_within_region = fr->offset_in_region,
        .size = fr->addr.size,
        .offset_within_address_space = int128_get64(fr->addr.start),
        .readonly = fr->readonly,
    };
}

241 242 243 244
static bool flatrange_equal(FlatRange *a, FlatRange *b)
{
    return a->mr == b->mr
        && addrrange_equal(a->addr, b->addr)
245
        && a->offset_in_region == b->offset_in_region
246
        && a->romd_mode == b->romd_mode
247
        && a->readonly == b->readonly;
248 249
}

250
static FlatView *flatview_new(MemoryRegion *mr_root)
251
{
252 253 254
    FlatView *view;

    view = g_new0(FlatView, 1);
255
    view->ref = 1;
256 257
    view->root = mr_root;
    memory_region_ref(mr_root);
258
    trace_flatview_new(view, mr_root);
259 260

    return view;
261 262 263 264 265 266 267 268 269
}

/* Insert a range into a given position.  Caller is responsible for maintaining
 * sorting order.
 */
static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
{
    if (view->nr == view->nr_allocated) {
        view->nr_allocated = MAX(2 * view->nr, 10);
270
        view->ranges = g_realloc(view->ranges,
271 272 273 274 275
                                    view->nr_allocated * sizeof(*view->ranges));
    }
    memmove(view->ranges + pos + 1, view->ranges + pos,
            (view->nr - pos) * sizeof(FlatRange));
    view->ranges[pos] = *range;
276
    memory_region_ref(range->mr);
277 278 279 280 281
    ++view->nr;
}

static void flatview_destroy(FlatView *view)
{
282 283
    int i;

284
    trace_flatview_destroy(view, view->root);
285 286 287
    if (view->dispatch) {
        address_space_dispatch_free(view->dispatch);
    }
288 289 290
    for (i = 0; i < view->nr; i++) {
        memory_region_unref(view->ranges[i].mr);
    }
291
    g_free(view->ranges);
292
    memory_region_unref(view->root);
293
    g_free(view);
294 295
}

296
static bool flatview_ref(FlatView *view)
297
{
298
    return atomic_fetch_inc_nonzero(&view->ref) > 0;
299 300 301 302 303
}

static void flatview_unref(FlatView *view)
{
    if (atomic_fetch_dec(&view->ref) == 1) {
304
        trace_flatview_destroy_rcu(view, view->root);
305
        assert(view->root);
306
        call_rcu(view, flatview_destroy, rcu);
307 308 309
    }
}

310 311
static bool can_merge(FlatRange *r1, FlatRange *r2)
{
312
    return int128_eq(addrrange_end(r1->addr), r2->addr.start)
313
        && r1->mr == r2->mr
314 315 316
        && int128_eq(int128_add(int128_make64(r1->offset_in_region),
                                r1->addr.size),
                     int128_make64(r2->offset_in_region))
317
        && r1->dirty_log_mask == r2->dirty_log_mask
318
        && r1->romd_mode == r2->romd_mode
319
        && r1->readonly == r2->readonly;
320 321
}

322
/* Attempt to simplify a view by merging adjacent ranges */
323 324 325 326 327 328 329 330 331
static void flatview_simplify(FlatView *view)
{
    unsigned i, j;

    i = 0;
    while (i < view->nr) {
        j = i + 1;
        while (j < view->nr
               && can_merge(&view->ranges[j-1], &view->ranges[j])) {
332
            int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
333 334 335 336 337 338 339 340 341
            ++j;
        }
        ++i;
        memmove(&view->ranges[i], &view->ranges[j],
                (view->nr - j) * sizeof(view->ranges[j]));
        view->nr -= j - i;
    }
}

342 343 344 345 346 347 348 349 350
static bool memory_region_big_endian(MemoryRegion *mr)
{
#ifdef TARGET_WORDS_BIGENDIAN
    return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
#else
    return mr->ops->endianness == DEVICE_BIG_ENDIAN;
#endif
}

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
static bool memory_region_wrong_endianness(MemoryRegion *mr)
{
#ifdef TARGET_WORDS_BIGENDIAN
    return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
#else
    return mr->ops->endianness == DEVICE_BIG_ENDIAN;
#endif
}

static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
{
    if (memory_region_wrong_endianness(mr)) {
        switch (size) {
        case 1:
            break;
        case 2:
            *data = bswap16(*data);
            break;
        case 4:
            *data = bswap32(*data);
            break;
        case 8:
            *data = bswap64(*data);
            break;
        default:
            abort();
        }
    }
}

381 382 383 384 385 386 387 388 389 390 391 392 393 394
static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
{
    MemoryRegion *root;
    hwaddr abs_addr = offset;

    abs_addr += mr->addr;
    for (root = mr; root->container; ) {
        root = root->container;
        abs_addr += root->addr;
    }

    return abs_addr;
}

395 396 397 398 399 400 401 402
static int get_cpu_index(void)
{
    if (current_cpu) {
        return current_cpu->cpu_index;
    }
    return -1;
}

403 404 405 406 407 408 409 410 411 412 413
static MemTxResult memory_region_oldmmio_read_accessor(MemoryRegion *mr,
                                                       hwaddr addr,
                                                       uint64_t *value,
                                                       unsigned size,
                                                       unsigned shift,
                                                       uint64_t mask,
                                                       MemTxAttrs attrs)
{
    uint64_t tmp;

    tmp = mr->ops->old_mmio.read[ctz32(size)](mr->opaque, addr);
414
    if (mr->subpage) {
415
        trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
416 417 418 419 420
    } else if (mr == &io_mem_notdirty) {
        /* Accesses to code which has previously been translated into a TB show
         * up in the MMIO path, as accesses to the io_mem_notdirty
         * MemoryRegion. */
        trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
421 422
    } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
423
        trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
424
    }
425 426 427 428 429
    *value |= (tmp & mask) << shift;
    return MEMTX_OK;
}

static MemTxResult  memory_region_read_accessor(MemoryRegion *mr,
430 431 432 433
                                                hwaddr addr,
                                                uint64_t *value,
                                                unsigned size,
                                                unsigned shift,
434 435
                                                uint64_t mask,
                                                MemTxAttrs attrs)
436 437 438
{
    uint64_t tmp;

439
    tmp = mr->ops->read(mr->opaque, addr, size);
440
    if (mr->subpage) {
441
        trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
442 443 444 445 446
    } else if (mr == &io_mem_notdirty) {
        /* Accesses to code which has previously been translated into a TB show
         * up in the MMIO path, as accesses to the io_mem_notdirty
         * MemoryRegion. */
        trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
447 448
    } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
449
        trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
450
    }
451
    *value |= (tmp & mask) << shift;
452
    return MEMTX_OK;
453 454
}

455 456 457 458 459 460 461
static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
                                                          hwaddr addr,
                                                          uint64_t *value,
                                                          unsigned size,
                                                          unsigned shift,
                                                          uint64_t mask,
                                                          MemTxAttrs attrs)
462
{
463 464
    uint64_t tmp = 0;
    MemTxResult r;
465

466
    r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
467
    if (mr->subpage) {
468
        trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
469 470 471 472 473
    } else if (mr == &io_mem_notdirty) {
        /* Accesses to code which has previously been translated into a TB show
         * up in the MMIO path, as accesses to the io_mem_notdirty
         * MemoryRegion. */
        trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
474 475
    } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
476
        trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
477
    }
478
    *value |= (tmp & mask) << shift;
479
    return r;
480 481
}

482 483 484 485 486 487 488
static MemTxResult memory_region_oldmmio_write_accessor(MemoryRegion *mr,
                                                        hwaddr addr,
                                                        uint64_t *value,
                                                        unsigned size,
                                                        unsigned shift,
                                                        uint64_t mask,
                                                        MemTxAttrs attrs)
489 490 491 492
{
    uint64_t tmp;

    tmp = (*value >> shift) & mask;
493
    if (mr->subpage) {
494
        trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
495 496 497 498 499
    } else if (mr == &io_mem_notdirty) {
        /* Accesses to code which has previously been translated into a TB show
         * up in the MMIO path, as accesses to the io_mem_notdirty
         * MemoryRegion. */
        trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
500 501
    } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
502
        trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
503
    }
504
    mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);
505
    return MEMTX_OK;
506 507
}

508 509 510 511 512 513 514
static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
                                                hwaddr addr,
                                                uint64_t *value,
                                                unsigned size,
                                                unsigned shift,
                                                uint64_t mask,
                                                MemTxAttrs attrs)
515 516 517 518
{
    uint64_t tmp;

    tmp = (*value >> shift) & mask;
519
    if (mr->subpage) {
520
        trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
521 522 523 524 525
    } else if (mr == &io_mem_notdirty) {
        /* Accesses to code which has previously been translated into a TB show
         * up in the MMIO path, as accesses to the io_mem_notdirty
         * MemoryRegion. */
        trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
526 527
    } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
528
        trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
529
    }
530
    mr->ops->write(mr->opaque, addr, tmp, size);
531
    return MEMTX_OK;
532 533
}

534 535 536 537 538 539 540 541 542 543 544
static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
                                                           hwaddr addr,
                                                           uint64_t *value,
                                                           unsigned size,
                                                           unsigned shift,
                                                           uint64_t mask,
                                                           MemTxAttrs attrs)
{
    uint64_t tmp;

    tmp = (*value >> shift) & mask;
545
    if (mr->subpage) {
546
        trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
547 548 549 550 551
    } else if (mr == &io_mem_notdirty) {
        /* Accesses to code which has previously been translated into a TB show
         * up in the MMIO path, as accesses to the io_mem_notdirty
         * MemoryRegion. */
        trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
552 553
    } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
554
        trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
555
    }
556 557 558 559
    return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
}

static MemTxResult access_with_adjusted_size(hwaddr addr,
560 561 562 563
                                      uint64_t *value,
                                      unsigned size,
                                      unsigned access_size_min,
                                      unsigned access_size_max,
564 565 566 567 568 569 570 571
                                      MemTxResult (*access_fn)
                                                  (MemoryRegion *mr,
                                                   hwaddr addr,
                                                   uint64_t *value,
                                                   unsigned size,
                                                   unsigned shift,
                                                   uint64_t mask,
                                                   MemTxAttrs attrs),
572 573
                                      MemoryRegion *mr,
                                      MemTxAttrs attrs)
574 575 576 577
{
    uint64_t access_mask;
    unsigned access_size;
    unsigned i;
578
    MemTxResult r = MEMTX_OK;
579 580 581 582 583 584 585

    if (!access_size_min) {
        access_size_min = 1;
    }
    if (!access_size_max) {
        access_size_max = 4;
    }
586 587

    /* FIXME: support unaligned access? */
588 589
    access_size = MAX(MIN(size, access_size_max), access_size_min);
    access_mask = -1ULL >> (64 - access_size * 8);
590 591
    if (memory_region_big_endian(mr)) {
        for (i = 0; i < size; i += access_size) {
592
            r |= access_fn(mr, addr + i, value, access_size,
593
                        (size - access_size - i) * 8, access_mask, attrs);
594 595 596
        }
    } else {
        for (i = 0; i < size; i += access_size) {
597
            r |= access_fn(mr, addr + i, value, access_size, i * 8,
598
                        access_mask, attrs);
599
        }
600
    }
601
    return r;
602 603
}

604 605
static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
{
606 607
    AddressSpace *as;

608 609
    while (mr->container) {
        mr = mr->container;
610
    }
611 612 613 614
    QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
        if (mr == as->root) {
            return as;
        }
615
    }
616
    return NULL;
617 618
}

619 620 621 622 623
/* Render a memory region into the global view.  Ranges in @view obscure
 * ranges in @mr.
 */
static void render_memory_region(FlatView *view,
                                 MemoryRegion *mr,
624
                                 Int128 base,
625 626
                                 AddrRange clip,
                                 bool readonly)
627 628 629
{
    MemoryRegion *subregion;
    unsigned i;
630
    hwaddr offset_in_region;
631 632
    Int128 remain;
    Int128 now;
633 634 635
    FlatRange fr;
    AddrRange tmp;

636 637 638 639
    if (!mr->enabled) {
        return;
    }

640
    int128_addto(&base, int128_make64(mr->addr));
641
    readonly |= mr->readonly;
642 643 644 645 646 647 648 649 650 651

    tmp = addrrange_make(base, mr->size);

    if (!addrrange_intersects(tmp, clip)) {
        return;
    }

    clip = addrrange_intersection(tmp, clip);

    if (mr->alias) {
652 653
        int128_subfrom(&base, int128_make64(mr->alias->addr));
        int128_subfrom(&base, int128_make64(mr->alias_offset));
654
        render_memory_region(view, mr->alias, base, clip, readonly);
655 656 657 658 659
        return;
    }

    /* Render subregions in priority order. */
    QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
660
        render_memory_region(view, subregion, base, clip, readonly);
661 662
    }

663
    if (!mr->terminates) {
664 665 666
        return;
    }

667
    offset_in_region = int128_get64(int128_sub(clip.start, base));
668 669 670
    base = clip.start;
    remain = clip.size;

671
    fr.mr = mr;
672
    fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
673
    fr.romd_mode = mr->romd_mode;
674 675
    fr.readonly = readonly;

676
    /* Render the region itself into any gaps left by the current view. */
677 678
    for (i = 0; i < view->nr && int128_nz(remain); ++i) {
        if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
679 680
            continue;
        }
681 682 683
        if (int128_lt(base, view->ranges[i].addr.start)) {
            now = int128_min(remain,
                             int128_sub(view->ranges[i].addr.start, base));
684 685 686 687
            fr.offset_in_region = offset_in_region;
            fr.addr = addrrange_make(base, now);
            flatview_insert(view, i, &fr);
            ++i;
688 689 690
            int128_addto(&base, now);
            offset_in_region += int128_get64(now);
            int128_subfrom(&remain, now);
691
        }
692 693 694 695 696 697
        now = int128_sub(int128_min(int128_add(base, remain),
                                    addrrange_end(view->ranges[i].addr)),
                         base);
        int128_addto(&base, now);
        offset_in_region += int128_get64(now);
        int128_subfrom(&remain, now);
698
    }
699
    if (int128_nz(remain)) {
700 701 702 703 704 705
        fr.offset_in_region = offset_in_region;
        fr.addr = addrrange_make(base, remain);
        flatview_insert(view, i, &fr);
    }
}

706 707
static MemoryRegion *memory_region_get_flatview_root(MemoryRegion *mr)
{
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
    while (mr->enabled) {
        if (mr->alias) {
            if (!mr->alias_offset && int128_ge(mr->size, mr->alias->size)) {
                /* The alias is included in its entirety.  Use it as
                 * the "real" root, so that we can share more FlatViews.
                 */
                mr = mr->alias;
                continue;
            }
        } else if (!mr->terminates) {
            unsigned int found = 0;
            MemoryRegion *child, *next = NULL;
            QTAILQ_FOREACH(child, &mr->subregions, subregions_link) {
                if (child->enabled) {
                    if (++found > 1) {
                        next = NULL;
                        break;
                    }
                    if (!child->addr && int128_ge(mr->size, child->size)) {
                        /* A child is included in its entirety.  If it's the only
                         * enabled one, use it in the hope of finding an alias down the
                         * way. This will also let us share FlatViews.
                         */
                        next = child;
                    }
                }
            }
735 736 737
            if (found == 0) {
                return NULL;
            }
738 739 740 741 742 743
            if (next) {
                mr = next;
                continue;
            }
        }

744
        return mr;
745 746
    }

747
    return NULL;
748 749
}

750
/* Render a memory topology into a list of disjoint absolute ranges. */
751
static FlatView *generate_memory_topology(MemoryRegion *mr)
752
{
753
    int i;
754
    FlatView *view;
755

756
    view = flatview_new(mr);
757

758
    if (mr) {
759
        render_memory_region(view, mr, int128_zero(),
760 761
                             addrrange_make(int128_zero(), int128_2_64()), false);
    }
762
    flatview_simplify(view);
763

764 765 766 767 768 769 770
    view->dispatch = address_space_dispatch_new(view);
    for (i = 0; i < view->nr; i++) {
        MemoryRegionSection mrs =
            section_from_flat_range(&view->ranges[i], view);
        flatview_add_to_dispatch(view, &mrs);
    }
    address_space_dispatch_compact(view->dispatch);
771
    g_hash_table_replace(flat_views, mr, view);
772

773 774 775
    return view;
}

776 777 778 779 780 781 782
static void address_space_add_del_ioeventfds(AddressSpace *as,
                                             MemoryRegionIoeventfd *fds_new,
                                             unsigned fds_new_nb,
                                             MemoryRegionIoeventfd *fds_old,
                                             unsigned fds_old_nb)
{
    unsigned iold, inew;
783 784
    MemoryRegionIoeventfd *fd;
    MemoryRegionSection section;
785 786 787 788 789 790 791 792 793 794 795

    /* Generate a symmetric difference of the old and new fd sets, adding
     * and deleting as necessary.
     */

    iold = inew = 0;
    while (iold < fds_old_nb || inew < fds_new_nb) {
        if (iold < fds_old_nb
            && (inew == fds_new_nb
                || memory_region_ioeventfd_before(fds_old[iold],
                                                  fds_new[inew]))) {
796 797
            fd = &fds_old[iold];
            section = (MemoryRegionSection) {
798
                .fv = address_space_to_flatview(as),
799
                .offset_within_address_space = int128_get64(fd->addr.start),
800
                .size = fd->addr.size,
801
            };
802
            MEMORY_LISTENER_CALL(as, eventfd_del, Forward, &section,
803
                                 fd->match_data, fd->data, fd->e);
804 805 806 807 808
            ++iold;
        } else if (inew < fds_new_nb
                   && (iold == fds_old_nb
                       || memory_region_ioeventfd_before(fds_new[inew],
                                                         fds_old[iold]))) {
809 810
            fd = &fds_new[inew];
            section = (MemoryRegionSection) {
811
                .fv = address_space_to_flatview(as),
812
                .offset_within_address_space = int128_get64(fd->addr.start),
813
                .size = fd->addr.size,
814
            };
815
            MEMORY_LISTENER_CALL(as, eventfd_add, Reverse, &section,
816
                                 fd->match_data, fd->data, fd->e);
817 818 819 820 821 822 823 824
            ++inew;
        } else {
            ++iold;
            ++inew;
        }
    }
}

825 826 827 828
static FlatView *address_space_get_flatview(AddressSpace *as)
{
    FlatView *view;

829
    rcu_read_lock();
830
    do {
831
        view = address_space_to_flatview(as);
832 833 834 835
        /* If somebody has replaced as->current_map concurrently,
         * flatview_ref returns false.
         */
    } while (!flatview_ref(view));
836
    rcu_read_unlock();
837 838 839
    return view;
}

840 841
static void address_space_update_ioeventfds(AddressSpace *as)
{
842
    FlatView *view;
843 844 845 846 847 848
    FlatRange *fr;
    unsigned ioeventfd_nb = 0;
    MemoryRegionIoeventfd *ioeventfds = NULL;
    AddrRange tmp;
    unsigned i;

849
    view = address_space_get_flatview(as);
850
    FOR_EACH_FLAT_RANGE(fr, view) {
851 852
        for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
            tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
853 854
                                  int128_sub(fr->addr.start,
                                             int128_make64(fr->offset_in_region)));
855 856
            if (addrrange_intersects(fr->addr, tmp)) {
                ++ioeventfd_nb;
857
                ioeventfds = g_realloc(ioeventfds,
858 859 860 861 862 863 864 865 866 867
                                          ioeventfd_nb * sizeof(*ioeventfds));
                ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
                ioeventfds[ioeventfd_nb-1].addr = tmp;
            }
        }
    }

    address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
                                     as->ioeventfds, as->ioeventfd_nb);

868
    g_free(as->ioeventfds);
869 870
    as->ioeventfds = ioeventfds;
    as->ioeventfd_nb = ioeventfd_nb;
871
    flatview_unref(view);
872 873
}

874
static void address_space_update_topology_pass(AddressSpace *as,
875 876
                                               const FlatView *old_view,
                                               const FlatView *new_view,
877
                                               bool adding)
878 879 880 881 882 883 884 885
{
    unsigned iold, inew;
    FlatRange *frold, *frnew;

    /* Generate a symmetric difference of the old and new memory maps.
     * Kill ranges in the old map, and instantiate ranges in the new map.
     */
    iold = inew = 0;
886 887 888
    while (iold < old_view->nr || inew < new_view->nr) {
        if (iold < old_view->nr) {
            frold = &old_view->ranges[iold];
889 890 891
        } else {
            frold = NULL;
        }
892 893
        if (inew < new_view->nr) {
            frnew = &new_view->ranges[inew];
894 895 896 897 898 899
        } else {
            frnew = NULL;
        }

        if (frold
            && (!frnew
900 901
                || int128_lt(frold->addr.start, frnew->addr.start)
                || (int128_eq(frold->addr.start, frnew->addr.start)
902
                    && !flatrange_equal(frold, frnew)))) {
903
            /* In old but not in new, or in both but attributes changed. */
904

905
            if (!adding) {
906
                MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
907 908
            }

909 910
            ++iold;
        } else if (frold && frnew && flatrange_equal(frold, frnew)) {
911
            /* In both and unchanged (except logging may have changed) */
912

913
            if (adding) {
914
                MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
915 916 917 918 919 920 921 922 923
                if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
                    MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
                                                  frold->dirty_log_mask,
                                                  frnew->dirty_log_mask);
                }
                if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
                    MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
                                                  frold->dirty_log_mask,
                                                  frnew->dirty_log_mask);
924
                }
925 926
            }

927 928 929 930 931
            ++iold;
            ++inew;
        } else {
            /* In new */

932
            if (adding) {
933
                MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
934 935
            }

936 937 938
            ++inew;
        }
    }
939 940
}

941 942
static void flatviews_init(void)
{
943 944
    static FlatView *empty_view;

945 946 947 948 949 950
    if (flat_views) {
        return;
    }

    flat_views = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL,
                                       (GDestroyNotify) flatview_unref);
951 952 953 954 955 956 957 958
    if (!empty_view) {
        empty_view = generate_memory_topology(NULL);
        /* We keep it alive forever in the global variable.  */
        flatview_ref(empty_view);
    } else {
        g_hash_table_replace(flat_views, NULL, empty_view);
        flatview_ref(empty_view);
    }
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
}

static void flatviews_reset(void)
{
    AddressSpace *as;

    if (flat_views) {
        g_hash_table_unref(flat_views);
        flat_views = NULL;
    }
    flatviews_init();

    /* Render unique FVs */
    QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
        MemoryRegion *physmr = memory_region_get_flatview_root(as->root);

        if (g_hash_table_lookup(flat_views, physmr)) {
            continue;
        }

        generate_memory_topology(physmr);
    }
}

static void address_space_set_flatview(AddressSpace *as)
984
{
985
    FlatView *old_view = address_space_to_flatview(as);
986 987 988 989 990
    MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
    FlatView *new_view = g_hash_table_lookup(flat_views, physmr);

    assert(new_view);

991 992 993 994 995 996 997 998
    if (old_view == new_view) {
        return;
    }

    if (old_view) {
        flatview_ref(old_view);
    }

999
    flatview_ref(new_view);
1000 1001

    if (!QTAILQ_EMPTY(&as->listeners)) {
1002 1003 1004 1005 1006 1007 1008
        FlatView tmpview = { .nr = 0 }, *old_view2 = old_view;

        if (!old_view2) {
            old_view2 = &tmpview;
        }
        address_space_update_topology_pass(as, old_view2, new_view, false);
        address_space_update_topology_pass(as, old_view2, new_view, true);
1009
    }
1010

1011 1012
    /* Writes are protected by the BQL.  */
    atomic_rcu_set(&as->current_map, new_view);
1013 1014 1015
    if (old_view) {
        flatview_unref(old_view);
    }
1016 1017 1018 1019 1020 1021 1022

    /* Note that all the old MemoryRegions are still alive up to this
     * point.  This relieves most MemoryListeners from the need to
     * ref/unref the MemoryRegions they get---unless they use them
     * outside the iothread mutex, in which case precise reference
     * counting is necessary.
     */
1023 1024 1025
    if (old_view) {
        flatview_unref(old_view);
    }
1026 1027
}

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
static void address_space_update_topology(AddressSpace *as)
{
    MemoryRegion *physmr = memory_region_get_flatview_root(as->root);

    flatviews_init();
    if (!g_hash_table_lookup(flat_views, physmr)) {
        generate_memory_topology(physmr);
    }
    address_space_set_flatview(as);
}

Avi Kivity's avatar
Avi Kivity committed
1039 1040
void memory_region_transaction_begin(void)
{
1041
    qemu_flush_coalesced_mmio_buffer();
Avi Kivity's avatar
Avi Kivity committed
1042 1043 1044 1045 1046
    ++memory_region_transaction_depth;
}

void memory_region_transaction_commit(void)
{
1047 1048
    AddressSpace *as;

Avi Kivity's avatar
Avi Kivity committed
1049
    assert(memory_region_transaction_depth);
1050 1051
    assert(qemu_mutex_iothread_locked());

Avi Kivity's avatar
Avi Kivity committed
1052
    --memory_region_transaction_depth;
1053 1054
    if (!memory_region_transaction_depth) {
        if (memory_region_update_pending) {
1055 1056
            flatviews_reset();

1057
            MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
1058

1059
            QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1060
                address_space_set_flatview(as);
1061
                address_space_update_ioeventfds(as);
1062
            }
1063
            memory_region_update_pending = false;
1064
            ioeventfd_update_pending = false;
1065 1066 1067 1068 1069
            MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
        } else if (ioeventfd_update_pending) {
            QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
                address_space_update_ioeventfds(as);
            }
1070
            ioeventfd_update_pending = false;
1071 1072
        }
   }
Avi Kivity's avatar
Avi Kivity committed
1073 1074
}

1075 1076 1077 1078 1079 1080
static void memory_region_destructor_none(MemoryRegion *mr)
{
}

static void memory_region_destructor_ram(MemoryRegion *mr)
{
1081
    qemu_ram_free(mr->ram_block);
1082 1083
}

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
static bool memory_region_need_escape(char c)
{
    return c == '/' || c == '[' || c == '\\' || c == ']';
}

static char *memory_region_escape_name(const char *name)
{
    const char *p;
    char *escaped, *q;
    uint8_t c;
    size_t bytes = 0;

    for (p = name; *p; p++) {
        bytes += memory_region_need_escape(*p) ? 4 : 1;
    }
    if (bytes == p - name) {
       return g_memdup(name, bytes + 1);
    }

    escaped = g_malloc(bytes + 1);
    for (p = name, q = escaped; *p; p++) {
        c = *p;
        if (unlikely(memory_region_need_escape(c))) {
            *q++ = '\\';
            *q++ = 'x';
            *q++ = "0123456789abcdef"[c >> 4];
            c = "0123456789abcdef"[c & 15];
        }
        *q++ = c;
    }
    *q = 0;
    return escaped;
}

1118 1119 1120 1121
static void memory_region_do_init(MemoryRegion *mr,
                                  Object *owner,
                                  const char *name,
                                  uint64_t size)
1122
{
1123 1124 1125 1126
    mr->size = int128_make64(size);
    if (size == UINT64_MAX) {
        mr->size = int128_2_64();
    }
1127
    mr->name = g_strdup(name);
1128
    mr->owner = owner;
1129
    mr->ram_block = NULL;
1130 1131

    if (name) {
1132 1133
        char *escaped_name = memory_region_escape_name(name);
        char *name_array = g_strdup_printf("%s[*]", escaped_name);
1134 1135 1136 1137 1138

        if (!owner) {
            owner = container_get(qdev_get_machine(), "/unattached");
        }

1139
        object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
1140
        object_unref(OBJECT(mr));
1141 1142
        g_free(name_array);
        g_free(escaped_name);
1143 1144 1145
    }
}

1146 1147 1148 1149 1150 1151 1152 1153 1154
void memory_region_init(MemoryRegion *mr,
                        Object *owner,
                        const char *name,
                        uint64_t size)
{
    object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
    memory_region_do_init(mr, owner, name, size);
}

1155 1156
static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
                                   void *opaque, Error **errp)
1157 1158 1159 1160
{
    MemoryRegion *mr = MEMORY_REGION(obj);
    uint64_t value = mr->addr;

1161
    visit_type_uint64(v, name, &value, errp);
1162 1163
}

1164 1165 1166
static void memory_region_get_container(Object *obj, Visitor *v,
                                        const char *name, void *opaque,
                                        Error **errp)
1167 1168 1169 1170 1171 1172 1173
{
    MemoryRegion *mr = MEMORY_REGION(obj);
    gchar *path = (gchar *)"";

    if (mr->container) {
        path = object_get_canonical_path(OBJECT(mr->container));
    }
1174
    visit_type_str(v, name, &path, errp);
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    if (mr->container) {
        g_free(path);
    }
}

static Object *memory_region_resolve_container(Object *obj, void *opaque,
                                               const char *part)
{
    MemoryRegion *mr = MEMORY_REGION(obj);

    return OBJECT(mr->container);
}

1188 1189 1190
static void memory_region_get_priority(Object *obj, Visitor *v,
                                       const char *name, void *opaque,
                                       Error **errp)
1191 1192 1193 1194
{
    MemoryRegion *mr = MEMORY_REGION(obj);
    int32_t value = mr->priority;

1195
    visit_type_int32(v, name, &value, errp);
1196 1197
}

1198 1199
static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
                                   void *opaque, Error **errp)
1200 1201 1202 1203
{
    MemoryRegion *mr = MEMORY_REGION(obj);
    uint64_t value = memory_region_size(mr);

1204
    visit_type_uint64(v, name, &value, errp);
1205 1206
}

1207 1208 1209
static void memory_region_initfn(Object *obj)
{
    MemoryRegion *mr = MEMORY_REGION(obj);
1210
    ObjectProperty *op;
1211 1212

    mr->ops = &unassigned_mem_ops;
1213
    mr->enabled = true;
1214
    mr->romd_mode = true;
1215
    mr->global_locking = true;
1216
    mr->destructor = memory_region_destructor_none;
1217 1218
    QTAILQ_INIT(&mr->subregions);
    QTAILQ_INIT(&mr->coalesced);
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

    op = object_property_add(OBJECT(mr), "container",
                             "link<" TYPE_MEMORY_REGION ">",
                             memory_region_get_container,
                             NULL, /* memory_region_set_container */
                             NULL, NULL, &error_abort);
    op->resolve = memory_region_resolve_container;

    object_property_add(OBJECT(mr), "addr", "uint64",
                        memory_region_get_addr,
                        NULL, /* memory_region_set_addr */
                        NULL, NULL, &error_abort);
1231 1232 1233 1234
    object_property_add(OBJECT(mr), "priority", "uint32",
                        memory_region_get_priority,
                        NULL, /* memory_region_set_priority */
                        NULL, NULL, &error_abort);
1235 1236 1237 1238
    object_property_add(OBJECT(mr), "size", "uint64",
                        memory_region_get_size,
                        NULL, /* memory_region_set_size, */
                        NULL, NULL, &error_abort);
1239 1240
}

1241 1242 1243 1244 1245 1246 1247
static void iommu_memory_region_initfn(Object *obj)
{
    MemoryRegion *mr = MEMORY_REGION(obj);

    mr->is_iommu = true;
}

1248 1249 1250 1251 1252 1253
static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
                                    unsigned size)
{
#ifdef DEBUG_UNASSIGNED
    printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
#endif
1254 1255
    if (current_cpu != NULL) {
        cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1256
    }
1257
    return 0;
1258 1259 1260 1261 1262 1263 1264 1265
}

static void unassigned_mem_write(void *opaque, hwaddr addr,
                                 uint64_t val, unsigned size)
{
#ifdef DEBUG_UNASSIGNED
    printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
#endif
1266 1267
    if (current_cpu != NULL) {
        cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1268
    }
1269 1270
}

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
                                   unsigned size, bool is_write)
{
    return false;
}

const MemoryRegionOps unassigned_mem_ops = {
    .valid.accepts = unassigned_mem_accepts,
    .endianness = DEVICE_NATIVE_ENDIAN,
};

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
static uint64_t memory_region_ram_device_read(void *opaque,
                                              hwaddr addr, unsigned size)
{
    MemoryRegion *mr = opaque;
    uint64_t data = (uint64_t)~0;

    switch (size) {
    case 1:
        data = *(uint8_t *)(mr->ram_block->host + addr);
        break;
    case 2:
        data = *(uint16_t *)(mr->ram_block->host + addr);
        break;
    case 4:
        data = *(uint32_t *)(mr->ram_block->host + addr);
        break;
    case 8:
        data = *(uint64_t *)(mr->ram_block->host + addr);
        break;
    }

    trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);

    return data;
}

static void memory_region_ram_device_write(void *opaque, hwaddr addr,
                                           uint64_t data, unsigned size)
{
    MemoryRegion *mr = opaque;

    trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);

    switch (size) {
    case 1:
        *(uint8_t *)(mr->ram_block->host + addr) = (uint8_t)data;
        break;
    case 2:
        *(uint16_t *)(mr->ram_block->host + addr) = (uint16_t)data;
        break;
    case 4:
        *(uint32_t *)(mr->ram_block->host + addr) = (uint32_t)data;
        break;
    case 8:
        *(uint64_t *)(mr->ram_block->host + addr) = data;
        break;
    }
}

static const MemoryRegionOps ram_device_mem_ops = {
    .read = memory_region_ram_device_read,
    .write = memory_region_ram_device_write,
1334
    .endianness = DEVICE_HOST_ENDIAN,
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    .valid = {
        .min_access_size = 1,
        .max_access_size = 8,
        .unaligned = true,
    },
    .impl = {
        .min_access_size = 1,
        .max_access_size = 8,
        .unaligned = true,
    },
};

1347 1348 1349 1350
bool memory_region_access_valid(MemoryRegion *mr,
                                hwaddr addr,
                                unsigned size,
                                bool is_write)
1351
{
1352 1353
    int access_size_min, access_size_max;
    int access_size, i;
1354

1355 1356 1357 1358
    if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
        return false;
    }

1359
    if (!mr->ops->valid.accepts) {
1360 1361 1362
        return true;
    }

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
    access_size_min = mr->ops->valid.min_access_size;
    if (!mr->ops->valid.min_access_size) {
        access_size_min = 1;
    }

    access_size_max = mr->ops->valid.max_access_size;
    if (!mr->ops->valid.max_access_size) {
        access_size_max = 4;
    }

    access_size = MAX(MIN(size, access_size_max), access_size_min);
    for (i = 0; i < size; i += access_size) {
        if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
                                    is_write)) {
            return false;
        }
1379
    }