megasas: do not read iovec count more than once from frame
[qemu/ar7.git] / memory.c
blobe08fa0ae6c8a302a418214d067f6c918f1056337
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 "qapi/error.h"
18 #include "qemu-common.h"
19 #include "cpu.h"
20 #include "exec/memory.h"
21 #include "exec/address-spaces.h"
22 #include "exec/ioport.h"
23 #include "qapi/visitor.h"
24 #include "qemu/bitops.h"
25 #include "qemu/error-report.h"
26 #include "qom/object.h"
27 #include "trace-root.h"
29 #include "exec/memory-internal.h"
30 #include "exec/ram_addr.h"
31 #include "sysemu/kvm.h"
32 #include "sysemu/sysemu.h"
34 //#define DEBUG_UNASSIGNED
36 static unsigned memory_region_transaction_depth;
37 static bool memory_region_update_pending;
38 static bool ioeventfd_update_pending;
39 static bool global_dirty_log = false;
41 static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
42 = QTAILQ_HEAD_INITIALIZER(memory_listeners);
44 static QTAILQ_HEAD(, AddressSpace) address_spaces
45 = QTAILQ_HEAD_INITIALIZER(address_spaces);
47 typedef struct AddrRange AddrRange;
50 * Note that signed integers are needed for negative offsetting in aliases
51 * (large MemoryRegion::alias_offset).
53 struct AddrRange {
54 Int128 start;
55 Int128 size;
58 static AddrRange addrrange_make(Int128 start, Int128 size)
60 return (AddrRange) { start, size };
63 static bool addrrange_equal(AddrRange r1, AddrRange r2)
65 return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
68 static Int128 addrrange_end(AddrRange r)
70 return int128_add(r.start, r.size);
73 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
75 int128_addto(&range.start, delta);
76 return range;
79 static bool addrrange_contains(AddrRange range, Int128 addr)
81 return int128_ge(addr, range.start)
82 && int128_lt(addr, addrrange_end(range));
85 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
87 return addrrange_contains(r1, r2.start)
88 || addrrange_contains(r2, r1.start);
91 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
93 Int128 start = int128_max(r1.start, r2.start);
94 Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
95 return addrrange_make(start, int128_sub(end, start));
98 enum ListenerDirection { Forward, Reverse };
100 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...) \
101 do { \
102 MemoryListener *_listener; \
104 switch (_direction) { \
105 case Forward: \
106 QTAILQ_FOREACH(_listener, &memory_listeners, link) { \
107 if (_listener->_callback) { \
108 _listener->_callback(_listener, ##_args); \
111 break; \
112 case Reverse: \
113 QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, \
114 memory_listeners, link) { \
115 if (_listener->_callback) { \
116 _listener->_callback(_listener, ##_args); \
119 break; \
120 default: \
121 abort(); \
123 } while (0)
125 #define MEMORY_LISTENER_CALL(_as, _callback, _direction, _section, _args...) \
126 do { \
127 MemoryListener *_listener; \
128 struct memory_listeners_as *list = &(_as)->listeners; \
130 switch (_direction) { \
131 case Forward: \
132 QTAILQ_FOREACH(_listener, list, link_as) { \
133 if (_listener->_callback) { \
134 _listener->_callback(_listener, _section, ##_args); \
137 break; \
138 case Reverse: \
139 QTAILQ_FOREACH_REVERSE(_listener, list, memory_listeners_as, \
140 link_as) { \
141 if (_listener->_callback) { \
142 _listener->_callback(_listener, _section, ##_args); \
145 break; \
146 default: \
147 abort(); \
149 } while (0)
151 /* No need to ref/unref .mr, the FlatRange keeps it alive. */
152 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...) \
153 do { \
154 MemoryRegionSection mrs = section_from_flat_range(fr, as); \
155 MEMORY_LISTENER_CALL(as, callback, dir, &mrs, ##_args); \
156 } while(0)
158 struct CoalescedMemoryRange {
159 AddrRange addr;
160 QTAILQ_ENTRY(CoalescedMemoryRange) link;
163 struct MemoryRegionIoeventfd {
164 AddrRange addr;
165 bool match_data;
166 uint64_t data;
167 EventNotifier *e;
170 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
171 MemoryRegionIoeventfd b)
173 if (int128_lt(a.addr.start, b.addr.start)) {
174 return true;
175 } else if (int128_gt(a.addr.start, b.addr.start)) {
176 return false;
177 } else if (int128_lt(a.addr.size, b.addr.size)) {
178 return true;
179 } else if (int128_gt(a.addr.size, b.addr.size)) {
180 return false;
181 } else if (a.match_data < b.match_data) {
182 return true;
183 } else if (a.match_data > b.match_data) {
184 return false;
185 } else if (a.match_data) {
186 if (a.data < b.data) {
187 return true;
188 } else if (a.data > b.data) {
189 return false;
192 if (a.e < b.e) {
193 return true;
194 } else if (a.e > b.e) {
195 return false;
197 return false;
200 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
201 MemoryRegionIoeventfd b)
203 return !memory_region_ioeventfd_before(a, b)
204 && !memory_region_ioeventfd_before(b, a);
207 typedef struct FlatRange FlatRange;
208 typedef struct FlatView FlatView;
210 /* Range of memory in the global map. Addresses are absolute. */
211 struct FlatRange {
212 MemoryRegion *mr;
213 hwaddr offset_in_region;
214 AddrRange addr;
215 uint8_t dirty_log_mask;
216 bool romd_mode;
217 bool readonly;
220 /* Flattened global view of current active memory hierarchy. Kept in sorted
221 * order.
223 struct FlatView {
224 struct rcu_head rcu;
225 unsigned ref;
226 FlatRange *ranges;
227 unsigned nr;
228 unsigned nr_allocated;
231 typedef struct AddressSpaceOps AddressSpaceOps;
233 #define FOR_EACH_FLAT_RANGE(var, view) \
234 for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
236 static inline MemoryRegionSection
237 section_from_flat_range(FlatRange *fr, AddressSpace *as)
239 return (MemoryRegionSection) {
240 .mr = fr->mr,
241 .address_space = as,
242 .offset_within_region = fr->offset_in_region,
243 .size = fr->addr.size,
244 .offset_within_address_space = int128_get64(fr->addr.start),
245 .readonly = fr->readonly,
249 static bool flatrange_equal(FlatRange *a, FlatRange *b)
251 return a->mr == b->mr
252 && addrrange_equal(a->addr, b->addr)
253 && a->offset_in_region == b->offset_in_region
254 && a->romd_mode == b->romd_mode
255 && a->readonly == b->readonly;
258 static void flatview_init(FlatView *view)
260 view->ref = 1;
261 view->ranges = NULL;
262 view->nr = 0;
263 view->nr_allocated = 0;
266 /* Insert a range into a given position. Caller is responsible for maintaining
267 * sorting order.
269 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
271 if (view->nr == view->nr_allocated) {
272 view->nr_allocated = MAX(2 * view->nr, 10);
273 view->ranges = g_realloc(view->ranges,
274 view->nr_allocated * sizeof(*view->ranges));
276 memmove(view->ranges + pos + 1, view->ranges + pos,
277 (view->nr - pos) * sizeof(FlatRange));
278 view->ranges[pos] = *range;
279 memory_region_ref(range->mr);
280 ++view->nr;
283 static void flatview_destroy(FlatView *view)
285 int i;
287 for (i = 0; i < view->nr; i++) {
288 memory_region_unref(view->ranges[i].mr);
290 g_free(view->ranges);
291 g_free(view);
294 static void flatview_ref(FlatView *view)
296 atomic_inc(&view->ref);
299 static void flatview_unref(FlatView *view)
301 if (atomic_fetch_dec(&view->ref) == 1) {
302 flatview_destroy(view);
306 static bool can_merge(FlatRange *r1, FlatRange *r2)
308 return int128_eq(addrrange_end(r1->addr), r2->addr.start)
309 && r1->mr == r2->mr
310 && int128_eq(int128_add(int128_make64(r1->offset_in_region),
311 r1->addr.size),
312 int128_make64(r2->offset_in_region))
313 && r1->dirty_log_mask == r2->dirty_log_mask
314 && r1->romd_mode == r2->romd_mode
315 && r1->readonly == r2->readonly;
318 /* Attempt to simplify a view by merging adjacent ranges */
319 static void flatview_simplify(FlatView *view)
321 unsigned i, j;
323 i = 0;
324 while (i < view->nr) {
325 j = i + 1;
326 while (j < view->nr
327 && can_merge(&view->ranges[j-1], &view->ranges[j])) {
328 int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
329 ++j;
331 ++i;
332 memmove(&view->ranges[i], &view->ranges[j],
333 (view->nr - j) * sizeof(view->ranges[j]));
334 view->nr -= j - i;
338 static bool memory_region_big_endian(MemoryRegion *mr)
340 #ifdef TARGET_WORDS_BIGENDIAN
341 return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
342 #else
343 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
344 #endif
347 static bool memory_region_wrong_endianness(MemoryRegion *mr)
349 #ifdef TARGET_WORDS_BIGENDIAN
350 return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
351 #else
352 return mr->ops->endianness == DEVICE_BIG_ENDIAN;
353 #endif
356 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
358 if (memory_region_wrong_endianness(mr)) {
359 switch (size) {
360 case 1:
361 break;
362 case 2:
363 *data = bswap16(*data);
364 break;
365 case 4:
366 *data = bswap32(*data);
367 break;
368 case 8:
369 *data = bswap64(*data);
370 break;
371 default:
372 abort();
377 static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
379 MemoryRegion *root;
380 hwaddr abs_addr = offset;
382 abs_addr += mr->addr;
383 for (root = mr; root->container; ) {
384 root = root->container;
385 abs_addr += root->addr;
388 return abs_addr;
391 static int get_cpu_index(void)
393 if (current_cpu) {
394 return current_cpu->cpu_index;
396 return -1;
399 static MemTxResult memory_region_oldmmio_read_accessor(MemoryRegion *mr,
400 hwaddr addr,
401 uint64_t *value,
402 unsigned size,
403 unsigned shift,
404 uint64_t mask,
405 MemTxAttrs attrs)
407 uint64_t tmp;
409 tmp = mr->ops->old_mmio.read[ctz32(size)](mr->opaque, addr);
410 if (mr->subpage) {
411 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
412 } else if (mr == &io_mem_notdirty) {
413 /* Accesses to code which has previously been translated into a TB show
414 * up in the MMIO path, as accesses to the io_mem_notdirty
415 * MemoryRegion. */
416 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
417 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
418 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
419 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
421 *value |= (tmp & mask) << shift;
422 return MEMTX_OK;
425 static MemTxResult memory_region_read_accessor(MemoryRegion *mr,
426 hwaddr addr,
427 uint64_t *value,
428 unsigned size,
429 unsigned shift,
430 uint64_t mask,
431 MemTxAttrs attrs)
433 uint64_t tmp;
435 tmp = mr->ops->read(mr->opaque, addr, size);
436 if (mr->subpage) {
437 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
438 } else if (mr == &io_mem_notdirty) {
439 /* Accesses to code which has previously been translated into a TB show
440 * up in the MMIO path, as accesses to the io_mem_notdirty
441 * MemoryRegion. */
442 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
443 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
444 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
445 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
447 *value |= (tmp & mask) << shift;
448 return MEMTX_OK;
451 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
452 hwaddr addr,
453 uint64_t *value,
454 unsigned size,
455 unsigned shift,
456 uint64_t mask,
457 MemTxAttrs attrs)
459 uint64_t tmp = 0;
460 MemTxResult r;
462 r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
463 if (mr->subpage) {
464 trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
465 } else if (mr == &io_mem_notdirty) {
466 /* Accesses to code which has previously been translated into a TB show
467 * up in the MMIO path, as accesses to the io_mem_notdirty
468 * MemoryRegion. */
469 trace_memory_region_tb_read(get_cpu_index(), addr, tmp, size);
470 } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
471 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
472 trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size);
474 *value |= (tmp & mask) << shift;
475 return r;
478 static MemTxResult memory_region_oldmmio_write_accessor(MemoryRegion *mr,
479 hwaddr addr,
480 uint64_t *value,
481 unsigned size,
482 unsigned shift,
483 uint64_t mask,
484 MemTxAttrs attrs)
486 uint64_t tmp;
488 tmp = (*value >> shift) & mask;
489 if (mr->subpage) {
490 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
491 } else if (mr == &io_mem_notdirty) {
492 /* Accesses to code which has previously been translated into a TB show
493 * up in the MMIO path, as accesses to the io_mem_notdirty
494 * MemoryRegion. */
495 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
496 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
497 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
498 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
500 mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);
501 return MEMTX_OK;
504 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
505 hwaddr addr,
506 uint64_t *value,
507 unsigned size,
508 unsigned shift,
509 uint64_t mask,
510 MemTxAttrs attrs)
512 uint64_t tmp;
514 tmp = (*value >> shift) & mask;
515 if (mr->subpage) {
516 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
517 } else if (mr == &io_mem_notdirty) {
518 /* Accesses to code which has previously been translated into a TB show
519 * up in the MMIO path, as accesses to the io_mem_notdirty
520 * MemoryRegion. */
521 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
522 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
523 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
524 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
526 mr->ops->write(mr->opaque, addr, tmp, size);
527 return MEMTX_OK;
530 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
531 hwaddr addr,
532 uint64_t *value,
533 unsigned size,
534 unsigned shift,
535 uint64_t mask,
536 MemTxAttrs attrs)
538 uint64_t tmp;
540 tmp = (*value >> shift) & mask;
541 if (mr->subpage) {
542 trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
543 } else if (mr == &io_mem_notdirty) {
544 /* Accesses to code which has previously been translated into a TB show
545 * up in the MMIO path, as accesses to the io_mem_notdirty
546 * MemoryRegion. */
547 trace_memory_region_tb_write(get_cpu_index(), addr, tmp, size);
548 } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
549 hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
550 trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);
552 return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
555 static MemTxResult access_with_adjusted_size(hwaddr addr,
556 uint64_t *value,
557 unsigned size,
558 unsigned access_size_min,
559 unsigned access_size_max,
560 MemTxResult (*access)(MemoryRegion *mr,
561 hwaddr addr,
562 uint64_t *value,
563 unsigned size,
564 unsigned shift,
565 uint64_t mask,
566 MemTxAttrs attrs),
567 MemoryRegion *mr,
568 MemTxAttrs attrs)
570 uint64_t access_mask;
571 unsigned access_size;
572 unsigned i;
573 MemTxResult r = MEMTX_OK;
575 if (!access_size_min) {
576 access_size_min = 1;
578 if (!access_size_max) {
579 access_size_max = 4;
582 /* FIXME: support unaligned access? */
583 access_size = MAX(MIN(size, access_size_max), access_size_min);
584 access_mask = -1ULL >> (64 - access_size * 8);
585 if (memory_region_big_endian(mr)) {
586 for (i = 0; i < size; i += access_size) {
587 r |= access(mr, addr + i, value, access_size,
588 (size - access_size - i) * 8, access_mask, attrs);
590 } else {
591 for (i = 0; i < size; i += access_size) {
592 r |= access(mr, addr + i, value, access_size, i * 8,
593 access_mask, attrs);
596 return r;
599 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
601 AddressSpace *as;
603 while (mr->container) {
604 mr = mr->container;
606 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
607 if (mr == as->root) {
608 return as;
611 return NULL;
614 /* Render a memory region into the global view. Ranges in @view obscure
615 * ranges in @mr.
617 static void render_memory_region(FlatView *view,
618 MemoryRegion *mr,
619 Int128 base,
620 AddrRange clip,
621 bool readonly)
623 MemoryRegion *subregion;
624 unsigned i;
625 hwaddr offset_in_region;
626 Int128 remain;
627 Int128 now;
628 FlatRange fr;
629 AddrRange tmp;
631 if (!mr->enabled) {
632 return;
635 int128_addto(&base, int128_make64(mr->addr));
636 readonly |= mr->readonly;
638 tmp = addrrange_make(base, mr->size);
640 if (!addrrange_intersects(tmp, clip)) {
641 return;
644 clip = addrrange_intersection(tmp, clip);
646 if (mr->alias) {
647 int128_subfrom(&base, int128_make64(mr->alias->addr));
648 int128_subfrom(&base, int128_make64(mr->alias_offset));
649 render_memory_region(view, mr->alias, base, clip, readonly);
650 return;
653 /* Render subregions in priority order. */
654 QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
655 render_memory_region(view, subregion, base, clip, readonly);
658 if (!mr->terminates) {
659 return;
662 offset_in_region = int128_get64(int128_sub(clip.start, base));
663 base = clip.start;
664 remain = clip.size;
666 fr.mr = mr;
667 fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
668 fr.romd_mode = mr->romd_mode;
669 fr.readonly = readonly;
671 /* Render the region itself into any gaps left by the current view. */
672 for (i = 0; i < view->nr && int128_nz(remain); ++i) {
673 if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
674 continue;
676 if (int128_lt(base, view->ranges[i].addr.start)) {
677 now = int128_min(remain,
678 int128_sub(view->ranges[i].addr.start, base));
679 fr.offset_in_region = offset_in_region;
680 fr.addr = addrrange_make(base, now);
681 flatview_insert(view, i, &fr);
682 ++i;
683 int128_addto(&base, now);
684 offset_in_region += int128_get64(now);
685 int128_subfrom(&remain, now);
687 now = int128_sub(int128_min(int128_add(base, remain),
688 addrrange_end(view->ranges[i].addr)),
689 base);
690 int128_addto(&base, now);
691 offset_in_region += int128_get64(now);
692 int128_subfrom(&remain, now);
694 if (int128_nz(remain)) {
695 fr.offset_in_region = offset_in_region;
696 fr.addr = addrrange_make(base, remain);
697 flatview_insert(view, i, &fr);
701 /* Render a memory topology into a list of disjoint absolute ranges. */
702 static FlatView *generate_memory_topology(MemoryRegion *mr)
704 FlatView *view;
706 view = g_new(FlatView, 1);
707 flatview_init(view);
709 if (mr) {
710 render_memory_region(view, mr, int128_zero(),
711 addrrange_make(int128_zero(), int128_2_64()), false);
713 flatview_simplify(view);
715 return view;
718 static void address_space_add_del_ioeventfds(AddressSpace *as,
719 MemoryRegionIoeventfd *fds_new,
720 unsigned fds_new_nb,
721 MemoryRegionIoeventfd *fds_old,
722 unsigned fds_old_nb)
724 unsigned iold, inew;
725 MemoryRegionIoeventfd *fd;
726 MemoryRegionSection section;
728 /* Generate a symmetric difference of the old and new fd sets, adding
729 * and deleting as necessary.
732 iold = inew = 0;
733 while (iold < fds_old_nb || inew < fds_new_nb) {
734 if (iold < fds_old_nb
735 && (inew == fds_new_nb
736 || memory_region_ioeventfd_before(fds_old[iold],
737 fds_new[inew]))) {
738 fd = &fds_old[iold];
739 section = (MemoryRegionSection) {
740 .address_space = as,
741 .offset_within_address_space = int128_get64(fd->addr.start),
742 .size = fd->addr.size,
744 MEMORY_LISTENER_CALL(as, eventfd_del, Forward, &section,
745 fd->match_data, fd->data, fd->e);
746 ++iold;
747 } else if (inew < fds_new_nb
748 && (iold == fds_old_nb
749 || memory_region_ioeventfd_before(fds_new[inew],
750 fds_old[iold]))) {
751 fd = &fds_new[inew];
752 section = (MemoryRegionSection) {
753 .address_space = as,
754 .offset_within_address_space = int128_get64(fd->addr.start),
755 .size = fd->addr.size,
757 MEMORY_LISTENER_CALL(as, eventfd_add, Reverse, &section,
758 fd->match_data, fd->data, fd->e);
759 ++inew;
760 } else {
761 ++iold;
762 ++inew;
767 static FlatView *address_space_get_flatview(AddressSpace *as)
769 FlatView *view;
771 rcu_read_lock();
772 view = atomic_rcu_read(&as->current_map);
773 flatview_ref(view);
774 rcu_read_unlock();
775 return view;
778 static void address_space_update_ioeventfds(AddressSpace *as)
780 FlatView *view;
781 FlatRange *fr;
782 unsigned ioeventfd_nb = 0;
783 MemoryRegionIoeventfd *ioeventfds = NULL;
784 AddrRange tmp;
785 unsigned i;
787 view = address_space_get_flatview(as);
788 FOR_EACH_FLAT_RANGE(fr, view) {
789 for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
790 tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
791 int128_sub(fr->addr.start,
792 int128_make64(fr->offset_in_region)));
793 if (addrrange_intersects(fr->addr, tmp)) {
794 ++ioeventfd_nb;
795 ioeventfds = g_realloc(ioeventfds,
796 ioeventfd_nb * sizeof(*ioeventfds));
797 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
798 ioeventfds[ioeventfd_nb-1].addr = tmp;
803 address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
804 as->ioeventfds, as->ioeventfd_nb);
806 g_free(as->ioeventfds);
807 as->ioeventfds = ioeventfds;
808 as->ioeventfd_nb = ioeventfd_nb;
809 flatview_unref(view);
812 static void address_space_update_topology_pass(AddressSpace *as,
813 const FlatView *old_view,
814 const FlatView *new_view,
815 bool adding)
817 unsigned iold, inew;
818 FlatRange *frold, *frnew;
820 /* Generate a symmetric difference of the old and new memory maps.
821 * Kill ranges in the old map, and instantiate ranges in the new map.
823 iold = inew = 0;
824 while (iold < old_view->nr || inew < new_view->nr) {
825 if (iold < old_view->nr) {
826 frold = &old_view->ranges[iold];
827 } else {
828 frold = NULL;
830 if (inew < new_view->nr) {
831 frnew = &new_view->ranges[inew];
832 } else {
833 frnew = NULL;
836 if (frold
837 && (!frnew
838 || int128_lt(frold->addr.start, frnew->addr.start)
839 || (int128_eq(frold->addr.start, frnew->addr.start)
840 && !flatrange_equal(frold, frnew)))) {
841 /* In old but not in new, or in both but attributes changed. */
843 if (!adding) {
844 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
847 ++iold;
848 } else if (frold && frnew && flatrange_equal(frold, frnew)) {
849 /* In both and unchanged (except logging may have changed) */
851 if (adding) {
852 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
853 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
854 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
855 frold->dirty_log_mask,
856 frnew->dirty_log_mask);
858 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
859 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
860 frold->dirty_log_mask,
861 frnew->dirty_log_mask);
865 ++iold;
866 ++inew;
867 } else {
868 /* In new */
870 if (adding) {
871 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
874 ++inew;
880 static void address_space_update_topology(AddressSpace *as)
882 FlatView *old_view = address_space_get_flatview(as);
883 FlatView *new_view = generate_memory_topology(as->root);
885 address_space_update_topology_pass(as, old_view, new_view, false);
886 address_space_update_topology_pass(as, old_view, new_view, true);
888 /* Writes are protected by the BQL. */
889 atomic_rcu_set(&as->current_map, new_view);
890 call_rcu(old_view, flatview_unref, rcu);
892 /* Note that all the old MemoryRegions are still alive up to this
893 * point. This relieves most MemoryListeners from the need to
894 * ref/unref the MemoryRegions they get---unless they use them
895 * outside the iothread mutex, in which case precise reference
896 * counting is necessary.
898 flatview_unref(old_view);
900 address_space_update_ioeventfds(as);
903 void memory_region_transaction_begin(void)
905 qemu_flush_coalesced_mmio_buffer();
906 ++memory_region_transaction_depth;
909 void memory_region_transaction_commit(void)
911 AddressSpace *as;
913 assert(memory_region_transaction_depth);
914 assert(qemu_mutex_iothread_locked());
916 --memory_region_transaction_depth;
917 if (!memory_region_transaction_depth) {
918 if (memory_region_update_pending) {
919 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
921 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
922 address_space_update_topology(as);
924 memory_region_update_pending = false;
925 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
926 } else if (ioeventfd_update_pending) {
927 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
928 address_space_update_ioeventfds(as);
930 ioeventfd_update_pending = false;
935 static void memory_region_destructor_none(MemoryRegion *mr)
939 static void memory_region_destructor_ram(MemoryRegion *mr)
941 qemu_ram_free(mr->ram_block);
944 static bool memory_region_need_escape(char c)
946 return c == '/' || c == '[' || c == '\\' || c == ']';
949 static char *memory_region_escape_name(const char *name)
951 const char *p;
952 char *escaped, *q;
953 uint8_t c;
954 size_t bytes = 0;
956 for (p = name; *p; p++) {
957 bytes += memory_region_need_escape(*p) ? 4 : 1;
959 if (bytes == p - name) {
960 return g_memdup(name, bytes + 1);
963 escaped = g_malloc(bytes + 1);
964 for (p = name, q = escaped; *p; p++) {
965 c = *p;
966 if (unlikely(memory_region_need_escape(c))) {
967 *q++ = '\\';
968 *q++ = 'x';
969 *q++ = "0123456789abcdef"[c >> 4];
970 c = "0123456789abcdef"[c & 15];
972 *q++ = c;
974 *q = 0;
975 return escaped;
978 void memory_region_init(MemoryRegion *mr,
979 Object *owner,
980 const char *name,
981 uint64_t size)
983 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
984 mr->size = int128_make64(size);
985 if (size == UINT64_MAX) {
986 mr->size = int128_2_64();
988 mr->name = g_strdup(name);
989 mr->owner = owner;
990 mr->ram_block = NULL;
992 if (name) {
993 char *escaped_name = memory_region_escape_name(name);
994 char *name_array = g_strdup_printf("%s[*]", escaped_name);
996 if (!owner) {
997 owner = container_get(qdev_get_machine(), "/unattached");
1000 object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
1001 object_unref(OBJECT(mr));
1002 g_free(name_array);
1003 g_free(escaped_name);
1007 static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
1008 void *opaque, Error **errp)
1010 MemoryRegion *mr = MEMORY_REGION(obj);
1011 uint64_t value = mr->addr;
1013 visit_type_uint64(v, name, &value, errp);
1016 static void memory_region_get_container(Object *obj, Visitor *v,
1017 const char *name, void *opaque,
1018 Error **errp)
1020 MemoryRegion *mr = MEMORY_REGION(obj);
1021 gchar *path = (gchar *)"";
1023 if (mr->container) {
1024 path = object_get_canonical_path(OBJECT(mr->container));
1026 visit_type_str(v, name, &path, errp);
1027 if (mr->container) {
1028 g_free(path);
1032 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1033 const char *part)
1035 MemoryRegion *mr = MEMORY_REGION(obj);
1037 return OBJECT(mr->container);
1040 static void memory_region_get_priority(Object *obj, Visitor *v,
1041 const char *name, void *opaque,
1042 Error **errp)
1044 MemoryRegion *mr = MEMORY_REGION(obj);
1045 int32_t value = mr->priority;
1047 visit_type_int32(v, name, &value, errp);
1050 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1051 void *opaque, Error **errp)
1053 MemoryRegion *mr = MEMORY_REGION(obj);
1054 uint64_t value = memory_region_size(mr);
1056 visit_type_uint64(v, name, &value, errp);
1059 static void memory_region_initfn(Object *obj)
1061 MemoryRegion *mr = MEMORY_REGION(obj);
1062 ObjectProperty *op;
1064 mr->ops = &unassigned_mem_ops;
1065 mr->enabled = true;
1066 mr->romd_mode = true;
1067 mr->global_locking = true;
1068 mr->destructor = memory_region_destructor_none;
1069 QTAILQ_INIT(&mr->subregions);
1070 QTAILQ_INIT(&mr->coalesced);
1072 op = object_property_add(OBJECT(mr), "container",
1073 "link<" TYPE_MEMORY_REGION ">",
1074 memory_region_get_container,
1075 NULL, /* memory_region_set_container */
1076 NULL, NULL, &error_abort);
1077 op->resolve = memory_region_resolve_container;
1079 object_property_add(OBJECT(mr), "addr", "uint64",
1080 memory_region_get_addr,
1081 NULL, /* memory_region_set_addr */
1082 NULL, NULL, &error_abort);
1083 object_property_add(OBJECT(mr), "priority", "uint32",
1084 memory_region_get_priority,
1085 NULL, /* memory_region_set_priority */
1086 NULL, NULL, &error_abort);
1087 object_property_add(OBJECT(mr), "size", "uint64",
1088 memory_region_get_size,
1089 NULL, /* memory_region_set_size, */
1090 NULL, NULL, &error_abort);
1093 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1094 unsigned size)
1096 #ifdef DEBUG_UNASSIGNED
1097 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1098 #endif
1099 if (current_cpu != NULL) {
1100 cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1102 return 0;
1105 static void unassigned_mem_write(void *opaque, hwaddr addr,
1106 uint64_t val, unsigned size)
1108 #ifdef DEBUG_UNASSIGNED
1109 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1110 #endif
1111 if (current_cpu != NULL) {
1112 cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1116 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1117 unsigned size, bool is_write)
1119 return false;
1122 const MemoryRegionOps unassigned_mem_ops = {
1123 .valid.accepts = unassigned_mem_accepts,
1124 .endianness = DEVICE_NATIVE_ENDIAN,
1127 static uint64_t memory_region_ram_device_read(void *opaque,
1128 hwaddr addr, unsigned size)
1130 MemoryRegion *mr = opaque;
1131 uint64_t data = (uint64_t)~0;
1133 switch (size) {
1134 case 1:
1135 data = *(uint8_t *)(mr->ram_block->host + addr);
1136 break;
1137 case 2:
1138 data = *(uint16_t *)(mr->ram_block->host + addr);
1139 break;
1140 case 4:
1141 data = *(uint32_t *)(mr->ram_block->host + addr);
1142 break;
1143 case 8:
1144 data = *(uint64_t *)(mr->ram_block->host + addr);
1145 break;
1148 trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);
1150 return data;
1153 static void memory_region_ram_device_write(void *opaque, hwaddr addr,
1154 uint64_t data, unsigned size)
1156 MemoryRegion *mr = opaque;
1158 trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);
1160 switch (size) {
1161 case 1:
1162 *(uint8_t *)(mr->ram_block->host + addr) = (uint8_t)data;
1163 break;
1164 case 2:
1165 *(uint16_t *)(mr->ram_block->host + addr) = (uint16_t)data;
1166 break;
1167 case 4:
1168 *(uint32_t *)(mr->ram_block->host + addr) = (uint32_t)data;
1169 break;
1170 case 8:
1171 *(uint64_t *)(mr->ram_block->host + addr) = data;
1172 break;
1176 static const MemoryRegionOps ram_device_mem_ops = {
1177 .read = memory_region_ram_device_read,
1178 .write = memory_region_ram_device_write,
1179 .endianness = DEVICE_HOST_ENDIAN,
1180 .valid = {
1181 .min_access_size = 1,
1182 .max_access_size = 8,
1183 .unaligned = true,
1185 .impl = {
1186 .min_access_size = 1,
1187 .max_access_size = 8,
1188 .unaligned = true,
1192 bool memory_region_access_valid(MemoryRegion *mr,
1193 hwaddr addr,
1194 unsigned size,
1195 bool is_write)
1197 int access_size_min, access_size_max;
1198 int access_size, i;
1200 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1201 return false;
1204 if (!mr->ops->valid.accepts) {
1205 return true;
1208 access_size_min = mr->ops->valid.min_access_size;
1209 if (!mr->ops->valid.min_access_size) {
1210 access_size_min = 1;
1213 access_size_max = mr->ops->valid.max_access_size;
1214 if (!mr->ops->valid.max_access_size) {
1215 access_size_max = 4;
1218 access_size = MAX(MIN(size, access_size_max), access_size_min);
1219 for (i = 0; i < size; i += access_size) {
1220 if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
1221 is_write)) {
1222 return false;
1226 return true;
1229 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1230 hwaddr addr,
1231 uint64_t *pval,
1232 unsigned size,
1233 MemTxAttrs attrs)
1235 *pval = 0;
1237 if (mr->ops->read) {
1238 return access_with_adjusted_size(addr, pval, size,
1239 mr->ops->impl.min_access_size,
1240 mr->ops->impl.max_access_size,
1241 memory_region_read_accessor,
1242 mr, attrs);
1243 } else if (mr->ops->read_with_attrs) {
1244 return access_with_adjusted_size(addr, pval, size,
1245 mr->ops->impl.min_access_size,
1246 mr->ops->impl.max_access_size,
1247 memory_region_read_with_attrs_accessor,
1248 mr, attrs);
1249 } else {
1250 return access_with_adjusted_size(addr, pval, size, 1, 4,
1251 memory_region_oldmmio_read_accessor,
1252 mr, attrs);
1256 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1257 hwaddr addr,
1258 uint64_t *pval,
1259 unsigned size,
1260 MemTxAttrs attrs)
1262 MemTxResult r;
1264 if (!memory_region_access_valid(mr, addr, size, false)) {
1265 *pval = unassigned_mem_read(mr, addr, size);
1266 return MEMTX_DECODE_ERROR;
1269 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1270 adjust_endianness(mr, pval, size);
1271 return r;
1274 /* Return true if an eventfd was signalled */
1275 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1276 hwaddr addr,
1277 uint64_t data,
1278 unsigned size,
1279 MemTxAttrs attrs)
1281 MemoryRegionIoeventfd ioeventfd = {
1282 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1283 .data = data,
1285 unsigned i;
1287 for (i = 0; i < mr->ioeventfd_nb; i++) {
1288 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1289 ioeventfd.e = mr->ioeventfds[i].e;
1291 if (memory_region_ioeventfd_equal(ioeventfd, mr->ioeventfds[i])) {
1292 event_notifier_set(ioeventfd.e);
1293 return true;
1297 return false;
1300 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1301 hwaddr addr,
1302 uint64_t data,
1303 unsigned size,
1304 MemTxAttrs attrs)
1306 if (!memory_region_access_valid(mr, addr, size, true)) {
1307 unassigned_mem_write(mr, addr, data, size);
1308 return MEMTX_DECODE_ERROR;
1311 adjust_endianness(mr, &data, size);
1313 if ((!kvm_eventfds_enabled()) &&
1314 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1315 return MEMTX_OK;
1318 if (mr->ops->write) {
1319 return access_with_adjusted_size(addr, &data, size,
1320 mr->ops->impl.min_access_size,
1321 mr->ops->impl.max_access_size,
1322 memory_region_write_accessor, mr,
1323 attrs);
1324 } else if (mr->ops->write_with_attrs) {
1325 return
1326 access_with_adjusted_size(addr, &data, size,
1327 mr->ops->impl.min_access_size,
1328 mr->ops->impl.max_access_size,
1329 memory_region_write_with_attrs_accessor,
1330 mr, attrs);
1331 } else {
1332 return access_with_adjusted_size(addr, &data, size, 1, 4,
1333 memory_region_oldmmio_write_accessor,
1334 mr, attrs);
1338 void memory_region_init_io(MemoryRegion *mr,
1339 Object *owner,
1340 const MemoryRegionOps *ops,
1341 void *opaque,
1342 const char *name,
1343 uint64_t size)
1345 memory_region_init(mr, owner, name, size);
1346 mr->ops = ops ? ops : &unassigned_mem_ops;
1347 mr->opaque = opaque;
1348 mr->terminates = true;
1351 void memory_region_init_ram(MemoryRegion *mr,
1352 Object *owner,
1353 const char *name,
1354 uint64_t size,
1355 Error **errp)
1357 memory_region_init(mr, owner, name, size);
1358 mr->ram = true;
1359 mr->terminates = true;
1360 mr->destructor = memory_region_destructor_ram;
1361 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1362 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1365 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1366 Object *owner,
1367 const char *name,
1368 uint64_t size,
1369 uint64_t max_size,
1370 void (*resized)(const char*,
1371 uint64_t length,
1372 void *host),
1373 Error **errp)
1375 memory_region_init(mr, owner, name, size);
1376 mr->ram = true;
1377 mr->terminates = true;
1378 mr->destructor = memory_region_destructor_ram;
1379 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1380 mr, errp);
1381 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1384 #ifdef __linux__
1385 void memory_region_init_ram_from_file(MemoryRegion *mr,
1386 struct Object *owner,
1387 const char *name,
1388 uint64_t size,
1389 bool share,
1390 const char *path,
1391 Error **errp)
1393 memory_region_init(mr, owner, name, size);
1394 mr->ram = true;
1395 mr->terminates = true;
1396 mr->destructor = memory_region_destructor_ram;
1397 mr->ram_block = qemu_ram_alloc_from_file(size, mr, share, path, errp);
1398 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1401 void memory_region_init_ram_from_fd(MemoryRegion *mr,
1402 struct Object *owner,
1403 const char *name,
1404 uint64_t size,
1405 bool share,
1406 int fd,
1407 Error **errp)
1409 memory_region_init(mr, owner, name, size);
1410 mr->ram = true;
1411 mr->terminates = true;
1412 mr->destructor = memory_region_destructor_ram;
1413 mr->ram_block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
1414 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1416 #endif
1418 void memory_region_init_ram_ptr(MemoryRegion *mr,
1419 Object *owner,
1420 const char *name,
1421 uint64_t size,
1422 void *ptr)
1424 memory_region_init(mr, owner, name, size);
1425 mr->ram = true;
1426 mr->terminates = true;
1427 mr->destructor = memory_region_destructor_ram;
1428 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1430 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1431 assert(ptr != NULL);
1432 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1435 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1436 Object *owner,
1437 const char *name,
1438 uint64_t size,
1439 void *ptr)
1441 memory_region_init_ram_ptr(mr, owner, name, size, ptr);
1442 mr->ram_device = true;
1443 mr->ops = &ram_device_mem_ops;
1444 mr->opaque = mr;
1447 void memory_region_init_alias(MemoryRegion *mr,
1448 Object *owner,
1449 const char *name,
1450 MemoryRegion *orig,
1451 hwaddr offset,
1452 uint64_t size)
1454 memory_region_init(mr, owner, name, size);
1455 mr->alias = orig;
1456 mr->alias_offset = offset;
1459 void memory_region_init_rom(MemoryRegion *mr,
1460 struct Object *owner,
1461 const char *name,
1462 uint64_t size,
1463 Error **errp)
1465 memory_region_init(mr, owner, name, size);
1466 mr->ram = true;
1467 mr->readonly = true;
1468 mr->terminates = true;
1469 mr->destructor = memory_region_destructor_ram;
1470 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1471 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1474 void memory_region_init_rom_device(MemoryRegion *mr,
1475 Object *owner,
1476 const MemoryRegionOps *ops,
1477 void *opaque,
1478 const char *name,
1479 uint64_t size,
1480 Error **errp)
1482 assert(ops);
1483 memory_region_init(mr, owner, name, size);
1484 mr->ops = ops;
1485 mr->opaque = opaque;
1486 mr->terminates = true;
1487 mr->rom_device = true;
1488 mr->destructor = memory_region_destructor_ram;
1489 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1492 void memory_region_init_iommu(MemoryRegion *mr,
1493 Object *owner,
1494 const MemoryRegionIOMMUOps *ops,
1495 const char *name,
1496 uint64_t size)
1498 memory_region_init(mr, owner, name, size);
1499 mr->iommu_ops = ops,
1500 mr->terminates = true; /* then re-forwards */
1501 QLIST_INIT(&mr->iommu_notify);
1502 mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
1505 static void memory_region_finalize(Object *obj)
1507 MemoryRegion *mr = MEMORY_REGION(obj);
1509 assert(!mr->container);
1511 /* We know the region is not visible in any address space (it
1512 * does not have a container and cannot be a root either because
1513 * it has no references, so we can blindly clear mr->enabled.
1514 * memory_region_set_enabled instead could trigger a transaction
1515 * and cause an infinite loop.
1517 mr->enabled = false;
1518 memory_region_transaction_begin();
1519 while (!QTAILQ_EMPTY(&mr->subregions)) {
1520 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1521 memory_region_del_subregion(mr, subregion);
1523 memory_region_transaction_commit();
1525 mr->destructor(mr);
1526 memory_region_clear_coalescing(mr);
1527 g_free((char *)mr->name);
1528 g_free(mr->ioeventfds);
1531 Object *memory_region_owner(MemoryRegion *mr)
1533 Object *obj = OBJECT(mr);
1534 return obj->parent;
1537 void memory_region_ref(MemoryRegion *mr)
1539 /* MMIO callbacks most likely will access data that belongs
1540 * to the owner, hence the need to ref/unref the owner whenever
1541 * the memory region is in use.
1543 * The memory region is a child of its owner. As long as the
1544 * owner doesn't call unparent itself on the memory region,
1545 * ref-ing the owner will also keep the memory region alive.
1546 * Memory regions without an owner are supposed to never go away;
1547 * we do not ref/unref them because it slows down DMA sensibly.
1549 if (mr && mr->owner) {
1550 object_ref(mr->owner);
1554 void memory_region_unref(MemoryRegion *mr)
1556 if (mr && mr->owner) {
1557 object_unref(mr->owner);
1561 uint64_t memory_region_size(MemoryRegion *mr)
1563 if (int128_eq(mr->size, int128_2_64())) {
1564 return UINT64_MAX;
1566 return int128_get64(mr->size);
1569 const char *memory_region_name(const MemoryRegion *mr)
1571 if (!mr->name) {
1572 ((MemoryRegion *)mr)->name =
1573 object_get_canonical_path_component(OBJECT(mr));
1575 return mr->name;
1578 bool memory_region_is_ram_device(MemoryRegion *mr)
1580 return mr->ram_device;
1583 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1585 uint8_t mask = mr->dirty_log_mask;
1586 if (global_dirty_log && mr->ram_block) {
1587 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1589 return mask;
1592 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1594 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1597 static void memory_region_update_iommu_notify_flags(MemoryRegion *mr)
1599 IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1600 IOMMUNotifier *iommu_notifier;
1602 IOMMU_NOTIFIER_FOREACH(iommu_notifier, mr) {
1603 flags |= iommu_notifier->notifier_flags;
1606 if (flags != mr->iommu_notify_flags &&
1607 mr->iommu_ops->notify_flag_changed) {
1608 mr->iommu_ops->notify_flag_changed(mr, mr->iommu_notify_flags,
1609 flags);
1612 mr->iommu_notify_flags = flags;
1615 void memory_region_register_iommu_notifier(MemoryRegion *mr,
1616 IOMMUNotifier *n)
1618 if (mr->alias) {
1619 memory_region_register_iommu_notifier(mr->alias, n);
1620 return;
1623 /* We need to register for at least one bitfield */
1624 assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
1625 assert(n->start <= n->end);
1626 QLIST_INSERT_HEAD(&mr->iommu_notify, n, node);
1627 memory_region_update_iommu_notify_flags(mr);
1630 uint64_t memory_region_iommu_get_min_page_size(MemoryRegion *mr)
1632 assert(memory_region_is_iommu(mr));
1633 if (mr->iommu_ops && mr->iommu_ops->get_min_page_size) {
1634 return mr->iommu_ops->get_min_page_size(mr);
1636 return TARGET_PAGE_SIZE;
1639 void memory_region_iommu_replay(MemoryRegion *mr, IOMMUNotifier *n)
1641 hwaddr addr, granularity;
1642 IOMMUTLBEntry iotlb;
1644 /* If the IOMMU has its own replay callback, override */
1645 if (mr->iommu_ops->replay) {
1646 mr->iommu_ops->replay(mr, n);
1647 return;
1650 granularity = memory_region_iommu_get_min_page_size(mr);
1652 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1653 iotlb = mr->iommu_ops->translate(mr, addr, IOMMU_NONE);
1654 if (iotlb.perm != IOMMU_NONE) {
1655 n->notify(n, &iotlb);
1658 /* if (2^64 - MR size) < granularity, it's possible to get an
1659 * infinite loop here. This should catch such a wraparound */
1660 if ((addr + granularity) < addr) {
1661 break;
1666 void memory_region_iommu_replay_all(MemoryRegion *mr)
1668 IOMMUNotifier *notifier;
1670 IOMMU_NOTIFIER_FOREACH(notifier, mr) {
1671 memory_region_iommu_replay(mr, notifier);
1675 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1676 IOMMUNotifier *n)
1678 if (mr->alias) {
1679 memory_region_unregister_iommu_notifier(mr->alias, n);
1680 return;
1682 QLIST_REMOVE(n, node);
1683 memory_region_update_iommu_notify_flags(mr);
1686 void memory_region_notify_one(IOMMUNotifier *notifier,
1687 IOMMUTLBEntry *entry)
1689 IOMMUNotifierFlag request_flags;
1692 * Skip the notification if the notification does not overlap
1693 * with registered range.
1695 if (notifier->start > entry->iova + entry->addr_mask + 1 ||
1696 notifier->end < entry->iova) {
1697 return;
1700 if (entry->perm & IOMMU_RW) {
1701 request_flags = IOMMU_NOTIFIER_MAP;
1702 } else {
1703 request_flags = IOMMU_NOTIFIER_UNMAP;
1706 if (notifier->notifier_flags & request_flags) {
1707 notifier->notify(notifier, entry);
1711 void memory_region_notify_iommu(MemoryRegion *mr,
1712 IOMMUTLBEntry entry)
1714 IOMMUNotifier *iommu_notifier;
1716 assert(memory_region_is_iommu(mr));
1718 IOMMU_NOTIFIER_FOREACH(iommu_notifier, mr) {
1719 memory_region_notify_one(iommu_notifier, &entry);
1723 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1725 uint8_t mask = 1 << client;
1726 uint8_t old_logging;
1728 assert(client == DIRTY_MEMORY_VGA);
1729 old_logging = mr->vga_logging_count;
1730 mr->vga_logging_count += log ? 1 : -1;
1731 if (!!old_logging == !!mr->vga_logging_count) {
1732 return;
1735 memory_region_transaction_begin();
1736 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1737 memory_region_update_pending |= mr->enabled;
1738 memory_region_transaction_commit();
1741 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1742 hwaddr size, unsigned client)
1744 assert(mr->ram_block);
1745 return cpu_physical_memory_get_dirty(memory_region_get_ram_addr(mr) + addr,
1746 size, client);
1749 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1750 hwaddr size)
1752 assert(mr->ram_block);
1753 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
1754 size,
1755 memory_region_get_dirty_log_mask(mr));
1758 bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,
1759 hwaddr size, unsigned client)
1761 assert(mr->ram_block);
1762 return cpu_physical_memory_test_and_clear_dirty(
1763 memory_region_get_ram_addr(mr) + addr, size, client);
1766 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
1767 hwaddr addr,
1768 hwaddr size,
1769 unsigned client)
1771 assert(mr->ram_block);
1772 return cpu_physical_memory_snapshot_and_clear_dirty(
1773 memory_region_get_ram_addr(mr) + addr, size, client);
1776 bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
1777 hwaddr addr, hwaddr size)
1779 assert(mr->ram_block);
1780 return cpu_physical_memory_snapshot_get_dirty(snap,
1781 memory_region_get_ram_addr(mr) + addr, size);
1784 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1786 MemoryListener *listener;
1787 AddressSpace *as;
1788 FlatView *view;
1789 FlatRange *fr;
1791 /* If the same address space has multiple log_sync listeners, we
1792 * visit that address space's FlatView multiple times. But because
1793 * log_sync listeners are rare, it's still cheaper than walking each
1794 * address space once.
1796 QTAILQ_FOREACH(listener, &memory_listeners, link) {
1797 if (!listener->log_sync) {
1798 continue;
1800 as = listener->address_space;
1801 view = address_space_get_flatview(as);
1802 FOR_EACH_FLAT_RANGE(fr, view) {
1803 if (fr->mr == mr) {
1804 MemoryRegionSection mrs = section_from_flat_range(fr, as);
1805 listener->log_sync(listener, &mrs);
1808 flatview_unref(view);
1812 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1814 if (mr->readonly != readonly) {
1815 memory_region_transaction_begin();
1816 mr->readonly = readonly;
1817 memory_region_update_pending |= mr->enabled;
1818 memory_region_transaction_commit();
1822 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
1824 if (mr->romd_mode != romd_mode) {
1825 memory_region_transaction_begin();
1826 mr->romd_mode = romd_mode;
1827 memory_region_update_pending |= mr->enabled;
1828 memory_region_transaction_commit();
1832 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1833 hwaddr size, unsigned client)
1835 assert(mr->ram_block);
1836 cpu_physical_memory_test_and_clear_dirty(
1837 memory_region_get_ram_addr(mr) + addr, size, client);
1840 int memory_region_get_fd(MemoryRegion *mr)
1842 int fd;
1844 rcu_read_lock();
1845 while (mr->alias) {
1846 mr = mr->alias;
1848 fd = mr->ram_block->fd;
1849 rcu_read_unlock();
1851 return fd;
1854 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1856 void *ptr;
1857 uint64_t offset = 0;
1859 rcu_read_lock();
1860 while (mr->alias) {
1861 offset += mr->alias_offset;
1862 mr = mr->alias;
1864 assert(mr->ram_block);
1865 ptr = qemu_map_ram_ptr(mr->ram_block, offset);
1866 rcu_read_unlock();
1868 return ptr;
1871 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
1873 RAMBlock *block;
1875 block = qemu_ram_block_from_host(ptr, false, offset);
1876 if (!block) {
1877 return NULL;
1880 return block->mr;
1883 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
1885 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
1888 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
1890 assert(mr->ram_block);
1892 qemu_ram_resize(mr->ram_block, newsize, errp);
1895 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1897 FlatView *view;
1898 FlatRange *fr;
1899 CoalescedMemoryRange *cmr;
1900 AddrRange tmp;
1901 MemoryRegionSection section;
1903 view = address_space_get_flatview(as);
1904 FOR_EACH_FLAT_RANGE(fr, view) {
1905 if (fr->mr == mr) {
1906 section = (MemoryRegionSection) {
1907 .address_space = as,
1908 .offset_within_address_space = int128_get64(fr->addr.start),
1909 .size = fr->addr.size,
1912 MEMORY_LISTENER_CALL(as, coalesced_mmio_del, Reverse, &section,
1913 int128_get64(fr->addr.start),
1914 int128_get64(fr->addr.size));
1915 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1916 tmp = addrrange_shift(cmr->addr,
1917 int128_sub(fr->addr.start,
1918 int128_make64(fr->offset_in_region)));
1919 if (!addrrange_intersects(tmp, fr->addr)) {
1920 continue;
1922 tmp = addrrange_intersection(tmp, fr->addr);
1923 MEMORY_LISTENER_CALL(as, coalesced_mmio_add, Forward, &section,
1924 int128_get64(tmp.start),
1925 int128_get64(tmp.size));
1929 flatview_unref(view);
1932 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1934 AddressSpace *as;
1936 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1937 memory_region_update_coalesced_range_as(mr, as);
1941 void memory_region_set_coalescing(MemoryRegion *mr)
1943 memory_region_clear_coalescing(mr);
1944 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1947 void memory_region_add_coalescing(MemoryRegion *mr,
1948 hwaddr offset,
1949 uint64_t size)
1951 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1953 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1954 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1955 memory_region_update_coalesced_range(mr);
1956 memory_region_set_flush_coalesced(mr);
1959 void memory_region_clear_coalescing(MemoryRegion *mr)
1961 CoalescedMemoryRange *cmr;
1962 bool updated = false;
1964 qemu_flush_coalesced_mmio_buffer();
1965 mr->flush_coalesced_mmio = false;
1967 while (!QTAILQ_EMPTY(&mr->coalesced)) {
1968 cmr = QTAILQ_FIRST(&mr->coalesced);
1969 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1970 g_free(cmr);
1971 updated = true;
1974 if (updated) {
1975 memory_region_update_coalesced_range(mr);
1979 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1981 mr->flush_coalesced_mmio = true;
1984 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1986 qemu_flush_coalesced_mmio_buffer();
1987 if (QTAILQ_EMPTY(&mr->coalesced)) {
1988 mr->flush_coalesced_mmio = false;
1992 void memory_region_set_global_locking(MemoryRegion *mr)
1994 mr->global_locking = true;
1997 void memory_region_clear_global_locking(MemoryRegion *mr)
1999 mr->global_locking = false;
2002 static bool userspace_eventfd_warning;
2004 void memory_region_add_eventfd(MemoryRegion *mr,
2005 hwaddr addr,
2006 unsigned size,
2007 bool match_data,
2008 uint64_t data,
2009 EventNotifier *e)
2011 MemoryRegionIoeventfd mrfd = {
2012 .addr.start = int128_make64(addr),
2013 .addr.size = int128_make64(size),
2014 .match_data = match_data,
2015 .data = data,
2016 .e = e,
2018 unsigned i;
2020 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
2021 userspace_eventfd_warning))) {
2022 userspace_eventfd_warning = true;
2023 error_report("Using eventfd without MMIO binding in KVM. "
2024 "Suboptimal performance expected");
2027 if (size) {
2028 adjust_endianness(mr, &mrfd.data, size);
2030 memory_region_transaction_begin();
2031 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2032 if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
2033 break;
2036 ++mr->ioeventfd_nb;
2037 mr->ioeventfds = g_realloc(mr->ioeventfds,
2038 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2039 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2040 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2041 mr->ioeventfds[i] = mrfd;
2042 ioeventfd_update_pending |= mr->enabled;
2043 memory_region_transaction_commit();
2046 void memory_region_del_eventfd(MemoryRegion *mr,
2047 hwaddr addr,
2048 unsigned size,
2049 bool match_data,
2050 uint64_t data,
2051 EventNotifier *e)
2053 MemoryRegionIoeventfd mrfd = {
2054 .addr.start = int128_make64(addr),
2055 .addr.size = int128_make64(size),
2056 .match_data = match_data,
2057 .data = data,
2058 .e = e,
2060 unsigned i;
2062 if (size) {
2063 adjust_endianness(mr, &mrfd.data, size);
2065 memory_region_transaction_begin();
2066 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2067 if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
2068 break;
2071 assert(i != mr->ioeventfd_nb);
2072 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2073 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2074 --mr->ioeventfd_nb;
2075 mr->ioeventfds = g_realloc(mr->ioeventfds,
2076 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
2077 ioeventfd_update_pending |= mr->enabled;
2078 memory_region_transaction_commit();
2081 static void memory_region_update_container_subregions(MemoryRegion *subregion)
2083 MemoryRegion *mr = subregion->container;
2084 MemoryRegion *other;
2086 memory_region_transaction_begin();
2088 memory_region_ref(subregion);
2089 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2090 if (subregion->priority >= other->priority) {
2091 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2092 goto done;
2095 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2096 done:
2097 memory_region_update_pending |= mr->enabled && subregion->enabled;
2098 memory_region_transaction_commit();
2101 static void memory_region_add_subregion_common(MemoryRegion *mr,
2102 hwaddr offset,
2103 MemoryRegion *subregion)
2105 assert(!subregion->container);
2106 subregion->container = mr;
2107 subregion->addr = offset;
2108 memory_region_update_container_subregions(subregion);
2111 void memory_region_add_subregion(MemoryRegion *mr,
2112 hwaddr offset,
2113 MemoryRegion *subregion)
2115 subregion->priority = 0;
2116 memory_region_add_subregion_common(mr, offset, subregion);
2119 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2120 hwaddr offset,
2121 MemoryRegion *subregion,
2122 int priority)
2124 subregion->priority = priority;
2125 memory_region_add_subregion_common(mr, offset, subregion);
2128 void memory_region_del_subregion(MemoryRegion *mr,
2129 MemoryRegion *subregion)
2131 memory_region_transaction_begin();
2132 assert(subregion->container == mr);
2133 subregion->container = NULL;
2134 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
2135 memory_region_unref(subregion);
2136 memory_region_update_pending |= mr->enabled && subregion->enabled;
2137 memory_region_transaction_commit();
2140 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2142 if (enabled == mr->enabled) {
2143 return;
2145 memory_region_transaction_begin();
2146 mr->enabled = enabled;
2147 memory_region_update_pending = true;
2148 memory_region_transaction_commit();
2151 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2153 Int128 s = int128_make64(size);
2155 if (size == UINT64_MAX) {
2156 s = int128_2_64();
2158 if (int128_eq(s, mr->size)) {
2159 return;
2161 memory_region_transaction_begin();
2162 mr->size = s;
2163 memory_region_update_pending = true;
2164 memory_region_transaction_commit();
2167 static void memory_region_readd_subregion(MemoryRegion *mr)
2169 MemoryRegion *container = mr->container;
2171 if (container) {
2172 memory_region_transaction_begin();
2173 memory_region_ref(mr);
2174 memory_region_del_subregion(container, mr);
2175 mr->container = container;
2176 memory_region_update_container_subregions(mr);
2177 memory_region_unref(mr);
2178 memory_region_transaction_commit();
2182 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2184 if (addr != mr->addr) {
2185 mr->addr = addr;
2186 memory_region_readd_subregion(mr);
2190 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
2192 assert(mr->alias);
2194 if (offset == mr->alias_offset) {
2195 return;
2198 memory_region_transaction_begin();
2199 mr->alias_offset = offset;
2200 memory_region_update_pending |= mr->enabled;
2201 memory_region_transaction_commit();
2204 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2206 return mr->align;
2209 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2211 const AddrRange *addr = addr_;
2212 const FlatRange *fr = fr_;
2214 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2215 return -1;
2216 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2217 return 1;
2219 return 0;
2222 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
2224 return bsearch(&addr, view->ranges, view->nr,
2225 sizeof(FlatRange), cmp_flatrange_addr);
2228 bool memory_region_is_mapped(MemoryRegion *mr)
2230 return mr->container ? true : false;
2233 /* Same as memory_region_find, but it does not add a reference to the
2234 * returned region. It must be called from an RCU critical section.
2236 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2237 hwaddr addr, uint64_t size)
2239 MemoryRegionSection ret = { .mr = NULL };
2240 MemoryRegion *root;
2241 AddressSpace *as;
2242 AddrRange range;
2243 FlatView *view;
2244 FlatRange *fr;
2246 addr += mr->addr;
2247 for (root = mr; root->container; ) {
2248 root = root->container;
2249 addr += root->addr;
2252 as = memory_region_to_address_space(root);
2253 if (!as) {
2254 return ret;
2256 range = addrrange_make(int128_make64(addr), int128_make64(size));
2258 view = atomic_rcu_read(&as->current_map);
2259 fr = flatview_lookup(view, range);
2260 if (!fr) {
2261 return ret;
2264 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2265 --fr;
2268 ret.mr = fr->mr;
2269 ret.address_space = as;
2270 range = addrrange_intersection(range, fr->addr);
2271 ret.offset_within_region = fr->offset_in_region;
2272 ret.offset_within_region += int128_get64(int128_sub(range.start,
2273 fr->addr.start));
2274 ret.size = range.size;
2275 ret.offset_within_address_space = int128_get64(range.start);
2276 ret.readonly = fr->readonly;
2277 return ret;
2280 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2281 hwaddr addr, uint64_t size)
2283 MemoryRegionSection ret;
2284 rcu_read_lock();
2285 ret = memory_region_find_rcu(mr, addr, size);
2286 if (ret.mr) {
2287 memory_region_ref(ret.mr);
2289 rcu_read_unlock();
2290 return ret;
2293 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2295 MemoryRegion *mr;
2297 rcu_read_lock();
2298 mr = memory_region_find_rcu(container, addr, 1).mr;
2299 rcu_read_unlock();
2300 return mr && mr != container;
2303 void memory_global_dirty_log_sync(void)
2305 MemoryListener *listener;
2306 AddressSpace *as;
2307 FlatView *view;
2308 FlatRange *fr;
2310 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2311 if (!listener->log_sync) {
2312 continue;
2314 as = listener->address_space;
2315 view = address_space_get_flatview(as);
2316 FOR_EACH_FLAT_RANGE(fr, view) {
2317 if (fr->dirty_log_mask) {
2318 MemoryRegionSection mrs = section_from_flat_range(fr, as);
2319 listener->log_sync(listener, &mrs);
2322 flatview_unref(view);
2326 void memory_global_dirty_log_start(void)
2328 global_dirty_log = true;
2330 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2332 /* Refresh DIRTY_LOG_MIGRATION bit. */
2333 memory_region_transaction_begin();
2334 memory_region_update_pending = true;
2335 memory_region_transaction_commit();
2338 void memory_global_dirty_log_stop(void)
2340 global_dirty_log = false;
2342 /* Refresh DIRTY_LOG_MIGRATION bit. */
2343 memory_region_transaction_begin();
2344 memory_region_update_pending = true;
2345 memory_region_transaction_commit();
2347 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2350 static void listener_add_address_space(MemoryListener *listener,
2351 AddressSpace *as)
2353 FlatView *view;
2354 FlatRange *fr;
2356 if (listener->begin) {
2357 listener->begin(listener);
2359 if (global_dirty_log) {
2360 if (listener->log_global_start) {
2361 listener->log_global_start(listener);
2365 view = address_space_get_flatview(as);
2366 FOR_EACH_FLAT_RANGE(fr, view) {
2367 MemoryRegionSection section = {
2368 .mr = fr->mr,
2369 .address_space = as,
2370 .offset_within_region = fr->offset_in_region,
2371 .size = fr->addr.size,
2372 .offset_within_address_space = int128_get64(fr->addr.start),
2373 .readonly = fr->readonly,
2375 if (fr->dirty_log_mask && listener->log_start) {
2376 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2378 if (listener->region_add) {
2379 listener->region_add(listener, &section);
2382 if (listener->commit) {
2383 listener->commit(listener);
2385 flatview_unref(view);
2388 void memory_listener_register(MemoryListener *listener, AddressSpace *as)
2390 MemoryListener *other = NULL;
2392 listener->address_space = as;
2393 if (QTAILQ_EMPTY(&memory_listeners)
2394 || listener->priority >= QTAILQ_LAST(&memory_listeners,
2395 memory_listeners)->priority) {
2396 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2397 } else {
2398 QTAILQ_FOREACH(other, &memory_listeners, link) {
2399 if (listener->priority < other->priority) {
2400 break;
2403 QTAILQ_INSERT_BEFORE(other, listener, link);
2406 if (QTAILQ_EMPTY(&as->listeners)
2407 || listener->priority >= QTAILQ_LAST(&as->listeners,
2408 memory_listeners)->priority) {
2409 QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
2410 } else {
2411 QTAILQ_FOREACH(other, &as->listeners, link_as) {
2412 if (listener->priority < other->priority) {
2413 break;
2416 QTAILQ_INSERT_BEFORE(other, listener, link_as);
2419 listener_add_address_space(listener, as);
2422 void memory_listener_unregister(MemoryListener *listener)
2424 if (!listener->address_space) {
2425 return;
2428 QTAILQ_REMOVE(&memory_listeners, listener, link);
2429 QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
2430 listener->address_space = NULL;
2433 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2435 memory_region_ref(root);
2436 memory_region_transaction_begin();
2437 as->ref_count = 1;
2438 as->root = root;
2439 as->malloced = false;
2440 as->current_map = g_new(FlatView, 1);
2441 flatview_init(as->current_map);
2442 as->ioeventfd_nb = 0;
2443 as->ioeventfds = NULL;
2444 QTAILQ_INIT(&as->listeners);
2445 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2446 as->name = g_strdup(name ? name : "anonymous");
2447 address_space_init_dispatch(as);
2448 memory_region_update_pending |= root->enabled;
2449 memory_region_transaction_commit();
2452 static void do_address_space_destroy(AddressSpace *as)
2454 bool do_free = as->malloced;
2456 address_space_destroy_dispatch(as);
2457 assert(QTAILQ_EMPTY(&as->listeners));
2459 flatview_unref(as->current_map);
2460 g_free(as->name);
2461 g_free(as->ioeventfds);
2462 memory_region_unref(as->root);
2463 if (do_free) {
2464 g_free(as);
2468 AddressSpace *address_space_init_shareable(MemoryRegion *root, const char *name)
2470 AddressSpace *as;
2472 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2473 if (root == as->root && as->malloced) {
2474 as->ref_count++;
2475 return as;
2479 as = g_malloc0(sizeof *as);
2480 address_space_init(as, root, name);
2481 as->malloced = true;
2482 return as;
2485 void address_space_destroy(AddressSpace *as)
2487 MemoryRegion *root = as->root;
2489 as->ref_count--;
2490 if (as->ref_count) {
2491 return;
2493 /* Flush out anything from MemoryListeners listening in on this */
2494 memory_region_transaction_begin();
2495 as->root = NULL;
2496 memory_region_transaction_commit();
2497 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2498 address_space_unregister(as);
2500 /* At this point, as->dispatch and as->current_map are dummy
2501 * entries that the guest should never use. Wait for the old
2502 * values to expire before freeing the data.
2504 as->root = root;
2505 call_rcu(as, do_address_space_destroy, rcu);
2508 static const char *memory_region_type(MemoryRegion *mr)
2510 if (memory_region_is_ram_device(mr)) {
2511 return "ramd";
2512 } else if (memory_region_is_romd(mr)) {
2513 return "romd";
2514 } else if (memory_region_is_rom(mr)) {
2515 return "rom";
2516 } else if (memory_region_is_ram(mr)) {
2517 return "ram";
2518 } else {
2519 return "i/o";
2523 typedef struct MemoryRegionList MemoryRegionList;
2525 struct MemoryRegionList {
2526 const MemoryRegion *mr;
2527 QTAILQ_ENTRY(MemoryRegionList) queue;
2530 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
2532 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
2533 int128_sub((size), int128_one())) : 0)
2534 #define MTREE_INDENT " "
2536 static void mtree_print_mr(fprintf_function mon_printf, void *f,
2537 const MemoryRegion *mr, unsigned int level,
2538 hwaddr base,
2539 MemoryRegionListHead *alias_print_queue)
2541 MemoryRegionList *new_ml, *ml, *next_ml;
2542 MemoryRegionListHead submr_print_queue;
2543 const MemoryRegion *submr;
2544 unsigned int i;
2545 hwaddr cur_start, cur_end;
2547 if (!mr) {
2548 return;
2551 for (i = 0; i < level; i++) {
2552 mon_printf(f, MTREE_INDENT);
2555 cur_start = base + mr->addr;
2556 cur_end = cur_start + MR_SIZE(mr->size);
2559 * Try to detect overflow of memory region. This should never
2560 * happen normally. When it happens, we dump something to warn the
2561 * user who is observing this.
2563 if (cur_start < base || cur_end < cur_start) {
2564 mon_printf(f, "[DETECTED OVERFLOW!] ");
2567 if (mr->alias) {
2568 MemoryRegionList *ml;
2569 bool found = false;
2571 /* check if the alias is already in the queue */
2572 QTAILQ_FOREACH(ml, alias_print_queue, queue) {
2573 if (ml->mr == mr->alias) {
2574 found = true;
2578 if (!found) {
2579 ml = g_new(MemoryRegionList, 1);
2580 ml->mr = mr->alias;
2581 QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
2583 mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
2584 " (prio %d, %s): alias %s @%s " TARGET_FMT_plx
2585 "-" TARGET_FMT_plx "%s\n",
2586 cur_start, cur_end,
2587 mr->priority,
2588 memory_region_type((MemoryRegion *)mr),
2589 memory_region_name(mr),
2590 memory_region_name(mr->alias),
2591 mr->alias_offset,
2592 mr->alias_offset + MR_SIZE(mr->size),
2593 mr->enabled ? "" : " [disabled]");
2594 } else {
2595 mon_printf(f,
2596 TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %s): %s%s\n",
2597 cur_start, cur_end,
2598 mr->priority,
2599 memory_region_type((MemoryRegion *)mr),
2600 memory_region_name(mr),
2601 mr->enabled ? "" : " [disabled]");
2604 QTAILQ_INIT(&submr_print_queue);
2606 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2607 new_ml = g_new(MemoryRegionList, 1);
2608 new_ml->mr = submr;
2609 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2610 if (new_ml->mr->addr < ml->mr->addr ||
2611 (new_ml->mr->addr == ml->mr->addr &&
2612 new_ml->mr->priority > ml->mr->priority)) {
2613 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
2614 new_ml = NULL;
2615 break;
2618 if (new_ml) {
2619 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
2623 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2624 mtree_print_mr(mon_printf, f, ml->mr, level + 1, cur_start,
2625 alias_print_queue);
2628 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
2629 g_free(ml);
2633 static void mtree_print_flatview(fprintf_function p, void *f,
2634 AddressSpace *as)
2636 FlatView *view = address_space_get_flatview(as);
2637 FlatRange *range = &view->ranges[0];
2638 MemoryRegion *mr;
2639 int n = view->nr;
2641 if (n <= 0) {
2642 p(f, MTREE_INDENT "No rendered FlatView for "
2643 "address space '%s'\n", as->name);
2644 flatview_unref(view);
2645 return;
2648 while (n--) {
2649 mr = range->mr;
2650 if (range->offset_in_region) {
2651 p(f, MTREE_INDENT TARGET_FMT_plx "-"
2652 TARGET_FMT_plx " (prio %d, %s): %s @" TARGET_FMT_plx "\n",
2653 int128_get64(range->addr.start),
2654 int128_get64(range->addr.start) + MR_SIZE(range->addr.size),
2655 mr->priority,
2656 range->readonly ? "rom" : memory_region_type(mr),
2657 memory_region_name(mr),
2658 range->offset_in_region);
2659 } else {
2660 p(f, MTREE_INDENT TARGET_FMT_plx "-"
2661 TARGET_FMT_plx " (prio %d, %s): %s\n",
2662 int128_get64(range->addr.start),
2663 int128_get64(range->addr.start) + MR_SIZE(range->addr.size),
2664 mr->priority,
2665 range->readonly ? "rom" : memory_region_type(mr),
2666 memory_region_name(mr));
2668 range++;
2671 flatview_unref(view);
2674 void mtree_info(fprintf_function mon_printf, void *f, bool flatview)
2676 MemoryRegionListHead ml_head;
2677 MemoryRegionList *ml, *ml2;
2678 AddressSpace *as;
2680 if (flatview) {
2681 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2682 mon_printf(f, "address-space (flat view): %s\n", as->name);
2683 mtree_print_flatview(mon_printf, f, as);
2684 mon_printf(f, "\n");
2686 return;
2689 QTAILQ_INIT(&ml_head);
2691 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2692 mon_printf(f, "address-space: %s\n", as->name);
2693 mtree_print_mr(mon_printf, f, as->root, 1, 0, &ml_head);
2694 mon_printf(f, "\n");
2697 /* print aliased regions */
2698 QTAILQ_FOREACH(ml, &ml_head, queue) {
2699 mon_printf(f, "memory-region: %s\n", memory_region_name(ml->mr));
2700 mtree_print_mr(mon_printf, f, ml->mr, 1, 0, &ml_head);
2701 mon_printf(f, "\n");
2704 QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
2705 g_free(ml);
2709 static const TypeInfo memory_region_info = {
2710 .parent = TYPE_OBJECT,
2711 .name = TYPE_MEMORY_REGION,
2712 .instance_size = sizeof(MemoryRegion),
2713 .instance_init = memory_region_initfn,
2714 .instance_finalize = memory_region_finalize,
2717 static void memory_register_types(void)
2719 type_register_static(&memory_region_info);
2722 type_init(memory_register_types)