hw/ssi: Add a model of Xilinx Versal's OSPI flash memory controller
[qemu.git] / softmmu / memory.c
blob678dc62f0697bb253685b2f2d60b7c97ab2483a7
1 /*
2 * Physical memory management
4 * Copyright 2011 Red Hat, Inc. and/or its affiliates
6 * Authors:
7 * Avi Kivity <avi@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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.
16 #include "qemu/osdep.h"
17 #include "qemu/log.h"
18 #include "qapi/error.h"
19 #include "exec/memory.h"
20 #include "qapi/visitor.h"
21 #include "qemu/bitops.h"
22 #include "qemu/error-report.h"
23 #include "qemu/main-loop.h"
24 #include "qemu/qemu-print.h"
25 #include "qom/object.h"
26 #include "trace.h"
28 #include "exec/memory-internal.h"
29 #include "exec/ram_addr.h"
30 #include "sysemu/kvm.h"
31 #include "sysemu/runstate.h"
32 #include "sysemu/tcg.h"
33 #include "qemu/accel.h"
34 #include "hw/boards.h"
35 #include "migration/vmstate.h"
37 //#define DEBUG_UNASSIGNED
39 static unsigned memory_region_transaction_depth;
40 static bool memory_region_update_pending;
41 static bool ioeventfd_update_pending;
42 unsigned int global_dirty_tracking;
44 static QTAILQ_HEAD(, MemoryListener) memory_listeners
45 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
47 static QTAILQ_HEAD(, AddressSpace) address_spaces
48 = QTAILQ_HEAD_INITIALIZER(address_spaces);
50 static GHashTable *flat_views;
52 typedef struct AddrRange AddrRange;
55 * Note that signed integers are needed for negative offsetting in aliases
56 * (large MemoryRegion::alias_offset).
58 struct AddrRange {
59 Int128 start;
60 Int128 size;
63 static AddrRange addrrange_make(Int128 start, Int128 size)
65 return (AddrRange) { start, size };
68 static bool addrrange_equal(AddrRange r1, AddrRange r2)
70 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
73 static Int128 addrrange_end(AddrRange r)
75 return int128_add(r.start, r.size);
78 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
80 int128_addto(&range.start, delta);
81 return range;
84 static bool addrrange_contains(AddrRange range, Int128 addr)
86 return int128_ge(addr, range.start)
87 && int128_lt(addr, addrrange_end(range));
90 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
92 return addrrange_contains(r1, r2.start)
93 || addrrange_contains(r2, r1.start);
96 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
98 Int128 start = int128_max(r1.start, r2.start);
99 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
100 return addrrange_make(start, int128_sub(end, start));
103 enum ListenerDirection { Forward, Reverse };
105 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
106 do { \
107 MemoryListener *_listener; \
109 switch (_direction) { \
110 case Forward: \
111 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
112 if (_listener->_callback) { \
113 _listener->_callback(_listener, ##_args); \
116 break; \
117 case Reverse: \
118 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, link) { \
119 if (_listener->_callback) { \
120 _listener->_callback(_listener, ##_args); \
123 break; \
124 default: \
125 abort(); \
127 } while (0)
129 #define MEMORY_LISTENER_CALL(_as, _callback, _direction, _section, _args...) \
130 do { \
131 MemoryListener *_listener; \
133 switch (_direction) { \
134 case Forward: \
135 QTAILQ_FOREACH(_listener, &(_as)->listeners, link_as) { \
136 if (_listener->_callback) { \
137 _listener->_callback(_listener, _section, ##_args); \
140 break; \
141 case Reverse: \
142 QTAILQ_FOREACH_REVERSE(_listener, &(_as)->listeners, link_as) { \
143 if (_listener->_callback) { \
144 _listener->_callback(_listener, _section, ##_args); \
147 break; \
148 default: \
149 abort(); \
151 } while (0)
153 /* No need to ref/unref .mr, the FlatRange keeps it alive. */
154 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...) \
155 do { \
156 MemoryRegionSection mrs = section_from_flat_range(fr, \
157 address_space_to_flatview(as)); \
158 MEMORY_LISTENER_CALL(as, callback, dir, &mrs, ##_args); \
159 } while(0)
161 struct CoalescedMemoryRange {
162 AddrRange addr;
163 QTAILQ_ENTRY(CoalescedMemoryRange) link;
166 struct MemoryRegionIoeventfd {
167 AddrRange addr;
168 bool match_data;
169 uint64_t data;
170 EventNotifier *e;
173 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd *a,
174 MemoryRegionIoeventfd *b)
176 if (int128_lt(a->addr.start, b->addr.start)) {
177 return true;
178 } else if (int128_gt(a->addr.start, b->addr.start)) {
179 return false;
180 } else if (int128_lt(a->addr.size, b->addr.size)) {
181 return true;
182 } else if (int128_gt(a->addr.size, b->addr.size)) {
183 return false;
184 } else if (a->match_data < b->match_data) {
185 return true;
186 } else if (a->match_data > b->match_data) {
187 return false;
188 } else if (a->match_data) {
189 if (a->data < b->data) {
190 return true;
191 } else if (a->data > b->data) {
192 return false;
195 if (a->e < b->e) {
196 return true;
197 } else if (a->e > b->e) {
198 return false;
200 return false;
203 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd *a,
204 MemoryRegionIoeventfd *b)
206 if (int128_eq(a->addr.start, b->addr.start) &&
207 (!int128_nz(a->addr.size) || !int128_nz(b->addr.size) ||
208 (int128_eq(a->addr.size, b->addr.size) &&
209 (a->match_data == b->match_data) &&
210 ((a->match_data && (a->data == b->data)) || !a->match_data) &&
211 (a->e == b->e))))
212 return true;
214 return false;
217 /* Range of memory in the global map. Addresses are absolute. */
218 struct FlatRange {
219 MemoryRegion *mr;
220 hwaddr offset_in_region;
221 AddrRange addr;
222 uint8_t dirty_log_mask;
223 bool romd_mode;
224 bool readonly;
225 bool nonvolatile;
228 #define FOR_EACH_FLAT_RANGE(var, view) \
229 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
231 static inline MemoryRegionSection
232 section_from_flat_range(FlatRange *fr, FlatView *fv)
234 return (MemoryRegionSection) {
235 .mr = fr->mr,
236 .fv = fv,
237 .offset_within_region = fr->offset_in_region,
238 .size = fr->addr.size,
239 .offset_within_address_space = int128_get64(fr->addr.start),
240 .readonly = fr->readonly,
241 .nonvolatile = fr->nonvolatile,
245 static bool flatrange_equal(FlatRange *a, FlatRange *b)
247 return a->mr == b->mr
248 && addrrange_equal(a->addr, b->addr)
249 && a->offset_in_region == b->offset_in_region
250 && a->romd_mode == b->romd_mode
251 && a->readonly == b->readonly
252 && a->nonvolatile == b->nonvolatile;
255 static FlatView *flatview_new(MemoryRegion *mr_root)
257 FlatView *view;
259 view = g_new0(FlatView, 1);
260 view->ref = 1;
261 view->root = mr_root;
262 memory_region_ref(mr_root);
263 trace_flatview_new(view, mr_root);
265 return view;
268 /* Insert a range into a given position. Caller is responsible for maintaining
269 * sorting order.
271 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
273 if (view->nr == view->nr_allocated) {
274 view->nr_allocated = MAX(2 * view->nr, 10);
275 view->ranges = g_realloc(view->ranges,
276 view->nr_allocated * sizeof(*view->ranges));
278 memmove(view->ranges + pos + 1, view->ranges + pos,
279 (view->nr - pos) * sizeof(FlatRange));
280 view->ranges[pos] = *range;
281 memory_region_ref(range->mr);
282 ++view->nr;
285 static void flatview_destroy(FlatView *view)
287 int i;
289 trace_flatview_destroy(view, view->root);
290 if (view->dispatch) {
291 address_space_dispatch_free(view->dispatch);
293 for (i = 0; i < view->nr; i++) {
294 memory_region_unref(view->ranges[i].mr);
296 g_free(view->ranges);
297 memory_region_unref(view->root);
298 g_free(view);
301 static bool flatview_ref(FlatView *view)
303 return qatomic_fetch_inc_nonzero(&view->ref) > 0;
306 void flatview_unref(FlatView *view)
308 if (qatomic_fetch_dec(&view->ref) == 1) {
309 trace_flatview_destroy_rcu(view, view->root);
310 assert(view->root);
311 call_rcu(view, flatview_destroy, rcu);
315 static bool can_merge(FlatRange *r1, FlatRange *r2)
317 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
318 && r1->mr == r2->mr
319 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
320 r1->addr.size),
321 int128_make64(r2->offset_in_region))
322 && r1->dirty_log_mask == r2->dirty_log_mask
323 && r1->romd_mode == r2->romd_mode
324 && r1->readonly == r2->readonly
325 && r1->nonvolatile == r2->nonvolatile;
328 /* Attempt to simplify a view by merging adjacent ranges */
329 static void flatview_simplify(FlatView *view)
331 unsigned i, j, k;
333 i = 0;
334 while (i < view->nr) {
335 j = i + 1;
336 while (j < view->nr
337 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
338 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
339 ++j;
341 ++i;
342 for (k = i; k < j; k++) {
343 memory_region_unref(view->ranges[k].mr);
345 memmove(&view->ranges[i], &view->ranges[j],
346 (view->nr - j) * sizeof(view->ranges[j]));
347 view->nr -= j - i;
351 static bool memory_region_big_endian(MemoryRegion *mr)
353 #ifdef TARGET_WORDS_BIGENDIAN
354 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
355 #else
356 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
357 #endif
360 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, MemOp op)
362 if ((op & MO_BSWAP) != devend_memop(mr->ops->endianness)) {
363 switch (op & MO_SIZE) {
364 case MO_8:
365 break;
366 case MO_16:
367 *data = bswap16(*data);
368 break;
369 case MO_32:
370 *data = bswap32(*data);
371 break;
372 case MO_64:
373 *data = bswap64(*data);
374 break;
375 default:
376 g_assert_not_reached();
381 static inline void memory_region_shift_read_access(uint64_t *value,
382 signed shift,
383 uint64_t mask,
384 uint64_t tmp)
386 if (shift >= 0) {
387 *value |= (tmp & mask) << shift;
388 } else {
389 *value |= (tmp & mask) >> -shift;
393 static inline uint64_t memory_region_shift_write_access(uint64_t *value,
394 signed shift,
395 uint64_t mask)
397 uint64_t tmp;
399 if (shift >= 0) {
400 tmp = (*value >> shift) & mask;
401 } else {
402 tmp = (*value << -shift) & mask;
405 return tmp;
408 static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
410 MemoryRegion *root;
411 hwaddr abs_addr = offset;
413 abs_addr += mr->addr;
414 for (root = mr; root->container; ) {
415 root = root->container;
416 abs_addr += root->addr;
419 return abs_addr;
422 static int get_cpu_index(void)
424 if (current_cpu) {
425 return current_cpu->cpu_index;
427 return -1;
430 static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
431 hwaddr addr,
432 uint64_t *value,
433 unsigned size,
434 signed shift,
435 uint64_t mask,
436 MemTxAttrs attrs)
438 uint64_t tmp;
440 tmp = mr->ops->read(mr->opaque, addr, size);
441 if (mr->subpage) {
442 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
443 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_READ)) {
444 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
445 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size,
446 memory_region_name(mr));
448 memory_region_shift_read_access(value, shift, mask, tmp);
449 return MEMTX_OK;
452 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
453 hwaddr addr,
454 uint64_t *value,
455 unsigned size,
456 signed shift,
457 uint64_t mask,
458 MemTxAttrs attrs)
460 uint64_t tmp = 0;
461 MemTxResult r;
463 r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
464 if (mr->subpage) {
465 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
466 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_READ)) {
467 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
468 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size,
469 memory_region_name(mr));
471 memory_region_shift_read_access(value, shift, mask, tmp);
472 return r;
475 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
476 hwaddr addr,
477 uint64_t *value,
478 unsigned size,
479 signed shift,
480 uint64_t mask,
481 MemTxAttrs attrs)
483 uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
485 if (mr->subpage) {
486 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
487 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_WRITE)) {
488 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
489 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size,
490 memory_region_name(mr));
492 mr->ops->write(mr->opaque, addr, tmp, size);
493 return MEMTX_OK;
496 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
497 hwaddr addr,
498 uint64_t *value,
499 unsigned size,
500 signed shift,
501 uint64_t mask,
502 MemTxAttrs attrs)
504 uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
506 if (mr->subpage) {
507 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
508 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_WRITE)) {
509 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
510 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size,
511 memory_region_name(mr));
513 return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
516 static MemTxResult access_with_adjusted_size(hwaddr addr,
517 uint64_t *value,
518 unsigned size,
519 unsigned access_size_min,
520 unsigned access_size_max,
521 MemTxResult (*access_fn)
522 (MemoryRegion *mr,
523 hwaddr addr,
524 uint64_t *value,
525 unsigned size,
526 signed shift,
527 uint64_t mask,
528 MemTxAttrs attrs),
529 MemoryRegion *mr,
530 MemTxAttrs attrs)
532 uint64_t access_mask;
533 unsigned access_size;
534 unsigned i;
535 MemTxResult r = MEMTX_OK;
537 if (!access_size_min) {
538 access_size_min = 1;
540 if (!access_size_max) {
541 access_size_max = 4;
544 /* FIXME: support unaligned access? */
545 access_size = MAX(MIN(size, access_size_max), access_size_min);
546 access_mask = MAKE_64BIT_MASK(0, access_size * 8);
547 if (memory_region_big_endian(mr)) {
548 for (i = 0; i < size; i += access_size) {
549 r |= access_fn(mr, addr + i, value, access_size,
550 (size - access_size - i) * 8, access_mask, attrs);
552 } else {
553 for (i = 0; i < size; i += access_size) {
554 r |= access_fn(mr, addr + i, value, access_size, i * 8,
555 access_mask, attrs);
558 return r;
561 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
563 AddressSpace *as;
565 while (mr->container) {
566 mr = mr->container;
568 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
569 if (mr == as->root) {
570 return as;
573 return NULL;
576 /* Render a memory region into the global view. Ranges in @view obscure
577 * ranges in @mr.
579 static void render_memory_region(FlatView *view,
580 MemoryRegion *mr,
581 Int128 base,
582 AddrRange clip,
583 bool readonly,
584 bool nonvolatile)
586 MemoryRegion *subregion;
587 unsigned i;
588 hwaddr offset_in_region;
589 Int128 remain;
590 Int128 now;
591 FlatRange fr;
592 AddrRange tmp;
594 if (!mr->enabled) {
595 return;
598 int128_addto(&base, int128_make64(mr->addr));
599 readonly |= mr->readonly;
600 nonvolatile |= mr->nonvolatile;
602 tmp = addrrange_make(base, mr->size);
604 if (!addrrange_intersects(tmp, clip)) {
605 return;
608 clip = addrrange_intersection(tmp, clip);
610 if (mr->alias) {
611 int128_subfrom(&base, int128_make64(mr->alias->addr));
612 int128_subfrom(&base, int128_make64(mr->alias_offset));
613 render_memory_region(view, mr->alias, base, clip,
614 readonly, nonvolatile);
615 return;
618 /* Render subregions in priority order. */
619 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
620 render_memory_region(view, subregion, base, clip,
621 readonly, nonvolatile);
624 if (!mr->terminates) {
625 return;
628 offset_in_region = int128_get64(int128_sub(clip.start, base));
629 base = clip.start;
630 remain = clip.size;
632 fr.mr = mr;
633 fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
634 fr.romd_mode = mr->romd_mode;
635 fr.readonly = readonly;
636 fr.nonvolatile = nonvolatile;
638 /* Render the region itself into any gaps left by the current view. */
639 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
640 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
641 continue;
643 if (int128_lt(base, view->ranges[i].addr.start)) {
644 now = int128_min(remain,
645 int128_sub(view->ranges[i].addr.start, base));
646 fr.offset_in_region = offset_in_region;
647 fr.addr = addrrange_make(base, now);
648 flatview_insert(view, i, &fr);
649 ++i;
650 int128_addto(&base, now);
651 offset_in_region += int128_get64(now);
652 int128_subfrom(&remain, now);
654 now = int128_sub(int128_min(int128_add(base, remain),
655 addrrange_end(view->ranges[i].addr)),
656 base);
657 int128_addto(&base, now);
658 offset_in_region += int128_get64(now);
659 int128_subfrom(&remain, now);
661 if (int128_nz(remain)) {
662 fr.offset_in_region = offset_in_region;
663 fr.addr = addrrange_make(base, remain);
664 flatview_insert(view, i, &fr);
668 void flatview_for_each_range(FlatView *fv, flatview_cb cb , void *opaque)
670 FlatRange *fr;
672 assert(fv);
673 assert(cb);
675 FOR_EACH_FLAT_RANGE(fr, fv) {
676 if (cb(fr->addr.start, fr->addr.size, fr->mr,
677 fr->offset_in_region, opaque)) {
678 break;
683 static MemoryRegion *memory_region_get_flatview_root(MemoryRegion *mr)
685 while (mr->enabled) {
686 if (mr->alias) {
687 if (!mr->alias_offset && int128_ge(mr->size, mr->alias->size)) {
688 /* The alias is included in its entirety. Use it as
689 * the "real" root, so that we can share more FlatViews.
691 mr = mr->alias;
692 continue;
694 } else if (!mr->terminates) {
695 unsigned int found = 0;
696 MemoryRegion *child, *next = NULL;
697 QTAILQ_FOREACH(child, &mr->subregions, subregions_link) {
698 if (child->enabled) {
699 if (++found > 1) {
700 next = NULL;
701 break;
703 if (!child->addr && int128_ge(mr->size, child->size)) {
704 /* A child is included in its entirety. If it's the only
705 * enabled one, use it in the hope of finding an alias down the
706 * way. This will also let us share FlatViews.
708 next = child;
712 if (found == 0) {
713 return NULL;
715 if (next) {
716 mr = next;
717 continue;
721 return mr;
724 return NULL;
727 /* Render a memory topology into a list of disjoint absolute ranges. */
728 static FlatView *generate_memory_topology(MemoryRegion *mr)
730 int i;
731 FlatView *view;
733 view = flatview_new(mr);
735 if (mr) {
736 render_memory_region(view, mr, int128_zero(),
737 addrrange_make(int128_zero(), int128_2_64()),
738 false, false);
740 flatview_simplify(view);
742 view->dispatch = address_space_dispatch_new(view);
743 for (i = 0; i < view->nr; i++) {
744 MemoryRegionSection mrs =
745 section_from_flat_range(&view->ranges[i], view);
746 flatview_add_to_dispatch(view, &mrs);
748 address_space_dispatch_compact(view->dispatch);
749 g_hash_table_replace(flat_views, mr, view);
751 return view;
754 static void address_space_add_del_ioeventfds(AddressSpace *as,
755 MemoryRegionIoeventfd *fds_new,
756 unsigned fds_new_nb,
757 MemoryRegionIoeventfd *fds_old,
758 unsigned fds_old_nb)
760 unsigned iold, inew;
761 MemoryRegionIoeventfd *fd;
762 MemoryRegionSection section;
764 /* Generate a symmetric difference of the old and new fd sets, adding
765 * and deleting as necessary.
768 iold = inew = 0;
769 while (iold < fds_old_nb || inew < fds_new_nb) {
770 if (iold < fds_old_nb
771 && (inew == fds_new_nb
772 || memory_region_ioeventfd_before(&fds_old[iold],
773 &fds_new[inew]))) {
774 fd = &fds_old[iold];
775 section = (MemoryRegionSection) {
776 .fv = address_space_to_flatview(as),
777 .offset_within_address_space = int128_get64(fd->addr.start),
778 .size = fd->addr.size,
780 MEMORY_LISTENER_CALL(as, eventfd_del, Forward, &section,
781 fd->match_data, fd->data, fd->e);
782 ++iold;
783 } else if (inew < fds_new_nb
784 && (iold == fds_old_nb
785 || memory_region_ioeventfd_before(&fds_new[inew],
786 &fds_old[iold]))) {
787 fd = &fds_new[inew];
788 section = (MemoryRegionSection) {
789 .fv = address_space_to_flatview(as),
790 .offset_within_address_space = int128_get64(fd->addr.start),
791 .size = fd->addr.size,
793 MEMORY_LISTENER_CALL(as, eventfd_add, Reverse, &section,
794 fd->match_data, fd->data, fd->e);
795 ++inew;
796 } else {
797 ++iold;
798 ++inew;
803 FlatView *address_space_get_flatview(AddressSpace *as)
805 FlatView *view;
807 RCU_READ_LOCK_GUARD();
808 do {
809 view = address_space_to_flatview(as);
810 /* If somebody has replaced as->current_map concurrently,
811 * flatview_ref returns false.
813 } while (!flatview_ref(view));
814 return view;
817 static void address_space_update_ioeventfds(AddressSpace *as)
819 FlatView *view;
820 FlatRange *fr;
821 unsigned ioeventfd_nb = 0;
822 unsigned ioeventfd_max;
823 MemoryRegionIoeventfd *ioeventfds;
824 AddrRange tmp;
825 unsigned i;
828 * It is likely that the number of ioeventfds hasn't changed much, so use
829 * the previous size as the starting value, with some headroom to avoid
830 * gratuitous reallocations.
832 ioeventfd_max = QEMU_ALIGN_UP(as->ioeventfd_nb, 4);
833 ioeventfds = g_new(MemoryRegionIoeventfd, ioeventfd_max);
835 view = address_space_get_flatview(as);
836 FOR_EACH_FLAT_RANGE(fr, view) {
837 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
838 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
839 int128_sub(fr->addr.start,
840 int128_make64(fr->offset_in_region)));
841 if (addrrange_intersects(fr->addr, tmp)) {
842 ++ioeventfd_nb;
843 if (ioeventfd_nb > ioeventfd_max) {
844 ioeventfd_max = MAX(ioeventfd_max * 2, 4);
845 ioeventfds = g_realloc(ioeventfds,
846 ioeventfd_max * sizeof(*ioeventfds));
848 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
849 ioeventfds[ioeventfd_nb-1].addr = tmp;
854 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
855 as->ioeventfds, as->ioeventfd_nb);
857 g_free(as->ioeventfds);
858 as->ioeventfds = ioeventfds;
859 as->ioeventfd_nb = ioeventfd_nb;
860 flatview_unref(view);
864 * Notify the memory listeners about the coalesced IO change events of
865 * range `cmr'. Only the part that has intersection of the specified
866 * FlatRange will be sent.
868 static void flat_range_coalesced_io_notify(FlatRange *fr, AddressSpace *as,
869 CoalescedMemoryRange *cmr, bool add)
871 AddrRange tmp;
873 tmp = addrrange_shift(cmr->addr,
874 int128_sub(fr->addr.start,
875 int128_make64(fr->offset_in_region)));
876 if (!addrrange_intersects(tmp, fr->addr)) {
877 return;
879 tmp = addrrange_intersection(tmp, fr->addr);
881 if (add) {
882 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, coalesced_io_add,
883 int128_get64(tmp.start),
884 int128_get64(tmp.size));
885 } else {
886 MEMORY_LISTENER_UPDATE_REGION(fr, as, Reverse, coalesced_io_del,
887 int128_get64(tmp.start),
888 int128_get64(tmp.size));
892 static void flat_range_coalesced_io_del(FlatRange *fr, AddressSpace *as)
894 CoalescedMemoryRange *cmr;
896 QTAILQ_FOREACH(cmr, &fr->mr->coalesced, link) {
897 flat_range_coalesced_io_notify(fr, as, cmr, false);
901 static void flat_range_coalesced_io_add(FlatRange *fr, AddressSpace *as)
903 MemoryRegion *mr = fr->mr;
904 CoalescedMemoryRange *cmr;
906 if (QTAILQ_EMPTY(&mr->coalesced)) {
907 return;
910 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
911 flat_range_coalesced_io_notify(fr, as, cmr, true);
915 static void address_space_update_topology_pass(AddressSpace *as,
916 const FlatView *old_view,
917 const FlatView *new_view,
918 bool adding)
920 unsigned iold, inew;
921 FlatRange *frold, *frnew;
923 /* Generate a symmetric difference of the old and new memory maps.
924 * Kill ranges in the old map, and instantiate ranges in the new map.
926 iold = inew = 0;
927 while (iold < old_view->nr || inew < new_view->nr) {
928 if (iold < old_view->nr) {
929 frold = &old_view->ranges[iold];
930 } else {
931 frold = NULL;
933 if (inew < new_view->nr) {
934 frnew = &new_view->ranges[inew];
935 } else {
936 frnew = NULL;
939 if (frold
940 && (!frnew
941 || int128_lt(frold->addr.start, frnew->addr.start)
942 || (int128_eq(frold->addr.start, frnew->addr.start)
943 && !flatrange_equal(frold, frnew)))) {
944 /* In old but not in new, or in both but attributes changed. */
946 if (!adding) {
947 flat_range_coalesced_io_del(frold, as);
948 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
951 ++iold;
952 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
953 /* In both and unchanged (except logging may have changed) */
955 if (adding) {
956 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
957 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
958 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
959 frold->dirty_log_mask,
960 frnew->dirty_log_mask);
962 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
963 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
964 frold->dirty_log_mask,
965 frnew->dirty_log_mask);
969 ++iold;
970 ++inew;
971 } else {
972 /* In new */
974 if (adding) {
975 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
976 flat_range_coalesced_io_add(frnew, as);
979 ++inew;
984 static void flatviews_init(void)
986 static FlatView *empty_view;
988 if (flat_views) {
989 return;
992 flat_views = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL,
993 (GDestroyNotify) flatview_unref);
994 if (!empty_view) {
995 empty_view = generate_memory_topology(NULL);
996 /* We keep it alive forever in the global variable. */
997 flatview_ref(empty_view);
998 } else {
999 g_hash_table_replace(flat_views, NULL, empty_view);
1000 flatview_ref(empty_view);
1004 static void flatviews_reset(void)
1006 AddressSpace *as;
1008 if (flat_views) {
1009 g_hash_table_unref(flat_views);
1010 flat_views = NULL;
1012 flatviews_init();
1014 /* Render unique FVs */
1015 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1016 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1018 if (g_hash_table_lookup(flat_views, physmr)) {
1019 continue;
1022 generate_memory_topology(physmr);
1026 static void address_space_set_flatview(AddressSpace *as)
1028 FlatView *old_view = address_space_to_flatview(as);
1029 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1030 FlatView *new_view = g_hash_table_lookup(flat_views, physmr);
1032 assert(new_view);
1034 if (old_view == new_view) {
1035 return;
1038 if (old_view) {
1039 flatview_ref(old_view);
1042 flatview_ref(new_view);
1044 if (!QTAILQ_EMPTY(&as->listeners)) {
1045 FlatView tmpview = { .nr = 0 }, *old_view2 = old_view;
1047 if (!old_view2) {
1048 old_view2 = &tmpview;
1050 address_space_update_topology_pass(as, old_view2, new_view, false);
1051 address_space_update_topology_pass(as, old_view2, new_view, true);
1054 /* Writes are protected by the BQL. */
1055 qatomic_rcu_set(&as->current_map, new_view);
1056 if (old_view) {
1057 flatview_unref(old_view);
1060 /* Note that all the old MemoryRegions are still alive up to this
1061 * point. This relieves most MemoryListeners from the need to
1062 * ref/unref the MemoryRegions they get---unless they use them
1063 * outside the iothread mutex, in which case precise reference
1064 * counting is necessary.
1066 if (old_view) {
1067 flatview_unref(old_view);
1071 static void address_space_update_topology(AddressSpace *as)
1073 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1075 flatviews_init();
1076 if (!g_hash_table_lookup(flat_views, physmr)) {
1077 generate_memory_topology(physmr);
1079 address_space_set_flatview(as);
1082 void memory_region_transaction_begin(void)
1084 qemu_flush_coalesced_mmio_buffer();
1085 ++memory_region_transaction_depth;
1088 void memory_region_transaction_commit(void)
1090 AddressSpace *as;
1092 assert(memory_region_transaction_depth);
1093 assert(qemu_mutex_iothread_locked());
1095 --memory_region_transaction_depth;
1096 if (!memory_region_transaction_depth) {
1097 if (memory_region_update_pending) {
1098 flatviews_reset();
1100 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
1102 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1103 address_space_set_flatview(as);
1104 address_space_update_ioeventfds(as);
1106 memory_region_update_pending = false;
1107 ioeventfd_update_pending = false;
1108 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
1109 } else if (ioeventfd_update_pending) {
1110 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1111 address_space_update_ioeventfds(as);
1113 ioeventfd_update_pending = false;
1118 static void memory_region_destructor_none(MemoryRegion *mr)
1122 static void memory_region_destructor_ram(MemoryRegion *mr)
1124 qemu_ram_free(mr->ram_block);
1127 static bool memory_region_need_escape(char c)
1129 return c == '/' || c == '[' || c == '\\' || c == ']';
1132 static char *memory_region_escape_name(const char *name)
1134 const char *p;
1135 char *escaped, *q;
1136 uint8_t c;
1137 size_t bytes = 0;
1139 for (p = name; *p; p++) {
1140 bytes += memory_region_need_escape(*p) ? 4 : 1;
1142 if (bytes == p - name) {
1143 return g_memdup(name, bytes + 1);
1146 escaped = g_malloc(bytes + 1);
1147 for (p = name, q = escaped; *p; p++) {
1148 c = *p;
1149 if (unlikely(memory_region_need_escape(c))) {
1150 *q++ = '\\';
1151 *q++ = 'x';
1152 *q++ = "0123456789abcdef"[c >> 4];
1153 c = "0123456789abcdef"[c & 15];
1155 *q++ = c;
1157 *q = 0;
1158 return escaped;
1161 static void memory_region_do_init(MemoryRegion *mr,
1162 Object *owner,
1163 const char *name,
1164 uint64_t size)
1166 mr->size = int128_make64(size);
1167 if (size == UINT64_MAX) {
1168 mr->size = int128_2_64();
1170 mr->name = g_strdup(name);
1171 mr->owner = owner;
1172 mr->ram_block = NULL;
1174 if (name) {
1175 char *escaped_name = memory_region_escape_name(name);
1176 char *name_array = g_strdup_printf("%s[*]", escaped_name);
1178 if (!owner) {
1179 owner = container_get(qdev_get_machine(), "/unattached");
1182 object_property_add_child(owner, name_array, OBJECT(mr));
1183 object_unref(OBJECT(mr));
1184 g_free(name_array);
1185 g_free(escaped_name);
1189 void memory_region_init(MemoryRegion *mr,
1190 Object *owner,
1191 const char *name,
1192 uint64_t size)
1194 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
1195 memory_region_do_init(mr, owner, name, size);
1198 static void memory_region_get_container(Object *obj, Visitor *v,
1199 const char *name, void *opaque,
1200 Error **errp)
1202 MemoryRegion *mr = MEMORY_REGION(obj);
1203 char *path = (char *)"";
1205 if (mr->container) {
1206 path = object_get_canonical_path(OBJECT(mr->container));
1208 visit_type_str(v, name, &path, errp);
1209 if (mr->container) {
1210 g_free(path);
1214 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1215 const char *part)
1217 MemoryRegion *mr = MEMORY_REGION(obj);
1219 return OBJECT(mr->container);
1222 static void memory_region_get_priority(Object *obj, Visitor *v,
1223 const char *name, void *opaque,
1224 Error **errp)
1226 MemoryRegion *mr = MEMORY_REGION(obj);
1227 int32_t value = mr->priority;
1229 visit_type_int32(v, name, &value, errp);
1232 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1233 void *opaque, Error **errp)
1235 MemoryRegion *mr = MEMORY_REGION(obj);
1236 uint64_t value = memory_region_size(mr);
1238 visit_type_uint64(v, name, &value, errp);
1241 static void memory_region_initfn(Object *obj)
1243 MemoryRegion *mr = MEMORY_REGION(obj);
1244 ObjectProperty *op;
1246 mr->ops = &unassigned_mem_ops;
1247 mr->enabled = true;
1248 mr->romd_mode = true;
1249 mr->destructor = memory_region_destructor_none;
1250 QTAILQ_INIT(&mr->subregions);
1251 QTAILQ_INIT(&mr->coalesced);
1253 op = object_property_add(OBJECT(mr), "container",
1254 "link<" TYPE_MEMORY_REGION ">",
1255 memory_region_get_container,
1256 NULL, /* memory_region_set_container */
1257 NULL, NULL);
1258 op->resolve = memory_region_resolve_container;
1260 object_property_add_uint64_ptr(OBJECT(mr), "addr",
1261 &mr->addr, OBJ_PROP_FLAG_READ);
1262 object_property_add(OBJECT(mr), "priority", "uint32",
1263 memory_region_get_priority,
1264 NULL, /* memory_region_set_priority */
1265 NULL, NULL);
1266 object_property_add(OBJECT(mr), "size", "uint64",
1267 memory_region_get_size,
1268 NULL, /* memory_region_set_size, */
1269 NULL, NULL);
1272 static void iommu_memory_region_initfn(Object *obj)
1274 MemoryRegion *mr = MEMORY_REGION(obj);
1276 mr->is_iommu = true;
1279 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1280 unsigned size)
1282 #ifdef DEBUG_UNASSIGNED
1283 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1284 #endif
1285 return 0;
1288 static void unassigned_mem_write(void *opaque, hwaddr addr,
1289 uint64_t val, unsigned size)
1291 #ifdef DEBUG_UNASSIGNED
1292 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1293 #endif
1296 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1297 unsigned size, bool is_write,
1298 MemTxAttrs attrs)
1300 return false;
1303 const MemoryRegionOps unassigned_mem_ops = {
1304 .valid.accepts = unassigned_mem_accepts,
1305 .endianness = DEVICE_NATIVE_ENDIAN,
1308 static uint64_t memory_region_ram_device_read(void *opaque,
1309 hwaddr addr, unsigned size)
1311 MemoryRegion *mr = opaque;
1312 uint64_t data = (uint64_t)~0;
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;
1329 trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);
1331 return data;
1334 static void memory_region_ram_device_write(void *opaque, hwaddr addr,
1335 uint64_t data, unsigned size)
1337 MemoryRegion *mr = opaque;
1339 trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);
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;
1357 static const MemoryRegionOps ram_device_mem_ops = {
1358 .read = memory_region_ram_device_read,
1359 .write = memory_region_ram_device_write,
1360 .endianness = DEVICE_HOST_ENDIAN,
1361 .valid = {
1362 .min_access_size = 1,
1363 .max_access_size = 8,
1364 .unaligned = true,
1366 .impl = {
1367 .min_access_size = 1,
1368 .max_access_size = 8,
1369 .unaligned = true,
1373 bool memory_region_access_valid(MemoryRegion *mr,
1374 hwaddr addr,
1375 unsigned size,
1376 bool is_write,
1377 MemTxAttrs attrs)
1379 if (mr->ops->valid.accepts
1380 && !mr->ops->valid.accepts(mr->opaque, addr, size, is_write, attrs)) {
1381 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1382 ", size %u, region '%s', reason: rejected\n",
1383 is_write ? "write" : "read",
1384 addr, size, memory_region_name(mr));
1385 return false;
1388 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1389 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1390 ", size %u, region '%s', reason: unaligned\n",
1391 is_write ? "write" : "read",
1392 addr, size, memory_region_name(mr));
1393 return false;
1396 /* Treat zero as compatibility all valid */
1397 if (!mr->ops->valid.max_access_size) {
1398 return true;
1401 if (size > mr->ops->valid.max_access_size
1402 || size < mr->ops->valid.min_access_size) {
1403 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1404 ", size %u, region '%s', reason: invalid size "
1405 "(min:%u max:%u)\n",
1406 is_write ? "write" : "read",
1407 addr, size, memory_region_name(mr),
1408 mr->ops->valid.min_access_size,
1409 mr->ops->valid.max_access_size);
1410 return false;
1412 return true;
1415 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1416 hwaddr addr,
1417 uint64_t *pval,
1418 unsigned size,
1419 MemTxAttrs attrs)
1421 *pval = 0;
1423 if (mr->ops->read) {
1424 return access_with_adjusted_size(addr, pval, size,
1425 mr->ops->impl.min_access_size,
1426 mr->ops->impl.max_access_size,
1427 memory_region_read_accessor,
1428 mr, attrs);
1429 } else {
1430 return access_with_adjusted_size(addr, pval, size,
1431 mr->ops->impl.min_access_size,
1432 mr->ops->impl.max_access_size,
1433 memory_region_read_with_attrs_accessor,
1434 mr, attrs);
1438 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1439 hwaddr addr,
1440 uint64_t *pval,
1441 MemOp op,
1442 MemTxAttrs attrs)
1444 unsigned size = memop_size(op);
1445 MemTxResult r;
1447 if (mr->alias) {
1448 return memory_region_dispatch_read(mr->alias,
1449 mr->alias_offset + addr,
1450 pval, op, attrs);
1452 if (!memory_region_access_valid(mr, addr, size, false, attrs)) {
1453 *pval = unassigned_mem_read(mr, addr, size);
1454 return MEMTX_DECODE_ERROR;
1457 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1458 adjust_endianness(mr, pval, op);
1459 return r;
1462 /* Return true if an eventfd was signalled */
1463 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1464 hwaddr addr,
1465 uint64_t data,
1466 unsigned size,
1467 MemTxAttrs attrs)
1469 MemoryRegionIoeventfd ioeventfd = {
1470 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1471 .data = data,
1473 unsigned i;
1475 for (i = 0; i < mr->ioeventfd_nb; i++) {
1476 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1477 ioeventfd.e = mr->ioeventfds[i].e;
1479 if (memory_region_ioeventfd_equal(&ioeventfd, &mr->ioeventfds[i])) {
1480 event_notifier_set(ioeventfd.e);
1481 return true;
1485 return false;
1488 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1489 hwaddr addr,
1490 uint64_t data,
1491 MemOp op,
1492 MemTxAttrs attrs)
1494 unsigned size = memop_size(op);
1496 if (mr->alias) {
1497 return memory_region_dispatch_write(mr->alias,
1498 mr->alias_offset + addr,
1499 data, op, attrs);
1501 if (!memory_region_access_valid(mr, addr, size, true, attrs)) {
1502 unassigned_mem_write(mr, addr, data, size);
1503 return MEMTX_DECODE_ERROR;
1506 adjust_endianness(mr, &data, op);
1508 if ((!kvm_eventfds_enabled()) &&
1509 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1510 return MEMTX_OK;
1513 if (mr->ops->write) {
1514 return access_with_adjusted_size(addr, &data, size,
1515 mr->ops->impl.min_access_size,
1516 mr->ops->impl.max_access_size,
1517 memory_region_write_accessor, mr,
1518 attrs);
1519 } else {
1520 return
1521 access_with_adjusted_size(addr, &data, size,
1522 mr->ops->impl.min_access_size,
1523 mr->ops->impl.max_access_size,
1524 memory_region_write_with_attrs_accessor,
1525 mr, attrs);
1529 void memory_region_init_io(MemoryRegion *mr,
1530 Object *owner,
1531 const MemoryRegionOps *ops,
1532 void *opaque,
1533 const char *name,
1534 uint64_t size)
1536 memory_region_init(mr, owner, name, size);
1537 mr->ops = ops ? ops : &unassigned_mem_ops;
1538 mr->opaque = opaque;
1539 mr->terminates = true;
1542 void memory_region_init_ram_nomigrate(MemoryRegion *mr,
1543 Object *owner,
1544 const char *name,
1545 uint64_t size,
1546 Error **errp)
1548 memory_region_init_ram_flags_nomigrate(mr, owner, name, size, 0, errp);
1551 void memory_region_init_ram_flags_nomigrate(MemoryRegion *mr,
1552 Object *owner,
1553 const char *name,
1554 uint64_t size,
1555 uint32_t ram_flags,
1556 Error **errp)
1558 Error *err = NULL;
1559 memory_region_init(mr, owner, name, size);
1560 mr->ram = true;
1561 mr->terminates = true;
1562 mr->destructor = memory_region_destructor_ram;
1563 mr->ram_block = qemu_ram_alloc(size, ram_flags, mr, &err);
1564 if (err) {
1565 mr->size = int128_zero();
1566 object_unparent(OBJECT(mr));
1567 error_propagate(errp, err);
1571 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1572 Object *owner,
1573 const char *name,
1574 uint64_t size,
1575 uint64_t max_size,
1576 void (*resized)(const char*,
1577 uint64_t length,
1578 void *host),
1579 Error **errp)
1581 Error *err = NULL;
1582 memory_region_init(mr, owner, name, size);
1583 mr->ram = true;
1584 mr->terminates = true;
1585 mr->destructor = memory_region_destructor_ram;
1586 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1587 mr, &err);
1588 if (err) {
1589 mr->size = int128_zero();
1590 object_unparent(OBJECT(mr));
1591 error_propagate(errp, err);
1595 #ifdef CONFIG_POSIX
1596 void memory_region_init_ram_from_file(MemoryRegion *mr,
1597 Object *owner,
1598 const char *name,
1599 uint64_t size,
1600 uint64_t align,
1601 uint32_t ram_flags,
1602 const char *path,
1603 bool readonly,
1604 Error **errp)
1606 Error *err = NULL;
1607 memory_region_init(mr, owner, name, size);
1608 mr->ram = true;
1609 mr->readonly = readonly;
1610 mr->terminates = true;
1611 mr->destructor = memory_region_destructor_ram;
1612 mr->align = align;
1613 mr->ram_block = qemu_ram_alloc_from_file(size, mr, ram_flags, path,
1614 readonly, &err);
1615 if (err) {
1616 mr->size = int128_zero();
1617 object_unparent(OBJECT(mr));
1618 error_propagate(errp, err);
1622 void memory_region_init_ram_from_fd(MemoryRegion *mr,
1623 Object *owner,
1624 const char *name,
1625 uint64_t size,
1626 uint32_t ram_flags,
1627 int fd,
1628 ram_addr_t offset,
1629 Error **errp)
1631 Error *err = NULL;
1632 memory_region_init(mr, owner, name, size);
1633 mr->ram = true;
1634 mr->terminates = true;
1635 mr->destructor = memory_region_destructor_ram;
1636 mr->ram_block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, offset,
1637 false, &err);
1638 if (err) {
1639 mr->size = int128_zero();
1640 object_unparent(OBJECT(mr));
1641 error_propagate(errp, err);
1644 #endif
1646 void memory_region_init_ram_ptr(MemoryRegion *mr,
1647 Object *owner,
1648 const char *name,
1649 uint64_t size,
1650 void *ptr)
1652 memory_region_init(mr, owner, name, size);
1653 mr->ram = true;
1654 mr->terminates = true;
1655 mr->destructor = memory_region_destructor_ram;
1657 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1658 assert(ptr != NULL);
1659 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1662 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1663 Object *owner,
1664 const char *name,
1665 uint64_t size,
1666 void *ptr)
1668 memory_region_init(mr, owner, name, size);
1669 mr->ram = true;
1670 mr->terminates = true;
1671 mr->ram_device = true;
1672 mr->ops = &ram_device_mem_ops;
1673 mr->opaque = mr;
1674 mr->destructor = memory_region_destructor_ram;
1676 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1677 assert(ptr != NULL);
1678 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1681 void memory_region_init_alias(MemoryRegion *mr,
1682 Object *owner,
1683 const char *name,
1684 MemoryRegion *orig,
1685 hwaddr offset,
1686 uint64_t size)
1688 memory_region_init(mr, owner, name, size);
1689 mr->alias = orig;
1690 mr->alias_offset = offset;
1693 void memory_region_init_rom_nomigrate(MemoryRegion *mr,
1694 Object *owner,
1695 const char *name,
1696 uint64_t size,
1697 Error **errp)
1699 memory_region_init_ram_flags_nomigrate(mr, owner, name, size, 0, errp);
1700 mr->readonly = true;
1703 void memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1704 Object *owner,
1705 const MemoryRegionOps *ops,
1706 void *opaque,
1707 const char *name,
1708 uint64_t size,
1709 Error **errp)
1711 Error *err = NULL;
1712 assert(ops);
1713 memory_region_init(mr, owner, name, size);
1714 mr->ops = ops;
1715 mr->opaque = opaque;
1716 mr->terminates = true;
1717 mr->rom_device = true;
1718 mr->destructor = memory_region_destructor_ram;
1719 mr->ram_block = qemu_ram_alloc(size, 0, mr, &err);
1720 if (err) {
1721 mr->size = int128_zero();
1722 object_unparent(OBJECT(mr));
1723 error_propagate(errp, err);
1727 void memory_region_init_iommu(void *_iommu_mr,
1728 size_t instance_size,
1729 const char *mrtypename,
1730 Object *owner,
1731 const char *name,
1732 uint64_t size)
1734 struct IOMMUMemoryRegion *iommu_mr;
1735 struct MemoryRegion *mr;
1737 object_initialize(_iommu_mr, instance_size, mrtypename);
1738 mr = MEMORY_REGION(_iommu_mr);
1739 memory_region_do_init(mr, owner, name, size);
1740 iommu_mr = IOMMU_MEMORY_REGION(mr);
1741 mr->terminates = true; /* then re-forwards */
1742 QLIST_INIT(&iommu_mr->iommu_notify);
1743 iommu_mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
1746 static void memory_region_finalize(Object *obj)
1748 MemoryRegion *mr = MEMORY_REGION(obj);
1750 assert(!mr->container);
1752 /* We know the region is not visible in any address space (it
1753 * does not have a container and cannot be a root either because
1754 * it has no references, so we can blindly clear mr->enabled.
1755 * memory_region_set_enabled instead could trigger a transaction
1756 * and cause an infinite loop.
1758 mr->enabled = false;
1759 memory_region_transaction_begin();
1760 while (!QTAILQ_EMPTY(&mr->subregions)) {
1761 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1762 memory_region_del_subregion(mr, subregion);
1764 memory_region_transaction_commit();
1766 mr->destructor(mr);
1767 memory_region_clear_coalescing(mr);
1768 g_free((char *)mr->name);
1769 g_free(mr->ioeventfds);
1772 Object *memory_region_owner(MemoryRegion *mr)
1774 Object *obj = OBJECT(mr);
1775 return obj->parent;
1778 void memory_region_ref(MemoryRegion *mr)
1780 /* MMIO callbacks most likely will access data that belongs
1781 * to the owner, hence the need to ref/unref the owner whenever
1782 * the memory region is in use.
1784 * The memory region is a child of its owner. As long as the
1785 * owner doesn't call unparent itself on the memory region,
1786 * ref-ing the owner will also keep the memory region alive.
1787 * Memory regions without an owner are supposed to never go away;
1788 * we do not ref/unref them because it slows down DMA sensibly.
1790 if (mr && mr->owner) {
1791 object_ref(mr->owner);
1795 void memory_region_unref(MemoryRegion *mr)
1797 if (mr && mr->owner) {
1798 object_unref(mr->owner);
1802 uint64_t memory_region_size(MemoryRegion *mr)
1804 if (int128_eq(mr->size, int128_2_64())) {
1805 return UINT64_MAX;
1807 return int128_get64(mr->size);
1810 const char *memory_region_name(const MemoryRegion *mr)
1812 if (!mr->name) {
1813 ((MemoryRegion *)mr)->name =
1814 g_strdup(object_get_canonical_path_component(OBJECT(mr)));
1816 return mr->name;
1819 bool memory_region_is_ram_device(MemoryRegion *mr)
1821 return mr->ram_device;
1824 bool memory_region_is_protected(MemoryRegion *mr)
1826 return mr->ram && (mr->ram_block->flags & RAM_PROTECTED);
1829 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1831 uint8_t mask = mr->dirty_log_mask;
1832 RAMBlock *rb = mr->ram_block;
1834 if (global_dirty_tracking && ((rb && qemu_ram_is_migratable(rb)) ||
1835 memory_region_is_iommu(mr))) {
1836 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1839 if (tcg_enabled() && rb) {
1840 /* TCG only cares about dirty memory logging for RAM, not IOMMU. */
1841 mask |= (1 << DIRTY_MEMORY_CODE);
1843 return mask;
1846 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1848 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1851 static int memory_region_update_iommu_notify_flags(IOMMUMemoryRegion *iommu_mr,
1852 Error **errp)
1854 IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1855 IOMMUNotifier *iommu_notifier;
1856 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1857 int ret = 0;
1859 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
1860 flags |= iommu_notifier->notifier_flags;
1863 if (flags != iommu_mr->iommu_notify_flags && imrc->notify_flag_changed) {
1864 ret = imrc->notify_flag_changed(iommu_mr,
1865 iommu_mr->iommu_notify_flags,
1866 flags, errp);
1869 if (!ret) {
1870 iommu_mr->iommu_notify_flags = flags;
1872 return ret;
1875 int memory_region_iommu_set_page_size_mask(IOMMUMemoryRegion *iommu_mr,
1876 uint64_t page_size_mask,
1877 Error **errp)
1879 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1880 int ret = 0;
1882 if (imrc->iommu_set_page_size_mask) {
1883 ret = imrc->iommu_set_page_size_mask(iommu_mr, page_size_mask, errp);
1885 return ret;
1888 int memory_region_register_iommu_notifier(MemoryRegion *mr,
1889 IOMMUNotifier *n, Error **errp)
1891 IOMMUMemoryRegion *iommu_mr;
1892 int ret;
1894 if (mr->alias) {
1895 return memory_region_register_iommu_notifier(mr->alias, n, errp);
1898 /* We need to register for at least one bitfield */
1899 iommu_mr = IOMMU_MEMORY_REGION(mr);
1900 assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
1901 assert(n->start <= n->end);
1902 assert(n->iommu_idx >= 0 &&
1903 n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
1905 QLIST_INSERT_HEAD(&iommu_mr->iommu_notify, n, node);
1906 ret = memory_region_update_iommu_notify_flags(iommu_mr, errp);
1907 if (ret) {
1908 QLIST_REMOVE(n, node);
1910 return ret;
1913 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr)
1915 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1917 if (imrc->get_min_page_size) {
1918 return imrc->get_min_page_size(iommu_mr);
1920 return TARGET_PAGE_SIZE;
1923 void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
1925 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
1926 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1927 hwaddr addr, granularity;
1928 IOMMUTLBEntry iotlb;
1930 /* If the IOMMU has its own replay callback, override */
1931 if (imrc->replay) {
1932 imrc->replay(iommu_mr, n);
1933 return;
1936 granularity = memory_region_iommu_get_min_page_size(iommu_mr);
1938 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1939 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, n->iommu_idx);
1940 if (iotlb.perm != IOMMU_NONE) {
1941 n->notify(n, &iotlb);
1944 /* if (2^64 - MR size) < granularity, it's possible to get an
1945 * infinite loop here. This should catch such a wraparound */
1946 if ((addr + granularity) < addr) {
1947 break;
1952 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1953 IOMMUNotifier *n)
1955 IOMMUMemoryRegion *iommu_mr;
1957 if (mr->alias) {
1958 memory_region_unregister_iommu_notifier(mr->alias, n);
1959 return;
1961 QLIST_REMOVE(n, node);
1962 iommu_mr = IOMMU_MEMORY_REGION(mr);
1963 memory_region_update_iommu_notify_flags(iommu_mr, NULL);
1966 void memory_region_notify_iommu_one(IOMMUNotifier *notifier,
1967 IOMMUTLBEvent *event)
1969 IOMMUTLBEntry *entry = &event->entry;
1970 hwaddr entry_end = entry->iova + entry->addr_mask;
1971 IOMMUTLBEntry tmp = *entry;
1973 if (event->type == IOMMU_NOTIFIER_UNMAP) {
1974 assert(entry->perm == IOMMU_NONE);
1978 * Skip the notification if the notification does not overlap
1979 * with registered range.
1981 if (notifier->start > entry_end || notifier->end < entry->iova) {
1982 return;
1985 if (notifier->notifier_flags & IOMMU_NOTIFIER_DEVIOTLB_UNMAP) {
1986 /* Crop (iova, addr_mask) to range */
1987 tmp.iova = MAX(tmp.iova, notifier->start);
1988 tmp.addr_mask = MIN(entry_end, notifier->end) - tmp.iova;
1989 } else {
1990 assert(entry->iova >= notifier->start && entry_end <= notifier->end);
1993 if (event->type & notifier->notifier_flags) {
1994 notifier->notify(notifier, &tmp);
1998 void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
1999 int iommu_idx,
2000 IOMMUTLBEvent event)
2002 IOMMUNotifier *iommu_notifier;
2004 assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
2006 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
2007 if (iommu_notifier->iommu_idx == iommu_idx) {
2008 memory_region_notify_iommu_one(iommu_notifier, &event);
2013 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
2014 enum IOMMUMemoryRegionAttr attr,
2015 void *data)
2017 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2019 if (!imrc->get_attr) {
2020 return -EINVAL;
2023 return imrc->get_attr(iommu_mr, attr, data);
2026 int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
2027 MemTxAttrs attrs)
2029 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2031 if (!imrc->attrs_to_index) {
2032 return 0;
2035 return imrc->attrs_to_index(iommu_mr, attrs);
2038 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr)
2040 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2042 if (!imrc->num_indexes) {
2043 return 1;
2046 return imrc->num_indexes(iommu_mr);
2049 RamDiscardManager *memory_region_get_ram_discard_manager(MemoryRegion *mr)
2051 if (!memory_region_is_mapped(mr) || !memory_region_is_ram(mr)) {
2052 return NULL;
2054 return mr->rdm;
2057 void memory_region_set_ram_discard_manager(MemoryRegion *mr,
2058 RamDiscardManager *rdm)
2060 g_assert(memory_region_is_ram(mr) && !memory_region_is_mapped(mr));
2061 g_assert(!rdm || !mr->rdm);
2062 mr->rdm = rdm;
2065 uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,
2066 const MemoryRegion *mr)
2068 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2070 g_assert(rdmc->get_min_granularity);
2071 return rdmc->get_min_granularity(rdm, mr);
2074 bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
2075 const MemoryRegionSection *section)
2077 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2079 g_assert(rdmc->is_populated);
2080 return rdmc->is_populated(rdm, section);
2083 int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
2084 MemoryRegionSection *section,
2085 ReplayRamPopulate replay_fn,
2086 void *opaque)
2088 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2090 g_assert(rdmc->replay_populated);
2091 return rdmc->replay_populated(rdm, section, replay_fn, opaque);
2094 void ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
2095 MemoryRegionSection *section,
2096 ReplayRamDiscard replay_fn,
2097 void *opaque)
2099 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2101 g_assert(rdmc->replay_discarded);
2102 rdmc->replay_discarded(rdm, section, replay_fn, opaque);
2105 void ram_discard_manager_register_listener(RamDiscardManager *rdm,
2106 RamDiscardListener *rdl,
2107 MemoryRegionSection *section)
2109 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2111 g_assert(rdmc->register_listener);
2112 rdmc->register_listener(rdm, rdl, section);
2115 void ram_discard_manager_unregister_listener(RamDiscardManager *rdm,
2116 RamDiscardListener *rdl)
2118 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2120 g_assert(rdmc->unregister_listener);
2121 rdmc->unregister_listener(rdm, rdl);
2124 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
2126 uint8_t mask = 1 << client;
2127 uint8_t old_logging;
2129 assert(client == DIRTY_MEMORY_VGA);
2130 old_logging = mr->vga_logging_count;
2131 mr->vga_logging_count += log ? 1 : -1;
2132 if (!!old_logging == !!mr->vga_logging_count) {
2133 return;
2136 memory_region_transaction_begin();
2137 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
2138 memory_region_update_pending |= mr->enabled;
2139 memory_region_transaction_commit();
2142 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
2143 hwaddr size)
2145 assert(mr->ram_block);
2146 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
2147 size,
2148 memory_region_get_dirty_log_mask(mr));
2152 * If memory region `mr' is NULL, do global sync. Otherwise, sync
2153 * dirty bitmap for the specified memory region.
2155 static void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
2157 MemoryListener *listener;
2158 AddressSpace *as;
2159 FlatView *view;
2160 FlatRange *fr;
2162 /* If the same address space has multiple log_sync listeners, we
2163 * visit that address space's FlatView multiple times. But because
2164 * log_sync listeners are rare, it's still cheaper than walking each
2165 * address space once.
2167 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2168 if (listener->log_sync) {
2169 as = listener->address_space;
2170 view = address_space_get_flatview(as);
2171 FOR_EACH_FLAT_RANGE(fr, view) {
2172 if (fr->dirty_log_mask && (!mr || fr->mr == mr)) {
2173 MemoryRegionSection mrs = section_from_flat_range(fr, view);
2174 listener->log_sync(listener, &mrs);
2177 flatview_unref(view);
2178 trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 0);
2179 } else if (listener->log_sync_global) {
2181 * No matter whether MR is specified, what we can do here
2182 * is to do a global sync, because we are not capable to
2183 * sync in a finer granularity.
2185 listener->log_sync_global(listener);
2186 trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 1);
2191 void memory_region_clear_dirty_bitmap(MemoryRegion *mr, hwaddr start,
2192 hwaddr len)
2194 MemoryRegionSection mrs;
2195 MemoryListener *listener;
2196 AddressSpace *as;
2197 FlatView *view;
2198 FlatRange *fr;
2199 hwaddr sec_start, sec_end, sec_size;
2201 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2202 if (!listener->log_clear) {
2203 continue;
2205 as = listener->address_space;
2206 view = address_space_get_flatview(as);
2207 FOR_EACH_FLAT_RANGE(fr, view) {
2208 if (!fr->dirty_log_mask || fr->mr != mr) {
2210 * Clear dirty bitmap operation only applies to those
2211 * regions whose dirty logging is at least enabled
2213 continue;
2216 mrs = section_from_flat_range(fr, view);
2218 sec_start = MAX(mrs.offset_within_region, start);
2219 sec_end = mrs.offset_within_region + int128_get64(mrs.size);
2220 sec_end = MIN(sec_end, start + len);
2222 if (sec_start >= sec_end) {
2224 * If this memory region section has no intersection
2225 * with the requested range, skip.
2227 continue;
2230 /* Valid case; shrink the section if needed */
2231 mrs.offset_within_address_space +=
2232 sec_start - mrs.offset_within_region;
2233 mrs.offset_within_region = sec_start;
2234 sec_size = sec_end - sec_start;
2235 mrs.size = int128_make64(sec_size);
2236 listener->log_clear(listener, &mrs);
2238 flatview_unref(view);
2242 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
2243 hwaddr addr,
2244 hwaddr size,
2245 unsigned client)
2247 DirtyBitmapSnapshot *snapshot;
2248 assert(mr->ram_block);
2249 memory_region_sync_dirty_bitmap(mr);
2250 snapshot = cpu_physical_memory_snapshot_and_clear_dirty(mr, addr, size, client);
2251 memory_global_after_dirty_log_sync();
2252 return snapshot;
2255 bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
2256 hwaddr addr, hwaddr size)
2258 assert(mr->ram_block);
2259 return cpu_physical_memory_snapshot_get_dirty(snap,
2260 memory_region_get_ram_addr(mr) + addr, size);
2263 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
2265 if (mr->readonly != readonly) {
2266 memory_region_transaction_begin();
2267 mr->readonly = readonly;
2268 memory_region_update_pending |= mr->enabled;
2269 memory_region_transaction_commit();
2273 void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile)
2275 if (mr->nonvolatile != nonvolatile) {
2276 memory_region_transaction_begin();
2277 mr->nonvolatile = nonvolatile;
2278 memory_region_update_pending |= mr->enabled;
2279 memory_region_transaction_commit();
2283 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
2285 if (mr->romd_mode != romd_mode) {
2286 memory_region_transaction_begin();
2287 mr->romd_mode = romd_mode;
2288 memory_region_update_pending |= mr->enabled;
2289 memory_region_transaction_commit();
2293 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
2294 hwaddr size, unsigned client)
2296 assert(mr->ram_block);
2297 cpu_physical_memory_test_and_clear_dirty(
2298 memory_region_get_ram_addr(mr) + addr, size, client);
2301 int memory_region_get_fd(MemoryRegion *mr)
2303 int fd;
2305 RCU_READ_LOCK_GUARD();
2306 while (mr->alias) {
2307 mr = mr->alias;
2309 fd = mr->ram_block->fd;
2311 return fd;
2314 void *memory_region_get_ram_ptr(MemoryRegion *mr)
2316 void *ptr;
2317 uint64_t offset = 0;
2319 RCU_READ_LOCK_GUARD();
2320 while (mr->alias) {
2321 offset += mr->alias_offset;
2322 mr = mr->alias;
2324 assert(mr->ram_block);
2325 ptr = qemu_map_ram_ptr(mr->ram_block, offset);
2327 return ptr;
2330 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
2332 RAMBlock *block;
2334 block = qemu_ram_block_from_host(ptr, false, offset);
2335 if (!block) {
2336 return NULL;
2339 return block->mr;
2342 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
2344 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
2347 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
2349 assert(mr->ram_block);
2351 qemu_ram_resize(mr->ram_block, newsize, errp);
2354 void memory_region_msync(MemoryRegion *mr, hwaddr addr, hwaddr size)
2356 if (mr->ram_block) {
2357 qemu_ram_msync(mr->ram_block, addr, size);
2361 void memory_region_writeback(MemoryRegion *mr, hwaddr addr, hwaddr size)
2364 * Might be extended case needed to cover
2365 * different types of memory regions
2367 if (mr->dirty_log_mask) {
2368 memory_region_msync(mr, addr, size);
2373 * Call proper memory listeners about the change on the newly
2374 * added/removed CoalescedMemoryRange.
2376 static void memory_region_update_coalesced_range(MemoryRegion *mr,
2377 CoalescedMemoryRange *cmr,
2378 bool add)
2380 AddressSpace *as;
2381 FlatView *view;
2382 FlatRange *fr;
2384 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2385 view = address_space_get_flatview(as);
2386 FOR_EACH_FLAT_RANGE(fr, view) {
2387 if (fr->mr == mr) {
2388 flat_range_coalesced_io_notify(fr, as, cmr, add);
2391 flatview_unref(view);
2395 void memory_region_set_coalescing(MemoryRegion *mr)
2397 memory_region_clear_coalescing(mr);
2398 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
2401 void memory_region_add_coalescing(MemoryRegion *mr,
2402 hwaddr offset,
2403 uint64_t size)
2405 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
2407 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
2408 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
2409 memory_region_update_coalesced_range(mr, cmr, true);
2410 memory_region_set_flush_coalesced(mr);
2413 void memory_region_clear_coalescing(MemoryRegion *mr)
2415 CoalescedMemoryRange *cmr;
2417 if (QTAILQ_EMPTY(&mr->coalesced)) {
2418 return;
2421 qemu_flush_coalesced_mmio_buffer();
2422 mr->flush_coalesced_mmio = false;
2424 while (!QTAILQ_EMPTY(&mr->coalesced)) {
2425 cmr = QTAILQ_FIRST(&mr->coalesced);
2426 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
2427 memory_region_update_coalesced_range(mr, cmr, false);
2428 g_free(cmr);
2432 void memory_region_set_flush_coalesced(MemoryRegion *mr)
2434 mr->flush_coalesced_mmio = true;
2437 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
2439 qemu_flush_coalesced_mmio_buffer();
2440 if (QTAILQ_EMPTY(&mr->coalesced)) {
2441 mr->flush_coalesced_mmio = false;
2445 static bool userspace_eventfd_warning;
2447 void memory_region_add_eventfd(MemoryRegion *mr,
2448 hwaddr addr,
2449 unsigned size,
2450 bool match_data,
2451 uint64_t data,
2452 EventNotifier *e)
2454 MemoryRegionIoeventfd mrfd = {
2455 .addr.start = int128_make64(addr),
2456 .addr.size = int128_make64(size),
2457 .match_data = match_data,
2458 .data = data,
2459 .e = e,
2461 unsigned i;
2463 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
2464 userspace_eventfd_warning))) {
2465 userspace_eventfd_warning = true;
2466 error_report("Using eventfd without MMIO binding in KVM. "
2467 "Suboptimal performance expected");
2470 if (size) {
2471 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2473 memory_region_transaction_begin();
2474 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2475 if (memory_region_ioeventfd_before(&mrfd, &mr->ioeventfds[i])) {
2476 break;
2479 ++mr->ioeventfd_nb;
2480 mr->ioeventfds = g_realloc(mr->ioeventfds,
2481 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2482 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2483 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2484 mr->ioeventfds[i] = mrfd;
2485 ioeventfd_update_pending |= mr->enabled;
2486 memory_region_transaction_commit();
2489 void memory_region_del_eventfd(MemoryRegion *mr,
2490 hwaddr addr,
2491 unsigned size,
2492 bool match_data,
2493 uint64_t data,
2494 EventNotifier *e)
2496 MemoryRegionIoeventfd mrfd = {
2497 .addr.start = int128_make64(addr),
2498 .addr.size = int128_make64(size),
2499 .match_data = match_data,
2500 .data = data,
2501 .e = e,
2503 unsigned i;
2505 if (size) {
2506 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2508 memory_region_transaction_begin();
2509 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2510 if (memory_region_ioeventfd_equal(&mrfd, &mr->ioeventfds[i])) {
2511 break;
2514 assert(i != mr->ioeventfd_nb);
2515 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2516 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2517 --mr->ioeventfd_nb;
2518 mr->ioeventfds = g_realloc(mr->ioeventfds,
2519 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
2520 ioeventfd_update_pending |= mr->enabled;
2521 memory_region_transaction_commit();
2524 static void memory_region_update_container_subregions(MemoryRegion *subregion)
2526 MemoryRegion *mr = subregion->container;
2527 MemoryRegion *other;
2529 memory_region_transaction_begin();
2531 memory_region_ref(subregion);
2532 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2533 if (subregion->priority >= other->priority) {
2534 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2535 goto done;
2538 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2539 done:
2540 memory_region_update_pending |= mr->enabled && subregion->enabled;
2541 memory_region_transaction_commit();
2544 static void memory_region_add_subregion_common(MemoryRegion *mr,
2545 hwaddr offset,
2546 MemoryRegion *subregion)
2548 MemoryRegion *alias;
2550 assert(!subregion->container);
2551 subregion->container = mr;
2552 for (alias = subregion->alias; alias; alias = alias->alias) {
2553 alias->mapped_via_alias++;
2555 subregion->addr = offset;
2556 memory_region_update_container_subregions(subregion);
2559 void memory_region_add_subregion(MemoryRegion *mr,
2560 hwaddr offset,
2561 MemoryRegion *subregion)
2563 subregion->priority = 0;
2564 memory_region_add_subregion_common(mr, offset, subregion);
2567 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2568 hwaddr offset,
2569 MemoryRegion *subregion,
2570 int priority)
2572 subregion->priority = priority;
2573 memory_region_add_subregion_common(mr, offset, subregion);
2576 void memory_region_del_subregion(MemoryRegion *mr,
2577 MemoryRegion *subregion)
2579 MemoryRegion *alias;
2581 memory_region_transaction_begin();
2582 assert(subregion->container == mr);
2583 subregion->container = NULL;
2584 for (alias = subregion->alias; alias; alias = alias->alias) {
2585 alias->mapped_via_alias--;
2586 assert(alias->mapped_via_alias >= 0);
2588 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
2589 memory_region_unref(subregion);
2590 memory_region_update_pending |= mr->enabled && subregion->enabled;
2591 memory_region_transaction_commit();
2594 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2596 if (enabled == mr->enabled) {
2597 return;
2599 memory_region_transaction_begin();
2600 mr->enabled = enabled;
2601 memory_region_update_pending = true;
2602 memory_region_transaction_commit();
2605 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2607 Int128 s = int128_make64(size);
2609 if (size == UINT64_MAX) {
2610 s = int128_2_64();
2612 if (int128_eq(s, mr->size)) {
2613 return;
2615 memory_region_transaction_begin();
2616 mr->size = s;
2617 memory_region_update_pending = true;
2618 memory_region_transaction_commit();
2621 static void memory_region_readd_subregion(MemoryRegion *mr)
2623 MemoryRegion *container = mr->container;
2625 if (container) {
2626 memory_region_transaction_begin();
2627 memory_region_ref(mr);
2628 memory_region_del_subregion(container, mr);
2629 mr->container = container;
2630 memory_region_update_container_subregions(mr);
2631 memory_region_unref(mr);
2632 memory_region_transaction_commit();
2636 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2638 if (addr != mr->addr) {
2639 mr->addr = addr;
2640 memory_region_readd_subregion(mr);
2644 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
2646 assert(mr->alias);
2648 if (offset == mr->alias_offset) {
2649 return;
2652 memory_region_transaction_begin();
2653 mr->alias_offset = offset;
2654 memory_region_update_pending |= mr->enabled;
2655 memory_region_transaction_commit();
2658 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2660 return mr->align;
2663 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2665 const AddrRange *addr = addr_;
2666 const FlatRange *fr = fr_;
2668 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2669 return -1;
2670 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2671 return 1;
2673 return 0;
2676 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
2678 return bsearch(&addr, view->ranges, view->nr,
2679 sizeof(FlatRange), cmp_flatrange_addr);
2682 bool memory_region_is_mapped(MemoryRegion *mr)
2684 return !!mr->container || mr->mapped_via_alias;
2687 /* Same as memory_region_find, but it does not add a reference to the
2688 * returned region. It must be called from an RCU critical section.
2690 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2691 hwaddr addr, uint64_t size)
2693 MemoryRegionSection ret = { .mr = NULL };
2694 MemoryRegion *root;
2695 AddressSpace *as;
2696 AddrRange range;
2697 FlatView *view;
2698 FlatRange *fr;
2700 addr += mr->addr;
2701 for (root = mr; root->container; ) {
2702 root = root->container;
2703 addr += root->addr;
2706 as = memory_region_to_address_space(root);
2707 if (!as) {
2708 return ret;
2710 range = addrrange_make(int128_make64(addr), int128_make64(size));
2712 view = address_space_to_flatview(as);
2713 fr = flatview_lookup(view, range);
2714 if (!fr) {
2715 return ret;
2718 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2719 --fr;
2722 ret.mr = fr->mr;
2723 ret.fv = view;
2724 range = addrrange_intersection(range, fr->addr);
2725 ret.offset_within_region = fr->offset_in_region;
2726 ret.offset_within_region += int128_get64(int128_sub(range.start,
2727 fr->addr.start));
2728 ret.size = range.size;
2729 ret.offset_within_address_space = int128_get64(range.start);
2730 ret.readonly = fr->readonly;
2731 ret.nonvolatile = fr->nonvolatile;
2732 return ret;
2735 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2736 hwaddr addr, uint64_t size)
2738 MemoryRegionSection ret;
2739 RCU_READ_LOCK_GUARD();
2740 ret = memory_region_find_rcu(mr, addr, size);
2741 if (ret.mr) {
2742 memory_region_ref(ret.mr);
2744 return ret;
2747 MemoryRegionSection *memory_region_section_new_copy(MemoryRegionSection *s)
2749 MemoryRegionSection *tmp = g_new(MemoryRegionSection, 1);
2751 *tmp = *s;
2752 if (tmp->mr) {
2753 memory_region_ref(tmp->mr);
2755 if (tmp->fv) {
2756 bool ret = flatview_ref(tmp->fv);
2758 g_assert(ret);
2760 return tmp;
2763 void memory_region_section_free_copy(MemoryRegionSection *s)
2765 if (s->fv) {
2766 flatview_unref(s->fv);
2768 if (s->mr) {
2769 memory_region_unref(s->mr);
2771 g_free(s);
2774 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2776 MemoryRegion *mr;
2778 RCU_READ_LOCK_GUARD();
2779 mr = memory_region_find_rcu(container, addr, 1).mr;
2780 return mr && mr != container;
2783 void memory_global_dirty_log_sync(void)
2785 memory_region_sync_dirty_bitmap(NULL);
2788 void memory_global_after_dirty_log_sync(void)
2790 MEMORY_LISTENER_CALL_GLOBAL(log_global_after_sync, Forward);
2793 static VMChangeStateEntry *vmstate_change;
2795 void memory_global_dirty_log_start(unsigned int flags)
2797 unsigned int old_flags = global_dirty_tracking;
2799 if (vmstate_change) {
2800 qemu_del_vm_change_state_handler(vmstate_change);
2801 vmstate_change = NULL;
2804 assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2805 assert(!(global_dirty_tracking & flags));
2806 global_dirty_tracking |= flags;
2807 trace_global_dirty_changed(global_dirty_tracking);
2809 if (!old_flags) {
2810 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2811 memory_region_transaction_begin();
2812 memory_region_update_pending = true;
2813 memory_region_transaction_commit();
2817 static void memory_global_dirty_log_do_stop(unsigned int flags)
2819 assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2820 assert((global_dirty_tracking & flags) == flags);
2821 global_dirty_tracking &= ~flags;
2823 trace_global_dirty_changed(global_dirty_tracking);
2825 if (!global_dirty_tracking) {
2826 memory_region_transaction_begin();
2827 memory_region_update_pending = true;
2828 memory_region_transaction_commit();
2829 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2833 static void memory_vm_change_state_handler(void *opaque, bool running,
2834 RunState state)
2836 unsigned int flags = (unsigned int)(uintptr_t)opaque;
2837 if (running) {
2838 memory_global_dirty_log_do_stop(flags);
2840 if (vmstate_change) {
2841 qemu_del_vm_change_state_handler(vmstate_change);
2842 vmstate_change = NULL;
2847 void memory_global_dirty_log_stop(unsigned int flags)
2849 if (!runstate_is_running()) {
2850 if (vmstate_change) {
2851 return;
2853 vmstate_change = qemu_add_vm_change_state_handler(
2854 memory_vm_change_state_handler,
2855 (void *)(uintptr_t)flags);
2856 return;
2859 memory_global_dirty_log_do_stop(flags);
2862 static void listener_add_address_space(MemoryListener *listener,
2863 AddressSpace *as)
2865 FlatView *view;
2866 FlatRange *fr;
2868 if (listener->begin) {
2869 listener->begin(listener);
2871 if (global_dirty_tracking) {
2872 if (listener->log_global_start) {
2873 listener->log_global_start(listener);
2877 view = address_space_get_flatview(as);
2878 FOR_EACH_FLAT_RANGE(fr, view) {
2879 MemoryRegionSection section = section_from_flat_range(fr, view);
2881 if (listener->region_add) {
2882 listener->region_add(listener, &section);
2884 if (fr->dirty_log_mask && listener->log_start) {
2885 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2888 if (listener->commit) {
2889 listener->commit(listener);
2891 flatview_unref(view);
2894 static void listener_del_address_space(MemoryListener *listener,
2895 AddressSpace *as)
2897 FlatView *view;
2898 FlatRange *fr;
2900 if (listener->begin) {
2901 listener->begin(listener);
2903 view = address_space_get_flatview(as);
2904 FOR_EACH_FLAT_RANGE(fr, view) {
2905 MemoryRegionSection section = section_from_flat_range(fr, view);
2907 if (fr->dirty_log_mask && listener->log_stop) {
2908 listener->log_stop(listener, &section, fr->dirty_log_mask, 0);
2910 if (listener->region_del) {
2911 listener->region_del(listener, &section);
2914 if (listener->commit) {
2915 listener->commit(listener);
2917 flatview_unref(view);
2920 void memory_listener_register(MemoryListener *listener, AddressSpace *as)
2922 MemoryListener *other = NULL;
2924 /* Only one of them can be defined for a listener */
2925 assert(!(listener->log_sync && listener->log_sync_global));
2927 listener->address_space = as;
2928 if (QTAILQ_EMPTY(&memory_listeners)
2929 || listener->priority >= QTAILQ_LAST(&memory_listeners)->priority) {
2930 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2931 } else {
2932 QTAILQ_FOREACH(other, &memory_listeners, link) {
2933 if (listener->priority < other->priority) {
2934 break;
2937 QTAILQ_INSERT_BEFORE(other, listener, link);
2940 if (QTAILQ_EMPTY(&as->listeners)
2941 || listener->priority >= QTAILQ_LAST(&as->listeners)->priority) {
2942 QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
2943 } else {
2944 QTAILQ_FOREACH(other, &as->listeners, link_as) {
2945 if (listener->priority < other->priority) {
2946 break;
2949 QTAILQ_INSERT_BEFORE(other, listener, link_as);
2952 listener_add_address_space(listener, as);
2955 void memory_listener_unregister(MemoryListener *listener)
2957 if (!listener->address_space) {
2958 return;
2961 listener_del_address_space(listener, listener->address_space);
2962 QTAILQ_REMOVE(&memory_listeners, listener, link);
2963 QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
2964 listener->address_space = NULL;
2967 void address_space_remove_listeners(AddressSpace *as)
2969 while (!QTAILQ_EMPTY(&as->listeners)) {
2970 memory_listener_unregister(QTAILQ_FIRST(&as->listeners));
2974 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2976 memory_region_ref(root);
2977 as->root = root;
2978 as->current_map = NULL;
2979 as->ioeventfd_nb = 0;
2980 as->ioeventfds = NULL;
2981 QTAILQ_INIT(&as->listeners);
2982 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2983 as->name = g_strdup(name ? name : "anonymous");
2984 address_space_update_topology(as);
2985 address_space_update_ioeventfds(as);
2988 static void do_address_space_destroy(AddressSpace *as)
2990 assert(QTAILQ_EMPTY(&as->listeners));
2992 flatview_unref(as->current_map);
2993 g_free(as->name);
2994 g_free(as->ioeventfds);
2995 memory_region_unref(as->root);
2998 void address_space_destroy(AddressSpace *as)
3000 MemoryRegion *root = as->root;
3002 /* Flush out anything from MemoryListeners listening in on this */
3003 memory_region_transaction_begin();
3004 as->root = NULL;
3005 memory_region_transaction_commit();
3006 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
3008 /* At this point, as->dispatch and as->current_map are dummy
3009 * entries that the guest should never use. Wait for the old
3010 * values to expire before freeing the data.
3012 as->root = root;
3013 call_rcu(as, do_address_space_destroy, rcu);
3016 static const char *memory_region_type(MemoryRegion *mr)
3018 if (mr->alias) {
3019 return memory_region_type(mr->alias);
3021 if (memory_region_is_ram_device(mr)) {
3022 return "ramd";
3023 } else if (memory_region_is_romd(mr)) {
3024 return "romd";
3025 } else if (memory_region_is_rom(mr)) {
3026 return "rom";
3027 } else if (memory_region_is_ram(mr)) {
3028 return "ram";
3029 } else {
3030 return "i/o";
3034 typedef struct MemoryRegionList MemoryRegionList;
3036 struct MemoryRegionList {
3037 const MemoryRegion *mr;
3038 QTAILQ_ENTRY(MemoryRegionList) mrqueue;
3041 typedef QTAILQ_HEAD(, MemoryRegionList) MemoryRegionListHead;
3043 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3044 int128_sub((size), int128_one())) : 0)
3045 #define MTREE_INDENT " "
3047 static void mtree_expand_owner(const char *label, Object *obj)
3049 DeviceState *dev = (DeviceState *) object_dynamic_cast(obj, TYPE_DEVICE);
3051 qemu_printf(" %s:{%s", label, dev ? "dev" : "obj");
3052 if (dev && dev->id) {
3053 qemu_printf(" id=%s", dev->id);
3054 } else {
3055 char *canonical_path = object_get_canonical_path(obj);
3056 if (canonical_path) {
3057 qemu_printf(" path=%s", canonical_path);
3058 g_free(canonical_path);
3059 } else {
3060 qemu_printf(" type=%s", object_get_typename(obj));
3063 qemu_printf("}");
3066 static void mtree_print_mr_owner(const MemoryRegion *mr)
3068 Object *owner = mr->owner;
3069 Object *parent = memory_region_owner((MemoryRegion *)mr);
3071 if (!owner && !parent) {
3072 qemu_printf(" orphan");
3073 return;
3075 if (owner) {
3076 mtree_expand_owner("owner", owner);
3078 if (parent && parent != owner) {
3079 mtree_expand_owner("parent", parent);
3083 static void mtree_print_mr(const MemoryRegion *mr, unsigned int level,
3084 hwaddr base,
3085 MemoryRegionListHead *alias_print_queue,
3086 bool owner, bool display_disabled)
3088 MemoryRegionList *new_ml, *ml, *next_ml;
3089 MemoryRegionListHead submr_print_queue;
3090 const MemoryRegion *submr;
3091 unsigned int i;
3092 hwaddr cur_start, cur_end;
3094 if (!mr) {
3095 return;
3098 cur_start = base + mr->addr;
3099 cur_end = cur_start + MR_SIZE(mr->size);
3102 * Try to detect overflow of memory region. This should never
3103 * happen normally. When it happens, we dump something to warn the
3104 * user who is observing this.
3106 if (cur_start < base || cur_end < cur_start) {
3107 qemu_printf("[DETECTED OVERFLOW!] ");
3110 if (mr->alias) {
3111 MemoryRegionList *ml;
3112 bool found = false;
3114 /* check if the alias is already in the queue */
3115 QTAILQ_FOREACH(ml, alias_print_queue, mrqueue) {
3116 if (ml->mr == mr->alias) {
3117 found = true;
3121 if (!found) {
3122 ml = g_new(MemoryRegionList, 1);
3123 ml->mr = mr->alias;
3124 QTAILQ_INSERT_TAIL(alias_print_queue, ml, mrqueue);
3126 if (mr->enabled || display_disabled) {
3127 for (i = 0; i < level; i++) {
3128 qemu_printf(MTREE_INDENT);
3130 qemu_printf(TARGET_FMT_plx "-" TARGET_FMT_plx
3131 " (prio %d, %s%s): alias %s @%s " TARGET_FMT_plx
3132 "-" TARGET_FMT_plx "%s",
3133 cur_start, cur_end,
3134 mr->priority,
3135 mr->nonvolatile ? "nv-" : "",
3136 memory_region_type((MemoryRegion *)mr),
3137 memory_region_name(mr),
3138 memory_region_name(mr->alias),
3139 mr->alias_offset,
3140 mr->alias_offset + MR_SIZE(mr->size),
3141 mr->enabled ? "" : " [disabled]");
3142 if (owner) {
3143 mtree_print_mr_owner(mr);
3145 qemu_printf("\n");
3147 } else {
3148 if (mr->enabled || display_disabled) {
3149 for (i = 0; i < level; i++) {
3150 qemu_printf(MTREE_INDENT);
3152 qemu_printf(TARGET_FMT_plx "-" TARGET_FMT_plx
3153 " (prio %d, %s%s): %s%s",
3154 cur_start, cur_end,
3155 mr->priority,
3156 mr->nonvolatile ? "nv-" : "",
3157 memory_region_type((MemoryRegion *)mr),
3158 memory_region_name(mr),
3159 mr->enabled ? "" : " [disabled]");
3160 if (owner) {
3161 mtree_print_mr_owner(mr);
3163 qemu_printf("\n");
3167 QTAILQ_INIT(&submr_print_queue);
3169 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
3170 new_ml = g_new(MemoryRegionList, 1);
3171 new_ml->mr = submr;
3172 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3173 if (new_ml->mr->addr < ml->mr->addr ||
3174 (new_ml->mr->addr == ml->mr->addr &&
3175 new_ml->mr->priority > ml->mr->priority)) {
3176 QTAILQ_INSERT_BEFORE(ml, new_ml, mrqueue);
3177 new_ml = NULL;
3178 break;
3181 if (new_ml) {
3182 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, mrqueue);
3186 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3187 mtree_print_mr(ml->mr, level + 1, cur_start,
3188 alias_print_queue, owner, display_disabled);
3191 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, mrqueue, next_ml) {
3192 g_free(ml);
3196 struct FlatViewInfo {
3197 int counter;
3198 bool dispatch_tree;
3199 bool owner;
3200 AccelClass *ac;
3203 static void mtree_print_flatview(gpointer key, gpointer value,
3204 gpointer user_data)
3206 FlatView *view = key;
3207 GArray *fv_address_spaces = value;
3208 struct FlatViewInfo *fvi = user_data;
3209 FlatRange *range = &view->ranges[0];
3210 MemoryRegion *mr;
3211 int n = view->nr;
3212 int i;
3213 AddressSpace *as;
3215 qemu_printf("FlatView #%d\n", fvi->counter);
3216 ++fvi->counter;
3218 for (i = 0; i < fv_address_spaces->len; ++i) {
3219 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3220 qemu_printf(" AS \"%s\", root: %s",
3221 as->name, memory_region_name(as->root));
3222 if (as->root->alias) {
3223 qemu_printf(", alias %s", memory_region_name(as->root->alias));
3225 qemu_printf("\n");
3228 qemu_printf(" Root memory region: %s\n",
3229 view->root ? memory_region_name(view->root) : "(none)");
3231 if (n <= 0) {
3232 qemu_printf(MTREE_INDENT "No rendered FlatView\n\n");
3233 return;
3236 while (n--) {
3237 mr = range->mr;
3238 if (range->offset_in_region) {
3239 qemu_printf(MTREE_INDENT TARGET_FMT_plx "-" TARGET_FMT_plx
3240 " (prio %d, %s%s): %s @" TARGET_FMT_plx,
3241 int128_get64(range->addr.start),
3242 int128_get64(range->addr.start)
3243 + MR_SIZE(range->addr.size),
3244 mr->priority,
3245 range->nonvolatile ? "nv-" : "",
3246 range->readonly ? "rom" : memory_region_type(mr),
3247 memory_region_name(mr),
3248 range->offset_in_region);
3249 } else {
3250 qemu_printf(MTREE_INDENT TARGET_FMT_plx "-" TARGET_FMT_plx
3251 " (prio %d, %s%s): %s",
3252 int128_get64(range->addr.start),
3253 int128_get64(range->addr.start)
3254 + MR_SIZE(range->addr.size),
3255 mr->priority,
3256 range->nonvolatile ? "nv-" : "",
3257 range->readonly ? "rom" : memory_region_type(mr),
3258 memory_region_name(mr));
3260 if (fvi->owner) {
3261 mtree_print_mr_owner(mr);
3264 if (fvi->ac) {
3265 for (i = 0; i < fv_address_spaces->len; ++i) {
3266 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3267 if (fvi->ac->has_memory(current_machine, as,
3268 int128_get64(range->addr.start),
3269 MR_SIZE(range->addr.size) + 1)) {
3270 qemu_printf(" %s", fvi->ac->name);
3274 qemu_printf("\n");
3275 range++;
3278 #if !defined(CONFIG_USER_ONLY)
3279 if (fvi->dispatch_tree && view->root) {
3280 mtree_print_dispatch(view->dispatch, view->root);
3282 #endif
3284 qemu_printf("\n");
3287 static gboolean mtree_info_flatview_free(gpointer key, gpointer value,
3288 gpointer user_data)
3290 FlatView *view = key;
3291 GArray *fv_address_spaces = value;
3293 g_array_unref(fv_address_spaces);
3294 flatview_unref(view);
3296 return true;
3299 static void mtree_info_flatview(bool dispatch_tree, bool owner)
3301 struct FlatViewInfo fvi = {
3302 .counter = 0,
3303 .dispatch_tree = dispatch_tree,
3304 .owner = owner,
3306 AddressSpace *as;
3307 FlatView *view;
3308 GArray *fv_address_spaces;
3309 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3310 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
3312 if (ac->has_memory) {
3313 fvi.ac = ac;
3316 /* Gather all FVs in one table */
3317 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3318 view = address_space_get_flatview(as);
3320 fv_address_spaces = g_hash_table_lookup(views, view);
3321 if (!fv_address_spaces) {
3322 fv_address_spaces = g_array_new(false, false, sizeof(as));
3323 g_hash_table_insert(views, view, fv_address_spaces);
3326 g_array_append_val(fv_address_spaces, as);
3329 /* Print */
3330 g_hash_table_foreach(views, mtree_print_flatview, &fvi);
3332 /* Free */
3333 g_hash_table_foreach_remove(views, mtree_info_flatview_free, 0);
3334 g_hash_table_unref(views);
3337 struct AddressSpaceInfo {
3338 MemoryRegionListHead *ml_head;
3339 bool owner;
3340 bool disabled;
3343 /* Returns negative value if a < b; zero if a = b; positive value if a > b. */
3344 static gint address_space_compare_name(gconstpointer a, gconstpointer b)
3346 const AddressSpace *as_a = a;
3347 const AddressSpace *as_b = b;
3349 return g_strcmp0(as_a->name, as_b->name);
3352 static void mtree_print_as_name(gpointer data, gpointer user_data)
3354 AddressSpace *as = data;
3356 qemu_printf("address-space: %s\n", as->name);
3359 static void mtree_print_as(gpointer key, gpointer value, gpointer user_data)
3361 MemoryRegion *mr = key;
3362 GSList *as_same_root_mr_list = value;
3363 struct AddressSpaceInfo *asi = user_data;
3365 g_slist_foreach(as_same_root_mr_list, mtree_print_as_name, NULL);
3366 mtree_print_mr(mr, 1, 0, asi->ml_head, asi->owner, asi->disabled);
3367 qemu_printf("\n");
3370 static gboolean mtree_info_as_free(gpointer key, gpointer value,
3371 gpointer user_data)
3373 GSList *as_same_root_mr_list = value;
3375 g_slist_free(as_same_root_mr_list);
3377 return true;
3380 static void mtree_info_as(bool dispatch_tree, bool owner, bool disabled)
3382 MemoryRegionListHead ml_head;
3383 MemoryRegionList *ml, *ml2;
3384 AddressSpace *as;
3385 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3386 GSList *as_same_root_mr_list;
3387 struct AddressSpaceInfo asi = {
3388 .ml_head = &ml_head,
3389 .owner = owner,
3390 .disabled = disabled,
3393 QTAILQ_INIT(&ml_head);
3395 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3396 /* Create hashtable, key=AS root MR, value = list of AS */
3397 as_same_root_mr_list = g_hash_table_lookup(views, as->root);
3398 as_same_root_mr_list = g_slist_insert_sorted(as_same_root_mr_list, as,
3399 address_space_compare_name);
3400 g_hash_table_insert(views, as->root, as_same_root_mr_list);
3403 /* print address spaces */
3404 g_hash_table_foreach(views, mtree_print_as, &asi);
3405 g_hash_table_foreach_remove(views, mtree_info_as_free, 0);
3406 g_hash_table_unref(views);
3408 /* print aliased regions */
3409 QTAILQ_FOREACH(ml, &ml_head, mrqueue) {
3410 qemu_printf("memory-region: %s\n", memory_region_name(ml->mr));
3411 mtree_print_mr(ml->mr, 1, 0, &ml_head, owner, disabled);
3412 qemu_printf("\n");
3415 QTAILQ_FOREACH_SAFE(ml, &ml_head, mrqueue, ml2) {
3416 g_free(ml);
3420 void mtree_info(bool flatview, bool dispatch_tree, bool owner, bool disabled)
3422 if (flatview) {
3423 mtree_info_flatview(dispatch_tree, owner);
3424 } else {
3425 mtree_info_as(dispatch_tree, owner, disabled);
3429 void memory_region_init_ram(MemoryRegion *mr,
3430 Object *owner,
3431 const char *name,
3432 uint64_t size,
3433 Error **errp)
3435 DeviceState *owner_dev;
3436 Error *err = NULL;
3438 memory_region_init_ram_nomigrate(mr, owner, name, size, &err);
3439 if (err) {
3440 error_propagate(errp, err);
3441 return;
3443 /* This will assert if owner is neither NULL nor a DeviceState.
3444 * We only want the owner here for the purposes of defining a
3445 * unique name for migration. TODO: Ideally we should implement
3446 * a naming scheme for Objects which are not DeviceStates, in
3447 * which case we can relax this restriction.
3449 owner_dev = DEVICE(owner);
3450 vmstate_register_ram(mr, owner_dev);
3453 void memory_region_init_rom(MemoryRegion *mr,
3454 Object *owner,
3455 const char *name,
3456 uint64_t size,
3457 Error **errp)
3459 DeviceState *owner_dev;
3460 Error *err = NULL;
3462 memory_region_init_rom_nomigrate(mr, owner, name, size, &err);
3463 if (err) {
3464 error_propagate(errp, err);
3465 return;
3467 /* This will assert if owner is neither NULL nor a DeviceState.
3468 * We only want the owner here for the purposes of defining a
3469 * unique name for migration. TODO: Ideally we should implement
3470 * a naming scheme for Objects which are not DeviceStates, in
3471 * which case we can relax this restriction.
3473 owner_dev = DEVICE(owner);
3474 vmstate_register_ram(mr, owner_dev);
3477 void memory_region_init_rom_device(MemoryRegion *mr,
3478 Object *owner,
3479 const MemoryRegionOps *ops,
3480 void *opaque,
3481 const char *name,
3482 uint64_t size,
3483 Error **errp)
3485 DeviceState *owner_dev;
3486 Error *err = NULL;
3488 memory_region_init_rom_device_nomigrate(mr, owner, ops, opaque,
3489 name, size, &err);
3490 if (err) {
3491 error_propagate(errp, err);
3492 return;
3494 /* This will assert if owner is neither NULL nor a DeviceState.
3495 * We only want the owner here for the purposes of defining a
3496 * unique name for migration. TODO: Ideally we should implement
3497 * a naming scheme for Objects which are not DeviceStates, in
3498 * which case we can relax this restriction.
3500 owner_dev = DEVICE(owner);
3501 vmstate_register_ram(mr, owner_dev);
3505 * Support softmmu builds with CONFIG_FUZZ using a weak symbol and a stub for
3506 * the fuzz_dma_read_cb callback
3508 #ifdef CONFIG_FUZZ
3509 void __attribute__((weak)) fuzz_dma_read_cb(size_t addr,
3510 size_t len,
3511 MemoryRegion *mr)
3514 #endif
3516 static const TypeInfo memory_region_info = {
3517 .parent = TYPE_OBJECT,
3518 .name = TYPE_MEMORY_REGION,
3519 .class_size = sizeof(MemoryRegionClass),
3520 .instance_size = sizeof(MemoryRegion),
3521 .instance_init = memory_region_initfn,
3522 .instance_finalize = memory_region_finalize,
3525 static const TypeInfo iommu_memory_region_info = {
3526 .parent = TYPE_MEMORY_REGION,
3527 .name = TYPE_IOMMU_MEMORY_REGION,
3528 .class_size = sizeof(IOMMUMemoryRegionClass),
3529 .instance_size = sizeof(IOMMUMemoryRegion),
3530 .instance_init = iommu_memory_region_initfn,
3531 .abstract = true,
3534 static const TypeInfo ram_discard_manager_info = {
3535 .parent = TYPE_INTERFACE,
3536 .name = TYPE_RAM_DISCARD_MANAGER,
3537 .class_size = sizeof(RamDiscardManagerClass),
3540 static void memory_register_types(void)
3542 type_register_static(&memory_region_info);
3543 type_register_static(&iommu_memory_region_info);
3544 type_register_static(&ram_discard_manager_info);
3547 type_init(memory_register_types)