2 * Physical memory management
4 * Copyright 2011 Red Hat, Inc. and/or its affiliates
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 "qapi/error.h"
18 #include "qemu-common.h"
20 #include "exec/memory.h"
21 #include "exec/address-spaces.h"
22 #include "exec/ioport.h"
23 #include "qapi/visitor.h"
24 #include "qemu/bitops.h"
25 #include "qemu/error-report.h"
26 #include "qom/object.h"
29 #include "exec/memory-internal.h"
30 #include "exec/ram_addr.h"
31 #include "sysemu/kvm.h"
32 #include "sysemu/sysemu.h"
34 //#define DEBUG_UNASSIGNED
36 #define RAM_ADDR_INVALID (~(ram_addr_t)0)
38 static unsigned memory_region_transaction_depth;
39 static bool memory_region_update_pending;
40 static bool ioeventfd_update_pending;
41 static bool global_dirty_log = false;
43 static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
44 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
46 static QTAILQ_HEAD(, AddressSpace) address_spaces
47 = QTAILQ_HEAD_INITIALIZER(address_spaces);
49 typedef struct AddrRange AddrRange;
52 * Note that signed integers are needed for negative offsetting in aliases
53 * (large MemoryRegion::alias_offset).
60 static AddrRange addrrange_make(Int128 start, Int128 size)
62 return (AddrRange) { start, size };
65 static bool addrrange_equal(AddrRange r1, AddrRange r2)
67 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
70 static Int128 addrrange_end(AddrRange r)
72 return int128_add(r.start, r.size);
75 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
77 int128_addto(&range.start, delta);
81 static bool addrrange_contains(AddrRange range, Int128 addr)
83 return int128_ge(addr, range.start)
84 && int128_lt(addr, addrrange_end(range));
87 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
89 return addrrange_contains(r1, r2.start)
90 || addrrange_contains(r2, r1.start);
93 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
95 Int128 start = int128_max(r1.start, r2.start);
96 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
97 return addrrange_make(start, int128_sub(end, start));
100 enum ListenerDirection { Forward, Reverse };
102 static bool memory_listener_match(MemoryListener *listener,
103 MemoryRegionSection *section)
105 return !listener->address_space_filter
106 || listener->address_space_filter == section->address_space;
109 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
111 MemoryListener *_listener; \
113 switch (_direction) { \
115 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
116 if (_listener->_callback) { \
117 _listener->_callback(_listener, ##_args); \
122 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
123 memory_listeners, link) { \
124 if (_listener->_callback) { \
125 _listener->_callback(_listener, ##_args); \
134 #define MEMORY_LISTENER_CALL(_callback, _direction, _section, _args...) \
136 MemoryListener *_listener; \
138 switch (_direction) { \
140 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
141 if (_listener->_callback \
142 && memory_listener_match(_listener, _section)) { \
143 _listener->_callback(_listener, _section, ##_args); \
148 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
149 memory_listeners, link) { \
150 if (_listener->_callback \
151 && memory_listener_match(_listener, _section)) { \
152 _listener->_callback(_listener, _section, ##_args); \
161 /* No need to ref/unref .mr, the FlatRange keeps it alive. */
162 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...) \
163 MEMORY_LISTENER_CALL(callback, dir, (&(MemoryRegionSection) { \
165 .address_space = (as), \
166 .offset_within_region = (fr)->offset_in_region, \
167 .size = (fr)->addr.size, \
168 .offset_within_address_space = int128_get64((fr)->addr.start), \
169 .readonly = (fr)->readonly, \
172 struct CoalescedMemoryRange {
174 QTAILQ_ENTRY(CoalescedMemoryRange) link;
177 struct MemoryRegionIoeventfd {
184 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
185 MemoryRegionIoeventfd b)
187 if (int128_lt(a.addr.start, b.addr.start)) {
189 } else if (int128_gt(a.addr.start, b.addr.start)) {
191 } else if (int128_lt(a.addr.size, b.addr.size)) {
193 } else if (int128_gt(a.addr.size, b.addr.size)) {
195 } else if (a.match_data < b.match_data) {
197 } else if (a.match_data > b.match_data) {
199 } else if (a.match_data) {
200 if (a.data < b.data) {
202 } else if (a.data > b.data) {
208 } else if (a.e > b.e) {
214 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
215 MemoryRegionIoeventfd b)
217 return !memory_region_ioeventfd_before(a, b)
218 && !memory_region_ioeventfd_before(b, a);
221 typedef struct FlatRange FlatRange;
222 typedef struct FlatView FlatView;
224 /* Range of memory in the global map. Addresses are absolute. */
227 hwaddr offset_in_region;
229 uint8_t dirty_log_mask;
233 /* Flattened global view of current active memory hierarchy. Kept in sorted
241 unsigned nr_allocated;
244 typedef struct AddressSpaceOps AddressSpaceOps;
246 #define FOR_EACH_FLAT_RANGE(var, view) \
247 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
249 static bool flatrange_equal(FlatRange *a, FlatRange *b)
251 return a->mr == b->mr
252 && addrrange_equal(a->addr, b->addr)
253 && a->offset_in_region == b->offset_in_region
254 && a->readonly == b->readonly;
257 static void flatview_init(FlatView *view)
262 view->nr_allocated = 0;
265 /* Insert a range into a given position. Caller is responsible for maintaining
268 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
270 if (view->nr == view->nr_allocated) {
271 view->nr_allocated = MAX(2 * view->nr, 10);
272 view->ranges = g_realloc(view->ranges,
273 view->nr_allocated * sizeof(*view->ranges));
275 memmove(view->ranges + pos + 1, view->ranges + pos,
276 (view->nr - pos) * sizeof(FlatRange));
277 view->ranges[pos] = *range;
278 memory_region_ref(range->mr);
282 static void flatview_destroy(FlatView *view)
286 for (i = 0; i < view->nr; i++) {
287 memory_region_unref(view->ranges[i].mr);
289 g_free(view->ranges);
293 static void flatview_ref(FlatView *view)
295 atomic_inc(&view->ref);
298 static void flatview_unref(FlatView *view)
300 if (atomic_fetch_dec(&view->ref) == 1) {
301 flatview_destroy(view);
305 static bool can_merge(FlatRange *r1, FlatRange *r2)
307 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
309 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
311 int128_make64(r2->offset_in_region))
312 && r1->dirty_log_mask == r2->dirty_log_mask
313 && r1->readonly == r2->readonly;
316 /* Attempt to simplify a view by merging adjacent ranges */
317 static void flatview_simplify(FlatView *view)
322 while (i < view->nr) {
325 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
326 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
330 memmove(&view->ranges[i], &view->ranges[j],
331 (view->nr - j) * sizeof(view->ranges[j]));
336 static bool memory_region_big_endian(MemoryRegion *mr)
338 #ifdef TARGET_WORDS_BIGENDIAN
339 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
341 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
345 static bool memory_region_wrong_endianness(MemoryRegion *mr)
347 #ifdef TARGET_WORDS_BIGENDIAN
348 return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
350 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
354 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
356 if (memory_region_wrong_endianness(mr)) {
361 *data = bswap16(*data);
364 *data = bswap32(*data);
367 *data = bswap64(*data);
375 static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
378 hwaddr abs_addr = offset;
380 abs_addr += mr->addr;
381 for (root = mr; root->container; ) {
382 root = root->container;
383 abs_addr += root->addr;
389 static int get_cpu_index(void)
392 return current_cpu->cpu_index;
397 static MemTxResult memory_region_oldmmio_read_accessor(MemoryRegion *mr,
407 tmp = mr->ops->old_mmio.read[ctz32(size)](mr->opaque, addr);
409 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
410 } else if (mr == &io_mem_notdirty) {
411 /* Accesses to code which has previously been translated into a TB show
412 * up in the MMIO path, as accesses to the io_mem_notdirty
414 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
415 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
416 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
417 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
419 *value |= (tmp & mask) << shift;
423 static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
433 tmp = mr->ops->read(mr->opaque, addr, size);
435 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
436 } else if (mr == &io_mem_notdirty) {
437 /* Accesses to code which has previously been translated into a TB show
438 * up in the MMIO path, as accesses to the io_mem_notdirty
440 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
441 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
442 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
443 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
445 *value |= (tmp & mask) << shift;
449 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
460 r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
462 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
463 } else if (mr == &io_mem_notdirty) {
464 /* Accesses to code which has previously been translated into a TB show
465 * up in the MMIO path, as accesses to the io_mem_notdirty
467 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
468 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
469 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
470 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
472 *value |= (tmp & mask) << shift;
476 static MemTxResult memory_region_oldmmio_write_accessor(MemoryRegion *mr,
486 tmp = (*value >> shift) & mask;
488 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
489 } else if (mr == &io_mem_notdirty) {
490 /* Accesses to code which has previously been translated into a TB show
491 * up in the MMIO path, as accesses to the io_mem_notdirty
493 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
494 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
495 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
496 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
498 mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);
502 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
512 tmp = (*value >> shift) & mask;
514 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
515 } else if (mr == &io_mem_notdirty) {
516 /* Accesses to code which has previously been translated into a TB show
517 * up in the MMIO path, as accesses to the io_mem_notdirty
519 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
520 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
521 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
522 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
524 mr->ops->write(mr->opaque, addr, tmp, size);
528 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
538 tmp = (*value >> shift) & mask;
540 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
541 } else if (mr == &io_mem_notdirty) {
542 /* Accesses to code which has previously been translated into a TB show
543 * up in the MMIO path, as accesses to the io_mem_notdirty
545 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
546 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
547 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
548 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
550 return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
553 static MemTxResult access_with_adjusted_size(hwaddr addr,
556 unsigned access_size_min,
557 unsigned access_size_max,
558 MemTxResult (*access)(MemoryRegion *mr,
568 uint64_t access_mask;
569 unsigned access_size;
571 MemTxResult r = MEMTX_OK;
573 if (!access_size_min) {
576 if (!access_size_max) {
580 /* FIXME: support unaligned access? */
581 access_size = MAX(MIN(size, access_size_max), access_size_min);
582 access_mask = -1ULL >> (64 - access_size * 8);
583 if (memory_region_big_endian(mr)) {
584 for (i = 0; i < size; i += access_size) {
585 r |= access(mr, addr + i, value, access_size,
586 (size - access_size - i) * 8, access_mask, attrs);
589 for (i = 0; i < size; i += access_size) {
590 r |= access(mr, addr + i, value, access_size, i * 8,
597 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
601 while (mr->container) {
604 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
605 if (mr == as->root) {
612 /* Render a memory region into the global view. Ranges in @view obscure
615 static void render_memory_region(FlatView *view,
621 MemoryRegion *subregion;
623 hwaddr offset_in_region;
633 int128_addto(&base, int128_make64(mr->addr));
634 readonly |= mr->readonly;
636 tmp = addrrange_make(base, mr->size);
638 if (!addrrange_intersects(tmp, clip)) {
642 clip = addrrange_intersection(tmp, clip);
645 int128_subfrom(&base, int128_make64(mr->alias->addr));
646 int128_subfrom(&base, int128_make64(mr->alias_offset));
647 render_memory_region(view, mr->alias, base, clip, readonly);
651 /* Render subregions in priority order. */
652 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
653 render_memory_region(view, subregion, base, clip, readonly);
656 if (!mr->terminates) {
660 offset_in_region = int128_get64(int128_sub(clip.start, base));
665 fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
666 fr.readonly = readonly;
668 /* Render the region itself into any gaps left by the current view. */
669 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
670 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
673 if (int128_lt(base, view->ranges[i].addr.start)) {
674 now = int128_min(remain,
675 int128_sub(view->ranges[i].addr.start, base));
676 fr.offset_in_region = offset_in_region;
677 fr.addr = addrrange_make(base, now);
678 flatview_insert(view, i, &fr);
680 int128_addto(&base, now);
681 offset_in_region += int128_get64(now);
682 int128_subfrom(&remain, now);
684 now = int128_sub(int128_min(int128_add(base, remain),
685 addrrange_end(view->ranges[i].addr)),
687 int128_addto(&base, now);
688 offset_in_region += int128_get64(now);
689 int128_subfrom(&remain, now);
691 if (int128_nz(remain)) {
692 fr.offset_in_region = offset_in_region;
693 fr.addr = addrrange_make(base, remain);
694 flatview_insert(view, i, &fr);
698 /* Render a memory topology into a list of disjoint absolute ranges. */
699 static FlatView *generate_memory_topology(MemoryRegion *mr)
703 view = g_new(FlatView, 1);
707 render_memory_region(view, mr, int128_zero(),
708 addrrange_make(int128_zero(), int128_2_64()), false);
710 flatview_simplify(view);
715 static void address_space_add_del_ioeventfds(AddressSpace *as,
716 MemoryRegionIoeventfd *fds_new,
718 MemoryRegionIoeventfd *fds_old,
722 MemoryRegionIoeventfd *fd;
723 MemoryRegionSection section;
725 /* Generate a symmetric difference of the old and new fd sets, adding
726 * and deleting as necessary.
730 while (iold < fds_old_nb || inew < fds_new_nb) {
731 if (iold < fds_old_nb
732 && (inew == fds_new_nb
733 || memory_region_ioeventfd_before(fds_old[iold],
736 section = (MemoryRegionSection) {
738 .offset_within_address_space = int128_get64(fd->addr.start),
739 .size = fd->addr.size,
741 MEMORY_LISTENER_CALL(eventfd_del, Forward, §ion,
742 fd->match_data, fd->data, fd->e);
744 } else if (inew < fds_new_nb
745 && (iold == fds_old_nb
746 || memory_region_ioeventfd_before(fds_new[inew],
749 section = (MemoryRegionSection) {
751 .offset_within_address_space = int128_get64(fd->addr.start),
752 .size = fd->addr.size,
754 MEMORY_LISTENER_CALL(eventfd_add, Reverse, §ion,
755 fd->match_data, fd->data, fd->e);
764 static FlatView *address_space_get_flatview(AddressSpace *as)
769 view = atomic_rcu_read(&as->current_map);
775 static void address_space_update_ioeventfds(AddressSpace *as)
779 unsigned ioeventfd_nb = 0;
780 MemoryRegionIoeventfd *ioeventfds = NULL;
784 view = address_space_get_flatview(as);
785 FOR_EACH_FLAT_RANGE(fr, view) {
786 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
787 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
788 int128_sub(fr->addr.start,
789 int128_make64(fr->offset_in_region)));
790 if (addrrange_intersects(fr->addr, tmp)) {
792 ioeventfds = g_realloc(ioeventfds,
793 ioeventfd_nb * sizeof(*ioeventfds));
794 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
795 ioeventfds[ioeventfd_nb-1].addr = tmp;
800 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
801 as->ioeventfds, as->ioeventfd_nb);
803 g_free(as->ioeventfds);
804 as->ioeventfds = ioeventfds;
805 as->ioeventfd_nb = ioeventfd_nb;
806 flatview_unref(view);
809 static void address_space_update_topology_pass(AddressSpace *as,
810 const FlatView *old_view,
811 const FlatView *new_view,
815 FlatRange *frold, *frnew;
817 /* Generate a symmetric difference of the old and new memory maps.
818 * Kill ranges in the old map, and instantiate ranges in the new map.
821 while (iold < old_view->nr || inew < new_view->nr) {
822 if (iold < old_view->nr) {
823 frold = &old_view->ranges[iold];
827 if (inew < new_view->nr) {
828 frnew = &new_view->ranges[inew];
835 || int128_lt(frold->addr.start, frnew->addr.start)
836 || (int128_eq(frold->addr.start, frnew->addr.start)
837 && !flatrange_equal(frold, frnew)))) {
838 /* In old but not in new, or in both but attributes changed. */
841 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
845 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
846 /* In both and unchanged (except logging may have changed) */
849 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
850 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
851 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
852 frold->dirty_log_mask,
853 frnew->dirty_log_mask);
855 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
856 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
857 frold->dirty_log_mask,
858 frnew->dirty_log_mask);
868 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
877 static void address_space_update_topology(AddressSpace *as)
879 FlatView *old_view = address_space_get_flatview(as);
880 FlatView *new_view = generate_memory_topology(as->root);
882 address_space_update_topology_pass(as, old_view, new_view, false);
883 address_space_update_topology_pass(as, old_view, new_view, true);
885 /* Writes are protected by the BQL. */
886 atomic_rcu_set(&as->current_map, new_view);
887 call_rcu(old_view, flatview_unref, rcu);
889 /* Note that all the old MemoryRegions are still alive up to this
890 * point. This relieves most MemoryListeners from the need to
891 * ref/unref the MemoryRegions they get---unless they use them
892 * outside the iothread mutex, in which case precise reference
893 * counting is necessary.
895 flatview_unref(old_view);
897 address_space_update_ioeventfds(as);
900 void memory_region_transaction_begin(void)
902 qemu_flush_coalesced_mmio_buffer();
903 ++memory_region_transaction_depth;
906 static void memory_region_clear_pending(void)
908 memory_region_update_pending = false;
909 ioeventfd_update_pending = false;
912 void memory_region_transaction_commit(void)
916 assert(memory_region_transaction_depth);
917 --memory_region_transaction_depth;
918 if (!memory_region_transaction_depth) {
919 if (memory_region_update_pending) {
920 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
922 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
923 address_space_update_topology(as);
926 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
927 } else if (ioeventfd_update_pending) {
928 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
929 address_space_update_ioeventfds(as);
932 memory_region_clear_pending();
936 static void memory_region_destructor_none(MemoryRegion *mr)
940 static void memory_region_destructor_ram(MemoryRegion *mr)
942 qemu_ram_free(mr->ram_block);
945 static void memory_region_destructor_rom_device(MemoryRegion *mr)
947 qemu_ram_free(mr->ram_block);
950 static bool memory_region_need_escape(char c)
952 return c == '/' || c == '[' || c == '\\' || c == ']';
955 static char *memory_region_escape_name(const char *name)
962 for (p = name; *p; p++) {
963 bytes += memory_region_need_escape(*p) ? 4 : 1;
965 if (bytes == p - name) {
966 return g_memdup(name, bytes + 1);
969 escaped = g_malloc(bytes + 1);
970 for (p = name, q = escaped; *p; p++) {
972 if (unlikely(memory_region_need_escape(c))) {
975 *q++ = "0123456789abcdef"[c >> 4];
976 c = "0123456789abcdef"[c & 15];
984 void memory_region_init(MemoryRegion *mr,
989 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
990 mr->size = int128_make64(size);
991 if (size == UINT64_MAX) {
992 mr->size = int128_2_64();
994 mr->name = g_strdup(name);
996 mr->ram_block = NULL;
999 char *escaped_name = memory_region_escape_name(name);
1000 char *name_array = g_strdup_printf("%s[*]", escaped_name);
1003 owner = container_get(qdev_get_machine(), "/unattached");
1006 object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
1007 object_unref(OBJECT(mr));
1009 g_free(escaped_name);
1013 static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
1014 void *opaque, Error **errp)
1016 MemoryRegion *mr = MEMORY_REGION(obj);
1017 uint64_t value = mr->addr;
1019 visit_type_uint64(v, name, &value, errp);
1022 static void memory_region_get_container(Object *obj, Visitor *v,
1023 const char *name, void *opaque,
1026 MemoryRegion *mr = MEMORY_REGION(obj);
1027 gchar *path = (gchar *)"";
1029 if (mr->container) {
1030 path = object_get_canonical_path(OBJECT(mr->container));
1032 visit_type_str(v, name, &path, errp);
1033 if (mr->container) {
1038 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1041 MemoryRegion *mr = MEMORY_REGION(obj);
1043 return OBJECT(mr->container);
1046 static void memory_region_get_priority(Object *obj, Visitor *v,
1047 const char *name, void *opaque,
1050 MemoryRegion *mr = MEMORY_REGION(obj);
1051 int32_t value = mr->priority;
1053 visit_type_int32(v, name, &value, errp);
1056 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1057 void *opaque, Error **errp)
1059 MemoryRegion *mr = MEMORY_REGION(obj);
1060 uint64_t value = memory_region_size(mr);
1062 visit_type_uint64(v, name, &value, errp);
1065 static void memory_region_initfn(Object *obj)
1067 MemoryRegion *mr = MEMORY_REGION(obj);
1070 mr->ops = &unassigned_mem_ops;
1072 mr->romd_mode = true;
1073 mr->global_locking = true;
1074 mr->destructor = memory_region_destructor_none;
1075 QTAILQ_INIT(&mr->subregions);
1076 QTAILQ_INIT(&mr->coalesced);
1078 op = object_property_add(OBJECT(mr), "container",
1079 "link<" TYPE_MEMORY_REGION ">",
1080 memory_region_get_container,
1081 NULL, /* memory_region_set_container */
1082 NULL, NULL, &error_abort);
1083 op->resolve = memory_region_resolve_container;
1085 object_property_add(OBJECT(mr), "addr", "uint64",
1086 memory_region_get_addr,
1087 NULL, /* memory_region_set_addr */
1088 NULL, NULL, &error_abort);
1089 object_property_add(OBJECT(mr), "priority", "uint32",
1090 memory_region_get_priority,
1091 NULL, /* memory_region_set_priority */
1092 NULL, NULL, &error_abort);
1093 object_property_add(OBJECT(mr), "size", "uint64",
1094 memory_region_get_size,
1095 NULL, /* memory_region_set_size, */
1096 NULL, NULL, &error_abort);
1099 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1102 #ifdef DEBUG_UNASSIGNED
1103 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1105 if (current_cpu != NULL) {
1106 cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1111 static void unassigned_mem_write(void *opaque, hwaddr addr,
1112 uint64_t val, unsigned size)
1114 #ifdef DEBUG_UNASSIGNED
1115 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1117 if (current_cpu != NULL) {
1118 cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1122 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1123 unsigned size, bool is_write)
1128 const MemoryRegionOps unassigned_mem_ops = {
1129 .valid.accepts = unassigned_mem_accepts,
1130 .endianness = DEVICE_NATIVE_ENDIAN,
1133 bool memory_region_access_valid(MemoryRegion *mr,
1138 int access_size_min, access_size_max;
1141 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1145 if (!mr->ops->valid.accepts) {
1149 access_size_min = mr->ops->valid.min_access_size;
1150 if (!mr->ops->valid.min_access_size) {
1151 access_size_min = 1;
1154 access_size_max = mr->ops->valid.max_access_size;
1155 if (!mr->ops->valid.max_access_size) {
1156 access_size_max = 4;
1159 access_size = MAX(MIN(size, access_size_max), access_size_min);
1160 for (i = 0; i < size; i += access_size) {
1161 if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
1170 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1178 if (mr->ops->read) {
1179 return access_with_adjusted_size(addr, pval, size,
1180 mr->ops->impl.min_access_size,
1181 mr->ops->impl.max_access_size,
1182 memory_region_read_accessor,
1184 } else if (mr->ops->read_with_attrs) {
1185 return access_with_adjusted_size(addr, pval, size,
1186 mr->ops->impl.min_access_size,
1187 mr->ops->impl.max_access_size,
1188 memory_region_read_with_attrs_accessor,
1191 return access_with_adjusted_size(addr, pval, size, 1, 4,
1192 memory_region_oldmmio_read_accessor,
1197 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1205 if (!memory_region_access_valid(mr, addr, size, false)) {
1206 *pval = unassigned_mem_read(mr, addr, size);
1207 return MEMTX_DECODE_ERROR;
1210 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1211 adjust_endianness(mr, pval, size);
1215 /* Return true if an eventfd was signalled */
1216 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1222 MemoryRegionIoeventfd ioeventfd = {
1223 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1228 for (i = 0; i < mr->ioeventfd_nb; i++) {
1229 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1230 ioeventfd.e = mr->ioeventfds[i].e;
1232 if (memory_region_ioeventfd_equal(ioeventfd, mr->ioeventfds[i])) {
1233 event_notifier_set(ioeventfd.e);
1241 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1247 if (!memory_region_access_valid(mr, addr, size, true)) {
1248 unassigned_mem_write(mr, addr, data, size);
1249 return MEMTX_DECODE_ERROR;
1252 adjust_endianness(mr, &data, size);
1254 if ((!kvm_eventfds_enabled()) &&
1255 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1259 if (mr->ops->write) {
1260 return access_with_adjusted_size(addr, &data, size,
1261 mr->ops->impl.min_access_size,
1262 mr->ops->impl.max_access_size,
1263 memory_region_write_accessor, mr,
1265 } else if (mr->ops->write_with_attrs) {
1267 access_with_adjusted_size(addr, &data, size,
1268 mr->ops->impl.min_access_size,
1269 mr->ops->impl.max_access_size,
1270 memory_region_write_with_attrs_accessor,
1273 return access_with_adjusted_size(addr, &data, size, 1, 4,
1274 memory_region_oldmmio_write_accessor,
1279 void memory_region_init_io(MemoryRegion *mr,
1281 const MemoryRegionOps *ops,
1286 memory_region_init(mr, owner, name, size);
1287 mr->ops = ops ? ops : &unassigned_mem_ops;
1288 mr->opaque = opaque;
1289 mr->terminates = true;
1292 void memory_region_init_ram(MemoryRegion *mr,
1298 memory_region_init(mr, owner, name, size);
1300 mr->terminates = true;
1301 mr->destructor = memory_region_destructor_ram;
1302 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1303 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1306 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1311 void (*resized)(const char*,
1316 memory_region_init(mr, owner, name, size);
1318 mr->terminates = true;
1319 mr->destructor = memory_region_destructor_ram;
1320 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1322 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1326 void memory_region_init_ram_from_file(MemoryRegion *mr,
1327 struct Object *owner,
1334 memory_region_init(mr, owner, name, size);
1336 mr->terminates = true;
1337 mr->destructor = memory_region_destructor_ram;
1338 mr->ram_block = qemu_ram_alloc_from_file(size, mr, share, path, errp);
1339 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1343 void memory_region_init_ram_ptr(MemoryRegion *mr,
1349 memory_region_init(mr, owner, name, size);
1351 mr->terminates = true;
1352 mr->destructor = memory_region_destructor_ram;
1353 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1355 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1356 assert(ptr != NULL);
1357 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1360 void memory_region_set_skip_dump(MemoryRegion *mr)
1362 mr->skip_dump = true;
1365 void memory_region_init_alias(MemoryRegion *mr,
1372 memory_region_init(mr, owner, name, size);
1374 mr->alias_offset = offset;
1377 void memory_region_init_rom_device(MemoryRegion *mr,
1379 const MemoryRegionOps *ops,
1385 memory_region_init(mr, owner, name, size);
1387 mr->opaque = opaque;
1388 mr->terminates = true;
1389 mr->rom_device = true;
1390 mr->destructor = memory_region_destructor_rom_device;
1391 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1394 void memory_region_init_iommu(MemoryRegion *mr,
1396 const MemoryRegionIOMMUOps *ops,
1400 memory_region_init(mr, owner, name, size);
1401 mr->iommu_ops = ops,
1402 mr->terminates = true; /* then re-forwards */
1403 notifier_list_init(&mr->iommu_notify);
1406 static void memory_region_finalize(Object *obj)
1408 MemoryRegion *mr = MEMORY_REGION(obj);
1410 assert(!mr->container);
1412 /* We know the region is not visible in any address space (it
1413 * does not have a container and cannot be a root either because
1414 * it has no references, so we can blindly clear mr->enabled.
1415 * memory_region_set_enabled instead could trigger a transaction
1416 * and cause an infinite loop.
1418 mr->enabled = false;
1419 memory_region_transaction_begin();
1420 while (!QTAILQ_EMPTY(&mr->subregions)) {
1421 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1422 memory_region_del_subregion(mr, subregion);
1424 memory_region_transaction_commit();
1427 memory_region_clear_coalescing(mr);
1428 g_free((char *)mr->name);
1429 g_free(mr->ioeventfds);
1432 Object *memory_region_owner(MemoryRegion *mr)
1434 Object *obj = OBJECT(mr);
1438 void memory_region_ref(MemoryRegion *mr)
1440 /* MMIO callbacks most likely will access data that belongs
1441 * to the owner, hence the need to ref/unref the owner whenever
1442 * the memory region is in use.
1444 * The memory region is a child of its owner. As long as the
1445 * owner doesn't call unparent itself on the memory region,
1446 * ref-ing the owner will also keep the memory region alive.
1447 * Memory regions without an owner are supposed to never go away;
1448 * we do not ref/unref them because it slows down DMA sensibly.
1450 if (mr && mr->owner) {
1451 object_ref(mr->owner);
1455 void memory_region_unref(MemoryRegion *mr)
1457 if (mr && mr->owner) {
1458 object_unref(mr->owner);
1462 uint64_t memory_region_size(MemoryRegion *mr)
1464 if (int128_eq(mr->size, int128_2_64())) {
1467 return int128_get64(mr->size);
1470 const char *memory_region_name(const MemoryRegion *mr)
1473 ((MemoryRegion *)mr)->name =
1474 object_get_canonical_path_component(OBJECT(mr));
1479 bool memory_region_is_skip_dump(MemoryRegion *mr)
1481 return mr->skip_dump;
1484 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1486 uint8_t mask = mr->dirty_log_mask;
1487 if (global_dirty_log) {
1488 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1493 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1495 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1498 void memory_region_register_iommu_notifier(MemoryRegion *mr, Notifier *n)
1500 notifier_list_add(&mr->iommu_notify, n);
1503 void memory_region_iommu_replay(MemoryRegion *mr, Notifier *n,
1504 hwaddr granularity, bool is_write)
1507 IOMMUTLBEntry iotlb;
1509 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1510 iotlb = mr->iommu_ops->translate(mr, addr, is_write);
1511 if (iotlb.perm != IOMMU_NONE) {
1512 n->notify(n, &iotlb);
1515 /* if (2^64 - MR size) < granularity, it's possible to get an
1516 * infinite loop here. This should catch such a wraparound */
1517 if ((addr + granularity) < addr) {
1523 void memory_region_unregister_iommu_notifier(Notifier *n)
1528 void memory_region_notify_iommu(MemoryRegion *mr,
1529 IOMMUTLBEntry entry)
1531 assert(memory_region_is_iommu(mr));
1532 notifier_list_notify(&mr->iommu_notify, &entry);
1535 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1537 uint8_t mask = 1 << client;
1538 uint8_t old_logging;
1540 assert(client == DIRTY_MEMORY_VGA);
1541 old_logging = mr->vga_logging_count;
1542 mr->vga_logging_count += log ? 1 : -1;
1543 if (!!old_logging == !!mr->vga_logging_count) {
1547 memory_region_transaction_begin();
1548 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1549 memory_region_update_pending |= mr->enabled;
1550 memory_region_transaction_commit();
1553 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1554 hwaddr size, unsigned client)
1556 assert(mr->ram_block);
1557 return cpu_physical_memory_get_dirty(memory_region_get_ram_addr(mr) + addr,
1561 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1564 assert(mr->ram_block);
1565 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
1567 memory_region_get_dirty_log_mask(mr));
1570 bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,
1571 hwaddr size, unsigned client)
1573 assert(mr->ram_block);
1574 return cpu_physical_memory_test_and_clear_dirty(
1575 memory_region_get_ram_addr(mr) + addr, size, client);
1579 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1584 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1585 FlatView *view = address_space_get_flatview(as);
1586 FOR_EACH_FLAT_RANGE(fr, view) {
1588 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1591 flatview_unref(view);
1595 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1597 if (mr->readonly != readonly) {
1598 memory_region_transaction_begin();
1599 mr->readonly = readonly;
1600 memory_region_update_pending |= mr->enabled;
1601 memory_region_transaction_commit();
1605 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
1607 if (mr->romd_mode != romd_mode) {
1608 memory_region_transaction_begin();
1609 mr->romd_mode = romd_mode;
1610 memory_region_update_pending |= mr->enabled;
1611 memory_region_transaction_commit();
1615 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1616 hwaddr size, unsigned client)
1618 assert(mr->ram_block);
1619 cpu_physical_memory_test_and_clear_dirty(
1620 memory_region_get_ram_addr(mr) + addr, size, client);
1623 int memory_region_get_fd(MemoryRegion *mr)
1626 return memory_region_get_fd(mr->alias);
1629 assert(mr->ram_block);
1631 return qemu_get_ram_fd(memory_region_get_ram_addr(mr));
1634 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1637 uint64_t offset = 0;
1641 offset += mr->alias_offset;
1644 assert(mr->ram_block);
1645 ptr = qemu_get_ram_ptr(mr->ram_block, memory_region_get_ram_addr(mr));
1648 return ptr + offset;
1651 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
1653 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
1656 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
1658 assert(mr->ram_block);
1660 qemu_ram_resize(mr->ram_block, newsize, errp);
1663 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1667 CoalescedMemoryRange *cmr;
1669 MemoryRegionSection section;
1671 view = address_space_get_flatview(as);
1672 FOR_EACH_FLAT_RANGE(fr, view) {
1674 section = (MemoryRegionSection) {
1675 .address_space = as,
1676 .offset_within_address_space = int128_get64(fr->addr.start),
1677 .size = fr->addr.size,
1680 MEMORY_LISTENER_CALL(coalesced_mmio_del, Reverse, §ion,
1681 int128_get64(fr->addr.start),
1682 int128_get64(fr->addr.size));
1683 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1684 tmp = addrrange_shift(cmr->addr,
1685 int128_sub(fr->addr.start,
1686 int128_make64(fr->offset_in_region)));
1687 if (!addrrange_intersects(tmp, fr->addr)) {
1690 tmp = addrrange_intersection(tmp, fr->addr);
1691 MEMORY_LISTENER_CALL(coalesced_mmio_add, Forward, §ion,
1692 int128_get64(tmp.start),
1693 int128_get64(tmp.size));
1697 flatview_unref(view);
1700 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1704 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1705 memory_region_update_coalesced_range_as(mr, as);
1709 void memory_region_set_coalescing(MemoryRegion *mr)
1711 memory_region_clear_coalescing(mr);
1712 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1715 void memory_region_add_coalescing(MemoryRegion *mr,
1719 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1721 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1722 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1723 memory_region_update_coalesced_range(mr);
1724 memory_region_set_flush_coalesced(mr);
1727 void memory_region_clear_coalescing(MemoryRegion *mr)
1729 CoalescedMemoryRange *cmr;
1730 bool updated = false;
1732 qemu_flush_coalesced_mmio_buffer();
1733 mr->flush_coalesced_mmio = false;
1735 while (!QTAILQ_EMPTY(&mr->coalesced)) {
1736 cmr = QTAILQ_FIRST(&mr->coalesced);
1737 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1743 memory_region_update_coalesced_range(mr);
1747 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1749 mr->flush_coalesced_mmio = true;
1752 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1754 qemu_flush_coalesced_mmio_buffer();
1755 if (QTAILQ_EMPTY(&mr->coalesced)) {
1756 mr->flush_coalesced_mmio = false;
1760 void memory_region_set_global_locking(MemoryRegion *mr)
1762 mr->global_locking = true;
1765 void memory_region_clear_global_locking(MemoryRegion *mr)
1767 mr->global_locking = false;
1770 static bool userspace_eventfd_warning;
1772 void memory_region_add_eventfd(MemoryRegion *mr,
1779 MemoryRegionIoeventfd mrfd = {
1780 .addr.start = int128_make64(addr),
1781 .addr.size = int128_make64(size),
1782 .match_data = match_data,
1788 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
1789 userspace_eventfd_warning))) {
1790 userspace_eventfd_warning = true;
1791 error_report("Using eventfd without MMIO binding in KVM. "
1792 "Suboptimal performance expected");
1796 adjust_endianness(mr, &mrfd.data, size);
1798 memory_region_transaction_begin();
1799 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1800 if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
1805 mr->ioeventfds = g_realloc(mr->ioeventfds,
1806 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
1807 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
1808 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
1809 mr->ioeventfds[i] = mrfd;
1810 ioeventfd_update_pending |= mr->enabled;
1811 memory_region_transaction_commit();
1814 void memory_region_del_eventfd(MemoryRegion *mr,
1821 MemoryRegionIoeventfd mrfd = {
1822 .addr.start = int128_make64(addr),
1823 .addr.size = int128_make64(size),
1824 .match_data = match_data,
1831 adjust_endianness(mr, &mrfd.data, size);
1833 memory_region_transaction_begin();
1834 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1835 if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
1839 assert(i != mr->ioeventfd_nb);
1840 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
1841 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
1843 mr->ioeventfds = g_realloc(mr->ioeventfds,
1844 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
1845 ioeventfd_update_pending |= mr->enabled;
1846 memory_region_transaction_commit();
1849 static void memory_region_update_container_subregions(MemoryRegion *subregion)
1851 MemoryRegion *mr = subregion->container;
1852 MemoryRegion *other;
1854 memory_region_transaction_begin();
1856 memory_region_ref(subregion);
1857 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1858 if (subregion->priority >= other->priority) {
1859 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
1863 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
1865 memory_region_update_pending |= mr->enabled && subregion->enabled;
1866 memory_region_transaction_commit();
1869 static void memory_region_add_subregion_common(MemoryRegion *mr,
1871 MemoryRegion *subregion)
1873 assert(!subregion->container);
1874 subregion->container = mr;
1875 subregion->addr = offset;
1876 memory_region_update_container_subregions(subregion);
1879 void memory_region_add_subregion(MemoryRegion *mr,
1881 MemoryRegion *subregion)
1883 subregion->priority = 0;
1884 memory_region_add_subregion_common(mr, offset, subregion);
1887 void memory_region_add_subregion_overlap(MemoryRegion *mr,
1889 MemoryRegion *subregion,
1892 subregion->priority = priority;
1893 memory_region_add_subregion_common(mr, offset, subregion);
1896 void memory_region_del_subregion(MemoryRegion *mr,
1897 MemoryRegion *subregion)
1899 memory_region_transaction_begin();
1900 assert(subregion->container == mr);
1901 subregion->container = NULL;
1902 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
1903 memory_region_unref(subregion);
1904 memory_region_update_pending |= mr->enabled && subregion->enabled;
1905 memory_region_transaction_commit();
1908 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
1910 if (enabled == mr->enabled) {
1913 memory_region_transaction_begin();
1914 mr->enabled = enabled;
1915 memory_region_update_pending = true;
1916 memory_region_transaction_commit();
1919 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
1921 Int128 s = int128_make64(size);
1923 if (size == UINT64_MAX) {
1926 if (int128_eq(s, mr->size)) {
1929 memory_region_transaction_begin();
1931 memory_region_update_pending = true;
1932 memory_region_transaction_commit();
1935 static void memory_region_readd_subregion(MemoryRegion *mr)
1937 MemoryRegion *container = mr->container;
1940 memory_region_transaction_begin();
1941 memory_region_ref(mr);
1942 memory_region_del_subregion(container, mr);
1943 mr->container = container;
1944 memory_region_update_container_subregions(mr);
1945 memory_region_unref(mr);
1946 memory_region_transaction_commit();
1950 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
1952 if (addr != mr->addr) {
1954 memory_region_readd_subregion(mr);
1958 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
1962 if (offset == mr->alias_offset) {
1966 memory_region_transaction_begin();
1967 mr->alias_offset = offset;
1968 memory_region_update_pending |= mr->enabled;
1969 memory_region_transaction_commit();
1972 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
1977 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
1979 const AddrRange *addr = addr_;
1980 const FlatRange *fr = fr_;
1982 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
1984 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
1990 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
1992 return bsearch(&addr, view->ranges, view->nr,
1993 sizeof(FlatRange), cmp_flatrange_addr);
1996 bool memory_region_is_mapped(MemoryRegion *mr)
1998 return mr->container ? true : false;
2001 /* Same as memory_region_find, but it does not add a reference to the
2002 * returned region. It must be called from an RCU critical section.
2004 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2005 hwaddr addr, uint64_t size)
2007 MemoryRegionSection ret = { .mr = NULL };
2015 for (root = mr; root->container; ) {
2016 root = root->container;
2020 as = memory_region_to_address_space(root);
2024 range = addrrange_make(int128_make64(addr), int128_make64(size));
2026 view = atomic_rcu_read(&as->current_map);
2027 fr = flatview_lookup(view, range);
2032 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2037 ret.address_space = as;
2038 range = addrrange_intersection(range, fr->addr);
2039 ret.offset_within_region = fr->offset_in_region;
2040 ret.offset_within_region += int128_get64(int128_sub(range.start,
2042 ret.size = range.size;
2043 ret.offset_within_address_space = int128_get64(range.start);
2044 ret.readonly = fr->readonly;
2048 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2049 hwaddr addr, uint64_t size)
2051 MemoryRegionSection ret;
2053 ret = memory_region_find_rcu(mr, addr, size);
2055 memory_region_ref(ret.mr);
2061 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2066 mr = memory_region_find_rcu(container, addr, 1).mr;
2068 return mr && mr != container;
2071 void address_space_sync_dirty_bitmap(AddressSpace *as)
2076 view = address_space_get_flatview(as);
2077 FOR_EACH_FLAT_RANGE(fr, view) {
2078 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
2080 flatview_unref(view);
2083 void memory_global_dirty_log_start(void)
2085 global_dirty_log = true;
2087 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2089 /* Refresh DIRTY_LOG_MIGRATION bit. */
2090 memory_region_transaction_begin();
2091 memory_region_update_pending = true;
2092 memory_region_transaction_commit();
2095 void memory_global_dirty_log_stop(void)
2097 global_dirty_log = false;
2099 /* Refresh DIRTY_LOG_MIGRATION bit. */
2100 memory_region_transaction_begin();
2101 memory_region_update_pending = true;
2102 memory_region_transaction_commit();
2104 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2107 static void listener_add_address_space(MemoryListener *listener,
2113 if (listener->address_space_filter
2114 && listener->address_space_filter != as) {
2118 if (listener->begin) {
2119 listener->begin(listener);
2121 if (global_dirty_log) {
2122 if (listener->log_global_start) {
2123 listener->log_global_start(listener);
2127 view = address_space_get_flatview(as);
2128 FOR_EACH_FLAT_RANGE(fr, view) {
2129 MemoryRegionSection section = {
2131 .address_space = as,
2132 .offset_within_region = fr->offset_in_region,
2133 .size = fr->addr.size,
2134 .offset_within_address_space = int128_get64(fr->addr.start),
2135 .readonly = fr->readonly,
2137 if (fr->dirty_log_mask && listener->log_start) {
2138 listener->log_start(listener, §ion, 0, fr->dirty_log_mask);
2140 if (listener->region_add) {
2141 listener->region_add(listener, §ion);
2144 if (listener->commit) {
2145 listener->commit(listener);
2147 flatview_unref(view);
2150 void memory_listener_register(MemoryListener *listener, AddressSpace *filter)
2152 MemoryListener *other = NULL;
2155 listener->address_space_filter = filter;
2156 if (QTAILQ_EMPTY(&memory_listeners)
2157 || listener->priority >= QTAILQ_LAST(&memory_listeners,
2158 memory_listeners)->priority) {
2159 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2161 QTAILQ_FOREACH(other, &memory_listeners, link) {
2162 if (listener->priority < other->priority) {
2166 QTAILQ_INSERT_BEFORE(other, listener, link);
2169 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2170 listener_add_address_space(listener, as);
2174 void memory_listener_unregister(MemoryListener *listener)
2176 QTAILQ_REMOVE(&memory_listeners, listener, link);
2179 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2181 memory_region_ref(root);
2182 memory_region_transaction_begin();
2185 as->malloced = false;
2186 as->current_map = g_new(FlatView, 1);
2187 flatview_init(as->current_map);
2188 as->ioeventfd_nb = 0;
2189 as->ioeventfds = NULL;
2190 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2191 as->name = g_strdup(name ? name : "anonymous");
2192 address_space_init_dispatch(as);
2193 memory_region_update_pending |= root->enabled;
2194 memory_region_transaction_commit();
2197 static void do_address_space_destroy(AddressSpace *as)
2199 MemoryListener *listener;
2200 bool do_free = as->malloced;
2202 address_space_destroy_dispatch(as);
2204 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2205 assert(listener->address_space_filter != as);
2208 flatview_unref(as->current_map);
2210 g_free(as->ioeventfds);
2211 memory_region_unref(as->root);
2217 AddressSpace *address_space_init_shareable(MemoryRegion *root, const char *name)
2221 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2222 if (root == as->root && as->malloced) {
2228 as = g_malloc0(sizeof *as);
2229 address_space_init(as, root, name);
2230 as->malloced = true;
2234 void address_space_destroy(AddressSpace *as)
2236 MemoryRegion *root = as->root;
2239 if (as->ref_count) {
2242 /* Flush out anything from MemoryListeners listening in on this */
2243 memory_region_transaction_begin();
2245 memory_region_transaction_commit();
2246 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2247 address_space_unregister(as);
2249 /* At this point, as->dispatch and as->current_map are dummy
2250 * entries that the guest should never use. Wait for the old
2251 * values to expire before freeing the data.
2254 call_rcu(as, do_address_space_destroy, rcu);
2257 typedef struct MemoryRegionList MemoryRegionList;
2259 struct MemoryRegionList {
2260 const MemoryRegion *mr;
2261 QTAILQ_ENTRY(MemoryRegionList) queue;
2264 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
2266 static void mtree_print_mr(fprintf_function mon_printf, void *f,
2267 const MemoryRegion *mr, unsigned int level,
2269 MemoryRegionListHead *alias_print_queue)
2271 MemoryRegionList *new_ml, *ml, *next_ml;
2272 MemoryRegionListHead submr_print_queue;
2273 const MemoryRegion *submr;
2280 for (i = 0; i < level; i++) {
2285 MemoryRegionList *ml;
2288 /* check if the alias is already in the queue */
2289 QTAILQ_FOREACH(ml, alias_print_queue, queue) {
2290 if (ml->mr == mr->alias) {
2296 ml = g_new(MemoryRegionList, 1);
2298 QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
2300 mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
2301 " (prio %d, %c%c): alias %s @%s " TARGET_FMT_plx
2302 "-" TARGET_FMT_plx "%s\n",
2305 + (int128_nz(mr->size) ?
2306 (hwaddr)int128_get64(int128_sub(mr->size,
2307 int128_one())) : 0),
2309 mr->romd_mode ? 'R' : '-',
2310 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2312 memory_region_name(mr),
2313 memory_region_name(mr->alias),
2316 + (int128_nz(mr->size) ?
2317 (hwaddr)int128_get64(int128_sub(mr->size,
2318 int128_one())) : 0),
2319 mr->enabled ? "" : " [disabled]");
2322 TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %c%c): %s%s\n",
2325 + (int128_nz(mr->size) ?
2326 (hwaddr)int128_get64(int128_sub(mr->size,
2327 int128_one())) : 0),
2329 mr->romd_mode ? 'R' : '-',
2330 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2332 memory_region_name(mr),
2333 mr->enabled ? "" : " [disabled]");
2336 QTAILQ_INIT(&submr_print_queue);
2338 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2339 new_ml = g_new(MemoryRegionList, 1);
2341 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2342 if (new_ml->mr->addr < ml->mr->addr ||
2343 (new_ml->mr->addr == ml->mr->addr &&
2344 new_ml->mr->priority > ml->mr->priority)) {
2345 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
2351 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
2355 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2356 mtree_print_mr(mon_printf, f, ml->mr, level + 1, base + mr->addr,
2360 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
2365 void mtree_info(fprintf_function mon_printf, void *f)
2367 MemoryRegionListHead ml_head;
2368 MemoryRegionList *ml, *ml2;
2371 QTAILQ_INIT(&ml_head);
2373 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2374 mon_printf(f, "address-space: %s\n", as->name);
2375 mtree_print_mr(mon_printf, f, as->root, 1, 0, &ml_head);
2376 mon_printf(f, "\n");
2379 /* print aliased regions */
2380 QTAILQ_FOREACH(ml, &ml_head, queue) {
2381 mon_printf(f, "memory-region: %s\n", memory_region_name(ml->mr));
2382 mtree_print_mr(mon_printf, f, ml->mr, 1, 0, &ml_head);
2383 mon_printf(f, "\n");
2386 QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
2391 static const TypeInfo memory_region_info = {
2392 .parent = TYPE_OBJECT,
2393 .name = TYPE_MEMORY_REGION,
2394 .instance_size = sizeof(MemoryRegion),
2395 .instance_init = memory_region_initfn,
2396 .instance_finalize = memory_region_finalize,
2399 static void memory_register_types(void)
2401 type_register_static(&memory_region_info);
2404 type_init(memory_register_types)