target/arm: Reorg do_coproc_insn
[qemu/armbru.git] / softmmu / memory.c
blob9d64efca269b2f7b7ee310cd88d789f41aab0383
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"
36 #include "exec/address-spaces.h"
38 //#define DEBUG_UNASSIGNED
40 static unsigned memory_region_transaction_depth;
41 static bool memory_region_update_pending;
42 static bool ioeventfd_update_pending;
43 unsigned int global_dirty_tracking;
45 static QTAILQ_HEAD(, MemoryListener) memory_listeners
46 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
48 static QTAILQ_HEAD(, AddressSpace) address_spaces
49 = QTAILQ_HEAD_INITIALIZER(address_spaces);
51 static GHashTable *flat_views;
53 typedef struct AddrRange AddrRange;
56 * Note that signed integers are needed for negative offsetting in aliases
57 * (large MemoryRegion::alias_offset).
59 struct AddrRange {
60 Int128 start;
61 Int128 size;
64 static AddrRange addrrange_make(Int128 start, Int128 size)
66 return (AddrRange) { start, size };
69 static bool addrrange_equal(AddrRange r1, AddrRange r2)
71 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
74 static Int128 addrrange_end(AddrRange r)
76 return int128_add(r.start, r.size);
79 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
81 int128_addto(&range.start, delta);
82 return range;
85 static bool addrrange_contains(AddrRange range, Int128 addr)
87 return int128_ge(addr, range.start)
88 && int128_lt(addr, addrrange_end(range));
91 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
93 return addrrange_contains(r1, r2.start)
94 || addrrange_contains(r2, r1.start);
97 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
99 Int128 start = int128_max(r1.start, r2.start);
100 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
101 return addrrange_make(start, int128_sub(end, start));
104 enum ListenerDirection { Forward, Reverse };
106 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
107 do { \
108 MemoryListener *_listener; \
110 switch (_direction) { \
111 case Forward: \
112 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
113 if (_listener->_callback) { \
114 _listener->_callback(_listener, ##_args); \
117 break; \
118 case Reverse: \
119 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, link) { \
120 if (_listener->_callback) { \
121 _listener->_callback(_listener, ##_args); \
124 break; \
125 default: \
126 abort(); \
128 } while (0)
130 #define MEMORY_LISTENER_CALL(_as, _callback, _direction, _section, _args...) \
131 do { \
132 MemoryListener *_listener; \
134 switch (_direction) { \
135 case Forward: \
136 QTAILQ_FOREACH(_listener, &(_as)->listeners, link_as) { \
137 if (_listener->_callback) { \
138 _listener->_callback(_listener, _section, ##_args); \
141 break; \
142 case Reverse: \
143 QTAILQ_FOREACH_REVERSE(_listener, &(_as)->listeners, link_as) { \
144 if (_listener->_callback) { \
145 _listener->_callback(_listener, _section, ##_args); \
148 break; \
149 default: \
150 abort(); \
152 } while (0)
154 /* No need to ref/unref .mr, the FlatRange keeps it alive. */
155 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...) \
156 do { \
157 MemoryRegionSection mrs = section_from_flat_range(fr, \
158 address_space_to_flatview(as)); \
159 MEMORY_LISTENER_CALL(as, callback, dir, &mrs, ##_args); \
160 } while(0)
162 struct CoalescedMemoryRange {
163 AddrRange addr;
164 QTAILQ_ENTRY(CoalescedMemoryRange) link;
167 struct MemoryRegionIoeventfd {
168 AddrRange addr;
169 bool match_data;
170 uint64_t data;
171 EventNotifier *e;
174 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd *a,
175 MemoryRegionIoeventfd *b)
177 if (int128_lt(a->addr.start, b->addr.start)) {
178 return true;
179 } else if (int128_gt(a->addr.start, b->addr.start)) {
180 return false;
181 } else if (int128_lt(a->addr.size, b->addr.size)) {
182 return true;
183 } else if (int128_gt(a->addr.size, b->addr.size)) {
184 return false;
185 } else if (a->match_data < b->match_data) {
186 return true;
187 } else if (a->match_data > b->match_data) {
188 return false;
189 } else if (a->match_data) {
190 if (a->data < b->data) {
191 return true;
192 } else if (a->data > b->data) {
193 return false;
196 if (a->e < b->e) {
197 return true;
198 } else if (a->e > b->e) {
199 return false;
201 return false;
204 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd *a,
205 MemoryRegionIoeventfd *b)
207 if (int128_eq(a->addr.start, b->addr.start) &&
208 (!int128_nz(a->addr.size) || !int128_nz(b->addr.size) ||
209 (int128_eq(a->addr.size, b->addr.size) &&
210 (a->match_data == b->match_data) &&
211 ((a->match_data && (a->data == b->data)) || !a->match_data) &&
212 (a->e == b->e))))
213 return true;
215 return false;
218 /* Range of memory in the global map. Addresses are absolute. */
219 struct FlatRange {
220 MemoryRegion *mr;
221 hwaddr offset_in_region;
222 AddrRange addr;
223 uint8_t dirty_log_mask;
224 bool romd_mode;
225 bool readonly;
226 bool nonvolatile;
229 #define FOR_EACH_FLAT_RANGE(var, view) \
230 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
232 static inline MemoryRegionSection
233 section_from_flat_range(FlatRange *fr, FlatView *fv)
235 return (MemoryRegionSection) {
236 .mr = fr->mr,
237 .fv = fv,
238 .offset_within_region = fr->offset_in_region,
239 .size = fr->addr.size,
240 .offset_within_address_space = int128_get64(fr->addr.start),
241 .readonly = fr->readonly,
242 .nonvolatile = fr->nonvolatile,
246 static bool flatrange_equal(FlatRange *a, FlatRange *b)
248 return a->mr == b->mr
249 && addrrange_equal(a->addr, b->addr)
250 && a->offset_in_region == b->offset_in_region
251 && a->romd_mode == b->romd_mode
252 && a->readonly == b->readonly
253 && a->nonvolatile == b->nonvolatile;
256 static FlatView *flatview_new(MemoryRegion *mr_root)
258 FlatView *view;
260 view = g_new0(FlatView, 1);
261 view->ref = 1;
262 view->root = mr_root;
263 memory_region_ref(mr_root);
264 trace_flatview_new(view, mr_root);
266 return view;
269 /* Insert a range into a given position. Caller is responsible for maintaining
270 * sorting order.
272 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
274 if (view->nr == view->nr_allocated) {
275 view->nr_allocated = MAX(2 * view->nr, 10);
276 view->ranges = g_realloc(view->ranges,
277 view->nr_allocated * sizeof(*view->ranges));
279 memmove(view->ranges + pos + 1, view->ranges + pos,
280 (view->nr - pos) * sizeof(FlatRange));
281 view->ranges[pos] = *range;
282 memory_region_ref(range->mr);
283 ++view->nr;
286 static void flatview_destroy(FlatView *view)
288 int i;
290 trace_flatview_destroy(view, view->root);
291 if (view->dispatch) {
292 address_space_dispatch_free(view->dispatch);
294 for (i = 0; i < view->nr; i++) {
295 memory_region_unref(view->ranges[i].mr);
297 g_free(view->ranges);
298 memory_region_unref(view->root);
299 g_free(view);
302 static bool flatview_ref(FlatView *view)
304 return qatomic_fetch_inc_nonzero(&view->ref) > 0;
307 void flatview_unref(FlatView *view)
309 if (qatomic_fetch_dec(&view->ref) == 1) {
310 trace_flatview_destroy_rcu(view, view->root);
311 assert(view->root);
312 call_rcu(view, flatview_destroy, rcu);
316 static bool can_merge(FlatRange *r1, FlatRange *r2)
318 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
319 && r1->mr == r2->mr
320 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
321 r1->addr.size),
322 int128_make64(r2->offset_in_region))
323 && r1->dirty_log_mask == r2->dirty_log_mask
324 && r1->romd_mode == r2->romd_mode
325 && r1->readonly == r2->readonly
326 && r1->nonvolatile == r2->nonvolatile;
329 /* Attempt to simplify a view by merging adjacent ranges */
330 static void flatview_simplify(FlatView *view)
332 unsigned i, j, k;
334 i = 0;
335 while (i < view->nr) {
336 j = i + 1;
337 while (j < view->nr
338 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
339 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
340 ++j;
342 ++i;
343 for (k = i; k < j; k++) {
344 memory_region_unref(view->ranges[k].mr);
346 memmove(&view->ranges[i], &view->ranges[j],
347 (view->nr - j) * sizeof(view->ranges[j]));
348 view->nr -= j - i;
352 static bool memory_region_big_endian(MemoryRegion *mr)
354 #if TARGET_BIG_ENDIAN
355 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
356 #else
357 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
358 #endif
361 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, MemOp op)
363 if ((op & MO_BSWAP) != devend_memop(mr->ops->endianness)) {
364 switch (op & MO_SIZE) {
365 case MO_8:
366 break;
367 case MO_16:
368 *data = bswap16(*data);
369 break;
370 case MO_32:
371 *data = bswap32(*data);
372 break;
373 case MO_64:
374 *data = bswap64(*data);
375 break;
376 default:
377 g_assert_not_reached();
382 static inline void memory_region_shift_read_access(uint64_t *value,
383 signed shift,
384 uint64_t mask,
385 uint64_t tmp)
387 if (shift >= 0) {
388 *value |= (tmp & mask) << shift;
389 } else {
390 *value |= (tmp & mask) >> -shift;
394 static inline uint64_t memory_region_shift_write_access(uint64_t *value,
395 signed shift,
396 uint64_t mask)
398 uint64_t tmp;
400 if (shift >= 0) {
401 tmp = (*value >> shift) & mask;
402 } else {
403 tmp = (*value << -shift) & mask;
406 return tmp;
409 static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
411 MemoryRegion *root;
412 hwaddr abs_addr = offset;
414 abs_addr += mr->addr;
415 for (root = mr; root->container; ) {
416 root = root->container;
417 abs_addr += root->addr;
420 return abs_addr;
423 static int get_cpu_index(void)
425 if (current_cpu) {
426 return current_cpu->cpu_index;
428 return -1;
431 static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
432 hwaddr addr,
433 uint64_t *value,
434 unsigned size,
435 signed shift,
436 uint64_t mask,
437 MemTxAttrs attrs)
439 uint64_t tmp;
441 tmp = mr->ops->read(mr->opaque, addr, size);
442 if (mr->subpage) {
443 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
444 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_READ)) {
445 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
446 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size,
447 memory_region_name(mr));
449 memory_region_shift_read_access(value, shift, mask, tmp);
450 return MEMTX_OK;
453 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
454 hwaddr addr,
455 uint64_t *value,
456 unsigned size,
457 signed shift,
458 uint64_t mask,
459 MemTxAttrs attrs)
461 uint64_t tmp = 0;
462 MemTxResult r;
464 r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
465 if (mr->subpage) {
466 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
467 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_READ)) {
468 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
469 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size,
470 memory_region_name(mr));
472 memory_region_shift_read_access(value, shift, mask, tmp);
473 return r;
476 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
477 hwaddr addr,
478 uint64_t *value,
479 unsigned size,
480 signed shift,
481 uint64_t mask,
482 MemTxAttrs attrs)
484 uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
486 if (mr->subpage) {
487 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
488 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_WRITE)) {
489 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
490 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size,
491 memory_region_name(mr));
493 mr->ops->write(mr->opaque, addr, tmp, size);
494 return MEMTX_OK;
497 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
498 hwaddr addr,
499 uint64_t *value,
500 unsigned size,
501 signed shift,
502 uint64_t mask,
503 MemTxAttrs attrs)
505 uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
507 if (mr->subpage) {
508 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
509 } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_WRITE)) {
510 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
511 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size,
512 memory_region_name(mr));
514 return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
517 static MemTxResult access_with_adjusted_size(hwaddr addr,
518 uint64_t *value,
519 unsigned size,
520 unsigned access_size_min,
521 unsigned access_size_max,
522 MemTxResult (*access_fn)
523 (MemoryRegion *mr,
524 hwaddr addr,
525 uint64_t *value,
526 unsigned size,
527 signed shift,
528 uint64_t mask,
529 MemTxAttrs attrs),
530 MemoryRegion *mr,
531 MemTxAttrs attrs)
533 uint64_t access_mask;
534 unsigned access_size;
535 unsigned i;
536 MemTxResult r = MEMTX_OK;
538 if (!access_size_min) {
539 access_size_min = 1;
541 if (!access_size_max) {
542 access_size_max = 4;
545 /* FIXME: support unaligned access? */
546 access_size = MAX(MIN(size, access_size_max), access_size_min);
547 access_mask = MAKE_64BIT_MASK(0, access_size * 8);
548 if (memory_region_big_endian(mr)) {
549 for (i = 0; i < size; i += access_size) {
550 r |= access_fn(mr, addr + i, value, access_size,
551 (size - access_size - i) * 8, access_mask, attrs);
553 } else {
554 for (i = 0; i < size; i += access_size) {
555 r |= access_fn(mr, addr + i, value, access_size, i * 8,
556 access_mask, attrs);
559 return r;
562 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
564 AddressSpace *as;
566 while (mr->container) {
567 mr = mr->container;
569 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
570 if (mr == as->root) {
571 return as;
574 return NULL;
577 /* Render a memory region into the global view. Ranges in @view obscure
578 * ranges in @mr.
580 static void render_memory_region(FlatView *view,
581 MemoryRegion *mr,
582 Int128 base,
583 AddrRange clip,
584 bool readonly,
585 bool nonvolatile)
587 MemoryRegion *subregion;
588 unsigned i;
589 hwaddr offset_in_region;
590 Int128 remain;
591 Int128 now;
592 FlatRange fr;
593 AddrRange tmp;
595 if (!mr->enabled) {
596 return;
599 int128_addto(&base, int128_make64(mr->addr));
600 readonly |= mr->readonly;
601 nonvolatile |= mr->nonvolatile;
603 tmp = addrrange_make(base, mr->size);
605 if (!addrrange_intersects(tmp, clip)) {
606 return;
609 clip = addrrange_intersection(tmp, clip);
611 if (mr->alias) {
612 int128_subfrom(&base, int128_make64(mr->alias->addr));
613 int128_subfrom(&base, int128_make64(mr->alias_offset));
614 render_memory_region(view, mr->alias, base, clip,
615 readonly, nonvolatile);
616 return;
619 /* Render subregions in priority order. */
620 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
621 render_memory_region(view, subregion, base, clip,
622 readonly, nonvolatile);
625 if (!mr->terminates) {
626 return;
629 offset_in_region = int128_get64(int128_sub(clip.start, base));
630 base = clip.start;
631 remain = clip.size;
633 fr.mr = mr;
634 fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
635 fr.romd_mode = mr->romd_mode;
636 fr.readonly = readonly;
637 fr.nonvolatile = nonvolatile;
639 /* Render the region itself into any gaps left by the current view. */
640 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
641 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
642 continue;
644 if (int128_lt(base, view->ranges[i].addr.start)) {
645 now = int128_min(remain,
646 int128_sub(view->ranges[i].addr.start, base));
647 fr.offset_in_region = offset_in_region;
648 fr.addr = addrrange_make(base, now);
649 flatview_insert(view, i, &fr);
650 ++i;
651 int128_addto(&base, now);
652 offset_in_region += int128_get64(now);
653 int128_subfrom(&remain, now);
655 now = int128_sub(int128_min(int128_add(base, remain),
656 addrrange_end(view->ranges[i].addr)),
657 base);
658 int128_addto(&base, now);
659 offset_in_region += int128_get64(now);
660 int128_subfrom(&remain, now);
662 if (int128_nz(remain)) {
663 fr.offset_in_region = offset_in_region;
664 fr.addr = addrrange_make(base, remain);
665 flatview_insert(view, i, &fr);
669 void flatview_for_each_range(FlatView *fv, flatview_cb cb , void *opaque)
671 FlatRange *fr;
673 assert(fv);
674 assert(cb);
676 FOR_EACH_FLAT_RANGE(fr, fv) {
677 if (cb(fr->addr.start, fr->addr.size, fr->mr,
678 fr->offset_in_region, opaque)) {
679 break;
684 static MemoryRegion *memory_region_get_flatview_root(MemoryRegion *mr)
686 while (mr->enabled) {
687 if (mr->alias) {
688 if (!mr->alias_offset && int128_ge(mr->size, mr->alias->size)) {
689 /* The alias is included in its entirety. Use it as
690 * the "real" root, so that we can share more FlatViews.
692 mr = mr->alias;
693 continue;
695 } else if (!mr->terminates) {
696 unsigned int found = 0;
697 MemoryRegion *child, *next = NULL;
698 QTAILQ_FOREACH(child, &mr->subregions, subregions_link) {
699 if (child->enabled) {
700 if (++found > 1) {
701 next = NULL;
702 break;
704 if (!child->addr && int128_ge(mr->size, child->size)) {
705 /* A child is included in its entirety. If it's the only
706 * enabled one, use it in the hope of finding an alias down the
707 * way. This will also let us share FlatViews.
709 next = child;
713 if (found == 0) {
714 return NULL;
716 if (next) {
717 mr = next;
718 continue;
722 return mr;
725 return NULL;
728 /* Render a memory topology into a list of disjoint absolute ranges. */
729 static FlatView *generate_memory_topology(MemoryRegion *mr)
731 int i;
732 FlatView *view;
734 view = flatview_new(mr);
736 if (mr) {
737 render_memory_region(view, mr, int128_zero(),
738 addrrange_make(int128_zero(), int128_2_64()),
739 false, false);
741 flatview_simplify(view);
743 view->dispatch = address_space_dispatch_new(view);
744 for (i = 0; i < view->nr; i++) {
745 MemoryRegionSection mrs =
746 section_from_flat_range(&view->ranges[i], view);
747 flatview_add_to_dispatch(view, &mrs);
749 address_space_dispatch_compact(view->dispatch);
750 g_hash_table_replace(flat_views, mr, view);
752 return view;
755 static void address_space_add_del_ioeventfds(AddressSpace *as,
756 MemoryRegionIoeventfd *fds_new,
757 unsigned fds_new_nb,
758 MemoryRegionIoeventfd *fds_old,
759 unsigned fds_old_nb)
761 unsigned iold, inew;
762 MemoryRegionIoeventfd *fd;
763 MemoryRegionSection section;
765 /* Generate a symmetric difference of the old and new fd sets, adding
766 * and deleting as necessary.
769 iold = inew = 0;
770 while (iold < fds_old_nb || inew < fds_new_nb) {
771 if (iold < fds_old_nb
772 && (inew == fds_new_nb
773 || memory_region_ioeventfd_before(&fds_old[iold],
774 &fds_new[inew]))) {
775 fd = &fds_old[iold];
776 section = (MemoryRegionSection) {
777 .fv = address_space_to_flatview(as),
778 .offset_within_address_space = int128_get64(fd->addr.start),
779 .size = fd->addr.size,
781 MEMORY_LISTENER_CALL(as, eventfd_del, Forward, &section,
782 fd->match_data, fd->data, fd->e);
783 ++iold;
784 } else if (inew < fds_new_nb
785 && (iold == fds_old_nb
786 || memory_region_ioeventfd_before(&fds_new[inew],
787 &fds_old[iold]))) {
788 fd = &fds_new[inew];
789 section = (MemoryRegionSection) {
790 .fv = address_space_to_flatview(as),
791 .offset_within_address_space = int128_get64(fd->addr.start),
792 .size = fd->addr.size,
794 MEMORY_LISTENER_CALL(as, eventfd_add, Reverse, &section,
795 fd->match_data, fd->data, fd->e);
796 ++inew;
797 } else {
798 ++iold;
799 ++inew;
804 FlatView *address_space_get_flatview(AddressSpace *as)
806 FlatView *view;
808 RCU_READ_LOCK_GUARD();
809 do {
810 view = address_space_to_flatview(as);
811 /* If somebody has replaced as->current_map concurrently,
812 * flatview_ref returns false.
814 } while (!flatview_ref(view));
815 return view;
818 static void address_space_update_ioeventfds(AddressSpace *as)
820 FlatView *view;
821 FlatRange *fr;
822 unsigned ioeventfd_nb = 0;
823 unsigned ioeventfd_max;
824 MemoryRegionIoeventfd *ioeventfds;
825 AddrRange tmp;
826 unsigned i;
829 * It is likely that the number of ioeventfds hasn't changed much, so use
830 * the previous size as the starting value, with some headroom to avoid
831 * gratuitous reallocations.
833 ioeventfd_max = QEMU_ALIGN_UP(as->ioeventfd_nb, 4);
834 ioeventfds = g_new(MemoryRegionIoeventfd, ioeventfd_max);
836 view = address_space_get_flatview(as);
837 FOR_EACH_FLAT_RANGE(fr, view) {
838 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
839 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
840 int128_sub(fr->addr.start,
841 int128_make64(fr->offset_in_region)));
842 if (addrrange_intersects(fr->addr, tmp)) {
843 ++ioeventfd_nb;
844 if (ioeventfd_nb > ioeventfd_max) {
845 ioeventfd_max = MAX(ioeventfd_max * 2, 4);
846 ioeventfds = g_realloc(ioeventfds,
847 ioeventfd_max * sizeof(*ioeventfds));
849 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
850 ioeventfds[ioeventfd_nb-1].addr = tmp;
855 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
856 as->ioeventfds, as->ioeventfd_nb);
858 g_free(as->ioeventfds);
859 as->ioeventfds = ioeventfds;
860 as->ioeventfd_nb = ioeventfd_nb;
861 flatview_unref(view);
865 * Notify the memory listeners about the coalesced IO change events of
866 * range `cmr'. Only the part that has intersection of the specified
867 * FlatRange will be sent.
869 static void flat_range_coalesced_io_notify(FlatRange *fr, AddressSpace *as,
870 CoalescedMemoryRange *cmr, bool add)
872 AddrRange tmp;
874 tmp = addrrange_shift(cmr->addr,
875 int128_sub(fr->addr.start,
876 int128_make64(fr->offset_in_region)));
877 if (!addrrange_intersects(tmp, fr->addr)) {
878 return;
880 tmp = addrrange_intersection(tmp, fr->addr);
882 if (add) {
883 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, coalesced_io_add,
884 int128_get64(tmp.start),
885 int128_get64(tmp.size));
886 } else {
887 MEMORY_LISTENER_UPDATE_REGION(fr, as, Reverse, coalesced_io_del,
888 int128_get64(tmp.start),
889 int128_get64(tmp.size));
893 static void flat_range_coalesced_io_del(FlatRange *fr, AddressSpace *as)
895 CoalescedMemoryRange *cmr;
897 QTAILQ_FOREACH(cmr, &fr->mr->coalesced, link) {
898 flat_range_coalesced_io_notify(fr, as, cmr, false);
902 static void flat_range_coalesced_io_add(FlatRange *fr, AddressSpace *as)
904 MemoryRegion *mr = fr->mr;
905 CoalescedMemoryRange *cmr;
907 if (QTAILQ_EMPTY(&mr->coalesced)) {
908 return;
911 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
912 flat_range_coalesced_io_notify(fr, as, cmr, true);
916 static void address_space_update_topology_pass(AddressSpace *as,
917 const FlatView *old_view,
918 const FlatView *new_view,
919 bool adding)
921 unsigned iold, inew;
922 FlatRange *frold, *frnew;
924 /* Generate a symmetric difference of the old and new memory maps.
925 * Kill ranges in the old map, and instantiate ranges in the new map.
927 iold = inew = 0;
928 while (iold < old_view->nr || inew < new_view->nr) {
929 if (iold < old_view->nr) {
930 frold = &old_view->ranges[iold];
931 } else {
932 frold = NULL;
934 if (inew < new_view->nr) {
935 frnew = &new_view->ranges[inew];
936 } else {
937 frnew = NULL;
940 if (frold
941 && (!frnew
942 || int128_lt(frold->addr.start, frnew->addr.start)
943 || (int128_eq(frold->addr.start, frnew->addr.start)
944 && !flatrange_equal(frold, frnew)))) {
945 /* In old but not in new, or in both but attributes changed. */
947 if (!adding) {
948 flat_range_coalesced_io_del(frold, as);
949 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
952 ++iold;
953 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
954 /* In both and unchanged (except logging may have changed) */
956 if (adding) {
957 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
958 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
959 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
960 frold->dirty_log_mask,
961 frnew->dirty_log_mask);
963 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
964 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
965 frold->dirty_log_mask,
966 frnew->dirty_log_mask);
970 ++iold;
971 ++inew;
972 } else {
973 /* In new */
975 if (adding) {
976 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
977 flat_range_coalesced_io_add(frnew, as);
980 ++inew;
985 static void flatviews_init(void)
987 static FlatView *empty_view;
989 if (flat_views) {
990 return;
993 flat_views = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL,
994 (GDestroyNotify) flatview_unref);
995 if (!empty_view) {
996 empty_view = generate_memory_topology(NULL);
997 /* We keep it alive forever in the global variable. */
998 flatview_ref(empty_view);
999 } else {
1000 g_hash_table_replace(flat_views, NULL, empty_view);
1001 flatview_ref(empty_view);
1005 static void flatviews_reset(void)
1007 AddressSpace *as;
1009 if (flat_views) {
1010 g_hash_table_unref(flat_views);
1011 flat_views = NULL;
1013 flatviews_init();
1015 /* Render unique FVs */
1016 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1017 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1019 if (g_hash_table_lookup(flat_views, physmr)) {
1020 continue;
1023 generate_memory_topology(physmr);
1027 static void address_space_set_flatview(AddressSpace *as)
1029 FlatView *old_view = address_space_to_flatview(as);
1030 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1031 FlatView *new_view = g_hash_table_lookup(flat_views, physmr);
1033 assert(new_view);
1035 if (old_view == new_view) {
1036 return;
1039 if (old_view) {
1040 flatview_ref(old_view);
1043 flatview_ref(new_view);
1045 if (!QTAILQ_EMPTY(&as->listeners)) {
1046 FlatView tmpview = { .nr = 0 }, *old_view2 = old_view;
1048 if (!old_view2) {
1049 old_view2 = &tmpview;
1051 address_space_update_topology_pass(as, old_view2, new_view, false);
1052 address_space_update_topology_pass(as, old_view2, new_view, true);
1055 /* Writes are protected by the BQL. */
1056 qatomic_rcu_set(&as->current_map, new_view);
1057 if (old_view) {
1058 flatview_unref(old_view);
1061 /* Note that all the old MemoryRegions are still alive up to this
1062 * point. This relieves most MemoryListeners from the need to
1063 * ref/unref the MemoryRegions they get---unless they use them
1064 * outside the iothread mutex, in which case precise reference
1065 * counting is necessary.
1067 if (old_view) {
1068 flatview_unref(old_view);
1072 static void address_space_update_topology(AddressSpace *as)
1074 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1076 flatviews_init();
1077 if (!g_hash_table_lookup(flat_views, physmr)) {
1078 generate_memory_topology(physmr);
1080 address_space_set_flatview(as);
1083 void memory_region_transaction_begin(void)
1085 qemu_flush_coalesced_mmio_buffer();
1086 ++memory_region_transaction_depth;
1089 void memory_region_transaction_commit(void)
1091 AddressSpace *as;
1093 assert(memory_region_transaction_depth);
1094 assert(qemu_mutex_iothread_locked());
1096 --memory_region_transaction_depth;
1097 if (!memory_region_transaction_depth) {
1098 if (memory_region_update_pending) {
1099 flatviews_reset();
1101 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
1103 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1104 address_space_set_flatview(as);
1105 address_space_update_ioeventfds(as);
1107 memory_region_update_pending = false;
1108 ioeventfd_update_pending = false;
1109 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
1110 } else if (ioeventfd_update_pending) {
1111 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1112 address_space_update_ioeventfds(as);
1114 ioeventfd_update_pending = false;
1119 static void memory_region_destructor_none(MemoryRegion *mr)
1123 static void memory_region_destructor_ram(MemoryRegion *mr)
1125 qemu_ram_free(mr->ram_block);
1128 static bool memory_region_need_escape(char c)
1130 return c == '/' || c == '[' || c == '\\' || c == ']';
1133 static char *memory_region_escape_name(const char *name)
1135 const char *p;
1136 char *escaped, *q;
1137 uint8_t c;
1138 size_t bytes = 0;
1140 for (p = name; *p; p++) {
1141 bytes += memory_region_need_escape(*p) ? 4 : 1;
1143 if (bytes == p - name) {
1144 return g_memdup(name, bytes + 1);
1147 escaped = g_malloc(bytes + 1);
1148 for (p = name, q = escaped; *p; p++) {
1149 c = *p;
1150 if (unlikely(memory_region_need_escape(c))) {
1151 *q++ = '\\';
1152 *q++ = 'x';
1153 *q++ = "0123456789abcdef"[c >> 4];
1154 c = "0123456789abcdef"[c & 15];
1156 *q++ = c;
1158 *q = 0;
1159 return escaped;
1162 static void memory_region_do_init(MemoryRegion *mr,
1163 Object *owner,
1164 const char *name,
1165 uint64_t size)
1167 mr->size = int128_make64(size);
1168 if (size == UINT64_MAX) {
1169 mr->size = int128_2_64();
1171 mr->name = g_strdup(name);
1172 mr->owner = owner;
1173 mr->ram_block = NULL;
1175 if (name) {
1176 char *escaped_name = memory_region_escape_name(name);
1177 char *name_array = g_strdup_printf("%s[*]", escaped_name);
1179 if (!owner) {
1180 owner = container_get(qdev_get_machine(), "/unattached");
1183 object_property_add_child(owner, name_array, OBJECT(mr));
1184 object_unref(OBJECT(mr));
1185 g_free(name_array);
1186 g_free(escaped_name);
1190 void memory_region_init(MemoryRegion *mr,
1191 Object *owner,
1192 const char *name,
1193 uint64_t size)
1195 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
1196 memory_region_do_init(mr, owner, name, size);
1199 static void memory_region_get_container(Object *obj, Visitor *v,
1200 const char *name, void *opaque,
1201 Error **errp)
1203 MemoryRegion *mr = MEMORY_REGION(obj);
1204 char *path = (char *)"";
1206 if (mr->container) {
1207 path = object_get_canonical_path(OBJECT(mr->container));
1209 visit_type_str(v, name, &path, errp);
1210 if (mr->container) {
1211 g_free(path);
1215 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1216 const char *part)
1218 MemoryRegion *mr = MEMORY_REGION(obj);
1220 return OBJECT(mr->container);
1223 static void memory_region_get_priority(Object *obj, Visitor *v,
1224 const char *name, void *opaque,
1225 Error **errp)
1227 MemoryRegion *mr = MEMORY_REGION(obj);
1228 int32_t value = mr->priority;
1230 visit_type_int32(v, name, &value, errp);
1233 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1234 void *opaque, Error **errp)
1236 MemoryRegion *mr = MEMORY_REGION(obj);
1237 uint64_t value = memory_region_size(mr);
1239 visit_type_uint64(v, name, &value, errp);
1242 static void memory_region_initfn(Object *obj)
1244 MemoryRegion *mr = MEMORY_REGION(obj);
1245 ObjectProperty *op;
1247 mr->ops = &unassigned_mem_ops;
1248 mr->enabled = true;
1249 mr->romd_mode = true;
1250 mr->destructor = memory_region_destructor_none;
1251 QTAILQ_INIT(&mr->subregions);
1252 QTAILQ_INIT(&mr->coalesced);
1254 op = object_property_add(OBJECT(mr), "container",
1255 "link<" TYPE_MEMORY_REGION ">",
1256 memory_region_get_container,
1257 NULL, /* memory_region_set_container */
1258 NULL, NULL);
1259 op->resolve = memory_region_resolve_container;
1261 object_property_add_uint64_ptr(OBJECT(mr), "addr",
1262 &mr->addr, OBJ_PROP_FLAG_READ);
1263 object_property_add(OBJECT(mr), "priority", "uint32",
1264 memory_region_get_priority,
1265 NULL, /* memory_region_set_priority */
1266 NULL, NULL);
1267 object_property_add(OBJECT(mr), "size", "uint64",
1268 memory_region_get_size,
1269 NULL, /* memory_region_set_size, */
1270 NULL, NULL);
1273 static void iommu_memory_region_initfn(Object *obj)
1275 MemoryRegion *mr = MEMORY_REGION(obj);
1277 mr->is_iommu = true;
1280 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1281 unsigned size)
1283 #ifdef DEBUG_UNASSIGNED
1284 printf("Unassigned mem read " HWADDR_FMT_plx "\n", addr);
1285 #endif
1286 return 0;
1289 static void unassigned_mem_write(void *opaque, hwaddr addr,
1290 uint64_t val, unsigned size)
1292 #ifdef DEBUG_UNASSIGNED
1293 printf("Unassigned mem write " HWADDR_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1294 #endif
1297 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1298 unsigned size, bool is_write,
1299 MemTxAttrs attrs)
1301 return false;
1304 const MemoryRegionOps unassigned_mem_ops = {
1305 .valid.accepts = unassigned_mem_accepts,
1306 .endianness = DEVICE_NATIVE_ENDIAN,
1309 static uint64_t memory_region_ram_device_read(void *opaque,
1310 hwaddr addr, unsigned size)
1312 MemoryRegion *mr = opaque;
1313 uint64_t data = (uint64_t)~0;
1315 switch (size) {
1316 case 1:
1317 data = *(uint8_t *)(mr->ram_block->host + addr);
1318 break;
1319 case 2:
1320 data = *(uint16_t *)(mr->ram_block->host + addr);
1321 break;
1322 case 4:
1323 data = *(uint32_t *)(mr->ram_block->host + addr);
1324 break;
1325 case 8:
1326 data = *(uint64_t *)(mr->ram_block->host + addr);
1327 break;
1330 trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);
1332 return data;
1335 static void memory_region_ram_device_write(void *opaque, hwaddr addr,
1336 uint64_t data, unsigned size)
1338 MemoryRegion *mr = opaque;
1340 trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);
1342 switch (size) {
1343 case 1:
1344 *(uint8_t *)(mr->ram_block->host + addr) = (uint8_t)data;
1345 break;
1346 case 2:
1347 *(uint16_t *)(mr->ram_block->host + addr) = (uint16_t)data;
1348 break;
1349 case 4:
1350 *(uint32_t *)(mr->ram_block->host + addr) = (uint32_t)data;
1351 break;
1352 case 8:
1353 *(uint64_t *)(mr->ram_block->host + addr) = data;
1354 break;
1358 static const MemoryRegionOps ram_device_mem_ops = {
1359 .read = memory_region_ram_device_read,
1360 .write = memory_region_ram_device_write,
1361 .endianness = DEVICE_HOST_ENDIAN,
1362 .valid = {
1363 .min_access_size = 1,
1364 .max_access_size = 8,
1365 .unaligned = true,
1367 .impl = {
1368 .min_access_size = 1,
1369 .max_access_size = 8,
1370 .unaligned = true,
1374 bool memory_region_access_valid(MemoryRegion *mr,
1375 hwaddr addr,
1376 unsigned size,
1377 bool is_write,
1378 MemTxAttrs attrs)
1380 if (mr->ops->valid.accepts
1381 && !mr->ops->valid.accepts(mr->opaque, addr, size, is_write, attrs)) {
1382 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1383 ", size %u, region '%s', reason: rejected\n",
1384 is_write ? "write" : "read",
1385 addr, size, memory_region_name(mr));
1386 return false;
1389 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1390 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1391 ", size %u, region '%s', reason: unaligned\n",
1392 is_write ? "write" : "read",
1393 addr, size, memory_region_name(mr));
1394 return false;
1397 /* Treat zero as compatibility all valid */
1398 if (!mr->ops->valid.max_access_size) {
1399 return true;
1402 if (size > mr->ops->valid.max_access_size
1403 || size < mr->ops->valid.min_access_size) {
1404 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1405 ", size %u, region '%s', reason: invalid size "
1406 "(min:%u max:%u)\n",
1407 is_write ? "write" : "read",
1408 addr, size, memory_region_name(mr),
1409 mr->ops->valid.min_access_size,
1410 mr->ops->valid.max_access_size);
1411 return false;
1413 return true;
1416 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1417 hwaddr addr,
1418 uint64_t *pval,
1419 unsigned size,
1420 MemTxAttrs attrs)
1422 *pval = 0;
1424 if (mr->ops->read) {
1425 return access_with_adjusted_size(addr, pval, size,
1426 mr->ops->impl.min_access_size,
1427 mr->ops->impl.max_access_size,
1428 memory_region_read_accessor,
1429 mr, attrs);
1430 } else {
1431 return access_with_adjusted_size(addr, pval, size,
1432 mr->ops->impl.min_access_size,
1433 mr->ops->impl.max_access_size,
1434 memory_region_read_with_attrs_accessor,
1435 mr, attrs);
1439 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1440 hwaddr addr,
1441 uint64_t *pval,
1442 MemOp op,
1443 MemTxAttrs attrs)
1445 unsigned size = memop_size(op);
1446 MemTxResult r;
1448 if (mr->alias) {
1449 return memory_region_dispatch_read(mr->alias,
1450 mr->alias_offset + addr,
1451 pval, op, attrs);
1453 if (!memory_region_access_valid(mr, addr, size, false, attrs)) {
1454 *pval = unassigned_mem_read(mr, addr, size);
1455 return MEMTX_DECODE_ERROR;
1458 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1459 adjust_endianness(mr, pval, op);
1460 return r;
1463 /* Return true if an eventfd was signalled */
1464 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1465 hwaddr addr,
1466 uint64_t data,
1467 unsigned size,
1468 MemTxAttrs attrs)
1470 MemoryRegionIoeventfd ioeventfd = {
1471 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1472 .data = data,
1474 unsigned i;
1476 for (i = 0; i < mr->ioeventfd_nb; i++) {
1477 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1478 ioeventfd.e = mr->ioeventfds[i].e;
1480 if (memory_region_ioeventfd_equal(&ioeventfd, &mr->ioeventfds[i])) {
1481 event_notifier_set(ioeventfd.e);
1482 return true;
1486 return false;
1489 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1490 hwaddr addr,
1491 uint64_t data,
1492 MemOp op,
1493 MemTxAttrs attrs)
1495 unsigned size = memop_size(op);
1497 if (mr->alias) {
1498 return memory_region_dispatch_write(mr->alias,
1499 mr->alias_offset + addr,
1500 data, op, attrs);
1502 if (!memory_region_access_valid(mr, addr, size, true, attrs)) {
1503 unassigned_mem_write(mr, addr, data, size);
1504 return MEMTX_DECODE_ERROR;
1507 adjust_endianness(mr, &data, op);
1509 if ((!kvm_eventfds_enabled()) &&
1510 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1511 return MEMTX_OK;
1514 if (mr->ops->write) {
1515 return access_with_adjusted_size(addr, &data, size,
1516 mr->ops->impl.min_access_size,
1517 mr->ops->impl.max_access_size,
1518 memory_region_write_accessor, mr,
1519 attrs);
1520 } else {
1521 return
1522 access_with_adjusted_size(addr, &data, size,
1523 mr->ops->impl.min_access_size,
1524 mr->ops->impl.max_access_size,
1525 memory_region_write_with_attrs_accessor,
1526 mr, attrs);
1530 void memory_region_init_io(MemoryRegion *mr,
1531 Object *owner,
1532 const MemoryRegionOps *ops,
1533 void *opaque,
1534 const char *name,
1535 uint64_t size)
1537 memory_region_init(mr, owner, name, size);
1538 mr->ops = ops ? ops : &unassigned_mem_ops;
1539 mr->opaque = opaque;
1540 mr->terminates = true;
1543 void memory_region_init_ram_nomigrate(MemoryRegion *mr,
1544 Object *owner,
1545 const char *name,
1546 uint64_t size,
1547 Error **errp)
1549 memory_region_init_ram_flags_nomigrate(mr, owner, name, size, 0, errp);
1552 void memory_region_init_ram_flags_nomigrate(MemoryRegion *mr,
1553 Object *owner,
1554 const char *name,
1555 uint64_t size,
1556 uint32_t ram_flags,
1557 Error **errp)
1559 Error *err = NULL;
1560 memory_region_init(mr, owner, name, size);
1561 mr->ram = true;
1562 mr->terminates = true;
1563 mr->destructor = memory_region_destructor_ram;
1564 mr->ram_block = qemu_ram_alloc(size, ram_flags, mr, &err);
1565 if (err) {
1566 mr->size = int128_zero();
1567 object_unparent(OBJECT(mr));
1568 error_propagate(errp, err);
1572 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1573 Object *owner,
1574 const char *name,
1575 uint64_t size,
1576 uint64_t max_size,
1577 void (*resized)(const char*,
1578 uint64_t length,
1579 void *host),
1580 Error **errp)
1582 Error *err = NULL;
1583 memory_region_init(mr, owner, name, size);
1584 mr->ram = true;
1585 mr->terminates = true;
1586 mr->destructor = memory_region_destructor_ram;
1587 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1588 mr, &err);
1589 if (err) {
1590 mr->size = int128_zero();
1591 object_unparent(OBJECT(mr));
1592 error_propagate(errp, err);
1596 #ifdef CONFIG_POSIX
1597 void memory_region_init_ram_from_file(MemoryRegion *mr,
1598 Object *owner,
1599 const char *name,
1600 uint64_t size,
1601 uint64_t align,
1602 uint32_t ram_flags,
1603 const char *path,
1604 bool readonly,
1605 Error **errp)
1607 Error *err = NULL;
1608 memory_region_init(mr, owner, name, size);
1609 mr->ram = true;
1610 mr->readonly = readonly;
1611 mr->terminates = true;
1612 mr->destructor = memory_region_destructor_ram;
1613 mr->align = align;
1614 mr->ram_block = qemu_ram_alloc_from_file(size, mr, ram_flags, path,
1615 readonly, &err);
1616 if (err) {
1617 mr->size = int128_zero();
1618 object_unparent(OBJECT(mr));
1619 error_propagate(errp, err);
1623 void memory_region_init_ram_from_fd(MemoryRegion *mr,
1624 Object *owner,
1625 const char *name,
1626 uint64_t size,
1627 uint32_t ram_flags,
1628 int fd,
1629 ram_addr_t offset,
1630 Error **errp)
1632 Error *err = NULL;
1633 memory_region_init(mr, owner, name, size);
1634 mr->ram = true;
1635 mr->terminates = true;
1636 mr->destructor = memory_region_destructor_ram;
1637 mr->ram_block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, offset,
1638 false, &err);
1639 if (err) {
1640 mr->size = int128_zero();
1641 object_unparent(OBJECT(mr));
1642 error_propagate(errp, err);
1645 #endif
1647 void memory_region_init_ram_ptr(MemoryRegion *mr,
1648 Object *owner,
1649 const char *name,
1650 uint64_t size,
1651 void *ptr)
1653 memory_region_init(mr, owner, name, size);
1654 mr->ram = true;
1655 mr->terminates = true;
1656 mr->destructor = memory_region_destructor_ram;
1658 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1659 assert(ptr != NULL);
1660 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1663 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1664 Object *owner,
1665 const char *name,
1666 uint64_t size,
1667 void *ptr)
1669 memory_region_init(mr, owner, name, size);
1670 mr->ram = true;
1671 mr->terminates = true;
1672 mr->ram_device = true;
1673 mr->ops = &ram_device_mem_ops;
1674 mr->opaque = mr;
1675 mr->destructor = memory_region_destructor_ram;
1677 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1678 assert(ptr != NULL);
1679 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1682 void memory_region_init_alias(MemoryRegion *mr,
1683 Object *owner,
1684 const char *name,
1685 MemoryRegion *orig,
1686 hwaddr offset,
1687 uint64_t size)
1689 memory_region_init(mr, owner, name, size);
1690 mr->alias = orig;
1691 mr->alias_offset = offset;
1694 void memory_region_init_rom_nomigrate(MemoryRegion *mr,
1695 Object *owner,
1696 const char *name,
1697 uint64_t size,
1698 Error **errp)
1700 memory_region_init_ram_flags_nomigrate(mr, owner, name, size, 0, errp);
1701 mr->readonly = true;
1704 void memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1705 Object *owner,
1706 const MemoryRegionOps *ops,
1707 void *opaque,
1708 const char *name,
1709 uint64_t size,
1710 Error **errp)
1712 Error *err = NULL;
1713 assert(ops);
1714 memory_region_init(mr, owner, name, size);
1715 mr->ops = ops;
1716 mr->opaque = opaque;
1717 mr->terminates = true;
1718 mr->rom_device = true;
1719 mr->destructor = memory_region_destructor_ram;
1720 mr->ram_block = qemu_ram_alloc(size, 0, mr, &err);
1721 if (err) {
1722 mr->size = int128_zero();
1723 object_unparent(OBJECT(mr));
1724 error_propagate(errp, err);
1728 void memory_region_init_iommu(void *_iommu_mr,
1729 size_t instance_size,
1730 const char *mrtypename,
1731 Object *owner,
1732 const char *name,
1733 uint64_t size)
1735 struct IOMMUMemoryRegion *iommu_mr;
1736 struct MemoryRegion *mr;
1738 object_initialize(_iommu_mr, instance_size, mrtypename);
1739 mr = MEMORY_REGION(_iommu_mr);
1740 memory_region_do_init(mr, owner, name, size);
1741 iommu_mr = IOMMU_MEMORY_REGION(mr);
1742 mr->terminates = true; /* then re-forwards */
1743 QLIST_INIT(&iommu_mr->iommu_notify);
1744 iommu_mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
1747 static void memory_region_finalize(Object *obj)
1749 MemoryRegion *mr = MEMORY_REGION(obj);
1751 assert(!mr->container);
1753 /* We know the region is not visible in any address space (it
1754 * does not have a container and cannot be a root either because
1755 * it has no references, so we can blindly clear mr->enabled.
1756 * memory_region_set_enabled instead could trigger a transaction
1757 * and cause an infinite loop.
1759 mr->enabled = false;
1760 memory_region_transaction_begin();
1761 while (!QTAILQ_EMPTY(&mr->subregions)) {
1762 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1763 memory_region_del_subregion(mr, subregion);
1765 memory_region_transaction_commit();
1767 mr->destructor(mr);
1768 memory_region_clear_coalescing(mr);
1769 g_free((char *)mr->name);
1770 g_free(mr->ioeventfds);
1773 Object *memory_region_owner(MemoryRegion *mr)
1775 Object *obj = OBJECT(mr);
1776 return obj->parent;
1779 void memory_region_ref(MemoryRegion *mr)
1781 /* MMIO callbacks most likely will access data that belongs
1782 * to the owner, hence the need to ref/unref the owner whenever
1783 * the memory region is in use.
1785 * The memory region is a child of its owner. As long as the
1786 * owner doesn't call unparent itself on the memory region,
1787 * ref-ing the owner will also keep the memory region alive.
1788 * Memory regions without an owner are supposed to never go away;
1789 * we do not ref/unref them because it slows down DMA sensibly.
1791 if (mr && mr->owner) {
1792 object_ref(mr->owner);
1796 void memory_region_unref(MemoryRegion *mr)
1798 if (mr && mr->owner) {
1799 object_unref(mr->owner);
1803 uint64_t memory_region_size(MemoryRegion *mr)
1805 if (int128_eq(mr->size, int128_2_64())) {
1806 return UINT64_MAX;
1808 return int128_get64(mr->size);
1811 const char *memory_region_name(const MemoryRegion *mr)
1813 if (!mr->name) {
1814 ((MemoryRegion *)mr)->name =
1815 g_strdup(object_get_canonical_path_component(OBJECT(mr)));
1817 return mr->name;
1820 bool memory_region_is_ram_device(MemoryRegion *mr)
1822 return mr->ram_device;
1825 bool memory_region_is_protected(MemoryRegion *mr)
1827 return mr->ram && (mr->ram_block->flags & RAM_PROTECTED);
1830 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1832 uint8_t mask = mr->dirty_log_mask;
1833 RAMBlock *rb = mr->ram_block;
1835 if (global_dirty_tracking && ((rb && qemu_ram_is_migratable(rb)) ||
1836 memory_region_is_iommu(mr))) {
1837 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1840 if (tcg_enabled() && rb) {
1841 /* TCG only cares about dirty memory logging for RAM, not IOMMU. */
1842 mask |= (1 << DIRTY_MEMORY_CODE);
1844 return mask;
1847 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1849 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1852 static int memory_region_update_iommu_notify_flags(IOMMUMemoryRegion *iommu_mr,
1853 Error **errp)
1855 IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1856 IOMMUNotifier *iommu_notifier;
1857 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1858 int ret = 0;
1860 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
1861 flags |= iommu_notifier->notifier_flags;
1864 if (flags != iommu_mr->iommu_notify_flags && imrc->notify_flag_changed) {
1865 ret = imrc->notify_flag_changed(iommu_mr,
1866 iommu_mr->iommu_notify_flags,
1867 flags, errp);
1870 if (!ret) {
1871 iommu_mr->iommu_notify_flags = flags;
1873 return ret;
1876 int memory_region_iommu_set_page_size_mask(IOMMUMemoryRegion *iommu_mr,
1877 uint64_t page_size_mask,
1878 Error **errp)
1880 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1881 int ret = 0;
1883 if (imrc->iommu_set_page_size_mask) {
1884 ret = imrc->iommu_set_page_size_mask(iommu_mr, page_size_mask, errp);
1886 return ret;
1889 int memory_region_register_iommu_notifier(MemoryRegion *mr,
1890 IOMMUNotifier *n, Error **errp)
1892 IOMMUMemoryRegion *iommu_mr;
1893 int ret;
1895 if (mr->alias) {
1896 return memory_region_register_iommu_notifier(mr->alias, n, errp);
1899 /* We need to register for at least one bitfield */
1900 iommu_mr = IOMMU_MEMORY_REGION(mr);
1901 assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
1902 assert(n->start <= n->end);
1903 assert(n->iommu_idx >= 0 &&
1904 n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
1906 QLIST_INSERT_HEAD(&iommu_mr->iommu_notify, n, node);
1907 ret = memory_region_update_iommu_notify_flags(iommu_mr, errp);
1908 if (ret) {
1909 QLIST_REMOVE(n, node);
1911 return ret;
1914 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr)
1916 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1918 if (imrc->get_min_page_size) {
1919 return imrc->get_min_page_size(iommu_mr);
1921 return TARGET_PAGE_SIZE;
1924 void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
1926 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
1927 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1928 hwaddr addr, granularity;
1929 IOMMUTLBEntry iotlb;
1931 /* If the IOMMU has its own replay callback, override */
1932 if (imrc->replay) {
1933 imrc->replay(iommu_mr, n);
1934 return;
1937 granularity = memory_region_iommu_get_min_page_size(iommu_mr);
1939 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1940 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, n->iommu_idx);
1941 if (iotlb.perm != IOMMU_NONE) {
1942 n->notify(n, &iotlb);
1945 /* if (2^64 - MR size) < granularity, it's possible to get an
1946 * infinite loop here. This should catch such a wraparound */
1947 if ((addr + granularity) < addr) {
1948 break;
1953 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1954 IOMMUNotifier *n)
1956 IOMMUMemoryRegion *iommu_mr;
1958 if (mr->alias) {
1959 memory_region_unregister_iommu_notifier(mr->alias, n);
1960 return;
1962 QLIST_REMOVE(n, node);
1963 iommu_mr = IOMMU_MEMORY_REGION(mr);
1964 memory_region_update_iommu_notify_flags(iommu_mr, NULL);
1967 void memory_region_notify_iommu_one(IOMMUNotifier *notifier,
1968 IOMMUTLBEvent *event)
1970 IOMMUTLBEntry *entry = &event->entry;
1971 hwaddr entry_end = entry->iova + entry->addr_mask;
1972 IOMMUTLBEntry tmp = *entry;
1974 if (event->type == IOMMU_NOTIFIER_UNMAP) {
1975 assert(entry->perm == IOMMU_NONE);
1979 * Skip the notification if the notification does not overlap
1980 * with registered range.
1982 if (notifier->start > entry_end || notifier->end < entry->iova) {
1983 return;
1986 if (notifier->notifier_flags & IOMMU_NOTIFIER_DEVIOTLB_UNMAP) {
1987 /* Crop (iova, addr_mask) to range */
1988 tmp.iova = MAX(tmp.iova, notifier->start);
1989 tmp.addr_mask = MIN(entry_end, notifier->end) - tmp.iova;
1990 } else {
1991 assert(entry->iova >= notifier->start && entry_end <= notifier->end);
1994 if (event->type & notifier->notifier_flags) {
1995 notifier->notify(notifier, &tmp);
1999 void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
2000 int iommu_idx,
2001 IOMMUTLBEvent event)
2003 IOMMUNotifier *iommu_notifier;
2005 assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
2007 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
2008 if (iommu_notifier->iommu_idx == iommu_idx) {
2009 memory_region_notify_iommu_one(iommu_notifier, &event);
2014 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
2015 enum IOMMUMemoryRegionAttr attr,
2016 void *data)
2018 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2020 if (!imrc->get_attr) {
2021 return -EINVAL;
2024 return imrc->get_attr(iommu_mr, attr, data);
2027 int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
2028 MemTxAttrs attrs)
2030 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2032 if (!imrc->attrs_to_index) {
2033 return 0;
2036 return imrc->attrs_to_index(iommu_mr, attrs);
2039 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr)
2041 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2043 if (!imrc->num_indexes) {
2044 return 1;
2047 return imrc->num_indexes(iommu_mr);
2050 RamDiscardManager *memory_region_get_ram_discard_manager(MemoryRegion *mr)
2052 if (!memory_region_is_mapped(mr) || !memory_region_is_ram(mr)) {
2053 return NULL;
2055 return mr->rdm;
2058 void memory_region_set_ram_discard_manager(MemoryRegion *mr,
2059 RamDiscardManager *rdm)
2061 g_assert(memory_region_is_ram(mr) && !memory_region_is_mapped(mr));
2062 g_assert(!rdm || !mr->rdm);
2063 mr->rdm = rdm;
2066 uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,
2067 const MemoryRegion *mr)
2069 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2071 g_assert(rdmc->get_min_granularity);
2072 return rdmc->get_min_granularity(rdm, mr);
2075 bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
2076 const MemoryRegionSection *section)
2078 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2080 g_assert(rdmc->is_populated);
2081 return rdmc->is_populated(rdm, section);
2084 int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
2085 MemoryRegionSection *section,
2086 ReplayRamPopulate replay_fn,
2087 void *opaque)
2089 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2091 g_assert(rdmc->replay_populated);
2092 return rdmc->replay_populated(rdm, section, replay_fn, opaque);
2095 void ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
2096 MemoryRegionSection *section,
2097 ReplayRamDiscard replay_fn,
2098 void *opaque)
2100 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2102 g_assert(rdmc->replay_discarded);
2103 rdmc->replay_discarded(rdm, section, replay_fn, opaque);
2106 void ram_discard_manager_register_listener(RamDiscardManager *rdm,
2107 RamDiscardListener *rdl,
2108 MemoryRegionSection *section)
2110 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2112 g_assert(rdmc->register_listener);
2113 rdmc->register_listener(rdm, rdl, section);
2116 void ram_discard_manager_unregister_listener(RamDiscardManager *rdm,
2117 RamDiscardListener *rdl)
2119 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2121 g_assert(rdmc->unregister_listener);
2122 rdmc->unregister_listener(rdm, rdl);
2125 /* Called with rcu_read_lock held. */
2126 bool memory_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
2127 ram_addr_t *ram_addr, bool *read_only,
2128 bool *mr_has_discard_manager)
2130 MemoryRegion *mr;
2131 hwaddr xlat;
2132 hwaddr len = iotlb->addr_mask + 1;
2133 bool writable = iotlb->perm & IOMMU_WO;
2135 if (mr_has_discard_manager) {
2136 *mr_has_discard_manager = false;
2139 * The IOMMU TLB entry we have just covers translation through
2140 * this IOMMU to its immediate target. We need to translate
2141 * it the rest of the way through to memory.
2143 mr = address_space_translate(&address_space_memory, iotlb->translated_addr,
2144 &xlat, &len, writable, MEMTXATTRS_UNSPECIFIED);
2145 if (!memory_region_is_ram(mr)) {
2146 error_report("iommu map to non memory area %" HWADDR_PRIx "", xlat);
2147 return false;
2148 } else if (memory_region_has_ram_discard_manager(mr)) {
2149 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(mr);
2150 MemoryRegionSection tmp = {
2151 .mr = mr,
2152 .offset_within_region = xlat,
2153 .size = int128_make64(len),
2155 if (mr_has_discard_manager) {
2156 *mr_has_discard_manager = true;
2159 * Malicious VMs can map memory into the IOMMU, which is expected
2160 * to remain discarded. vfio will pin all pages, populating memory.
2161 * Disallow that. vmstate priorities make sure any RamDiscardManager
2162 * were already restored before IOMMUs are restored.
2164 if (!ram_discard_manager_is_populated(rdm, &tmp)) {
2165 error_report("iommu map to discarded memory (e.g., unplugged via"
2166 " virtio-mem): %" HWADDR_PRIx "",
2167 iotlb->translated_addr);
2168 return false;
2173 * Translation truncates length to the IOMMU page size,
2174 * check that it did not truncate too much.
2176 if (len & iotlb->addr_mask) {
2177 error_report("iommu has granularity incompatible with target AS");
2178 return false;
2181 if (vaddr) {
2182 *vaddr = memory_region_get_ram_ptr(mr) + xlat;
2185 if (ram_addr) {
2186 *ram_addr = memory_region_get_ram_addr(mr) + xlat;
2189 if (read_only) {
2190 *read_only = !writable || mr->readonly;
2193 return true;
2196 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
2198 uint8_t mask = 1 << client;
2199 uint8_t old_logging;
2201 assert(client == DIRTY_MEMORY_VGA);
2202 old_logging = mr->vga_logging_count;
2203 mr->vga_logging_count += log ? 1 : -1;
2204 if (!!old_logging == !!mr->vga_logging_count) {
2205 return;
2208 memory_region_transaction_begin();
2209 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
2210 memory_region_update_pending |= mr->enabled;
2211 memory_region_transaction_commit();
2214 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
2215 hwaddr size)
2217 assert(mr->ram_block);
2218 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
2219 size,
2220 memory_region_get_dirty_log_mask(mr));
2224 * If memory region `mr' is NULL, do global sync. Otherwise, sync
2225 * dirty bitmap for the specified memory region.
2227 static void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
2229 MemoryListener *listener;
2230 AddressSpace *as;
2231 FlatView *view;
2232 FlatRange *fr;
2234 /* If the same address space has multiple log_sync listeners, we
2235 * visit that address space's FlatView multiple times. But because
2236 * log_sync listeners are rare, it's still cheaper than walking each
2237 * address space once.
2239 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2240 if (listener->log_sync) {
2241 as = listener->address_space;
2242 view = address_space_get_flatview(as);
2243 FOR_EACH_FLAT_RANGE(fr, view) {
2244 if (fr->dirty_log_mask && (!mr || fr->mr == mr)) {
2245 MemoryRegionSection mrs = section_from_flat_range(fr, view);
2246 listener->log_sync(listener, &mrs);
2249 flatview_unref(view);
2250 trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 0);
2251 } else if (listener->log_sync_global) {
2253 * No matter whether MR is specified, what we can do here
2254 * is to do a global sync, because we are not capable to
2255 * sync in a finer granularity.
2257 listener->log_sync_global(listener);
2258 trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 1);
2263 void memory_region_clear_dirty_bitmap(MemoryRegion *mr, hwaddr start,
2264 hwaddr len)
2266 MemoryRegionSection mrs;
2267 MemoryListener *listener;
2268 AddressSpace *as;
2269 FlatView *view;
2270 FlatRange *fr;
2271 hwaddr sec_start, sec_end, sec_size;
2273 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2274 if (!listener->log_clear) {
2275 continue;
2277 as = listener->address_space;
2278 view = address_space_get_flatview(as);
2279 FOR_EACH_FLAT_RANGE(fr, view) {
2280 if (!fr->dirty_log_mask || fr->mr != mr) {
2282 * Clear dirty bitmap operation only applies to those
2283 * regions whose dirty logging is at least enabled
2285 continue;
2288 mrs = section_from_flat_range(fr, view);
2290 sec_start = MAX(mrs.offset_within_region, start);
2291 sec_end = mrs.offset_within_region + int128_get64(mrs.size);
2292 sec_end = MIN(sec_end, start + len);
2294 if (sec_start >= sec_end) {
2296 * If this memory region section has no intersection
2297 * with the requested range, skip.
2299 continue;
2302 /* Valid case; shrink the section if needed */
2303 mrs.offset_within_address_space +=
2304 sec_start - mrs.offset_within_region;
2305 mrs.offset_within_region = sec_start;
2306 sec_size = sec_end - sec_start;
2307 mrs.size = int128_make64(sec_size);
2308 listener->log_clear(listener, &mrs);
2310 flatview_unref(view);
2314 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
2315 hwaddr addr,
2316 hwaddr size,
2317 unsigned client)
2319 DirtyBitmapSnapshot *snapshot;
2320 assert(mr->ram_block);
2321 memory_region_sync_dirty_bitmap(mr);
2322 snapshot = cpu_physical_memory_snapshot_and_clear_dirty(mr, addr, size, client);
2323 memory_global_after_dirty_log_sync();
2324 return snapshot;
2327 bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
2328 hwaddr addr, hwaddr size)
2330 assert(mr->ram_block);
2331 return cpu_physical_memory_snapshot_get_dirty(snap,
2332 memory_region_get_ram_addr(mr) + addr, size);
2335 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
2337 if (mr->readonly != readonly) {
2338 memory_region_transaction_begin();
2339 mr->readonly = readonly;
2340 memory_region_update_pending |= mr->enabled;
2341 memory_region_transaction_commit();
2345 void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile)
2347 if (mr->nonvolatile != nonvolatile) {
2348 memory_region_transaction_begin();
2349 mr->nonvolatile = nonvolatile;
2350 memory_region_update_pending |= mr->enabled;
2351 memory_region_transaction_commit();
2355 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
2357 if (mr->romd_mode != romd_mode) {
2358 memory_region_transaction_begin();
2359 mr->romd_mode = romd_mode;
2360 memory_region_update_pending |= mr->enabled;
2361 memory_region_transaction_commit();
2365 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
2366 hwaddr size, unsigned client)
2368 assert(mr->ram_block);
2369 cpu_physical_memory_test_and_clear_dirty(
2370 memory_region_get_ram_addr(mr) + addr, size, client);
2373 int memory_region_get_fd(MemoryRegion *mr)
2375 RCU_READ_LOCK_GUARD();
2376 while (mr->alias) {
2377 mr = mr->alias;
2379 return mr->ram_block->fd;
2382 void *memory_region_get_ram_ptr(MemoryRegion *mr)
2384 uint64_t offset = 0;
2386 RCU_READ_LOCK_GUARD();
2387 while (mr->alias) {
2388 offset += mr->alias_offset;
2389 mr = mr->alias;
2391 assert(mr->ram_block);
2392 return qemu_map_ram_ptr(mr->ram_block, offset);
2395 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
2397 RAMBlock *block;
2399 block = qemu_ram_block_from_host(ptr, false, offset);
2400 if (!block) {
2401 return NULL;
2404 return block->mr;
2407 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
2409 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
2412 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
2414 assert(mr->ram_block);
2416 qemu_ram_resize(mr->ram_block, newsize, errp);
2419 void memory_region_msync(MemoryRegion *mr, hwaddr addr, hwaddr size)
2421 if (mr->ram_block) {
2422 qemu_ram_msync(mr->ram_block, addr, size);
2426 void memory_region_writeback(MemoryRegion *mr, hwaddr addr, hwaddr size)
2429 * Might be extended case needed to cover
2430 * different types of memory regions
2432 if (mr->dirty_log_mask) {
2433 memory_region_msync(mr, addr, size);
2438 * Call proper memory listeners about the change on the newly
2439 * added/removed CoalescedMemoryRange.
2441 static void memory_region_update_coalesced_range(MemoryRegion *mr,
2442 CoalescedMemoryRange *cmr,
2443 bool add)
2445 AddressSpace *as;
2446 FlatView *view;
2447 FlatRange *fr;
2449 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2450 view = address_space_get_flatview(as);
2451 FOR_EACH_FLAT_RANGE(fr, view) {
2452 if (fr->mr == mr) {
2453 flat_range_coalesced_io_notify(fr, as, cmr, add);
2456 flatview_unref(view);
2460 void memory_region_set_coalescing(MemoryRegion *mr)
2462 memory_region_clear_coalescing(mr);
2463 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
2466 void memory_region_add_coalescing(MemoryRegion *mr,
2467 hwaddr offset,
2468 uint64_t size)
2470 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
2472 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
2473 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
2474 memory_region_update_coalesced_range(mr, cmr, true);
2475 memory_region_set_flush_coalesced(mr);
2478 void memory_region_clear_coalescing(MemoryRegion *mr)
2480 CoalescedMemoryRange *cmr;
2482 if (QTAILQ_EMPTY(&mr->coalesced)) {
2483 return;
2486 qemu_flush_coalesced_mmio_buffer();
2487 mr->flush_coalesced_mmio = false;
2489 while (!QTAILQ_EMPTY(&mr->coalesced)) {
2490 cmr = QTAILQ_FIRST(&mr->coalesced);
2491 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
2492 memory_region_update_coalesced_range(mr, cmr, false);
2493 g_free(cmr);
2497 void memory_region_set_flush_coalesced(MemoryRegion *mr)
2499 mr->flush_coalesced_mmio = true;
2502 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
2504 qemu_flush_coalesced_mmio_buffer();
2505 if (QTAILQ_EMPTY(&mr->coalesced)) {
2506 mr->flush_coalesced_mmio = false;
2510 static bool userspace_eventfd_warning;
2512 void memory_region_add_eventfd(MemoryRegion *mr,
2513 hwaddr addr,
2514 unsigned size,
2515 bool match_data,
2516 uint64_t data,
2517 EventNotifier *e)
2519 MemoryRegionIoeventfd mrfd = {
2520 .addr.start = int128_make64(addr),
2521 .addr.size = int128_make64(size),
2522 .match_data = match_data,
2523 .data = data,
2524 .e = e,
2526 unsigned i;
2528 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
2529 userspace_eventfd_warning))) {
2530 userspace_eventfd_warning = true;
2531 error_report("Using eventfd without MMIO binding in KVM. "
2532 "Suboptimal performance expected");
2535 if (size) {
2536 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2538 memory_region_transaction_begin();
2539 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2540 if (memory_region_ioeventfd_before(&mrfd, &mr->ioeventfds[i])) {
2541 break;
2544 ++mr->ioeventfd_nb;
2545 mr->ioeventfds = g_realloc(mr->ioeventfds,
2546 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2547 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2548 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2549 mr->ioeventfds[i] = mrfd;
2550 ioeventfd_update_pending |= mr->enabled;
2551 memory_region_transaction_commit();
2554 void memory_region_del_eventfd(MemoryRegion *mr,
2555 hwaddr addr,
2556 unsigned size,
2557 bool match_data,
2558 uint64_t data,
2559 EventNotifier *e)
2561 MemoryRegionIoeventfd mrfd = {
2562 .addr.start = int128_make64(addr),
2563 .addr.size = int128_make64(size),
2564 .match_data = match_data,
2565 .data = data,
2566 .e = e,
2568 unsigned i;
2570 if (size) {
2571 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2573 memory_region_transaction_begin();
2574 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2575 if (memory_region_ioeventfd_equal(&mrfd, &mr->ioeventfds[i])) {
2576 break;
2579 assert(i != mr->ioeventfd_nb);
2580 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2581 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2582 --mr->ioeventfd_nb;
2583 mr->ioeventfds = g_realloc(mr->ioeventfds,
2584 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
2585 ioeventfd_update_pending |= mr->enabled;
2586 memory_region_transaction_commit();
2589 static void memory_region_update_container_subregions(MemoryRegion *subregion)
2591 MemoryRegion *mr = subregion->container;
2592 MemoryRegion *other;
2594 memory_region_transaction_begin();
2596 memory_region_ref(subregion);
2597 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2598 if (subregion->priority >= other->priority) {
2599 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2600 goto done;
2603 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2604 done:
2605 memory_region_update_pending |= mr->enabled && subregion->enabled;
2606 memory_region_transaction_commit();
2609 static void memory_region_add_subregion_common(MemoryRegion *mr,
2610 hwaddr offset,
2611 MemoryRegion *subregion)
2613 MemoryRegion *alias;
2615 assert(!subregion->container);
2616 subregion->container = mr;
2617 for (alias = subregion->alias; alias; alias = alias->alias) {
2618 alias->mapped_via_alias++;
2620 subregion->addr = offset;
2621 memory_region_update_container_subregions(subregion);
2624 void memory_region_add_subregion(MemoryRegion *mr,
2625 hwaddr offset,
2626 MemoryRegion *subregion)
2628 subregion->priority = 0;
2629 memory_region_add_subregion_common(mr, offset, subregion);
2632 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2633 hwaddr offset,
2634 MemoryRegion *subregion,
2635 int priority)
2637 subregion->priority = priority;
2638 memory_region_add_subregion_common(mr, offset, subregion);
2641 void memory_region_del_subregion(MemoryRegion *mr,
2642 MemoryRegion *subregion)
2644 MemoryRegion *alias;
2646 memory_region_transaction_begin();
2647 assert(subregion->container == mr);
2648 subregion->container = NULL;
2649 for (alias = subregion->alias; alias; alias = alias->alias) {
2650 alias->mapped_via_alias--;
2651 assert(alias->mapped_via_alias >= 0);
2653 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
2654 memory_region_unref(subregion);
2655 memory_region_update_pending |= mr->enabled && subregion->enabled;
2656 memory_region_transaction_commit();
2659 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2661 if (enabled == mr->enabled) {
2662 return;
2664 memory_region_transaction_begin();
2665 mr->enabled = enabled;
2666 memory_region_update_pending = true;
2667 memory_region_transaction_commit();
2670 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2672 Int128 s = int128_make64(size);
2674 if (size == UINT64_MAX) {
2675 s = int128_2_64();
2677 if (int128_eq(s, mr->size)) {
2678 return;
2680 memory_region_transaction_begin();
2681 mr->size = s;
2682 memory_region_update_pending = true;
2683 memory_region_transaction_commit();
2686 static void memory_region_readd_subregion(MemoryRegion *mr)
2688 MemoryRegion *container = mr->container;
2690 if (container) {
2691 memory_region_transaction_begin();
2692 memory_region_ref(mr);
2693 memory_region_del_subregion(container, mr);
2694 memory_region_add_subregion_common(container, mr->addr, mr);
2695 memory_region_unref(mr);
2696 memory_region_transaction_commit();
2700 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2702 if (addr != mr->addr) {
2703 mr->addr = addr;
2704 memory_region_readd_subregion(mr);
2708 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
2710 assert(mr->alias);
2712 if (offset == mr->alias_offset) {
2713 return;
2716 memory_region_transaction_begin();
2717 mr->alias_offset = offset;
2718 memory_region_update_pending |= mr->enabled;
2719 memory_region_transaction_commit();
2722 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2724 return mr->align;
2727 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2729 const AddrRange *addr = addr_;
2730 const FlatRange *fr = fr_;
2732 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2733 return -1;
2734 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2735 return 1;
2737 return 0;
2740 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
2742 return bsearch(&addr, view->ranges, view->nr,
2743 sizeof(FlatRange), cmp_flatrange_addr);
2746 bool memory_region_is_mapped(MemoryRegion *mr)
2748 return !!mr->container || mr->mapped_via_alias;
2751 /* Same as memory_region_find, but it does not add a reference to the
2752 * returned region. It must be called from an RCU critical section.
2754 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2755 hwaddr addr, uint64_t size)
2757 MemoryRegionSection ret = { .mr = NULL };
2758 MemoryRegion *root;
2759 AddressSpace *as;
2760 AddrRange range;
2761 FlatView *view;
2762 FlatRange *fr;
2764 addr += mr->addr;
2765 for (root = mr; root->container; ) {
2766 root = root->container;
2767 addr += root->addr;
2770 as = memory_region_to_address_space(root);
2771 if (!as) {
2772 return ret;
2774 range = addrrange_make(int128_make64(addr), int128_make64(size));
2776 view = address_space_to_flatview(as);
2777 fr = flatview_lookup(view, range);
2778 if (!fr) {
2779 return ret;
2782 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2783 --fr;
2786 ret.mr = fr->mr;
2787 ret.fv = view;
2788 range = addrrange_intersection(range, fr->addr);
2789 ret.offset_within_region = fr->offset_in_region;
2790 ret.offset_within_region += int128_get64(int128_sub(range.start,
2791 fr->addr.start));
2792 ret.size = range.size;
2793 ret.offset_within_address_space = int128_get64(range.start);
2794 ret.readonly = fr->readonly;
2795 ret.nonvolatile = fr->nonvolatile;
2796 return ret;
2799 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2800 hwaddr addr, uint64_t size)
2802 MemoryRegionSection ret;
2803 RCU_READ_LOCK_GUARD();
2804 ret = memory_region_find_rcu(mr, addr, size);
2805 if (ret.mr) {
2806 memory_region_ref(ret.mr);
2808 return ret;
2811 MemoryRegionSection *memory_region_section_new_copy(MemoryRegionSection *s)
2813 MemoryRegionSection *tmp = g_new(MemoryRegionSection, 1);
2815 *tmp = *s;
2816 if (tmp->mr) {
2817 memory_region_ref(tmp->mr);
2819 if (tmp->fv) {
2820 bool ret = flatview_ref(tmp->fv);
2822 g_assert(ret);
2824 return tmp;
2827 void memory_region_section_free_copy(MemoryRegionSection *s)
2829 if (s->fv) {
2830 flatview_unref(s->fv);
2832 if (s->mr) {
2833 memory_region_unref(s->mr);
2835 g_free(s);
2838 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2840 MemoryRegion *mr;
2842 RCU_READ_LOCK_GUARD();
2843 mr = memory_region_find_rcu(container, addr, 1).mr;
2844 return mr && mr != container;
2847 void memory_global_dirty_log_sync(void)
2849 memory_region_sync_dirty_bitmap(NULL);
2852 void memory_global_after_dirty_log_sync(void)
2854 MEMORY_LISTENER_CALL_GLOBAL(log_global_after_sync, Forward);
2858 * Dirty track stop flags that are postponed due to VM being stopped. Should
2859 * only be used within vmstate_change hook.
2861 static unsigned int postponed_stop_flags;
2862 static VMChangeStateEntry *vmstate_change;
2863 static void memory_global_dirty_log_stop_postponed_run(void);
2865 void memory_global_dirty_log_start(unsigned int flags)
2867 unsigned int old_flags;
2869 assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2871 if (vmstate_change) {
2872 /* If there is postponed stop(), operate on it first */
2873 postponed_stop_flags &= ~flags;
2874 memory_global_dirty_log_stop_postponed_run();
2877 flags &= ~global_dirty_tracking;
2878 if (!flags) {
2879 return;
2882 old_flags = global_dirty_tracking;
2883 global_dirty_tracking |= flags;
2884 trace_global_dirty_changed(global_dirty_tracking);
2886 if (!old_flags) {
2887 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2888 memory_region_transaction_begin();
2889 memory_region_update_pending = true;
2890 memory_region_transaction_commit();
2894 static void memory_global_dirty_log_do_stop(unsigned int flags)
2896 assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2897 assert((global_dirty_tracking & flags) == flags);
2898 global_dirty_tracking &= ~flags;
2900 trace_global_dirty_changed(global_dirty_tracking);
2902 if (!global_dirty_tracking) {
2903 memory_region_transaction_begin();
2904 memory_region_update_pending = true;
2905 memory_region_transaction_commit();
2906 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2911 * Execute the postponed dirty log stop operations if there is, then reset
2912 * everything (including the flags and the vmstate change hook).
2914 static void memory_global_dirty_log_stop_postponed_run(void)
2916 /* This must be called with the vmstate handler registered */
2917 assert(vmstate_change);
2919 /* Note: postponed_stop_flags can be cleared in log start routine */
2920 if (postponed_stop_flags) {
2921 memory_global_dirty_log_do_stop(postponed_stop_flags);
2922 postponed_stop_flags = 0;
2925 qemu_del_vm_change_state_handler(vmstate_change);
2926 vmstate_change = NULL;
2929 static void memory_vm_change_state_handler(void *opaque, bool running,
2930 RunState state)
2932 if (running) {
2933 memory_global_dirty_log_stop_postponed_run();
2937 void memory_global_dirty_log_stop(unsigned int flags)
2939 if (!runstate_is_running()) {
2940 /* Postpone the dirty log stop, e.g., to when VM starts again */
2941 if (vmstate_change) {
2942 /* Batch with previous postponed flags */
2943 postponed_stop_flags |= flags;
2944 } else {
2945 postponed_stop_flags = flags;
2946 vmstate_change = qemu_add_vm_change_state_handler(
2947 memory_vm_change_state_handler, NULL);
2949 return;
2952 memory_global_dirty_log_do_stop(flags);
2955 static void listener_add_address_space(MemoryListener *listener,
2956 AddressSpace *as)
2958 FlatView *view;
2959 FlatRange *fr;
2961 if (listener->begin) {
2962 listener->begin(listener);
2964 if (global_dirty_tracking) {
2965 if (listener->log_global_start) {
2966 listener->log_global_start(listener);
2970 view = address_space_get_flatview(as);
2971 FOR_EACH_FLAT_RANGE(fr, view) {
2972 MemoryRegionSection section = section_from_flat_range(fr, view);
2974 if (listener->region_add) {
2975 listener->region_add(listener, &section);
2977 if (fr->dirty_log_mask && listener->log_start) {
2978 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2981 if (listener->commit) {
2982 listener->commit(listener);
2984 flatview_unref(view);
2987 static void listener_del_address_space(MemoryListener *listener,
2988 AddressSpace *as)
2990 FlatView *view;
2991 FlatRange *fr;
2993 if (listener->begin) {
2994 listener->begin(listener);
2996 view = address_space_get_flatview(as);
2997 FOR_EACH_FLAT_RANGE(fr, view) {
2998 MemoryRegionSection section = section_from_flat_range(fr, view);
3000 if (fr->dirty_log_mask && listener->log_stop) {
3001 listener->log_stop(listener, &section, fr->dirty_log_mask, 0);
3003 if (listener->region_del) {
3004 listener->region_del(listener, &section);
3007 if (listener->commit) {
3008 listener->commit(listener);
3010 flatview_unref(view);
3013 void memory_listener_register(MemoryListener *listener, AddressSpace *as)
3015 MemoryListener *other = NULL;
3017 /* Only one of them can be defined for a listener */
3018 assert(!(listener->log_sync && listener->log_sync_global));
3020 listener->address_space = as;
3021 if (QTAILQ_EMPTY(&memory_listeners)
3022 || listener->priority >= QTAILQ_LAST(&memory_listeners)->priority) {
3023 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
3024 } else {
3025 QTAILQ_FOREACH(other, &memory_listeners, link) {
3026 if (listener->priority < other->priority) {
3027 break;
3030 QTAILQ_INSERT_BEFORE(other, listener, link);
3033 if (QTAILQ_EMPTY(&as->listeners)
3034 || listener->priority >= QTAILQ_LAST(&as->listeners)->priority) {
3035 QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
3036 } else {
3037 QTAILQ_FOREACH(other, &as->listeners, link_as) {
3038 if (listener->priority < other->priority) {
3039 break;
3042 QTAILQ_INSERT_BEFORE(other, listener, link_as);
3045 listener_add_address_space(listener, as);
3048 void memory_listener_unregister(MemoryListener *listener)
3050 if (!listener->address_space) {
3051 return;
3054 listener_del_address_space(listener, listener->address_space);
3055 QTAILQ_REMOVE(&memory_listeners, listener, link);
3056 QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
3057 listener->address_space = NULL;
3060 void address_space_remove_listeners(AddressSpace *as)
3062 while (!QTAILQ_EMPTY(&as->listeners)) {
3063 memory_listener_unregister(QTAILQ_FIRST(&as->listeners));
3067 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
3069 memory_region_ref(root);
3070 as->root = root;
3071 as->current_map = NULL;
3072 as->ioeventfd_nb = 0;
3073 as->ioeventfds = NULL;
3074 QTAILQ_INIT(&as->listeners);
3075 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
3076 as->name = g_strdup(name ? name : "anonymous");
3077 address_space_update_topology(as);
3078 address_space_update_ioeventfds(as);
3081 static void do_address_space_destroy(AddressSpace *as)
3083 assert(QTAILQ_EMPTY(&as->listeners));
3085 flatview_unref(as->current_map);
3086 g_free(as->name);
3087 g_free(as->ioeventfds);
3088 memory_region_unref(as->root);
3091 void address_space_destroy(AddressSpace *as)
3093 MemoryRegion *root = as->root;
3095 /* Flush out anything from MemoryListeners listening in on this */
3096 memory_region_transaction_begin();
3097 as->root = NULL;
3098 memory_region_transaction_commit();
3099 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
3101 /* At this point, as->dispatch and as->current_map are dummy
3102 * entries that the guest should never use. Wait for the old
3103 * values to expire before freeing the data.
3105 as->root = root;
3106 call_rcu(as, do_address_space_destroy, rcu);
3109 static const char *memory_region_type(MemoryRegion *mr)
3111 if (mr->alias) {
3112 return memory_region_type(mr->alias);
3114 if (memory_region_is_ram_device(mr)) {
3115 return "ramd";
3116 } else if (memory_region_is_romd(mr)) {
3117 return "romd";
3118 } else if (memory_region_is_rom(mr)) {
3119 return "rom";
3120 } else if (memory_region_is_ram(mr)) {
3121 return "ram";
3122 } else {
3123 return "i/o";
3127 typedef struct MemoryRegionList MemoryRegionList;
3129 struct MemoryRegionList {
3130 const MemoryRegion *mr;
3131 QTAILQ_ENTRY(MemoryRegionList) mrqueue;
3134 typedef QTAILQ_HEAD(, MemoryRegionList) MemoryRegionListHead;
3136 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3137 int128_sub((size), int128_one())) : 0)
3138 #define MTREE_INDENT " "
3140 static void mtree_expand_owner(const char *label, Object *obj)
3142 DeviceState *dev = (DeviceState *) object_dynamic_cast(obj, TYPE_DEVICE);
3144 qemu_printf(" %s:{%s", label, dev ? "dev" : "obj");
3145 if (dev && dev->id) {
3146 qemu_printf(" id=%s", dev->id);
3147 } else {
3148 char *canonical_path = object_get_canonical_path(obj);
3149 if (canonical_path) {
3150 qemu_printf(" path=%s", canonical_path);
3151 g_free(canonical_path);
3152 } else {
3153 qemu_printf(" type=%s", object_get_typename(obj));
3156 qemu_printf("}");
3159 static void mtree_print_mr_owner(const MemoryRegion *mr)
3161 Object *owner = mr->owner;
3162 Object *parent = memory_region_owner((MemoryRegion *)mr);
3164 if (!owner && !parent) {
3165 qemu_printf(" orphan");
3166 return;
3168 if (owner) {
3169 mtree_expand_owner("owner", owner);
3171 if (parent && parent != owner) {
3172 mtree_expand_owner("parent", parent);
3176 static void mtree_print_mr(const MemoryRegion *mr, unsigned int level,
3177 hwaddr base,
3178 MemoryRegionListHead *alias_print_queue,
3179 bool owner, bool display_disabled)
3181 MemoryRegionList *new_ml, *ml, *next_ml;
3182 MemoryRegionListHead submr_print_queue;
3183 const MemoryRegion *submr;
3184 unsigned int i;
3185 hwaddr cur_start, cur_end;
3187 if (!mr) {
3188 return;
3191 cur_start = base + mr->addr;
3192 cur_end = cur_start + MR_SIZE(mr->size);
3195 * Try to detect overflow of memory region. This should never
3196 * happen normally. When it happens, we dump something to warn the
3197 * user who is observing this.
3199 if (cur_start < base || cur_end < cur_start) {
3200 qemu_printf("[DETECTED OVERFLOW!] ");
3203 if (mr->alias) {
3204 MemoryRegionList *ml;
3205 bool found = false;
3207 /* check if the alias is already in the queue */
3208 QTAILQ_FOREACH(ml, alias_print_queue, mrqueue) {
3209 if (ml->mr == mr->alias) {
3210 found = true;
3214 if (!found) {
3215 ml = g_new(MemoryRegionList, 1);
3216 ml->mr = mr->alias;
3217 QTAILQ_INSERT_TAIL(alias_print_queue, ml, mrqueue);
3219 if (mr->enabled || display_disabled) {
3220 for (i = 0; i < level; i++) {
3221 qemu_printf(MTREE_INDENT);
3223 qemu_printf(HWADDR_FMT_plx "-" HWADDR_FMT_plx
3224 " (prio %d, %s%s): alias %s @%s " HWADDR_FMT_plx
3225 "-" HWADDR_FMT_plx "%s",
3226 cur_start, cur_end,
3227 mr->priority,
3228 mr->nonvolatile ? "nv-" : "",
3229 memory_region_type((MemoryRegion *)mr),
3230 memory_region_name(mr),
3231 memory_region_name(mr->alias),
3232 mr->alias_offset,
3233 mr->alias_offset + MR_SIZE(mr->size),
3234 mr->enabled ? "" : " [disabled]");
3235 if (owner) {
3236 mtree_print_mr_owner(mr);
3238 qemu_printf("\n");
3240 } else {
3241 if (mr->enabled || display_disabled) {
3242 for (i = 0; i < level; i++) {
3243 qemu_printf(MTREE_INDENT);
3245 qemu_printf(HWADDR_FMT_plx "-" HWADDR_FMT_plx
3246 " (prio %d, %s%s): %s%s",
3247 cur_start, cur_end,
3248 mr->priority,
3249 mr->nonvolatile ? "nv-" : "",
3250 memory_region_type((MemoryRegion *)mr),
3251 memory_region_name(mr),
3252 mr->enabled ? "" : " [disabled]");
3253 if (owner) {
3254 mtree_print_mr_owner(mr);
3256 qemu_printf("\n");
3260 QTAILQ_INIT(&submr_print_queue);
3262 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
3263 new_ml = g_new(MemoryRegionList, 1);
3264 new_ml->mr = submr;
3265 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3266 if (new_ml->mr->addr < ml->mr->addr ||
3267 (new_ml->mr->addr == ml->mr->addr &&
3268 new_ml->mr->priority > ml->mr->priority)) {
3269 QTAILQ_INSERT_BEFORE(ml, new_ml, mrqueue);
3270 new_ml = NULL;
3271 break;
3274 if (new_ml) {
3275 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, mrqueue);
3279 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3280 mtree_print_mr(ml->mr, level + 1, cur_start,
3281 alias_print_queue, owner, display_disabled);
3284 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, mrqueue, next_ml) {
3285 g_free(ml);
3289 struct FlatViewInfo {
3290 int counter;
3291 bool dispatch_tree;
3292 bool owner;
3293 AccelClass *ac;
3296 static void mtree_print_flatview(gpointer key, gpointer value,
3297 gpointer user_data)
3299 FlatView *view = key;
3300 GArray *fv_address_spaces = value;
3301 struct FlatViewInfo *fvi = user_data;
3302 FlatRange *range = &view->ranges[0];
3303 MemoryRegion *mr;
3304 int n = view->nr;
3305 int i;
3306 AddressSpace *as;
3308 qemu_printf("FlatView #%d\n", fvi->counter);
3309 ++fvi->counter;
3311 for (i = 0; i < fv_address_spaces->len; ++i) {
3312 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3313 qemu_printf(" AS \"%s\", root: %s",
3314 as->name, memory_region_name(as->root));
3315 if (as->root->alias) {
3316 qemu_printf(", alias %s", memory_region_name(as->root->alias));
3318 qemu_printf("\n");
3321 qemu_printf(" Root memory region: %s\n",
3322 view->root ? memory_region_name(view->root) : "(none)");
3324 if (n <= 0) {
3325 qemu_printf(MTREE_INDENT "No rendered FlatView\n\n");
3326 return;
3329 while (n--) {
3330 mr = range->mr;
3331 if (range->offset_in_region) {
3332 qemu_printf(MTREE_INDENT HWADDR_FMT_plx "-" HWADDR_FMT_plx
3333 " (prio %d, %s%s): %s @" HWADDR_FMT_plx,
3334 int128_get64(range->addr.start),
3335 int128_get64(range->addr.start)
3336 + MR_SIZE(range->addr.size),
3337 mr->priority,
3338 range->nonvolatile ? "nv-" : "",
3339 range->readonly ? "rom" : memory_region_type(mr),
3340 memory_region_name(mr),
3341 range->offset_in_region);
3342 } else {
3343 qemu_printf(MTREE_INDENT HWADDR_FMT_plx "-" HWADDR_FMT_plx
3344 " (prio %d, %s%s): %s",
3345 int128_get64(range->addr.start),
3346 int128_get64(range->addr.start)
3347 + MR_SIZE(range->addr.size),
3348 mr->priority,
3349 range->nonvolatile ? "nv-" : "",
3350 range->readonly ? "rom" : memory_region_type(mr),
3351 memory_region_name(mr));
3353 if (fvi->owner) {
3354 mtree_print_mr_owner(mr);
3357 if (fvi->ac) {
3358 for (i = 0; i < fv_address_spaces->len; ++i) {
3359 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3360 if (fvi->ac->has_memory(current_machine, as,
3361 int128_get64(range->addr.start),
3362 MR_SIZE(range->addr.size) + 1)) {
3363 qemu_printf(" %s", fvi->ac->name);
3367 qemu_printf("\n");
3368 range++;
3371 #if !defined(CONFIG_USER_ONLY)
3372 if (fvi->dispatch_tree && view->root) {
3373 mtree_print_dispatch(view->dispatch, view->root);
3375 #endif
3377 qemu_printf("\n");
3380 static gboolean mtree_info_flatview_free(gpointer key, gpointer value,
3381 gpointer user_data)
3383 FlatView *view = key;
3384 GArray *fv_address_spaces = value;
3386 g_array_unref(fv_address_spaces);
3387 flatview_unref(view);
3389 return true;
3392 static void mtree_info_flatview(bool dispatch_tree, bool owner)
3394 struct FlatViewInfo fvi = {
3395 .counter = 0,
3396 .dispatch_tree = dispatch_tree,
3397 .owner = owner,
3399 AddressSpace *as;
3400 FlatView *view;
3401 GArray *fv_address_spaces;
3402 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3403 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
3405 if (ac->has_memory) {
3406 fvi.ac = ac;
3409 /* Gather all FVs in one table */
3410 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3411 view = address_space_get_flatview(as);
3413 fv_address_spaces = g_hash_table_lookup(views, view);
3414 if (!fv_address_spaces) {
3415 fv_address_spaces = g_array_new(false, false, sizeof(as));
3416 g_hash_table_insert(views, view, fv_address_spaces);
3419 g_array_append_val(fv_address_spaces, as);
3422 /* Print */
3423 g_hash_table_foreach(views, mtree_print_flatview, &fvi);
3425 /* Free */
3426 g_hash_table_foreach_remove(views, mtree_info_flatview_free, 0);
3427 g_hash_table_unref(views);
3430 struct AddressSpaceInfo {
3431 MemoryRegionListHead *ml_head;
3432 bool owner;
3433 bool disabled;
3436 /* Returns negative value if a < b; zero if a = b; positive value if a > b. */
3437 static gint address_space_compare_name(gconstpointer a, gconstpointer b)
3439 const AddressSpace *as_a = a;
3440 const AddressSpace *as_b = b;
3442 return g_strcmp0(as_a->name, as_b->name);
3445 static void mtree_print_as_name(gpointer data, gpointer user_data)
3447 AddressSpace *as = data;
3449 qemu_printf("address-space: %s\n", as->name);
3452 static void mtree_print_as(gpointer key, gpointer value, gpointer user_data)
3454 MemoryRegion *mr = key;
3455 GSList *as_same_root_mr_list = value;
3456 struct AddressSpaceInfo *asi = user_data;
3458 g_slist_foreach(as_same_root_mr_list, mtree_print_as_name, NULL);
3459 mtree_print_mr(mr, 1, 0, asi->ml_head, asi->owner, asi->disabled);
3460 qemu_printf("\n");
3463 static gboolean mtree_info_as_free(gpointer key, gpointer value,
3464 gpointer user_data)
3466 GSList *as_same_root_mr_list = value;
3468 g_slist_free(as_same_root_mr_list);
3470 return true;
3473 static void mtree_info_as(bool dispatch_tree, bool owner, bool disabled)
3475 MemoryRegionListHead ml_head;
3476 MemoryRegionList *ml, *ml2;
3477 AddressSpace *as;
3478 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3479 GSList *as_same_root_mr_list;
3480 struct AddressSpaceInfo asi = {
3481 .ml_head = &ml_head,
3482 .owner = owner,
3483 .disabled = disabled,
3486 QTAILQ_INIT(&ml_head);
3488 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3489 /* Create hashtable, key=AS root MR, value = list of AS */
3490 as_same_root_mr_list = g_hash_table_lookup(views, as->root);
3491 as_same_root_mr_list = g_slist_insert_sorted(as_same_root_mr_list, as,
3492 address_space_compare_name);
3493 g_hash_table_insert(views, as->root, as_same_root_mr_list);
3496 /* print address spaces */
3497 g_hash_table_foreach(views, mtree_print_as, &asi);
3498 g_hash_table_foreach_remove(views, mtree_info_as_free, 0);
3499 g_hash_table_unref(views);
3501 /* print aliased regions */
3502 QTAILQ_FOREACH(ml, &ml_head, mrqueue) {
3503 qemu_printf("memory-region: %s\n", memory_region_name(ml->mr));
3504 mtree_print_mr(ml->mr, 1, 0, &ml_head, owner, disabled);
3505 qemu_printf("\n");
3508 QTAILQ_FOREACH_SAFE(ml, &ml_head, mrqueue, ml2) {
3509 g_free(ml);
3513 void mtree_info(bool flatview, bool dispatch_tree, bool owner, bool disabled)
3515 if (flatview) {
3516 mtree_info_flatview(dispatch_tree, owner);
3517 } else {
3518 mtree_info_as(dispatch_tree, owner, disabled);
3522 void memory_region_init_ram(MemoryRegion *mr,
3523 Object *owner,
3524 const char *name,
3525 uint64_t size,
3526 Error **errp)
3528 DeviceState *owner_dev;
3529 Error *err = NULL;
3531 memory_region_init_ram_nomigrate(mr, owner, name, size, &err);
3532 if (err) {
3533 error_propagate(errp, err);
3534 return;
3536 /* This will assert if owner is neither NULL nor a DeviceState.
3537 * We only want the owner here for the purposes of defining a
3538 * unique name for migration. TODO: Ideally we should implement
3539 * a naming scheme for Objects which are not DeviceStates, in
3540 * which case we can relax this restriction.
3542 owner_dev = DEVICE(owner);
3543 vmstate_register_ram(mr, owner_dev);
3546 void memory_region_init_rom(MemoryRegion *mr,
3547 Object *owner,
3548 const char *name,
3549 uint64_t size,
3550 Error **errp)
3552 DeviceState *owner_dev;
3553 Error *err = NULL;
3555 memory_region_init_rom_nomigrate(mr, owner, name, size, &err);
3556 if (err) {
3557 error_propagate(errp, err);
3558 return;
3560 /* This will assert if owner is neither NULL nor a DeviceState.
3561 * We only want the owner here for the purposes of defining a
3562 * unique name for migration. TODO: Ideally we should implement
3563 * a naming scheme for Objects which are not DeviceStates, in
3564 * which case we can relax this restriction.
3566 owner_dev = DEVICE(owner);
3567 vmstate_register_ram(mr, owner_dev);
3570 void memory_region_init_rom_device(MemoryRegion *mr,
3571 Object *owner,
3572 const MemoryRegionOps *ops,
3573 void *opaque,
3574 const char *name,
3575 uint64_t size,
3576 Error **errp)
3578 DeviceState *owner_dev;
3579 Error *err = NULL;
3581 memory_region_init_rom_device_nomigrate(mr, owner, ops, opaque,
3582 name, size, &err);
3583 if (err) {
3584 error_propagate(errp, err);
3585 return;
3587 /* This will assert if owner is neither NULL nor a DeviceState.
3588 * We only want the owner here for the purposes of defining a
3589 * unique name for migration. TODO: Ideally we should implement
3590 * a naming scheme for Objects which are not DeviceStates, in
3591 * which case we can relax this restriction.
3593 owner_dev = DEVICE(owner);
3594 vmstate_register_ram(mr, owner_dev);
3598 * Support softmmu builds with CONFIG_FUZZ using a weak symbol and a stub for
3599 * the fuzz_dma_read_cb callback
3601 #ifdef CONFIG_FUZZ
3602 void __attribute__((weak)) fuzz_dma_read_cb(size_t addr,
3603 size_t len,
3604 MemoryRegion *mr)
3607 #endif
3609 static const TypeInfo memory_region_info = {
3610 .parent = TYPE_OBJECT,
3611 .name = TYPE_MEMORY_REGION,
3612 .class_size = sizeof(MemoryRegionClass),
3613 .instance_size = sizeof(MemoryRegion),
3614 .instance_init = memory_region_initfn,
3615 .instance_finalize = memory_region_finalize,
3618 static const TypeInfo iommu_memory_region_info = {
3619 .parent = TYPE_MEMORY_REGION,
3620 .name = TYPE_IOMMU_MEMORY_REGION,
3621 .class_size = sizeof(IOMMUMemoryRegionClass),
3622 .instance_size = sizeof(IOMMUMemoryRegion),
3623 .instance_init = iommu_memory_region_initfn,
3624 .abstract = true,
3627 static const TypeInfo ram_discard_manager_info = {
3628 .parent = TYPE_INTERFACE,
3629 .name = TYPE_RAM_DISCARD_MANAGER,
3630 .class_size = sizeof(RamDiscardManagerClass),
3633 static void memory_register_types(void)
3635 type_register_static(&memory_region_info);
3636 type_register_static(&iommu_memory_region_info);
3637 type_register_static(&ram_discard_manager_info);
3640 type_init(memory_register_types)