qapi-visit: Honor prefix of discriminator enum
[qemu/kevin.git] / memory.c
blob09041edd437db20eb76148dfa296dc0e43d41f75
1 /*
2 * Physical memory management
4 * Copyright 2011 Red Hat, Inc. and/or its affiliates
6 * Authors:
7 * Avi Kivity <avi@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "exec/memory.h"
18 #include "exec/address-spaces.h"
19 #include "exec/ioport.h"
20 #include "qapi/visitor.h"
21 #include "qemu/bitops.h"
22 #include "qemu/error-report.h"
23 #include "qom/object.h"
24 #include "trace.h"
26 #include "exec/memory-internal.h"
27 #include "exec/ram_addr.h"
28 #include "sysemu/kvm.h"
29 #include "sysemu/sysemu.h"
31 //#define DEBUG_UNASSIGNED
33 #define RAM_ADDR_INVALID (~(ram_addr_t)0)
35 static unsigned memory_region_transaction_depth;
36 static bool memory_region_update_pending;
37 static bool ioeventfd_update_pending;
38 static bool global_dirty_log = false;
40 static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
41 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
43 static QTAILQ_HEAD(, AddressSpace) address_spaces
44 = QTAILQ_HEAD_INITIALIZER(address_spaces);
46 typedef struct AddrRange AddrRange;
49 * Note that signed integers are needed for negative offsetting in aliases
50 * (large MemoryRegion::alias_offset).
52 struct AddrRange {
53 Int128 start;
54 Int128 size;
57 static AddrRange addrrange_make(Int128 start, Int128 size)
59 return (AddrRange) { start, size };
62 static bool addrrange_equal(AddrRange r1, AddrRange r2)
64 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
67 static Int128 addrrange_end(AddrRange r)
69 return int128_add(r.start, r.size);
72 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
74 int128_addto(&range.start, delta);
75 return range;
78 static bool addrrange_contains(AddrRange range, Int128 addr)
80 return int128_ge(addr, range.start)
81 && int128_lt(addr, addrrange_end(range));
84 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
86 return addrrange_contains(r1, r2.start)
87 || addrrange_contains(r2, r1.start);
90 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
92 Int128 start = int128_max(r1.start, r2.start);
93 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
94 return addrrange_make(start, int128_sub(end, start));
97 enum ListenerDirection { Forward, Reverse };
99 static bool memory_listener_match(MemoryListener *listener,
100 MemoryRegionSection *section)
102 return !listener->address_space_filter
103 || listener->address_space_filter == section->address_space;
106 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
107 do { \
108 MemoryListener *_listener; \
110 switch (_direction) { \
111 case Forward: \
112 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
113 if (_listener->_callback) { \
114 _listener->_callback(_listener, ##_args); \
117 break; \
118 case Reverse: \
119 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
120 memory_listeners, link) { \
121 if (_listener->_callback) { \
122 _listener->_callback(_listener, ##_args); \
125 break; \
126 default: \
127 abort(); \
129 } while (0)
131 #define MEMORY_LISTENER_CALL(_callback, _direction, _section, _args...) \
132 do { \
133 MemoryListener *_listener; \
135 switch (_direction) { \
136 case Forward: \
137 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
138 if (_listener->_callback \
139 && memory_listener_match(_listener, _section)) { \
140 _listener->_callback(_listener, _section, ##_args); \
143 break; \
144 case Reverse: \
145 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
146 memory_listeners, link) { \
147 if (_listener->_callback \
148 && memory_listener_match(_listener, _section)) { \
149 _listener->_callback(_listener, _section, ##_args); \
152 break; \
153 default: \
154 abort(); \
156 } while (0)
158 /* No need to ref/unref .mr, the FlatRange keeps it alive. */
159 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...) \
160 MEMORY_LISTENER_CALL(callback, dir, (&(MemoryRegionSection) { \
161 .mr = (fr)->mr, \
162 .address_space = (as), \
163 .offset_within_region = (fr)->offset_in_region, \
164 .size = (fr)->addr.size, \
165 .offset_within_address_space = int128_get64((fr)->addr.start), \
166 .readonly = (fr)->readonly, \
167 }), ##_args)
169 struct CoalescedMemoryRange {
170 AddrRange addr;
171 QTAILQ_ENTRY(CoalescedMemoryRange) link;
174 struct MemoryRegionIoeventfd {
175 AddrRange addr;
176 bool match_data;
177 uint64_t data;
178 EventNotifier *e;
181 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
182 MemoryRegionIoeventfd b)
184 if (int128_lt(a.addr.start, b.addr.start)) {
185 return true;
186 } else if (int128_gt(a.addr.start, b.addr.start)) {
187 return false;
188 } else if (int128_lt(a.addr.size, b.addr.size)) {
189 return true;
190 } else if (int128_gt(a.addr.size, b.addr.size)) {
191 return false;
192 } else if (a.match_data < b.match_data) {
193 return true;
194 } else if (a.match_data > b.match_data) {
195 return false;
196 } else if (a.match_data) {
197 if (a.data < b.data) {
198 return true;
199 } else if (a.data > b.data) {
200 return false;
203 if (a.e < b.e) {
204 return true;
205 } else if (a.e > b.e) {
206 return false;
208 return false;
211 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
212 MemoryRegionIoeventfd b)
214 return !memory_region_ioeventfd_before(a, b)
215 && !memory_region_ioeventfd_before(b, a);
218 typedef struct FlatRange FlatRange;
219 typedef struct FlatView FlatView;
221 /* Range of memory in the global map. Addresses are absolute. */
222 struct FlatRange {
223 MemoryRegion *mr;
224 hwaddr offset_in_region;
225 AddrRange addr;
226 uint8_t dirty_log_mask;
227 bool romd_mode;
228 bool readonly;
231 /* Flattened global view of current active memory hierarchy. Kept in sorted
232 * order.
234 struct FlatView {
235 struct rcu_head rcu;
236 unsigned ref;
237 FlatRange *ranges;
238 unsigned nr;
239 unsigned nr_allocated;
242 typedef struct AddressSpaceOps AddressSpaceOps;
244 #define FOR_EACH_FLAT_RANGE(var, view) \
245 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
247 static bool flatrange_equal(FlatRange *a, FlatRange *b)
249 return a->mr == b->mr
250 && addrrange_equal(a->addr, b->addr)
251 && a->offset_in_region == b->offset_in_region
252 && a->romd_mode == b->romd_mode
253 && a->readonly == b->readonly;
256 static void flatview_init(FlatView *view)
258 view->ref = 1;
259 view->ranges = NULL;
260 view->nr = 0;
261 view->nr_allocated = 0;
264 /* Insert a range into a given position. Caller is responsible for maintaining
265 * sorting order.
267 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
269 if (view->nr == view->nr_allocated) {
270 view->nr_allocated = MAX(2 * view->nr, 10);
271 view->ranges = g_realloc(view->ranges,
272 view->nr_allocated * sizeof(*view->ranges));
274 memmove(view->ranges + pos + 1, view->ranges + pos,
275 (view->nr - pos) * sizeof(FlatRange));
276 view->ranges[pos] = *range;
277 memory_region_ref(range->mr);
278 ++view->nr;
281 static void flatview_destroy(FlatView *view)
283 int i;
285 for (i = 0; i < view->nr; i++) {
286 memory_region_unref(view->ranges[i].mr);
288 g_free(view->ranges);
289 g_free(view);
292 static void flatview_ref(FlatView *view)
294 atomic_inc(&view->ref);
297 static void flatview_unref(FlatView *view)
299 if (atomic_fetch_dec(&view->ref) == 1) {
300 flatview_destroy(view);
304 static bool can_merge(FlatRange *r1, FlatRange *r2)
306 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
307 && r1->mr == r2->mr
308 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
309 r1->addr.size),
310 int128_make64(r2->offset_in_region))
311 && r1->dirty_log_mask == r2->dirty_log_mask
312 && r1->romd_mode == r2->romd_mode
313 && r1->readonly == r2->readonly;
316 /* Attempt to simplify a view by merging adjacent ranges */
317 static void flatview_simplify(FlatView *view)
319 unsigned i, j;
321 i = 0;
322 while (i < view->nr) {
323 j = i + 1;
324 while (j < view->nr
325 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
326 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
327 ++j;
329 ++i;
330 memmove(&view->ranges[i], &view->ranges[j],
331 (view->nr - j) * sizeof(view->ranges[j]));
332 view->nr -= j - i;
336 static bool memory_region_big_endian(MemoryRegion *mr)
338 #ifdef TARGET_WORDS_BIGENDIAN
339 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
340 #else
341 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
342 #endif
345 static bool memory_region_wrong_endianness(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 void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
356 if (memory_region_wrong_endianness(mr)) {
357 switch (size) {
358 case 1:
359 break;
360 case 2:
361 *data = bswap16(*data);
362 break;
363 case 4:
364 *data = bswap32(*data);
365 break;
366 case 8:
367 *data = bswap64(*data);
368 break;
369 default:
370 abort();
375 static MemTxResult memory_region_oldmmio_read_accessor(MemoryRegion *mr,
376 hwaddr addr,
377 uint64_t *value,
378 unsigned size,
379 unsigned shift,
380 uint64_t mask,
381 MemTxAttrs attrs)
383 uint64_t tmp;
385 tmp = mr->ops->old_mmio.read[ctz32(size)](mr->opaque, addr);
386 trace_memory_region_ops_read(mr, addr, tmp, size);
387 *value |= (tmp & mask) << shift;
388 return MEMTX_OK;
391 static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
392 hwaddr addr,
393 uint64_t *value,
394 unsigned size,
395 unsigned shift,
396 uint64_t mask,
397 MemTxAttrs attrs)
399 uint64_t tmp;
401 tmp = mr->ops->read(mr->opaque, addr, size);
402 trace_memory_region_ops_read(mr, addr, tmp, size);
403 *value |= (tmp & mask) << shift;
404 return MEMTX_OK;
407 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
408 hwaddr addr,
409 uint64_t *value,
410 unsigned size,
411 unsigned shift,
412 uint64_t mask,
413 MemTxAttrs attrs)
415 uint64_t tmp = 0;
416 MemTxResult r;
418 r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
419 trace_memory_region_ops_read(mr, addr, tmp, size);
420 *value |= (tmp & mask) << shift;
421 return r;
424 static MemTxResult memory_region_oldmmio_write_accessor(MemoryRegion *mr,
425 hwaddr addr,
426 uint64_t *value,
427 unsigned size,
428 unsigned shift,
429 uint64_t mask,
430 MemTxAttrs attrs)
432 uint64_t tmp;
434 tmp = (*value >> shift) & mask;
435 trace_memory_region_ops_write(mr, addr, tmp, size);
436 mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);
437 return MEMTX_OK;
440 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
441 hwaddr addr,
442 uint64_t *value,
443 unsigned size,
444 unsigned shift,
445 uint64_t mask,
446 MemTxAttrs attrs)
448 uint64_t tmp;
450 tmp = (*value >> shift) & mask;
451 trace_memory_region_ops_write(mr, addr, tmp, size);
452 mr->ops->write(mr->opaque, addr, tmp, size);
453 return MEMTX_OK;
456 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
457 hwaddr addr,
458 uint64_t *value,
459 unsigned size,
460 unsigned shift,
461 uint64_t mask,
462 MemTxAttrs attrs)
464 uint64_t tmp;
466 tmp = (*value >> shift) & mask;
467 trace_memory_region_ops_write(mr, addr, tmp, size);
468 return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
471 static MemTxResult access_with_adjusted_size(hwaddr addr,
472 uint64_t *value,
473 unsigned size,
474 unsigned access_size_min,
475 unsigned access_size_max,
476 MemTxResult (*access)(MemoryRegion *mr,
477 hwaddr addr,
478 uint64_t *value,
479 unsigned size,
480 unsigned shift,
481 uint64_t mask,
482 MemTxAttrs attrs),
483 MemoryRegion *mr,
484 MemTxAttrs attrs)
486 uint64_t access_mask;
487 unsigned access_size;
488 unsigned i;
489 MemTxResult r = MEMTX_OK;
491 if (!access_size_min) {
492 access_size_min = 1;
494 if (!access_size_max) {
495 access_size_max = 4;
498 /* FIXME: support unaligned access? */
499 access_size = MAX(MIN(size, access_size_max), access_size_min);
500 access_mask = -1ULL >> (64 - access_size * 8);
501 if (memory_region_big_endian(mr)) {
502 for (i = 0; i < size; i += access_size) {
503 r |= access(mr, addr + i, value, access_size,
504 (size - access_size - i) * 8, access_mask, attrs);
506 } else {
507 for (i = 0; i < size; i += access_size) {
508 r |= access(mr, addr + i, value, access_size, i * 8,
509 access_mask, attrs);
512 return r;
515 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
517 AddressSpace *as;
519 while (mr->container) {
520 mr = mr->container;
522 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
523 if (mr == as->root) {
524 return as;
527 return NULL;
530 /* Render a memory region into the global view. Ranges in @view obscure
531 * ranges in @mr.
533 static void render_memory_region(FlatView *view,
534 MemoryRegion *mr,
535 Int128 base,
536 AddrRange clip,
537 bool readonly)
539 MemoryRegion *subregion;
540 unsigned i;
541 hwaddr offset_in_region;
542 Int128 remain;
543 Int128 now;
544 FlatRange fr;
545 AddrRange tmp;
547 if (!mr->enabled) {
548 return;
551 int128_addto(&base, int128_make64(mr->addr));
552 readonly |= mr->readonly;
554 tmp = addrrange_make(base, mr->size);
556 if (!addrrange_intersects(tmp, clip)) {
557 return;
560 clip = addrrange_intersection(tmp, clip);
562 if (mr->alias) {
563 int128_subfrom(&base, int128_make64(mr->alias->addr));
564 int128_subfrom(&base, int128_make64(mr->alias_offset));
565 render_memory_region(view, mr->alias, base, clip, readonly);
566 return;
569 /* Render subregions in priority order. */
570 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
571 render_memory_region(view, subregion, base, clip, readonly);
574 if (!mr->terminates) {
575 return;
578 offset_in_region = int128_get64(int128_sub(clip.start, base));
579 base = clip.start;
580 remain = clip.size;
582 fr.mr = mr;
583 fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
584 fr.romd_mode = mr->romd_mode;
585 fr.readonly = readonly;
587 /* Render the region itself into any gaps left by the current view. */
588 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
589 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
590 continue;
592 if (int128_lt(base, view->ranges[i].addr.start)) {
593 now = int128_min(remain,
594 int128_sub(view->ranges[i].addr.start, base));
595 fr.offset_in_region = offset_in_region;
596 fr.addr = addrrange_make(base, now);
597 flatview_insert(view, i, &fr);
598 ++i;
599 int128_addto(&base, now);
600 offset_in_region += int128_get64(now);
601 int128_subfrom(&remain, now);
603 now = int128_sub(int128_min(int128_add(base, remain),
604 addrrange_end(view->ranges[i].addr)),
605 base);
606 int128_addto(&base, now);
607 offset_in_region += int128_get64(now);
608 int128_subfrom(&remain, now);
610 if (int128_nz(remain)) {
611 fr.offset_in_region = offset_in_region;
612 fr.addr = addrrange_make(base, remain);
613 flatview_insert(view, i, &fr);
617 /* Render a memory topology into a list of disjoint absolute ranges. */
618 static FlatView *generate_memory_topology(MemoryRegion *mr)
620 FlatView *view;
622 view = g_new(FlatView, 1);
623 flatview_init(view);
625 if (mr) {
626 render_memory_region(view, mr, int128_zero(),
627 addrrange_make(int128_zero(), int128_2_64()), false);
629 flatview_simplify(view);
631 return view;
634 static void address_space_add_del_ioeventfds(AddressSpace *as,
635 MemoryRegionIoeventfd *fds_new,
636 unsigned fds_new_nb,
637 MemoryRegionIoeventfd *fds_old,
638 unsigned fds_old_nb)
640 unsigned iold, inew;
641 MemoryRegionIoeventfd *fd;
642 MemoryRegionSection section;
644 /* Generate a symmetric difference of the old and new fd sets, adding
645 * and deleting as necessary.
648 iold = inew = 0;
649 while (iold < fds_old_nb || inew < fds_new_nb) {
650 if (iold < fds_old_nb
651 && (inew == fds_new_nb
652 || memory_region_ioeventfd_before(fds_old[iold],
653 fds_new[inew]))) {
654 fd = &fds_old[iold];
655 section = (MemoryRegionSection) {
656 .address_space = as,
657 .offset_within_address_space = int128_get64(fd->addr.start),
658 .size = fd->addr.size,
660 MEMORY_LISTENER_CALL(eventfd_del, Forward, &section,
661 fd->match_data, fd->data, fd->e);
662 ++iold;
663 } else if (inew < fds_new_nb
664 && (iold == fds_old_nb
665 || memory_region_ioeventfd_before(fds_new[inew],
666 fds_old[iold]))) {
667 fd = &fds_new[inew];
668 section = (MemoryRegionSection) {
669 .address_space = as,
670 .offset_within_address_space = int128_get64(fd->addr.start),
671 .size = fd->addr.size,
673 MEMORY_LISTENER_CALL(eventfd_add, Reverse, &section,
674 fd->match_data, fd->data, fd->e);
675 ++inew;
676 } else {
677 ++iold;
678 ++inew;
683 static FlatView *address_space_get_flatview(AddressSpace *as)
685 FlatView *view;
687 rcu_read_lock();
688 view = atomic_rcu_read(&as->current_map);
689 flatview_ref(view);
690 rcu_read_unlock();
691 return view;
694 static void address_space_update_ioeventfds(AddressSpace *as)
696 FlatView *view;
697 FlatRange *fr;
698 unsigned ioeventfd_nb = 0;
699 MemoryRegionIoeventfd *ioeventfds = NULL;
700 AddrRange tmp;
701 unsigned i;
703 view = address_space_get_flatview(as);
704 FOR_EACH_FLAT_RANGE(fr, view) {
705 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
706 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
707 int128_sub(fr->addr.start,
708 int128_make64(fr->offset_in_region)));
709 if (addrrange_intersects(fr->addr, tmp)) {
710 ++ioeventfd_nb;
711 ioeventfds = g_realloc(ioeventfds,
712 ioeventfd_nb * sizeof(*ioeventfds));
713 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
714 ioeventfds[ioeventfd_nb-1].addr = tmp;
719 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
720 as->ioeventfds, as->ioeventfd_nb);
722 g_free(as->ioeventfds);
723 as->ioeventfds = ioeventfds;
724 as->ioeventfd_nb = ioeventfd_nb;
725 flatview_unref(view);
728 static void address_space_update_topology_pass(AddressSpace *as,
729 const FlatView *old_view,
730 const FlatView *new_view,
731 bool adding)
733 unsigned iold, inew;
734 FlatRange *frold, *frnew;
736 /* Generate a symmetric difference of the old and new memory maps.
737 * Kill ranges in the old map, and instantiate ranges in the new map.
739 iold = inew = 0;
740 while (iold < old_view->nr || inew < new_view->nr) {
741 if (iold < old_view->nr) {
742 frold = &old_view->ranges[iold];
743 } else {
744 frold = NULL;
746 if (inew < new_view->nr) {
747 frnew = &new_view->ranges[inew];
748 } else {
749 frnew = NULL;
752 if (frold
753 && (!frnew
754 || int128_lt(frold->addr.start, frnew->addr.start)
755 || (int128_eq(frold->addr.start, frnew->addr.start)
756 && !flatrange_equal(frold, frnew)))) {
757 /* In old but not in new, or in both but attributes changed. */
759 if (!adding) {
760 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
763 ++iold;
764 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
765 /* In both and unchanged (except logging may have changed) */
767 if (adding) {
768 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
769 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
770 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
771 frold->dirty_log_mask,
772 frnew->dirty_log_mask);
774 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
775 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
776 frold->dirty_log_mask,
777 frnew->dirty_log_mask);
781 ++iold;
782 ++inew;
783 } else {
784 /* In new */
786 if (adding) {
787 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
790 ++inew;
796 static void address_space_update_topology(AddressSpace *as)
798 FlatView *old_view = address_space_get_flatview(as);
799 FlatView *new_view = generate_memory_topology(as->root);
801 address_space_update_topology_pass(as, old_view, new_view, false);
802 address_space_update_topology_pass(as, old_view, new_view, true);
804 /* Writes are protected by the BQL. */
805 atomic_rcu_set(&as->current_map, new_view);
806 call_rcu(old_view, flatview_unref, rcu);
808 /* Note that all the old MemoryRegions are still alive up to this
809 * point. This relieves most MemoryListeners from the need to
810 * ref/unref the MemoryRegions they get---unless they use them
811 * outside the iothread mutex, in which case precise reference
812 * counting is necessary.
814 flatview_unref(old_view);
816 address_space_update_ioeventfds(as);
819 void memory_region_transaction_begin(void)
821 qemu_flush_coalesced_mmio_buffer();
822 ++memory_region_transaction_depth;
825 static void memory_region_clear_pending(void)
827 memory_region_update_pending = false;
828 ioeventfd_update_pending = false;
831 void memory_region_transaction_commit(void)
833 AddressSpace *as;
835 assert(memory_region_transaction_depth);
836 --memory_region_transaction_depth;
837 if (!memory_region_transaction_depth) {
838 if (memory_region_update_pending) {
839 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
841 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
842 address_space_update_topology(as);
845 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
846 } else if (ioeventfd_update_pending) {
847 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
848 address_space_update_ioeventfds(as);
851 memory_region_clear_pending();
855 static void memory_region_destructor_none(MemoryRegion *mr)
859 static void memory_region_destructor_ram(MemoryRegion *mr)
861 qemu_ram_free(mr->ram_addr);
864 static void memory_region_destructor_rom_device(MemoryRegion *mr)
866 qemu_ram_free(mr->ram_addr & TARGET_PAGE_MASK);
869 static bool memory_region_need_escape(char c)
871 return c == '/' || c == '[' || c == '\\' || c == ']';
874 static char *memory_region_escape_name(const char *name)
876 const char *p;
877 char *escaped, *q;
878 uint8_t c;
879 size_t bytes = 0;
881 for (p = name; *p; p++) {
882 bytes += memory_region_need_escape(*p) ? 4 : 1;
884 if (bytes == p - name) {
885 return g_memdup(name, bytes + 1);
888 escaped = g_malloc(bytes + 1);
889 for (p = name, q = escaped; *p; p++) {
890 c = *p;
891 if (unlikely(memory_region_need_escape(c))) {
892 *q++ = '\\';
893 *q++ = 'x';
894 *q++ = "0123456789abcdef"[c >> 4];
895 c = "0123456789abcdef"[c & 15];
897 *q++ = c;
899 *q = 0;
900 return escaped;
903 void memory_region_init(MemoryRegion *mr,
904 Object *owner,
905 const char *name,
906 uint64_t size)
908 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
909 mr->size = int128_make64(size);
910 if (size == UINT64_MAX) {
911 mr->size = int128_2_64();
913 mr->name = g_strdup(name);
914 mr->owner = owner;
916 if (name) {
917 char *escaped_name = memory_region_escape_name(name);
918 char *name_array = g_strdup_printf("%s[*]", escaped_name);
920 if (!owner) {
921 owner = container_get(qdev_get_machine(), "/unattached");
924 object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
925 object_unref(OBJECT(mr));
926 g_free(name_array);
927 g_free(escaped_name);
931 static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
932 void *opaque, Error **errp)
934 MemoryRegion *mr = MEMORY_REGION(obj);
935 uint64_t value = mr->addr;
937 visit_type_uint64(v, name, &value, errp);
940 static void memory_region_get_container(Object *obj, Visitor *v,
941 const char *name, void *opaque,
942 Error **errp)
944 MemoryRegion *mr = MEMORY_REGION(obj);
945 gchar *path = (gchar *)"";
947 if (mr->container) {
948 path = object_get_canonical_path(OBJECT(mr->container));
950 visit_type_str(v, name, &path, errp);
951 if (mr->container) {
952 g_free(path);
956 static Object *memory_region_resolve_container(Object *obj, void *opaque,
957 const char *part)
959 MemoryRegion *mr = MEMORY_REGION(obj);
961 return OBJECT(mr->container);
964 static void memory_region_get_priority(Object *obj, Visitor *v,
965 const char *name, void *opaque,
966 Error **errp)
968 MemoryRegion *mr = MEMORY_REGION(obj);
969 int32_t value = mr->priority;
971 visit_type_int32(v, name, &value, errp);
974 static bool memory_region_get_may_overlap(Object *obj, Error **errp)
976 MemoryRegion *mr = MEMORY_REGION(obj);
978 return mr->may_overlap;
981 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
982 void *opaque, Error **errp)
984 MemoryRegion *mr = MEMORY_REGION(obj);
985 uint64_t value = memory_region_size(mr);
987 visit_type_uint64(v, name, &value, errp);
990 static void memory_region_initfn(Object *obj)
992 MemoryRegion *mr = MEMORY_REGION(obj);
993 ObjectProperty *op;
995 mr->ops = &unassigned_mem_ops;
996 mr->ram_addr = RAM_ADDR_INVALID;
997 mr->enabled = true;
998 mr->romd_mode = true;
999 mr->global_locking = true;
1000 mr->destructor = memory_region_destructor_none;
1001 QTAILQ_INIT(&mr->subregions);
1002 QTAILQ_INIT(&mr->coalesced);
1004 op = object_property_add(OBJECT(mr), "container",
1005 "link<" TYPE_MEMORY_REGION ">",
1006 memory_region_get_container,
1007 NULL, /* memory_region_set_container */
1008 NULL, NULL, &error_abort);
1009 op->resolve = memory_region_resolve_container;
1011 object_property_add(OBJECT(mr), "addr", "uint64",
1012 memory_region_get_addr,
1013 NULL, /* memory_region_set_addr */
1014 NULL, NULL, &error_abort);
1015 object_property_add(OBJECT(mr), "priority", "uint32",
1016 memory_region_get_priority,
1017 NULL, /* memory_region_set_priority */
1018 NULL, NULL, &error_abort);
1019 object_property_add_bool(OBJECT(mr), "may-overlap",
1020 memory_region_get_may_overlap,
1021 NULL, /* memory_region_set_may_overlap */
1022 &error_abort);
1023 object_property_add(OBJECT(mr), "size", "uint64",
1024 memory_region_get_size,
1025 NULL, /* memory_region_set_size, */
1026 NULL, NULL, &error_abort);
1029 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1030 unsigned size)
1032 #ifdef DEBUG_UNASSIGNED
1033 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1034 #endif
1035 if (current_cpu != NULL) {
1036 cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1038 return 0;
1041 static void unassigned_mem_write(void *opaque, hwaddr addr,
1042 uint64_t val, unsigned size)
1044 #ifdef DEBUG_UNASSIGNED
1045 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1046 #endif
1047 if (current_cpu != NULL) {
1048 cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1052 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1053 unsigned size, bool is_write)
1055 return false;
1058 const MemoryRegionOps unassigned_mem_ops = {
1059 .valid.accepts = unassigned_mem_accepts,
1060 .endianness = DEVICE_NATIVE_ENDIAN,
1063 bool memory_region_access_valid(MemoryRegion *mr,
1064 hwaddr addr,
1065 unsigned size,
1066 bool is_write)
1068 int access_size_min, access_size_max;
1069 int access_size, i;
1071 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1072 return false;
1075 if (!mr->ops->valid.accepts) {
1076 return true;
1079 access_size_min = mr->ops->valid.min_access_size;
1080 if (!mr->ops->valid.min_access_size) {
1081 access_size_min = 1;
1084 access_size_max = mr->ops->valid.max_access_size;
1085 if (!mr->ops->valid.max_access_size) {
1086 access_size_max = 4;
1089 access_size = MAX(MIN(size, access_size_max), access_size_min);
1090 for (i = 0; i < size; i += access_size) {
1091 if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
1092 is_write)) {
1093 return false;
1097 return true;
1100 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1101 hwaddr addr,
1102 uint64_t *pval,
1103 unsigned size,
1104 MemTxAttrs attrs)
1106 *pval = 0;
1108 if (mr->ops->read) {
1109 return access_with_adjusted_size(addr, pval, size,
1110 mr->ops->impl.min_access_size,
1111 mr->ops->impl.max_access_size,
1112 memory_region_read_accessor,
1113 mr, attrs);
1114 } else if (mr->ops->read_with_attrs) {
1115 return access_with_adjusted_size(addr, pval, size,
1116 mr->ops->impl.min_access_size,
1117 mr->ops->impl.max_access_size,
1118 memory_region_read_with_attrs_accessor,
1119 mr, attrs);
1120 } else {
1121 return access_with_adjusted_size(addr, pval, size, 1, 4,
1122 memory_region_oldmmio_read_accessor,
1123 mr, attrs);
1127 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1128 hwaddr addr,
1129 uint64_t *pval,
1130 unsigned size,
1131 MemTxAttrs attrs)
1133 MemTxResult r;
1135 if (!memory_region_access_valid(mr, addr, size, false)) {
1136 *pval = unassigned_mem_read(mr, addr, size);
1137 return MEMTX_DECODE_ERROR;
1140 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1141 adjust_endianness(mr, pval, size);
1142 return r;
1145 /* Return true if an eventfd was signalled */
1146 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1147 hwaddr addr,
1148 uint64_t data,
1149 unsigned size,
1150 MemTxAttrs attrs)
1152 MemoryRegionIoeventfd ioeventfd = {
1153 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1154 .data = data,
1156 unsigned i;
1158 for (i = 0; i < mr->ioeventfd_nb; i++) {
1159 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1160 ioeventfd.e = mr->ioeventfds[i].e;
1162 if (memory_region_ioeventfd_equal(ioeventfd, mr->ioeventfds[i])) {
1163 event_notifier_set(ioeventfd.e);
1164 return true;
1168 return false;
1171 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1172 hwaddr addr,
1173 uint64_t data,
1174 unsigned size,
1175 MemTxAttrs attrs)
1177 if (!memory_region_access_valid(mr, addr, size, true)) {
1178 unassigned_mem_write(mr, addr, data, size);
1179 return MEMTX_DECODE_ERROR;
1182 adjust_endianness(mr, &data, size);
1184 if ((!kvm_eventfds_enabled()) &&
1185 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1186 return MEMTX_OK;
1189 if (mr->ops->write) {
1190 return access_with_adjusted_size(addr, &data, size,
1191 mr->ops->impl.min_access_size,
1192 mr->ops->impl.max_access_size,
1193 memory_region_write_accessor, mr,
1194 attrs);
1195 } else if (mr->ops->write_with_attrs) {
1196 return
1197 access_with_adjusted_size(addr, &data, size,
1198 mr->ops->impl.min_access_size,
1199 mr->ops->impl.max_access_size,
1200 memory_region_write_with_attrs_accessor,
1201 mr, attrs);
1202 } else {
1203 return access_with_adjusted_size(addr, &data, size, 1, 4,
1204 memory_region_oldmmio_write_accessor,
1205 mr, attrs);
1209 void memory_region_init_io(MemoryRegion *mr,
1210 Object *owner,
1211 const MemoryRegionOps *ops,
1212 void *opaque,
1213 const char *name,
1214 uint64_t size)
1216 memory_region_init(mr, owner, name, size);
1217 mr->ops = ops ? ops : &unassigned_mem_ops;
1218 mr->opaque = opaque;
1219 mr->terminates = true;
1222 void memory_region_init_ram(MemoryRegion *mr,
1223 Object *owner,
1224 const char *name,
1225 uint64_t size,
1226 Error **errp)
1228 memory_region_init(mr, owner, name, size);
1229 mr->ram = true;
1230 mr->terminates = true;
1231 mr->destructor = memory_region_destructor_ram;
1232 mr->ram_addr = qemu_ram_alloc(size, mr, errp);
1233 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1236 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1237 Object *owner,
1238 const char *name,
1239 uint64_t size,
1240 uint64_t max_size,
1241 void (*resized)(const char*,
1242 uint64_t length,
1243 void *host),
1244 Error **errp)
1246 memory_region_init(mr, owner, name, size);
1247 mr->ram = true;
1248 mr->terminates = true;
1249 mr->destructor = memory_region_destructor_ram;
1250 mr->ram_addr = qemu_ram_alloc_resizeable(size, max_size, resized, mr, errp);
1251 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1254 #ifdef __linux__
1255 void memory_region_init_ram_from_file(MemoryRegion *mr,
1256 struct Object *owner,
1257 const char *name,
1258 uint64_t size,
1259 bool share,
1260 const char *path,
1261 Error **errp)
1263 memory_region_init(mr, owner, name, size);
1264 mr->ram = true;
1265 mr->terminates = true;
1266 mr->destructor = memory_region_destructor_ram;
1267 mr->ram_addr = qemu_ram_alloc_from_file(size, mr, share, path, errp);
1268 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1270 #endif
1272 void memory_region_init_ram_ptr(MemoryRegion *mr,
1273 Object *owner,
1274 const char *name,
1275 uint64_t size,
1276 void *ptr)
1278 memory_region_init(mr, owner, name, size);
1279 mr->ram = true;
1280 mr->terminates = true;
1281 mr->destructor = memory_region_destructor_ram;
1282 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1284 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1285 assert(ptr != NULL);
1286 mr->ram_addr = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1289 void memory_region_set_skip_dump(MemoryRegion *mr)
1291 mr->skip_dump = true;
1294 void memory_region_init_alias(MemoryRegion *mr,
1295 Object *owner,
1296 const char *name,
1297 MemoryRegion *orig,
1298 hwaddr offset,
1299 uint64_t size)
1301 memory_region_init(mr, owner, name, size);
1302 mr->alias = orig;
1303 mr->alias_offset = offset;
1306 void memory_region_init_rom_device(MemoryRegion *mr,
1307 Object *owner,
1308 const MemoryRegionOps *ops,
1309 void *opaque,
1310 const char *name,
1311 uint64_t size,
1312 Error **errp)
1314 memory_region_init(mr, owner, name, size);
1315 mr->ops = ops;
1316 mr->opaque = opaque;
1317 mr->terminates = true;
1318 mr->rom_device = true;
1319 mr->destructor = memory_region_destructor_rom_device;
1320 mr->ram_addr = qemu_ram_alloc(size, mr, errp);
1323 void memory_region_init_iommu(MemoryRegion *mr,
1324 Object *owner,
1325 const MemoryRegionIOMMUOps *ops,
1326 const char *name,
1327 uint64_t size)
1329 memory_region_init(mr, owner, name, size);
1330 mr->iommu_ops = ops,
1331 mr->terminates = true; /* then re-forwards */
1332 notifier_list_init(&mr->iommu_notify);
1335 static void memory_region_finalize(Object *obj)
1337 MemoryRegion *mr = MEMORY_REGION(obj);
1339 assert(!mr->container);
1341 /* We know the region is not visible in any address space (it
1342 * does not have a container and cannot be a root either because
1343 * it has no references, so we can blindly clear mr->enabled.
1344 * memory_region_set_enabled instead could trigger a transaction
1345 * and cause an infinite loop.
1347 mr->enabled = false;
1348 memory_region_transaction_begin();
1349 while (!QTAILQ_EMPTY(&mr->subregions)) {
1350 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1351 memory_region_del_subregion(mr, subregion);
1353 memory_region_transaction_commit();
1355 mr->destructor(mr);
1356 memory_region_clear_coalescing(mr);
1357 g_free((char *)mr->name);
1358 g_free(mr->ioeventfds);
1361 Object *memory_region_owner(MemoryRegion *mr)
1363 Object *obj = OBJECT(mr);
1364 return obj->parent;
1367 void memory_region_ref(MemoryRegion *mr)
1369 /* MMIO callbacks most likely will access data that belongs
1370 * to the owner, hence the need to ref/unref the owner whenever
1371 * the memory region is in use.
1373 * The memory region is a child of its owner. As long as the
1374 * owner doesn't call unparent itself on the memory region,
1375 * ref-ing the owner will also keep the memory region alive.
1376 * Memory regions without an owner are supposed to never go away;
1377 * we do not ref/unref them because it slows down DMA sensibly.
1379 if (mr && mr->owner) {
1380 object_ref(mr->owner);
1384 void memory_region_unref(MemoryRegion *mr)
1386 if (mr && mr->owner) {
1387 object_unref(mr->owner);
1391 uint64_t memory_region_size(MemoryRegion *mr)
1393 if (int128_eq(mr->size, int128_2_64())) {
1394 return UINT64_MAX;
1396 return int128_get64(mr->size);
1399 const char *memory_region_name(const MemoryRegion *mr)
1401 if (!mr->name) {
1402 ((MemoryRegion *)mr)->name =
1403 object_get_canonical_path_component(OBJECT(mr));
1405 return mr->name;
1408 bool memory_region_is_skip_dump(MemoryRegion *mr)
1410 return mr->skip_dump;
1413 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1415 uint8_t mask = mr->dirty_log_mask;
1416 if (global_dirty_log) {
1417 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1419 return mask;
1422 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1424 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1427 void memory_region_register_iommu_notifier(MemoryRegion *mr, Notifier *n)
1429 notifier_list_add(&mr->iommu_notify, n);
1432 void memory_region_iommu_replay(MemoryRegion *mr, Notifier *n,
1433 hwaddr granularity, bool is_write)
1435 hwaddr addr;
1436 IOMMUTLBEntry iotlb;
1438 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1439 iotlb = mr->iommu_ops->translate(mr, addr, is_write);
1440 if (iotlb.perm != IOMMU_NONE) {
1441 n->notify(n, &iotlb);
1444 /* if (2^64 - MR size) < granularity, it's possible to get an
1445 * infinite loop here. This should catch such a wraparound */
1446 if ((addr + granularity) < addr) {
1447 break;
1452 void memory_region_unregister_iommu_notifier(Notifier *n)
1454 notifier_remove(n);
1457 void memory_region_notify_iommu(MemoryRegion *mr,
1458 IOMMUTLBEntry entry)
1460 assert(memory_region_is_iommu(mr));
1461 notifier_list_notify(&mr->iommu_notify, &entry);
1464 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1466 uint8_t mask = 1 << client;
1467 uint8_t old_logging;
1469 assert(client == DIRTY_MEMORY_VGA);
1470 old_logging = mr->vga_logging_count;
1471 mr->vga_logging_count += log ? 1 : -1;
1472 if (!!old_logging == !!mr->vga_logging_count) {
1473 return;
1476 memory_region_transaction_begin();
1477 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1478 memory_region_update_pending |= mr->enabled;
1479 memory_region_transaction_commit();
1482 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1483 hwaddr size, unsigned client)
1485 assert(mr->ram_addr != RAM_ADDR_INVALID);
1486 return cpu_physical_memory_get_dirty(mr->ram_addr + addr, size, client);
1489 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1490 hwaddr size)
1492 assert(mr->ram_addr != RAM_ADDR_INVALID);
1493 cpu_physical_memory_set_dirty_range(mr->ram_addr + addr, size,
1494 memory_region_get_dirty_log_mask(mr));
1497 bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,
1498 hwaddr size, unsigned client)
1500 assert(mr->ram_addr != RAM_ADDR_INVALID);
1501 return cpu_physical_memory_test_and_clear_dirty(mr->ram_addr + addr,
1502 size, client);
1506 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1508 AddressSpace *as;
1509 FlatRange *fr;
1511 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1512 FlatView *view = address_space_get_flatview(as);
1513 FOR_EACH_FLAT_RANGE(fr, view) {
1514 if (fr->mr == mr) {
1515 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1518 flatview_unref(view);
1522 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1524 if (mr->readonly != readonly) {
1525 memory_region_transaction_begin();
1526 mr->readonly = readonly;
1527 memory_region_update_pending |= mr->enabled;
1528 memory_region_transaction_commit();
1532 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
1534 if (mr->romd_mode != romd_mode) {
1535 memory_region_transaction_begin();
1536 mr->romd_mode = romd_mode;
1537 memory_region_update_pending |= mr->enabled;
1538 memory_region_transaction_commit();
1542 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1543 hwaddr size, unsigned client)
1545 assert(mr->ram_addr != RAM_ADDR_INVALID);
1546 cpu_physical_memory_test_and_clear_dirty(mr->ram_addr + addr, size,
1547 client);
1550 int memory_region_get_fd(MemoryRegion *mr)
1552 if (mr->alias) {
1553 return memory_region_get_fd(mr->alias);
1556 assert(mr->ram_addr != RAM_ADDR_INVALID);
1558 return qemu_get_ram_fd(mr->ram_addr & TARGET_PAGE_MASK);
1561 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1563 void *ptr;
1564 uint64_t offset = 0;
1566 rcu_read_lock();
1567 while (mr->alias) {
1568 offset += mr->alias_offset;
1569 mr = mr->alias;
1571 assert(mr->ram_addr != RAM_ADDR_INVALID);
1572 ptr = qemu_get_ram_ptr(mr->ram_addr & TARGET_PAGE_MASK);
1573 rcu_read_unlock();
1575 return ptr + offset;
1578 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
1580 assert(mr->ram_addr != RAM_ADDR_INVALID);
1582 qemu_ram_resize(mr->ram_addr, newsize, errp);
1585 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1587 FlatView *view;
1588 FlatRange *fr;
1589 CoalescedMemoryRange *cmr;
1590 AddrRange tmp;
1591 MemoryRegionSection section;
1593 view = address_space_get_flatview(as);
1594 FOR_EACH_FLAT_RANGE(fr, view) {
1595 if (fr->mr == mr) {
1596 section = (MemoryRegionSection) {
1597 .address_space = as,
1598 .offset_within_address_space = int128_get64(fr->addr.start),
1599 .size = fr->addr.size,
1602 MEMORY_LISTENER_CALL(coalesced_mmio_del, Reverse, &section,
1603 int128_get64(fr->addr.start),
1604 int128_get64(fr->addr.size));
1605 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1606 tmp = addrrange_shift(cmr->addr,
1607 int128_sub(fr->addr.start,
1608 int128_make64(fr->offset_in_region)));
1609 if (!addrrange_intersects(tmp, fr->addr)) {
1610 continue;
1612 tmp = addrrange_intersection(tmp, fr->addr);
1613 MEMORY_LISTENER_CALL(coalesced_mmio_add, Forward, &section,
1614 int128_get64(tmp.start),
1615 int128_get64(tmp.size));
1619 flatview_unref(view);
1622 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1624 AddressSpace *as;
1626 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1627 memory_region_update_coalesced_range_as(mr, as);
1631 void memory_region_set_coalescing(MemoryRegion *mr)
1633 memory_region_clear_coalescing(mr);
1634 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1637 void memory_region_add_coalescing(MemoryRegion *mr,
1638 hwaddr offset,
1639 uint64_t size)
1641 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1643 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1644 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1645 memory_region_update_coalesced_range(mr);
1646 memory_region_set_flush_coalesced(mr);
1649 void memory_region_clear_coalescing(MemoryRegion *mr)
1651 CoalescedMemoryRange *cmr;
1652 bool updated = false;
1654 qemu_flush_coalesced_mmio_buffer();
1655 mr->flush_coalesced_mmio = false;
1657 while (!QTAILQ_EMPTY(&mr->coalesced)) {
1658 cmr = QTAILQ_FIRST(&mr->coalesced);
1659 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1660 g_free(cmr);
1661 updated = true;
1664 if (updated) {
1665 memory_region_update_coalesced_range(mr);
1669 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1671 mr->flush_coalesced_mmio = true;
1674 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1676 qemu_flush_coalesced_mmio_buffer();
1677 if (QTAILQ_EMPTY(&mr->coalesced)) {
1678 mr->flush_coalesced_mmio = false;
1682 void memory_region_set_global_locking(MemoryRegion *mr)
1684 mr->global_locking = true;
1687 void memory_region_clear_global_locking(MemoryRegion *mr)
1689 mr->global_locking = false;
1692 static bool userspace_eventfd_warning;
1694 void memory_region_add_eventfd(MemoryRegion *mr,
1695 hwaddr addr,
1696 unsigned size,
1697 bool match_data,
1698 uint64_t data,
1699 EventNotifier *e)
1701 MemoryRegionIoeventfd mrfd = {
1702 .addr.start = int128_make64(addr),
1703 .addr.size = int128_make64(size),
1704 .match_data = match_data,
1705 .data = data,
1706 .e = e,
1708 unsigned i;
1710 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
1711 userspace_eventfd_warning))) {
1712 userspace_eventfd_warning = true;
1713 error_report("Using eventfd without MMIO binding in KVM. "
1714 "Suboptimal performance expected");
1717 if (size) {
1718 adjust_endianness(mr, &mrfd.data, size);
1720 memory_region_transaction_begin();
1721 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1722 if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
1723 break;
1726 ++mr->ioeventfd_nb;
1727 mr->ioeventfds = g_realloc(mr->ioeventfds,
1728 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
1729 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
1730 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
1731 mr->ioeventfds[i] = mrfd;
1732 ioeventfd_update_pending |= mr->enabled;
1733 memory_region_transaction_commit();
1736 void memory_region_del_eventfd(MemoryRegion *mr,
1737 hwaddr addr,
1738 unsigned size,
1739 bool match_data,
1740 uint64_t data,
1741 EventNotifier *e)
1743 MemoryRegionIoeventfd mrfd = {
1744 .addr.start = int128_make64(addr),
1745 .addr.size = int128_make64(size),
1746 .match_data = match_data,
1747 .data = data,
1748 .e = e,
1750 unsigned i;
1752 if (size) {
1753 adjust_endianness(mr, &mrfd.data, size);
1755 memory_region_transaction_begin();
1756 for (i = 0; i < mr->ioeventfd_nb; ++i) {
1757 if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
1758 break;
1761 assert(i != mr->ioeventfd_nb);
1762 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
1763 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
1764 --mr->ioeventfd_nb;
1765 mr->ioeventfds = g_realloc(mr->ioeventfds,
1766 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
1767 ioeventfd_update_pending |= mr->enabled;
1768 memory_region_transaction_commit();
1771 static void memory_region_update_container_subregions(MemoryRegion *subregion)
1773 hwaddr offset = subregion->addr;
1774 MemoryRegion *mr = subregion->container;
1775 MemoryRegion *other;
1777 memory_region_transaction_begin();
1779 memory_region_ref(subregion);
1780 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1781 if (subregion->may_overlap || other->may_overlap) {
1782 continue;
1784 if (int128_ge(int128_make64(offset),
1785 int128_add(int128_make64(other->addr), other->size))
1786 || int128_le(int128_add(int128_make64(offset), subregion->size),
1787 int128_make64(other->addr))) {
1788 continue;
1790 #if 0
1791 printf("warning: subregion collision %llx/%llx (%s) "
1792 "vs %llx/%llx (%s)\n",
1793 (unsigned long long)offset,
1794 (unsigned long long)int128_get64(subregion->size),
1795 subregion->name,
1796 (unsigned long long)other->addr,
1797 (unsigned long long)int128_get64(other->size),
1798 other->name);
1799 #endif
1801 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1802 if (subregion->priority >= other->priority) {
1803 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
1804 goto done;
1807 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
1808 done:
1809 memory_region_update_pending |= mr->enabled && subregion->enabled;
1810 memory_region_transaction_commit();
1813 static void memory_region_add_subregion_common(MemoryRegion *mr,
1814 hwaddr offset,
1815 MemoryRegion *subregion)
1817 assert(!subregion->container);
1818 subregion->container = mr;
1819 subregion->addr = offset;
1820 memory_region_update_container_subregions(subregion);
1823 void memory_region_add_subregion(MemoryRegion *mr,
1824 hwaddr offset,
1825 MemoryRegion *subregion)
1827 subregion->may_overlap = false;
1828 subregion->priority = 0;
1829 memory_region_add_subregion_common(mr, offset, subregion);
1832 void memory_region_add_subregion_overlap(MemoryRegion *mr,
1833 hwaddr offset,
1834 MemoryRegion *subregion,
1835 int priority)
1837 subregion->may_overlap = true;
1838 subregion->priority = priority;
1839 memory_region_add_subregion_common(mr, offset, subregion);
1842 void memory_region_del_subregion(MemoryRegion *mr,
1843 MemoryRegion *subregion)
1845 memory_region_transaction_begin();
1846 assert(subregion->container == mr);
1847 subregion->container = NULL;
1848 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
1849 memory_region_unref(subregion);
1850 memory_region_update_pending |= mr->enabled && subregion->enabled;
1851 memory_region_transaction_commit();
1854 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
1856 if (enabled == mr->enabled) {
1857 return;
1859 memory_region_transaction_begin();
1860 mr->enabled = enabled;
1861 memory_region_update_pending = true;
1862 memory_region_transaction_commit();
1865 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
1867 Int128 s = int128_make64(size);
1869 if (size == UINT64_MAX) {
1870 s = int128_2_64();
1872 if (int128_eq(s, mr->size)) {
1873 return;
1875 memory_region_transaction_begin();
1876 mr->size = s;
1877 memory_region_update_pending = true;
1878 memory_region_transaction_commit();
1881 static void memory_region_readd_subregion(MemoryRegion *mr)
1883 MemoryRegion *container = mr->container;
1885 if (container) {
1886 memory_region_transaction_begin();
1887 memory_region_ref(mr);
1888 memory_region_del_subregion(container, mr);
1889 mr->container = container;
1890 memory_region_update_container_subregions(mr);
1891 memory_region_unref(mr);
1892 memory_region_transaction_commit();
1896 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
1898 if (addr != mr->addr) {
1899 mr->addr = addr;
1900 memory_region_readd_subregion(mr);
1904 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
1906 assert(mr->alias);
1908 if (offset == mr->alias_offset) {
1909 return;
1912 memory_region_transaction_begin();
1913 mr->alias_offset = offset;
1914 memory_region_update_pending |= mr->enabled;
1915 memory_region_transaction_commit();
1918 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
1920 return mr->align;
1923 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
1925 const AddrRange *addr = addr_;
1926 const FlatRange *fr = fr_;
1928 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
1929 return -1;
1930 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
1931 return 1;
1933 return 0;
1936 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
1938 return bsearch(&addr, view->ranges, view->nr,
1939 sizeof(FlatRange), cmp_flatrange_addr);
1942 bool memory_region_is_mapped(MemoryRegion *mr)
1944 return mr->container ? true : false;
1947 /* Same as memory_region_find, but it does not add a reference to the
1948 * returned region. It must be called from an RCU critical section.
1950 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
1951 hwaddr addr, uint64_t size)
1953 MemoryRegionSection ret = { .mr = NULL };
1954 MemoryRegion *root;
1955 AddressSpace *as;
1956 AddrRange range;
1957 FlatView *view;
1958 FlatRange *fr;
1960 addr += mr->addr;
1961 for (root = mr; root->container; ) {
1962 root = root->container;
1963 addr += root->addr;
1966 as = memory_region_to_address_space(root);
1967 if (!as) {
1968 return ret;
1970 range = addrrange_make(int128_make64(addr), int128_make64(size));
1972 view = atomic_rcu_read(&as->current_map);
1973 fr = flatview_lookup(view, range);
1974 if (!fr) {
1975 return ret;
1978 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
1979 --fr;
1982 ret.mr = fr->mr;
1983 ret.address_space = as;
1984 range = addrrange_intersection(range, fr->addr);
1985 ret.offset_within_region = fr->offset_in_region;
1986 ret.offset_within_region += int128_get64(int128_sub(range.start,
1987 fr->addr.start));
1988 ret.size = range.size;
1989 ret.offset_within_address_space = int128_get64(range.start);
1990 ret.readonly = fr->readonly;
1991 return ret;
1994 MemoryRegionSection memory_region_find(MemoryRegion *mr,
1995 hwaddr addr, uint64_t size)
1997 MemoryRegionSection ret;
1998 rcu_read_lock();
1999 ret = memory_region_find_rcu(mr, addr, size);
2000 if (ret.mr) {
2001 memory_region_ref(ret.mr);
2003 rcu_read_unlock();
2004 return ret;
2007 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2009 MemoryRegion *mr;
2011 rcu_read_lock();
2012 mr = memory_region_find_rcu(container, addr, 1).mr;
2013 rcu_read_unlock();
2014 return mr && mr != container;
2017 void address_space_sync_dirty_bitmap(AddressSpace *as)
2019 FlatView *view;
2020 FlatRange *fr;
2022 view = address_space_get_flatview(as);
2023 FOR_EACH_FLAT_RANGE(fr, view) {
2024 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
2026 flatview_unref(view);
2029 void memory_global_dirty_log_start(void)
2031 global_dirty_log = true;
2033 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2035 /* Refresh DIRTY_LOG_MIGRATION bit. */
2036 memory_region_transaction_begin();
2037 memory_region_update_pending = true;
2038 memory_region_transaction_commit();
2041 void memory_global_dirty_log_stop(void)
2043 global_dirty_log = false;
2045 /* Refresh DIRTY_LOG_MIGRATION bit. */
2046 memory_region_transaction_begin();
2047 memory_region_update_pending = true;
2048 memory_region_transaction_commit();
2050 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2053 static void listener_add_address_space(MemoryListener *listener,
2054 AddressSpace *as)
2056 FlatView *view;
2057 FlatRange *fr;
2059 if (listener->address_space_filter
2060 && listener->address_space_filter != as) {
2061 return;
2064 if (listener->begin) {
2065 listener->begin(listener);
2067 if (global_dirty_log) {
2068 if (listener->log_global_start) {
2069 listener->log_global_start(listener);
2073 view = address_space_get_flatview(as);
2074 FOR_EACH_FLAT_RANGE(fr, view) {
2075 MemoryRegionSection section = {
2076 .mr = fr->mr,
2077 .address_space = as,
2078 .offset_within_region = fr->offset_in_region,
2079 .size = fr->addr.size,
2080 .offset_within_address_space = int128_get64(fr->addr.start),
2081 .readonly = fr->readonly,
2083 if (fr->dirty_log_mask && listener->log_start) {
2084 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2086 if (listener->region_add) {
2087 listener->region_add(listener, &section);
2090 if (listener->commit) {
2091 listener->commit(listener);
2093 flatview_unref(view);
2096 void memory_listener_register(MemoryListener *listener, AddressSpace *filter)
2098 MemoryListener *other = NULL;
2099 AddressSpace *as;
2101 listener->address_space_filter = filter;
2102 if (QTAILQ_EMPTY(&memory_listeners)
2103 || listener->priority >= QTAILQ_LAST(&memory_listeners,
2104 memory_listeners)->priority) {
2105 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2106 } else {
2107 QTAILQ_FOREACH(other, &memory_listeners, link) {
2108 if (listener->priority < other->priority) {
2109 break;
2112 QTAILQ_INSERT_BEFORE(other, listener, link);
2115 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2116 listener_add_address_space(listener, as);
2120 void memory_listener_unregister(MemoryListener *listener)
2122 QTAILQ_REMOVE(&memory_listeners, listener, link);
2125 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2127 memory_region_ref(root);
2128 memory_region_transaction_begin();
2129 as->ref_count = 1;
2130 as->root = root;
2131 as->malloced = false;
2132 as->current_map = g_new(FlatView, 1);
2133 flatview_init(as->current_map);
2134 as->ioeventfd_nb = 0;
2135 as->ioeventfds = NULL;
2136 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2137 as->name = g_strdup(name ? name : "anonymous");
2138 address_space_init_dispatch(as);
2139 memory_region_update_pending |= root->enabled;
2140 memory_region_transaction_commit();
2143 static void do_address_space_destroy(AddressSpace *as)
2145 MemoryListener *listener;
2146 bool do_free = as->malloced;
2148 address_space_destroy_dispatch(as);
2150 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2151 assert(listener->address_space_filter != as);
2154 flatview_unref(as->current_map);
2155 g_free(as->name);
2156 g_free(as->ioeventfds);
2157 memory_region_unref(as->root);
2158 if (do_free) {
2159 g_free(as);
2163 AddressSpace *address_space_init_shareable(MemoryRegion *root, const char *name)
2165 AddressSpace *as;
2167 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2168 if (root == as->root && as->malloced) {
2169 as->ref_count++;
2170 return as;
2174 as = g_malloc0(sizeof *as);
2175 address_space_init(as, root, name);
2176 as->malloced = true;
2177 return as;
2180 void address_space_destroy(AddressSpace *as)
2182 MemoryRegion *root = as->root;
2184 as->ref_count--;
2185 if (as->ref_count) {
2186 return;
2188 /* Flush out anything from MemoryListeners listening in on this */
2189 memory_region_transaction_begin();
2190 as->root = NULL;
2191 memory_region_transaction_commit();
2192 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2193 address_space_unregister(as);
2195 /* At this point, as->dispatch and as->current_map are dummy
2196 * entries that the guest should never use. Wait for the old
2197 * values to expire before freeing the data.
2199 as->root = root;
2200 call_rcu(as, do_address_space_destroy, rcu);
2203 typedef struct MemoryRegionList MemoryRegionList;
2205 struct MemoryRegionList {
2206 const MemoryRegion *mr;
2207 QTAILQ_ENTRY(MemoryRegionList) queue;
2210 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
2212 static void mtree_print_mr(fprintf_function mon_printf, void *f,
2213 const MemoryRegion *mr, unsigned int level,
2214 hwaddr base,
2215 MemoryRegionListHead *alias_print_queue)
2217 MemoryRegionList *new_ml, *ml, *next_ml;
2218 MemoryRegionListHead submr_print_queue;
2219 const MemoryRegion *submr;
2220 unsigned int i;
2222 if (!mr) {
2223 return;
2226 for (i = 0; i < level; i++) {
2227 mon_printf(f, " ");
2230 if (mr->alias) {
2231 MemoryRegionList *ml;
2232 bool found = false;
2234 /* check if the alias is already in the queue */
2235 QTAILQ_FOREACH(ml, alias_print_queue, queue) {
2236 if (ml->mr == mr->alias) {
2237 found = true;
2241 if (!found) {
2242 ml = g_new(MemoryRegionList, 1);
2243 ml->mr = mr->alias;
2244 QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
2246 mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
2247 " (prio %d, %c%c): alias %s @%s " TARGET_FMT_plx
2248 "-" TARGET_FMT_plx "%s\n",
2249 base + mr->addr,
2250 base + mr->addr
2251 + (int128_nz(mr->size) ?
2252 (hwaddr)int128_get64(int128_sub(mr->size,
2253 int128_one())) : 0),
2254 mr->priority,
2255 mr->romd_mode ? 'R' : '-',
2256 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2257 : '-',
2258 memory_region_name(mr),
2259 memory_region_name(mr->alias),
2260 mr->alias_offset,
2261 mr->alias_offset
2262 + (int128_nz(mr->size) ?
2263 (hwaddr)int128_get64(int128_sub(mr->size,
2264 int128_one())) : 0),
2265 mr->enabled ? "" : " [disabled]");
2266 } else {
2267 mon_printf(f,
2268 TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %c%c): %s%s\n",
2269 base + mr->addr,
2270 base + mr->addr
2271 + (int128_nz(mr->size) ?
2272 (hwaddr)int128_get64(int128_sub(mr->size,
2273 int128_one())) : 0),
2274 mr->priority,
2275 mr->romd_mode ? 'R' : '-',
2276 !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2277 : '-',
2278 memory_region_name(mr),
2279 mr->enabled ? "" : " [disabled]");
2282 QTAILQ_INIT(&submr_print_queue);
2284 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2285 new_ml = g_new(MemoryRegionList, 1);
2286 new_ml->mr = submr;
2287 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2288 if (new_ml->mr->addr < ml->mr->addr ||
2289 (new_ml->mr->addr == ml->mr->addr &&
2290 new_ml->mr->priority > ml->mr->priority)) {
2291 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
2292 new_ml = NULL;
2293 break;
2296 if (new_ml) {
2297 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
2301 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2302 mtree_print_mr(mon_printf, f, ml->mr, level + 1, base + mr->addr,
2303 alias_print_queue);
2306 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
2307 g_free(ml);
2311 void mtree_info(fprintf_function mon_printf, void *f)
2313 MemoryRegionListHead ml_head;
2314 MemoryRegionList *ml, *ml2;
2315 AddressSpace *as;
2317 QTAILQ_INIT(&ml_head);
2319 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2320 mon_printf(f, "address-space: %s\n", as->name);
2321 mtree_print_mr(mon_printf, f, as->root, 1, 0, &ml_head);
2322 mon_printf(f, "\n");
2325 /* print aliased regions */
2326 QTAILQ_FOREACH(ml, &ml_head, queue) {
2327 mon_printf(f, "memory-region: %s\n", memory_region_name(ml->mr));
2328 mtree_print_mr(mon_printf, f, ml->mr, 1, 0, &ml_head);
2329 mon_printf(f, "\n");
2332 QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
2333 g_free(ml);
2337 static const TypeInfo memory_region_info = {
2338 .parent = TYPE_OBJECT,
2339 .name = TYPE_MEMORY_REGION,
2340 .instance_size = sizeof(MemoryRegion),
2341 .instance_init = memory_region_initfn,
2342 .instance_finalize = memory_region_finalize,
2345 static void memory_register_types(void)
2347 type_register_static(&memory_region_info);
2350 type_init(memory_register_types)