memory: Define API for MemoryRegionOps to take attrs and return status
[qemu.git] / memory.c
blob9bb5674bb9ac157c3fb5c0f4c19b7b314f03327d
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 static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
37 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
39 static QTAILQ_HEAD(, AddressSpace) address_spaces
40 = QTAILQ_HEAD_INITIALIZER(address_spaces);
42 typedef struct AddrRange AddrRange;
45 * Note that signed integers are needed for negative offsetting in aliases
46 * (large MemoryRegion::alias_offset).
48 struct AddrRange {
49 Int128 start;
50 Int128 size;
53 static AddrRange addrrange_make(Int128 start, Int128 size)
55 return (AddrRange) { start, size };
58 static bool addrrange_equal(AddrRange r1, AddrRange r2)
60 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
63 static Int128 addrrange_end(AddrRange r)
65 return int128_add(r.start, r.size);
68 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
70 int128_addto(&range.start, delta);
71 return range;
74 static bool addrrange_contains(AddrRange range, Int128 addr)
76 return int128_ge(addr, range.start)
77 && int128_lt(addr, addrrange_end(range));
80 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
82 return addrrange_contains(r1, r2.start)
83 || addrrange_contains(r2, r1.start);
86 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
88 Int128 start = int128_max(r1.start, r2.start);
89 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
90 return addrrange_make(start, int128_sub(end, start));
93 enum ListenerDirection { Forward, Reverse };
95 static bool memory_listener_match(MemoryListener *listener,
96 MemoryRegionSection *section)
98 return !listener->address_space_filter
99 || listener->address_space_filter == section->address_space;
102 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
103 do { \
104 MemoryListener *_listener; \
106 switch (_direction) { \
107 case Forward: \
108 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
109 if (_listener->_callback) { \
110 _listener->_callback(_listener, ##_args); \
113 break; \
114 case Reverse: \
115 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
116 memory_listeners, link) { \
117 if (_listener->_callback) { \
118 _listener->_callback(_listener, ##_args); \
121 break; \
122 default: \
123 abort(); \
125 } while (0)
127 #define MEMORY_LISTENER_CALL(_callback, _direction, _section, _args...) \
128 do { \
129 MemoryListener *_listener; \
131 switch (_direction) { \
132 case Forward: \
133 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
134 if (_listener->_callback \
135 && memory_listener_match(_listener, _section)) { \
136 _listener->_callback(_listener, _section, ##_args); \
139 break; \
140 case Reverse: \
141 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
142 memory_listeners, link) { \
143 if (_listener->_callback \
144 && memory_listener_match(_listener, _section)) { \
145 _listener->_callback(_listener, _section, ##_args); \
148 break; \
149 default: \
150 abort(); \
152 } while (0)
154 /* No need to ref/unref .mr, the FlatRange keeps it alive. */
155 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback) \
156 MEMORY_LISTENER_CALL(callback, dir, (&(MemoryRegionSection) { \
157 .mr = (fr)->mr, \
158 .address_space = (as), \
159 .offset_within_region = (fr)->offset_in_region, \
160 .size = (fr)->addr.size, \
161 .offset_within_address_space = int128_get64((fr)->addr.start), \
162 .readonly = (fr)->readonly, \
165 struct CoalescedMemoryRange {
166 AddrRange addr;
167 QTAILQ_ENTRY(CoalescedMemoryRange) link;
170 struct MemoryRegionIoeventfd {
171 AddrRange addr;
172 bool match_data;
173 uint64_t data;
174 EventNotifier *e;
177 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
178 MemoryRegionIoeventfd b)
180 if (int128_lt(a.addr.start, b.addr.start)) {
181 return true;
182 } else if (int128_gt(a.addr.start, b.addr.start)) {
183 return false;
184 } else if (int128_lt(a.addr.size, b.addr.size)) {
185 return true;
186 } else if (int128_gt(a.addr.size, b.addr.size)) {
187 return false;
188 } else if (a.match_data < b.match_data) {
189 return true;
190 } else if (a.match_data > b.match_data) {
191 return false;
192 } else if (a.match_data) {
193 if (a.data < b.data) {
194 return true;
195 } else if (a.data > b.data) {
196 return false;
199 if (a.e < b.e) {
200 return true;
201 } else if (a.e > b.e) {
202 return false;
204 return false;
207 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
208 MemoryRegionIoeventfd b)
210 return !memory_region_ioeventfd_before(a, b)
211 && !memory_region_ioeventfd_before(b, a);
214 typedef struct FlatRange FlatRange;
215 typedef struct FlatView FlatView;
217 /* Range of memory in the global map. Addresses are absolute. */
218 struct FlatRange {
219 MemoryRegion *mr;
220 hwaddr offset_in_region;
221 AddrRange addr;
222 uint8_t dirty_log_mask;
223 bool romd_mode;
224 bool readonly;
227 /* Flattened global view of current active memory hierarchy. Kept in sorted
228 * order.
230 struct FlatView {
231 struct rcu_head rcu;
232 unsigned ref;
233 FlatRange *ranges;
234 unsigned nr;
235 unsigned nr_allocated;
238 typedef struct AddressSpaceOps AddressSpaceOps;
240 #define FOR_EACH_FLAT_RANGE(var, view) \
241 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
243 static bool flatrange_equal(FlatRange *a, FlatRange *b)
245 return a->mr == b->mr
246 && addrrange_equal(a->addr, b->addr)
247 && a->offset_in_region == b->offset_in_region
248 && a->romd_mode == b->romd_mode
249 && a->readonly == b->readonly;
252 static void flatview_init(FlatView *view)
254 view->ref = 1;
255 view->ranges = NULL;
256 view->nr = 0;
257 view->nr_allocated = 0;
260 /* Insert a range into a given position. Caller is responsible for maintaining
261 * sorting order.
263 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
265 if (view->nr == view->nr_allocated) {
266 view->nr_allocated = MAX(2 * view->nr, 10);
267 view->ranges = g_realloc(view->ranges,
268 view->nr_allocated * sizeof(*view->ranges));
270 memmove(view->ranges + pos + 1, view->ranges + pos,
271 (view->nr - pos) * sizeof(FlatRange));
272 view->ranges[pos] = *range;
273 memory_region_ref(range->mr);
274 ++view->nr;
277 static void flatview_destroy(FlatView *view)
279 int i;
281 for (i = 0; i < view->nr; i++) {
282 memory_region_unref(view->ranges[i].mr);
284 g_free(view->ranges);
285 g_free(view);
288 static void flatview_ref(FlatView *view)
290 atomic_inc(&view->ref);
293 static void flatview_unref(FlatView *view)
295 if (atomic_fetch_dec(&view->ref) == 1) {
296 flatview_destroy(view);
300 static bool can_merge(FlatRange *r1, FlatRange *r2)
302 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
303 && r1->mr == r2->mr
304 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
305 r1->addr.size),
306 int128_make64(r2->offset_in_region))
307 && r1->dirty_log_mask == r2->dirty_log_mask
308 && r1->romd_mode == r2->romd_mode
309 && r1->readonly == r2->readonly;
312 /* Attempt to simplify a view by merging adjacent ranges */
313 static void flatview_simplify(FlatView *view)
315 unsigned i, j;
317 i = 0;
318 while (i < view->nr) {
319 j = i + 1;
320 while (j < view->nr
321 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
322 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
323 ++j;
325 ++i;
326 memmove(&view->ranges[i], &view->ranges[j],
327 (view->nr - j) * sizeof(view->ranges[j]));
328 view->nr -= j - i;
332 static bool memory_region_big_endian(MemoryRegion *mr)
334 #ifdef TARGET_WORDS_BIGENDIAN
335 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
336 #else
337 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
338 #endif
341 static bool memory_region_wrong_endianness(MemoryRegion *mr)
343 #ifdef TARGET_WORDS_BIGENDIAN
344 return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
345 #else
346 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
347 #endif
350 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
352 if (memory_region_wrong_endianness(mr)) {
353 switch (size) {
354 case 1:
355 break;
356 case 2:
357 *data = bswap16(*data);
358 break;
359 case 4:
360 *data = bswap32(*data);
361 break;
362 case 8:
363 *data = bswap64(*data);
364 break;
365 default:
366 abort();
371 static MemTxResult memory_region_oldmmio_read_accessor(MemoryRegion *mr,
372 hwaddr addr,
373 uint64_t *value,
374 unsigned size,
375 unsigned shift,
376 uint64_t mask,
377 MemTxAttrs attrs)
379 uint64_t tmp;
381 tmp = mr->ops->old_mmio.read[ctz32(size)](mr->opaque, addr);
382 trace_memory_region_ops_read(mr, addr, tmp, size);
383 *value |= (tmp & mask) << shift;
384 return MEMTX_OK;
387 static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
388 hwaddr addr,
389 uint64_t *value,
390 unsigned size,
391 unsigned shift,
392 uint64_t mask,
393 MemTxAttrs attrs)
395 uint64_t tmp;
397 if (mr->flush_coalesced_mmio) {
398 qemu_flush_coalesced_mmio_buffer();
400 tmp = mr->ops->read(mr->opaque, addr, size);
401 trace_memory_region_ops_read(mr, addr, tmp, size);
402 *value |= (tmp & mask) << shift;
403 return MEMTX_OK;
406 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
407 hwaddr addr,
408 uint64_t *value,
409 unsigned size,
410 unsigned shift,
411 uint64_t mask,
412 MemTxAttrs attrs)
414 uint64_t tmp = 0;
415 MemTxResult r;
417 if (mr->flush_coalesced_mmio) {
418 qemu_flush_coalesced_mmio_buffer();
420 r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
421 trace_memory_region_ops_read(mr, addr, tmp, size);
422 *value |= (tmp & mask) << shift;
423 return r;
426 static MemTxResult memory_region_oldmmio_write_accessor(MemoryRegion *mr,
427 hwaddr addr,
428 uint64_t *value,
429 unsigned size,
430 unsigned shift,
431 uint64_t mask,
432 MemTxAttrs attrs)
434 uint64_t tmp;
436 tmp = (*value >> shift) & mask;
437 trace_memory_region_ops_write(mr, addr, tmp, size);
438 mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);
439 return MEMTX_OK;
442 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
443 hwaddr addr,
444 uint64_t *value,
445 unsigned size,
446 unsigned shift,
447 uint64_t mask,
448 MemTxAttrs attrs)
450 uint64_t tmp;
452 if (mr->flush_coalesced_mmio) {
453 qemu_flush_coalesced_mmio_buffer();
455 tmp = (*value >> shift) & mask;
456 trace_memory_region_ops_write(mr, addr, tmp, size);
457 mr->ops->write(mr->opaque, addr, tmp, size);
458 return MEMTX_OK;
461 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
462 hwaddr addr,
463 uint64_t *value,
464 unsigned size,
465 unsigned shift,
466 uint64_t mask,
467 MemTxAttrs attrs)
469 uint64_t tmp;
471 if (mr->flush_coalesced_mmio) {
472 qemu_flush_coalesced_mmio_buffer();
474 tmp = (*value >> shift) & mask;
475 trace_memory_region_ops_write(mr, addr, tmp, size);
476 return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
479 static MemTxResult access_with_adjusted_size(hwaddr addr,
480 uint64_t *value,
481 unsigned size,
482 unsigned access_size_min,
483 unsigned access_size_max,
484 MemTxResult (*access)(MemoryRegion *mr,
485 hwaddr addr,
486 uint64_t *value,
487 unsigned size,
488 unsigned shift,
489 uint64_t mask,
490 MemTxAttrs attrs),
491 MemoryRegion *mr,
492 MemTxAttrs attrs)
494 uint64_t access_mask;
495 unsigned access_size;
496 unsigned i;
497 MemTxResult r = MEMTX_OK;
499 if (!access_size_min) {
500 access_size_min = 1;
502 if (!access_size_max) {
503 access_size_max = 4;
506 /* FIXME: support unaligned access? */
507 access_size = MAX(MIN(size, access_size_max), access_size_min);
508 access_mask = -1ULL >> (64 - access_size * 8);
509 if (memory_region_big_endian(mr)) {
510 for (i = 0; i < size; i += access_size) {
511 r |= access(mr, addr + i, value, access_size,
512 (size - access_size - i) * 8, access_mask, attrs);
514 } else {
515 for (i = 0; i < size; i += access_size) {
516 r |= access(mr, addr + i, value, access_size, i * 8,
517 access_mask, attrs);
520 return r;
523 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
525 AddressSpace *as;
527 while (mr->container) {
528 mr = mr->container;
530 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
531 if (mr == as->root) {
532 return as;
535 return NULL;
538 /* Render a memory region into the global view. Ranges in @view obscure
539 * ranges in @mr.
541 static void render_memory_region(FlatView *view,
542 MemoryRegion *mr,
543 Int128 base,
544 AddrRange clip,
545 bool readonly)
547 MemoryRegion *subregion;
548 unsigned i;
549 hwaddr offset_in_region;
550 Int128 remain;
551 Int128 now;
552 FlatRange fr;
553 AddrRange tmp;
555 if (!mr->enabled) {
556 return;
559 int128_addto(&base, int128_make64(mr->addr));
560 readonly |= mr->readonly;
562 tmp = addrrange_make(base, mr->size);
564 if (!addrrange_intersects(tmp, clip)) {
565 return;
568 clip = addrrange_intersection(tmp, clip);
570 if (mr->alias) {
571 int128_subfrom(&base, int128_make64(mr->alias->addr));
572 int128_subfrom(&base, int128_make64(mr->alias_offset));
573 render_memory_region(view, mr->alias, base, clip, readonly);
574 return;
577 /* Render subregions in priority order. */
578 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
579 render_memory_region(view, subregion, base, clip, readonly);
582 if (!mr->terminates) {
583 return;
586 offset_in_region = int128_get64(int128_sub(clip.start, base));
587 base = clip.start;
588 remain = clip.size;
590 fr.mr = mr;
591 fr.dirty_log_mask = mr->dirty_log_mask;
592 fr.romd_mode = mr->romd_mode;
593 fr.readonly = readonly;
595 /* Render the region itself into any gaps left by the current view. */
596 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
597 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
598 continue;
600 if (int128_lt(base, view->ranges[i].addr.start)) {
601 now = int128_min(remain,
602 int128_sub(view->ranges[i].addr.start, base));
603 fr.offset_in_region = offset_in_region;
604 fr.addr = addrrange_make(base, now);
605 flatview_insert(view, i, &fr);
606 ++i;
607 int128_addto(&base, now);
608 offset_in_region += int128_get64(now);
609 int128_subfrom(&remain, now);
611 now = int128_sub(int128_min(int128_add(base, remain),
612 addrrange_end(view->ranges[i].addr)),
613 base);
614 int128_addto(&base, now);
615 offset_in_region += int128_get64(now);
616 int128_subfrom(&remain, now);
618 if (int128_nz(remain)) {
619 fr.offset_in_region = offset_in_region;
620 fr.addr = addrrange_make(base, remain);
621 flatview_insert(view, i, &fr);
625 /* Render a memory topology into a list of disjoint absolute ranges. */
626 static FlatView *generate_memory_topology(MemoryRegion *mr)
628 FlatView *view;
630 view = g_new(FlatView, 1);
631 flatview_init(view);
633 if (mr) {
634 render_memory_region(view, mr, int128_zero(),
635 addrrange_make(int128_zero(), int128_2_64()), false);
637 flatview_simplify(view);
639 return view;
642 static void address_space_add_del_ioeventfds(AddressSpace *as,
643 MemoryRegionIoeventfd *fds_new,
644 unsigned fds_new_nb,
645 MemoryRegionIoeventfd *fds_old,
646 unsigned fds_old_nb)
648 unsigned iold, inew;
649 MemoryRegionIoeventfd *fd;
650 MemoryRegionSection section;
652 /* Generate a symmetric difference of the old and new fd sets, adding
653 * and deleting as necessary.
656 iold = inew = 0;
657 while (iold < fds_old_nb || inew < fds_new_nb) {
658 if (iold < fds_old_nb
659 && (inew == fds_new_nb
660 || memory_region_ioeventfd_before(fds_old[iold],
661 fds_new[inew]))) {
662 fd = &fds_old[iold];
663 section = (MemoryRegionSection) {
664 .address_space = as,
665 .offset_within_address_space = int128_get64(fd->addr.start),
666 .size = fd->addr.size,
668 MEMORY_LISTENER_CALL(eventfd_del, Forward, &section,
669 fd->match_data, fd->data, fd->e);
670 ++iold;
671 } else if (inew < fds_new_nb
672 && (iold == fds_old_nb
673 || memory_region_ioeventfd_before(fds_new[inew],
674 fds_old[iold]))) {
675 fd = &fds_new[inew];
676 section = (MemoryRegionSection) {
677 .address_space = as,
678 .offset_within_address_space = int128_get64(fd->addr.start),
679 .size = fd->addr.size,
681 MEMORY_LISTENER_CALL(eventfd_add, Reverse, &section,
682 fd->match_data, fd->data, fd->e);
683 ++inew;
684 } else {
685 ++iold;
686 ++inew;
691 static FlatView *address_space_get_flatview(AddressSpace *as)
693 FlatView *view;
695 rcu_read_lock();
696 view = atomic_rcu_read(&as->current_map);
697 flatview_ref(view);
698 rcu_read_unlock();
699 return view;
702 static void address_space_update_ioeventfds(AddressSpace *as)
704 FlatView *view;
705 FlatRange *fr;
706 unsigned ioeventfd_nb = 0;
707 MemoryRegionIoeventfd *ioeventfds = NULL;
708 AddrRange tmp;
709 unsigned i;
711 view = address_space_get_flatview(as);
712 FOR_EACH_FLAT_RANGE(fr, view) {
713 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
714 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
715 int128_sub(fr->addr.start,
716 int128_make64(fr->offset_in_region)));
717 if (addrrange_intersects(fr->addr, tmp)) {
718 ++ioeventfd_nb;
719 ioeventfds = g_realloc(ioeventfds,
720 ioeventfd_nb * sizeof(*ioeventfds));
721 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
722 ioeventfds[ioeventfd_nb-1].addr = tmp;
727 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
728 as->ioeventfds, as->ioeventfd_nb);
730 g_free(as->ioeventfds);
731 as->ioeventfds = ioeventfds;
732 as->ioeventfd_nb = ioeventfd_nb;
733 flatview_unref(view);
736 static void address_space_update_topology_pass(AddressSpace *as,
737 const FlatView *old_view,
738 const FlatView *new_view,
739 bool adding)
741 unsigned iold, inew;
742 FlatRange *frold, *frnew;
744 /* Generate a symmetric difference of the old and new memory maps.
745 * Kill ranges in the old map, and instantiate ranges in the new map.
747 iold = inew = 0;
748 while (iold < old_view->nr || inew < new_view->nr) {
749 if (iold < old_view->nr) {
750 frold = &old_view->ranges[iold];
751 } else {
752 frold = NULL;
754 if (inew < new_view->nr) {
755 frnew = &new_view->ranges[inew];
756 } else {
757 frnew = NULL;
760 if (frold
761 && (!frnew
762 || int128_lt(frold->addr.start, frnew->addr.start)
763 || (int128_eq(frold->addr.start, frnew->addr.start)
764 && !flatrange_equal(frold, frnew)))) {
765 /* In old but not in new, or in both but attributes changed. */
767 if (!adding) {
768 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
771 ++iold;
772 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
773 /* In both and unchanged (except logging may have changed) */
775 if (adding) {
776 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
777 if (frold->dirty_log_mask && !frnew->dirty_log_mask) {
778 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop);
779 } else if (frnew->dirty_log_mask && !frold->dirty_log_mask) {
780 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start);
784 ++iold;
785 ++inew;
786 } else {
787 /* In new */
789 if (adding) {
790 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
793 ++inew;
799 static void address_space_update_topology(AddressSpace *as)
801 FlatView *old_view = address_space_get_flatview(as);
802 FlatView *new_view = generate_memory_topology(as->root);
804 address_space_update_topology_pass(as, old_view, new_view, false);
805 address_space_update_topology_pass(as, old_view, new_view, true);
807 /* Writes are protected by the BQL. */
808 atomic_rcu_set(&as->current_map, new_view);
809 call_rcu(old_view, flatview_unref, rcu);
811 /* Note that all the old MemoryRegions are still alive up to this
812 * point. This relieves most MemoryListeners from the need to
813 * ref/unref the MemoryRegions they get---unless they use them
814 * outside the iothread mutex, in which case precise reference
815 * counting is necessary.
817 flatview_unref(old_view);
819 address_space_update_ioeventfds(as);
822 void memory_region_transaction_begin(void)
824 qemu_flush_coalesced_mmio_buffer();
825 ++memory_region_transaction_depth;
828 static void memory_region_clear_pending(void)
830 memory_region_update_pending = false;
831 ioeventfd_update_pending = false;
834 void memory_region_transaction_commit(void)
836 AddressSpace *as;
838 assert(memory_region_transaction_depth);
839 --memory_region_transaction_depth;
840 if (!memory_region_transaction_depth) {
841 if (memory_region_update_pending) {
842 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
844 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
845 address_space_update_topology(as);
848 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
849 } else if (ioeventfd_update_pending) {
850 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
851 address_space_update_ioeventfds(as);
854 memory_region_clear_pending();
858 static void memory_region_destructor_none(MemoryRegion *mr)
862 static void memory_region_destructor_ram(MemoryRegion *mr)
864 qemu_ram_free(mr->ram_addr);
867 static void memory_region_destructor_alias(MemoryRegion *mr)
869 memory_region_unref(mr->alias);
872 static void memory_region_destructor_ram_from_ptr(MemoryRegion *mr)
874 qemu_ram_free_from_ptr(mr->ram_addr);
877 static void memory_region_destructor_rom_device(MemoryRegion *mr)
879 qemu_ram_free(mr->ram_addr & TARGET_PAGE_MASK);
882 static bool memory_region_need_escape(char c)
884 return c == '/' || c == '[' || c == '\\' || c == ']';
887 static char *memory_region_escape_name(const char *name)
889 const char *p;
890 char *escaped, *q;
891 uint8_t c;
892 size_t bytes = 0;
894 for (p = name; *p; p++) {
895 bytes += memory_region_need_escape(*p) ? 4 : 1;
897 if (bytes == p - name) {
898 return g_memdup(name, bytes + 1);
901 escaped = g_malloc(bytes + 1);
902 for (p = name, q = escaped; *p; p++) {
903 c = *p;
904 if (unlikely(memory_region_need_escape(c))) {
905 *q++ = '\\';
906 *q++ = 'x';
907 *q++ = "0123456789abcdef"[c >> 4];
908 c = "0123456789abcdef"[c & 15];
910 *q++ = c;
912 *q = 0;
913 return escaped;
916 void memory_region_init(MemoryRegion *mr,
917 Object *owner,
918 const char *name,
919 uint64_t size)
921 if (!owner) {
922 owner = container_get(qdev_get_machine(), "/unattached");
925 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
926 mr->size = int128_make64(size);
927 if (size == UINT64_MAX) {
928 mr->size = int128_2_64();
930 mr->name = g_strdup(name);
932 if (name) {
933 char *escaped_name = memory_region_escape_name(name);
934 char *name_array = g_strdup_printf("%s[*]", escaped_name);
935 object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
936 object_unref(OBJECT(mr));
937 g_free(name_array);
938 g_free(escaped_name);
942 static void memory_region_get_addr(Object *obj, Visitor *v, void *opaque,
943 const char *name, Error **errp)
945 MemoryRegion *mr = MEMORY_REGION(obj);
946 uint64_t value = mr->addr;
948 visit_type_uint64(v, &value, name, errp);
951 static void memory_region_get_container(Object *obj, Visitor *v, void *opaque,
952 const char *name, Error **errp)
954 MemoryRegion *mr = MEMORY_REGION(obj);
955 gchar *path = (gchar *)"";
957 if (mr->container) {
958 path = object_get_canonical_path(OBJECT(mr->container));
960 visit_type_str(v, &path, name, errp);
961 if (mr->container) {
962 g_free(path);
966 static Object *memory_region_resolve_container(Object *obj, void *opaque,
967 const char *part)
969 MemoryRegion *mr = MEMORY_REGION(obj);
971 return OBJECT(mr->container);
974 static void memory_region_get_priority(Object *obj, Visitor *v, void *opaque,
975 const char *name, Error **errp)
977 MemoryRegion *mr = MEMORY_REGION(obj);
978 int32_t value = mr->priority;
980 visit_type_int32(v, &value, name, errp);
983 static bool memory_region_get_may_overlap(Object *obj, Error **errp)
985 MemoryRegion *mr = MEMORY_REGION(obj);
987 return mr->may_overlap;
990 static void memory_region_get_size(Object *obj, Visitor *v, void *opaque,
991 const char *name, Error **errp)
993 MemoryRegion *mr = MEMORY_REGION(obj);
994 uint64_t value = memory_region_size(mr);
996 visit_type_uint64(v, &value, name, errp);
999 static void memory_region_initfn(Object *obj)
1001 MemoryRegion *mr = MEMORY_REGION(obj);
1002 ObjectProperty *op;
1004 mr->ops = &unassigned_mem_ops;
1005 mr->enabled = true;
1006 mr->romd_mode = true;
1007 mr->destructor = memory_region_destructor_none;
1008 QTAILQ_INIT(&mr->subregions);
1009 QTAILQ_INIT(&mr->coalesced);
1011 op = object_property_add(OBJECT(mr), "container",
1012 "link<" TYPE_MEMORY_REGION ">",
1013 memory_region_get_container,
1014 NULL, /* memory_region_set_container */
1015 NULL, NULL, &error_abort);
1016 op->resolve = memory_region_resolve_container;
1018 object_property_add(OBJECT(mr), "addr", "uint64",
1019 memory_region_get_addr,
1020 NULL, /* memory_region_set_addr */
1021 NULL, NULL, &error_abort);
1022 object_property_add(OBJECT(mr), "priority", "uint32",
1023 memory_region_get_priority,
1024 NULL, /* memory_region_set_priority */
1025 NULL, NULL, &error_abort);
1026 object_property_add_bool(OBJECT(mr), "may-overlap",
1027 memory_region_get_may_overlap,
1028 NULL, /* memory_region_set_may_overlap */
1029 &error_abort);
1030 object_property_add(OBJECT(mr), "size", "uint64",
1031 memory_region_get_size,
1032 NULL, /* memory_region_set_size, */
1033 NULL, NULL, &error_abort);
1036 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1037 unsigned size)
1039 #ifdef DEBUG_UNASSIGNED
1040 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1041 #endif
1042 if (current_cpu != NULL) {
1043 cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1045 return 0;
1048 static void unassigned_mem_write(void *opaque, hwaddr addr,
1049 uint64_t val, unsigned size)
1051 #ifdef DEBUG_UNASSIGNED
1052 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1053 #endif
1054 if (current_cpu != NULL) {
1055 cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1059 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1060 unsigned size, bool is_write)
1062 return false;
1065 const MemoryRegionOps unassigned_mem_ops = {
1066 .valid.accepts = unassigned_mem_accepts,
1067 .endianness = DEVICE_NATIVE_ENDIAN,
1070 bool memory_region_access_valid(MemoryRegion *mr,
1071 hwaddr addr,
1072 unsigned size,
1073 bool is_write)
1075 int access_size_min, access_size_max;
1076 int access_size, i;
1078 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1079 return false;
1082 if (!mr->ops->valid.accepts) {
1083 return true;
1086 access_size_min = mr->ops->valid.min_access_size;
1087 if (!mr->ops->valid.min_access_size) {
1088 access_size_min = 1;
1091 access_size_max = mr->ops->valid.max_access_size;
1092 if (!mr->ops->valid.max_access_size) {
1093 access_size_max = 4;
1096 access_size = MAX(MIN(size, access_size_max), access_size_min);
1097 for (i = 0; i < size; i += access_size) {
1098 if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
1099 is_write)) {
1100 return false;
1104 return true;
1107 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1108 hwaddr addr,
1109 uint64_t *pval,
1110 unsigned size,
1111 MemTxAttrs attrs)
1113 *pval = 0;
1115 if (mr->ops->read) {
1116 return access_with_adjusted_size(addr, pval, size,
1117 mr->ops->impl.min_access_size,
1118 mr->ops->impl.max_access_size,
1119 memory_region_read_accessor,
1120 mr, attrs);
1121 } else if (mr->ops->read_with_attrs) {
1122 return access_with_adjusted_size(addr, pval, size,
1123 mr->ops->impl.min_access_size,
1124 mr->ops->impl.max_access_size,
1125 memory_region_read_with_attrs_accessor,
1126 mr, attrs);
1127 } else {
1128 return access_with_adjusted_size(addr, pval, size, 1, 4,
1129 memory_region_oldmmio_read_accessor,
1130 mr, attrs);
1134 static MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1135 hwaddr addr,
1136 uint64_t *pval,
1137 unsigned size,
1138 MemTxAttrs attrs)
1140 MemTxResult r;
1142 if (!memory_region_access_valid(mr, addr, size, false)) {
1143 *pval = unassigned_mem_read(mr, addr, size);
1144 return MEMTX_DECODE_ERROR;
1147 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1148 adjust_endianness(mr, pval, size);
1149 return r;
1152 static MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1153 hwaddr addr,
1154 uint64_t data,
1155 unsigned size,
1156 MemTxAttrs attrs)
1158 if (!memory_region_access_valid(mr, addr, size, true)) {
1159 unassigned_mem_write(mr, addr, data, size);
1160 return MEMTX_DECODE_ERROR;
1163 adjust_endianness(mr, &data, size);
1165 if (mr->ops->write) {
1166 return access_with_adjusted_size(addr, &data, size,
1167 mr->ops->impl.min_access_size,
1168 mr->ops->impl.max_access_size,
1169 memory_region_write_accessor, mr,
1170 attrs);
1171 } else if (mr->ops->write_with_attrs) {
1172 return
1173 access_with_adjusted_size(addr, &data, size,
1174 mr->ops->impl.min_access_size,
1175 mr->ops->impl.max_access_size,
1176 memory_region_write_with_attrs_accessor,
1177 mr, attrs);
1178 } else {
1179 return access_with_adjusted_size(addr, &data, size, 1, 4,
1180 memory_region_oldmmio_write_accessor,
1181 mr, attrs);
1185 void memory_region_init_io(MemoryRegion *mr,
1186 Object *owner,
1187 const MemoryRegionOps *ops,
1188 void *opaque,
1189 const char *name,
1190 uint64_t size)
1192 memory_region_init(mr, owner, name, size);
1193 mr->ops = ops;
1194 mr->opaque = opaque;
1195 mr->terminates = true;
1196 mr->ram_addr = ~(ram_addr_t)0;
1199 void memory_region_init_ram(MemoryRegion *mr,
1200 Object *owner,
1201 const char *name,
1202 uint64_t size,
1203 Error **errp)
1205 memory_region_init(mr, owner, name, size);
1206 mr->ram = true;
1207 mr->terminates = true;
1208 mr->destructor = memory_region_destructor_ram;
1209 mr->ram_addr = qemu_ram_alloc(size, mr, errp);
1212 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1213 Object *owner,
1214 const char *name,
1215 uint64_t size,
1216 uint64_t max_size,
1217 void (*resized)(const char*,
1218 uint64_t length,
1219 void *host),
1220 Error **errp)
1222 memory_region_init(mr, owner, name, size);
1223 mr->ram = true;
1224 mr->terminates = true;
1225 mr->destructor = memory_region_destructor_ram;
1226 mr->ram_addr = qemu_ram_alloc_resizeable(size, max_size, resized, mr, errp);
1229 #ifdef __linux__
1230 void memory_region_init_ram_from_file(MemoryRegion *mr,
1231 struct Object *owner,
1232 const char *name,
1233 uint64_t size,
1234 bool share,
1235 const char *path,
1236 Error **errp)
1238 memory_region_init(mr, owner, name, size);
1239 mr->ram = true;
1240 mr->terminates = true;
1241 mr->destructor = memory_region_destructor_ram;
1242 mr->ram_addr = qemu_ram_alloc_from_file(size, mr, share, path, errp);
1244 #endif
1246 void memory_region_init_ram_ptr(MemoryRegion *mr,
1247 Object *owner,
1248 const char *name,
1249 uint64_t size,
1250 void *ptr)
1252 memory_region_init(mr, owner, name, size);
1253 mr->ram = true;
1254 mr->terminates = true;
1255 mr->destructor = memory_region_destructor_ram_from_ptr;
1257 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1258 assert(ptr != NULL);
1259 mr->ram_addr = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_abort);
1262 void memory_region_set_skip_dump(MemoryRegion *mr)
1264 mr->skip_dump = true;
1267 void memory_region_init_alias(MemoryRegion *mr,
1268 Object *owner,
1269 const char *name,
1270 MemoryRegion *orig,
1271 hwaddr offset,
1272 uint64_t size)
1274 memory_region_init(mr, owner, name, size);
1275 memory_region_ref(orig);
1276 mr->destructor = memory_region_destructor_alias;
1277 mr->alias = orig;
1278 mr->alias_offset = offset;
1281 void memory_region_init_rom_device(MemoryRegion *mr,
1282 Object *owner,
1283 const MemoryRegionOps *ops,
1284 void *opaque,
1285 const char *name,
1286 uint64_t size,
1287 Error **errp)
1289 memory_region_init(mr, owner, name, size);
1290 mr->ops = ops;
1291 mr->opaque = opaque;
1292 mr->terminates = true;
1293 mr->rom_device = true;
1294 mr->destructor = memory_region_destructor_rom_device;
1295 mr->ram_addr = qemu_ram_alloc(size, mr, errp);
1298 void memory_region_init_iommu(MemoryRegion *mr,
1299 Object *owner,
1300 const MemoryRegionIOMMUOps *ops,
1301 const char *name,
1302 uint64_t size)
1304 memory_region_init(mr, owner, name, size);
1305 mr->iommu_ops = ops,
1306 mr->terminates = true; /* then re-forwards */
1307 notifier_list_init(&mr->iommu_notify);
1310 void memory_region_init_reservation(MemoryRegion *mr,
1311 Object *owner,
1312 const char *name,
1313 uint64_t size)
1315 memory_region_init_io(mr, owner, &unassigned_mem_ops, mr, name, size);
1318 static void memory_region_finalize(Object *obj)
1320 MemoryRegion *mr = MEMORY_REGION(obj);
1322 assert(QTAILQ_EMPTY(&mr->subregions));
1323 mr->destructor(mr);
1324 memory_region_clear_coalescing(mr);
1325 g_free((char *)mr->name);
1326 g_free(mr->ioeventfds);
1329 Object *memory_region_owner(MemoryRegion *mr)
1331 Object *obj = OBJECT(mr);
1332 return obj->parent;
1335 void memory_region_ref(MemoryRegion *mr)
1337 /* MMIO callbacks most likely will access data that belongs
1338 * to the owner, hence the need to ref/unref the owner whenever
1339 * the memory region is in use.
1341 * The memory region is a child of its owner. As long as the
1342 * owner doesn't call unparent itself on the memory region,
1343 * ref-ing the owner will also keep the memory region alive.
1344 * Memory regions without an owner are supposed to never go away,
1345 * but we still ref/unref them for debugging purposes.
1347 Object *obj = OBJECT(mr);
1348 if (obj && obj->parent) {
1349 object_ref(obj->parent);
1350 } else {
1351 object_ref(obj);
1355 void memory_region_unref(MemoryRegion *mr)
1357 Object *obj = OBJECT(mr);
1358 if (obj && obj->parent) {
1359 object_unref(obj->parent);
1360 } else {
1361 object_unref(obj);
1365 uint64_t memory_region_size(MemoryRegion *mr)
1367 if (int128_eq(mr->size, int128_2_64())) {
1368 return UINT64_MAX;
1370 return int128_get64(mr->size);
1373 const char *memory_region_name(const MemoryRegion *mr)
1375 if (!mr->name) {
1376 ((MemoryRegion *)mr)->name =
1377 object_get_canonical_path_component(OBJECT(mr));
1379 return mr->name;
1382 bool memory_region_is_ram(MemoryRegion *mr)
1384 return mr->ram;
1387 bool memory_region_is_skip_dump(MemoryRegion *mr)
1389 return mr->skip_dump;
1392 bool memory_region_is_logging(MemoryRegion *mr)
1394 return mr->dirty_log_mask;
1397 bool memory_region_is_rom(MemoryRegion *mr)
1399 return mr->ram && mr->readonly;
1402 bool memory_region_is_iommu(MemoryRegion *mr)
1404 return mr->iommu_ops;
1407 void memory_region_register_iommu_notifier(MemoryRegion *mr, Notifier *n)
1409 notifier_list_add(&mr->iommu_notify, n);
1412 void memory_region_unregister_iommu_notifier(Notifier *n)
1414 notifier_remove(n);
1417 void memory_region_notify_iommu(MemoryRegion *mr,
1418 IOMMUTLBEntry entry)
1420 assert(memory_region_is_iommu(mr));
1421 notifier_list_notify(&mr->iommu_notify, &entry);
1424 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1426 uint8_t mask = 1 << client;
1428 memory_region_transaction_begin();
1429 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1430 memory_region_update_pending |= mr->enabled;
1431 memory_region_transaction_commit();
1434 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1435 hwaddr size, unsigned client)
1437 assert(mr->terminates);
1438 return cpu_physical_memory_get_dirty(mr->ram_addr + addr, size, client);
1441 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1442 hwaddr size)
1444 assert(mr->terminates);
1445 cpu_physical_memory_set_dirty_range(mr->ram_addr + addr, size);
1448 bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,
1449 hwaddr size, unsigned client)
1451 bool ret;
1452 assert(mr->terminates);
1453 ret = cpu_physical_memory_get_dirty(mr->ram_addr + addr, size, client);
1454 if (ret) {
1455 cpu_physical_memory_reset_dirty(mr->ram_addr + addr, size, client);
1457 return ret;
1461 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1463 AddressSpace *as;
1464 FlatRange *fr;
1466 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1467 FlatView *view = address_space_get_flatview(as);
1468 FOR_EACH_FLAT_RANGE(fr, view) {
1469 if (fr->mr == mr) {
1470 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1473 flatview_unref(view);
1477 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1479 if (mr->readonly != readonly) {
1480 memory_region_transaction_begin();
1481 mr->readonly = readonly;
1482 memory_region_update_pending |= mr->enabled;
1483 memory_region_transaction_commit();
1487 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
1489 if (mr->romd_mode != romd_mode) {
1490 memory_region_transaction_begin();
1491 mr->romd_mode = romd_mode;
1492 memory_region_update_pending |= mr->enabled;
1493 memory_region_transaction_commit();
1497 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1498 hwaddr size, unsigned client)
1500 assert(mr->terminates);
1501 cpu_physical_memory_reset_dirty(mr->ram_addr + addr, size, client);
1504 int memory_region_get_fd(MemoryRegion *mr)
1506 if (mr->alias) {
1507 return memory_region_get_fd(mr->alias);
1510 assert(mr->terminates);
1512 return qemu_get_ram_fd(mr->ram_addr & TARGET_PAGE_MASK);
1515 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1517 if (mr->alias) {
1518 return memory_region_get_ram_ptr(mr->alias) + mr->alias_offset;
1521 assert(mr->terminates);
1523 return qemu_get_ram_ptr(mr->ram_addr & TARGET_PAGE_MASK);
1526 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1528 FlatView *view;
1529 FlatRange *fr;
1530 CoalescedMemoryRange *cmr;
1531 AddrRange tmp;
1532 MemoryRegionSection section;
1534 view = address_space_get_flatview(as);
1535 FOR_EACH_FLAT_RANGE(fr, view) {
1536 if (fr->mr == mr) {
1537 section = (MemoryRegionSection) {
1538 .address_space = as,
1539 .offset_within_address_space = int128_get64(fr->addr.start),
1540 .size = fr->addr.size,
1543 MEMORY_LISTENER_CALL(coalesced_mmio_del, Reverse, &section,
1544 int128_get64(fr->addr.start),
1545 int128_get64(fr->addr.size));
1546 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1547 tmp = addrrange_shift(cmr->addr,
1548 int128_sub(fr->addr.start,
1549 int128_make64(fr->offset_in_region)));
1550 if (!addrrange_intersects(tmp, fr->addr)) {
1551 continue;
1553 tmp = addrrange_intersection(tmp, fr->addr);
1554 MEMORY_LISTENER_CALL(coalesced_mmio_add, Forward, &section,
1555 int128_get64(tmp.start),
1556 int128_get64(tmp.size));
1560 flatview_unref(view);
1563 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1565 AddressSpace *as;
1567 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1568 memory_region_update_coalesced_range_as(mr, as);
1572 void memory_region_set_coalescing(MemoryRegion *mr)
1574 memory_region_clear_coalescing(mr);
1575 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1578 void memory_region_add_coalescing(MemoryRegion *mr,
1579 hwaddr offset,
1580 uint64_t size)
1582 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1584 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1585 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1586 memory_region_update_coalesced_range(mr);
1587 memory_region_set_flush_coalesced(mr);
1590 void memory_region_clear_coalescing(MemoryRegion *mr)
1592 CoalescedMemoryRange *cmr;
1593 bool updated = false;
1595 qemu_flush_coalesced_mmio_buffer();
1596 mr->flush_coalesced_mmio = false;
1598 while (!QTAILQ_EMPTY(&mr->coalesced)) {
1599 cmr = QTAILQ_FIRST(&mr->coalesced);
1600 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1601 g_free(cmr);
1602 updated = true;
1605 if (updated) {
1606 memory_region_update_coalesced_range(mr);
1610 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1612 mr->flush_coalesced_mmio = true;
1615 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1617 qemu_flush_coalesced_mmio_buffer();
1618 if (QTAILQ_EMPTY(&mr->coalesced)) {
1619 mr->flush_coalesced_mmio = false;
1623 void memory_region_add_eventfd(MemoryRegion *mr,
1624 hwaddr addr,
1625 unsigned size,
1626 bool match_data,
1627 uint64_t data,
1628 EventNotifier *e)
1630 MemoryRegionIoeventfd mrfd = {
1631 .addr.start = int128_make64(addr),
1632 .addr.size = int128_make64(size),
1633 .match_data = match_data,
1634 .data = data,
1635 .e = e,
1637 unsigned i;
1639 adjust_endianness(mr, &mrfd.data, size);
1640 memory_region_transaction_begin();
1641 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1642 if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
1643 break;
1646 ++mr->ioeventfd_nb;
1647 mr->ioeventfds = g_realloc(mr->ioeventfds,
1648 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
1649 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
1650 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
1651 mr->ioeventfds[i] = mrfd;
1652 ioeventfd_update_pending |= mr->enabled;
1653 memory_region_transaction_commit();
1656 void memory_region_del_eventfd(MemoryRegion *mr,
1657 hwaddr addr,
1658 unsigned size,
1659 bool match_data,
1660 uint64_t data,
1661 EventNotifier *e)
1663 MemoryRegionIoeventfd mrfd = {
1664 .addr.start = int128_make64(addr),
1665 .addr.size = int128_make64(size),
1666 .match_data = match_data,
1667 .data = data,
1668 .e = e,
1670 unsigned i;
1672 adjust_endianness(mr, &mrfd.data, size);
1673 memory_region_transaction_begin();
1674 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1675 if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
1676 break;
1679 assert(i != mr->ioeventfd_nb);
1680 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
1681 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
1682 --mr->ioeventfd_nb;
1683 mr->ioeventfds = g_realloc(mr->ioeventfds,
1684 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
1685 ioeventfd_update_pending |= mr->enabled;
1686 memory_region_transaction_commit();
1689 static void memory_region_update_container_subregions(MemoryRegion *subregion)
1691 hwaddr offset = subregion->addr;
1692 MemoryRegion *mr = subregion->container;
1693 MemoryRegion *other;
1695 memory_region_transaction_begin();
1697 memory_region_ref(subregion);
1698 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1699 if (subregion->may_overlap || other->may_overlap) {
1700 continue;
1702 if (int128_ge(int128_make64(offset),
1703 int128_add(int128_make64(other->addr), other->size))
1704 || int128_le(int128_add(int128_make64(offset), subregion->size),
1705 int128_make64(other->addr))) {
1706 continue;
1708 #if 0
1709 printf("warning: subregion collision %llx/%llx (%s) "
1710 "vs %llx/%llx (%s)\n",
1711 (unsigned long long)offset,
1712 (unsigned long long)int128_get64(subregion->size),
1713 subregion->name,
1714 (unsigned long long)other->addr,
1715 (unsigned long long)int128_get64(other->size),
1716 other->name);
1717 #endif
1719 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1720 if (subregion->priority >= other->priority) {
1721 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
1722 goto done;
1725 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
1726 done:
1727 memory_region_update_pending |= mr->enabled && subregion->enabled;
1728 memory_region_transaction_commit();
1731 static void memory_region_add_subregion_common(MemoryRegion *mr,
1732 hwaddr offset,
1733 MemoryRegion *subregion)
1735 assert(!subregion->container);
1736 subregion->container = mr;
1737 subregion->addr = offset;
1738 memory_region_update_container_subregions(subregion);
1741 void memory_region_add_subregion(MemoryRegion *mr,
1742 hwaddr offset,
1743 MemoryRegion *subregion)
1745 subregion->may_overlap = false;
1746 subregion->priority = 0;
1747 memory_region_add_subregion_common(mr, offset, subregion);
1750 void memory_region_add_subregion_overlap(MemoryRegion *mr,
1751 hwaddr offset,
1752 MemoryRegion *subregion,
1753 int priority)
1755 subregion->may_overlap = true;
1756 subregion->priority = priority;
1757 memory_region_add_subregion_common(mr, offset, subregion);
1760 void memory_region_del_subregion(MemoryRegion *mr,
1761 MemoryRegion *subregion)
1763 memory_region_transaction_begin();
1764 assert(subregion->container == mr);
1765 subregion->container = NULL;
1766 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
1767 memory_region_unref(subregion);
1768 memory_region_update_pending |= mr->enabled && subregion->enabled;
1769 memory_region_transaction_commit();
1772 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
1774 if (enabled == mr->enabled) {
1775 return;
1777 memory_region_transaction_begin();
1778 mr->enabled = enabled;
1779 memory_region_update_pending = true;
1780 memory_region_transaction_commit();
1783 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
1785 Int128 s = int128_make64(size);
1787 if (size == UINT64_MAX) {
1788 s = int128_2_64();
1790 if (int128_eq(s, mr->size)) {
1791 return;
1793 memory_region_transaction_begin();
1794 mr->size = s;
1795 memory_region_update_pending = true;
1796 memory_region_transaction_commit();
1799 static void memory_region_readd_subregion(MemoryRegion *mr)
1801 MemoryRegion *container = mr->container;
1803 if (container) {
1804 memory_region_transaction_begin();
1805 memory_region_ref(mr);
1806 memory_region_del_subregion(container, mr);
1807 mr->container = container;
1808 memory_region_update_container_subregions(mr);
1809 memory_region_unref(mr);
1810 memory_region_transaction_commit();
1814 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
1816 if (addr != mr->addr) {
1817 mr->addr = addr;
1818 memory_region_readd_subregion(mr);
1822 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
1824 assert(mr->alias);
1826 if (offset == mr->alias_offset) {
1827 return;
1830 memory_region_transaction_begin();
1831 mr->alias_offset = offset;
1832 memory_region_update_pending |= mr->enabled;
1833 memory_region_transaction_commit();
1836 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
1838 return mr->ram_addr;
1841 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
1843 return mr->align;
1846 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
1848 const AddrRange *addr = addr_;
1849 const FlatRange *fr = fr_;
1851 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
1852 return -1;
1853 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
1854 return 1;
1856 return 0;
1859 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
1861 return bsearch(&addr, view->ranges, view->nr,
1862 sizeof(FlatRange), cmp_flatrange_addr);
1865 bool memory_region_present(MemoryRegion *container, hwaddr addr)
1867 MemoryRegion *mr = memory_region_find(container, addr, 1).mr;
1868 if (!mr || (mr == container)) {
1869 return false;
1871 memory_region_unref(mr);
1872 return true;
1875 bool memory_region_is_mapped(MemoryRegion *mr)
1877 return mr->container ? true : false;
1880 MemoryRegionSection memory_region_find(MemoryRegion *mr,
1881 hwaddr addr, uint64_t size)
1883 MemoryRegionSection ret = { .mr = NULL };
1884 MemoryRegion *root;
1885 AddressSpace *as;
1886 AddrRange range;
1887 FlatView *view;
1888 FlatRange *fr;
1890 addr += mr->addr;
1891 for (root = mr; root->container; ) {
1892 root = root->container;
1893 addr += root->addr;
1896 as = memory_region_to_address_space(root);
1897 if (!as) {
1898 return ret;
1900 range = addrrange_make(int128_make64(addr), int128_make64(size));
1902 rcu_read_lock();
1903 view = atomic_rcu_read(&as->current_map);
1904 fr = flatview_lookup(view, range);
1905 if (!fr) {
1906 goto out;
1909 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
1910 --fr;
1913 ret.mr = fr->mr;
1914 ret.address_space = as;
1915 range = addrrange_intersection(range, fr->addr);
1916 ret.offset_within_region = fr->offset_in_region;
1917 ret.offset_within_region += int128_get64(int128_sub(range.start,
1918 fr->addr.start));
1919 ret.size = range.size;
1920 ret.offset_within_address_space = int128_get64(range.start);
1921 ret.readonly = fr->readonly;
1922 memory_region_ref(ret.mr);
1923 out:
1924 rcu_read_unlock();
1925 return ret;
1928 void address_space_sync_dirty_bitmap(AddressSpace *as)
1930 FlatView *view;
1931 FlatRange *fr;
1933 view = address_space_get_flatview(as);
1934 FOR_EACH_FLAT_RANGE(fr, view) {
1935 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1937 flatview_unref(view);
1940 void memory_global_dirty_log_start(void)
1942 global_dirty_log = true;
1943 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
1946 void memory_global_dirty_log_stop(void)
1948 global_dirty_log = false;
1949 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
1952 static void listener_add_address_space(MemoryListener *listener,
1953 AddressSpace *as)
1955 FlatView *view;
1956 FlatRange *fr;
1958 if (listener->address_space_filter
1959 && listener->address_space_filter != as) {
1960 return;
1963 if (global_dirty_log) {
1964 if (listener->log_global_start) {
1965 listener->log_global_start(listener);
1969 view = address_space_get_flatview(as);
1970 FOR_EACH_FLAT_RANGE(fr, view) {
1971 MemoryRegionSection section = {
1972 .mr = fr->mr,
1973 .address_space = as,
1974 .offset_within_region = fr->offset_in_region,
1975 .size = fr->addr.size,
1976 .offset_within_address_space = int128_get64(fr->addr.start),
1977 .readonly = fr->readonly,
1979 if (listener->region_add) {
1980 listener->region_add(listener, &section);
1983 flatview_unref(view);
1986 void memory_listener_register(MemoryListener *listener, AddressSpace *filter)
1988 MemoryListener *other = NULL;
1989 AddressSpace *as;
1991 listener->address_space_filter = filter;
1992 if (QTAILQ_EMPTY(&memory_listeners)
1993 || listener->priority >= QTAILQ_LAST(&memory_listeners,
1994 memory_listeners)->priority) {
1995 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
1996 } else {
1997 QTAILQ_FOREACH(other, &memory_listeners, link) {
1998 if (listener->priority < other->priority) {
1999 break;
2002 QTAILQ_INSERT_BEFORE(other, listener, link);
2005 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2006 listener_add_address_space(listener, as);
2010 void memory_listener_unregister(MemoryListener *listener)
2012 QTAILQ_REMOVE(&memory_listeners, listener, link);
2015 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2017 memory_region_ref(root);
2018 memory_region_transaction_begin();
2019 as->root = root;
2020 as->current_map = g_new(FlatView, 1);
2021 flatview_init(as->current_map);
2022 as->ioeventfd_nb = 0;
2023 as->ioeventfds = NULL;
2024 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2025 as->name = g_strdup(name ? name : "anonymous");
2026 address_space_init_dispatch(as);
2027 memory_region_update_pending |= root->enabled;
2028 memory_region_transaction_commit();
2031 static void do_address_space_destroy(AddressSpace *as)
2033 MemoryListener *listener;
2035 address_space_destroy_dispatch(as);
2037 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2038 assert(listener->address_space_filter != as);
2041 flatview_unref(as->current_map);
2042 g_free(as->name);
2043 g_free(as->ioeventfds);
2044 memory_region_unref(as->root);
2047 void address_space_destroy(AddressSpace *as)
2049 MemoryRegion *root = as->root;
2051 /* Flush out anything from MemoryListeners listening in on this */
2052 memory_region_transaction_begin();
2053 as->root = NULL;
2054 memory_region_transaction_commit();
2055 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2056 address_space_unregister(as);
2058 /* At this point, as->dispatch and as->current_map are dummy
2059 * entries that the guest should never use. Wait for the old
2060 * values to expire before freeing the data.
2062 as->root = root;
2063 call_rcu(as, do_address_space_destroy, rcu);
2066 bool io_mem_read(MemoryRegion *mr, hwaddr addr, uint64_t *pval, unsigned size)
2068 return memory_region_dispatch_read(mr, addr, pval, size,
2069 MEMTXATTRS_UNSPECIFIED);
2072 bool io_mem_write(MemoryRegion *mr, hwaddr addr,
2073 uint64_t val, unsigned size)
2075 return memory_region_dispatch_write(mr, addr, val, size,
2076 MEMTXATTRS_UNSPECIFIED);
2079 typedef struct MemoryRegionList MemoryRegionList;
2081 struct MemoryRegionList {
2082 const MemoryRegion *mr;
2083 QTAILQ_ENTRY(MemoryRegionList) queue;
2086 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
2088 static void mtree_print_mr(fprintf_function mon_printf, void *f,
2089 const MemoryRegion *mr, unsigned int level,
2090 hwaddr base,
2091 MemoryRegionListHead *alias_print_queue)
2093 MemoryRegionList *new_ml, *ml, *next_ml;
2094 MemoryRegionListHead submr_print_queue;
2095 const MemoryRegion *submr;
2096 unsigned int i;
2098 if (!mr || !mr->enabled) {
2099 return;
2102 for (i = 0; i < level; i++) {
2103 mon_printf(f, " ");
2106 if (mr->alias) {
2107 MemoryRegionList *ml;
2108 bool found = false;
2110 /* check if the alias is already in the queue */
2111 QTAILQ_FOREACH(ml, alias_print_queue, queue) {
2112 if (ml->mr == mr->alias) {
2113 found = true;
2117 if (!found) {
2118 ml = g_new(MemoryRegionList, 1);
2119 ml->mr = mr->alias;
2120 QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
2122 mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
2123 " (prio %d, %c%c): alias %s @%s " TARGET_FMT_plx
2124 "-" TARGET_FMT_plx "\n",
2125 base + mr->addr,
2126 base + mr->addr
2127 + (int128_nz(mr->size) ?
2128 (hwaddr)int128_get64(int128_sub(mr->size,
2129 int128_one())) : 0),
2130 mr->priority,
2131 mr->romd_mode ? 'R' : '-',
2132 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2133 : '-',
2134 memory_region_name(mr),
2135 memory_region_name(mr->alias),
2136 mr->alias_offset,
2137 mr->alias_offset
2138 + (int128_nz(mr->size) ?
2139 (hwaddr)int128_get64(int128_sub(mr->size,
2140 int128_one())) : 0));
2141 } else {
2142 mon_printf(f,
2143 TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %c%c): %s\n",
2144 base + mr->addr,
2145 base + mr->addr
2146 + (int128_nz(mr->size) ?
2147 (hwaddr)int128_get64(int128_sub(mr->size,
2148 int128_one())) : 0),
2149 mr->priority,
2150 mr->romd_mode ? 'R' : '-',
2151 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2152 : '-',
2153 memory_region_name(mr));
2156 QTAILQ_INIT(&submr_print_queue);
2158 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2159 new_ml = g_new(MemoryRegionList, 1);
2160 new_ml->mr = submr;
2161 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2162 if (new_ml->mr->addr < ml->mr->addr ||
2163 (new_ml->mr->addr == ml->mr->addr &&
2164 new_ml->mr->priority > ml->mr->priority)) {
2165 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
2166 new_ml = NULL;
2167 break;
2170 if (new_ml) {
2171 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
2175 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2176 mtree_print_mr(mon_printf, f, ml->mr, level + 1, base + mr->addr,
2177 alias_print_queue);
2180 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
2181 g_free(ml);
2185 void mtree_info(fprintf_function mon_printf, void *f)
2187 MemoryRegionListHead ml_head;
2188 MemoryRegionList *ml, *ml2;
2189 AddressSpace *as;
2191 QTAILQ_INIT(&ml_head);
2193 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2194 mon_printf(f, "%s\n", as->name);
2195 mtree_print_mr(mon_printf, f, as->root, 0, 0, &ml_head);
2198 mon_printf(f, "aliases\n");
2199 /* print aliased regions */
2200 QTAILQ_FOREACH(ml, &ml_head, queue) {
2201 mon_printf(f, "%s\n", memory_region_name(ml->mr));
2202 mtree_print_mr(mon_printf, f, ml->mr, 0, 0, &ml_head);
2205 QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
2206 g_free(ml);
2210 static const TypeInfo memory_region_info = {
2211 .parent = TYPE_OBJECT,
2212 .name = TYPE_MEMORY_REGION,
2213 .instance_size = sizeof(MemoryRegion),
2214 .instance_init = memory_region_initfn,
2215 .instance_finalize = memory_region_finalize,
2218 static void memory_register_types(void)
2220 type_register_static(&memory_region_info);
2223 type_init(memory_register_types)