Revert "tests/requirements.txt: bump up avocado-framework version to 101.0"
[qemu/kevin.git] / softmmu / memory.c
blob7d9494ce7028d59f1b2bf8074f6af6908f0b6576
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;
537 bool reentrancy_guard_applied = false;
539 if (!access_size_min) {
540 access_size_min = 1;
542 if (!access_size_max) {
543 access_size_max = 4;
546 /* Do not allow more than one simultaneous access to a device's IO Regions */
547 if (mr->dev && !mr->disable_reentrancy_guard &&
548 !mr->ram_device && !mr->ram && !mr->rom_device && !mr->readonly) {
549 if (mr->dev->mem_reentrancy_guard.engaged_in_io) {
550 warn_report_once("Blocked re-entrant IO on MemoryRegion: "
551 "%s at addr: 0x%" HWADDR_PRIX,
552 memory_region_name(mr), addr);
553 return MEMTX_ACCESS_ERROR;
555 mr->dev->mem_reentrancy_guard.engaged_in_io = true;
556 reentrancy_guard_applied = true;
559 /* FIXME: support unaligned access? */
560 access_size = MAX(MIN(size, access_size_max), access_size_min);
561 access_mask = MAKE_64BIT_MASK(0, access_size * 8);
562 if (memory_region_big_endian(mr)) {
563 for (i = 0; i < size; i += access_size) {
564 r |= access_fn(mr, addr + i, value, access_size,
565 (size - access_size - i) * 8, access_mask, attrs);
567 } else {
568 for (i = 0; i < size; i += access_size) {
569 r |= access_fn(mr, addr + i, value, access_size, i * 8,
570 access_mask, attrs);
573 if (mr->dev && reentrancy_guard_applied) {
574 mr->dev->mem_reentrancy_guard.engaged_in_io = false;
576 return r;
579 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
581 AddressSpace *as;
583 while (mr->container) {
584 mr = mr->container;
586 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
587 if (mr == as->root) {
588 return as;
591 return NULL;
594 /* Render a memory region into the global view. Ranges in @view obscure
595 * ranges in @mr.
597 static void render_memory_region(FlatView *view,
598 MemoryRegion *mr,
599 Int128 base,
600 AddrRange clip,
601 bool readonly,
602 bool nonvolatile)
604 MemoryRegion *subregion;
605 unsigned i;
606 hwaddr offset_in_region;
607 Int128 remain;
608 Int128 now;
609 FlatRange fr;
610 AddrRange tmp;
612 if (!mr->enabled) {
613 return;
616 int128_addto(&base, int128_make64(mr->addr));
617 readonly |= mr->readonly;
618 nonvolatile |= mr->nonvolatile;
620 tmp = addrrange_make(base, mr->size);
622 if (!addrrange_intersects(tmp, clip)) {
623 return;
626 clip = addrrange_intersection(tmp, clip);
628 if (mr->alias) {
629 int128_subfrom(&base, int128_make64(mr->alias->addr));
630 int128_subfrom(&base, int128_make64(mr->alias_offset));
631 render_memory_region(view, mr->alias, base, clip,
632 readonly, nonvolatile);
633 return;
636 /* Render subregions in priority order. */
637 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
638 render_memory_region(view, subregion, base, clip,
639 readonly, nonvolatile);
642 if (!mr->terminates) {
643 return;
646 offset_in_region = int128_get64(int128_sub(clip.start, base));
647 base = clip.start;
648 remain = clip.size;
650 fr.mr = mr;
651 fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
652 fr.romd_mode = mr->romd_mode;
653 fr.readonly = readonly;
654 fr.nonvolatile = nonvolatile;
656 /* Render the region itself into any gaps left by the current view. */
657 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
658 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
659 continue;
661 if (int128_lt(base, view->ranges[i].addr.start)) {
662 now = int128_min(remain,
663 int128_sub(view->ranges[i].addr.start, base));
664 fr.offset_in_region = offset_in_region;
665 fr.addr = addrrange_make(base, now);
666 flatview_insert(view, i, &fr);
667 ++i;
668 int128_addto(&base, now);
669 offset_in_region += int128_get64(now);
670 int128_subfrom(&remain, now);
672 now = int128_sub(int128_min(int128_add(base, remain),
673 addrrange_end(view->ranges[i].addr)),
674 base);
675 int128_addto(&base, now);
676 offset_in_region += int128_get64(now);
677 int128_subfrom(&remain, now);
679 if (int128_nz(remain)) {
680 fr.offset_in_region = offset_in_region;
681 fr.addr = addrrange_make(base, remain);
682 flatview_insert(view, i, &fr);
686 void flatview_for_each_range(FlatView *fv, flatview_cb cb , void *opaque)
688 FlatRange *fr;
690 assert(fv);
691 assert(cb);
693 FOR_EACH_FLAT_RANGE(fr, fv) {
694 if (cb(fr->addr.start, fr->addr.size, fr->mr,
695 fr->offset_in_region, opaque)) {
696 break;
701 static MemoryRegion *memory_region_get_flatview_root(MemoryRegion *mr)
703 while (mr->enabled) {
704 if (mr->alias) {
705 if (!mr->alias_offset && int128_ge(mr->size, mr->alias->size)) {
706 /* The alias is included in its entirety. Use it as
707 * the "real" root, so that we can share more FlatViews.
709 mr = mr->alias;
710 continue;
712 } else if (!mr->terminates) {
713 unsigned int found = 0;
714 MemoryRegion *child, *next = NULL;
715 QTAILQ_FOREACH(child, &mr->subregions, subregions_link) {
716 if (child->enabled) {
717 if (++found > 1) {
718 next = NULL;
719 break;
721 if (!child->addr && int128_ge(mr->size, child->size)) {
722 /* A child is included in its entirety. If it's the only
723 * enabled one, use it in the hope of finding an alias down the
724 * way. This will also let us share FlatViews.
726 next = child;
730 if (found == 0) {
731 return NULL;
733 if (next) {
734 mr = next;
735 continue;
739 return mr;
742 return NULL;
745 /* Render a memory topology into a list of disjoint absolute ranges. */
746 static FlatView *generate_memory_topology(MemoryRegion *mr)
748 int i;
749 FlatView *view;
751 view = flatview_new(mr);
753 if (mr) {
754 render_memory_region(view, mr, int128_zero(),
755 addrrange_make(int128_zero(), int128_2_64()),
756 false, false);
758 flatview_simplify(view);
760 view->dispatch = address_space_dispatch_new(view);
761 for (i = 0; i < view->nr; i++) {
762 MemoryRegionSection mrs =
763 section_from_flat_range(&view->ranges[i], view);
764 flatview_add_to_dispatch(view, &mrs);
766 address_space_dispatch_compact(view->dispatch);
767 g_hash_table_replace(flat_views, mr, view);
769 return view;
772 static void address_space_add_del_ioeventfds(AddressSpace *as,
773 MemoryRegionIoeventfd *fds_new,
774 unsigned fds_new_nb,
775 MemoryRegionIoeventfd *fds_old,
776 unsigned fds_old_nb)
778 unsigned iold, inew;
779 MemoryRegionIoeventfd *fd;
780 MemoryRegionSection section;
782 /* Generate a symmetric difference of the old and new fd sets, adding
783 * and deleting as necessary.
786 iold = inew = 0;
787 while (iold < fds_old_nb || inew < fds_new_nb) {
788 if (iold < fds_old_nb
789 && (inew == fds_new_nb
790 || memory_region_ioeventfd_before(&fds_old[iold],
791 &fds_new[inew]))) {
792 fd = &fds_old[iold];
793 section = (MemoryRegionSection) {
794 .fv = address_space_to_flatview(as),
795 .offset_within_address_space = int128_get64(fd->addr.start),
796 .size = fd->addr.size,
798 MEMORY_LISTENER_CALL(as, eventfd_del, Forward, &section,
799 fd->match_data, fd->data, fd->e);
800 ++iold;
801 } else if (inew < fds_new_nb
802 && (iold == fds_old_nb
803 || memory_region_ioeventfd_before(&fds_new[inew],
804 &fds_old[iold]))) {
805 fd = &fds_new[inew];
806 section = (MemoryRegionSection) {
807 .fv = address_space_to_flatview(as),
808 .offset_within_address_space = int128_get64(fd->addr.start),
809 .size = fd->addr.size,
811 MEMORY_LISTENER_CALL(as, eventfd_add, Reverse, &section,
812 fd->match_data, fd->data, fd->e);
813 ++inew;
814 } else {
815 ++iold;
816 ++inew;
821 FlatView *address_space_get_flatview(AddressSpace *as)
823 FlatView *view;
825 RCU_READ_LOCK_GUARD();
826 do {
827 view = address_space_to_flatview(as);
828 /* If somebody has replaced as->current_map concurrently,
829 * flatview_ref returns false.
831 } while (!flatview_ref(view));
832 return view;
835 static void address_space_update_ioeventfds(AddressSpace *as)
837 FlatView *view;
838 FlatRange *fr;
839 unsigned ioeventfd_nb = 0;
840 unsigned ioeventfd_max;
841 MemoryRegionIoeventfd *ioeventfds;
842 AddrRange tmp;
843 unsigned i;
846 * It is likely that the number of ioeventfds hasn't changed much, so use
847 * the previous size as the starting value, with some headroom to avoid
848 * gratuitous reallocations.
850 ioeventfd_max = QEMU_ALIGN_UP(as->ioeventfd_nb, 4);
851 ioeventfds = g_new(MemoryRegionIoeventfd, ioeventfd_max);
853 view = address_space_get_flatview(as);
854 FOR_EACH_FLAT_RANGE(fr, view) {
855 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
856 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
857 int128_sub(fr->addr.start,
858 int128_make64(fr->offset_in_region)));
859 if (addrrange_intersects(fr->addr, tmp)) {
860 ++ioeventfd_nb;
861 if (ioeventfd_nb > ioeventfd_max) {
862 ioeventfd_max = MAX(ioeventfd_max * 2, 4);
863 ioeventfds = g_realloc(ioeventfds,
864 ioeventfd_max * sizeof(*ioeventfds));
866 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
867 ioeventfds[ioeventfd_nb-1].addr = tmp;
872 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
873 as->ioeventfds, as->ioeventfd_nb);
875 g_free(as->ioeventfds);
876 as->ioeventfds = ioeventfds;
877 as->ioeventfd_nb = ioeventfd_nb;
878 flatview_unref(view);
882 * Notify the memory listeners about the coalesced IO change events of
883 * range `cmr'. Only the part that has intersection of the specified
884 * FlatRange will be sent.
886 static void flat_range_coalesced_io_notify(FlatRange *fr, AddressSpace *as,
887 CoalescedMemoryRange *cmr, bool add)
889 AddrRange tmp;
891 tmp = addrrange_shift(cmr->addr,
892 int128_sub(fr->addr.start,
893 int128_make64(fr->offset_in_region)));
894 if (!addrrange_intersects(tmp, fr->addr)) {
895 return;
897 tmp = addrrange_intersection(tmp, fr->addr);
899 if (add) {
900 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, coalesced_io_add,
901 int128_get64(tmp.start),
902 int128_get64(tmp.size));
903 } else {
904 MEMORY_LISTENER_UPDATE_REGION(fr, as, Reverse, coalesced_io_del,
905 int128_get64(tmp.start),
906 int128_get64(tmp.size));
910 static void flat_range_coalesced_io_del(FlatRange *fr, AddressSpace *as)
912 CoalescedMemoryRange *cmr;
914 QTAILQ_FOREACH(cmr, &fr->mr->coalesced, link) {
915 flat_range_coalesced_io_notify(fr, as, cmr, false);
919 static void flat_range_coalesced_io_add(FlatRange *fr, AddressSpace *as)
921 MemoryRegion *mr = fr->mr;
922 CoalescedMemoryRange *cmr;
924 if (QTAILQ_EMPTY(&mr->coalesced)) {
925 return;
928 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
929 flat_range_coalesced_io_notify(fr, as, cmr, true);
933 static void address_space_update_topology_pass(AddressSpace *as,
934 const FlatView *old_view,
935 const FlatView *new_view,
936 bool adding)
938 unsigned iold, inew;
939 FlatRange *frold, *frnew;
941 /* Generate a symmetric difference of the old and new memory maps.
942 * Kill ranges in the old map, and instantiate ranges in the new map.
944 iold = inew = 0;
945 while (iold < old_view->nr || inew < new_view->nr) {
946 if (iold < old_view->nr) {
947 frold = &old_view->ranges[iold];
948 } else {
949 frold = NULL;
951 if (inew < new_view->nr) {
952 frnew = &new_view->ranges[inew];
953 } else {
954 frnew = NULL;
957 if (frold
958 && (!frnew
959 || int128_lt(frold->addr.start, frnew->addr.start)
960 || (int128_eq(frold->addr.start, frnew->addr.start)
961 && !flatrange_equal(frold, frnew)))) {
962 /* In old but not in new, or in both but attributes changed. */
964 if (!adding) {
965 flat_range_coalesced_io_del(frold, as);
966 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
969 ++iold;
970 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
971 /* In both and unchanged (except logging may have changed) */
973 if (adding) {
974 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
975 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
976 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
977 frold->dirty_log_mask,
978 frnew->dirty_log_mask);
980 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
981 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
982 frold->dirty_log_mask,
983 frnew->dirty_log_mask);
987 ++iold;
988 ++inew;
989 } else {
990 /* In new */
992 if (adding) {
993 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
994 flat_range_coalesced_io_add(frnew, as);
997 ++inew;
1002 static void flatviews_init(void)
1004 static FlatView *empty_view;
1006 if (flat_views) {
1007 return;
1010 flat_views = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL,
1011 (GDestroyNotify) flatview_unref);
1012 if (!empty_view) {
1013 empty_view = generate_memory_topology(NULL);
1014 /* We keep it alive forever in the global variable. */
1015 flatview_ref(empty_view);
1016 } else {
1017 g_hash_table_replace(flat_views, NULL, empty_view);
1018 flatview_ref(empty_view);
1022 static void flatviews_reset(void)
1024 AddressSpace *as;
1026 if (flat_views) {
1027 g_hash_table_unref(flat_views);
1028 flat_views = NULL;
1030 flatviews_init();
1032 /* Render unique FVs */
1033 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1034 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1036 if (g_hash_table_lookup(flat_views, physmr)) {
1037 continue;
1040 generate_memory_topology(physmr);
1044 static void address_space_set_flatview(AddressSpace *as)
1046 FlatView *old_view = address_space_to_flatview(as);
1047 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1048 FlatView *new_view = g_hash_table_lookup(flat_views, physmr);
1050 assert(new_view);
1052 if (old_view == new_view) {
1053 return;
1056 if (old_view) {
1057 flatview_ref(old_view);
1060 flatview_ref(new_view);
1062 if (!QTAILQ_EMPTY(&as->listeners)) {
1063 FlatView tmpview = { .nr = 0 }, *old_view2 = old_view;
1065 if (!old_view2) {
1066 old_view2 = &tmpview;
1068 address_space_update_topology_pass(as, old_view2, new_view, false);
1069 address_space_update_topology_pass(as, old_view2, new_view, true);
1072 /* Writes are protected by the BQL. */
1073 qatomic_rcu_set(&as->current_map, new_view);
1074 if (old_view) {
1075 flatview_unref(old_view);
1078 /* Note that all the old MemoryRegions are still alive up to this
1079 * point. This relieves most MemoryListeners from the need to
1080 * ref/unref the MemoryRegions they get---unless they use them
1081 * outside the iothread mutex, in which case precise reference
1082 * counting is necessary.
1084 if (old_view) {
1085 flatview_unref(old_view);
1089 static void address_space_update_topology(AddressSpace *as)
1091 MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1093 flatviews_init();
1094 if (!g_hash_table_lookup(flat_views, physmr)) {
1095 generate_memory_topology(physmr);
1097 address_space_set_flatview(as);
1100 void memory_region_transaction_begin(void)
1102 qemu_flush_coalesced_mmio_buffer();
1103 ++memory_region_transaction_depth;
1106 void memory_region_transaction_commit(void)
1108 AddressSpace *as;
1110 assert(memory_region_transaction_depth);
1111 assert(qemu_mutex_iothread_locked());
1113 --memory_region_transaction_depth;
1114 if (!memory_region_transaction_depth) {
1115 if (memory_region_update_pending) {
1116 flatviews_reset();
1118 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
1120 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1121 address_space_set_flatview(as);
1122 address_space_update_ioeventfds(as);
1124 memory_region_update_pending = false;
1125 ioeventfd_update_pending = false;
1126 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
1127 } else if (ioeventfd_update_pending) {
1128 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1129 address_space_update_ioeventfds(as);
1131 ioeventfd_update_pending = false;
1136 static void memory_region_destructor_none(MemoryRegion *mr)
1140 static void memory_region_destructor_ram(MemoryRegion *mr)
1142 qemu_ram_free(mr->ram_block);
1145 static bool memory_region_need_escape(char c)
1147 return c == '/' || c == '[' || c == '\\' || c == ']';
1150 static char *memory_region_escape_name(const char *name)
1152 const char *p;
1153 char *escaped, *q;
1154 uint8_t c;
1155 size_t bytes = 0;
1157 for (p = name; *p; p++) {
1158 bytes += memory_region_need_escape(*p) ? 4 : 1;
1160 if (bytes == p - name) {
1161 return g_memdup(name, bytes + 1);
1164 escaped = g_malloc(bytes + 1);
1165 for (p = name, q = escaped; *p; p++) {
1166 c = *p;
1167 if (unlikely(memory_region_need_escape(c))) {
1168 *q++ = '\\';
1169 *q++ = 'x';
1170 *q++ = "0123456789abcdef"[c >> 4];
1171 c = "0123456789abcdef"[c & 15];
1173 *q++ = c;
1175 *q = 0;
1176 return escaped;
1179 static void memory_region_do_init(MemoryRegion *mr,
1180 Object *owner,
1181 const char *name,
1182 uint64_t size)
1184 mr->size = int128_make64(size);
1185 if (size == UINT64_MAX) {
1186 mr->size = int128_2_64();
1188 mr->name = g_strdup(name);
1189 mr->owner = owner;
1190 mr->dev = (DeviceState *) object_dynamic_cast(mr->owner, TYPE_DEVICE);
1191 mr->ram_block = NULL;
1193 if (name) {
1194 char *escaped_name = memory_region_escape_name(name);
1195 char *name_array = g_strdup_printf("%s[*]", escaped_name);
1197 if (!owner) {
1198 owner = container_get(qdev_get_machine(), "/unattached");
1201 object_property_add_child(owner, name_array, OBJECT(mr));
1202 object_unref(OBJECT(mr));
1203 g_free(name_array);
1204 g_free(escaped_name);
1208 void memory_region_init(MemoryRegion *mr,
1209 Object *owner,
1210 const char *name,
1211 uint64_t size)
1213 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
1214 memory_region_do_init(mr, owner, name, size);
1217 static void memory_region_get_container(Object *obj, Visitor *v,
1218 const char *name, void *opaque,
1219 Error **errp)
1221 MemoryRegion *mr = MEMORY_REGION(obj);
1222 char *path = (char *)"";
1224 if (mr->container) {
1225 path = object_get_canonical_path(OBJECT(mr->container));
1227 visit_type_str(v, name, &path, errp);
1228 if (mr->container) {
1229 g_free(path);
1233 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1234 const char *part)
1236 MemoryRegion *mr = MEMORY_REGION(obj);
1238 return OBJECT(mr->container);
1241 static void memory_region_get_priority(Object *obj, Visitor *v,
1242 const char *name, void *opaque,
1243 Error **errp)
1245 MemoryRegion *mr = MEMORY_REGION(obj);
1246 int32_t value = mr->priority;
1248 visit_type_int32(v, name, &value, errp);
1251 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1252 void *opaque, Error **errp)
1254 MemoryRegion *mr = MEMORY_REGION(obj);
1255 uint64_t value = memory_region_size(mr);
1257 visit_type_uint64(v, name, &value, errp);
1260 static void memory_region_initfn(Object *obj)
1262 MemoryRegion *mr = MEMORY_REGION(obj);
1263 ObjectProperty *op;
1265 mr->ops = &unassigned_mem_ops;
1266 mr->enabled = true;
1267 mr->romd_mode = true;
1268 mr->destructor = memory_region_destructor_none;
1269 QTAILQ_INIT(&mr->subregions);
1270 QTAILQ_INIT(&mr->coalesced);
1272 op = object_property_add(OBJECT(mr), "container",
1273 "link<" TYPE_MEMORY_REGION ">",
1274 memory_region_get_container,
1275 NULL, /* memory_region_set_container */
1276 NULL, NULL);
1277 op->resolve = memory_region_resolve_container;
1279 object_property_add_uint64_ptr(OBJECT(mr), "addr",
1280 &mr->addr, OBJ_PROP_FLAG_READ);
1281 object_property_add(OBJECT(mr), "priority", "uint32",
1282 memory_region_get_priority,
1283 NULL, /* memory_region_set_priority */
1284 NULL, NULL);
1285 object_property_add(OBJECT(mr), "size", "uint64",
1286 memory_region_get_size,
1287 NULL, /* memory_region_set_size, */
1288 NULL, NULL);
1291 static void iommu_memory_region_initfn(Object *obj)
1293 MemoryRegion *mr = MEMORY_REGION(obj);
1295 mr->is_iommu = true;
1298 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1299 unsigned size)
1301 #ifdef DEBUG_UNASSIGNED
1302 printf("Unassigned mem read " HWADDR_FMT_plx "\n", addr);
1303 #endif
1304 return 0;
1307 static void unassigned_mem_write(void *opaque, hwaddr addr,
1308 uint64_t val, unsigned size)
1310 #ifdef DEBUG_UNASSIGNED
1311 printf("Unassigned mem write " HWADDR_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1312 #endif
1315 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1316 unsigned size, bool is_write,
1317 MemTxAttrs attrs)
1319 return false;
1322 const MemoryRegionOps unassigned_mem_ops = {
1323 .valid.accepts = unassigned_mem_accepts,
1324 .endianness = DEVICE_NATIVE_ENDIAN,
1327 static uint64_t memory_region_ram_device_read(void *opaque,
1328 hwaddr addr, unsigned size)
1330 MemoryRegion *mr = opaque;
1331 uint64_t data = (uint64_t)~0;
1333 switch (size) {
1334 case 1:
1335 data = *(uint8_t *)(mr->ram_block->host + addr);
1336 break;
1337 case 2:
1338 data = *(uint16_t *)(mr->ram_block->host + addr);
1339 break;
1340 case 4:
1341 data = *(uint32_t *)(mr->ram_block->host + addr);
1342 break;
1343 case 8:
1344 data = *(uint64_t *)(mr->ram_block->host + addr);
1345 break;
1348 trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);
1350 return data;
1353 static void memory_region_ram_device_write(void *opaque, hwaddr addr,
1354 uint64_t data, unsigned size)
1356 MemoryRegion *mr = opaque;
1358 trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);
1360 switch (size) {
1361 case 1:
1362 *(uint8_t *)(mr->ram_block->host + addr) = (uint8_t)data;
1363 break;
1364 case 2:
1365 *(uint16_t *)(mr->ram_block->host + addr) = (uint16_t)data;
1366 break;
1367 case 4:
1368 *(uint32_t *)(mr->ram_block->host + addr) = (uint32_t)data;
1369 break;
1370 case 8:
1371 *(uint64_t *)(mr->ram_block->host + addr) = data;
1372 break;
1376 static const MemoryRegionOps ram_device_mem_ops = {
1377 .read = memory_region_ram_device_read,
1378 .write = memory_region_ram_device_write,
1379 .endianness = DEVICE_HOST_ENDIAN,
1380 .valid = {
1381 .min_access_size = 1,
1382 .max_access_size = 8,
1383 .unaligned = true,
1385 .impl = {
1386 .min_access_size = 1,
1387 .max_access_size = 8,
1388 .unaligned = true,
1392 bool memory_region_access_valid(MemoryRegion *mr,
1393 hwaddr addr,
1394 unsigned size,
1395 bool is_write,
1396 MemTxAttrs attrs)
1398 if (mr->ops->valid.accepts
1399 && !mr->ops->valid.accepts(mr->opaque, addr, size, is_write, attrs)) {
1400 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1401 ", size %u, region '%s', reason: rejected\n",
1402 is_write ? "write" : "read",
1403 addr, size, memory_region_name(mr));
1404 return false;
1407 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1408 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1409 ", size %u, region '%s', reason: unaligned\n",
1410 is_write ? "write" : "read",
1411 addr, size, memory_region_name(mr));
1412 return false;
1415 /* Treat zero as compatibility all valid */
1416 if (!mr->ops->valid.max_access_size) {
1417 return true;
1420 if (size > mr->ops->valid.max_access_size
1421 || size < mr->ops->valid.min_access_size) {
1422 qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1423 ", size %u, region '%s', reason: invalid size "
1424 "(min:%u max:%u)\n",
1425 is_write ? "write" : "read",
1426 addr, size, memory_region_name(mr),
1427 mr->ops->valid.min_access_size,
1428 mr->ops->valid.max_access_size);
1429 return false;
1431 return true;
1434 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1435 hwaddr addr,
1436 uint64_t *pval,
1437 unsigned size,
1438 MemTxAttrs attrs)
1440 *pval = 0;
1442 if (mr->ops->read) {
1443 return access_with_adjusted_size(addr, pval, size,
1444 mr->ops->impl.min_access_size,
1445 mr->ops->impl.max_access_size,
1446 memory_region_read_accessor,
1447 mr, attrs);
1448 } else {
1449 return access_with_adjusted_size(addr, pval, size,
1450 mr->ops->impl.min_access_size,
1451 mr->ops->impl.max_access_size,
1452 memory_region_read_with_attrs_accessor,
1453 mr, attrs);
1457 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1458 hwaddr addr,
1459 uint64_t *pval,
1460 MemOp op,
1461 MemTxAttrs attrs)
1463 unsigned size = memop_size(op);
1464 MemTxResult r;
1466 if (mr->alias) {
1467 return memory_region_dispatch_read(mr->alias,
1468 mr->alias_offset + addr,
1469 pval, op, attrs);
1471 if (!memory_region_access_valid(mr, addr, size, false, attrs)) {
1472 *pval = unassigned_mem_read(mr, addr, size);
1473 return MEMTX_DECODE_ERROR;
1476 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1477 adjust_endianness(mr, pval, op);
1478 return r;
1481 /* Return true if an eventfd was signalled */
1482 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1483 hwaddr addr,
1484 uint64_t data,
1485 unsigned size,
1486 MemTxAttrs attrs)
1488 MemoryRegionIoeventfd ioeventfd = {
1489 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1490 .data = data,
1492 unsigned i;
1494 for (i = 0; i < mr->ioeventfd_nb; i++) {
1495 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1496 ioeventfd.e = mr->ioeventfds[i].e;
1498 if (memory_region_ioeventfd_equal(&ioeventfd, &mr->ioeventfds[i])) {
1499 event_notifier_set(ioeventfd.e);
1500 return true;
1504 return false;
1507 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1508 hwaddr addr,
1509 uint64_t data,
1510 MemOp op,
1511 MemTxAttrs attrs)
1513 unsigned size = memop_size(op);
1515 if (mr->alias) {
1516 return memory_region_dispatch_write(mr->alias,
1517 mr->alias_offset + addr,
1518 data, op, attrs);
1520 if (!memory_region_access_valid(mr, addr, size, true, attrs)) {
1521 unassigned_mem_write(mr, addr, data, size);
1522 return MEMTX_DECODE_ERROR;
1525 adjust_endianness(mr, &data, op);
1527 if ((!kvm_eventfds_enabled()) &&
1528 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1529 return MEMTX_OK;
1532 if (mr->ops->write) {
1533 return access_with_adjusted_size(addr, &data, size,
1534 mr->ops->impl.min_access_size,
1535 mr->ops->impl.max_access_size,
1536 memory_region_write_accessor, mr,
1537 attrs);
1538 } else {
1539 return
1540 access_with_adjusted_size(addr, &data, size,
1541 mr->ops->impl.min_access_size,
1542 mr->ops->impl.max_access_size,
1543 memory_region_write_with_attrs_accessor,
1544 mr, attrs);
1548 void memory_region_init_io(MemoryRegion *mr,
1549 Object *owner,
1550 const MemoryRegionOps *ops,
1551 void *opaque,
1552 const char *name,
1553 uint64_t size)
1555 memory_region_init(mr, owner, name, size);
1556 mr->ops = ops ? ops : &unassigned_mem_ops;
1557 mr->opaque = opaque;
1558 mr->terminates = true;
1561 void memory_region_init_ram_nomigrate(MemoryRegion *mr,
1562 Object *owner,
1563 const char *name,
1564 uint64_t size,
1565 Error **errp)
1567 memory_region_init_ram_flags_nomigrate(mr, owner, name, size, 0, errp);
1570 void memory_region_init_ram_flags_nomigrate(MemoryRegion *mr,
1571 Object *owner,
1572 const char *name,
1573 uint64_t size,
1574 uint32_t ram_flags,
1575 Error **errp)
1577 Error *err = NULL;
1578 memory_region_init(mr, owner, name, size);
1579 mr->ram = true;
1580 mr->terminates = true;
1581 mr->destructor = memory_region_destructor_ram;
1582 mr->ram_block = qemu_ram_alloc(size, ram_flags, mr, &err);
1583 if (err) {
1584 mr->size = int128_zero();
1585 object_unparent(OBJECT(mr));
1586 error_propagate(errp, err);
1590 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1591 Object *owner,
1592 const char *name,
1593 uint64_t size,
1594 uint64_t max_size,
1595 void (*resized)(const char*,
1596 uint64_t length,
1597 void *host),
1598 Error **errp)
1600 Error *err = NULL;
1601 memory_region_init(mr, owner, name, size);
1602 mr->ram = true;
1603 mr->terminates = true;
1604 mr->destructor = memory_region_destructor_ram;
1605 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1606 mr, &err);
1607 if (err) {
1608 mr->size = int128_zero();
1609 object_unparent(OBJECT(mr));
1610 error_propagate(errp, err);
1614 #ifdef CONFIG_POSIX
1615 void memory_region_init_ram_from_file(MemoryRegion *mr,
1616 Object *owner,
1617 const char *name,
1618 uint64_t size,
1619 uint64_t align,
1620 uint32_t ram_flags,
1621 const char *path,
1622 ram_addr_t offset,
1623 bool readonly,
1624 Error **errp)
1626 Error *err = NULL;
1627 memory_region_init(mr, owner, name, size);
1628 mr->ram = true;
1629 mr->readonly = readonly;
1630 mr->terminates = true;
1631 mr->destructor = memory_region_destructor_ram;
1632 mr->align = align;
1633 mr->ram_block = qemu_ram_alloc_from_file(size, mr, ram_flags, path,
1634 offset, readonly, &err);
1635 if (err) {
1636 mr->size = int128_zero();
1637 object_unparent(OBJECT(mr));
1638 error_propagate(errp, err);
1642 void memory_region_init_ram_from_fd(MemoryRegion *mr,
1643 Object *owner,
1644 const char *name,
1645 uint64_t size,
1646 uint32_t ram_flags,
1647 int fd,
1648 ram_addr_t offset,
1649 Error **errp)
1651 Error *err = NULL;
1652 memory_region_init(mr, owner, name, size);
1653 mr->ram = true;
1654 mr->terminates = true;
1655 mr->destructor = memory_region_destructor_ram;
1656 mr->ram_block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, offset,
1657 false, &err);
1658 if (err) {
1659 mr->size = int128_zero();
1660 object_unparent(OBJECT(mr));
1661 error_propagate(errp, err);
1664 #endif
1666 void memory_region_init_ram_ptr(MemoryRegion *mr,
1667 Object *owner,
1668 const char *name,
1669 uint64_t size,
1670 void *ptr)
1672 memory_region_init(mr, owner, name, size);
1673 mr->ram = true;
1674 mr->terminates = true;
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_ram_device_ptr(MemoryRegion *mr,
1683 Object *owner,
1684 const char *name,
1685 uint64_t size,
1686 void *ptr)
1688 memory_region_init(mr, owner, name, size);
1689 mr->ram = true;
1690 mr->terminates = true;
1691 mr->ram_device = true;
1692 mr->ops = &ram_device_mem_ops;
1693 mr->opaque = mr;
1694 mr->destructor = memory_region_destructor_ram;
1696 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1697 assert(ptr != NULL);
1698 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1701 void memory_region_init_alias(MemoryRegion *mr,
1702 Object *owner,
1703 const char *name,
1704 MemoryRegion *orig,
1705 hwaddr offset,
1706 uint64_t size)
1708 memory_region_init(mr, owner, name, size);
1709 mr->alias = orig;
1710 mr->alias_offset = offset;
1713 void memory_region_init_rom_nomigrate(MemoryRegion *mr,
1714 Object *owner,
1715 const char *name,
1716 uint64_t size,
1717 Error **errp)
1719 memory_region_init_ram_flags_nomigrate(mr, owner, name, size, 0, errp);
1720 mr->readonly = true;
1723 void memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1724 Object *owner,
1725 const MemoryRegionOps *ops,
1726 void *opaque,
1727 const char *name,
1728 uint64_t size,
1729 Error **errp)
1731 Error *err = NULL;
1732 assert(ops);
1733 memory_region_init(mr, owner, name, size);
1734 mr->ops = ops;
1735 mr->opaque = opaque;
1736 mr->terminates = true;
1737 mr->rom_device = true;
1738 mr->destructor = memory_region_destructor_ram;
1739 mr->ram_block = qemu_ram_alloc(size, 0, mr, &err);
1740 if (err) {
1741 mr->size = int128_zero();
1742 object_unparent(OBJECT(mr));
1743 error_propagate(errp, err);
1747 void memory_region_init_iommu(void *_iommu_mr,
1748 size_t instance_size,
1749 const char *mrtypename,
1750 Object *owner,
1751 const char *name,
1752 uint64_t size)
1754 struct IOMMUMemoryRegion *iommu_mr;
1755 struct MemoryRegion *mr;
1757 object_initialize(_iommu_mr, instance_size, mrtypename);
1758 mr = MEMORY_REGION(_iommu_mr);
1759 memory_region_do_init(mr, owner, name, size);
1760 iommu_mr = IOMMU_MEMORY_REGION(mr);
1761 mr->terminates = true; /* then re-forwards */
1762 QLIST_INIT(&iommu_mr->iommu_notify);
1763 iommu_mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
1766 static void memory_region_finalize(Object *obj)
1768 MemoryRegion *mr = MEMORY_REGION(obj);
1770 assert(!mr->container);
1772 /* We know the region is not visible in any address space (it
1773 * does not have a container and cannot be a root either because
1774 * it has no references, so we can blindly clear mr->enabled.
1775 * memory_region_set_enabled instead could trigger a transaction
1776 * and cause an infinite loop.
1778 mr->enabled = false;
1779 memory_region_transaction_begin();
1780 while (!QTAILQ_EMPTY(&mr->subregions)) {
1781 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1782 memory_region_del_subregion(mr, subregion);
1784 memory_region_transaction_commit();
1786 mr->destructor(mr);
1787 memory_region_clear_coalescing(mr);
1788 g_free((char *)mr->name);
1789 g_free(mr->ioeventfds);
1792 Object *memory_region_owner(MemoryRegion *mr)
1794 Object *obj = OBJECT(mr);
1795 return obj->parent;
1798 void memory_region_ref(MemoryRegion *mr)
1800 /* MMIO callbacks most likely will access data that belongs
1801 * to the owner, hence the need to ref/unref the owner whenever
1802 * the memory region is in use.
1804 * The memory region is a child of its owner. As long as the
1805 * owner doesn't call unparent itself on the memory region,
1806 * ref-ing the owner will also keep the memory region alive.
1807 * Memory regions without an owner are supposed to never go away;
1808 * we do not ref/unref them because it slows down DMA sensibly.
1810 if (mr && mr->owner) {
1811 object_ref(mr->owner);
1815 void memory_region_unref(MemoryRegion *mr)
1817 if (mr && mr->owner) {
1818 object_unref(mr->owner);
1822 uint64_t memory_region_size(MemoryRegion *mr)
1824 if (int128_eq(mr->size, int128_2_64())) {
1825 return UINT64_MAX;
1827 return int128_get64(mr->size);
1830 const char *memory_region_name(const MemoryRegion *mr)
1832 if (!mr->name) {
1833 ((MemoryRegion *)mr)->name =
1834 g_strdup(object_get_canonical_path_component(OBJECT(mr)));
1836 return mr->name;
1839 bool memory_region_is_ram_device(MemoryRegion *mr)
1841 return mr->ram_device;
1844 bool memory_region_is_protected(MemoryRegion *mr)
1846 return mr->ram && (mr->ram_block->flags & RAM_PROTECTED);
1849 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1851 uint8_t mask = mr->dirty_log_mask;
1852 RAMBlock *rb = mr->ram_block;
1854 if (global_dirty_tracking && ((rb && qemu_ram_is_migratable(rb)) ||
1855 memory_region_is_iommu(mr))) {
1856 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1859 if (tcg_enabled() && rb) {
1860 /* TCG only cares about dirty memory logging for RAM, not IOMMU. */
1861 mask |= (1 << DIRTY_MEMORY_CODE);
1863 return mask;
1866 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1868 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1871 static int memory_region_update_iommu_notify_flags(IOMMUMemoryRegion *iommu_mr,
1872 Error **errp)
1874 IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1875 IOMMUNotifier *iommu_notifier;
1876 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1877 int ret = 0;
1879 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
1880 flags |= iommu_notifier->notifier_flags;
1883 if (flags != iommu_mr->iommu_notify_flags && imrc->notify_flag_changed) {
1884 ret = imrc->notify_flag_changed(iommu_mr,
1885 iommu_mr->iommu_notify_flags,
1886 flags, errp);
1889 if (!ret) {
1890 iommu_mr->iommu_notify_flags = flags;
1892 return ret;
1895 int memory_region_iommu_set_page_size_mask(IOMMUMemoryRegion *iommu_mr,
1896 uint64_t page_size_mask,
1897 Error **errp)
1899 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1900 int ret = 0;
1902 if (imrc->iommu_set_page_size_mask) {
1903 ret = imrc->iommu_set_page_size_mask(iommu_mr, page_size_mask, errp);
1905 return ret;
1908 int memory_region_register_iommu_notifier(MemoryRegion *mr,
1909 IOMMUNotifier *n, Error **errp)
1911 IOMMUMemoryRegion *iommu_mr;
1912 int ret;
1914 if (mr->alias) {
1915 return memory_region_register_iommu_notifier(mr->alias, n, errp);
1918 /* We need to register for at least one bitfield */
1919 iommu_mr = IOMMU_MEMORY_REGION(mr);
1920 assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
1921 assert(n->start <= n->end);
1922 assert(n->iommu_idx >= 0 &&
1923 n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
1925 QLIST_INSERT_HEAD(&iommu_mr->iommu_notify, n, node);
1926 ret = memory_region_update_iommu_notify_flags(iommu_mr, errp);
1927 if (ret) {
1928 QLIST_REMOVE(n, node);
1930 return ret;
1933 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr)
1935 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1937 if (imrc->get_min_page_size) {
1938 return imrc->get_min_page_size(iommu_mr);
1940 return TARGET_PAGE_SIZE;
1943 void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
1945 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
1946 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1947 hwaddr addr, granularity;
1948 IOMMUTLBEntry iotlb;
1950 /* If the IOMMU has its own replay callback, override */
1951 if (imrc->replay) {
1952 imrc->replay(iommu_mr, n);
1953 return;
1956 granularity = memory_region_iommu_get_min_page_size(iommu_mr);
1958 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1959 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, n->iommu_idx);
1960 if (iotlb.perm != IOMMU_NONE) {
1961 n->notify(n, &iotlb);
1964 /* if (2^64 - MR size) < granularity, it's possible to get an
1965 * infinite loop here. This should catch such a wraparound */
1966 if ((addr + granularity) < addr) {
1967 break;
1972 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1973 IOMMUNotifier *n)
1975 IOMMUMemoryRegion *iommu_mr;
1977 if (mr->alias) {
1978 memory_region_unregister_iommu_notifier(mr->alias, n);
1979 return;
1981 QLIST_REMOVE(n, node);
1982 iommu_mr = IOMMU_MEMORY_REGION(mr);
1983 memory_region_update_iommu_notify_flags(iommu_mr, NULL);
1986 void memory_region_notify_iommu_one(IOMMUNotifier *notifier,
1987 IOMMUTLBEvent *event)
1989 IOMMUTLBEntry *entry = &event->entry;
1990 hwaddr entry_end = entry->iova + entry->addr_mask;
1991 IOMMUTLBEntry tmp = *entry;
1993 if (event->type == IOMMU_NOTIFIER_UNMAP) {
1994 assert(entry->perm == IOMMU_NONE);
1998 * Skip the notification if the notification does not overlap
1999 * with registered range.
2001 if (notifier->start > entry_end || notifier->end < entry->iova) {
2002 return;
2005 if (notifier->notifier_flags & IOMMU_NOTIFIER_DEVIOTLB_UNMAP) {
2006 /* Crop (iova, addr_mask) to range */
2007 tmp.iova = MAX(tmp.iova, notifier->start);
2008 tmp.addr_mask = MIN(entry_end, notifier->end) - tmp.iova;
2009 } else {
2010 assert(entry->iova >= notifier->start && entry_end <= notifier->end);
2013 if (event->type & notifier->notifier_flags) {
2014 notifier->notify(notifier, &tmp);
2018 void memory_region_unmap_iommu_notifier_range(IOMMUNotifier *notifier)
2020 IOMMUTLBEvent event;
2022 event.type = IOMMU_NOTIFIER_UNMAP;
2023 event.entry.target_as = &address_space_memory;
2024 event.entry.iova = notifier->start;
2025 event.entry.perm = IOMMU_NONE;
2026 event.entry.addr_mask = notifier->end - notifier->start;
2028 memory_region_notify_iommu_one(notifier, &event);
2031 void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
2032 int iommu_idx,
2033 IOMMUTLBEvent event)
2035 IOMMUNotifier *iommu_notifier;
2037 assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
2039 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
2040 if (iommu_notifier->iommu_idx == iommu_idx) {
2041 memory_region_notify_iommu_one(iommu_notifier, &event);
2046 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
2047 enum IOMMUMemoryRegionAttr attr,
2048 void *data)
2050 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2052 if (!imrc->get_attr) {
2053 return -EINVAL;
2056 return imrc->get_attr(iommu_mr, attr, data);
2059 int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
2060 MemTxAttrs attrs)
2062 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2064 if (!imrc->attrs_to_index) {
2065 return 0;
2068 return imrc->attrs_to_index(iommu_mr, attrs);
2071 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr)
2073 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2075 if (!imrc->num_indexes) {
2076 return 1;
2079 return imrc->num_indexes(iommu_mr);
2082 RamDiscardManager *memory_region_get_ram_discard_manager(MemoryRegion *mr)
2084 if (!memory_region_is_mapped(mr) || !memory_region_is_ram(mr)) {
2085 return NULL;
2087 return mr->rdm;
2090 void memory_region_set_ram_discard_manager(MemoryRegion *mr,
2091 RamDiscardManager *rdm)
2093 g_assert(memory_region_is_ram(mr) && !memory_region_is_mapped(mr));
2094 g_assert(!rdm || !mr->rdm);
2095 mr->rdm = rdm;
2098 uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,
2099 const MemoryRegion *mr)
2101 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2103 g_assert(rdmc->get_min_granularity);
2104 return rdmc->get_min_granularity(rdm, mr);
2107 bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
2108 const MemoryRegionSection *section)
2110 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2112 g_assert(rdmc->is_populated);
2113 return rdmc->is_populated(rdm, section);
2116 int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
2117 MemoryRegionSection *section,
2118 ReplayRamPopulate replay_fn,
2119 void *opaque)
2121 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2123 g_assert(rdmc->replay_populated);
2124 return rdmc->replay_populated(rdm, section, replay_fn, opaque);
2127 void ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
2128 MemoryRegionSection *section,
2129 ReplayRamDiscard replay_fn,
2130 void *opaque)
2132 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2134 g_assert(rdmc->replay_discarded);
2135 rdmc->replay_discarded(rdm, section, replay_fn, opaque);
2138 void ram_discard_manager_register_listener(RamDiscardManager *rdm,
2139 RamDiscardListener *rdl,
2140 MemoryRegionSection *section)
2142 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2144 g_assert(rdmc->register_listener);
2145 rdmc->register_listener(rdm, rdl, section);
2148 void ram_discard_manager_unregister_listener(RamDiscardManager *rdm,
2149 RamDiscardListener *rdl)
2151 RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2153 g_assert(rdmc->unregister_listener);
2154 rdmc->unregister_listener(rdm, rdl);
2157 /* Called with rcu_read_lock held. */
2158 bool memory_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
2159 ram_addr_t *ram_addr, bool *read_only,
2160 bool *mr_has_discard_manager)
2162 MemoryRegion *mr;
2163 hwaddr xlat;
2164 hwaddr len = iotlb->addr_mask + 1;
2165 bool writable = iotlb->perm & IOMMU_WO;
2167 if (mr_has_discard_manager) {
2168 *mr_has_discard_manager = false;
2171 * The IOMMU TLB entry we have just covers translation through
2172 * this IOMMU to its immediate target. We need to translate
2173 * it the rest of the way through to memory.
2175 mr = address_space_translate(&address_space_memory, iotlb->translated_addr,
2176 &xlat, &len, writable, MEMTXATTRS_UNSPECIFIED);
2177 if (!memory_region_is_ram(mr)) {
2178 error_report("iommu map to non memory area %" HWADDR_PRIx "", xlat);
2179 return false;
2180 } else if (memory_region_has_ram_discard_manager(mr)) {
2181 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(mr);
2182 MemoryRegionSection tmp = {
2183 .mr = mr,
2184 .offset_within_region = xlat,
2185 .size = int128_make64(len),
2187 if (mr_has_discard_manager) {
2188 *mr_has_discard_manager = true;
2191 * Malicious VMs can map memory into the IOMMU, which is expected
2192 * to remain discarded. vfio will pin all pages, populating memory.
2193 * Disallow that. vmstate priorities make sure any RamDiscardManager
2194 * were already restored before IOMMUs are restored.
2196 if (!ram_discard_manager_is_populated(rdm, &tmp)) {
2197 error_report("iommu map to discarded memory (e.g., unplugged via"
2198 " virtio-mem): %" HWADDR_PRIx "",
2199 iotlb->translated_addr);
2200 return false;
2205 * Translation truncates length to the IOMMU page size,
2206 * check that it did not truncate too much.
2208 if (len & iotlb->addr_mask) {
2209 error_report("iommu has granularity incompatible with target AS");
2210 return false;
2213 if (vaddr) {
2214 *vaddr = memory_region_get_ram_ptr(mr) + xlat;
2217 if (ram_addr) {
2218 *ram_addr = memory_region_get_ram_addr(mr) + xlat;
2221 if (read_only) {
2222 *read_only = !writable || mr->readonly;
2225 return true;
2228 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
2230 uint8_t mask = 1 << client;
2231 uint8_t old_logging;
2233 assert(client == DIRTY_MEMORY_VGA);
2234 old_logging = mr->vga_logging_count;
2235 mr->vga_logging_count += log ? 1 : -1;
2236 if (!!old_logging == !!mr->vga_logging_count) {
2237 return;
2240 memory_region_transaction_begin();
2241 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
2242 memory_region_update_pending |= mr->enabled;
2243 memory_region_transaction_commit();
2246 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
2247 hwaddr size)
2249 assert(mr->ram_block);
2250 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
2251 size,
2252 memory_region_get_dirty_log_mask(mr));
2256 * If memory region `mr' is NULL, do global sync. Otherwise, sync
2257 * dirty bitmap for the specified memory region.
2259 static void memory_region_sync_dirty_bitmap(MemoryRegion *mr, bool last_stage)
2261 MemoryListener *listener;
2262 AddressSpace *as;
2263 FlatView *view;
2264 FlatRange *fr;
2266 /* If the same address space has multiple log_sync listeners, we
2267 * visit that address space's FlatView multiple times. But because
2268 * log_sync listeners are rare, it's still cheaper than walking each
2269 * address space once.
2271 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2272 if (listener->log_sync) {
2273 as = listener->address_space;
2274 view = address_space_get_flatview(as);
2275 FOR_EACH_FLAT_RANGE(fr, view) {
2276 if (fr->dirty_log_mask && (!mr || fr->mr == mr)) {
2277 MemoryRegionSection mrs = section_from_flat_range(fr, view);
2278 listener->log_sync(listener, &mrs);
2281 flatview_unref(view);
2282 trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 0);
2283 } else if (listener->log_sync_global) {
2285 * No matter whether MR is specified, what we can do here
2286 * is to do a global sync, because we are not capable to
2287 * sync in a finer granularity.
2289 listener->log_sync_global(listener, last_stage);
2290 trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 1);
2295 void memory_region_clear_dirty_bitmap(MemoryRegion *mr, hwaddr start,
2296 hwaddr len)
2298 MemoryRegionSection mrs;
2299 MemoryListener *listener;
2300 AddressSpace *as;
2301 FlatView *view;
2302 FlatRange *fr;
2303 hwaddr sec_start, sec_end, sec_size;
2305 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2306 if (!listener->log_clear) {
2307 continue;
2309 as = listener->address_space;
2310 view = address_space_get_flatview(as);
2311 FOR_EACH_FLAT_RANGE(fr, view) {
2312 if (!fr->dirty_log_mask || fr->mr != mr) {
2314 * Clear dirty bitmap operation only applies to those
2315 * regions whose dirty logging is at least enabled
2317 continue;
2320 mrs = section_from_flat_range(fr, view);
2322 sec_start = MAX(mrs.offset_within_region, start);
2323 sec_end = mrs.offset_within_region + int128_get64(mrs.size);
2324 sec_end = MIN(sec_end, start + len);
2326 if (sec_start >= sec_end) {
2328 * If this memory region section has no intersection
2329 * with the requested range, skip.
2331 continue;
2334 /* Valid case; shrink the section if needed */
2335 mrs.offset_within_address_space +=
2336 sec_start - mrs.offset_within_region;
2337 mrs.offset_within_region = sec_start;
2338 sec_size = sec_end - sec_start;
2339 mrs.size = int128_make64(sec_size);
2340 listener->log_clear(listener, &mrs);
2342 flatview_unref(view);
2346 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
2347 hwaddr addr,
2348 hwaddr size,
2349 unsigned client)
2351 DirtyBitmapSnapshot *snapshot;
2352 assert(mr->ram_block);
2353 memory_region_sync_dirty_bitmap(mr, false);
2354 snapshot = cpu_physical_memory_snapshot_and_clear_dirty(mr, addr, size, client);
2355 memory_global_after_dirty_log_sync();
2356 return snapshot;
2359 bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
2360 hwaddr addr, hwaddr size)
2362 assert(mr->ram_block);
2363 return cpu_physical_memory_snapshot_get_dirty(snap,
2364 memory_region_get_ram_addr(mr) + addr, size);
2367 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
2369 if (mr->readonly != readonly) {
2370 memory_region_transaction_begin();
2371 mr->readonly = readonly;
2372 memory_region_update_pending |= mr->enabled;
2373 memory_region_transaction_commit();
2377 void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile)
2379 if (mr->nonvolatile != nonvolatile) {
2380 memory_region_transaction_begin();
2381 mr->nonvolatile = nonvolatile;
2382 memory_region_update_pending |= mr->enabled;
2383 memory_region_transaction_commit();
2387 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
2389 if (mr->romd_mode != romd_mode) {
2390 memory_region_transaction_begin();
2391 mr->romd_mode = romd_mode;
2392 memory_region_update_pending |= mr->enabled;
2393 memory_region_transaction_commit();
2397 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
2398 hwaddr size, unsigned client)
2400 assert(mr->ram_block);
2401 cpu_physical_memory_test_and_clear_dirty(
2402 memory_region_get_ram_addr(mr) + addr, size, client);
2405 int memory_region_get_fd(MemoryRegion *mr)
2407 RCU_READ_LOCK_GUARD();
2408 while (mr->alias) {
2409 mr = mr->alias;
2411 return mr->ram_block->fd;
2414 void *memory_region_get_ram_ptr(MemoryRegion *mr)
2416 uint64_t offset = 0;
2418 RCU_READ_LOCK_GUARD();
2419 while (mr->alias) {
2420 offset += mr->alias_offset;
2421 mr = mr->alias;
2423 assert(mr->ram_block);
2424 return qemu_map_ram_ptr(mr->ram_block, offset);
2427 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
2429 RAMBlock *block;
2431 block = qemu_ram_block_from_host(ptr, false, offset);
2432 if (!block) {
2433 return NULL;
2436 return block->mr;
2439 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
2441 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
2444 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
2446 assert(mr->ram_block);
2448 qemu_ram_resize(mr->ram_block, newsize, errp);
2451 void memory_region_msync(MemoryRegion *mr, hwaddr addr, hwaddr size)
2453 if (mr->ram_block) {
2454 qemu_ram_msync(mr->ram_block, addr, size);
2458 void memory_region_writeback(MemoryRegion *mr, hwaddr addr, hwaddr size)
2461 * Might be extended case needed to cover
2462 * different types of memory regions
2464 if (mr->dirty_log_mask) {
2465 memory_region_msync(mr, addr, size);
2470 * Call proper memory listeners about the change on the newly
2471 * added/removed CoalescedMemoryRange.
2473 static void memory_region_update_coalesced_range(MemoryRegion *mr,
2474 CoalescedMemoryRange *cmr,
2475 bool add)
2477 AddressSpace *as;
2478 FlatView *view;
2479 FlatRange *fr;
2481 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2482 view = address_space_get_flatview(as);
2483 FOR_EACH_FLAT_RANGE(fr, view) {
2484 if (fr->mr == mr) {
2485 flat_range_coalesced_io_notify(fr, as, cmr, add);
2488 flatview_unref(view);
2492 void memory_region_set_coalescing(MemoryRegion *mr)
2494 memory_region_clear_coalescing(mr);
2495 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
2498 void memory_region_add_coalescing(MemoryRegion *mr,
2499 hwaddr offset,
2500 uint64_t size)
2502 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
2504 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
2505 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
2506 memory_region_update_coalesced_range(mr, cmr, true);
2507 memory_region_set_flush_coalesced(mr);
2510 void memory_region_clear_coalescing(MemoryRegion *mr)
2512 CoalescedMemoryRange *cmr;
2514 if (QTAILQ_EMPTY(&mr->coalesced)) {
2515 return;
2518 qemu_flush_coalesced_mmio_buffer();
2519 mr->flush_coalesced_mmio = false;
2521 while (!QTAILQ_EMPTY(&mr->coalesced)) {
2522 cmr = QTAILQ_FIRST(&mr->coalesced);
2523 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
2524 memory_region_update_coalesced_range(mr, cmr, false);
2525 g_free(cmr);
2529 void memory_region_set_flush_coalesced(MemoryRegion *mr)
2531 mr->flush_coalesced_mmio = true;
2534 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
2536 qemu_flush_coalesced_mmio_buffer();
2537 if (QTAILQ_EMPTY(&mr->coalesced)) {
2538 mr->flush_coalesced_mmio = false;
2542 static bool userspace_eventfd_warning;
2544 void memory_region_add_eventfd(MemoryRegion *mr,
2545 hwaddr addr,
2546 unsigned size,
2547 bool match_data,
2548 uint64_t data,
2549 EventNotifier *e)
2551 MemoryRegionIoeventfd mrfd = {
2552 .addr.start = int128_make64(addr),
2553 .addr.size = int128_make64(size),
2554 .match_data = match_data,
2555 .data = data,
2556 .e = e,
2558 unsigned i;
2560 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
2561 userspace_eventfd_warning))) {
2562 userspace_eventfd_warning = true;
2563 error_report("Using eventfd without MMIO binding in KVM. "
2564 "Suboptimal performance expected");
2567 if (size) {
2568 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2570 memory_region_transaction_begin();
2571 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2572 if (memory_region_ioeventfd_before(&mrfd, &mr->ioeventfds[i])) {
2573 break;
2576 ++mr->ioeventfd_nb;
2577 mr->ioeventfds = g_realloc(mr->ioeventfds,
2578 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2579 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2580 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2581 mr->ioeventfds[i] = mrfd;
2582 ioeventfd_update_pending |= mr->enabled;
2583 memory_region_transaction_commit();
2586 void memory_region_del_eventfd(MemoryRegion *mr,
2587 hwaddr addr,
2588 unsigned size,
2589 bool match_data,
2590 uint64_t data,
2591 EventNotifier *e)
2593 MemoryRegionIoeventfd mrfd = {
2594 .addr.start = int128_make64(addr),
2595 .addr.size = int128_make64(size),
2596 .match_data = match_data,
2597 .data = data,
2598 .e = e,
2600 unsigned i;
2602 if (size) {
2603 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2605 memory_region_transaction_begin();
2606 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2607 if (memory_region_ioeventfd_equal(&mrfd, &mr->ioeventfds[i])) {
2608 break;
2611 assert(i != mr->ioeventfd_nb);
2612 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2613 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2614 --mr->ioeventfd_nb;
2615 mr->ioeventfds = g_realloc(mr->ioeventfds,
2616 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
2617 ioeventfd_update_pending |= mr->enabled;
2618 memory_region_transaction_commit();
2621 static void memory_region_update_container_subregions(MemoryRegion *subregion)
2623 MemoryRegion *mr = subregion->container;
2624 MemoryRegion *other;
2626 memory_region_transaction_begin();
2628 memory_region_ref(subregion);
2629 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2630 if (subregion->priority >= other->priority) {
2631 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2632 goto done;
2635 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2636 done:
2637 memory_region_update_pending |= mr->enabled && subregion->enabled;
2638 memory_region_transaction_commit();
2641 static void memory_region_add_subregion_common(MemoryRegion *mr,
2642 hwaddr offset,
2643 MemoryRegion *subregion)
2645 MemoryRegion *alias;
2647 assert(!subregion->container);
2648 subregion->container = mr;
2649 for (alias = subregion->alias; alias; alias = alias->alias) {
2650 alias->mapped_via_alias++;
2652 subregion->addr = offset;
2653 memory_region_update_container_subregions(subregion);
2656 void memory_region_add_subregion(MemoryRegion *mr,
2657 hwaddr offset,
2658 MemoryRegion *subregion)
2660 subregion->priority = 0;
2661 memory_region_add_subregion_common(mr, offset, subregion);
2664 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2665 hwaddr offset,
2666 MemoryRegion *subregion,
2667 int priority)
2669 subregion->priority = priority;
2670 memory_region_add_subregion_common(mr, offset, subregion);
2673 void memory_region_del_subregion(MemoryRegion *mr,
2674 MemoryRegion *subregion)
2676 MemoryRegion *alias;
2678 memory_region_transaction_begin();
2679 assert(subregion->container == mr);
2680 subregion->container = NULL;
2681 for (alias = subregion->alias; alias; alias = alias->alias) {
2682 alias->mapped_via_alias--;
2683 assert(alias->mapped_via_alias >= 0);
2685 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
2686 memory_region_unref(subregion);
2687 memory_region_update_pending |= mr->enabled && subregion->enabled;
2688 memory_region_transaction_commit();
2691 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2693 if (enabled == mr->enabled) {
2694 return;
2696 memory_region_transaction_begin();
2697 mr->enabled = enabled;
2698 memory_region_update_pending = true;
2699 memory_region_transaction_commit();
2702 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2704 Int128 s = int128_make64(size);
2706 if (size == UINT64_MAX) {
2707 s = int128_2_64();
2709 if (int128_eq(s, mr->size)) {
2710 return;
2712 memory_region_transaction_begin();
2713 mr->size = s;
2714 memory_region_update_pending = true;
2715 memory_region_transaction_commit();
2718 static void memory_region_readd_subregion(MemoryRegion *mr)
2720 MemoryRegion *container = mr->container;
2722 if (container) {
2723 memory_region_transaction_begin();
2724 memory_region_ref(mr);
2725 memory_region_del_subregion(container, mr);
2726 memory_region_add_subregion_common(container, mr->addr, mr);
2727 memory_region_unref(mr);
2728 memory_region_transaction_commit();
2732 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2734 if (addr != mr->addr) {
2735 mr->addr = addr;
2736 memory_region_readd_subregion(mr);
2740 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
2742 assert(mr->alias);
2744 if (offset == mr->alias_offset) {
2745 return;
2748 memory_region_transaction_begin();
2749 mr->alias_offset = offset;
2750 memory_region_update_pending |= mr->enabled;
2751 memory_region_transaction_commit();
2754 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2756 return mr->align;
2759 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2761 const AddrRange *addr = addr_;
2762 const FlatRange *fr = fr_;
2764 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2765 return -1;
2766 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2767 return 1;
2769 return 0;
2772 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
2774 return bsearch(&addr, view->ranges, view->nr,
2775 sizeof(FlatRange), cmp_flatrange_addr);
2778 bool memory_region_is_mapped(MemoryRegion *mr)
2780 return !!mr->container || mr->mapped_via_alias;
2783 /* Same as memory_region_find, but it does not add a reference to the
2784 * returned region. It must be called from an RCU critical section.
2786 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2787 hwaddr addr, uint64_t size)
2789 MemoryRegionSection ret = { .mr = NULL };
2790 MemoryRegion *root;
2791 AddressSpace *as;
2792 AddrRange range;
2793 FlatView *view;
2794 FlatRange *fr;
2796 addr += mr->addr;
2797 for (root = mr; root->container; ) {
2798 root = root->container;
2799 addr += root->addr;
2802 as = memory_region_to_address_space(root);
2803 if (!as) {
2804 return ret;
2806 range = addrrange_make(int128_make64(addr), int128_make64(size));
2808 view = address_space_to_flatview(as);
2809 fr = flatview_lookup(view, range);
2810 if (!fr) {
2811 return ret;
2814 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2815 --fr;
2818 ret.mr = fr->mr;
2819 ret.fv = view;
2820 range = addrrange_intersection(range, fr->addr);
2821 ret.offset_within_region = fr->offset_in_region;
2822 ret.offset_within_region += int128_get64(int128_sub(range.start,
2823 fr->addr.start));
2824 ret.size = range.size;
2825 ret.offset_within_address_space = int128_get64(range.start);
2826 ret.readonly = fr->readonly;
2827 ret.nonvolatile = fr->nonvolatile;
2828 return ret;
2831 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2832 hwaddr addr, uint64_t size)
2834 MemoryRegionSection ret;
2835 RCU_READ_LOCK_GUARD();
2836 ret = memory_region_find_rcu(mr, addr, size);
2837 if (ret.mr) {
2838 memory_region_ref(ret.mr);
2840 return ret;
2843 MemoryRegionSection *memory_region_section_new_copy(MemoryRegionSection *s)
2845 MemoryRegionSection *tmp = g_new(MemoryRegionSection, 1);
2847 *tmp = *s;
2848 if (tmp->mr) {
2849 memory_region_ref(tmp->mr);
2851 if (tmp->fv) {
2852 bool ret = flatview_ref(tmp->fv);
2854 g_assert(ret);
2856 return tmp;
2859 void memory_region_section_free_copy(MemoryRegionSection *s)
2861 if (s->fv) {
2862 flatview_unref(s->fv);
2864 if (s->mr) {
2865 memory_region_unref(s->mr);
2867 g_free(s);
2870 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2872 MemoryRegion *mr;
2874 RCU_READ_LOCK_GUARD();
2875 mr = memory_region_find_rcu(container, addr, 1).mr;
2876 return mr && mr != container;
2879 void memory_global_dirty_log_sync(bool last_stage)
2881 memory_region_sync_dirty_bitmap(NULL, last_stage);
2884 void memory_global_after_dirty_log_sync(void)
2886 MEMORY_LISTENER_CALL_GLOBAL(log_global_after_sync, Forward);
2890 * Dirty track stop flags that are postponed due to VM being stopped. Should
2891 * only be used within vmstate_change hook.
2893 static unsigned int postponed_stop_flags;
2894 static VMChangeStateEntry *vmstate_change;
2895 static void memory_global_dirty_log_stop_postponed_run(void);
2897 void memory_global_dirty_log_start(unsigned int flags)
2899 unsigned int old_flags;
2901 assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2903 if (vmstate_change) {
2904 /* If there is postponed stop(), operate on it first */
2905 postponed_stop_flags &= ~flags;
2906 memory_global_dirty_log_stop_postponed_run();
2909 flags &= ~global_dirty_tracking;
2910 if (!flags) {
2911 return;
2914 old_flags = global_dirty_tracking;
2915 global_dirty_tracking |= flags;
2916 trace_global_dirty_changed(global_dirty_tracking);
2918 if (!old_flags) {
2919 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2920 memory_region_transaction_begin();
2921 memory_region_update_pending = true;
2922 memory_region_transaction_commit();
2926 static void memory_global_dirty_log_do_stop(unsigned int flags)
2928 assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2929 assert((global_dirty_tracking & flags) == flags);
2930 global_dirty_tracking &= ~flags;
2932 trace_global_dirty_changed(global_dirty_tracking);
2934 if (!global_dirty_tracking) {
2935 memory_region_transaction_begin();
2936 memory_region_update_pending = true;
2937 memory_region_transaction_commit();
2938 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2943 * Execute the postponed dirty log stop operations if there is, then reset
2944 * everything (including the flags and the vmstate change hook).
2946 static void memory_global_dirty_log_stop_postponed_run(void)
2948 /* This must be called with the vmstate handler registered */
2949 assert(vmstate_change);
2951 /* Note: postponed_stop_flags can be cleared in log start routine */
2952 if (postponed_stop_flags) {
2953 memory_global_dirty_log_do_stop(postponed_stop_flags);
2954 postponed_stop_flags = 0;
2957 qemu_del_vm_change_state_handler(vmstate_change);
2958 vmstate_change = NULL;
2961 static void memory_vm_change_state_handler(void *opaque, bool running,
2962 RunState state)
2964 if (running) {
2965 memory_global_dirty_log_stop_postponed_run();
2969 void memory_global_dirty_log_stop(unsigned int flags)
2971 if (!runstate_is_running()) {
2972 /* Postpone the dirty log stop, e.g., to when VM starts again */
2973 if (vmstate_change) {
2974 /* Batch with previous postponed flags */
2975 postponed_stop_flags |= flags;
2976 } else {
2977 postponed_stop_flags = flags;
2978 vmstate_change = qemu_add_vm_change_state_handler(
2979 memory_vm_change_state_handler, NULL);
2981 return;
2984 memory_global_dirty_log_do_stop(flags);
2987 static void listener_add_address_space(MemoryListener *listener,
2988 AddressSpace *as)
2990 FlatView *view;
2991 FlatRange *fr;
2993 if (listener->begin) {
2994 listener->begin(listener);
2996 if (global_dirty_tracking) {
2997 if (listener->log_global_start) {
2998 listener->log_global_start(listener);
3002 view = address_space_get_flatview(as);
3003 FOR_EACH_FLAT_RANGE(fr, view) {
3004 MemoryRegionSection section = section_from_flat_range(fr, view);
3006 if (listener->region_add) {
3007 listener->region_add(listener, &section);
3009 if (fr->dirty_log_mask && listener->log_start) {
3010 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
3013 if (listener->commit) {
3014 listener->commit(listener);
3016 flatview_unref(view);
3019 static void listener_del_address_space(MemoryListener *listener,
3020 AddressSpace *as)
3022 FlatView *view;
3023 FlatRange *fr;
3025 if (listener->begin) {
3026 listener->begin(listener);
3028 view = address_space_get_flatview(as);
3029 FOR_EACH_FLAT_RANGE(fr, view) {
3030 MemoryRegionSection section = section_from_flat_range(fr, view);
3032 if (fr->dirty_log_mask && listener->log_stop) {
3033 listener->log_stop(listener, &section, fr->dirty_log_mask, 0);
3035 if (listener->region_del) {
3036 listener->region_del(listener, &section);
3039 if (listener->commit) {
3040 listener->commit(listener);
3042 flatview_unref(view);
3045 void memory_listener_register(MemoryListener *listener, AddressSpace *as)
3047 MemoryListener *other = NULL;
3049 /* Only one of them can be defined for a listener */
3050 assert(!(listener->log_sync && listener->log_sync_global));
3052 listener->address_space = as;
3053 if (QTAILQ_EMPTY(&memory_listeners)
3054 || listener->priority >= QTAILQ_LAST(&memory_listeners)->priority) {
3055 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
3056 } else {
3057 QTAILQ_FOREACH(other, &memory_listeners, link) {
3058 if (listener->priority < other->priority) {
3059 break;
3062 QTAILQ_INSERT_BEFORE(other, listener, link);
3065 if (QTAILQ_EMPTY(&as->listeners)
3066 || listener->priority >= QTAILQ_LAST(&as->listeners)->priority) {
3067 QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
3068 } else {
3069 QTAILQ_FOREACH(other, &as->listeners, link_as) {
3070 if (listener->priority < other->priority) {
3071 break;
3074 QTAILQ_INSERT_BEFORE(other, listener, link_as);
3077 listener_add_address_space(listener, as);
3080 void memory_listener_unregister(MemoryListener *listener)
3082 if (!listener->address_space) {
3083 return;
3086 listener_del_address_space(listener, listener->address_space);
3087 QTAILQ_REMOVE(&memory_listeners, listener, link);
3088 QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
3089 listener->address_space = NULL;
3092 void address_space_remove_listeners(AddressSpace *as)
3094 while (!QTAILQ_EMPTY(&as->listeners)) {
3095 memory_listener_unregister(QTAILQ_FIRST(&as->listeners));
3099 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
3101 memory_region_ref(root);
3102 as->root = root;
3103 as->current_map = NULL;
3104 as->ioeventfd_nb = 0;
3105 as->ioeventfds = NULL;
3106 QTAILQ_INIT(&as->listeners);
3107 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
3108 as->name = g_strdup(name ? name : "anonymous");
3109 address_space_update_topology(as);
3110 address_space_update_ioeventfds(as);
3113 static void do_address_space_destroy(AddressSpace *as)
3115 assert(QTAILQ_EMPTY(&as->listeners));
3117 flatview_unref(as->current_map);
3118 g_free(as->name);
3119 g_free(as->ioeventfds);
3120 memory_region_unref(as->root);
3123 void address_space_destroy(AddressSpace *as)
3125 MemoryRegion *root = as->root;
3127 /* Flush out anything from MemoryListeners listening in on this */
3128 memory_region_transaction_begin();
3129 as->root = NULL;
3130 memory_region_transaction_commit();
3131 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
3133 /* At this point, as->dispatch and as->current_map are dummy
3134 * entries that the guest should never use. Wait for the old
3135 * values to expire before freeing the data.
3137 as->root = root;
3138 call_rcu(as, do_address_space_destroy, rcu);
3141 static const char *memory_region_type(MemoryRegion *mr)
3143 if (mr->alias) {
3144 return memory_region_type(mr->alias);
3146 if (memory_region_is_ram_device(mr)) {
3147 return "ramd";
3148 } else if (memory_region_is_romd(mr)) {
3149 return "romd";
3150 } else if (memory_region_is_rom(mr)) {
3151 return "rom";
3152 } else if (memory_region_is_ram(mr)) {
3153 return "ram";
3154 } else {
3155 return "i/o";
3159 typedef struct MemoryRegionList MemoryRegionList;
3161 struct MemoryRegionList {
3162 const MemoryRegion *mr;
3163 QTAILQ_ENTRY(MemoryRegionList) mrqueue;
3166 typedef QTAILQ_HEAD(, MemoryRegionList) MemoryRegionListHead;
3168 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3169 int128_sub((size), int128_one())) : 0)
3170 #define MTREE_INDENT " "
3172 static void mtree_expand_owner(const char *label, Object *obj)
3174 DeviceState *dev = (DeviceState *) object_dynamic_cast(obj, TYPE_DEVICE);
3176 qemu_printf(" %s:{%s", label, dev ? "dev" : "obj");
3177 if (dev && dev->id) {
3178 qemu_printf(" id=%s", dev->id);
3179 } else {
3180 char *canonical_path = object_get_canonical_path(obj);
3181 if (canonical_path) {
3182 qemu_printf(" path=%s", canonical_path);
3183 g_free(canonical_path);
3184 } else {
3185 qemu_printf(" type=%s", object_get_typename(obj));
3188 qemu_printf("}");
3191 static void mtree_print_mr_owner(const MemoryRegion *mr)
3193 Object *owner = mr->owner;
3194 Object *parent = memory_region_owner((MemoryRegion *)mr);
3196 if (!owner && !parent) {
3197 qemu_printf(" orphan");
3198 return;
3200 if (owner) {
3201 mtree_expand_owner("owner", owner);
3203 if (parent && parent != owner) {
3204 mtree_expand_owner("parent", parent);
3208 static void mtree_print_mr(const MemoryRegion *mr, unsigned int level,
3209 hwaddr base,
3210 MemoryRegionListHead *alias_print_queue,
3211 bool owner, bool display_disabled)
3213 MemoryRegionList *new_ml, *ml, *next_ml;
3214 MemoryRegionListHead submr_print_queue;
3215 const MemoryRegion *submr;
3216 unsigned int i;
3217 hwaddr cur_start, cur_end;
3219 if (!mr) {
3220 return;
3223 cur_start = base + mr->addr;
3224 cur_end = cur_start + MR_SIZE(mr->size);
3227 * Try to detect overflow of memory region. This should never
3228 * happen normally. When it happens, we dump something to warn the
3229 * user who is observing this.
3231 if (cur_start < base || cur_end < cur_start) {
3232 qemu_printf("[DETECTED OVERFLOW!] ");
3235 if (mr->alias) {
3236 MemoryRegionList *ml;
3237 bool found = false;
3239 /* check if the alias is already in the queue */
3240 QTAILQ_FOREACH(ml, alias_print_queue, mrqueue) {
3241 if (ml->mr == mr->alias) {
3242 found = true;
3246 if (!found) {
3247 ml = g_new(MemoryRegionList, 1);
3248 ml->mr = mr->alias;
3249 QTAILQ_INSERT_TAIL(alias_print_queue, ml, mrqueue);
3251 if (mr->enabled || display_disabled) {
3252 for (i = 0; i < level; i++) {
3253 qemu_printf(MTREE_INDENT);
3255 qemu_printf(HWADDR_FMT_plx "-" HWADDR_FMT_plx
3256 " (prio %d, %s%s): alias %s @%s " HWADDR_FMT_plx
3257 "-" HWADDR_FMT_plx "%s",
3258 cur_start, cur_end,
3259 mr->priority,
3260 mr->nonvolatile ? "nv-" : "",
3261 memory_region_type((MemoryRegion *)mr),
3262 memory_region_name(mr),
3263 memory_region_name(mr->alias),
3264 mr->alias_offset,
3265 mr->alias_offset + MR_SIZE(mr->size),
3266 mr->enabled ? "" : " [disabled]");
3267 if (owner) {
3268 mtree_print_mr_owner(mr);
3270 qemu_printf("\n");
3272 } else {
3273 if (mr->enabled || display_disabled) {
3274 for (i = 0; i < level; i++) {
3275 qemu_printf(MTREE_INDENT);
3277 qemu_printf(HWADDR_FMT_plx "-" HWADDR_FMT_plx
3278 " (prio %d, %s%s): %s%s",
3279 cur_start, cur_end,
3280 mr->priority,
3281 mr->nonvolatile ? "nv-" : "",
3282 memory_region_type((MemoryRegion *)mr),
3283 memory_region_name(mr),
3284 mr->enabled ? "" : " [disabled]");
3285 if (owner) {
3286 mtree_print_mr_owner(mr);
3288 qemu_printf("\n");
3292 QTAILQ_INIT(&submr_print_queue);
3294 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
3295 new_ml = g_new(MemoryRegionList, 1);
3296 new_ml->mr = submr;
3297 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3298 if (new_ml->mr->addr < ml->mr->addr ||
3299 (new_ml->mr->addr == ml->mr->addr &&
3300 new_ml->mr->priority > ml->mr->priority)) {
3301 QTAILQ_INSERT_BEFORE(ml, new_ml, mrqueue);
3302 new_ml = NULL;
3303 break;
3306 if (new_ml) {
3307 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, mrqueue);
3311 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3312 mtree_print_mr(ml->mr, level + 1, cur_start,
3313 alias_print_queue, owner, display_disabled);
3316 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, mrqueue, next_ml) {
3317 g_free(ml);
3321 struct FlatViewInfo {
3322 int counter;
3323 bool dispatch_tree;
3324 bool owner;
3325 AccelClass *ac;
3328 static void mtree_print_flatview(gpointer key, gpointer value,
3329 gpointer user_data)
3331 FlatView *view = key;
3332 GArray *fv_address_spaces = value;
3333 struct FlatViewInfo *fvi = user_data;
3334 FlatRange *range = &view->ranges[0];
3335 MemoryRegion *mr;
3336 int n = view->nr;
3337 int i;
3338 AddressSpace *as;
3340 qemu_printf("FlatView #%d\n", fvi->counter);
3341 ++fvi->counter;
3343 for (i = 0; i < fv_address_spaces->len; ++i) {
3344 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3345 qemu_printf(" AS \"%s\", root: %s",
3346 as->name, memory_region_name(as->root));
3347 if (as->root->alias) {
3348 qemu_printf(", alias %s", memory_region_name(as->root->alias));
3350 qemu_printf("\n");
3353 qemu_printf(" Root memory region: %s\n",
3354 view->root ? memory_region_name(view->root) : "(none)");
3356 if (n <= 0) {
3357 qemu_printf(MTREE_INDENT "No rendered FlatView\n\n");
3358 return;
3361 while (n--) {
3362 mr = range->mr;
3363 if (range->offset_in_region) {
3364 qemu_printf(MTREE_INDENT HWADDR_FMT_plx "-" HWADDR_FMT_plx
3365 " (prio %d, %s%s): %s @" HWADDR_FMT_plx,
3366 int128_get64(range->addr.start),
3367 int128_get64(range->addr.start)
3368 + MR_SIZE(range->addr.size),
3369 mr->priority,
3370 range->nonvolatile ? "nv-" : "",
3371 range->readonly ? "rom" : memory_region_type(mr),
3372 memory_region_name(mr),
3373 range->offset_in_region);
3374 } else {
3375 qemu_printf(MTREE_INDENT HWADDR_FMT_plx "-" HWADDR_FMT_plx
3376 " (prio %d, %s%s): %s",
3377 int128_get64(range->addr.start),
3378 int128_get64(range->addr.start)
3379 + MR_SIZE(range->addr.size),
3380 mr->priority,
3381 range->nonvolatile ? "nv-" : "",
3382 range->readonly ? "rom" : memory_region_type(mr),
3383 memory_region_name(mr));
3385 if (fvi->owner) {
3386 mtree_print_mr_owner(mr);
3389 if (fvi->ac) {
3390 for (i = 0; i < fv_address_spaces->len; ++i) {
3391 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3392 if (fvi->ac->has_memory(current_machine, as,
3393 int128_get64(range->addr.start),
3394 MR_SIZE(range->addr.size) + 1)) {
3395 qemu_printf(" %s", fvi->ac->name);
3399 qemu_printf("\n");
3400 range++;
3403 #if !defined(CONFIG_USER_ONLY)
3404 if (fvi->dispatch_tree && view->root) {
3405 mtree_print_dispatch(view->dispatch, view->root);
3407 #endif
3409 qemu_printf("\n");
3412 static gboolean mtree_info_flatview_free(gpointer key, gpointer value,
3413 gpointer user_data)
3415 FlatView *view = key;
3416 GArray *fv_address_spaces = value;
3418 g_array_unref(fv_address_spaces);
3419 flatview_unref(view);
3421 return true;
3424 static void mtree_info_flatview(bool dispatch_tree, bool owner)
3426 struct FlatViewInfo fvi = {
3427 .counter = 0,
3428 .dispatch_tree = dispatch_tree,
3429 .owner = owner,
3431 AddressSpace *as;
3432 FlatView *view;
3433 GArray *fv_address_spaces;
3434 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3435 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
3437 if (ac->has_memory) {
3438 fvi.ac = ac;
3441 /* Gather all FVs in one table */
3442 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3443 view = address_space_get_flatview(as);
3445 fv_address_spaces = g_hash_table_lookup(views, view);
3446 if (!fv_address_spaces) {
3447 fv_address_spaces = g_array_new(false, false, sizeof(as));
3448 g_hash_table_insert(views, view, fv_address_spaces);
3451 g_array_append_val(fv_address_spaces, as);
3454 /* Print */
3455 g_hash_table_foreach(views, mtree_print_flatview, &fvi);
3457 /* Free */
3458 g_hash_table_foreach_remove(views, mtree_info_flatview_free, 0);
3459 g_hash_table_unref(views);
3462 struct AddressSpaceInfo {
3463 MemoryRegionListHead *ml_head;
3464 bool owner;
3465 bool disabled;
3468 /* Returns negative value if a < b; zero if a = b; positive value if a > b. */
3469 static gint address_space_compare_name(gconstpointer a, gconstpointer b)
3471 const AddressSpace *as_a = a;
3472 const AddressSpace *as_b = b;
3474 return g_strcmp0(as_a->name, as_b->name);
3477 static void mtree_print_as_name(gpointer data, gpointer user_data)
3479 AddressSpace *as = data;
3481 qemu_printf("address-space: %s\n", as->name);
3484 static void mtree_print_as(gpointer key, gpointer value, gpointer user_data)
3486 MemoryRegion *mr = key;
3487 GSList *as_same_root_mr_list = value;
3488 struct AddressSpaceInfo *asi = user_data;
3490 g_slist_foreach(as_same_root_mr_list, mtree_print_as_name, NULL);
3491 mtree_print_mr(mr, 1, 0, asi->ml_head, asi->owner, asi->disabled);
3492 qemu_printf("\n");
3495 static gboolean mtree_info_as_free(gpointer key, gpointer value,
3496 gpointer user_data)
3498 GSList *as_same_root_mr_list = value;
3500 g_slist_free(as_same_root_mr_list);
3502 return true;
3505 static void mtree_info_as(bool dispatch_tree, bool owner, bool disabled)
3507 MemoryRegionListHead ml_head;
3508 MemoryRegionList *ml, *ml2;
3509 AddressSpace *as;
3510 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3511 GSList *as_same_root_mr_list;
3512 struct AddressSpaceInfo asi = {
3513 .ml_head = &ml_head,
3514 .owner = owner,
3515 .disabled = disabled,
3518 QTAILQ_INIT(&ml_head);
3520 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3521 /* Create hashtable, key=AS root MR, value = list of AS */
3522 as_same_root_mr_list = g_hash_table_lookup(views, as->root);
3523 as_same_root_mr_list = g_slist_insert_sorted(as_same_root_mr_list, as,
3524 address_space_compare_name);
3525 g_hash_table_insert(views, as->root, as_same_root_mr_list);
3528 /* print address spaces */
3529 g_hash_table_foreach(views, mtree_print_as, &asi);
3530 g_hash_table_foreach_remove(views, mtree_info_as_free, 0);
3531 g_hash_table_unref(views);
3533 /* print aliased regions */
3534 QTAILQ_FOREACH(ml, &ml_head, mrqueue) {
3535 qemu_printf("memory-region: %s\n", memory_region_name(ml->mr));
3536 mtree_print_mr(ml->mr, 1, 0, &ml_head, owner, disabled);
3537 qemu_printf("\n");
3540 QTAILQ_FOREACH_SAFE(ml, &ml_head, mrqueue, ml2) {
3541 g_free(ml);
3545 void mtree_info(bool flatview, bool dispatch_tree, bool owner, bool disabled)
3547 if (flatview) {
3548 mtree_info_flatview(dispatch_tree, owner);
3549 } else {
3550 mtree_info_as(dispatch_tree, owner, disabled);
3554 void memory_region_init_ram(MemoryRegion *mr,
3555 Object *owner,
3556 const char *name,
3557 uint64_t size,
3558 Error **errp)
3560 DeviceState *owner_dev;
3561 Error *err = NULL;
3563 memory_region_init_ram_nomigrate(mr, owner, name, size, &err);
3564 if (err) {
3565 error_propagate(errp, err);
3566 return;
3568 /* This will assert if owner is neither NULL nor a DeviceState.
3569 * We only want the owner here for the purposes of defining a
3570 * unique name for migration. TODO: Ideally we should implement
3571 * a naming scheme for Objects which are not DeviceStates, in
3572 * which case we can relax this restriction.
3574 owner_dev = DEVICE(owner);
3575 vmstate_register_ram(mr, owner_dev);
3578 void memory_region_init_rom(MemoryRegion *mr,
3579 Object *owner,
3580 const char *name,
3581 uint64_t size,
3582 Error **errp)
3584 DeviceState *owner_dev;
3585 Error *err = NULL;
3587 memory_region_init_rom_nomigrate(mr, owner, name, size, &err);
3588 if (err) {
3589 error_propagate(errp, err);
3590 return;
3592 /* This will assert if owner is neither NULL nor a DeviceState.
3593 * We only want the owner here for the purposes of defining a
3594 * unique name for migration. TODO: Ideally we should implement
3595 * a naming scheme for Objects which are not DeviceStates, in
3596 * which case we can relax this restriction.
3598 owner_dev = DEVICE(owner);
3599 vmstate_register_ram(mr, owner_dev);
3602 void memory_region_init_rom_device(MemoryRegion *mr,
3603 Object *owner,
3604 const MemoryRegionOps *ops,
3605 void *opaque,
3606 const char *name,
3607 uint64_t size,
3608 Error **errp)
3610 DeviceState *owner_dev;
3611 Error *err = NULL;
3613 memory_region_init_rom_device_nomigrate(mr, owner, ops, opaque,
3614 name, size, &err);
3615 if (err) {
3616 error_propagate(errp, err);
3617 return;
3619 /* This will assert if owner is neither NULL nor a DeviceState.
3620 * We only want the owner here for the purposes of defining a
3621 * unique name for migration. TODO: Ideally we should implement
3622 * a naming scheme for Objects which are not DeviceStates, in
3623 * which case we can relax this restriction.
3625 owner_dev = DEVICE(owner);
3626 vmstate_register_ram(mr, owner_dev);
3630 * Support softmmu builds with CONFIG_FUZZ using a weak symbol and a stub for
3631 * the fuzz_dma_read_cb callback
3633 #ifdef CONFIG_FUZZ
3634 void __attribute__((weak)) fuzz_dma_read_cb(size_t addr,
3635 size_t len,
3636 MemoryRegion *mr)
3639 #endif
3641 static const TypeInfo memory_region_info = {
3642 .parent = TYPE_OBJECT,
3643 .name = TYPE_MEMORY_REGION,
3644 .class_size = sizeof(MemoryRegionClass),
3645 .instance_size = sizeof(MemoryRegion),
3646 .instance_init = memory_region_initfn,
3647 .instance_finalize = memory_region_finalize,
3650 static const TypeInfo iommu_memory_region_info = {
3651 .parent = TYPE_MEMORY_REGION,
3652 .name = TYPE_IOMMU_MEMORY_REGION,
3653 .class_size = sizeof(IOMMUMemoryRegionClass),
3654 .instance_size = sizeof(IOMMUMemoryRegion),
3655 .instance_init = iommu_memory_region_initfn,
3656 .abstract = true,
3659 static const TypeInfo ram_discard_manager_info = {
3660 .parent = TYPE_INTERFACE,
3661 .name = TYPE_RAM_DISCARD_MANAGER,
3662 .class_size = sizeof(RamDiscardManagerClass),
3665 static void memory_register_types(void)
3667 type_register_static(&memory_region_info);
3668 type_register_static(&iommu_memory_region_info);
3669 type_register_static(&ram_discard_manager_info);
3672 type_init(memory_register_types)