Merge remote-tracking branch 'remotes/pmaydell/tags/pull-target-arm-20140829' into...
[qemu/cris-port.git] / memory.c
blobef0be1c3aac7a4c2ce41686e04bfb9cd4d6bc1e8
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 "exec/memory.h"
17 #include "exec/address-spaces.h"
18 #include "exec/ioport.h"
19 #include "qapi/visitor.h"
20 #include "qemu/bitops.h"
21 #include "qom/object.h"
22 #include "trace.h"
23 #include <assert.h>
25 #include "exec/memory-internal.h"
26 #include "exec/ram_addr.h"
27 #include "sysemu/sysemu.h"
29 //#define DEBUG_UNASSIGNED
31 static unsigned memory_region_transaction_depth;
32 static bool memory_region_update_pending;
33 static bool ioeventfd_update_pending;
34 static bool global_dirty_log = false;
36 /* flat_view_mutex is taken around reading as->current_map; the critical
37 * section is extremely short, so I'm using a single mutex for every AS.
38 * We could also RCU for the read-side.
40 * The BQL is taken around transaction commits, hence both locks are taken
41 * while writing to as->current_map (with the BQL taken outside).
43 static QemuMutex flat_view_mutex;
45 static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
46 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
48 static QTAILQ_HEAD(, AddressSpace) address_spaces
49 = QTAILQ_HEAD_INITIALIZER(address_spaces);
51 static void memory_init(void)
53 qemu_mutex_init(&flat_view_mutex);
56 typedef struct AddrRange AddrRange;
59 * Note that signed integers are needed for negative offsetting in aliases
60 * (large MemoryRegion::alias_offset).
62 struct AddrRange {
63 Int128 start;
64 Int128 size;
67 static AddrRange addrrange_make(Int128 start, Int128 size)
69 return (AddrRange) { start, size };
72 static bool addrrange_equal(AddrRange r1, AddrRange r2)
74 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
77 static Int128 addrrange_end(AddrRange r)
79 return int128_add(r.start, r.size);
82 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
84 int128_addto(&range.start, delta);
85 return range;
88 static bool addrrange_contains(AddrRange range, Int128 addr)
90 return int128_ge(addr, range.start)
91 && int128_lt(addr, addrrange_end(range));
94 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
96 return addrrange_contains(r1, r2.start)
97 || addrrange_contains(r2, r1.start);
100 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
102 Int128 start = int128_max(r1.start, r2.start);
103 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
104 return addrrange_make(start, int128_sub(end, start));
107 enum ListenerDirection { Forward, Reverse };
109 static bool memory_listener_match(MemoryListener *listener,
110 MemoryRegionSection *section)
112 return !listener->address_space_filter
113 || listener->address_space_filter == section->address_space;
116 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
117 do { \
118 MemoryListener *_listener; \
120 switch (_direction) { \
121 case Forward: \
122 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
123 if (_listener->_callback) { \
124 _listener->_callback(_listener, ##_args); \
127 break; \
128 case Reverse: \
129 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
130 memory_listeners, link) { \
131 if (_listener->_callback) { \
132 _listener->_callback(_listener, ##_args); \
135 break; \
136 default: \
137 abort(); \
139 } while (0)
141 #define MEMORY_LISTENER_CALL(_callback, _direction, _section, _args...) \
142 do { \
143 MemoryListener *_listener; \
145 switch (_direction) { \
146 case Forward: \
147 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
148 if (_listener->_callback \
149 && memory_listener_match(_listener, _section)) { \
150 _listener->_callback(_listener, _section, ##_args); \
153 break; \
154 case Reverse: \
155 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
156 memory_listeners, link) { \
157 if (_listener->_callback \
158 && memory_listener_match(_listener, _section)) { \
159 _listener->_callback(_listener, _section, ##_args); \
162 break; \
163 default: \
164 abort(); \
166 } while (0)
168 /* No need to ref/unref .mr, the FlatRange keeps it alive. */
169 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback) \
170 MEMORY_LISTENER_CALL(callback, dir, (&(MemoryRegionSection) { \
171 .mr = (fr)->mr, \
172 .address_space = (as), \
173 .offset_within_region = (fr)->offset_in_region, \
174 .size = (fr)->addr.size, \
175 .offset_within_address_space = int128_get64((fr)->addr.start), \
176 .readonly = (fr)->readonly, \
179 struct CoalescedMemoryRange {
180 AddrRange addr;
181 QTAILQ_ENTRY(CoalescedMemoryRange) link;
184 struct MemoryRegionIoeventfd {
185 AddrRange addr;
186 bool match_data;
187 uint64_t data;
188 EventNotifier *e;
191 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
192 MemoryRegionIoeventfd b)
194 if (int128_lt(a.addr.start, b.addr.start)) {
195 return true;
196 } else if (int128_gt(a.addr.start, b.addr.start)) {
197 return false;
198 } else if (int128_lt(a.addr.size, b.addr.size)) {
199 return true;
200 } else if (int128_gt(a.addr.size, b.addr.size)) {
201 return false;
202 } else if (a.match_data < b.match_data) {
203 return true;
204 } else if (a.match_data > b.match_data) {
205 return false;
206 } else if (a.match_data) {
207 if (a.data < b.data) {
208 return true;
209 } else if (a.data > b.data) {
210 return false;
213 if (a.e < b.e) {
214 return true;
215 } else if (a.e > b.e) {
216 return false;
218 return false;
221 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
222 MemoryRegionIoeventfd b)
224 return !memory_region_ioeventfd_before(a, b)
225 && !memory_region_ioeventfd_before(b, a);
228 typedef struct FlatRange FlatRange;
229 typedef struct FlatView FlatView;
231 /* Range of memory in the global map. Addresses are absolute. */
232 struct FlatRange {
233 MemoryRegion *mr;
234 hwaddr offset_in_region;
235 AddrRange addr;
236 uint8_t dirty_log_mask;
237 bool romd_mode;
238 bool readonly;
241 /* Flattened global view of current active memory hierarchy. Kept in sorted
242 * order.
244 struct FlatView {
245 unsigned ref;
246 FlatRange *ranges;
247 unsigned nr;
248 unsigned nr_allocated;
251 typedef struct AddressSpaceOps AddressSpaceOps;
253 #define FOR_EACH_FLAT_RANGE(var, view) \
254 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
256 static bool flatrange_equal(FlatRange *a, FlatRange *b)
258 return a->mr == b->mr
259 && addrrange_equal(a->addr, b->addr)
260 && a->offset_in_region == b->offset_in_region
261 && a->romd_mode == b->romd_mode
262 && a->readonly == b->readonly;
265 static void flatview_init(FlatView *view)
267 view->ref = 1;
268 view->ranges = NULL;
269 view->nr = 0;
270 view->nr_allocated = 0;
273 /* Insert a range into a given position. Caller is responsible for maintaining
274 * sorting order.
276 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
278 if (view->nr == view->nr_allocated) {
279 view->nr_allocated = MAX(2 * view->nr, 10);
280 view->ranges = g_realloc(view->ranges,
281 view->nr_allocated * sizeof(*view->ranges));
283 memmove(view->ranges + pos + 1, view->ranges + pos,
284 (view->nr - pos) * sizeof(FlatRange));
285 view->ranges[pos] = *range;
286 memory_region_ref(range->mr);
287 ++view->nr;
290 static void flatview_destroy(FlatView *view)
292 int i;
294 for (i = 0; i < view->nr; i++) {
295 memory_region_unref(view->ranges[i].mr);
297 g_free(view->ranges);
298 g_free(view);
301 static void flatview_ref(FlatView *view)
303 atomic_inc(&view->ref);
306 static void flatview_unref(FlatView *view)
308 if (atomic_fetch_dec(&view->ref) == 1) {
309 flatview_destroy(view);
313 static bool can_merge(FlatRange *r1, FlatRange *r2)
315 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
316 && r1->mr == r2->mr
317 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
318 r1->addr.size),
319 int128_make64(r2->offset_in_region))
320 && r1->dirty_log_mask == r2->dirty_log_mask
321 && r1->romd_mode == r2->romd_mode
322 && r1->readonly == r2->readonly;
325 /* Attempt to simplify a view by merging adjacent ranges */
326 static void flatview_simplify(FlatView *view)
328 unsigned i, j;
330 i = 0;
331 while (i < view->nr) {
332 j = i + 1;
333 while (j < view->nr
334 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
335 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
336 ++j;
338 ++i;
339 memmove(&view->ranges[i], &view->ranges[j],
340 (view->nr - j) * sizeof(view->ranges[j]));
341 view->nr -= j - i;
345 static bool memory_region_big_endian(MemoryRegion *mr)
347 #ifdef TARGET_WORDS_BIGENDIAN
348 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
349 #else
350 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
351 #endif
354 static bool memory_region_wrong_endianness(MemoryRegion *mr)
356 #ifdef TARGET_WORDS_BIGENDIAN
357 return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
358 #else
359 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
360 #endif
363 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
365 if (memory_region_wrong_endianness(mr)) {
366 switch (size) {
367 case 1:
368 break;
369 case 2:
370 *data = bswap16(*data);
371 break;
372 case 4:
373 *data = bswap32(*data);
374 break;
375 case 8:
376 *data = bswap64(*data);
377 break;
378 default:
379 abort();
384 static void memory_region_oldmmio_read_accessor(MemoryRegion *mr,
385 hwaddr addr,
386 uint64_t *value,
387 unsigned size,
388 unsigned shift,
389 uint64_t mask)
391 uint64_t tmp;
393 tmp = mr->ops->old_mmio.read[ctz32(size)](mr->opaque, addr);
394 trace_memory_region_ops_read(mr, addr, tmp, size);
395 *value |= (tmp & mask) << shift;
398 static void memory_region_read_accessor(MemoryRegion *mr,
399 hwaddr addr,
400 uint64_t *value,
401 unsigned size,
402 unsigned shift,
403 uint64_t mask)
405 uint64_t tmp;
407 if (mr->flush_coalesced_mmio) {
408 qemu_flush_coalesced_mmio_buffer();
410 tmp = mr->ops->read(mr->opaque, addr, size);
411 trace_memory_region_ops_read(mr, addr, tmp, size);
412 *value |= (tmp & mask) << shift;
415 static void memory_region_oldmmio_write_accessor(MemoryRegion *mr,
416 hwaddr addr,
417 uint64_t *value,
418 unsigned size,
419 unsigned shift,
420 uint64_t mask)
422 uint64_t tmp;
424 tmp = (*value >> shift) & mask;
425 trace_memory_region_ops_write(mr, addr, tmp, size);
426 mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);
429 static void memory_region_write_accessor(MemoryRegion *mr,
430 hwaddr addr,
431 uint64_t *value,
432 unsigned size,
433 unsigned shift,
434 uint64_t mask)
436 uint64_t tmp;
438 if (mr->flush_coalesced_mmio) {
439 qemu_flush_coalesced_mmio_buffer();
441 tmp = (*value >> shift) & mask;
442 trace_memory_region_ops_write(mr, addr, tmp, size);
443 mr->ops->write(mr->opaque, addr, tmp, size);
446 static void access_with_adjusted_size(hwaddr addr,
447 uint64_t *value,
448 unsigned size,
449 unsigned access_size_min,
450 unsigned access_size_max,
451 void (*access)(MemoryRegion *mr,
452 hwaddr addr,
453 uint64_t *value,
454 unsigned size,
455 unsigned shift,
456 uint64_t mask),
457 MemoryRegion *mr)
459 uint64_t access_mask;
460 unsigned access_size;
461 unsigned i;
463 if (!access_size_min) {
464 access_size_min = 1;
466 if (!access_size_max) {
467 access_size_max = 4;
470 /* FIXME: support unaligned access? */
471 access_size = MAX(MIN(size, access_size_max), access_size_min);
472 access_mask = -1ULL >> (64 - access_size * 8);
473 if (memory_region_big_endian(mr)) {
474 for (i = 0; i < size; i += access_size) {
475 access(mr, addr + i, value, access_size,
476 (size - access_size - i) * 8, access_mask);
478 } else {
479 for (i = 0; i < size; i += access_size) {
480 access(mr, addr + i, value, access_size, i * 8, access_mask);
485 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
487 AddressSpace *as;
489 while (mr->container) {
490 mr = mr->container;
492 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
493 if (mr == as->root) {
494 return as;
497 return NULL;
500 /* Render a memory region into the global view. Ranges in @view obscure
501 * ranges in @mr.
503 static void render_memory_region(FlatView *view,
504 MemoryRegion *mr,
505 Int128 base,
506 AddrRange clip,
507 bool readonly)
509 MemoryRegion *subregion;
510 unsigned i;
511 hwaddr offset_in_region;
512 Int128 remain;
513 Int128 now;
514 FlatRange fr;
515 AddrRange tmp;
517 if (!mr->enabled) {
518 return;
521 int128_addto(&base, int128_make64(mr->addr));
522 readonly |= mr->readonly;
524 tmp = addrrange_make(base, mr->size);
526 if (!addrrange_intersects(tmp, clip)) {
527 return;
530 clip = addrrange_intersection(tmp, clip);
532 if (mr->alias) {
533 int128_subfrom(&base, int128_make64(mr->alias->addr));
534 int128_subfrom(&base, int128_make64(mr->alias_offset));
535 render_memory_region(view, mr->alias, base, clip, readonly);
536 return;
539 /* Render subregions in priority order. */
540 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
541 render_memory_region(view, subregion, base, clip, readonly);
544 if (!mr->terminates) {
545 return;
548 offset_in_region = int128_get64(int128_sub(clip.start, base));
549 base = clip.start;
550 remain = clip.size;
552 fr.mr = mr;
553 fr.dirty_log_mask = mr->dirty_log_mask;
554 fr.romd_mode = mr->romd_mode;
555 fr.readonly = readonly;
557 /* Render the region itself into any gaps left by the current view. */
558 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
559 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
560 continue;
562 if (int128_lt(base, view->ranges[i].addr.start)) {
563 now = int128_min(remain,
564 int128_sub(view->ranges[i].addr.start, base));
565 fr.offset_in_region = offset_in_region;
566 fr.addr = addrrange_make(base, now);
567 flatview_insert(view, i, &fr);
568 ++i;
569 int128_addto(&base, now);
570 offset_in_region += int128_get64(now);
571 int128_subfrom(&remain, now);
573 now = int128_sub(int128_min(int128_add(base, remain),
574 addrrange_end(view->ranges[i].addr)),
575 base);
576 int128_addto(&base, now);
577 offset_in_region += int128_get64(now);
578 int128_subfrom(&remain, now);
580 if (int128_nz(remain)) {
581 fr.offset_in_region = offset_in_region;
582 fr.addr = addrrange_make(base, remain);
583 flatview_insert(view, i, &fr);
587 /* Render a memory topology into a list of disjoint absolute ranges. */
588 static FlatView *generate_memory_topology(MemoryRegion *mr)
590 FlatView *view;
592 view = g_new(FlatView, 1);
593 flatview_init(view);
595 if (mr) {
596 render_memory_region(view, mr, int128_zero(),
597 addrrange_make(int128_zero(), int128_2_64()), false);
599 flatview_simplify(view);
601 return view;
604 static void address_space_add_del_ioeventfds(AddressSpace *as,
605 MemoryRegionIoeventfd *fds_new,
606 unsigned fds_new_nb,
607 MemoryRegionIoeventfd *fds_old,
608 unsigned fds_old_nb)
610 unsigned iold, inew;
611 MemoryRegionIoeventfd *fd;
612 MemoryRegionSection section;
614 /* Generate a symmetric difference of the old and new fd sets, adding
615 * and deleting as necessary.
618 iold = inew = 0;
619 while (iold < fds_old_nb || inew < fds_new_nb) {
620 if (iold < fds_old_nb
621 && (inew == fds_new_nb
622 || memory_region_ioeventfd_before(fds_old[iold],
623 fds_new[inew]))) {
624 fd = &fds_old[iold];
625 section = (MemoryRegionSection) {
626 .address_space = as,
627 .offset_within_address_space = int128_get64(fd->addr.start),
628 .size = fd->addr.size,
630 MEMORY_LISTENER_CALL(eventfd_del, Forward, &section,
631 fd->match_data, fd->data, fd->e);
632 ++iold;
633 } else if (inew < fds_new_nb
634 && (iold == fds_old_nb
635 || memory_region_ioeventfd_before(fds_new[inew],
636 fds_old[iold]))) {
637 fd = &fds_new[inew];
638 section = (MemoryRegionSection) {
639 .address_space = as,
640 .offset_within_address_space = int128_get64(fd->addr.start),
641 .size = fd->addr.size,
643 MEMORY_LISTENER_CALL(eventfd_add, Reverse, &section,
644 fd->match_data, fd->data, fd->e);
645 ++inew;
646 } else {
647 ++iold;
648 ++inew;
653 static FlatView *address_space_get_flatview(AddressSpace *as)
655 FlatView *view;
657 qemu_mutex_lock(&flat_view_mutex);
658 view = as->current_map;
659 flatview_ref(view);
660 qemu_mutex_unlock(&flat_view_mutex);
661 return view;
664 static void address_space_update_ioeventfds(AddressSpace *as)
666 FlatView *view;
667 FlatRange *fr;
668 unsigned ioeventfd_nb = 0;
669 MemoryRegionIoeventfd *ioeventfds = NULL;
670 AddrRange tmp;
671 unsigned i;
673 view = address_space_get_flatview(as);
674 FOR_EACH_FLAT_RANGE(fr, view) {
675 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
676 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
677 int128_sub(fr->addr.start,
678 int128_make64(fr->offset_in_region)));
679 if (addrrange_intersects(fr->addr, tmp)) {
680 ++ioeventfd_nb;
681 ioeventfds = g_realloc(ioeventfds,
682 ioeventfd_nb * sizeof(*ioeventfds));
683 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
684 ioeventfds[ioeventfd_nb-1].addr = tmp;
689 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
690 as->ioeventfds, as->ioeventfd_nb);
692 g_free(as->ioeventfds);
693 as->ioeventfds = ioeventfds;
694 as->ioeventfd_nb = ioeventfd_nb;
695 flatview_unref(view);
698 static void address_space_update_topology_pass(AddressSpace *as,
699 const FlatView *old_view,
700 const FlatView *new_view,
701 bool adding)
703 unsigned iold, inew;
704 FlatRange *frold, *frnew;
706 /* Generate a symmetric difference of the old and new memory maps.
707 * Kill ranges in the old map, and instantiate ranges in the new map.
709 iold = inew = 0;
710 while (iold < old_view->nr || inew < new_view->nr) {
711 if (iold < old_view->nr) {
712 frold = &old_view->ranges[iold];
713 } else {
714 frold = NULL;
716 if (inew < new_view->nr) {
717 frnew = &new_view->ranges[inew];
718 } else {
719 frnew = NULL;
722 if (frold
723 && (!frnew
724 || int128_lt(frold->addr.start, frnew->addr.start)
725 || (int128_eq(frold->addr.start, frnew->addr.start)
726 && !flatrange_equal(frold, frnew)))) {
727 /* In old but not in new, or in both but attributes changed. */
729 if (!adding) {
730 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
733 ++iold;
734 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
735 /* In both and unchanged (except logging may have changed) */
737 if (adding) {
738 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
739 if (frold->dirty_log_mask && !frnew->dirty_log_mask) {
740 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop);
741 } else if (frnew->dirty_log_mask && !frold->dirty_log_mask) {
742 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start);
746 ++iold;
747 ++inew;
748 } else {
749 /* In new */
751 if (adding) {
752 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
755 ++inew;
761 static void address_space_update_topology(AddressSpace *as)
763 FlatView *old_view = address_space_get_flatview(as);
764 FlatView *new_view = generate_memory_topology(as->root);
766 address_space_update_topology_pass(as, old_view, new_view, false);
767 address_space_update_topology_pass(as, old_view, new_view, true);
769 qemu_mutex_lock(&flat_view_mutex);
770 flatview_unref(as->current_map);
771 as->current_map = new_view;
772 qemu_mutex_unlock(&flat_view_mutex);
774 /* Note that all the old MemoryRegions are still alive up to this
775 * point. This relieves most MemoryListeners from the need to
776 * ref/unref the MemoryRegions they get---unless they use them
777 * outside the iothread mutex, in which case precise reference
778 * counting is necessary.
780 flatview_unref(old_view);
782 address_space_update_ioeventfds(as);
785 void memory_region_transaction_begin(void)
787 qemu_flush_coalesced_mmio_buffer();
788 ++memory_region_transaction_depth;
791 static void memory_region_clear_pending(void)
793 memory_region_update_pending = false;
794 ioeventfd_update_pending = false;
797 void memory_region_transaction_commit(void)
799 AddressSpace *as;
801 assert(memory_region_transaction_depth);
802 --memory_region_transaction_depth;
803 if (!memory_region_transaction_depth) {
804 if (memory_region_update_pending) {
805 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
807 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
808 address_space_update_topology(as);
811 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
812 } else if (ioeventfd_update_pending) {
813 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
814 address_space_update_ioeventfds(as);
817 memory_region_clear_pending();
821 static void memory_region_destructor_none(MemoryRegion *mr)
825 static void memory_region_destructor_ram(MemoryRegion *mr)
827 qemu_ram_free(mr->ram_addr);
830 static void memory_region_destructor_alias(MemoryRegion *mr)
832 memory_region_unref(mr->alias);
835 static void memory_region_destructor_ram_from_ptr(MemoryRegion *mr)
837 qemu_ram_free_from_ptr(mr->ram_addr);
840 static void memory_region_destructor_rom_device(MemoryRegion *mr)
842 qemu_ram_free(mr->ram_addr & TARGET_PAGE_MASK);
845 static bool memory_region_need_escape(char c)
847 return c == '/' || c == '[' || c == '\\' || c == ']';
850 static char *memory_region_escape_name(const char *name)
852 const char *p;
853 char *escaped, *q;
854 uint8_t c;
855 size_t bytes = 0;
857 for (p = name; *p; p++) {
858 bytes += memory_region_need_escape(*p) ? 4 : 1;
860 if (bytes == p - name) {
861 return g_memdup(name, bytes + 1);
864 escaped = g_malloc(bytes + 1);
865 for (p = name, q = escaped; *p; p++) {
866 c = *p;
867 if (unlikely(memory_region_need_escape(c))) {
868 *q++ = '\\';
869 *q++ = 'x';
870 *q++ = "0123456789abcdef"[c >> 4];
871 c = "0123456789abcdef"[c & 15];
873 *q++ = c;
875 *q = 0;
876 return escaped;
879 static void object_property_add_child_array(Object *owner,
880 const char *name,
881 Object *child)
883 int i;
884 char *base_name = memory_region_escape_name(name);
886 for (i = 0; ; i++) {
887 char *full_name = g_strdup_printf("%s[%d]", base_name, i);
888 Error *local_err = NULL;
890 object_property_add_child(owner, full_name, child, &local_err);
891 g_free(full_name);
892 if (!local_err) {
893 break;
896 error_free(local_err);
899 g_free(base_name);
903 void memory_region_init(MemoryRegion *mr,
904 Object *owner,
905 const char *name,
906 uint64_t size)
908 if (!owner) {
909 owner = qdev_get_machine();
912 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
913 mr->size = int128_make64(size);
914 if (size == UINT64_MAX) {
915 mr->size = int128_2_64();
917 mr->name = g_strdup(name);
919 if (name) {
920 object_property_add_child_array(owner, name, OBJECT(mr));
921 object_unref(OBJECT(mr));
925 static void memory_region_get_addr(Object *obj, Visitor *v, void *opaque,
926 const char *name, Error **errp)
928 MemoryRegion *mr = MEMORY_REGION(obj);
929 uint64_t value = mr->addr;
931 visit_type_uint64(v, &value, name, errp);
934 static void memory_region_get_container(Object *obj, Visitor *v, void *opaque,
935 const char *name, Error **errp)
937 MemoryRegion *mr = MEMORY_REGION(obj);
938 gchar *path = (gchar *)"";
940 if (mr->container) {
941 path = object_get_canonical_path(OBJECT(mr->container));
943 visit_type_str(v, &path, name, errp);
944 if (mr->container) {
945 g_free(path);
949 static Object *memory_region_resolve_container(Object *obj, void *opaque,
950 const char *part)
952 MemoryRegion *mr = MEMORY_REGION(obj);
954 return OBJECT(mr->container);
957 static void memory_region_get_priority(Object *obj, Visitor *v, void *opaque,
958 const char *name, Error **errp)
960 MemoryRegion *mr = MEMORY_REGION(obj);
961 int32_t value = mr->priority;
963 visit_type_int32(v, &value, name, errp);
966 static bool memory_region_get_may_overlap(Object *obj, Error **errp)
968 MemoryRegion *mr = MEMORY_REGION(obj);
970 return mr->may_overlap;
973 static void memory_region_get_size(Object *obj, Visitor *v, void *opaque,
974 const char *name, Error **errp)
976 MemoryRegion *mr = MEMORY_REGION(obj);
977 uint64_t value = memory_region_size(mr);
979 visit_type_uint64(v, &value, name, errp);
982 static void memory_region_initfn(Object *obj)
984 MemoryRegion *mr = MEMORY_REGION(obj);
985 ObjectProperty *op;
987 mr->ops = &unassigned_mem_ops;
988 mr->enabled = true;
989 mr->romd_mode = true;
990 mr->destructor = memory_region_destructor_none;
991 QTAILQ_INIT(&mr->subregions);
992 QTAILQ_INIT(&mr->coalesced);
994 op = object_property_add(OBJECT(mr), "container",
995 "link<" TYPE_MEMORY_REGION ">",
996 memory_region_get_container,
997 NULL, /* memory_region_set_container */
998 NULL, NULL, &error_abort);
999 op->resolve = memory_region_resolve_container;
1001 object_property_add(OBJECT(mr), "addr", "uint64",
1002 memory_region_get_addr,
1003 NULL, /* memory_region_set_addr */
1004 NULL, NULL, &error_abort);
1005 object_property_add(OBJECT(mr), "priority", "uint32",
1006 memory_region_get_priority,
1007 NULL, /* memory_region_set_priority */
1008 NULL, NULL, &error_abort);
1009 object_property_add_bool(OBJECT(mr), "may-overlap",
1010 memory_region_get_may_overlap,
1011 NULL, /* memory_region_set_may_overlap */
1012 &error_abort);
1013 object_property_add(OBJECT(mr), "size", "uint64",
1014 memory_region_get_size,
1015 NULL, /* memory_region_set_size, */
1016 NULL, NULL, &error_abort);
1019 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1020 unsigned size)
1022 #ifdef DEBUG_UNASSIGNED
1023 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1024 #endif
1025 if (current_cpu != NULL) {
1026 cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1028 return 0;
1031 static void unassigned_mem_write(void *opaque, hwaddr addr,
1032 uint64_t val, unsigned size)
1034 #ifdef DEBUG_UNASSIGNED
1035 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1036 #endif
1037 if (current_cpu != NULL) {
1038 cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1042 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1043 unsigned size, bool is_write)
1045 return false;
1048 const MemoryRegionOps unassigned_mem_ops = {
1049 .valid.accepts = unassigned_mem_accepts,
1050 .endianness = DEVICE_NATIVE_ENDIAN,
1053 bool memory_region_access_valid(MemoryRegion *mr,
1054 hwaddr addr,
1055 unsigned size,
1056 bool is_write)
1058 int access_size_min, access_size_max;
1059 int access_size, i;
1061 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1062 return false;
1065 if (!mr->ops->valid.accepts) {
1066 return true;
1069 access_size_min = mr->ops->valid.min_access_size;
1070 if (!mr->ops->valid.min_access_size) {
1071 access_size_min = 1;
1074 access_size_max = mr->ops->valid.max_access_size;
1075 if (!mr->ops->valid.max_access_size) {
1076 access_size_max = 4;
1079 access_size = MAX(MIN(size, access_size_max), access_size_min);
1080 for (i = 0; i < size; i += access_size) {
1081 if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
1082 is_write)) {
1083 return false;
1087 return true;
1090 static uint64_t memory_region_dispatch_read1(MemoryRegion *mr,
1091 hwaddr addr,
1092 unsigned size)
1094 uint64_t data = 0;
1096 if (mr->ops->read) {
1097 access_with_adjusted_size(addr, &data, size,
1098 mr->ops->impl.min_access_size,
1099 mr->ops->impl.max_access_size,
1100 memory_region_read_accessor, mr);
1101 } else {
1102 access_with_adjusted_size(addr, &data, size, 1, 4,
1103 memory_region_oldmmio_read_accessor, mr);
1106 return data;
1109 static bool memory_region_dispatch_read(MemoryRegion *mr,
1110 hwaddr addr,
1111 uint64_t *pval,
1112 unsigned size)
1114 if (!memory_region_access_valid(mr, addr, size, false)) {
1115 *pval = unassigned_mem_read(mr, addr, size);
1116 return true;
1119 *pval = memory_region_dispatch_read1(mr, addr, size);
1120 adjust_endianness(mr, pval, size);
1121 return false;
1124 static bool memory_region_dispatch_write(MemoryRegion *mr,
1125 hwaddr addr,
1126 uint64_t data,
1127 unsigned size)
1129 if (!memory_region_access_valid(mr, addr, size, true)) {
1130 unassigned_mem_write(mr, addr, data, size);
1131 return true;
1134 adjust_endianness(mr, &data, size);
1136 if (mr->ops->write) {
1137 access_with_adjusted_size(addr, &data, size,
1138 mr->ops->impl.min_access_size,
1139 mr->ops->impl.max_access_size,
1140 memory_region_write_accessor, mr);
1141 } else {
1142 access_with_adjusted_size(addr, &data, size, 1, 4,
1143 memory_region_oldmmio_write_accessor, mr);
1145 return false;
1148 void memory_region_init_io(MemoryRegion *mr,
1149 Object *owner,
1150 const MemoryRegionOps *ops,
1151 void *opaque,
1152 const char *name,
1153 uint64_t size)
1155 memory_region_init(mr, owner, name, size);
1156 mr->ops = ops;
1157 mr->opaque = opaque;
1158 mr->terminates = true;
1159 mr->ram_addr = ~(ram_addr_t)0;
1162 void memory_region_init_ram(MemoryRegion *mr,
1163 Object *owner,
1164 const char *name,
1165 uint64_t size)
1167 memory_region_init(mr, owner, name, size);
1168 mr->ram = true;
1169 mr->terminates = true;
1170 mr->destructor = memory_region_destructor_ram;
1171 mr->ram_addr = qemu_ram_alloc(size, mr);
1174 #ifdef __linux__
1175 void memory_region_init_ram_from_file(MemoryRegion *mr,
1176 struct Object *owner,
1177 const char *name,
1178 uint64_t size,
1179 bool share,
1180 const char *path,
1181 Error **errp)
1183 memory_region_init(mr, owner, name, size);
1184 mr->ram = true;
1185 mr->terminates = true;
1186 mr->destructor = memory_region_destructor_ram;
1187 mr->ram_addr = qemu_ram_alloc_from_file(size, mr, share, path, errp);
1189 #endif
1191 void memory_region_init_ram_ptr(MemoryRegion *mr,
1192 Object *owner,
1193 const char *name,
1194 uint64_t size,
1195 void *ptr)
1197 memory_region_init(mr, owner, name, size);
1198 mr->ram = true;
1199 mr->terminates = true;
1200 mr->destructor = memory_region_destructor_ram_from_ptr;
1201 mr->ram_addr = qemu_ram_alloc_from_ptr(size, ptr, mr);
1204 void memory_region_init_alias(MemoryRegion *mr,
1205 Object *owner,
1206 const char *name,
1207 MemoryRegion *orig,
1208 hwaddr offset,
1209 uint64_t size)
1211 memory_region_init(mr, owner, name, size);
1212 memory_region_ref(orig);
1213 mr->destructor = memory_region_destructor_alias;
1214 mr->alias = orig;
1215 mr->alias_offset = offset;
1218 void memory_region_init_rom_device(MemoryRegion *mr,
1219 Object *owner,
1220 const MemoryRegionOps *ops,
1221 void *opaque,
1222 const char *name,
1223 uint64_t size)
1225 memory_region_init(mr, owner, name, size);
1226 mr->ops = ops;
1227 mr->opaque = opaque;
1228 mr->terminates = true;
1229 mr->rom_device = true;
1230 mr->destructor = memory_region_destructor_rom_device;
1231 mr->ram_addr = qemu_ram_alloc(size, mr);
1234 void memory_region_init_iommu(MemoryRegion *mr,
1235 Object *owner,
1236 const MemoryRegionIOMMUOps *ops,
1237 const char *name,
1238 uint64_t size)
1240 memory_region_init(mr, owner, name, size);
1241 mr->iommu_ops = ops,
1242 mr->terminates = true; /* then re-forwards */
1243 notifier_list_init(&mr->iommu_notify);
1246 void memory_region_init_reservation(MemoryRegion *mr,
1247 Object *owner,
1248 const char *name,
1249 uint64_t size)
1251 memory_region_init_io(mr, owner, &unassigned_mem_ops, mr, name, size);
1254 static void memory_region_finalize(Object *obj)
1256 MemoryRegion *mr = MEMORY_REGION(obj);
1258 assert(QTAILQ_EMPTY(&mr->subregions));
1259 assert(memory_region_transaction_depth == 0);
1260 mr->destructor(mr);
1261 memory_region_clear_coalescing(mr);
1262 g_free((char *)mr->name);
1263 g_free(mr->ioeventfds);
1266 Object *memory_region_owner(MemoryRegion *mr)
1268 Object *obj = OBJECT(mr);
1269 return obj->parent;
1272 void memory_region_ref(MemoryRegion *mr)
1274 /* MMIO callbacks most likely will access data that belongs
1275 * to the owner, hence the need to ref/unref the owner whenever
1276 * the memory region is in use.
1278 * The memory region is a child of its owner. As long as the
1279 * owner doesn't call unparent itself on the memory region,
1280 * ref-ing the owner will also keep the memory region alive.
1281 * Memory regions without an owner are supposed to never go away,
1282 * but we still ref/unref them for debugging purposes.
1284 Object *obj = OBJECT(mr);
1285 if (obj && obj->parent) {
1286 object_ref(obj->parent);
1287 } else {
1288 object_ref(obj);
1292 void memory_region_unref(MemoryRegion *mr)
1294 Object *obj = OBJECT(mr);
1295 if (obj && obj->parent) {
1296 object_unref(obj->parent);
1297 } else {
1298 object_unref(obj);
1302 uint64_t memory_region_size(MemoryRegion *mr)
1304 if (int128_eq(mr->size, int128_2_64())) {
1305 return UINT64_MAX;
1307 return int128_get64(mr->size);
1310 const char *memory_region_name(const MemoryRegion *mr)
1312 if (!mr->name) {
1313 ((MemoryRegion *)mr)->name =
1314 object_get_canonical_path_component(OBJECT(mr));
1316 return mr->name;
1319 bool memory_region_is_ram(MemoryRegion *mr)
1321 return mr->ram;
1324 bool memory_region_is_logging(MemoryRegion *mr)
1326 return mr->dirty_log_mask;
1329 bool memory_region_is_rom(MemoryRegion *mr)
1331 return mr->ram && mr->readonly;
1334 bool memory_region_is_iommu(MemoryRegion *mr)
1336 return mr->iommu_ops;
1339 void memory_region_register_iommu_notifier(MemoryRegion *mr, Notifier *n)
1341 notifier_list_add(&mr->iommu_notify, n);
1344 void memory_region_unregister_iommu_notifier(Notifier *n)
1346 notifier_remove(n);
1349 void memory_region_notify_iommu(MemoryRegion *mr,
1350 IOMMUTLBEntry entry)
1352 assert(memory_region_is_iommu(mr));
1353 notifier_list_notify(&mr->iommu_notify, &entry);
1356 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1358 uint8_t mask = 1 << client;
1360 memory_region_transaction_begin();
1361 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1362 memory_region_update_pending |= mr->enabled;
1363 memory_region_transaction_commit();
1366 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1367 hwaddr size, unsigned client)
1369 assert(mr->terminates);
1370 return cpu_physical_memory_get_dirty(mr->ram_addr + addr, size, client);
1373 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1374 hwaddr size)
1376 assert(mr->terminates);
1377 cpu_physical_memory_set_dirty_range(mr->ram_addr + addr, size);
1380 bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,
1381 hwaddr size, unsigned client)
1383 bool ret;
1384 assert(mr->terminates);
1385 ret = cpu_physical_memory_get_dirty(mr->ram_addr + addr, size, client);
1386 if (ret) {
1387 cpu_physical_memory_reset_dirty(mr->ram_addr + addr, size, client);
1389 return ret;
1393 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1395 AddressSpace *as;
1396 FlatRange *fr;
1398 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1399 FlatView *view = address_space_get_flatview(as);
1400 FOR_EACH_FLAT_RANGE(fr, view) {
1401 if (fr->mr == mr) {
1402 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1405 flatview_unref(view);
1409 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1411 if (mr->readonly != readonly) {
1412 memory_region_transaction_begin();
1413 mr->readonly = readonly;
1414 memory_region_update_pending |= mr->enabled;
1415 memory_region_transaction_commit();
1419 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
1421 if (mr->romd_mode != romd_mode) {
1422 memory_region_transaction_begin();
1423 mr->romd_mode = romd_mode;
1424 memory_region_update_pending |= mr->enabled;
1425 memory_region_transaction_commit();
1429 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1430 hwaddr size, unsigned client)
1432 assert(mr->terminates);
1433 cpu_physical_memory_reset_dirty(mr->ram_addr + addr, size, client);
1436 int memory_region_get_fd(MemoryRegion *mr)
1438 if (mr->alias) {
1439 return memory_region_get_fd(mr->alias);
1442 assert(mr->terminates);
1444 return qemu_get_ram_fd(mr->ram_addr & TARGET_PAGE_MASK);
1447 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1449 if (mr->alias) {
1450 return memory_region_get_ram_ptr(mr->alias) + mr->alias_offset;
1453 assert(mr->terminates);
1455 return qemu_get_ram_ptr(mr->ram_addr & TARGET_PAGE_MASK);
1458 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1460 FlatView *view;
1461 FlatRange *fr;
1462 CoalescedMemoryRange *cmr;
1463 AddrRange tmp;
1464 MemoryRegionSection section;
1466 view = address_space_get_flatview(as);
1467 FOR_EACH_FLAT_RANGE(fr, view) {
1468 if (fr->mr == mr) {
1469 section = (MemoryRegionSection) {
1470 .address_space = as,
1471 .offset_within_address_space = int128_get64(fr->addr.start),
1472 .size = fr->addr.size,
1475 MEMORY_LISTENER_CALL(coalesced_mmio_del, Reverse, &section,
1476 int128_get64(fr->addr.start),
1477 int128_get64(fr->addr.size));
1478 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1479 tmp = addrrange_shift(cmr->addr,
1480 int128_sub(fr->addr.start,
1481 int128_make64(fr->offset_in_region)));
1482 if (!addrrange_intersects(tmp, fr->addr)) {
1483 continue;
1485 tmp = addrrange_intersection(tmp, fr->addr);
1486 MEMORY_LISTENER_CALL(coalesced_mmio_add, Forward, &section,
1487 int128_get64(tmp.start),
1488 int128_get64(tmp.size));
1492 flatview_unref(view);
1495 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1497 AddressSpace *as;
1499 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1500 memory_region_update_coalesced_range_as(mr, as);
1504 void memory_region_set_coalescing(MemoryRegion *mr)
1506 memory_region_clear_coalescing(mr);
1507 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1510 void memory_region_add_coalescing(MemoryRegion *mr,
1511 hwaddr offset,
1512 uint64_t size)
1514 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1516 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1517 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1518 memory_region_update_coalesced_range(mr);
1519 memory_region_set_flush_coalesced(mr);
1522 void memory_region_clear_coalescing(MemoryRegion *mr)
1524 CoalescedMemoryRange *cmr;
1525 bool updated = false;
1527 qemu_flush_coalesced_mmio_buffer();
1528 mr->flush_coalesced_mmio = false;
1530 while (!QTAILQ_EMPTY(&mr->coalesced)) {
1531 cmr = QTAILQ_FIRST(&mr->coalesced);
1532 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1533 g_free(cmr);
1534 updated = true;
1537 if (updated) {
1538 memory_region_update_coalesced_range(mr);
1542 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1544 mr->flush_coalesced_mmio = true;
1547 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1549 qemu_flush_coalesced_mmio_buffer();
1550 if (QTAILQ_EMPTY(&mr->coalesced)) {
1551 mr->flush_coalesced_mmio = false;
1555 void memory_region_add_eventfd(MemoryRegion *mr,
1556 hwaddr addr,
1557 unsigned size,
1558 bool match_data,
1559 uint64_t data,
1560 EventNotifier *e)
1562 MemoryRegionIoeventfd mrfd = {
1563 .addr.start = int128_make64(addr),
1564 .addr.size = int128_make64(size),
1565 .match_data = match_data,
1566 .data = data,
1567 .e = e,
1569 unsigned i;
1571 adjust_endianness(mr, &mrfd.data, size);
1572 memory_region_transaction_begin();
1573 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1574 if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
1575 break;
1578 ++mr->ioeventfd_nb;
1579 mr->ioeventfds = g_realloc(mr->ioeventfds,
1580 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
1581 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
1582 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
1583 mr->ioeventfds[i] = mrfd;
1584 ioeventfd_update_pending |= mr->enabled;
1585 memory_region_transaction_commit();
1588 void memory_region_del_eventfd(MemoryRegion *mr,
1589 hwaddr addr,
1590 unsigned size,
1591 bool match_data,
1592 uint64_t data,
1593 EventNotifier *e)
1595 MemoryRegionIoeventfd mrfd = {
1596 .addr.start = int128_make64(addr),
1597 .addr.size = int128_make64(size),
1598 .match_data = match_data,
1599 .data = data,
1600 .e = e,
1602 unsigned i;
1604 adjust_endianness(mr, &mrfd.data, size);
1605 memory_region_transaction_begin();
1606 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1607 if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
1608 break;
1611 assert(i != mr->ioeventfd_nb);
1612 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
1613 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
1614 --mr->ioeventfd_nb;
1615 mr->ioeventfds = g_realloc(mr->ioeventfds,
1616 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
1617 ioeventfd_update_pending |= mr->enabled;
1618 memory_region_transaction_commit();
1621 static void memory_region_update_container_subregions(MemoryRegion *subregion)
1623 hwaddr offset = subregion->addr;
1624 MemoryRegion *mr = subregion->container;
1625 MemoryRegion *other;
1627 memory_region_transaction_begin();
1629 memory_region_ref(subregion);
1630 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1631 if (subregion->may_overlap || other->may_overlap) {
1632 continue;
1634 if (int128_ge(int128_make64(offset),
1635 int128_add(int128_make64(other->addr), other->size))
1636 || int128_le(int128_add(int128_make64(offset), subregion->size),
1637 int128_make64(other->addr))) {
1638 continue;
1640 #if 0
1641 printf("warning: subregion collision %llx/%llx (%s) "
1642 "vs %llx/%llx (%s)\n",
1643 (unsigned long long)offset,
1644 (unsigned long long)int128_get64(subregion->size),
1645 subregion->name,
1646 (unsigned long long)other->addr,
1647 (unsigned long long)int128_get64(other->size),
1648 other->name);
1649 #endif
1651 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1652 if (subregion->priority >= other->priority) {
1653 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
1654 goto done;
1657 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
1658 done:
1659 memory_region_update_pending |= mr->enabled && subregion->enabled;
1660 memory_region_transaction_commit();
1663 static void memory_region_add_subregion_common(MemoryRegion *mr,
1664 hwaddr offset,
1665 MemoryRegion *subregion)
1667 assert(!subregion->container);
1668 subregion->container = mr;
1669 subregion->addr = offset;
1670 memory_region_update_container_subregions(subregion);
1673 void memory_region_add_subregion(MemoryRegion *mr,
1674 hwaddr offset,
1675 MemoryRegion *subregion)
1677 subregion->may_overlap = false;
1678 subregion->priority = 0;
1679 memory_region_add_subregion_common(mr, offset, subregion);
1682 void memory_region_add_subregion_overlap(MemoryRegion *mr,
1683 hwaddr offset,
1684 MemoryRegion *subregion,
1685 int priority)
1687 subregion->may_overlap = true;
1688 subregion->priority = priority;
1689 memory_region_add_subregion_common(mr, offset, subregion);
1692 void memory_region_del_subregion(MemoryRegion *mr,
1693 MemoryRegion *subregion)
1695 memory_region_transaction_begin();
1696 assert(subregion->container == mr);
1697 subregion->container = NULL;
1698 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
1699 memory_region_unref(subregion);
1700 memory_region_update_pending |= mr->enabled && subregion->enabled;
1701 memory_region_transaction_commit();
1704 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
1706 if (enabled == mr->enabled) {
1707 return;
1709 memory_region_transaction_begin();
1710 mr->enabled = enabled;
1711 memory_region_update_pending = true;
1712 memory_region_transaction_commit();
1715 static void memory_region_readd_subregion(MemoryRegion *mr)
1717 MemoryRegion *container = mr->container;
1719 if (container) {
1720 memory_region_transaction_begin();
1721 memory_region_ref(mr);
1722 memory_region_del_subregion(container, mr);
1723 mr->container = container;
1724 memory_region_update_container_subregions(mr);
1725 memory_region_unref(mr);
1726 memory_region_transaction_commit();
1730 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
1732 if (addr != mr->addr) {
1733 mr->addr = addr;
1734 memory_region_readd_subregion(mr);
1738 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
1740 assert(mr->alias);
1742 if (offset == mr->alias_offset) {
1743 return;
1746 memory_region_transaction_begin();
1747 mr->alias_offset = offset;
1748 memory_region_update_pending |= mr->enabled;
1749 memory_region_transaction_commit();
1752 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
1754 return mr->ram_addr;
1757 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
1759 const AddrRange *addr = addr_;
1760 const FlatRange *fr = fr_;
1762 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
1763 return -1;
1764 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
1765 return 1;
1767 return 0;
1770 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
1772 return bsearch(&addr, view->ranges, view->nr,
1773 sizeof(FlatRange), cmp_flatrange_addr);
1776 bool memory_region_present(MemoryRegion *container, hwaddr addr)
1778 MemoryRegion *mr = memory_region_find(container, addr, 1).mr;
1779 if (!mr || (mr == container)) {
1780 return false;
1782 memory_region_unref(mr);
1783 return true;
1786 bool memory_region_is_mapped(MemoryRegion *mr)
1788 return mr->container ? true : false;
1791 MemoryRegionSection memory_region_find(MemoryRegion *mr,
1792 hwaddr addr, uint64_t size)
1794 MemoryRegionSection ret = { .mr = NULL };
1795 MemoryRegion *root;
1796 AddressSpace *as;
1797 AddrRange range;
1798 FlatView *view;
1799 FlatRange *fr;
1801 addr += mr->addr;
1802 for (root = mr; root->container; ) {
1803 root = root->container;
1804 addr += root->addr;
1807 as = memory_region_to_address_space(root);
1808 if (!as) {
1809 return ret;
1811 range = addrrange_make(int128_make64(addr), int128_make64(size));
1813 view = address_space_get_flatview(as);
1814 fr = flatview_lookup(view, range);
1815 if (!fr) {
1816 flatview_unref(view);
1817 return ret;
1820 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
1821 --fr;
1824 ret.mr = fr->mr;
1825 ret.address_space = as;
1826 range = addrrange_intersection(range, fr->addr);
1827 ret.offset_within_region = fr->offset_in_region;
1828 ret.offset_within_region += int128_get64(int128_sub(range.start,
1829 fr->addr.start));
1830 ret.size = range.size;
1831 ret.offset_within_address_space = int128_get64(range.start);
1832 ret.readonly = fr->readonly;
1833 memory_region_ref(ret.mr);
1835 flatview_unref(view);
1836 return ret;
1839 void address_space_sync_dirty_bitmap(AddressSpace *as)
1841 FlatView *view;
1842 FlatRange *fr;
1844 view = address_space_get_flatview(as);
1845 FOR_EACH_FLAT_RANGE(fr, view) {
1846 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1848 flatview_unref(view);
1851 void memory_global_dirty_log_start(void)
1853 global_dirty_log = true;
1854 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
1857 void memory_global_dirty_log_stop(void)
1859 global_dirty_log = false;
1860 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
1863 static void listener_add_address_space(MemoryListener *listener,
1864 AddressSpace *as)
1866 FlatView *view;
1867 FlatRange *fr;
1869 if (listener->address_space_filter
1870 && listener->address_space_filter != as) {
1871 return;
1874 if (global_dirty_log) {
1875 if (listener->log_global_start) {
1876 listener->log_global_start(listener);
1880 view = address_space_get_flatview(as);
1881 FOR_EACH_FLAT_RANGE(fr, view) {
1882 MemoryRegionSection section = {
1883 .mr = fr->mr,
1884 .address_space = as,
1885 .offset_within_region = fr->offset_in_region,
1886 .size = fr->addr.size,
1887 .offset_within_address_space = int128_get64(fr->addr.start),
1888 .readonly = fr->readonly,
1890 if (listener->region_add) {
1891 listener->region_add(listener, &section);
1894 flatview_unref(view);
1897 void memory_listener_register(MemoryListener *listener, AddressSpace *filter)
1899 MemoryListener *other = NULL;
1900 AddressSpace *as;
1902 listener->address_space_filter = filter;
1903 if (QTAILQ_EMPTY(&memory_listeners)
1904 || listener->priority >= QTAILQ_LAST(&memory_listeners,
1905 memory_listeners)->priority) {
1906 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
1907 } else {
1908 QTAILQ_FOREACH(other, &memory_listeners, link) {
1909 if (listener->priority < other->priority) {
1910 break;
1913 QTAILQ_INSERT_BEFORE(other, listener, link);
1916 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1917 listener_add_address_space(listener, as);
1921 void memory_listener_unregister(MemoryListener *listener)
1923 QTAILQ_REMOVE(&memory_listeners, listener, link);
1926 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
1928 if (QTAILQ_EMPTY(&address_spaces)) {
1929 memory_init();
1932 memory_region_transaction_begin();
1933 as->root = root;
1934 as->current_map = g_new(FlatView, 1);
1935 flatview_init(as->current_map);
1936 as->ioeventfd_nb = 0;
1937 as->ioeventfds = NULL;
1938 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
1939 as->name = g_strdup(name ? name : "anonymous");
1940 address_space_init_dispatch(as);
1941 memory_region_update_pending |= root->enabled;
1942 memory_region_transaction_commit();
1945 void address_space_destroy(AddressSpace *as)
1947 MemoryListener *listener;
1949 /* Flush out anything from MemoryListeners listening in on this */
1950 memory_region_transaction_begin();
1951 as->root = NULL;
1952 memory_region_transaction_commit();
1953 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
1954 address_space_destroy_dispatch(as);
1956 QTAILQ_FOREACH(listener, &memory_listeners, link) {
1957 assert(listener->address_space_filter != as);
1960 flatview_unref(as->current_map);
1961 g_free(as->name);
1962 g_free(as->ioeventfds);
1965 bool io_mem_read(MemoryRegion *mr, hwaddr addr, uint64_t *pval, unsigned size)
1967 return memory_region_dispatch_read(mr, addr, pval, size);
1970 bool io_mem_write(MemoryRegion *mr, hwaddr addr,
1971 uint64_t val, unsigned size)
1973 return memory_region_dispatch_write(mr, addr, val, size);
1976 typedef struct MemoryRegionList MemoryRegionList;
1978 struct MemoryRegionList {
1979 const MemoryRegion *mr;
1980 QTAILQ_ENTRY(MemoryRegionList) queue;
1983 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
1985 static void mtree_print_mr(fprintf_function mon_printf, void *f,
1986 const MemoryRegion *mr, unsigned int level,
1987 hwaddr base,
1988 MemoryRegionListHead *alias_print_queue)
1990 MemoryRegionList *new_ml, *ml, *next_ml;
1991 MemoryRegionListHead submr_print_queue;
1992 const MemoryRegion *submr;
1993 unsigned int i;
1995 if (!mr || !mr->enabled) {
1996 return;
1999 for (i = 0; i < level; i++) {
2000 mon_printf(f, " ");
2003 if (mr->alias) {
2004 MemoryRegionList *ml;
2005 bool found = false;
2007 /* check if the alias is already in the queue */
2008 QTAILQ_FOREACH(ml, alias_print_queue, queue) {
2009 if (ml->mr == mr->alias) {
2010 found = true;
2014 if (!found) {
2015 ml = g_new(MemoryRegionList, 1);
2016 ml->mr = mr->alias;
2017 QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
2019 mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
2020 " (prio %d, %c%c): alias %s @%s " TARGET_FMT_plx
2021 "-" TARGET_FMT_plx "\n",
2022 base + mr->addr,
2023 base + mr->addr
2024 + (int128_nz(mr->size) ?
2025 (hwaddr)int128_get64(int128_sub(mr->size,
2026 int128_one())) : 0),
2027 mr->priority,
2028 mr->romd_mode ? 'R' : '-',
2029 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2030 : '-',
2031 memory_region_name(mr),
2032 memory_region_name(mr->alias),
2033 mr->alias_offset,
2034 mr->alias_offset
2035 + (int128_nz(mr->size) ?
2036 (hwaddr)int128_get64(int128_sub(mr->size,
2037 int128_one())) : 0));
2038 } else {
2039 mon_printf(f,
2040 TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %c%c): %s\n",
2041 base + mr->addr,
2042 base + mr->addr
2043 + (int128_nz(mr->size) ?
2044 (hwaddr)int128_get64(int128_sub(mr->size,
2045 int128_one())) : 0),
2046 mr->priority,
2047 mr->romd_mode ? 'R' : '-',
2048 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2049 : '-',
2050 memory_region_name(mr));
2053 QTAILQ_INIT(&submr_print_queue);
2055 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2056 new_ml = g_new(MemoryRegionList, 1);
2057 new_ml->mr = submr;
2058 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2059 if (new_ml->mr->addr < ml->mr->addr ||
2060 (new_ml->mr->addr == ml->mr->addr &&
2061 new_ml->mr->priority > ml->mr->priority)) {
2062 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
2063 new_ml = NULL;
2064 break;
2067 if (new_ml) {
2068 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
2072 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2073 mtree_print_mr(mon_printf, f, ml->mr, level + 1, base + mr->addr,
2074 alias_print_queue);
2077 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
2078 g_free(ml);
2082 void mtree_info(fprintf_function mon_printf, void *f)
2084 MemoryRegionListHead ml_head;
2085 MemoryRegionList *ml, *ml2;
2086 AddressSpace *as;
2088 QTAILQ_INIT(&ml_head);
2090 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2091 mon_printf(f, "%s\n", as->name);
2092 mtree_print_mr(mon_printf, f, as->root, 0, 0, &ml_head);
2095 mon_printf(f, "aliases\n");
2096 /* print aliased regions */
2097 QTAILQ_FOREACH(ml, &ml_head, queue) {
2098 mon_printf(f, "%s\n", memory_region_name(ml->mr));
2099 mtree_print_mr(mon_printf, f, ml->mr, 0, 0, &ml_head);
2102 QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
2103 g_free(ml);
2107 static const TypeInfo memory_region_info = {
2108 .parent = TYPE_OBJECT,
2109 .name = TYPE_MEMORY_REGION,
2110 .instance_size = sizeof(MemoryRegion),
2111 .instance_init = memory_region_initfn,
2112 .instance_finalize = memory_region_finalize,
2115 static void memory_register_types(void)
2117 type_register_static(&memory_region_info);
2120 type_init(memory_register_types)