]> git.proxmox.com Git - mirror_qemu.git/blame - memory.c
Merge remote-tracking branch 'remotes/bonzini/tags/for-upstream' into staging
[mirror_qemu.git] / memory.c
CommitLineData
093bc2cd
AK
1/*
2 * Physical memory management
3 *
4 * Copyright 2011 Red Hat, Inc. and/or its affiliates
5 *
6 * Authors:
7 * Avi Kivity <avi@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
6b620ca3
PB
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
093bc2cd
AK
14 */
15
d38ea87a 16#include "qemu/osdep.h"
da34e65c 17#include "qapi/error.h"
33c11879 18#include "cpu.h"
022c62cb
PB
19#include "exec/memory.h"
20#include "exec/address-spaces.h"
409ddd01 21#include "qapi/visitor.h"
1de7afc9 22#include "qemu/bitops.h"
8c56c1a5 23#include "qemu/error-report.h"
b6b71cb5 24#include "qemu/qemu-print.h"
2c9b15ca 25#include "qom/object.h"
0ab8ed18 26#include "trace-root.h"
093bc2cd 27
022c62cb 28#include "exec/memory-internal.h"
220c3ebd 29#include "exec/ram_addr.h"
8c56c1a5 30#include "sysemu/kvm.h"
e1c57ab8 31#include "sysemu/sysemu.h"
14a48c1d 32#include "sysemu/tcg.h"
c9356746 33#include "hw/qdev-properties.h"
b08199c6 34#include "migration/vmstate.h"
67d95c15 35
d197063f
PB
36//#define DEBUG_UNASSIGNED
37
22bde714
JK
38static unsigned memory_region_transaction_depth;
39static bool memory_region_update_pending;
4dc56152 40static bool ioeventfd_update_pending;
7664e80c
AK
41static bool global_dirty_log = false;
42
eae3eb3e 43static QTAILQ_HEAD(, MemoryListener) memory_listeners
72e22d2f 44 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
4ef4db86 45
0d673e36
AK
46static QTAILQ_HEAD(, AddressSpace) address_spaces
47 = QTAILQ_HEAD_INITIALIZER(address_spaces);
48
967dc9b1
AK
49static GHashTable *flat_views;
50
093bc2cd
AK
51typedef struct AddrRange AddrRange;
52
8417cebf 53/*
c9cdaa3a 54 * Note that signed integers are needed for negative offsetting in aliases
8417cebf
AK
55 * (large MemoryRegion::alias_offset).
56 */
093bc2cd 57struct AddrRange {
08dafab4
AK
58 Int128 start;
59 Int128 size;
093bc2cd
AK
60};
61
08dafab4 62static AddrRange addrrange_make(Int128 start, Int128 size)
093bc2cd
AK
63{
64 return (AddrRange) { start, size };
65}
66
67static bool addrrange_equal(AddrRange r1, AddrRange r2)
68{
08dafab4 69 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
093bc2cd
AK
70}
71
08dafab4 72static Int128 addrrange_end(AddrRange r)
093bc2cd 73{
08dafab4 74 return int128_add(r.start, r.size);
093bc2cd
AK
75}
76
08dafab4 77static AddrRange addrrange_shift(AddrRange range, Int128 delta)
093bc2cd 78{
08dafab4 79 int128_addto(&range.start, delta);
093bc2cd
AK
80 return range;
81}
82
08dafab4
AK
83static bool addrrange_contains(AddrRange range, Int128 addr)
84{
85 return int128_ge(addr, range.start)
86 && int128_lt(addr, addrrange_end(range));
87}
88
093bc2cd
AK
89static bool addrrange_intersects(AddrRange r1, AddrRange r2)
90{
08dafab4
AK
91 return addrrange_contains(r1, r2.start)
92 || addrrange_contains(r2, r1.start);
093bc2cd
AK
93}
94
95static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
96{
08dafab4
AK
97 Int128 start = int128_max(r1.start, r2.start);
98 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
99 return addrrange_make(start, int128_sub(end, start));
093bc2cd
AK
100}
101
0e0d36b4
AK
102enum ListenerDirection { Forward, Reverse };
103
7376e582 104#define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
0e0d36b4
AK
105 do { \
106 MemoryListener *_listener; \
107 \
108 switch (_direction) { \
109 case Forward: \
110 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
975aefe0
AK
111 if (_listener->_callback) { \
112 _listener->_callback(_listener, ##_args); \
113 } \
0e0d36b4
AK
114 } \
115 break; \
116 case Reverse: \
eae3eb3e 117 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, link) { \
975aefe0
AK
118 if (_listener->_callback) { \
119 _listener->_callback(_listener, ##_args); \
120 } \
0e0d36b4
AK
121 } \
122 break; \
123 default: \
124 abort(); \
125 } \
126 } while (0)
127
9a54635d 128#define MEMORY_LISTENER_CALL(_as, _callback, _direction, _section, _args...) \
7376e582
AK
129 do { \
130 MemoryListener *_listener; \
131 \
132 switch (_direction) { \
133 case Forward: \
eae3eb3e 134 QTAILQ_FOREACH(_listener, &(_as)->listeners, link_as) { \
9a54635d 135 if (_listener->_callback) { \
7376e582
AK
136 _listener->_callback(_listener, _section, ##_args); \
137 } \
138 } \
139 break; \
140 case Reverse: \
eae3eb3e 141 QTAILQ_FOREACH_REVERSE(_listener, &(_as)->listeners, link_as) { \
9a54635d 142 if (_listener->_callback) { \
7376e582
AK
143 _listener->_callback(_listener, _section, ##_args); \
144 } \
145 } \
146 break; \
147 default: \
148 abort(); \
149 } \
150 } while (0)
151
dfde4e6e 152/* No need to ref/unref .mr, the FlatRange keeps it alive. */
b2dfd71c 153#define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...) \
9c1f8f44 154 do { \
16620684
AK
155 MemoryRegionSection mrs = section_from_flat_range(fr, \
156 address_space_to_flatview(as)); \
9a54635d 157 MEMORY_LISTENER_CALL(as, callback, dir, &mrs, ##_args); \
9c1f8f44 158 } while(0)
0e0d36b4 159
093bc2cd
AK
160struct CoalescedMemoryRange {
161 AddrRange addr;
162 QTAILQ_ENTRY(CoalescedMemoryRange) link;
163};
164
3e9d69e7
AK
165struct MemoryRegionIoeventfd {
166 AddrRange addr;
167 bool match_data;
168 uint64_t data;
753d5e14 169 EventNotifier *e;
3e9d69e7
AK
170};
171
73bb753d
TB
172static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd *a,
173 MemoryRegionIoeventfd *b)
3e9d69e7 174{
73bb753d 175 if (int128_lt(a->addr.start, b->addr.start)) {
3e9d69e7 176 return true;
73bb753d 177 } else if (int128_gt(a->addr.start, b->addr.start)) {
3e9d69e7 178 return false;
73bb753d 179 } else if (int128_lt(a->addr.size, b->addr.size)) {
3e9d69e7 180 return true;
73bb753d 181 } else if (int128_gt(a->addr.size, b->addr.size)) {
3e9d69e7 182 return false;
73bb753d 183 } else if (a->match_data < b->match_data) {
3e9d69e7 184 return true;
73bb753d 185 } else if (a->match_data > b->match_data) {
3e9d69e7 186 return false;
73bb753d
TB
187 } else if (a->match_data) {
188 if (a->data < b->data) {
3e9d69e7 189 return true;
73bb753d 190 } else if (a->data > b->data) {
3e9d69e7
AK
191 return false;
192 }
193 }
73bb753d 194 if (a->e < b->e) {
3e9d69e7 195 return true;
73bb753d 196 } else if (a->e > b->e) {
3e9d69e7
AK
197 return false;
198 }
199 return false;
200}
201
73bb753d
TB
202static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd *a,
203 MemoryRegionIoeventfd *b)
3e9d69e7
AK
204{
205 return !memory_region_ioeventfd_before(a, b)
206 && !memory_region_ioeventfd_before(b, a);
207}
208
093bc2cd
AK
209/* Range of memory in the global map. Addresses are absolute. */
210struct FlatRange {
211 MemoryRegion *mr;
a8170e5e 212 hwaddr offset_in_region;
093bc2cd 213 AddrRange addr;
5a583347 214 uint8_t dirty_log_mask;
b138e654 215 bool romd_mode;
fb1cd6f9 216 bool readonly;
c26763f8 217 bool nonvolatile;
3ac7d43a 218 int has_coalesced_range;
093bc2cd
AK
219};
220
093bc2cd
AK
221#define FOR_EACH_FLAT_RANGE(var, view) \
222 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
223
9c1f8f44 224static inline MemoryRegionSection
16620684 225section_from_flat_range(FlatRange *fr, FlatView *fv)
9c1f8f44
PB
226{
227 return (MemoryRegionSection) {
228 .mr = fr->mr,
16620684 229 .fv = fv,
9c1f8f44
PB
230 .offset_within_region = fr->offset_in_region,
231 .size = fr->addr.size,
232 .offset_within_address_space = int128_get64(fr->addr.start),
233 .readonly = fr->readonly,
c26763f8 234 .nonvolatile = fr->nonvolatile,
9c1f8f44
PB
235 };
236}
237
093bc2cd
AK
238static bool flatrange_equal(FlatRange *a, FlatRange *b)
239{
240 return a->mr == b->mr
241 && addrrange_equal(a->addr, b->addr)
d0a9b5bc 242 && a->offset_in_region == b->offset_in_region
b138e654 243 && a->romd_mode == b->romd_mode
c26763f8
MAL
244 && a->readonly == b->readonly
245 && a->nonvolatile == b->nonvolatile;
093bc2cd
AK
246}
247
89c177bb 248static FlatView *flatview_new(MemoryRegion *mr_root)
093bc2cd 249{
cc94cd6d
AK
250 FlatView *view;
251
252 view = g_new0(FlatView, 1);
856d7245 253 view->ref = 1;
89c177bb
AK
254 view->root = mr_root;
255 memory_region_ref(mr_root);
02d9651d 256 trace_flatview_new(view, mr_root);
cc94cd6d
AK
257
258 return view;
093bc2cd
AK
259}
260
261/* Insert a range into a given position. Caller is responsible for maintaining
262 * sorting order.
263 */
264static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
265{
266 if (view->nr == view->nr_allocated) {
267 view->nr_allocated = MAX(2 * view->nr, 10);
7267c094 268 view->ranges = g_realloc(view->ranges,
093bc2cd
AK
269 view->nr_allocated * sizeof(*view->ranges));
270 }
271 memmove(view->ranges + pos + 1, view->ranges + pos,
272 (view->nr - pos) * sizeof(FlatRange));
273 view->ranges[pos] = *range;
dfde4e6e 274 memory_region_ref(range->mr);
093bc2cd
AK
275 ++view->nr;
276}
277
278static void flatview_destroy(FlatView *view)
279{
dfde4e6e
PB
280 int i;
281
02d9651d 282 trace_flatview_destroy(view, view->root);
66a6df1d
AK
283 if (view->dispatch) {
284 address_space_dispatch_free(view->dispatch);
285 }
dfde4e6e
PB
286 for (i = 0; i < view->nr; i++) {
287 memory_region_unref(view->ranges[i].mr);
288 }
7267c094 289 g_free(view->ranges);
89c177bb 290 memory_region_unref(view->root);
a9a0c06d 291 g_free(view);
093bc2cd
AK
292}
293
447b0d0b 294static bool flatview_ref(FlatView *view)
856d7245 295{
447b0d0b 296 return atomic_fetch_inc_nonzero(&view->ref) > 0;
856d7245
PB
297}
298
48564041 299void flatview_unref(FlatView *view)
856d7245
PB
300{
301 if (atomic_fetch_dec(&view->ref) == 1) {
02d9651d 302 trace_flatview_destroy_rcu(view, view->root);
092aa2fc 303 assert(view->root);
66a6df1d 304 call_rcu(view, flatview_destroy, rcu);
856d7245
PB
305 }
306}
307
3d8e6bf9
AK
308static bool can_merge(FlatRange *r1, FlatRange *r2)
309{
08dafab4 310 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
3d8e6bf9 311 && r1->mr == r2->mr
08dafab4
AK
312 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
313 r1->addr.size),
314 int128_make64(r2->offset_in_region))
d0a9b5bc 315 && r1->dirty_log_mask == r2->dirty_log_mask
b138e654 316 && r1->romd_mode == r2->romd_mode
c26763f8
MAL
317 && r1->readonly == r2->readonly
318 && r1->nonvolatile == r2->nonvolatile;
3d8e6bf9
AK
319}
320
8508e024 321/* Attempt to simplify a view by merging adjacent ranges */
3d8e6bf9
AK
322static void flatview_simplify(FlatView *view)
323{
324 unsigned i, j;
325
326 i = 0;
327 while (i < view->nr) {
328 j = i + 1;
329 while (j < view->nr
330 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
08dafab4 331 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
3d8e6bf9
AK
332 ++j;
333 }
334 ++i;
335 memmove(&view->ranges[i], &view->ranges[j],
336 (view->nr - j) * sizeof(view->ranges[j]));
337 view->nr -= j - i;
338 }
339}
340
e7342aa3
PB
341static bool memory_region_big_endian(MemoryRegion *mr)
342{
343#ifdef TARGET_WORDS_BIGENDIAN
344 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
345#else
346 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
347#endif
348}
349
e11ef3d1
PB
350static bool memory_region_wrong_endianness(MemoryRegion *mr)
351{
352#ifdef TARGET_WORDS_BIGENDIAN
353 return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
354#else
355 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
356#endif
357}
358
359static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
360{
361 if (memory_region_wrong_endianness(mr)) {
362 switch (size) {
363 case 1:
364 break;
365 case 2:
366 *data = bswap16(*data);
367 break;
368 case 4:
369 *data = bswap32(*data);
370 break;
371 case 8:
372 *data = bswap64(*data);
373 break;
374 default:
375 abort();
376 }
377 }
378}
379
3c754a93 380static inline void memory_region_shift_read_access(uint64_t *value,
98f52cdb 381 signed shift,
3c754a93
PMD
382 uint64_t mask,
383 uint64_t tmp)
384{
98f52cdb
PMD
385 if (shift >= 0) {
386 *value |= (tmp & mask) << shift;
387 } else {
388 *value |= (tmp & mask) >> -shift;
389 }
3c754a93
PMD
390}
391
392static inline uint64_t memory_region_shift_write_access(uint64_t *value,
98f52cdb 393 signed shift,
3c754a93
PMD
394 uint64_t mask)
395{
98f52cdb
PMD
396 uint64_t tmp;
397
398 if (shift >= 0) {
399 tmp = (*value >> shift) & mask;
400 } else {
401 tmp = (*value << -shift) & mask;
402 }
403
404 return tmp;
3c754a93
PMD
405}
406
4779dc1d
HB
407static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
408{
409 MemoryRegion *root;
410 hwaddr abs_addr = offset;
411
412 abs_addr += mr->addr;
413 for (root = mr; root->container; ) {
414 root = root->container;
415 abs_addr += root->addr;
416 }
417
418 return abs_addr;
419}
420
5a68be94
HB
421static int get_cpu_index(void)
422{
423 if (current_cpu) {
424 return current_cpu->cpu_index;
425 }
426 return -1;
427}
428
cc05c43a 429static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
ce5d2f33
PB
430 hwaddr addr,
431 uint64_t *value,
432 unsigned size,
98f52cdb 433 signed shift,
cc05c43a
PM
434 uint64_t mask,
435 MemTxAttrs attrs)
ce5d2f33 436{
ce5d2f33
PB
437 uint64_t tmp;
438
cc05c43a 439 tmp = mr->ops->read(mr->opaque, addr, size);
23d92d68 440 if (mr->subpage) {
5a68be94 441 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
f2d08942
HB
442 } else if (mr == &io_mem_notdirty) {
443 /* Accesses to code which has previously been translated into a TB show
444 * up in the MMIO path, as accesses to the io_mem_notdirty
445 * MemoryRegion. */
446 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
4779dc1d
HB
447 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
448 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
5a68be94 449 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
23d92d68 450 }
3c754a93 451 memory_region_shift_read_access(value, shift, mask, tmp);
cc05c43a 452 return MEMTX_OK;
ce5d2f33
PB
453}
454
cc05c43a
PM
455static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
456 hwaddr addr,
457 uint64_t *value,
458 unsigned size,
98f52cdb 459 signed shift,
cc05c43a
PM
460 uint64_t mask,
461 MemTxAttrs attrs)
164a4dcd 462{
cc05c43a
PM
463 uint64_t tmp = 0;
464 MemTxResult r;
164a4dcd 465
cc05c43a 466 r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
23d92d68 467 if (mr->subpage) {
5a68be94 468 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
f2d08942
HB
469 } else if (mr == &io_mem_notdirty) {
470 /* Accesses to code which has previously been translated into a TB show
471 * up in the MMIO path, as accesses to the io_mem_notdirty
472 * MemoryRegion. */
473 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
4779dc1d
HB
474 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
475 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
5a68be94 476 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
23d92d68 477 }
3c754a93 478 memory_region_shift_read_access(value, shift, mask, tmp);
cc05c43a 479 return r;
164a4dcd
AK
480}
481
cc05c43a
PM
482static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
483 hwaddr addr,
484 uint64_t *value,
485 unsigned size,
98f52cdb 486 signed shift,
cc05c43a
PM
487 uint64_t mask,
488 MemTxAttrs attrs)
164a4dcd 489{
3c754a93 490 uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
164a4dcd 491
23d92d68 492 if (mr->subpage) {
5a68be94 493 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
f2d08942
HB
494 } else if (mr == &io_mem_notdirty) {
495 /* Accesses to code which has previously been translated into a TB show
496 * up in the MMIO path, as accesses to the io_mem_notdirty
497 * MemoryRegion. */
498 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
4779dc1d
HB
499 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
500 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
5a68be94 501 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
23d92d68 502 }
164a4dcd 503 mr->ops->write(mr->opaque, addr, tmp, size);
cc05c43a 504 return MEMTX_OK;
164a4dcd
AK
505}
506
cc05c43a
PM
507static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
508 hwaddr addr,
509 uint64_t *value,
510 unsigned size,
98f52cdb 511 signed shift,
cc05c43a
PM
512 uint64_t mask,
513 MemTxAttrs attrs)
514{
3c754a93 515 uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
cc05c43a 516
23d92d68 517 if (mr->subpage) {
5a68be94 518 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
f2d08942
HB
519 } else if (mr == &io_mem_notdirty) {
520 /* Accesses to code which has previously been translated into a TB show
521 * up in the MMIO path, as accesses to the io_mem_notdirty
522 * MemoryRegion. */
523 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
4779dc1d
HB
524 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
525 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
5a68be94 526 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
23d92d68 527 }
cc05c43a
PM
528 return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
529}
530
531static MemTxResult access_with_adjusted_size(hwaddr addr,
164a4dcd
AK
532 uint64_t *value,
533 unsigned size,
534 unsigned access_size_min,
535 unsigned access_size_max,
05e015f7
KF
536 MemTxResult (*access_fn)
537 (MemoryRegion *mr,
538 hwaddr addr,
539 uint64_t *value,
540 unsigned size,
98f52cdb 541 signed shift,
05e015f7
KF
542 uint64_t mask,
543 MemTxAttrs attrs),
cc05c43a
PM
544 MemoryRegion *mr,
545 MemTxAttrs attrs)
164a4dcd
AK
546{
547 uint64_t access_mask;
548 unsigned access_size;
549 unsigned i;
cc05c43a 550 MemTxResult r = MEMTX_OK;
164a4dcd
AK
551
552 if (!access_size_min) {
553 access_size_min = 1;
554 }
555 if (!access_size_max) {
556 access_size_max = 4;
557 }
ce5d2f33
PB
558
559 /* FIXME: support unaligned access? */
164a4dcd 560 access_size = MAX(MIN(size, access_size_max), access_size_min);
36960b4d 561 access_mask = MAKE_64BIT_MASK(0, access_size * 8);
e7342aa3
PB
562 if (memory_region_big_endian(mr)) {
563 for (i = 0; i < size; i += access_size) {
05e015f7 564 r |= access_fn(mr, addr + i, value, access_size,
cc05c43a 565 (size - access_size - i) * 8, access_mask, attrs);
e7342aa3
PB
566 }
567 } else {
568 for (i = 0; i < size; i += access_size) {
05e015f7 569 r |= access_fn(mr, addr + i, value, access_size, i * 8,
cc05c43a 570 access_mask, attrs);
e7342aa3 571 }
164a4dcd 572 }
cc05c43a 573 return r;
164a4dcd
AK
574}
575
e2177955
AK
576static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
577{
0d673e36
AK
578 AddressSpace *as;
579
feca4ac1
PB
580 while (mr->container) {
581 mr = mr->container;
e2177955 582 }
0d673e36
AK
583 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
584 if (mr == as->root) {
585 return as;
586 }
e2177955 587 }
eed2bacf 588 return NULL;
e2177955
AK
589}
590
093bc2cd
AK
591/* Render a memory region into the global view. Ranges in @view obscure
592 * ranges in @mr.
593 */
594static void render_memory_region(FlatView *view,
595 MemoryRegion *mr,
08dafab4 596 Int128 base,
fb1cd6f9 597 AddrRange clip,
c26763f8
MAL
598 bool readonly,
599 bool nonvolatile)
093bc2cd
AK
600{
601 MemoryRegion *subregion;
602 unsigned i;
a8170e5e 603 hwaddr offset_in_region;
08dafab4
AK
604 Int128 remain;
605 Int128 now;
093bc2cd
AK
606 FlatRange fr;
607 AddrRange tmp;
608
6bba19ba
AK
609 if (!mr->enabled) {
610 return;
611 }
612
08dafab4 613 int128_addto(&base, int128_make64(mr->addr));
fb1cd6f9 614 readonly |= mr->readonly;
c26763f8 615 nonvolatile |= mr->nonvolatile;
093bc2cd
AK
616
617 tmp = addrrange_make(base, mr->size);
618
619 if (!addrrange_intersects(tmp, clip)) {
620 return;
621 }
622
623 clip = addrrange_intersection(tmp, clip);
624
625 if (mr->alias) {
08dafab4
AK
626 int128_subfrom(&base, int128_make64(mr->alias->addr));
627 int128_subfrom(&base, int128_make64(mr->alias_offset));
c26763f8
MAL
628 render_memory_region(view, mr->alias, base, clip,
629 readonly, nonvolatile);
093bc2cd
AK
630 return;
631 }
632
633 /* Render subregions in priority order. */
634 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
c26763f8
MAL
635 render_memory_region(view, subregion, base, clip,
636 readonly, nonvolatile);
093bc2cd
AK
637 }
638
14a3c10a 639 if (!mr->terminates) {
093bc2cd
AK
640 return;
641 }
642
08dafab4 643 offset_in_region = int128_get64(int128_sub(clip.start, base));
093bc2cd
AK
644 base = clip.start;
645 remain = clip.size;
646
2eb74e1a 647 fr.mr = mr;
6f6a5ef3 648 fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
b138e654 649 fr.romd_mode = mr->romd_mode;
2eb74e1a 650 fr.readonly = readonly;
c26763f8 651 fr.nonvolatile = nonvolatile;
3ac7d43a 652 fr.has_coalesced_range = 0;
2eb74e1a 653
093bc2cd 654 /* Render the region itself into any gaps left by the current view. */
08dafab4
AK
655 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
656 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
093bc2cd
AK
657 continue;
658 }
08dafab4
AK
659 if (int128_lt(base, view->ranges[i].addr.start)) {
660 now = int128_min(remain,
661 int128_sub(view->ranges[i].addr.start, base));
093bc2cd
AK
662 fr.offset_in_region = offset_in_region;
663 fr.addr = addrrange_make(base, now);
664 flatview_insert(view, i, &fr);
665 ++i;
08dafab4
AK
666 int128_addto(&base, now);
667 offset_in_region += int128_get64(now);
668 int128_subfrom(&remain, now);
093bc2cd 669 }
d26a8cae
AK
670 now = int128_sub(int128_min(int128_add(base, remain),
671 addrrange_end(view->ranges[i].addr)),
672 base);
673 int128_addto(&base, now);
674 offset_in_region += int128_get64(now);
675 int128_subfrom(&remain, now);
093bc2cd 676 }
08dafab4 677 if (int128_nz(remain)) {
093bc2cd
AK
678 fr.offset_in_region = offset_in_region;
679 fr.addr = addrrange_make(base, remain);
680 flatview_insert(view, i, &fr);
681 }
682}
683
89c177bb
AK
684static MemoryRegion *memory_region_get_flatview_root(MemoryRegion *mr)
685{
e673ba9a
PB
686 while (mr->enabled) {
687 if (mr->alias) {
688 if (!mr->alias_offset && int128_ge(mr->size, mr->alias->size)) {
689 /* The alias is included in its entirety. Use it as
690 * the "real" root, so that we can share more FlatViews.
691 */
692 mr = mr->alias;
693 continue;
694 }
695 } else if (!mr->terminates) {
696 unsigned int found = 0;
697 MemoryRegion *child, *next = NULL;
698 QTAILQ_FOREACH(child, &mr->subregions, subregions_link) {
699 if (child->enabled) {
700 if (++found > 1) {
701 next = NULL;
702 break;
703 }
704 if (!child->addr && int128_ge(mr->size, child->size)) {
705 /* A child is included in its entirety. If it's the only
706 * enabled one, use it in the hope of finding an alias down the
707 * way. This will also let us share FlatViews.
708 */
709 next = child;
710 }
711 }
712 }
092aa2fc
AK
713 if (found == 0) {
714 return NULL;
715 }
e673ba9a
PB
716 if (next) {
717 mr = next;
718 continue;
719 }
720 }
721
092aa2fc 722 return mr;
89c177bb
AK
723 }
724
092aa2fc 725 return NULL;
89c177bb
AK
726}
727
093bc2cd 728/* Render a memory topology into a list of disjoint absolute ranges. */
a9a0c06d 729static FlatView *generate_memory_topology(MemoryRegion *mr)
093bc2cd 730{
9bf561e3 731 int i;
a9a0c06d 732 FlatView *view;
093bc2cd 733
89c177bb 734 view = flatview_new(mr);
093bc2cd 735
83f3c251 736 if (mr) {
a9a0c06d 737 render_memory_region(view, mr, int128_zero(),
c26763f8
MAL
738 addrrange_make(int128_zero(), int128_2_64()),
739 false, false);
83f3c251 740 }
a9a0c06d 741 flatview_simplify(view);
093bc2cd 742
9bf561e3
AK
743 view->dispatch = address_space_dispatch_new(view);
744 for (i = 0; i < view->nr; i++) {
745 MemoryRegionSection mrs =
746 section_from_flat_range(&view->ranges[i], view);
747 flatview_add_to_dispatch(view, &mrs);
748 }
749 address_space_dispatch_compact(view->dispatch);
967dc9b1 750 g_hash_table_replace(flat_views, mr, view);
9bf561e3 751
093bc2cd
AK
752 return view;
753}
754
3e9d69e7
AK
755static void address_space_add_del_ioeventfds(AddressSpace *as,
756 MemoryRegionIoeventfd *fds_new,
757 unsigned fds_new_nb,
758 MemoryRegionIoeventfd *fds_old,
759 unsigned fds_old_nb)
760{
761 unsigned iold, inew;
80a1ea37
AK
762 MemoryRegionIoeventfd *fd;
763 MemoryRegionSection section;
3e9d69e7
AK
764
765 /* Generate a symmetric difference of the old and new fd sets, adding
766 * and deleting as necessary.
767 */
768
769 iold = inew = 0;
770 while (iold < fds_old_nb || inew < fds_new_nb) {
771 if (iold < fds_old_nb
772 && (inew == fds_new_nb
73bb753d
TB
773 || memory_region_ioeventfd_before(&fds_old[iold],
774 &fds_new[inew]))) {
80a1ea37
AK
775 fd = &fds_old[iold];
776 section = (MemoryRegionSection) {
16620684 777 .fv = address_space_to_flatview(as),
80a1ea37 778 .offset_within_address_space = int128_get64(fd->addr.start),
052e87b0 779 .size = fd->addr.size,
80a1ea37 780 };
9a54635d 781 MEMORY_LISTENER_CALL(as, eventfd_del, Forward, &section,
753d5e14 782 fd->match_data, fd->data, fd->e);
3e9d69e7
AK
783 ++iold;
784 } else if (inew < fds_new_nb
785 && (iold == fds_old_nb
73bb753d
TB
786 || memory_region_ioeventfd_before(&fds_new[inew],
787 &fds_old[iold]))) {
80a1ea37
AK
788 fd = &fds_new[inew];
789 section = (MemoryRegionSection) {
16620684 790 .fv = address_space_to_flatview(as),
80a1ea37 791 .offset_within_address_space = int128_get64(fd->addr.start),
052e87b0 792 .size = fd->addr.size,
80a1ea37 793 };
9a54635d 794 MEMORY_LISTENER_CALL(as, eventfd_add, Reverse, &section,
753d5e14 795 fd->match_data, fd->data, fd->e);
3e9d69e7
AK
796 ++inew;
797 } else {
798 ++iold;
799 ++inew;
800 }
801 }
802}
803
48564041 804FlatView *address_space_get_flatview(AddressSpace *as)
856d7245
PB
805{
806 FlatView *view;
807
374f2981 808 rcu_read_lock();
447b0d0b 809 do {
16620684 810 view = address_space_to_flatview(as);
447b0d0b
PB
811 /* If somebody has replaced as->current_map concurrently,
812 * flatview_ref returns false.
813 */
814 } while (!flatview_ref(view));
374f2981 815 rcu_read_unlock();
856d7245
PB
816 return view;
817}
818
3e9d69e7
AK
819static void address_space_update_ioeventfds(AddressSpace *as)
820{
99e86347 821 FlatView *view;
3e9d69e7
AK
822 FlatRange *fr;
823 unsigned ioeventfd_nb = 0;
824 MemoryRegionIoeventfd *ioeventfds = NULL;
825 AddrRange tmp;
826 unsigned i;
827
856d7245 828 view = address_space_get_flatview(as);
99e86347 829 FOR_EACH_FLAT_RANGE(fr, view) {
3e9d69e7
AK
830 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
831 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
08dafab4
AK
832 int128_sub(fr->addr.start,
833 int128_make64(fr->offset_in_region)));
3e9d69e7
AK
834 if (addrrange_intersects(fr->addr, tmp)) {
835 ++ioeventfd_nb;
7267c094 836 ioeventfds = g_realloc(ioeventfds,
3e9d69e7
AK
837 ioeventfd_nb * sizeof(*ioeventfds));
838 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
839 ioeventfds[ioeventfd_nb-1].addr = tmp;
840 }
841 }
842 }
843
844 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
845 as->ioeventfds, as->ioeventfd_nb);
846
7267c094 847 g_free(as->ioeventfds);
3e9d69e7
AK
848 as->ioeventfds = ioeventfds;
849 as->ioeventfd_nb = ioeventfd_nb;
856d7245 850 flatview_unref(view);
3e9d69e7
AK
851}
852
909bf763
PB
853static void flat_range_coalesced_io_del(FlatRange *fr, AddressSpace *as)
854{
1f7af804
PB
855 if (!fr->has_coalesced_range) {
856 return;
857 }
858
3ac7d43a
PB
859 if (--fr->has_coalesced_range > 0) {
860 return;
861 }
862
909bf763
PB
863 MEMORY_LISTENER_UPDATE_REGION(fr, as, Reverse, coalesced_io_del,
864 int128_get64(fr->addr.start),
865 int128_get64(fr->addr.size));
866}
867
868static void flat_range_coalesced_io_add(FlatRange *fr, AddressSpace *as)
869{
870 MemoryRegion *mr = fr->mr;
871 CoalescedMemoryRange *cmr;
872 AddrRange tmp;
873
1f7af804
PB
874 if (QTAILQ_EMPTY(&mr->coalesced)) {
875 return;
876 }
877
3ac7d43a
PB
878 if (fr->has_coalesced_range++) {
879 return;
880 }
881
909bf763
PB
882 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
883 tmp = addrrange_shift(cmr->addr,
884 int128_sub(fr->addr.start,
885 int128_make64(fr->offset_in_region)));
886 if (!addrrange_intersects(tmp, fr->addr)) {
887 continue;
888 }
889 tmp = addrrange_intersection(tmp, fr->addr);
890 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, coalesced_io_add,
891 int128_get64(tmp.start),
892 int128_get64(tmp.size));
893 }
894}
895
b8af1afb 896static void address_space_update_topology_pass(AddressSpace *as,
a9a0c06d
PB
897 const FlatView *old_view,
898 const FlatView *new_view,
b8af1afb 899 bool adding)
093bc2cd 900{
093bc2cd
AK
901 unsigned iold, inew;
902 FlatRange *frold, *frnew;
093bc2cd
AK
903
904 /* Generate a symmetric difference of the old and new memory maps.
905 * Kill ranges in the old map, and instantiate ranges in the new map.
906 */
907 iold = inew = 0;
a9a0c06d
PB
908 while (iold < old_view->nr || inew < new_view->nr) {
909 if (iold < old_view->nr) {
910 frold = &old_view->ranges[iold];
093bc2cd
AK
911 } else {
912 frold = NULL;
913 }
a9a0c06d
PB
914 if (inew < new_view->nr) {
915 frnew = &new_view->ranges[inew];
093bc2cd
AK
916 } else {
917 frnew = NULL;
918 }
919
920 if (frold
921 && (!frnew
08dafab4
AK
922 || int128_lt(frold->addr.start, frnew->addr.start)
923 || (int128_eq(frold->addr.start, frnew->addr.start)
093bc2cd 924 && !flatrange_equal(frold, frnew)))) {
41a6e477 925 /* In old but not in new, or in both but attributes changed. */
093bc2cd 926
b8af1afb 927 if (!adding) {
3ac7d43a 928 flat_range_coalesced_io_del(frold, as);
72e22d2f 929 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
b8af1afb
AK
930 }
931
093bc2cd
AK
932 ++iold;
933 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
41a6e477 934 /* In both and unchanged (except logging may have changed) */
093bc2cd 935
4f826024 936 if (adding) {
50c1e149 937 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
b2dfd71c
PB
938 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
939 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
940 frold->dirty_log_mask,
941 frnew->dirty_log_mask);
942 }
943 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
944 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
945 frold->dirty_log_mask,
946 frnew->dirty_log_mask);
b8af1afb 947 }
5a583347
AK
948 }
949
093bc2cd
AK
950 ++iold;
951 ++inew;
093bc2cd
AK
952 } else {
953 /* In new */
954
b8af1afb 955 if (adding) {
72e22d2f 956 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
3ac7d43a 957 flat_range_coalesced_io_add(frnew, as);
b8af1afb
AK
958 }
959
093bc2cd
AK
960 ++inew;
961 }
962 }
b8af1afb
AK
963}
964
967dc9b1
AK
965static void flatviews_init(void)
966{
092aa2fc
AK
967 static FlatView *empty_view;
968
967dc9b1
AK
969 if (flat_views) {
970 return;
971 }
972
973 flat_views = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL,
974 (GDestroyNotify) flatview_unref);
092aa2fc
AK
975 if (!empty_view) {
976 empty_view = generate_memory_topology(NULL);
977 /* We keep it alive forever in the global variable. */
978 flatview_ref(empty_view);
979 } else {
980 g_hash_table_replace(flat_views, NULL, empty_view);
981 flatview_ref(empty_view);
982 }
967dc9b1
AK
983}
984
985static void flatviews_reset(void)
986{
987 AddressSpace *as;
988
989 if (flat_views) {
990 g_hash_table_unref(flat_views);
991 flat_views = NULL;
992 }
993 flatviews_init();
994
995 /* Render unique FVs */
996 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
997 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
998
999 if (g_hash_table_lookup(flat_views, physmr)) {
1000 continue;
1001 }
1002
1003 generate_memory_topology(physmr);
1004 }
1005}
1006
1007static void address_space_set_flatview(AddressSpace *as)
b8af1afb 1008{
67ace39b 1009 FlatView *old_view = address_space_to_flatview(as);
967dc9b1
AK
1010 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1011 FlatView *new_view = g_hash_table_lookup(flat_views, physmr);
1012
1013 assert(new_view);
1014
67ace39b
AK
1015 if (old_view == new_view) {
1016 return;
1017 }
1018
1019 if (old_view) {
1020 flatview_ref(old_view);
1021 }
1022
967dc9b1 1023 flatview_ref(new_view);
9a62e24f
AK
1024
1025 if (!QTAILQ_EMPTY(&as->listeners)) {
67ace39b
AK
1026 FlatView tmpview = { .nr = 0 }, *old_view2 = old_view;
1027
1028 if (!old_view2) {
1029 old_view2 = &tmpview;
1030 }
1031 address_space_update_topology_pass(as, old_view2, new_view, false);
1032 address_space_update_topology_pass(as, old_view2, new_view, true);
9a62e24f 1033 }
b8af1afb 1034
374f2981
PB
1035 /* Writes are protected by the BQL. */
1036 atomic_rcu_set(&as->current_map, new_view);
67ace39b
AK
1037 if (old_view) {
1038 flatview_unref(old_view);
1039 }
856d7245
PB
1040
1041 /* Note that all the old MemoryRegions are still alive up to this
1042 * point. This relieves most MemoryListeners from the need to
1043 * ref/unref the MemoryRegions they get---unless they use them
1044 * outside the iothread mutex, in which case precise reference
1045 * counting is necessary.
1046 */
67ace39b
AK
1047 if (old_view) {
1048 flatview_unref(old_view);
1049 }
093bc2cd
AK
1050}
1051
202fc01b
AK
1052static void address_space_update_topology(AddressSpace *as)
1053{
1054 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1055
1056 flatviews_init();
1057 if (!g_hash_table_lookup(flat_views, physmr)) {
1058 generate_memory_topology(physmr);
1059 }
1060 address_space_set_flatview(as);
1061}
1062
4ef4db86
AK
1063void memory_region_transaction_begin(void)
1064{
bb880ded 1065 qemu_flush_coalesced_mmio_buffer();
4ef4db86
AK
1066 ++memory_region_transaction_depth;
1067}
1068
1069void memory_region_transaction_commit(void)
1070{
0d673e36
AK
1071 AddressSpace *as;
1072
4ef4db86 1073 assert(memory_region_transaction_depth);
8d04fb55
JK
1074 assert(qemu_mutex_iothread_locked());
1075
4ef4db86 1076 --memory_region_transaction_depth;
4dc56152
GA
1077 if (!memory_region_transaction_depth) {
1078 if (memory_region_update_pending) {
967dc9b1
AK
1079 flatviews_reset();
1080
4dc56152 1081 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
02e2b95f 1082
4dc56152 1083 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
967dc9b1 1084 address_space_set_flatview(as);
02218487 1085 address_space_update_ioeventfds(as);
4dc56152 1086 }
ade9c1aa 1087 memory_region_update_pending = false;
0b152095 1088 ioeventfd_update_pending = false;
4dc56152
GA
1089 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
1090 } else if (ioeventfd_update_pending) {
1091 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1092 address_space_update_ioeventfds(as);
1093 }
ade9c1aa 1094 ioeventfd_update_pending = false;
4dc56152 1095 }
4dc56152 1096 }
4ef4db86
AK
1097}
1098
545e92e0
AK
1099static void memory_region_destructor_none(MemoryRegion *mr)
1100{
1101}
1102
1103static void memory_region_destructor_ram(MemoryRegion *mr)
1104{
f1060c55 1105 qemu_ram_free(mr->ram_block);
545e92e0
AK
1106}
1107
b4fefef9
PC
1108static bool memory_region_need_escape(char c)
1109{
1110 return c == '/' || c == '[' || c == '\\' || c == ']';
1111}
1112
1113static char *memory_region_escape_name(const char *name)
1114{
1115 const char *p;
1116 char *escaped, *q;
1117 uint8_t c;
1118 size_t bytes = 0;
1119
1120 for (p = name; *p; p++) {
1121 bytes += memory_region_need_escape(*p) ? 4 : 1;
1122 }
1123 if (bytes == p - name) {
1124 return g_memdup(name, bytes + 1);
1125 }
1126
1127 escaped = g_malloc(bytes + 1);
1128 for (p = name, q = escaped; *p; p++) {
1129 c = *p;
1130 if (unlikely(memory_region_need_escape(c))) {
1131 *q++ = '\\';
1132 *q++ = 'x';
1133 *q++ = "0123456789abcdef"[c >> 4];
1134 c = "0123456789abcdef"[c & 15];
1135 }
1136 *q++ = c;
1137 }
1138 *q = 0;
1139 return escaped;
1140}
1141
3df9d748
AK
1142static void memory_region_do_init(MemoryRegion *mr,
1143 Object *owner,
1144 const char *name,
1145 uint64_t size)
093bc2cd 1146{
08dafab4
AK
1147 mr->size = int128_make64(size);
1148 if (size == UINT64_MAX) {
1149 mr->size = int128_2_64();
1150 }
302fa283 1151 mr->name = g_strdup(name);
612263cf 1152 mr->owner = owner;
58eaa217 1153 mr->ram_block = NULL;
b4fefef9
PC
1154
1155 if (name) {
843ef73a
PC
1156 char *escaped_name = memory_region_escape_name(name);
1157 char *name_array = g_strdup_printf("%s[*]", escaped_name);
612263cf
PB
1158
1159 if (!owner) {
1160 owner = container_get(qdev_get_machine(), "/unattached");
1161 }
1162
843ef73a 1163 object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
b4fefef9 1164 object_unref(OBJECT(mr));
843ef73a
PC
1165 g_free(name_array);
1166 g_free(escaped_name);
b4fefef9
PC
1167 }
1168}
1169
3df9d748
AK
1170void memory_region_init(MemoryRegion *mr,
1171 Object *owner,
1172 const char *name,
1173 uint64_t size)
1174{
1175 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
1176 memory_region_do_init(mr, owner, name, size);
1177}
1178
d7bce999
EB
1179static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
1180 void *opaque, Error **errp)
409ddd01
PC
1181{
1182 MemoryRegion *mr = MEMORY_REGION(obj);
1183 uint64_t value = mr->addr;
1184
51e72bc1 1185 visit_type_uint64(v, name, &value, errp);
409ddd01
PC
1186}
1187
d7bce999
EB
1188static void memory_region_get_container(Object *obj, Visitor *v,
1189 const char *name, void *opaque,
1190 Error **errp)
409ddd01
PC
1191{
1192 MemoryRegion *mr = MEMORY_REGION(obj);
1193 gchar *path = (gchar *)"";
1194
1195 if (mr->container) {
1196 path = object_get_canonical_path(OBJECT(mr->container));
1197 }
51e72bc1 1198 visit_type_str(v, name, &path, errp);
409ddd01
PC
1199 if (mr->container) {
1200 g_free(path);
1201 }
1202}
1203
1204static Object *memory_region_resolve_container(Object *obj, void *opaque,
1205 const char *part)
1206{
1207 MemoryRegion *mr = MEMORY_REGION(obj);
1208
1209 return OBJECT(mr->container);
1210}
1211
d7bce999
EB
1212static void memory_region_get_priority(Object *obj, Visitor *v,
1213 const char *name, void *opaque,
1214 Error **errp)
d33382da
PC
1215{
1216 MemoryRegion *mr = MEMORY_REGION(obj);
1217 int32_t value = mr->priority;
1218
51e72bc1 1219 visit_type_int32(v, name, &value, errp);
d33382da
PC
1220}
1221
d7bce999
EB
1222static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1223 void *opaque, Error **errp)
52aef7bb
PC
1224{
1225 MemoryRegion *mr = MEMORY_REGION(obj);
1226 uint64_t value = memory_region_size(mr);
1227
51e72bc1 1228 visit_type_uint64(v, name, &value, errp);
52aef7bb
PC
1229}
1230
b4fefef9
PC
1231static void memory_region_initfn(Object *obj)
1232{
1233 MemoryRegion *mr = MEMORY_REGION(obj);
409ddd01 1234 ObjectProperty *op;
b4fefef9
PC
1235
1236 mr->ops = &unassigned_mem_ops;
6bba19ba 1237 mr->enabled = true;
5f9a5ea1 1238 mr->romd_mode = true;
196ea131 1239 mr->global_locking = true;
545e92e0 1240 mr->destructor = memory_region_destructor_none;
093bc2cd 1241 QTAILQ_INIT(&mr->subregions);
093bc2cd 1242 QTAILQ_INIT(&mr->coalesced);
409ddd01
PC
1243
1244 op = object_property_add(OBJECT(mr), "container",
1245 "link<" TYPE_MEMORY_REGION ">",
1246 memory_region_get_container,
1247 NULL, /* memory_region_set_container */
1248 NULL, NULL, &error_abort);
1249 op->resolve = memory_region_resolve_container;
1250
1251 object_property_add(OBJECT(mr), "addr", "uint64",
1252 memory_region_get_addr,
1253 NULL, /* memory_region_set_addr */
1254 NULL, NULL, &error_abort);
d33382da
PC
1255 object_property_add(OBJECT(mr), "priority", "uint32",
1256 memory_region_get_priority,
1257 NULL, /* memory_region_set_priority */
1258 NULL, NULL, &error_abort);
52aef7bb
PC
1259 object_property_add(OBJECT(mr), "size", "uint64",
1260 memory_region_get_size,
1261 NULL, /* memory_region_set_size, */
1262 NULL, NULL, &error_abort);
093bc2cd
AK
1263}
1264
3df9d748
AK
1265static void iommu_memory_region_initfn(Object *obj)
1266{
1267 MemoryRegion *mr = MEMORY_REGION(obj);
1268
1269 mr->is_iommu = true;
1270}
1271
b018ddf6
PB
1272static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1273 unsigned size)
1274{
1275#ifdef DEBUG_UNASSIGNED
1276 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1277#endif
4917cf44 1278 if (current_cpu != NULL) {
dbea78a4
PM
1279 bool is_exec = current_cpu->mem_io_access_type == MMU_INST_FETCH;
1280 cpu_unassigned_access(current_cpu, addr, false, is_exec, 0, size);
c658b94f 1281 }
68a7439a 1282 return 0;
b018ddf6
PB
1283}
1284
1285static void unassigned_mem_write(void *opaque, hwaddr addr,
1286 uint64_t val, unsigned size)
1287{
1288#ifdef DEBUG_UNASSIGNED
1289 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1290#endif
4917cf44
AF
1291 if (current_cpu != NULL) {
1292 cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
c658b94f 1293 }
b018ddf6
PB
1294}
1295
d197063f 1296static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
8372d383
PM
1297 unsigned size, bool is_write,
1298 MemTxAttrs attrs)
d197063f
PB
1299{
1300 return false;
1301}
1302
1303const MemoryRegionOps unassigned_mem_ops = {
1304 .valid.accepts = unassigned_mem_accepts,
1305 .endianness = DEVICE_NATIVE_ENDIAN,
1306};
1307
4a2e242b
AW
1308static uint64_t memory_region_ram_device_read(void *opaque,
1309 hwaddr addr, unsigned size)
1310{
1311 MemoryRegion *mr = opaque;
1312 uint64_t data = (uint64_t)~0;
1313
1314 switch (size) {
1315 case 1:
1316 data = *(uint8_t *)(mr->ram_block->host + addr);
1317 break;
1318 case 2:
1319 data = *(uint16_t *)(mr->ram_block->host + addr);
1320 break;
1321 case 4:
1322 data = *(uint32_t *)(mr->ram_block->host + addr);
1323 break;
1324 case 8:
1325 data = *(uint64_t *)(mr->ram_block->host + addr);
1326 break;
1327 }
1328
1329 trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);
1330
1331 return data;
1332}
1333
1334static void memory_region_ram_device_write(void *opaque, hwaddr addr,
1335 uint64_t data, unsigned size)
1336{
1337 MemoryRegion *mr = opaque;
1338
1339 trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);
1340
1341 switch (size) {
1342 case 1:
1343 *(uint8_t *)(mr->ram_block->host + addr) = (uint8_t)data;
1344 break;
1345 case 2:
1346 *(uint16_t *)(mr->ram_block->host + addr) = (uint16_t)data;
1347 break;
1348 case 4:
1349 *(uint32_t *)(mr->ram_block->host + addr) = (uint32_t)data;
1350 break;
1351 case 8:
1352 *(uint64_t *)(mr->ram_block->host + addr) = data;
1353 break;
1354 }
1355}
1356
1357static const MemoryRegionOps ram_device_mem_ops = {
1358 .read = memory_region_ram_device_read,
1359 .write = memory_region_ram_device_write,
c99a29e7 1360 .endianness = DEVICE_HOST_ENDIAN,
4a2e242b
AW
1361 .valid = {
1362 .min_access_size = 1,
1363 .max_access_size = 8,
1364 .unaligned = true,
1365 },
1366 .impl = {
1367 .min_access_size = 1,
1368 .max_access_size = 8,
1369 .unaligned = true,
1370 },
1371};
1372
d2702032
PB
1373bool memory_region_access_valid(MemoryRegion *mr,
1374 hwaddr addr,
1375 unsigned size,
6d7b9a6c
PM
1376 bool is_write,
1377 MemTxAttrs attrs)
093bc2cd 1378{
a014ed07
PB
1379 int access_size_min, access_size_max;
1380 int access_size, i;
897fa7cf 1381
093bc2cd
AK
1382 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1383 return false;
1384 }
1385
a014ed07 1386 if (!mr->ops->valid.accepts) {
093bc2cd
AK
1387 return true;
1388 }
1389
a014ed07
PB
1390 access_size_min = mr->ops->valid.min_access_size;
1391 if (!mr->ops->valid.min_access_size) {
1392 access_size_min = 1;
1393 }
1394
1395 access_size_max = mr->ops->valid.max_access_size;
1396 if (!mr->ops->valid.max_access_size) {
1397 access_size_max = 4;
1398 }
1399
1400 access_size = MAX(MIN(size, access_size_max), access_size_min);
1401 for (i = 0; i < size; i += access_size) {
1402 if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
8372d383 1403 is_write, attrs)) {
a014ed07
PB
1404 return false;
1405 }
093bc2cd 1406 }
a014ed07 1407
093bc2cd
AK
1408 return true;
1409}
1410
cc05c43a
PM
1411static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1412 hwaddr addr,
1413 uint64_t *pval,
1414 unsigned size,
1415 MemTxAttrs attrs)
093bc2cd 1416{
cc05c43a 1417 *pval = 0;
093bc2cd 1418
ce5d2f33 1419 if (mr->ops->read) {
cc05c43a
PM
1420 return access_with_adjusted_size(addr, pval, size,
1421 mr->ops->impl.min_access_size,
1422 mr->ops->impl.max_access_size,
1423 memory_region_read_accessor,
1424 mr, attrs);
62a0db94 1425 } else {
cc05c43a
PM
1426 return access_with_adjusted_size(addr, pval, size,
1427 mr->ops->impl.min_access_size,
1428 mr->ops->impl.max_access_size,
1429 memory_region_read_with_attrs_accessor,
1430 mr, attrs);
74901c3b 1431 }
093bc2cd
AK
1432}
1433
3b643495
PM
1434MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1435 hwaddr addr,
1436 uint64_t *pval,
1437 unsigned size,
1438 MemTxAttrs attrs)
a621f38d 1439{
cc05c43a
PM
1440 MemTxResult r;
1441
6d7b9a6c 1442 if (!memory_region_access_valid(mr, addr, size, false, attrs)) {
791af8c8 1443 *pval = unassigned_mem_read(mr, addr, size);
cc05c43a 1444 return MEMTX_DECODE_ERROR;
791af8c8 1445 }
a621f38d 1446
cc05c43a 1447 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
791af8c8 1448 adjust_endianness(mr, pval, size);
cc05c43a 1449 return r;
a621f38d 1450}
093bc2cd 1451
8c56c1a5
PF
1452/* Return true if an eventfd was signalled */
1453static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1454 hwaddr addr,
1455 uint64_t data,
1456 unsigned size,
1457 MemTxAttrs attrs)
1458{
1459 MemoryRegionIoeventfd ioeventfd = {
1460 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1461 .data = data,
1462 };
1463 unsigned i;
1464
1465 for (i = 0; i < mr->ioeventfd_nb; i++) {
1466 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1467 ioeventfd.e = mr->ioeventfds[i].e;
1468
73bb753d 1469 if (memory_region_ioeventfd_equal(&ioeventfd, &mr->ioeventfds[i])) {
8c56c1a5
PF
1470 event_notifier_set(ioeventfd.e);
1471 return true;
1472 }
1473 }
1474
1475 return false;
1476}
1477
3b643495
PM
1478MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1479 hwaddr addr,
1480 uint64_t data,
1481 unsigned size,
1482 MemTxAttrs attrs)
a621f38d 1483{
6d7b9a6c 1484 if (!memory_region_access_valid(mr, addr, size, true, attrs)) {
b018ddf6 1485 unassigned_mem_write(mr, addr, data, size);
cc05c43a 1486 return MEMTX_DECODE_ERROR;
093bc2cd
AK
1487 }
1488
a621f38d
AK
1489 adjust_endianness(mr, &data, size);
1490
8c56c1a5
PF
1491 if ((!kvm_eventfds_enabled()) &&
1492 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1493 return MEMTX_OK;
1494 }
1495
ce5d2f33 1496 if (mr->ops->write) {
cc05c43a
PM
1497 return access_with_adjusted_size(addr, &data, size,
1498 mr->ops->impl.min_access_size,
1499 mr->ops->impl.max_access_size,
1500 memory_region_write_accessor, mr,
1501 attrs);
62a0db94 1502 } else {
cc05c43a
PM
1503 return
1504 access_with_adjusted_size(addr, &data, size,
1505 mr->ops->impl.min_access_size,
1506 mr->ops->impl.max_access_size,
1507 memory_region_write_with_attrs_accessor,
1508 mr, attrs);
74901c3b 1509 }
093bc2cd
AK
1510}
1511
093bc2cd 1512void memory_region_init_io(MemoryRegion *mr,
2c9b15ca 1513 Object *owner,
093bc2cd
AK
1514 const MemoryRegionOps *ops,
1515 void *opaque,
1516 const char *name,
1517 uint64_t size)
1518{
2c9b15ca 1519 memory_region_init(mr, owner, name, size);
6d6d2abf 1520 mr->ops = ops ? ops : &unassigned_mem_ops;
093bc2cd 1521 mr->opaque = opaque;
14a3c10a 1522 mr->terminates = true;
093bc2cd
AK
1523}
1524
1cfe48c1
PM
1525void memory_region_init_ram_nomigrate(MemoryRegion *mr,
1526 Object *owner,
1527 const char *name,
1528 uint64_t size,
1529 Error **errp)
06329cce
MA
1530{
1531 memory_region_init_ram_shared_nomigrate(mr, owner, name, size, false, errp);
1532}
1533
1534void memory_region_init_ram_shared_nomigrate(MemoryRegion *mr,
1535 Object *owner,
1536 const char *name,
1537 uint64_t size,
1538 bool share,
1539 Error **errp)
093bc2cd 1540{
1cd3d492 1541 Error *err = NULL;
2c9b15ca 1542 memory_region_init(mr, owner, name, size);
8ea9252a 1543 mr->ram = true;
14a3c10a 1544 mr->terminates = true;
545e92e0 1545 mr->destructor = memory_region_destructor_ram;
1cd3d492 1546 mr->ram_block = qemu_ram_alloc(size, share, mr, &err);
677e7805 1547 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1cd3d492
IM
1548 if (err) {
1549 mr->size = int128_zero();
1550 object_unparent(OBJECT(mr));
1551 error_propagate(errp, err);
1552 }
0b183fc8
PB
1553}
1554
60786ef3
MT
1555void memory_region_init_resizeable_ram(MemoryRegion *mr,
1556 Object *owner,
1557 const char *name,
1558 uint64_t size,
1559 uint64_t max_size,
1560 void (*resized)(const char*,
1561 uint64_t length,
1562 void *host),
1563 Error **errp)
1564{
1cd3d492 1565 Error *err = NULL;
60786ef3
MT
1566 memory_region_init(mr, owner, name, size);
1567 mr->ram = true;
1568 mr->terminates = true;
1569 mr->destructor = memory_region_destructor_ram;
8e41fb63 1570 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1cd3d492 1571 mr, &err);
677e7805 1572 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1cd3d492
IM
1573 if (err) {
1574 mr->size = int128_zero();
1575 object_unparent(OBJECT(mr));
1576 error_propagate(errp, err);
1577 }
60786ef3
MT
1578}
1579
d5dbde46 1580#ifdef CONFIG_POSIX
0b183fc8
PB
1581void memory_region_init_ram_from_file(MemoryRegion *mr,
1582 struct Object *owner,
1583 const char *name,
1584 uint64_t size,
98376843 1585 uint64_t align,
cbfc0171 1586 uint32_t ram_flags,
7f56e740
PB
1587 const char *path,
1588 Error **errp)
0b183fc8 1589{
1cd3d492 1590 Error *err = NULL;
0b183fc8
PB
1591 memory_region_init(mr, owner, name, size);
1592 mr->ram = true;
1593 mr->terminates = true;
1594 mr->destructor = memory_region_destructor_ram;
98376843 1595 mr->align = align;
1cd3d492 1596 mr->ram_block = qemu_ram_alloc_from_file(size, mr, ram_flags, path, &err);
677e7805 1597 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1cd3d492
IM
1598 if (err) {
1599 mr->size = int128_zero();
1600 object_unparent(OBJECT(mr));
1601 error_propagate(errp, err);
1602 }
093bc2cd 1603}
fea617c5
MAL
1604
1605void memory_region_init_ram_from_fd(MemoryRegion *mr,
1606 struct Object *owner,
1607 const char *name,
1608 uint64_t size,
1609 bool share,
1610 int fd,
1611 Error **errp)
1612{
1cd3d492 1613 Error *err = NULL;
fea617c5
MAL
1614 memory_region_init(mr, owner, name, size);
1615 mr->ram = true;
1616 mr->terminates = true;
1617 mr->destructor = memory_region_destructor_ram;
cbfc0171
JH
1618 mr->ram_block = qemu_ram_alloc_from_fd(size, mr,
1619 share ? RAM_SHARED : 0,
1cd3d492 1620 fd, &err);
fea617c5 1621 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1cd3d492
IM
1622 if (err) {
1623 mr->size = int128_zero();
1624 object_unparent(OBJECT(mr));
1625 error_propagate(errp, err);
1626 }
fea617c5 1627}
0b183fc8 1628#endif
093bc2cd
AK
1629
1630void memory_region_init_ram_ptr(MemoryRegion *mr,
2c9b15ca 1631 Object *owner,
093bc2cd
AK
1632 const char *name,
1633 uint64_t size,
1634 void *ptr)
1635{
2c9b15ca 1636 memory_region_init(mr, owner, name, size);
8ea9252a 1637 mr->ram = true;
14a3c10a 1638 mr->terminates = true;
fc3e7665 1639 mr->destructor = memory_region_destructor_ram;
677e7805 1640 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
ef701d7b
HT
1641
1642 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1643 assert(ptr != NULL);
8e41fb63 1644 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
093bc2cd
AK
1645}
1646
21e00fa5
AW
1647void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1648 Object *owner,
1649 const char *name,
1650 uint64_t size,
1651 void *ptr)
e4dc3f59 1652{
2ddb89b0
BS
1653 memory_region_init(mr, owner, name, size);
1654 mr->ram = true;
1655 mr->terminates = true;
21e00fa5 1656 mr->ram_device = true;
4a2e242b
AW
1657 mr->ops = &ram_device_mem_ops;
1658 mr->opaque = mr;
2ddb89b0
BS
1659 mr->destructor = memory_region_destructor_ram;
1660 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1661 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1662 assert(ptr != NULL);
1663 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
e4dc3f59
ND
1664}
1665
093bc2cd 1666void memory_region_init_alias(MemoryRegion *mr,
2c9b15ca 1667 Object *owner,
093bc2cd
AK
1668 const char *name,
1669 MemoryRegion *orig,
a8170e5e 1670 hwaddr offset,
093bc2cd
AK
1671 uint64_t size)
1672{
2c9b15ca 1673 memory_region_init(mr, owner, name, size);
093bc2cd
AK
1674 mr->alias = orig;
1675 mr->alias_offset = offset;
1676}
1677
b59821a9
PM
1678void memory_region_init_rom_nomigrate(MemoryRegion *mr,
1679 struct Object *owner,
1680 const char *name,
1681 uint64_t size,
1682 Error **errp)
a1777f7f 1683{
1cd3d492 1684 Error *err = NULL;
a1777f7f
PM
1685 memory_region_init(mr, owner, name, size);
1686 mr->ram = true;
1687 mr->readonly = true;
1688 mr->terminates = true;
1689 mr->destructor = memory_region_destructor_ram;
1cd3d492 1690 mr->ram_block = qemu_ram_alloc(size, false, mr, &err);
a1777f7f 1691 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1cd3d492
IM
1692 if (err) {
1693 mr->size = int128_zero();
1694 object_unparent(OBJECT(mr));
1695 error_propagate(errp, err);
1696 }
a1777f7f
PM
1697}
1698
b59821a9
PM
1699void memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1700 Object *owner,
1701 const MemoryRegionOps *ops,
1702 void *opaque,
1703 const char *name,
1704 uint64_t size,
1705 Error **errp)
d0a9b5bc 1706{
1cd3d492 1707 Error *err = NULL;
39e0b03d 1708 assert(ops);
2c9b15ca 1709 memory_region_init(mr, owner, name, size);
7bc2b9cd 1710 mr->ops = ops;
75f5941c 1711 mr->opaque = opaque;
d0a9b5bc 1712 mr->terminates = true;
75c578dc 1713 mr->rom_device = true;
58268c8d 1714 mr->destructor = memory_region_destructor_ram;
1cd3d492
IM
1715 mr->ram_block = qemu_ram_alloc(size, false, mr, &err);
1716 if (err) {
1717 mr->size = int128_zero();
1718 object_unparent(OBJECT(mr));
1719 error_propagate(errp, err);
1720 }
d0a9b5bc
AK
1721}
1722
1221a474
AK
1723void memory_region_init_iommu(void *_iommu_mr,
1724 size_t instance_size,
1725 const char *mrtypename,
2c9b15ca 1726 Object *owner,
30951157
AK
1727 const char *name,
1728 uint64_t size)
1729{
1221a474 1730 struct IOMMUMemoryRegion *iommu_mr;
3df9d748
AK
1731 struct MemoryRegion *mr;
1732
1221a474
AK
1733 object_initialize(_iommu_mr, instance_size, mrtypename);
1734 mr = MEMORY_REGION(_iommu_mr);
3df9d748
AK
1735 memory_region_do_init(mr, owner, name, size);
1736 iommu_mr = IOMMU_MEMORY_REGION(mr);
30951157 1737 mr->terminates = true; /* then re-forwards */
3df9d748
AK
1738 QLIST_INIT(&iommu_mr->iommu_notify);
1739 iommu_mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
30951157
AK
1740}
1741
b4fefef9 1742static void memory_region_finalize(Object *obj)
093bc2cd 1743{
b4fefef9
PC
1744 MemoryRegion *mr = MEMORY_REGION(obj);
1745
2e2b8eb7
PB
1746 assert(!mr->container);
1747
1748 /* We know the region is not visible in any address space (it
1749 * does not have a container and cannot be a root either because
1750 * it has no references, so we can blindly clear mr->enabled.
1751 * memory_region_set_enabled instead could trigger a transaction
1752 * and cause an infinite loop.
1753 */
1754 mr->enabled = false;
1755 memory_region_transaction_begin();
1756 while (!QTAILQ_EMPTY(&mr->subregions)) {
1757 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1758 memory_region_del_subregion(mr, subregion);
1759 }
1760 memory_region_transaction_commit();
1761
545e92e0 1762 mr->destructor(mr);
093bc2cd 1763 memory_region_clear_coalescing(mr);
302fa283 1764 g_free((char *)mr->name);
7267c094 1765 g_free(mr->ioeventfds);
093bc2cd
AK
1766}
1767
803c0816
PB
1768Object *memory_region_owner(MemoryRegion *mr)
1769{
22a893e4
PB
1770 Object *obj = OBJECT(mr);
1771 return obj->parent;
803c0816
PB
1772}
1773
46637be2
PB
1774void memory_region_ref(MemoryRegion *mr)
1775{
22a893e4
PB
1776 /* MMIO callbacks most likely will access data that belongs
1777 * to the owner, hence the need to ref/unref the owner whenever
1778 * the memory region is in use.
1779 *
1780 * The memory region is a child of its owner. As long as the
1781 * owner doesn't call unparent itself on the memory region,
1782 * ref-ing the owner will also keep the memory region alive.
612263cf
PB
1783 * Memory regions without an owner are supposed to never go away;
1784 * we do not ref/unref them because it slows down DMA sensibly.
22a893e4 1785 */
612263cf
PB
1786 if (mr && mr->owner) {
1787 object_ref(mr->owner);
46637be2
PB
1788 }
1789}
1790
1791void memory_region_unref(MemoryRegion *mr)
1792{
612263cf
PB
1793 if (mr && mr->owner) {
1794 object_unref(mr->owner);
46637be2
PB
1795 }
1796}
1797
093bc2cd
AK
1798uint64_t memory_region_size(MemoryRegion *mr)
1799{
08dafab4
AK
1800 if (int128_eq(mr->size, int128_2_64())) {
1801 return UINT64_MAX;
1802 }
1803 return int128_get64(mr->size);
093bc2cd
AK
1804}
1805
5d546d4b 1806const char *memory_region_name(const MemoryRegion *mr)
8991c79b 1807{
d1dd32af
PC
1808 if (!mr->name) {
1809 ((MemoryRegion *)mr)->name =
1810 object_get_canonical_path_component(OBJECT(mr));
1811 }
302fa283 1812 return mr->name;
8991c79b
AK
1813}
1814
21e00fa5 1815bool memory_region_is_ram_device(MemoryRegion *mr)
e4dc3f59 1816{
21e00fa5 1817 return mr->ram_device;
e4dc3f59
ND
1818}
1819
2d1a35be 1820uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
55043ba3 1821{
6f6a5ef3 1822 uint8_t mask = mr->dirty_log_mask;
adaad61c 1823 if (global_dirty_log && mr->ram_block) {
6f6a5ef3
PB
1824 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1825 }
1826 return mask;
55043ba3
AK
1827}
1828
2d1a35be
PB
1829bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1830{
1831 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1832}
1833
3df9d748 1834static void memory_region_update_iommu_notify_flags(IOMMUMemoryRegion *iommu_mr)
5bf3d319
PX
1835{
1836 IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1837 IOMMUNotifier *iommu_notifier;
1221a474 1838 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
5bf3d319 1839
3df9d748 1840 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
5bf3d319
PX
1841 flags |= iommu_notifier->notifier_flags;
1842 }
1843
1221a474
AK
1844 if (flags != iommu_mr->iommu_notify_flags && imrc->notify_flag_changed) {
1845 imrc->notify_flag_changed(iommu_mr,
1846 iommu_mr->iommu_notify_flags,
1847 flags);
5bf3d319
PX
1848 }
1849
3df9d748 1850 iommu_mr->iommu_notify_flags = flags;
5bf3d319
PX
1851}
1852
cdb30812
PX
1853void memory_region_register_iommu_notifier(MemoryRegion *mr,
1854 IOMMUNotifier *n)
06866575 1855{
3df9d748
AK
1856 IOMMUMemoryRegion *iommu_mr;
1857
efcd38c5
JW
1858 if (mr->alias) {
1859 memory_region_register_iommu_notifier(mr->alias, n);
1860 return;
1861 }
1862
cdb30812 1863 /* We need to register for at least one bitfield */
3df9d748 1864 iommu_mr = IOMMU_MEMORY_REGION(mr);
cdb30812 1865 assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
698feb5e 1866 assert(n->start <= n->end);
cb1efcf4
PM
1867 assert(n->iommu_idx >= 0 &&
1868 n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
1869
3df9d748
AK
1870 QLIST_INSERT_HEAD(&iommu_mr->iommu_notify, n, node);
1871 memory_region_update_iommu_notify_flags(iommu_mr);
06866575
DG
1872}
1873
3df9d748 1874uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr)
a788f227 1875{
1221a474
AK
1876 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1877
1878 if (imrc->get_min_page_size) {
1879 return imrc->get_min_page_size(iommu_mr);
f682e9c2
AK
1880 }
1881 return TARGET_PAGE_SIZE;
1882}
1883
3df9d748 1884void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
f682e9c2 1885{
3df9d748 1886 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
1221a474 1887 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
f682e9c2 1888 hwaddr addr, granularity;
a788f227
DG
1889 IOMMUTLBEntry iotlb;
1890
faa362e3 1891 /* If the IOMMU has its own replay callback, override */
1221a474
AK
1892 if (imrc->replay) {
1893 imrc->replay(iommu_mr, n);
faa362e3
PX
1894 return;
1895 }
1896
3df9d748 1897 granularity = memory_region_iommu_get_min_page_size(iommu_mr);
f682e9c2 1898
a788f227 1899 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
2c91bcf2 1900 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, n->iommu_idx);
a788f227
DG
1901 if (iotlb.perm != IOMMU_NONE) {
1902 n->notify(n, &iotlb);
1903 }
1904
1905 /* if (2^64 - MR size) < granularity, it's possible to get an
1906 * infinite loop here. This should catch such a wraparound */
1907 if ((addr + granularity) < addr) {
1908 break;
1909 }
1910 }
1911}
1912
3df9d748 1913void memory_region_iommu_replay_all(IOMMUMemoryRegion *iommu_mr)
de472e4a
PX
1914{
1915 IOMMUNotifier *notifier;
1916
3df9d748
AK
1917 IOMMU_NOTIFIER_FOREACH(notifier, iommu_mr) {
1918 memory_region_iommu_replay(iommu_mr, notifier);
de472e4a
PX
1919 }
1920}
1921
cdb30812
PX
1922void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1923 IOMMUNotifier *n)
06866575 1924{
3df9d748
AK
1925 IOMMUMemoryRegion *iommu_mr;
1926
efcd38c5
JW
1927 if (mr->alias) {
1928 memory_region_unregister_iommu_notifier(mr->alias, n);
1929 return;
1930 }
cdb30812 1931 QLIST_REMOVE(n, node);
3df9d748
AK
1932 iommu_mr = IOMMU_MEMORY_REGION(mr);
1933 memory_region_update_iommu_notify_flags(iommu_mr);
06866575
DG
1934}
1935
bd2bfa4c
PX
1936void memory_region_notify_one(IOMMUNotifier *notifier,
1937 IOMMUTLBEntry *entry)
06866575 1938{
cdb30812
PX
1939 IOMMUNotifierFlag request_flags;
1940
bd2bfa4c
PX
1941 /*
1942 * Skip the notification if the notification does not overlap
1943 * with registered range.
1944 */
b021d1c0 1945 if (notifier->start > entry->iova + entry->addr_mask ||
bd2bfa4c
PX
1946 notifier->end < entry->iova) {
1947 return;
1948 }
cdb30812 1949
bd2bfa4c 1950 if (entry->perm & IOMMU_RW) {
cdb30812
PX
1951 request_flags = IOMMU_NOTIFIER_MAP;
1952 } else {
1953 request_flags = IOMMU_NOTIFIER_UNMAP;
1954 }
1955
bd2bfa4c
PX
1956 if (notifier->notifier_flags & request_flags) {
1957 notifier->notify(notifier, entry);
1958 }
1959}
1960
3df9d748 1961void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
cb1efcf4 1962 int iommu_idx,
bd2bfa4c
PX
1963 IOMMUTLBEntry entry)
1964{
1965 IOMMUNotifier *iommu_notifier;
1966
3df9d748 1967 assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
bd2bfa4c 1968
3df9d748 1969 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
cb1efcf4
PM
1970 if (iommu_notifier->iommu_idx == iommu_idx) {
1971 memory_region_notify_one(iommu_notifier, &entry);
1972 }
cdb30812 1973 }
06866575
DG
1974}
1975
f1334de6
AK
1976int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
1977 enum IOMMUMemoryRegionAttr attr,
1978 void *data)
1979{
1980 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1981
1982 if (!imrc->get_attr) {
1983 return -EINVAL;
1984 }
1985
1986 return imrc->get_attr(iommu_mr, attr, data);
1987}
1988
21f40209
PM
1989int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
1990 MemTxAttrs attrs)
1991{
1992 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1993
1994 if (!imrc->attrs_to_index) {
1995 return 0;
1996 }
1997
1998 return imrc->attrs_to_index(iommu_mr, attrs);
1999}
2000
2001int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr)
2002{
2003 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2004
2005 if (!imrc->num_indexes) {
2006 return 1;
2007 }
2008
2009 return imrc->num_indexes(iommu_mr);
2010}
2011
093bc2cd
AK
2012void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
2013{
5a583347 2014 uint8_t mask = 1 << client;
deb809ed 2015 uint8_t old_logging;
5a583347 2016
dbddac6d 2017 assert(client == DIRTY_MEMORY_VGA);
deb809ed
PB
2018 old_logging = mr->vga_logging_count;
2019 mr->vga_logging_count += log ? 1 : -1;
2020 if (!!old_logging == !!mr->vga_logging_count) {
2021 return;
2022 }
2023
59023ef4 2024 memory_region_transaction_begin();
5a583347 2025 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
22bde714 2026 memory_region_update_pending |= mr->enabled;
59023ef4 2027 memory_region_transaction_commit();
093bc2cd
AK
2028}
2029
a8170e5e
AK
2030void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
2031 hwaddr size)
093bc2cd 2032{
8e41fb63
FZ
2033 assert(mr->ram_block);
2034 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
2035 size,
58d2707e 2036 memory_region_get_dirty_log_mask(mr));
093bc2cd
AK
2037}
2038
0fe1eca7 2039static void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
093bc2cd 2040{
0a752eee 2041 MemoryListener *listener;
0d673e36 2042 AddressSpace *as;
0a752eee 2043 FlatView *view;
5a583347
AK
2044 FlatRange *fr;
2045
0a752eee
PB
2046 /* If the same address space has multiple log_sync listeners, we
2047 * visit that address space's FlatView multiple times. But because
2048 * log_sync listeners are rare, it's still cheaper than walking each
2049 * address space once.
2050 */
2051 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2052 if (!listener->log_sync) {
2053 continue;
2054 }
2055 as = listener->address_space;
2056 view = address_space_get_flatview(as);
99e86347 2057 FOR_EACH_FLAT_RANGE(fr, view) {
3ebb1817 2058 if (fr->dirty_log_mask && (!mr || fr->mr == mr)) {
16620684 2059 MemoryRegionSection mrs = section_from_flat_range(fr, view);
0a752eee 2060 listener->log_sync(listener, &mrs);
0d673e36 2061 }
5a583347 2062 }
856d7245 2063 flatview_unref(view);
5a583347 2064 }
093bc2cd
AK
2065}
2066
0fe1eca7
PB
2067DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
2068 hwaddr addr,
2069 hwaddr size,
2070 unsigned client)
2071{
2072 assert(mr->ram_block);
2073 memory_region_sync_dirty_bitmap(mr);
2074 return cpu_physical_memory_snapshot_and_clear_dirty(
2075 memory_region_get_ram_addr(mr) + addr, size, client);
2076}
2077
2078bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
2079 hwaddr addr, hwaddr size)
2080{
2081 assert(mr->ram_block);
2082 return cpu_physical_memory_snapshot_get_dirty(snap,
2083 memory_region_get_ram_addr(mr) + addr, size);
2084}
2085
093bc2cd
AK
2086void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
2087{
fb1cd6f9 2088 if (mr->readonly != readonly) {
59023ef4 2089 memory_region_transaction_begin();
fb1cd6f9 2090 mr->readonly = readonly;
22bde714 2091 memory_region_update_pending |= mr->enabled;
59023ef4 2092 memory_region_transaction_commit();
fb1cd6f9 2093 }
093bc2cd
AK
2094}
2095
c26763f8
MAL
2096void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile)
2097{
2098 if (mr->nonvolatile != nonvolatile) {
2099 memory_region_transaction_begin();
2100 mr->nonvolatile = nonvolatile;
2101 memory_region_update_pending |= mr->enabled;
2102 memory_region_transaction_commit();
2103 }
2104}
2105
5f9a5ea1 2106void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
d0a9b5bc 2107{
5f9a5ea1 2108 if (mr->romd_mode != romd_mode) {
59023ef4 2109 memory_region_transaction_begin();
5f9a5ea1 2110 mr->romd_mode = romd_mode;
22bde714 2111 memory_region_update_pending |= mr->enabled;
59023ef4 2112 memory_region_transaction_commit();
d0a9b5bc
AK
2113 }
2114}
2115
a8170e5e
AK
2116void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
2117 hwaddr size, unsigned client)
093bc2cd 2118{
8e41fb63
FZ
2119 assert(mr->ram_block);
2120 cpu_physical_memory_test_and_clear_dirty(
2121 memory_region_get_ram_addr(mr) + addr, size, client);
093bc2cd
AK
2122}
2123
a35ba7be
PB
2124int memory_region_get_fd(MemoryRegion *mr)
2125{
4ff87573
PB
2126 int fd;
2127
2128 rcu_read_lock();
2129 while (mr->alias) {
2130 mr = mr->alias;
a35ba7be 2131 }
4ff87573
PB
2132 fd = mr->ram_block->fd;
2133 rcu_read_unlock();
a35ba7be 2134
4ff87573
PB
2135 return fd;
2136}
a35ba7be 2137
093bc2cd
AK
2138void *memory_region_get_ram_ptr(MemoryRegion *mr)
2139{
49b24afc
PB
2140 void *ptr;
2141 uint64_t offset = 0;
093bc2cd 2142
49b24afc
PB
2143 rcu_read_lock();
2144 while (mr->alias) {
2145 offset += mr->alias_offset;
2146 mr = mr->alias;
2147 }
8e41fb63 2148 assert(mr->ram_block);
0878d0e1 2149 ptr = qemu_map_ram_ptr(mr->ram_block, offset);
49b24afc 2150 rcu_read_unlock();
093bc2cd 2151
0878d0e1 2152 return ptr;
093bc2cd
AK
2153}
2154
07bdaa41
PB
2155MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
2156{
2157 RAMBlock *block;
2158
2159 block = qemu_ram_block_from_host(ptr, false, offset);
2160 if (!block) {
2161 return NULL;
2162 }
2163
2164 return block->mr;
2165}
2166
7ebb2745
FZ
2167ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
2168{
2169 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
2170}
2171
37d7c084
PB
2172void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
2173{
8e41fb63 2174 assert(mr->ram_block);
37d7c084 2175
fa53a0e5 2176 qemu_ram_resize(mr->ram_block, newsize, errp);
37d7c084
PB
2177}
2178
0d673e36 2179static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
093bc2cd 2180{
99e86347 2181 FlatView *view;
093bc2cd 2182 FlatRange *fr;
093bc2cd 2183
856d7245 2184 view = address_space_get_flatview(as);
99e86347 2185 FOR_EACH_FLAT_RANGE(fr, view) {
093bc2cd 2186 if (fr->mr == mr) {
909bf763
PB
2187 flat_range_coalesced_io_del(fr, as);
2188 flat_range_coalesced_io_add(fr, as);
093bc2cd
AK
2189 }
2190 }
856d7245 2191 flatview_unref(view);
093bc2cd
AK
2192}
2193
0d673e36
AK
2194static void memory_region_update_coalesced_range(MemoryRegion *mr)
2195{
2196 AddressSpace *as;
2197
2198 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2199 memory_region_update_coalesced_range_as(mr, as);
2200 }
2201}
2202
093bc2cd
AK
2203void memory_region_set_coalescing(MemoryRegion *mr)
2204{
2205 memory_region_clear_coalescing(mr);
08dafab4 2206 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
093bc2cd
AK
2207}
2208
2209void memory_region_add_coalescing(MemoryRegion *mr,
a8170e5e 2210 hwaddr offset,
093bc2cd
AK
2211 uint64_t size)
2212{
7267c094 2213 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
093bc2cd 2214
08dafab4 2215 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
093bc2cd
AK
2216 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
2217 memory_region_update_coalesced_range(mr);
d410515e 2218 memory_region_set_flush_coalesced(mr);
093bc2cd
AK
2219}
2220
2221void memory_region_clear_coalescing(MemoryRegion *mr)
2222{
2223 CoalescedMemoryRange *cmr;
ab5b3db5 2224 bool updated = false;
093bc2cd 2225
d410515e
JK
2226 qemu_flush_coalesced_mmio_buffer();
2227 mr->flush_coalesced_mmio = false;
2228
093bc2cd
AK
2229 while (!QTAILQ_EMPTY(&mr->coalesced)) {
2230 cmr = QTAILQ_FIRST(&mr->coalesced);
2231 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
7267c094 2232 g_free(cmr);
ab5b3db5
FZ
2233 updated = true;
2234 }
2235
2236 if (updated) {
2237 memory_region_update_coalesced_range(mr);
093bc2cd 2238 }
093bc2cd
AK
2239}
2240
d410515e
JK
2241void memory_region_set_flush_coalesced(MemoryRegion *mr)
2242{
2243 mr->flush_coalesced_mmio = true;
2244}
2245
2246void memory_region_clear_flush_coalesced(MemoryRegion *mr)
2247{
2248 qemu_flush_coalesced_mmio_buffer();
2249 if (QTAILQ_EMPTY(&mr->coalesced)) {
2250 mr->flush_coalesced_mmio = false;
2251 }
2252}
2253
196ea131
JK
2254void memory_region_clear_global_locking(MemoryRegion *mr)
2255{
2256 mr->global_locking = false;
2257}
2258
8c56c1a5
PF
2259static bool userspace_eventfd_warning;
2260
3e9d69e7 2261void memory_region_add_eventfd(MemoryRegion *mr,
a8170e5e 2262 hwaddr addr,
3e9d69e7
AK
2263 unsigned size,
2264 bool match_data,
2265 uint64_t data,
753d5e14 2266 EventNotifier *e)
3e9d69e7
AK
2267{
2268 MemoryRegionIoeventfd mrfd = {
08dafab4
AK
2269 .addr.start = int128_make64(addr),
2270 .addr.size = int128_make64(size),
3e9d69e7
AK
2271 .match_data = match_data,
2272 .data = data,
753d5e14 2273 .e = e,
3e9d69e7
AK
2274 };
2275 unsigned i;
2276
8c56c1a5
PF
2277 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
2278 userspace_eventfd_warning))) {
2279 userspace_eventfd_warning = true;
2280 error_report("Using eventfd without MMIO binding in KVM. "
2281 "Suboptimal performance expected");
2282 }
2283
b8aecea2
JW
2284 if (size) {
2285 adjust_endianness(mr, &mrfd.data, size);
2286 }
59023ef4 2287 memory_region_transaction_begin();
3e9d69e7 2288 for (i = 0; i < mr->ioeventfd_nb; ++i) {
73bb753d 2289 if (memory_region_ioeventfd_before(&mrfd, &mr->ioeventfds[i])) {
3e9d69e7
AK
2290 break;
2291 }
2292 }
2293 ++mr->ioeventfd_nb;
7267c094 2294 mr->ioeventfds = g_realloc(mr->ioeventfds,
3e9d69e7
AK
2295 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2296 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2297 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2298 mr->ioeventfds[i] = mrfd;
4dc56152 2299 ioeventfd_update_pending |= mr->enabled;
59023ef4 2300 memory_region_transaction_commit();
3e9d69e7
AK
2301}
2302
2303void memory_region_del_eventfd(MemoryRegion *mr,
a8170e5e 2304 hwaddr addr,
3e9d69e7
AK
2305 unsigned size,
2306 bool match_data,
2307 uint64_t data,
753d5e14 2308 EventNotifier *e)
3e9d69e7
AK
2309{
2310 MemoryRegionIoeventfd mrfd = {
08dafab4
AK
2311 .addr.start = int128_make64(addr),
2312 .addr.size = int128_make64(size),
3e9d69e7
AK
2313 .match_data = match_data,
2314 .data = data,
753d5e14 2315 .e = e,
3e9d69e7
AK
2316 };
2317 unsigned i;
2318
b8aecea2
JW
2319 if (size) {
2320 adjust_endianness(mr, &mrfd.data, size);
2321 }
59023ef4 2322 memory_region_transaction_begin();
3e9d69e7 2323 for (i = 0; i < mr->ioeventfd_nb; ++i) {
73bb753d 2324 if (memory_region_ioeventfd_equal(&mrfd, &mr->ioeventfds[i])) {
3e9d69e7
AK
2325 break;
2326 }
2327 }
2328 assert(i != mr->ioeventfd_nb);
2329 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2330 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2331 --mr->ioeventfd_nb;
7267c094 2332 mr->ioeventfds = g_realloc(mr->ioeventfds,
3e9d69e7 2333 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
4dc56152 2334 ioeventfd_update_pending |= mr->enabled;
59023ef4 2335 memory_region_transaction_commit();
3e9d69e7
AK
2336}
2337
feca4ac1 2338static void memory_region_update_container_subregions(MemoryRegion *subregion)
093bc2cd 2339{
feca4ac1 2340 MemoryRegion *mr = subregion->container;
093bc2cd
AK
2341 MemoryRegion *other;
2342
59023ef4
JK
2343 memory_region_transaction_begin();
2344
dfde4e6e 2345 memory_region_ref(subregion);
093bc2cd
AK
2346 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2347 if (subregion->priority >= other->priority) {
2348 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2349 goto done;
2350 }
2351 }
2352 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2353done:
22bde714 2354 memory_region_update_pending |= mr->enabled && subregion->enabled;
59023ef4 2355 memory_region_transaction_commit();
093bc2cd
AK
2356}
2357
0598701a
PC
2358static void memory_region_add_subregion_common(MemoryRegion *mr,
2359 hwaddr offset,
2360 MemoryRegion *subregion)
2361{
feca4ac1
PB
2362 assert(!subregion->container);
2363 subregion->container = mr;
0598701a 2364 subregion->addr = offset;
feca4ac1 2365 memory_region_update_container_subregions(subregion);
0598701a 2366}
093bc2cd
AK
2367
2368void memory_region_add_subregion(MemoryRegion *mr,
a8170e5e 2369 hwaddr offset,
093bc2cd
AK
2370 MemoryRegion *subregion)
2371{
093bc2cd
AK
2372 subregion->priority = 0;
2373 memory_region_add_subregion_common(mr, offset, subregion);
2374}
2375
2376void memory_region_add_subregion_overlap(MemoryRegion *mr,
a8170e5e 2377 hwaddr offset,
093bc2cd 2378 MemoryRegion *subregion,
a1ff8ae0 2379 int priority)
093bc2cd 2380{
093bc2cd
AK
2381 subregion->priority = priority;
2382 memory_region_add_subregion_common(mr, offset, subregion);
2383}
2384
2385void memory_region_del_subregion(MemoryRegion *mr,
2386 MemoryRegion *subregion)
2387{
59023ef4 2388 memory_region_transaction_begin();
feca4ac1
PB
2389 assert(subregion->container == mr);
2390 subregion->container = NULL;
093bc2cd 2391 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
dfde4e6e 2392 memory_region_unref(subregion);
22bde714 2393 memory_region_update_pending |= mr->enabled && subregion->enabled;
59023ef4 2394 memory_region_transaction_commit();
6bba19ba
AK
2395}
2396
2397void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2398{
2399 if (enabled == mr->enabled) {
2400 return;
2401 }
59023ef4 2402 memory_region_transaction_begin();
6bba19ba 2403 mr->enabled = enabled;
22bde714 2404 memory_region_update_pending = true;
59023ef4 2405 memory_region_transaction_commit();
093bc2cd 2406}
1c0ffa58 2407
e7af4c67
MT
2408void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2409{
2410 Int128 s = int128_make64(size);
2411
2412 if (size == UINT64_MAX) {
2413 s = int128_2_64();
2414 }
2415 if (int128_eq(s, mr->size)) {
2416 return;
2417 }
2418 memory_region_transaction_begin();
2419 mr->size = s;
2420 memory_region_update_pending = true;
2421 memory_region_transaction_commit();
2422}
2423
67891b8a 2424static void memory_region_readd_subregion(MemoryRegion *mr)
2282e1af 2425{
feca4ac1 2426 MemoryRegion *container = mr->container;
2282e1af 2427
feca4ac1 2428 if (container) {
67891b8a
PC
2429 memory_region_transaction_begin();
2430 memory_region_ref(mr);
feca4ac1
PB
2431 memory_region_del_subregion(container, mr);
2432 mr->container = container;
2433 memory_region_update_container_subregions(mr);
67891b8a
PC
2434 memory_region_unref(mr);
2435 memory_region_transaction_commit();
2282e1af 2436 }
67891b8a 2437}
2282e1af 2438
67891b8a
PC
2439void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2440{
2441 if (addr != mr->addr) {
2442 mr->addr = addr;
2443 memory_region_readd_subregion(mr);
2444 }
2282e1af
AK
2445}
2446
a8170e5e 2447void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
4703359e 2448{
4703359e 2449 assert(mr->alias);
4703359e 2450
59023ef4 2451 if (offset == mr->alias_offset) {
4703359e
AK
2452 return;
2453 }
2454
59023ef4
JK
2455 memory_region_transaction_begin();
2456 mr->alias_offset = offset;
22bde714 2457 memory_region_update_pending |= mr->enabled;
59023ef4 2458 memory_region_transaction_commit();
4703359e
AK
2459}
2460
a2b257d6
IM
2461uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2462{
2463 return mr->align;
2464}
2465
e2177955
AK
2466static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2467{
2468 const AddrRange *addr = addr_;
2469 const FlatRange *fr = fr_;
2470
2471 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2472 return -1;
2473 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2474 return 1;
2475 }
2476 return 0;
2477}
2478
99e86347 2479static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
e2177955 2480{
99e86347 2481 return bsearch(&addr, view->ranges, view->nr,
e2177955
AK
2482 sizeof(FlatRange), cmp_flatrange_addr);
2483}
2484
eed2bacf
IM
2485bool memory_region_is_mapped(MemoryRegion *mr)
2486{
2487 return mr->container ? true : false;
2488}
2489
c6742b14
PB
2490/* Same as memory_region_find, but it does not add a reference to the
2491 * returned region. It must be called from an RCU critical section.
2492 */
2493static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2494 hwaddr addr, uint64_t size)
e2177955 2495{
052e87b0 2496 MemoryRegionSection ret = { .mr = NULL };
73034e9e
PB
2497 MemoryRegion *root;
2498 AddressSpace *as;
2499 AddrRange range;
99e86347 2500 FlatView *view;
73034e9e
PB
2501 FlatRange *fr;
2502
2503 addr += mr->addr;
feca4ac1
PB
2504 for (root = mr; root->container; ) {
2505 root = root->container;
73034e9e
PB
2506 addr += root->addr;
2507 }
e2177955 2508
73034e9e 2509 as = memory_region_to_address_space(root);
eed2bacf
IM
2510 if (!as) {
2511 return ret;
2512 }
73034e9e 2513 range = addrrange_make(int128_make64(addr), int128_make64(size));
99e86347 2514
16620684 2515 view = address_space_to_flatview(as);
99e86347 2516 fr = flatview_lookup(view, range);
e2177955 2517 if (!fr) {
c6742b14 2518 return ret;
e2177955
AK
2519 }
2520
99e86347 2521 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
e2177955
AK
2522 --fr;
2523 }
2524
2525 ret.mr = fr->mr;
16620684 2526 ret.fv = view;
e2177955
AK
2527 range = addrrange_intersection(range, fr->addr);
2528 ret.offset_within_region = fr->offset_in_region;
2529 ret.offset_within_region += int128_get64(int128_sub(range.start,
2530 fr->addr.start));
052e87b0 2531 ret.size = range.size;
e2177955 2532 ret.offset_within_address_space = int128_get64(range.start);
7a8499e8 2533 ret.readonly = fr->readonly;
c26763f8 2534 ret.nonvolatile = fr->nonvolatile;
c6742b14
PB
2535 return ret;
2536}
2537
2538MemoryRegionSection memory_region_find(MemoryRegion *mr,
2539 hwaddr addr, uint64_t size)
2540{
2541 MemoryRegionSection ret;
2542 rcu_read_lock();
2543 ret = memory_region_find_rcu(mr, addr, size);
2544 if (ret.mr) {
2545 memory_region_ref(ret.mr);
2546 }
2b647668 2547 rcu_read_unlock();
e2177955
AK
2548 return ret;
2549}
2550
c6742b14
PB
2551bool memory_region_present(MemoryRegion *container, hwaddr addr)
2552{
2553 MemoryRegion *mr;
2554
2555 rcu_read_lock();
2556 mr = memory_region_find_rcu(container, addr, 1).mr;
2557 rcu_read_unlock();
2558 return mr && mr != container;
2559}
2560
9c1f8f44 2561void memory_global_dirty_log_sync(void)
86e775c6 2562{
3ebb1817 2563 memory_region_sync_dirty_bitmap(NULL);
7664e80c
AK
2564}
2565
19310760
JZ
2566static VMChangeStateEntry *vmstate_change;
2567
7664e80c
AK
2568void memory_global_dirty_log_start(void)
2569{
19310760
JZ
2570 if (vmstate_change) {
2571 qemu_del_vm_change_state_handler(vmstate_change);
2572 vmstate_change = NULL;
2573 }
2574
7664e80c 2575 global_dirty_log = true;
6f6a5ef3 2576
7376e582 2577 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
6f6a5ef3 2578
39adb536 2579 /* Refresh DIRTY_MEMORY_MIGRATION bit. */
6f6a5ef3
PB
2580 memory_region_transaction_begin();
2581 memory_region_update_pending = true;
2582 memory_region_transaction_commit();
7664e80c
AK
2583}
2584
19310760 2585static void memory_global_dirty_log_do_stop(void)
7664e80c 2586{
7664e80c 2587 global_dirty_log = false;
6f6a5ef3 2588
39adb536 2589 /* Refresh DIRTY_MEMORY_MIGRATION bit. */
6f6a5ef3
PB
2590 memory_region_transaction_begin();
2591 memory_region_update_pending = true;
2592 memory_region_transaction_commit();
2593
7376e582 2594 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
7664e80c
AK
2595}
2596
19310760
JZ
2597static void memory_vm_change_state_handler(void *opaque, int running,
2598 RunState state)
2599{
2600 if (running) {
2601 memory_global_dirty_log_do_stop();
2602
2603 if (vmstate_change) {
2604 qemu_del_vm_change_state_handler(vmstate_change);
2605 vmstate_change = NULL;
2606 }
2607 }
2608}
2609
2610void memory_global_dirty_log_stop(void)
2611{
2612 if (!runstate_is_running()) {
2613 if (vmstate_change) {
2614 return;
2615 }
2616 vmstate_change = qemu_add_vm_change_state_handler(
2617 memory_vm_change_state_handler, NULL);
2618 return;
2619 }
2620
2621 memory_global_dirty_log_do_stop();
2622}
2623
7664e80c
AK
2624static void listener_add_address_space(MemoryListener *listener,
2625 AddressSpace *as)
2626{
99e86347 2627 FlatView *view;
7664e80c
AK
2628 FlatRange *fr;
2629
680a4783
PB
2630 if (listener->begin) {
2631 listener->begin(listener);
2632 }
7664e80c 2633 if (global_dirty_log) {
975aefe0
AK
2634 if (listener->log_global_start) {
2635 listener->log_global_start(listener);
2636 }
7664e80c 2637 }
975aefe0 2638
856d7245 2639 view = address_space_get_flatview(as);
99e86347 2640 FOR_EACH_FLAT_RANGE(fr, view) {
279836f8
DH
2641 MemoryRegionSection section = section_from_flat_range(fr, view);
2642
975aefe0
AK
2643 if (listener->region_add) {
2644 listener->region_add(listener, &section);
2645 }
ae990e6c
DH
2646 if (fr->dirty_log_mask && listener->log_start) {
2647 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2648 }
7664e80c 2649 }
680a4783
PB
2650 if (listener->commit) {
2651 listener->commit(listener);
2652 }
856d7245 2653 flatview_unref(view);
7664e80c
AK
2654}
2655
d25836ca
PX
2656static void listener_del_address_space(MemoryListener *listener,
2657 AddressSpace *as)
2658{
2659 FlatView *view;
2660 FlatRange *fr;
2661
2662 if (listener->begin) {
2663 listener->begin(listener);
2664 }
2665 view = address_space_get_flatview(as);
2666 FOR_EACH_FLAT_RANGE(fr, view) {
2667 MemoryRegionSection section = section_from_flat_range(fr, view);
2668
2669 if (fr->dirty_log_mask && listener->log_stop) {
2670 listener->log_stop(listener, &section, fr->dirty_log_mask, 0);
2671 }
2672 if (listener->region_del) {
2673 listener->region_del(listener, &section);
2674 }
2675 }
2676 if (listener->commit) {
2677 listener->commit(listener);
2678 }
2679 flatview_unref(view);
2680}
2681
d45fa784 2682void memory_listener_register(MemoryListener *listener, AddressSpace *as)
7664e80c 2683{
72e22d2f
AK
2684 MemoryListener *other = NULL;
2685
d45fa784 2686 listener->address_space = as;
72e22d2f 2687 if (QTAILQ_EMPTY(&memory_listeners)
eae3eb3e 2688 || listener->priority >= QTAILQ_LAST(&memory_listeners)->priority) {
72e22d2f
AK
2689 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2690 } else {
2691 QTAILQ_FOREACH(other, &memory_listeners, link) {
2692 if (listener->priority < other->priority) {
2693 break;
2694 }
2695 }
2696 QTAILQ_INSERT_BEFORE(other, listener, link);
2697 }
0d673e36 2698
9a54635d 2699 if (QTAILQ_EMPTY(&as->listeners)
eae3eb3e 2700 || listener->priority >= QTAILQ_LAST(&as->listeners)->priority) {
9a54635d
PB
2701 QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
2702 } else {
2703 QTAILQ_FOREACH(other, &as->listeners, link_as) {
2704 if (listener->priority < other->priority) {
2705 break;
2706 }
2707 }
2708 QTAILQ_INSERT_BEFORE(other, listener, link_as);
2709 }
2710
d45fa784 2711 listener_add_address_space(listener, as);
7664e80c
AK
2712}
2713
2714void memory_listener_unregister(MemoryListener *listener)
2715{
1d8280c1
PB
2716 if (!listener->address_space) {
2717 return;
2718 }
2719
d25836ca 2720 listener_del_address_space(listener, listener->address_space);
72e22d2f 2721 QTAILQ_REMOVE(&memory_listeners, listener, link);
9a54635d 2722 QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
1d8280c1 2723 listener->address_space = NULL;
86e775c6 2724}
e2177955 2725
a2166410
GK
2726void address_space_remove_listeners(AddressSpace *as)
2727{
2728 while (!QTAILQ_EMPTY(&as->listeners)) {
2729 memory_listener_unregister(QTAILQ_FIRST(&as->listeners));
2730 }
2731}
2732
7dca8043 2733void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
1c0ffa58 2734{
ac95190e 2735 memory_region_ref(root);
8786db7c 2736 as->root = root;
67ace39b 2737 as->current_map = NULL;
4c19eb72
AK
2738 as->ioeventfd_nb = 0;
2739 as->ioeventfds = NULL;
9a54635d 2740 QTAILQ_INIT(&as->listeners);
0d673e36 2741 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
7dca8043 2742 as->name = g_strdup(name ? name : "anonymous");
202fc01b
AK
2743 address_space_update_topology(as);
2744 address_space_update_ioeventfds(as);
1c0ffa58 2745}
658b2224 2746
374f2981 2747static void do_address_space_destroy(AddressSpace *as)
83f3c251 2748{
9a54635d 2749 assert(QTAILQ_EMPTY(&as->listeners));
078c44f4 2750
856d7245 2751 flatview_unref(as->current_map);
7dca8043 2752 g_free(as->name);
4c19eb72 2753 g_free(as->ioeventfds);
ac95190e 2754 memory_region_unref(as->root);
83f3c251
AK
2755}
2756
374f2981
PB
2757void address_space_destroy(AddressSpace *as)
2758{
ac95190e
PB
2759 MemoryRegion *root = as->root;
2760
374f2981
PB
2761 /* Flush out anything from MemoryListeners listening in on this */
2762 memory_region_transaction_begin();
2763 as->root = NULL;
2764 memory_region_transaction_commit();
2765 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2766
2767 /* At this point, as->dispatch and as->current_map are dummy
2768 * entries that the guest should never use. Wait for the old
2769 * values to expire before freeing the data.
2770 */
ac95190e 2771 as->root = root;
374f2981
PB
2772 call_rcu(as, do_address_space_destroy, rcu);
2773}
2774
4e831901
PX
2775static const char *memory_region_type(MemoryRegion *mr)
2776{
2777 if (memory_region_is_ram_device(mr)) {
2778 return "ramd";
2779 } else if (memory_region_is_romd(mr)) {
2780 return "romd";
2781 } else if (memory_region_is_rom(mr)) {
2782 return "rom";
2783 } else if (memory_region_is_ram(mr)) {
2784 return "ram";
2785 } else {
2786 return "i/o";
2787 }
2788}
2789
314e2987
BS
2790typedef struct MemoryRegionList MemoryRegionList;
2791
2792struct MemoryRegionList {
2793 const MemoryRegion *mr;
a16878d2 2794 QTAILQ_ENTRY(MemoryRegionList) mrqueue;
314e2987
BS
2795};
2796
b58deb34 2797typedef QTAILQ_HEAD(, MemoryRegionList) MemoryRegionListHead;
314e2987 2798
4e831901
PX
2799#define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
2800 int128_sub((size), int128_one())) : 0)
2801#define MTREE_INDENT " "
2802
b6b71cb5 2803static void mtree_expand_owner(const char *label, Object *obj)
fc051ae6
AK
2804{
2805 DeviceState *dev = (DeviceState *) object_dynamic_cast(obj, TYPE_DEVICE);
2806
b6b71cb5 2807 qemu_printf(" %s:{%s", label, dev ? "dev" : "obj");
fc051ae6 2808 if (dev && dev->id) {
b6b71cb5 2809 qemu_printf(" id=%s", dev->id);
fc051ae6
AK
2810 } else {
2811 gchar *canonical_path = object_get_canonical_path(obj);
2812 if (canonical_path) {
b6b71cb5 2813 qemu_printf(" path=%s", canonical_path);
fc051ae6
AK
2814 g_free(canonical_path);
2815 } else {
b6b71cb5 2816 qemu_printf(" type=%s", object_get_typename(obj));
fc051ae6
AK
2817 }
2818 }
b6b71cb5 2819 qemu_printf("}");
fc051ae6
AK
2820}
2821
b6b71cb5 2822static void mtree_print_mr_owner(const MemoryRegion *mr)
fc051ae6
AK
2823{
2824 Object *owner = mr->owner;
2825 Object *parent = memory_region_owner((MemoryRegion *)mr);
2826
2827 if (!owner && !parent) {
b6b71cb5 2828 qemu_printf(" orphan");
fc051ae6
AK
2829 return;
2830 }
2831 if (owner) {
b6b71cb5 2832 mtree_expand_owner("owner", owner);
fc051ae6
AK
2833 }
2834 if (parent && parent != owner) {
b6b71cb5 2835 mtree_expand_owner("parent", parent);
fc051ae6
AK
2836 }
2837}
2838
b6b71cb5 2839static void mtree_print_mr(const MemoryRegion *mr, unsigned int level,
a8170e5e 2840 hwaddr base,
fc051ae6
AK
2841 MemoryRegionListHead *alias_print_queue,
2842 bool owner)
314e2987 2843{
9479c57a
JK
2844 MemoryRegionList *new_ml, *ml, *next_ml;
2845 MemoryRegionListHead submr_print_queue;
314e2987
BS
2846 const MemoryRegion *submr;
2847 unsigned int i;
b31f8412 2848 hwaddr cur_start, cur_end;
314e2987 2849
f8a9f720 2850 if (!mr) {
314e2987
BS
2851 return;
2852 }
2853
2854 for (i = 0; i < level; i++) {
b6b71cb5 2855 qemu_printf(MTREE_INDENT);
314e2987
BS
2856 }
2857
b31f8412
PX
2858 cur_start = base + mr->addr;
2859 cur_end = cur_start + MR_SIZE(mr->size);
2860
2861 /*
2862 * Try to detect overflow of memory region. This should never
2863 * happen normally. When it happens, we dump something to warn the
2864 * user who is observing this.
2865 */
2866 if (cur_start < base || cur_end < cur_start) {
b6b71cb5 2867 qemu_printf("[DETECTED OVERFLOW!] ");
b31f8412
PX
2868 }
2869
314e2987
BS
2870 if (mr->alias) {
2871 MemoryRegionList *ml;
2872 bool found = false;
2873
2874 /* check if the alias is already in the queue */
a16878d2 2875 QTAILQ_FOREACH(ml, alias_print_queue, mrqueue) {
f54bb15f 2876 if (ml->mr == mr->alias) {
314e2987
BS
2877 found = true;
2878 }
2879 }
2880
2881 if (!found) {
2882 ml = g_new(MemoryRegionList, 1);
2883 ml->mr = mr->alias;
a16878d2 2884 QTAILQ_INSERT_TAIL(alias_print_queue, ml, mrqueue);
314e2987 2885 }
b6b71cb5
MA
2886 qemu_printf(TARGET_FMT_plx "-" TARGET_FMT_plx
2887 " (prio %d, %s%s): alias %s @%s " TARGET_FMT_plx
2888 "-" TARGET_FMT_plx "%s",
2889 cur_start, cur_end,
2890 mr->priority,
2891 mr->nonvolatile ? "nv-" : "",
2892 memory_region_type((MemoryRegion *)mr),
2893 memory_region_name(mr),
2894 memory_region_name(mr->alias),
2895 mr->alias_offset,
2896 mr->alias_offset + MR_SIZE(mr->size),
2897 mr->enabled ? "" : " [disabled]");
fc051ae6 2898 if (owner) {
b6b71cb5 2899 mtree_print_mr_owner(mr);
fc051ae6 2900 }
314e2987 2901 } else {
b6b71cb5
MA
2902 qemu_printf(TARGET_FMT_plx "-" TARGET_FMT_plx
2903 " (prio %d, %s%s): %s%s",
2904 cur_start, cur_end,
2905 mr->priority,
2906 mr->nonvolatile ? "nv-" : "",
2907 memory_region_type((MemoryRegion *)mr),
2908 memory_region_name(mr),
2909 mr->enabled ? "" : " [disabled]");
fc051ae6 2910 if (owner) {
b6b71cb5 2911 mtree_print_mr_owner(mr);
fc051ae6 2912 }
314e2987 2913 }
b6b71cb5 2914 qemu_printf("\n");
9479c57a
JK
2915
2916 QTAILQ_INIT(&submr_print_queue);
2917
314e2987 2918 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
9479c57a
JK
2919 new_ml = g_new(MemoryRegionList, 1);
2920 new_ml->mr = submr;
a16878d2 2921 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
9479c57a
JK
2922 if (new_ml->mr->addr < ml->mr->addr ||
2923 (new_ml->mr->addr == ml->mr->addr &&
2924 new_ml->mr->priority > ml->mr->priority)) {
a16878d2 2925 QTAILQ_INSERT_BEFORE(ml, new_ml, mrqueue);
9479c57a
JK
2926 new_ml = NULL;
2927 break;
2928 }
2929 }
2930 if (new_ml) {
a16878d2 2931 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, mrqueue);
9479c57a
JK
2932 }
2933 }
2934
a16878d2 2935 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
b6b71cb5 2936 mtree_print_mr(ml->mr, level + 1, cur_start,
fc051ae6 2937 alias_print_queue, owner);
9479c57a
JK
2938 }
2939
a16878d2 2940 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, mrqueue, next_ml) {
9479c57a 2941 g_free(ml);
314e2987
BS
2942 }
2943}
2944
5e8fd947 2945struct FlatViewInfo {
5e8fd947
AK
2946 int counter;
2947 bool dispatch_tree;
fc051ae6 2948 bool owner;
5e8fd947
AK
2949};
2950
2951static void mtree_print_flatview(gpointer key, gpointer value,
2952 gpointer user_data)
57bb40c9 2953{
5e8fd947
AK
2954 FlatView *view = key;
2955 GArray *fv_address_spaces = value;
2956 struct FlatViewInfo *fvi = user_data;
57bb40c9
PX
2957 FlatRange *range = &view->ranges[0];
2958 MemoryRegion *mr;
2959 int n = view->nr;
5e8fd947
AK
2960 int i;
2961 AddressSpace *as;
2962
b6b71cb5 2963 qemu_printf("FlatView #%d\n", fvi->counter);
5e8fd947
AK
2964 ++fvi->counter;
2965
2966 for (i = 0; i < fv_address_spaces->len; ++i) {
2967 as = g_array_index(fv_address_spaces, AddressSpace*, i);
b6b71cb5
MA
2968 qemu_printf(" AS \"%s\", root: %s",
2969 as->name, memory_region_name(as->root));
5e8fd947 2970 if (as->root->alias) {
b6b71cb5 2971 qemu_printf(", alias %s", memory_region_name(as->root->alias));
5e8fd947 2972 }
b6b71cb5 2973 qemu_printf("\n");
5e8fd947
AK
2974 }
2975
b6b71cb5 2976 qemu_printf(" Root memory region: %s\n",
5e8fd947 2977 view->root ? memory_region_name(view->root) : "(none)");
57bb40c9
PX
2978
2979 if (n <= 0) {
b6b71cb5 2980 qemu_printf(MTREE_INDENT "No rendered FlatView\n\n");
57bb40c9
PX
2981 return;
2982 }
2983
2984 while (n--) {
2985 mr = range->mr;
377a07aa 2986 if (range->offset_in_region) {
b6b71cb5
MA
2987 qemu_printf(MTREE_INDENT TARGET_FMT_plx "-" TARGET_FMT_plx
2988 " (prio %d, %s%s): %s @" TARGET_FMT_plx,
2989 int128_get64(range->addr.start),
2990 int128_get64(range->addr.start)
2991 + MR_SIZE(range->addr.size),
2992 mr->priority,
2993 range->nonvolatile ? "nv-" : "",
2994 range->readonly ? "rom" : memory_region_type(mr),
2995 memory_region_name(mr),
2996 range->offset_in_region);
377a07aa 2997 } else {
b6b71cb5
MA
2998 qemu_printf(MTREE_INDENT TARGET_FMT_plx "-" TARGET_FMT_plx
2999 " (prio %d, %s%s): %s",
3000 int128_get64(range->addr.start),
3001 int128_get64(range->addr.start)
3002 + MR_SIZE(range->addr.size),
3003 mr->priority,
3004 range->nonvolatile ? "nv-" : "",
3005 range->readonly ? "rom" : memory_region_type(mr),
3006 memory_region_name(mr));
377a07aa 3007 }
fc051ae6 3008 if (fvi->owner) {
b6b71cb5 3009 mtree_print_mr_owner(mr);
fc051ae6 3010 }
b6b71cb5 3011 qemu_printf("\n");
57bb40c9
PX
3012 range++;
3013 }
3014
5e8fd947
AK
3015#if !defined(CONFIG_USER_ONLY)
3016 if (fvi->dispatch_tree && view->root) {
b6b71cb5 3017 mtree_print_dispatch(view->dispatch, view->root);
5e8fd947
AK
3018 }
3019#endif
3020
b6b71cb5 3021 qemu_printf("\n");
5e8fd947
AK
3022}
3023
3024static gboolean mtree_info_flatview_free(gpointer key, gpointer value,
3025 gpointer user_data)
3026{
3027 FlatView *view = key;
3028 GArray *fv_address_spaces = value;
3029
3030 g_array_unref(fv_address_spaces);
57bb40c9 3031 flatview_unref(view);
5e8fd947
AK
3032
3033 return true;
57bb40c9
PX
3034}
3035
b6b71cb5 3036void mtree_info(bool flatview, bool dispatch_tree, bool owner)
314e2987
BS
3037{
3038 MemoryRegionListHead ml_head;
3039 MemoryRegionList *ml, *ml2;
0d673e36 3040 AddressSpace *as;
314e2987 3041
57bb40c9 3042 if (flatview) {
5e8fd947
AK
3043 FlatView *view;
3044 struct FlatViewInfo fvi = {
5e8fd947 3045 .counter = 0,
fc051ae6
AK
3046 .dispatch_tree = dispatch_tree,
3047 .owner = owner,
5e8fd947
AK
3048 };
3049 GArray *fv_address_spaces;
3050 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3051
3052 /* Gather all FVs in one table */
57bb40c9 3053 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
5e8fd947
AK
3054 view = address_space_get_flatview(as);
3055
3056 fv_address_spaces = g_hash_table_lookup(views, view);
3057 if (!fv_address_spaces) {
3058 fv_address_spaces = g_array_new(false, false, sizeof(as));
3059 g_hash_table_insert(views, view, fv_address_spaces);
3060 }
3061
3062 g_array_append_val(fv_address_spaces, as);
57bb40c9 3063 }
5e8fd947
AK
3064
3065 /* Print */
3066 g_hash_table_foreach(views, mtree_print_flatview, &fvi);
3067
3068 /* Free */
3069 g_hash_table_foreach_remove(views, mtree_info_flatview_free, 0);
3070 g_hash_table_unref(views);
3071
57bb40c9
PX
3072 return;
3073 }
3074
314e2987
BS
3075 QTAILQ_INIT(&ml_head);
3076
0d673e36 3077 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
b6b71cb5
MA
3078 qemu_printf("address-space: %s\n", as->name);
3079 mtree_print_mr(as->root, 1, 0, &ml_head, owner);
3080 qemu_printf("\n");
b9f9be88
BS
3081 }
3082
314e2987 3083 /* print aliased regions */
a16878d2 3084 QTAILQ_FOREACH(ml, &ml_head, mrqueue) {
b6b71cb5
MA
3085 qemu_printf("memory-region: %s\n", memory_region_name(ml->mr));
3086 mtree_print_mr(ml->mr, 1, 0, &ml_head, owner);
3087 qemu_printf("\n");
314e2987
BS
3088 }
3089
a16878d2 3090 QTAILQ_FOREACH_SAFE(ml, &ml_head, mrqueue, ml2) {
88365e47 3091 g_free(ml);
314e2987 3092 }
314e2987 3093}
b4fefef9 3094
b08199c6
PM
3095void memory_region_init_ram(MemoryRegion *mr,
3096 struct Object *owner,
3097 const char *name,
3098 uint64_t size,
3099 Error **errp)
3100{
3101 DeviceState *owner_dev;
3102 Error *err = NULL;
3103
3104 memory_region_init_ram_nomigrate(mr, owner, name, size, &err);
3105 if (err) {
3106 error_propagate(errp, err);
3107 return;
3108 }
3109 /* This will assert if owner is neither NULL nor a DeviceState.
3110 * We only want the owner here for the purposes of defining a
3111 * unique name for migration. TODO: Ideally we should implement
3112 * a naming scheme for Objects which are not DeviceStates, in
3113 * which case we can relax this restriction.
3114 */
3115 owner_dev = DEVICE(owner);
3116 vmstate_register_ram(mr, owner_dev);
3117}
3118
3119void memory_region_init_rom(MemoryRegion *mr,
3120 struct Object *owner,
3121 const char *name,
3122 uint64_t size,
3123 Error **errp)
3124{
3125 DeviceState *owner_dev;
3126 Error *err = NULL;
3127
3128 memory_region_init_rom_nomigrate(mr, owner, name, size, &err);
3129 if (err) {
3130 error_propagate(errp, err);
3131 return;
3132 }
3133 /* This will assert if owner is neither NULL nor a DeviceState.
3134 * We only want the owner here for the purposes of defining a
3135 * unique name for migration. TODO: Ideally we should implement
3136 * a naming scheme for Objects which are not DeviceStates, in
3137 * which case we can relax this restriction.
3138 */
3139 owner_dev = DEVICE(owner);
3140 vmstate_register_ram(mr, owner_dev);
3141}
3142
3143void memory_region_init_rom_device(MemoryRegion *mr,
3144 struct Object *owner,
3145 const MemoryRegionOps *ops,
3146 void *opaque,
3147 const char *name,
3148 uint64_t size,
3149 Error **errp)
3150{
3151 DeviceState *owner_dev;
3152 Error *err = NULL;
3153
3154 memory_region_init_rom_device_nomigrate(mr, owner, ops, opaque,
3155 name, size, &err);
3156 if (err) {
3157 error_propagate(errp, err);
3158 return;
3159 }
3160 /* This will assert if owner is neither NULL nor a DeviceState.
3161 * We only want the owner here for the purposes of defining a
3162 * unique name for migration. TODO: Ideally we should implement
3163 * a naming scheme for Objects which are not DeviceStates, in
3164 * which case we can relax this restriction.
3165 */
3166 owner_dev = DEVICE(owner);
3167 vmstate_register_ram(mr, owner_dev);
3168}
3169
b4fefef9
PC
3170static const TypeInfo memory_region_info = {
3171 .parent = TYPE_OBJECT,
3172 .name = TYPE_MEMORY_REGION,
3173 .instance_size = sizeof(MemoryRegion),
3174 .instance_init = memory_region_initfn,
3175 .instance_finalize = memory_region_finalize,
3176};
3177
3df9d748
AK
3178static const TypeInfo iommu_memory_region_info = {
3179 .parent = TYPE_MEMORY_REGION,
3180 .name = TYPE_IOMMU_MEMORY_REGION,
1221a474 3181 .class_size = sizeof(IOMMUMemoryRegionClass),
3df9d748
AK
3182 .instance_size = sizeof(IOMMUMemoryRegion),
3183 .instance_init = iommu_memory_region_initfn,
1221a474 3184 .abstract = true,
3df9d748
AK
3185};
3186
b4fefef9
PC
3187static void memory_register_types(void)
3188{
3189 type_register_static(&memory_region_info);
3df9d748 3190 type_register_static(&iommu_memory_region_info);
b4fefef9
PC
3191}
3192
3193type_init(memory_register_types)