xref: /openbmc/qemu/system/memory.c (revision 95e82f9b)
1 /*
2  * Physical memory management
3  *
4  * Copyright 2011 Red Hat, Inc. and/or its affiliates
5  *
6  * Authors:
7  *  Avi Kivity <avi@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
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.
14  */
15 
16 #include "qemu/osdep.h"
17 #include "qemu/log.h"
18 #include "qapi/error.h"
19 #include "exec/memory.h"
20 #include "qapi/visitor.h"
21 #include "qemu/bitops.h"
22 #include "qemu/error-report.h"
23 #include "qemu/main-loop.h"
24 #include "qemu/qemu-print.h"
25 #include "qom/object.h"
26 #include "trace.h"
27 
28 #include "exec/memory-internal.h"
29 #include "exec/ram_addr.h"
30 #include "sysemu/kvm.h"
31 #include "sysemu/runstate.h"
32 #include "sysemu/tcg.h"
33 #include "qemu/accel.h"
34 #include "hw/boards.h"
35 #include "migration/vmstate.h"
36 #include "exec/address-spaces.h"
37 
38 //#define DEBUG_UNASSIGNED
39 
40 static unsigned memory_region_transaction_depth;
41 static bool memory_region_update_pending;
42 static bool ioeventfd_update_pending;
43 unsigned int global_dirty_tracking;
44 
45 static QTAILQ_HEAD(, MemoryListener) memory_listeners
46     = QTAILQ_HEAD_INITIALIZER(memory_listeners);
47 
48 static QTAILQ_HEAD(, AddressSpace) address_spaces
49     = QTAILQ_HEAD_INITIALIZER(address_spaces);
50 
51 static GHashTable *flat_views;
52 
53 typedef struct AddrRange AddrRange;
54 
55 /*
56  * Note that signed integers are needed for negative offsetting in aliases
57  * (large MemoryRegion::alias_offset).
58  */
59 struct AddrRange {
60     Int128 start;
61     Int128 size;
62 };
63 
64 static AddrRange addrrange_make(Int128 start, Int128 size)
65 {
66     return (AddrRange) { start, size };
67 }
68 
69 static bool addrrange_equal(AddrRange r1, AddrRange r2)
70 {
71     return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
72 }
73 
74 static Int128 addrrange_end(AddrRange r)
75 {
76     return int128_add(r.start, r.size);
77 }
78 
79 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
80 {
81     int128_addto(&range.start, delta);
82     return range;
83 }
84 
85 static bool addrrange_contains(AddrRange range, Int128 addr)
86 {
87     return int128_ge(addr, range.start)
88         && int128_lt(addr, addrrange_end(range));
89 }
90 
91 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
92 {
93     return addrrange_contains(r1, r2.start)
94         || addrrange_contains(r2, r1.start);
95 }
96 
97 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
98 {
99     Int128 start = int128_max(r1.start, r2.start);
100     Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
101     return addrrange_make(start, int128_sub(end, start));
102 }
103 
104 enum ListenerDirection { Forward, Reverse };
105 
106 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...)    \
107     do {                                                                \
108         MemoryListener *_listener;                                      \
109                                                                         \
110         switch (_direction) {                                           \
111         case Forward:                                                   \
112             QTAILQ_FOREACH(_listener, &memory_listeners, link) {        \
113                 if (_listener->_callback) {                             \
114                     _listener->_callback(_listener, ##_args);           \
115                 }                                                       \
116             }                                                           \
117             break;                                                      \
118         case Reverse:                                                   \
119             QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners, link) { \
120                 if (_listener->_callback) {                             \
121                     _listener->_callback(_listener, ##_args);           \
122                 }                                                       \
123             }                                                           \
124             break;                                                      \
125         default:                                                        \
126             abort();                                                    \
127         }                                                               \
128     } while (0)
129 
130 #define MEMORY_LISTENER_CALL(_as, _callback, _direction, _section, _args...) \
131     do {                                                                \
132         MemoryListener *_listener;                                      \
133                                                                         \
134         switch (_direction) {                                           \
135         case Forward:                                                   \
136             QTAILQ_FOREACH(_listener, &(_as)->listeners, link_as) {     \
137                 if (_listener->_callback) {                             \
138                     _listener->_callback(_listener, _section, ##_args); \
139                 }                                                       \
140             }                                                           \
141             break;                                                      \
142         case Reverse:                                                   \
143             QTAILQ_FOREACH_REVERSE(_listener, &(_as)->listeners, link_as) { \
144                 if (_listener->_callback) {                             \
145                     _listener->_callback(_listener, _section, ##_args); \
146                 }                                                       \
147             }                                                           \
148             break;                                                      \
149         default:                                                        \
150             abort();                                                    \
151         }                                                               \
152     } while (0)
153 
154 /* No need to ref/unref .mr, the FlatRange keeps it alive.  */
155 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...)  \
156     do {                                                                \
157         MemoryRegionSection mrs = section_from_flat_range(fr,           \
158                 address_space_to_flatview(as));                         \
159         MEMORY_LISTENER_CALL(as, callback, dir, &mrs, ##_args);         \
160     } while(0)
161 
162 struct CoalescedMemoryRange {
163     AddrRange addr;
164     QTAILQ_ENTRY(CoalescedMemoryRange) link;
165 };
166 
167 struct MemoryRegionIoeventfd {
168     AddrRange addr;
169     bool match_data;
170     uint64_t data;
171     EventNotifier *e;
172 };
173 
174 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd *a,
175                                            MemoryRegionIoeventfd *b)
176 {
177     if (int128_lt(a->addr.start, b->addr.start)) {
178         return true;
179     } else if (int128_gt(a->addr.start, b->addr.start)) {
180         return false;
181     } else if (int128_lt(a->addr.size, b->addr.size)) {
182         return true;
183     } else if (int128_gt(a->addr.size, b->addr.size)) {
184         return false;
185     } else if (a->match_data < b->match_data) {
186         return true;
187     } else  if (a->match_data > b->match_data) {
188         return false;
189     } else if (a->match_data) {
190         if (a->data < b->data) {
191             return true;
192         } else if (a->data > b->data) {
193             return false;
194         }
195     }
196     if (a->e < b->e) {
197         return true;
198     } else if (a->e > b->e) {
199         return false;
200     }
201     return false;
202 }
203 
204 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd *a,
205                                           MemoryRegionIoeventfd *b)
206 {
207     if (int128_eq(a->addr.start, b->addr.start) &&
208         (!int128_nz(a->addr.size) || !int128_nz(b->addr.size) ||
209          (int128_eq(a->addr.size, b->addr.size) &&
210           (a->match_data == b->match_data) &&
211           ((a->match_data && (a->data == b->data)) || !a->match_data) &&
212           (a->e == b->e))))
213         return true;
214 
215     return false;
216 }
217 
218 /* Range of memory in the global map.  Addresses are absolute. */
219 struct FlatRange {
220     MemoryRegion *mr;
221     hwaddr offset_in_region;
222     AddrRange addr;
223     uint8_t dirty_log_mask;
224     bool romd_mode;
225     bool readonly;
226     bool nonvolatile;
227     bool unmergeable;
228 };
229 
230 #define FOR_EACH_FLAT_RANGE(var, view)          \
231     for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
232 
233 static inline MemoryRegionSection
234 section_from_flat_range(FlatRange *fr, FlatView *fv)
235 {
236     return (MemoryRegionSection) {
237         .mr = fr->mr,
238         .fv = fv,
239         .offset_within_region = fr->offset_in_region,
240         .size = fr->addr.size,
241         .offset_within_address_space = int128_get64(fr->addr.start),
242         .readonly = fr->readonly,
243         .nonvolatile = fr->nonvolatile,
244         .unmergeable = fr->unmergeable,
245     };
246 }
247 
248 static bool flatrange_equal(FlatRange *a, FlatRange *b)
249 {
250     return a->mr == b->mr
251         && addrrange_equal(a->addr, b->addr)
252         && a->offset_in_region == b->offset_in_region
253         && a->romd_mode == b->romd_mode
254         && a->readonly == b->readonly
255         && a->nonvolatile == b->nonvolatile
256         && a->unmergeable == b->unmergeable;
257 }
258 
259 static FlatView *flatview_new(MemoryRegion *mr_root)
260 {
261     FlatView *view;
262 
263     view = g_new0(FlatView, 1);
264     view->ref = 1;
265     view->root = mr_root;
266     memory_region_ref(mr_root);
267     trace_flatview_new(view, mr_root);
268 
269     return view;
270 }
271 
272 /* Insert a range into a given position.  Caller is responsible for maintaining
273  * sorting order.
274  */
275 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
276 {
277     if (view->nr == view->nr_allocated) {
278         view->nr_allocated = MAX(2 * view->nr, 10);
279         view->ranges = g_realloc(view->ranges,
280                                     view->nr_allocated * sizeof(*view->ranges));
281     }
282     memmove(view->ranges + pos + 1, view->ranges + pos,
283             (view->nr - pos) * sizeof(FlatRange));
284     view->ranges[pos] = *range;
285     memory_region_ref(range->mr);
286     ++view->nr;
287 }
288 
289 static void flatview_destroy(FlatView *view)
290 {
291     int i;
292 
293     trace_flatview_destroy(view, view->root);
294     if (view->dispatch) {
295         address_space_dispatch_free(view->dispatch);
296     }
297     for (i = 0; i < view->nr; i++) {
298         memory_region_unref(view->ranges[i].mr);
299     }
300     g_free(view->ranges);
301     memory_region_unref(view->root);
302     g_free(view);
303 }
304 
305 static bool flatview_ref(FlatView *view)
306 {
307     return qatomic_fetch_inc_nonzero(&view->ref) > 0;
308 }
309 
310 void flatview_unref(FlatView *view)
311 {
312     if (qatomic_fetch_dec(&view->ref) == 1) {
313         trace_flatview_destroy_rcu(view, view->root);
314         assert(view->root);
315         call_rcu(view, flatview_destroy, rcu);
316     }
317 }
318 
319 static bool can_merge(FlatRange *r1, FlatRange *r2)
320 {
321     return int128_eq(addrrange_end(r1->addr), r2->addr.start)
322         && r1->mr == r2->mr
323         && int128_eq(int128_add(int128_make64(r1->offset_in_region),
324                                 r1->addr.size),
325                      int128_make64(r2->offset_in_region))
326         && r1->dirty_log_mask == r2->dirty_log_mask
327         && r1->romd_mode == r2->romd_mode
328         && r1->readonly == r2->readonly
329         && r1->nonvolatile == r2->nonvolatile
330         && !r1->unmergeable && !r2->unmergeable;
331 }
332 
333 /* Attempt to simplify a view by merging adjacent ranges */
334 static void flatview_simplify(FlatView *view)
335 {
336     unsigned i, j, k;
337 
338     i = 0;
339     while (i < view->nr) {
340         j = i + 1;
341         while (j < view->nr
342                && can_merge(&view->ranges[j-1], &view->ranges[j])) {
343             int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
344             ++j;
345         }
346         ++i;
347         for (k = i; k < j; k++) {
348             memory_region_unref(view->ranges[k].mr);
349         }
350         memmove(&view->ranges[i], &view->ranges[j],
351                 (view->nr - j) * sizeof(view->ranges[j]));
352         view->nr -= j - i;
353     }
354 }
355 
356 static bool memory_region_big_endian(MemoryRegion *mr)
357 {
358 #if TARGET_BIG_ENDIAN
359     return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
360 #else
361     return mr->ops->endianness == DEVICE_BIG_ENDIAN;
362 #endif
363 }
364 
365 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, MemOp op)
366 {
367     if ((op & MO_BSWAP) != devend_memop(mr->ops->endianness)) {
368         switch (op & MO_SIZE) {
369         case MO_8:
370             break;
371         case MO_16:
372             *data = bswap16(*data);
373             break;
374         case MO_32:
375             *data = bswap32(*data);
376             break;
377         case MO_64:
378             *data = bswap64(*data);
379             break;
380         default:
381             g_assert_not_reached();
382         }
383     }
384 }
385 
386 static inline void memory_region_shift_read_access(uint64_t *value,
387                                                    signed shift,
388                                                    uint64_t mask,
389                                                    uint64_t tmp)
390 {
391     if (shift >= 0) {
392         *value |= (tmp & mask) << shift;
393     } else {
394         *value |= (tmp & mask) >> -shift;
395     }
396 }
397 
398 static inline uint64_t memory_region_shift_write_access(uint64_t *value,
399                                                         signed shift,
400                                                         uint64_t mask)
401 {
402     uint64_t tmp;
403 
404     if (shift >= 0) {
405         tmp = (*value >> shift) & mask;
406     } else {
407         tmp = (*value << -shift) & mask;
408     }
409 
410     return tmp;
411 }
412 
413 static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
414 {
415     MemoryRegion *root;
416     hwaddr abs_addr = offset;
417 
418     abs_addr += mr->addr;
419     for (root = mr; root->container; ) {
420         root = root->container;
421         abs_addr += root->addr;
422     }
423 
424     return abs_addr;
425 }
426 
427 static int get_cpu_index(void)
428 {
429     if (current_cpu) {
430         return current_cpu->cpu_index;
431     }
432     return -1;
433 }
434 
435 static MemTxResult  memory_region_read_accessor(MemoryRegion *mr,
436                                                 hwaddr addr,
437                                                 uint64_t *value,
438                                                 unsigned size,
439                                                 signed shift,
440                                                 uint64_t mask,
441                                                 MemTxAttrs attrs)
442 {
443     uint64_t tmp;
444 
445     tmp = mr->ops->read(mr->opaque, addr, size);
446     if (mr->subpage) {
447         trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
448     } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_READ)) {
449         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
450         trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size,
451                                      memory_region_name(mr));
452     }
453     memory_region_shift_read_access(value, shift, mask, tmp);
454     return MEMTX_OK;
455 }
456 
457 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
458                                                           hwaddr addr,
459                                                           uint64_t *value,
460                                                           unsigned size,
461                                                           signed shift,
462                                                           uint64_t mask,
463                                                           MemTxAttrs attrs)
464 {
465     uint64_t tmp = 0;
466     MemTxResult r;
467 
468     r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
469     if (mr->subpage) {
470         trace_memory_region_subpage_read(get_cpu_index(), mr, addr, tmp, size);
471     } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_READ)) {
472         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
473         trace_memory_region_ops_read(get_cpu_index(), mr, abs_addr, tmp, size,
474                                      memory_region_name(mr));
475     }
476     memory_region_shift_read_access(value, shift, mask, tmp);
477     return r;
478 }
479 
480 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
481                                                 hwaddr addr,
482                                                 uint64_t *value,
483                                                 unsigned size,
484                                                 signed shift,
485                                                 uint64_t mask,
486                                                 MemTxAttrs attrs)
487 {
488     uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
489 
490     if (mr->subpage) {
491         trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
492     } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_WRITE)) {
493         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
494         trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size,
495                                       memory_region_name(mr));
496     }
497     mr->ops->write(mr->opaque, addr, tmp, size);
498     return MEMTX_OK;
499 }
500 
501 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
502                                                            hwaddr addr,
503                                                            uint64_t *value,
504                                                            unsigned size,
505                                                            signed shift,
506                                                            uint64_t mask,
507                                                            MemTxAttrs attrs)
508 {
509     uint64_t tmp = memory_region_shift_write_access(value, shift, mask);
510 
511     if (mr->subpage) {
512         trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);
513     } else if (trace_event_get_state_backends(TRACE_MEMORY_REGION_OPS_WRITE)) {
514         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
515         trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size,
516                                       memory_region_name(mr));
517     }
518     return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
519 }
520 
521 static MemTxResult access_with_adjusted_size(hwaddr addr,
522                                       uint64_t *value,
523                                       unsigned size,
524                                       unsigned access_size_min,
525                                       unsigned access_size_max,
526                                       MemTxResult (*access_fn)
527                                                   (MemoryRegion *mr,
528                                                    hwaddr addr,
529                                                    uint64_t *value,
530                                                    unsigned size,
531                                                    signed shift,
532                                                    uint64_t mask,
533                                                    MemTxAttrs attrs),
534                                       MemoryRegion *mr,
535                                       MemTxAttrs attrs)
536 {
537     uint64_t access_mask;
538     unsigned access_size;
539     unsigned i;
540     MemTxResult r = MEMTX_OK;
541     bool reentrancy_guard_applied = false;
542 
543     if (!access_size_min) {
544         access_size_min = 1;
545     }
546     if (!access_size_max) {
547         access_size_max = 4;
548     }
549 
550     /* Do not allow more than one simultaneous access to a device's IO Regions */
551     if (mr->dev && !mr->disable_reentrancy_guard &&
552         !mr->ram_device && !mr->ram && !mr->rom_device && !mr->readonly) {
553         if (mr->dev->mem_reentrancy_guard.engaged_in_io) {
554             warn_report_once("Blocked re-entrant IO on MemoryRegion: "
555                              "%s at addr: 0x%" HWADDR_PRIX,
556                              memory_region_name(mr), addr);
557             return MEMTX_ACCESS_ERROR;
558         }
559         mr->dev->mem_reentrancy_guard.engaged_in_io = true;
560         reentrancy_guard_applied = true;
561     }
562 
563     /* FIXME: support unaligned access? */
564     access_size = MAX(MIN(size, access_size_max), access_size_min);
565     access_mask = MAKE_64BIT_MASK(0, access_size * 8);
566     if (memory_region_big_endian(mr)) {
567         for (i = 0; i < size; i += access_size) {
568             r |= access_fn(mr, addr + i, value, access_size,
569                         (size - access_size - i) * 8, access_mask, attrs);
570         }
571     } else {
572         for (i = 0; i < size; i += access_size) {
573             r |= access_fn(mr, addr + i, value, access_size, i * 8,
574                         access_mask, attrs);
575         }
576     }
577     if (mr->dev && reentrancy_guard_applied) {
578         mr->dev->mem_reentrancy_guard.engaged_in_io = false;
579     }
580     return r;
581 }
582 
583 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
584 {
585     AddressSpace *as;
586 
587     while (mr->container) {
588         mr = mr->container;
589     }
590     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
591         if (mr == as->root) {
592             return as;
593         }
594     }
595     return NULL;
596 }
597 
598 /* Render a memory region into the global view.  Ranges in @view obscure
599  * ranges in @mr.
600  */
601 static void render_memory_region(FlatView *view,
602                                  MemoryRegion *mr,
603                                  Int128 base,
604                                  AddrRange clip,
605                                  bool readonly,
606                                  bool nonvolatile,
607                                  bool unmergeable)
608 {
609     MemoryRegion *subregion;
610     unsigned i;
611     hwaddr offset_in_region;
612     Int128 remain;
613     Int128 now;
614     FlatRange fr;
615     AddrRange tmp;
616 
617     if (!mr->enabled) {
618         return;
619     }
620 
621     int128_addto(&base, int128_make64(mr->addr));
622     readonly |= mr->readonly;
623     nonvolatile |= mr->nonvolatile;
624     unmergeable |= mr->unmergeable;
625 
626     tmp = addrrange_make(base, mr->size);
627 
628     if (!addrrange_intersects(tmp, clip)) {
629         return;
630     }
631 
632     clip = addrrange_intersection(tmp, clip);
633 
634     if (mr->alias) {
635         int128_subfrom(&base, int128_make64(mr->alias->addr));
636         int128_subfrom(&base, int128_make64(mr->alias_offset));
637         render_memory_region(view, mr->alias, base, clip,
638                              readonly, nonvolatile, unmergeable);
639         return;
640     }
641 
642     /* Render subregions in priority order. */
643     QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
644         render_memory_region(view, subregion, base, clip,
645                              readonly, nonvolatile, unmergeable);
646     }
647 
648     if (!mr->terminates) {
649         return;
650     }
651 
652     offset_in_region = int128_get64(int128_sub(clip.start, base));
653     base = clip.start;
654     remain = clip.size;
655 
656     fr.mr = mr;
657     fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
658     fr.romd_mode = mr->romd_mode;
659     fr.readonly = readonly;
660     fr.nonvolatile = nonvolatile;
661     fr.unmergeable = unmergeable;
662 
663     /* Render the region itself into any gaps left by the current view. */
664     for (i = 0; i < view->nr && int128_nz(remain); ++i) {
665         if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
666             continue;
667         }
668         if (int128_lt(base, view->ranges[i].addr.start)) {
669             now = int128_min(remain,
670                              int128_sub(view->ranges[i].addr.start, base));
671             fr.offset_in_region = offset_in_region;
672             fr.addr = addrrange_make(base, now);
673             flatview_insert(view, i, &fr);
674             ++i;
675             int128_addto(&base, now);
676             offset_in_region += int128_get64(now);
677             int128_subfrom(&remain, now);
678         }
679         now = int128_sub(int128_min(int128_add(base, remain),
680                                     addrrange_end(view->ranges[i].addr)),
681                          base);
682         int128_addto(&base, now);
683         offset_in_region += int128_get64(now);
684         int128_subfrom(&remain, now);
685     }
686     if (int128_nz(remain)) {
687         fr.offset_in_region = offset_in_region;
688         fr.addr = addrrange_make(base, remain);
689         flatview_insert(view, i, &fr);
690     }
691 }
692 
693 void flatview_for_each_range(FlatView *fv, flatview_cb cb , void *opaque)
694 {
695     FlatRange *fr;
696 
697     assert(fv);
698     assert(cb);
699 
700     FOR_EACH_FLAT_RANGE(fr, fv) {
701         if (cb(fr->addr.start, fr->addr.size, fr->mr,
702                fr->offset_in_region, opaque)) {
703             break;
704         }
705     }
706 }
707 
708 static MemoryRegion *memory_region_get_flatview_root(MemoryRegion *mr)
709 {
710     while (mr->enabled) {
711         if (mr->alias) {
712             if (!mr->alias_offset && int128_ge(mr->size, mr->alias->size)) {
713                 /* The alias is included in its entirety.  Use it as
714                  * the "real" root, so that we can share more FlatViews.
715                  */
716                 mr = mr->alias;
717                 continue;
718             }
719         } else if (!mr->terminates) {
720             unsigned int found = 0;
721             MemoryRegion *child, *next = NULL;
722             QTAILQ_FOREACH(child, &mr->subregions, subregions_link) {
723                 if (child->enabled) {
724                     if (++found > 1) {
725                         next = NULL;
726                         break;
727                     }
728                     if (!child->addr && int128_ge(mr->size, child->size)) {
729                         /* A child is included in its entirety.  If it's the only
730                          * enabled one, use it in the hope of finding an alias down the
731                          * way. This will also let us share FlatViews.
732                          */
733                         next = child;
734                     }
735                 }
736             }
737             if (found == 0) {
738                 return NULL;
739             }
740             if (next) {
741                 mr = next;
742                 continue;
743             }
744         }
745 
746         return mr;
747     }
748 
749     return NULL;
750 }
751 
752 /* Render a memory topology into a list of disjoint absolute ranges. */
753 static FlatView *generate_memory_topology(MemoryRegion *mr)
754 {
755     int i;
756     FlatView *view;
757 
758     view = flatview_new(mr);
759 
760     if (mr) {
761         render_memory_region(view, mr, int128_zero(),
762                              addrrange_make(int128_zero(), int128_2_64()),
763                              false, false, false);
764     }
765     flatview_simplify(view);
766 
767     view->dispatch = address_space_dispatch_new(view);
768     for (i = 0; i < view->nr; i++) {
769         MemoryRegionSection mrs =
770             section_from_flat_range(&view->ranges[i], view);
771         flatview_add_to_dispatch(view, &mrs);
772     }
773     address_space_dispatch_compact(view->dispatch);
774     g_hash_table_replace(flat_views, mr, view);
775 
776     return view;
777 }
778 
779 static void address_space_add_del_ioeventfds(AddressSpace *as,
780                                              MemoryRegionIoeventfd *fds_new,
781                                              unsigned fds_new_nb,
782                                              MemoryRegionIoeventfd *fds_old,
783                                              unsigned fds_old_nb)
784 {
785     unsigned iold, inew;
786     MemoryRegionIoeventfd *fd;
787     MemoryRegionSection section;
788 
789     /* Generate a symmetric difference of the old and new fd sets, adding
790      * and deleting as necessary.
791      */
792 
793     iold = inew = 0;
794     while (iold < fds_old_nb || inew < fds_new_nb) {
795         if (iold < fds_old_nb
796             && (inew == fds_new_nb
797                 || memory_region_ioeventfd_before(&fds_old[iold],
798                                                   &fds_new[inew]))) {
799             fd = &fds_old[iold];
800             section = (MemoryRegionSection) {
801                 .fv = address_space_to_flatview(as),
802                 .offset_within_address_space = int128_get64(fd->addr.start),
803                 .size = fd->addr.size,
804             };
805             MEMORY_LISTENER_CALL(as, eventfd_del, Forward, &section,
806                                  fd->match_data, fd->data, fd->e);
807             ++iold;
808         } else if (inew < fds_new_nb
809                    && (iold == fds_old_nb
810                        || memory_region_ioeventfd_before(&fds_new[inew],
811                                                          &fds_old[iold]))) {
812             fd = &fds_new[inew];
813             section = (MemoryRegionSection) {
814                 .fv = address_space_to_flatview(as),
815                 .offset_within_address_space = int128_get64(fd->addr.start),
816                 .size = fd->addr.size,
817             };
818             MEMORY_LISTENER_CALL(as, eventfd_add, Reverse, &section,
819                                  fd->match_data, fd->data, fd->e);
820             ++inew;
821         } else {
822             ++iold;
823             ++inew;
824         }
825     }
826 }
827 
828 FlatView *address_space_get_flatview(AddressSpace *as)
829 {
830     FlatView *view;
831 
832     RCU_READ_LOCK_GUARD();
833     do {
834         view = address_space_to_flatview(as);
835         /* If somebody has replaced as->current_map concurrently,
836          * flatview_ref returns false.
837          */
838     } while (!flatview_ref(view));
839     return view;
840 }
841 
842 static void address_space_update_ioeventfds(AddressSpace *as)
843 {
844     FlatView *view;
845     FlatRange *fr;
846     unsigned ioeventfd_nb = 0;
847     unsigned ioeventfd_max;
848     MemoryRegionIoeventfd *ioeventfds;
849     AddrRange tmp;
850     unsigned i;
851 
852     if (!as->ioeventfd_notifiers) {
853         return;
854     }
855 
856     /*
857      * It is likely that the number of ioeventfds hasn't changed much, so use
858      * the previous size as the starting value, with some headroom to avoid
859      * gratuitous reallocations.
860      */
861     ioeventfd_max = QEMU_ALIGN_UP(as->ioeventfd_nb, 4);
862     ioeventfds = g_new(MemoryRegionIoeventfd, ioeventfd_max);
863 
864     view = address_space_get_flatview(as);
865     FOR_EACH_FLAT_RANGE(fr, view) {
866         for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
867             tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
868                                   int128_sub(fr->addr.start,
869                                              int128_make64(fr->offset_in_region)));
870             if (addrrange_intersects(fr->addr, tmp)) {
871                 ++ioeventfd_nb;
872                 if (ioeventfd_nb > ioeventfd_max) {
873                     ioeventfd_max = MAX(ioeventfd_max * 2, 4);
874                     ioeventfds = g_realloc(ioeventfds,
875                             ioeventfd_max * sizeof(*ioeventfds));
876                 }
877                 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
878                 ioeventfds[ioeventfd_nb-1].addr = tmp;
879             }
880         }
881     }
882 
883     address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
884                                      as->ioeventfds, as->ioeventfd_nb);
885 
886     g_free(as->ioeventfds);
887     as->ioeventfds = ioeventfds;
888     as->ioeventfd_nb = ioeventfd_nb;
889     flatview_unref(view);
890 }
891 
892 /*
893  * Notify the memory listeners about the coalesced IO change events of
894  * range `cmr'.  Only the part that has intersection of the specified
895  * FlatRange will be sent.
896  */
897 static void flat_range_coalesced_io_notify(FlatRange *fr, AddressSpace *as,
898                                            CoalescedMemoryRange *cmr, bool add)
899 {
900     AddrRange tmp;
901 
902     tmp = addrrange_shift(cmr->addr,
903                           int128_sub(fr->addr.start,
904                                      int128_make64(fr->offset_in_region)));
905     if (!addrrange_intersects(tmp, fr->addr)) {
906         return;
907     }
908     tmp = addrrange_intersection(tmp, fr->addr);
909 
910     if (add) {
911         MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, coalesced_io_add,
912                                       int128_get64(tmp.start),
913                                       int128_get64(tmp.size));
914     } else {
915         MEMORY_LISTENER_UPDATE_REGION(fr, as, Reverse, coalesced_io_del,
916                                       int128_get64(tmp.start),
917                                       int128_get64(tmp.size));
918     }
919 }
920 
921 static void flat_range_coalesced_io_del(FlatRange *fr, AddressSpace *as)
922 {
923     CoalescedMemoryRange *cmr;
924 
925     QTAILQ_FOREACH(cmr, &fr->mr->coalesced, link) {
926         flat_range_coalesced_io_notify(fr, as, cmr, false);
927     }
928 }
929 
930 static void flat_range_coalesced_io_add(FlatRange *fr, AddressSpace *as)
931 {
932     MemoryRegion *mr = fr->mr;
933     CoalescedMemoryRange *cmr;
934 
935     if (QTAILQ_EMPTY(&mr->coalesced)) {
936         return;
937     }
938 
939     QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
940         flat_range_coalesced_io_notify(fr, as, cmr, true);
941     }
942 }
943 
944 static void
945 flat_range_coalesced_io_notify_listener_add_del(FlatRange *fr,
946                                                 MemoryRegionSection *mrs,
947                                                 MemoryListener *listener,
948                                                 AddressSpace *as, bool add)
949 {
950     CoalescedMemoryRange *cmr;
951     MemoryRegion *mr = fr->mr;
952     AddrRange tmp;
953 
954     QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
955         tmp = addrrange_shift(cmr->addr,
956                               int128_sub(fr->addr.start,
957                                          int128_make64(fr->offset_in_region)));
958 
959         if (!addrrange_intersects(tmp, fr->addr)) {
960             return;
961         }
962         tmp = addrrange_intersection(tmp, fr->addr);
963 
964         if (add && listener->coalesced_io_add) {
965             listener->coalesced_io_add(listener, mrs,
966                                        int128_get64(tmp.start),
967                                        int128_get64(tmp.size));
968         } else if (!add && listener->coalesced_io_del) {
969             listener->coalesced_io_del(listener, mrs,
970                                        int128_get64(tmp.start),
971                                        int128_get64(tmp.size));
972         }
973     }
974 }
975 
976 static void address_space_update_topology_pass(AddressSpace *as,
977                                                const FlatView *old_view,
978                                                const FlatView *new_view,
979                                                bool adding)
980 {
981     unsigned iold, inew;
982     FlatRange *frold, *frnew;
983 
984     /* Generate a symmetric difference of the old and new memory maps.
985      * Kill ranges in the old map, and instantiate ranges in the new map.
986      */
987     iold = inew = 0;
988     while (iold < old_view->nr || inew < new_view->nr) {
989         if (iold < old_view->nr) {
990             frold = &old_view->ranges[iold];
991         } else {
992             frold = NULL;
993         }
994         if (inew < new_view->nr) {
995             frnew = &new_view->ranges[inew];
996         } else {
997             frnew = NULL;
998         }
999 
1000         if (frold
1001             && (!frnew
1002                 || int128_lt(frold->addr.start, frnew->addr.start)
1003                 || (int128_eq(frold->addr.start, frnew->addr.start)
1004                     && !flatrange_equal(frold, frnew)))) {
1005             /* In old but not in new, or in both but attributes changed. */
1006 
1007             if (!adding) {
1008                 flat_range_coalesced_io_del(frold, as);
1009                 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
1010             }
1011 
1012             ++iold;
1013         } else if (frold && frnew && flatrange_equal(frold, frnew)) {
1014             /* In both and unchanged (except logging may have changed) */
1015 
1016             if (adding) {
1017                 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
1018                 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
1019                     MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
1020                                                   frold->dirty_log_mask,
1021                                                   frnew->dirty_log_mask);
1022                 }
1023                 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
1024                     MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
1025                                                   frold->dirty_log_mask,
1026                                                   frnew->dirty_log_mask);
1027                 }
1028             }
1029 
1030             ++iold;
1031             ++inew;
1032         } else {
1033             /* In new */
1034 
1035             if (adding) {
1036                 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
1037                 flat_range_coalesced_io_add(frnew, as);
1038             }
1039 
1040             ++inew;
1041         }
1042     }
1043 }
1044 
1045 static void flatviews_init(void)
1046 {
1047     static FlatView *empty_view;
1048 
1049     if (flat_views) {
1050         return;
1051     }
1052 
1053     flat_views = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL,
1054                                        (GDestroyNotify) flatview_unref);
1055     if (!empty_view) {
1056         empty_view = generate_memory_topology(NULL);
1057         /* We keep it alive forever in the global variable.  */
1058         flatview_ref(empty_view);
1059     } else {
1060         g_hash_table_replace(flat_views, NULL, empty_view);
1061         flatview_ref(empty_view);
1062     }
1063 }
1064 
1065 static void flatviews_reset(void)
1066 {
1067     AddressSpace *as;
1068 
1069     if (flat_views) {
1070         g_hash_table_unref(flat_views);
1071         flat_views = NULL;
1072     }
1073     flatviews_init();
1074 
1075     /* Render unique FVs */
1076     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1077         MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1078 
1079         if (g_hash_table_lookup(flat_views, physmr)) {
1080             continue;
1081         }
1082 
1083         generate_memory_topology(physmr);
1084     }
1085 }
1086 
1087 static void address_space_set_flatview(AddressSpace *as)
1088 {
1089     FlatView *old_view = address_space_to_flatview(as);
1090     MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1091     FlatView *new_view = g_hash_table_lookup(flat_views, physmr);
1092 
1093     assert(new_view);
1094 
1095     if (old_view == new_view) {
1096         return;
1097     }
1098 
1099     if (old_view) {
1100         flatview_ref(old_view);
1101     }
1102 
1103     flatview_ref(new_view);
1104 
1105     if (!QTAILQ_EMPTY(&as->listeners)) {
1106         FlatView tmpview = { .nr = 0 }, *old_view2 = old_view;
1107 
1108         if (!old_view2) {
1109             old_view2 = &tmpview;
1110         }
1111         address_space_update_topology_pass(as, old_view2, new_view, false);
1112         address_space_update_topology_pass(as, old_view2, new_view, true);
1113     }
1114 
1115     /* Writes are protected by the BQL.  */
1116     qatomic_rcu_set(&as->current_map, new_view);
1117     if (old_view) {
1118         flatview_unref(old_view);
1119     }
1120 
1121     /* Note that all the old MemoryRegions are still alive up to this
1122      * point.  This relieves most MemoryListeners from the need to
1123      * ref/unref the MemoryRegions they get---unless they use them
1124      * outside the iothread mutex, in which case precise reference
1125      * counting is necessary.
1126      */
1127     if (old_view) {
1128         flatview_unref(old_view);
1129     }
1130 }
1131 
1132 static void address_space_update_topology(AddressSpace *as)
1133 {
1134     MemoryRegion *physmr = memory_region_get_flatview_root(as->root);
1135 
1136     flatviews_init();
1137     if (!g_hash_table_lookup(flat_views, physmr)) {
1138         generate_memory_topology(physmr);
1139     }
1140     address_space_set_flatview(as);
1141 }
1142 
1143 void memory_region_transaction_begin(void)
1144 {
1145     qemu_flush_coalesced_mmio_buffer();
1146     ++memory_region_transaction_depth;
1147 }
1148 
1149 void memory_region_transaction_commit(void)
1150 {
1151     AddressSpace *as;
1152 
1153     assert(memory_region_transaction_depth);
1154     assert(bql_locked());
1155 
1156     --memory_region_transaction_depth;
1157     if (!memory_region_transaction_depth) {
1158         if (memory_region_update_pending) {
1159             flatviews_reset();
1160 
1161             MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
1162 
1163             QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1164                 address_space_set_flatview(as);
1165                 address_space_update_ioeventfds(as);
1166             }
1167             memory_region_update_pending = false;
1168             ioeventfd_update_pending = false;
1169             MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
1170         } else if (ioeventfd_update_pending) {
1171             QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1172                 address_space_update_ioeventfds(as);
1173             }
1174             ioeventfd_update_pending = false;
1175         }
1176    }
1177 }
1178 
1179 static void memory_region_destructor_none(MemoryRegion *mr)
1180 {
1181 }
1182 
1183 static void memory_region_destructor_ram(MemoryRegion *mr)
1184 {
1185     qemu_ram_free(mr->ram_block);
1186 }
1187 
1188 static bool memory_region_need_escape(char c)
1189 {
1190     return c == '/' || c == '[' || c == '\\' || c == ']';
1191 }
1192 
1193 static char *memory_region_escape_name(const char *name)
1194 {
1195     const char *p;
1196     char *escaped, *q;
1197     uint8_t c;
1198     size_t bytes = 0;
1199 
1200     for (p = name; *p; p++) {
1201         bytes += memory_region_need_escape(*p) ? 4 : 1;
1202     }
1203     if (bytes == p - name) {
1204        return g_memdup(name, bytes + 1);
1205     }
1206 
1207     escaped = g_malloc(bytes + 1);
1208     for (p = name, q = escaped; *p; p++) {
1209         c = *p;
1210         if (unlikely(memory_region_need_escape(c))) {
1211             *q++ = '\\';
1212             *q++ = 'x';
1213             *q++ = "0123456789abcdef"[c >> 4];
1214             c = "0123456789abcdef"[c & 15];
1215         }
1216         *q++ = c;
1217     }
1218     *q = 0;
1219     return escaped;
1220 }
1221 
1222 static void memory_region_do_init(MemoryRegion *mr,
1223                                   Object *owner,
1224                                   const char *name,
1225                                   uint64_t size)
1226 {
1227     mr->size = int128_make64(size);
1228     if (size == UINT64_MAX) {
1229         mr->size = int128_2_64();
1230     }
1231     mr->name = g_strdup(name);
1232     mr->owner = owner;
1233     mr->dev = (DeviceState *) object_dynamic_cast(mr->owner, TYPE_DEVICE);
1234     mr->ram_block = NULL;
1235 
1236     if (name) {
1237         char *escaped_name = memory_region_escape_name(name);
1238         char *name_array = g_strdup_printf("%s[*]", escaped_name);
1239 
1240         if (!owner) {
1241             owner = container_get(qdev_get_machine(), "/unattached");
1242         }
1243 
1244         object_property_add_child(owner, name_array, OBJECT(mr));
1245         object_unref(OBJECT(mr));
1246         g_free(name_array);
1247         g_free(escaped_name);
1248     }
1249 }
1250 
1251 void memory_region_init(MemoryRegion *mr,
1252                         Object *owner,
1253                         const char *name,
1254                         uint64_t size)
1255 {
1256     object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
1257     memory_region_do_init(mr, owner, name, size);
1258 }
1259 
1260 static void memory_region_get_container(Object *obj, Visitor *v,
1261                                         const char *name, void *opaque,
1262                                         Error **errp)
1263 {
1264     MemoryRegion *mr = MEMORY_REGION(obj);
1265     char *path = (char *)"";
1266 
1267     if (mr->container) {
1268         path = object_get_canonical_path(OBJECT(mr->container));
1269     }
1270     visit_type_str(v, name, &path, errp);
1271     if (mr->container) {
1272         g_free(path);
1273     }
1274 }
1275 
1276 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1277                                                const char *part)
1278 {
1279     MemoryRegion *mr = MEMORY_REGION(obj);
1280 
1281     return OBJECT(mr->container);
1282 }
1283 
1284 static void memory_region_get_priority(Object *obj, Visitor *v,
1285                                        const char *name, void *opaque,
1286                                        Error **errp)
1287 {
1288     MemoryRegion *mr = MEMORY_REGION(obj);
1289     int32_t value = mr->priority;
1290 
1291     visit_type_int32(v, name, &value, errp);
1292 }
1293 
1294 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1295                                    void *opaque, Error **errp)
1296 {
1297     MemoryRegion *mr = MEMORY_REGION(obj);
1298     uint64_t value = memory_region_size(mr);
1299 
1300     visit_type_uint64(v, name, &value, errp);
1301 }
1302 
1303 static void memory_region_initfn(Object *obj)
1304 {
1305     MemoryRegion *mr = MEMORY_REGION(obj);
1306     ObjectProperty *op;
1307 
1308     mr->ops = &unassigned_mem_ops;
1309     mr->enabled = true;
1310     mr->romd_mode = true;
1311     mr->destructor = memory_region_destructor_none;
1312     QTAILQ_INIT(&mr->subregions);
1313     QTAILQ_INIT(&mr->coalesced);
1314 
1315     op = object_property_add(OBJECT(mr), "container",
1316                              "link<" TYPE_MEMORY_REGION ">",
1317                              memory_region_get_container,
1318                              NULL, /* memory_region_set_container */
1319                              NULL, NULL);
1320     op->resolve = memory_region_resolve_container;
1321 
1322     object_property_add_uint64_ptr(OBJECT(mr), "addr",
1323                                    &mr->addr, OBJ_PROP_FLAG_READ);
1324     object_property_add(OBJECT(mr), "priority", "uint32",
1325                         memory_region_get_priority,
1326                         NULL, /* memory_region_set_priority */
1327                         NULL, NULL);
1328     object_property_add(OBJECT(mr), "size", "uint64",
1329                         memory_region_get_size,
1330                         NULL, /* memory_region_set_size, */
1331                         NULL, NULL);
1332 }
1333 
1334 static void iommu_memory_region_initfn(Object *obj)
1335 {
1336     MemoryRegion *mr = MEMORY_REGION(obj);
1337 
1338     mr->is_iommu = true;
1339 }
1340 
1341 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1342                                     unsigned size)
1343 {
1344 #ifdef DEBUG_UNASSIGNED
1345     printf("Unassigned mem read " HWADDR_FMT_plx "\n", addr);
1346 #endif
1347     return 0;
1348 }
1349 
1350 static void unassigned_mem_write(void *opaque, hwaddr addr,
1351                                  uint64_t val, unsigned size)
1352 {
1353 #ifdef DEBUG_UNASSIGNED
1354     printf("Unassigned mem write " HWADDR_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1355 #endif
1356 }
1357 
1358 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1359                                    unsigned size, bool is_write,
1360                                    MemTxAttrs attrs)
1361 {
1362     return false;
1363 }
1364 
1365 const MemoryRegionOps unassigned_mem_ops = {
1366     .valid.accepts = unassigned_mem_accepts,
1367     .endianness = DEVICE_NATIVE_ENDIAN,
1368 };
1369 
1370 static uint64_t memory_region_ram_device_read(void *opaque,
1371                                               hwaddr addr, unsigned size)
1372 {
1373     MemoryRegion *mr = opaque;
1374     uint64_t data = ldn_he_p(mr->ram_block->host + addr, size);
1375 
1376     trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);
1377 
1378     return data;
1379 }
1380 
1381 static void memory_region_ram_device_write(void *opaque, hwaddr addr,
1382                                            uint64_t data, unsigned size)
1383 {
1384     MemoryRegion *mr = opaque;
1385 
1386     trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);
1387 
1388     stn_he_p(mr->ram_block->host + addr, size, data);
1389 }
1390 
1391 static const MemoryRegionOps ram_device_mem_ops = {
1392     .read = memory_region_ram_device_read,
1393     .write = memory_region_ram_device_write,
1394     .endianness = DEVICE_HOST_ENDIAN,
1395     .valid = {
1396         .min_access_size = 1,
1397         .max_access_size = 8,
1398         .unaligned = true,
1399     },
1400     .impl = {
1401         .min_access_size = 1,
1402         .max_access_size = 8,
1403         .unaligned = true,
1404     },
1405 };
1406 
1407 bool memory_region_access_valid(MemoryRegion *mr,
1408                                 hwaddr addr,
1409                                 unsigned size,
1410                                 bool is_write,
1411                                 MemTxAttrs attrs)
1412 {
1413     if (mr->ops->valid.accepts
1414         && !mr->ops->valid.accepts(mr->opaque, addr, size, is_write, attrs)) {
1415         qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1416                       ", size %u, region '%s', reason: rejected\n",
1417                       is_write ? "write" : "read",
1418                       addr, size, memory_region_name(mr));
1419         return false;
1420     }
1421 
1422     if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1423         qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1424                       ", size %u, region '%s', reason: unaligned\n",
1425                       is_write ? "write" : "read",
1426                       addr, size, memory_region_name(mr));
1427         return false;
1428     }
1429 
1430     /* Treat zero as compatibility all valid */
1431     if (!mr->ops->valid.max_access_size) {
1432         return true;
1433     }
1434 
1435     if (size > mr->ops->valid.max_access_size
1436         || size < mr->ops->valid.min_access_size) {
1437         qemu_log_mask(LOG_GUEST_ERROR, "Invalid %s at addr 0x%" HWADDR_PRIX
1438                       ", size %u, region '%s', reason: invalid size "
1439                       "(min:%u max:%u)\n",
1440                       is_write ? "write" : "read",
1441                       addr, size, memory_region_name(mr),
1442                       mr->ops->valid.min_access_size,
1443                       mr->ops->valid.max_access_size);
1444         return false;
1445     }
1446     return true;
1447 }
1448 
1449 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1450                                                 hwaddr addr,
1451                                                 uint64_t *pval,
1452                                                 unsigned size,
1453                                                 MemTxAttrs attrs)
1454 {
1455     *pval = 0;
1456 
1457     if (mr->ops->read) {
1458         return access_with_adjusted_size(addr, pval, size,
1459                                          mr->ops->impl.min_access_size,
1460                                          mr->ops->impl.max_access_size,
1461                                          memory_region_read_accessor,
1462                                          mr, attrs);
1463     } else {
1464         return access_with_adjusted_size(addr, pval, size,
1465                                          mr->ops->impl.min_access_size,
1466                                          mr->ops->impl.max_access_size,
1467                                          memory_region_read_with_attrs_accessor,
1468                                          mr, attrs);
1469     }
1470 }
1471 
1472 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1473                                         hwaddr addr,
1474                                         uint64_t *pval,
1475                                         MemOp op,
1476                                         MemTxAttrs attrs)
1477 {
1478     unsigned size = memop_size(op);
1479     MemTxResult r;
1480 
1481     if (mr->alias) {
1482         return memory_region_dispatch_read(mr->alias,
1483                                            mr->alias_offset + addr,
1484                                            pval, op, attrs);
1485     }
1486     if (!memory_region_access_valid(mr, addr, size, false, attrs)) {
1487         *pval = unassigned_mem_read(mr, addr, size);
1488         return MEMTX_DECODE_ERROR;
1489     }
1490 
1491     r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1492     adjust_endianness(mr, pval, op);
1493     return r;
1494 }
1495 
1496 /* Return true if an eventfd was signalled */
1497 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1498                                                     hwaddr addr,
1499                                                     uint64_t data,
1500                                                     unsigned size,
1501                                                     MemTxAttrs attrs)
1502 {
1503     MemoryRegionIoeventfd ioeventfd = {
1504         .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1505         .data = data,
1506     };
1507     unsigned i;
1508 
1509     for (i = 0; i < mr->ioeventfd_nb; i++) {
1510         ioeventfd.match_data = mr->ioeventfds[i].match_data;
1511         ioeventfd.e = mr->ioeventfds[i].e;
1512 
1513         if (memory_region_ioeventfd_equal(&ioeventfd, &mr->ioeventfds[i])) {
1514             event_notifier_set(ioeventfd.e);
1515             return true;
1516         }
1517     }
1518 
1519     return false;
1520 }
1521 
1522 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1523                                          hwaddr addr,
1524                                          uint64_t data,
1525                                          MemOp op,
1526                                          MemTxAttrs attrs)
1527 {
1528     unsigned size = memop_size(op);
1529 
1530     if (mr->alias) {
1531         return memory_region_dispatch_write(mr->alias,
1532                                             mr->alias_offset + addr,
1533                                             data, op, attrs);
1534     }
1535     if (!memory_region_access_valid(mr, addr, size, true, attrs)) {
1536         unassigned_mem_write(mr, addr, data, size);
1537         return MEMTX_DECODE_ERROR;
1538     }
1539 
1540     adjust_endianness(mr, &data, op);
1541 
1542     /*
1543      * FIXME: it's not clear why under KVM the write would be processed
1544      * directly, instead of going through eventfd.  This probably should
1545      * test "tcg_enabled() || qtest_enabled()", or should just go away.
1546      */
1547     if (!kvm_enabled() &&
1548         memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1549         return MEMTX_OK;
1550     }
1551 
1552     if (mr->ops->write) {
1553         return access_with_adjusted_size(addr, &data, size,
1554                                          mr->ops->impl.min_access_size,
1555                                          mr->ops->impl.max_access_size,
1556                                          memory_region_write_accessor, mr,
1557                                          attrs);
1558     } else {
1559         return
1560             access_with_adjusted_size(addr, &data, size,
1561                                       mr->ops->impl.min_access_size,
1562                                       mr->ops->impl.max_access_size,
1563                                       memory_region_write_with_attrs_accessor,
1564                                       mr, attrs);
1565     }
1566 }
1567 
1568 void memory_region_init_io(MemoryRegion *mr,
1569                            Object *owner,
1570                            const MemoryRegionOps *ops,
1571                            void *opaque,
1572                            const char *name,
1573                            uint64_t size)
1574 {
1575     memory_region_init(mr, owner, name, size);
1576     mr->ops = ops ? ops : &unassigned_mem_ops;
1577     mr->opaque = opaque;
1578     mr->terminates = true;
1579 }
1580 
1581 bool memory_region_init_ram_nomigrate(MemoryRegion *mr,
1582                                       Object *owner,
1583                                       const char *name,
1584                                       uint64_t size,
1585                                       Error **errp)
1586 {
1587     return memory_region_init_ram_flags_nomigrate(mr, owner, name,
1588                                                   size, 0, errp);
1589 }
1590 
1591 bool memory_region_init_ram_flags_nomigrate(MemoryRegion *mr,
1592                                             Object *owner,
1593                                             const char *name,
1594                                             uint64_t size,
1595                                             uint32_t ram_flags,
1596                                             Error **errp)
1597 {
1598     Error *err = NULL;
1599     memory_region_init(mr, owner, name, size);
1600     mr->ram = true;
1601     mr->terminates = true;
1602     mr->destructor = memory_region_destructor_ram;
1603     mr->ram_block = qemu_ram_alloc(size, ram_flags, mr, &err);
1604     if (err) {
1605         mr->size = int128_zero();
1606         object_unparent(OBJECT(mr));
1607         error_propagate(errp, err);
1608         return false;
1609     }
1610     return true;
1611 }
1612 
1613 bool memory_region_init_resizeable_ram(MemoryRegion *mr,
1614                                        Object *owner,
1615                                        const char *name,
1616                                        uint64_t size,
1617                                        uint64_t max_size,
1618                                        void (*resized)(const char*,
1619                                                        uint64_t length,
1620                                                        void *host),
1621                                        Error **errp)
1622 {
1623     Error *err = NULL;
1624     memory_region_init(mr, owner, name, size);
1625     mr->ram = true;
1626     mr->terminates = true;
1627     mr->destructor = memory_region_destructor_ram;
1628     mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1629                                               mr, &err);
1630     if (err) {
1631         mr->size = int128_zero();
1632         object_unparent(OBJECT(mr));
1633         error_propagate(errp, err);
1634         return false;
1635     }
1636     return true;
1637 }
1638 
1639 #ifdef CONFIG_POSIX
1640 bool memory_region_init_ram_from_file(MemoryRegion *mr,
1641                                       Object *owner,
1642                                       const char *name,
1643                                       uint64_t size,
1644                                       uint64_t align,
1645                                       uint32_t ram_flags,
1646                                       const char *path,
1647                                       ram_addr_t offset,
1648                                       Error **errp)
1649 {
1650     Error *err = NULL;
1651     memory_region_init(mr, owner, name, size);
1652     mr->ram = true;
1653     mr->readonly = !!(ram_flags & RAM_READONLY);
1654     mr->terminates = true;
1655     mr->destructor = memory_region_destructor_ram;
1656     mr->align = align;
1657     mr->ram_block = qemu_ram_alloc_from_file(size, mr, ram_flags, path,
1658                                              offset, &err);
1659     if (err) {
1660         mr->size = int128_zero();
1661         object_unparent(OBJECT(mr));
1662         error_propagate(errp, err);
1663         return false;
1664     }
1665     return true;
1666 }
1667 
1668 bool memory_region_init_ram_from_fd(MemoryRegion *mr,
1669                                     Object *owner,
1670                                     const char *name,
1671                                     uint64_t size,
1672                                     uint32_t ram_flags,
1673                                     int fd,
1674                                     ram_addr_t offset,
1675                                     Error **errp)
1676 {
1677     Error *err = NULL;
1678     memory_region_init(mr, owner, name, size);
1679     mr->ram = true;
1680     mr->readonly = !!(ram_flags & RAM_READONLY);
1681     mr->terminates = true;
1682     mr->destructor = memory_region_destructor_ram;
1683     mr->ram_block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, offset,
1684                                            &err);
1685     if (err) {
1686         mr->size = int128_zero();
1687         object_unparent(OBJECT(mr));
1688         error_propagate(errp, err);
1689         return false;
1690     }
1691     return true;
1692 }
1693 #endif
1694 
1695 void memory_region_init_ram_ptr(MemoryRegion *mr,
1696                                 Object *owner,
1697                                 const char *name,
1698                                 uint64_t size,
1699                                 void *ptr)
1700 {
1701     memory_region_init(mr, owner, name, size);
1702     mr->ram = true;
1703     mr->terminates = true;
1704     mr->destructor = memory_region_destructor_ram;
1705 
1706     /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL.  */
1707     assert(ptr != NULL);
1708     mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_abort);
1709 }
1710 
1711 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1712                                        Object *owner,
1713                                        const char *name,
1714                                        uint64_t size,
1715                                        void *ptr)
1716 {
1717     memory_region_init(mr, owner, name, size);
1718     mr->ram = true;
1719     mr->terminates = true;
1720     mr->ram_device = true;
1721     mr->ops = &ram_device_mem_ops;
1722     mr->opaque = mr;
1723     mr->destructor = memory_region_destructor_ram;
1724 
1725     /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL.  */
1726     assert(ptr != NULL);
1727     mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_abort);
1728 }
1729 
1730 void memory_region_init_alias(MemoryRegion *mr,
1731                               Object *owner,
1732                               const char *name,
1733                               MemoryRegion *orig,
1734                               hwaddr offset,
1735                               uint64_t size)
1736 {
1737     memory_region_init(mr, owner, name, size);
1738     mr->alias = orig;
1739     mr->alias_offset = offset;
1740 }
1741 
1742 bool memory_region_init_rom_nomigrate(MemoryRegion *mr,
1743                                       Object *owner,
1744                                       const char *name,
1745                                       uint64_t size,
1746                                       Error **errp)
1747 {
1748     if (!memory_region_init_ram_flags_nomigrate(mr, owner, name,
1749                                                 size, 0, errp)) {
1750          return false;
1751     }
1752     mr->readonly = true;
1753 
1754     return true;
1755 }
1756 
1757 bool memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1758                                              Object *owner,
1759                                              const MemoryRegionOps *ops,
1760                                              void *opaque,
1761                                              const char *name,
1762                                              uint64_t size,
1763                                              Error **errp)
1764 {
1765     Error *err = NULL;
1766     assert(ops);
1767     memory_region_init(mr, owner, name, size);
1768     mr->ops = ops;
1769     mr->opaque = opaque;
1770     mr->terminates = true;
1771     mr->rom_device = true;
1772     mr->destructor = memory_region_destructor_ram;
1773     mr->ram_block = qemu_ram_alloc(size, 0, mr, &err);
1774     if (err) {
1775         mr->size = int128_zero();
1776         object_unparent(OBJECT(mr));
1777         error_propagate(errp, err);
1778         return false;
1779     }
1780     return true;
1781 }
1782 
1783 void memory_region_init_iommu(void *_iommu_mr,
1784                               size_t instance_size,
1785                               const char *mrtypename,
1786                               Object *owner,
1787                               const char *name,
1788                               uint64_t size)
1789 {
1790     struct IOMMUMemoryRegion *iommu_mr;
1791     struct MemoryRegion *mr;
1792 
1793     object_initialize(_iommu_mr, instance_size, mrtypename);
1794     mr = MEMORY_REGION(_iommu_mr);
1795     memory_region_do_init(mr, owner, name, size);
1796     iommu_mr = IOMMU_MEMORY_REGION(mr);
1797     mr->terminates = true;  /* then re-forwards */
1798     QLIST_INIT(&iommu_mr->iommu_notify);
1799     iommu_mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
1800 }
1801 
1802 static void memory_region_finalize(Object *obj)
1803 {
1804     MemoryRegion *mr = MEMORY_REGION(obj);
1805 
1806     assert(!mr->container);
1807 
1808     /* We know the region is not visible in any address space (it
1809      * does not have a container and cannot be a root either because
1810      * it has no references, so we can blindly clear mr->enabled.
1811      * memory_region_set_enabled instead could trigger a transaction
1812      * and cause an infinite loop.
1813      */
1814     mr->enabled = false;
1815     memory_region_transaction_begin();
1816     while (!QTAILQ_EMPTY(&mr->subregions)) {
1817         MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1818         memory_region_del_subregion(mr, subregion);
1819     }
1820     memory_region_transaction_commit();
1821 
1822     mr->destructor(mr);
1823     memory_region_clear_coalescing(mr);
1824     g_free((char *)mr->name);
1825     g_free(mr->ioeventfds);
1826 }
1827 
1828 Object *memory_region_owner(MemoryRegion *mr)
1829 {
1830     Object *obj = OBJECT(mr);
1831     return obj->parent;
1832 }
1833 
1834 void memory_region_ref(MemoryRegion *mr)
1835 {
1836     /* MMIO callbacks most likely will access data that belongs
1837      * to the owner, hence the need to ref/unref the owner whenever
1838      * the memory region is in use.
1839      *
1840      * The memory region is a child of its owner.  As long as the
1841      * owner doesn't call unparent itself on the memory region,
1842      * ref-ing the owner will also keep the memory region alive.
1843      * Memory regions without an owner are supposed to never go away;
1844      * we do not ref/unref them because it slows down DMA sensibly.
1845      */
1846     if (mr && mr->owner) {
1847         object_ref(mr->owner);
1848     }
1849 }
1850 
1851 void memory_region_unref(MemoryRegion *mr)
1852 {
1853     if (mr && mr->owner) {
1854         object_unref(mr->owner);
1855     }
1856 }
1857 
1858 uint64_t memory_region_size(MemoryRegion *mr)
1859 {
1860     if (int128_eq(mr->size, int128_2_64())) {
1861         return UINT64_MAX;
1862     }
1863     return int128_get64(mr->size);
1864 }
1865 
1866 const char *memory_region_name(const MemoryRegion *mr)
1867 {
1868     if (!mr->name) {
1869         ((MemoryRegion *)mr)->name =
1870             g_strdup(object_get_canonical_path_component(OBJECT(mr)));
1871     }
1872     return mr->name;
1873 }
1874 
1875 bool memory_region_is_ram_device(MemoryRegion *mr)
1876 {
1877     return mr->ram_device;
1878 }
1879 
1880 bool memory_region_is_protected(MemoryRegion *mr)
1881 {
1882     return mr->ram && (mr->ram_block->flags & RAM_PROTECTED);
1883 }
1884 
1885 bool memory_region_has_guest_memfd(MemoryRegion *mr)
1886 {
1887     return mr->ram_block && mr->ram_block->guest_memfd >= 0;
1888 }
1889 
1890 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1891 {
1892     uint8_t mask = mr->dirty_log_mask;
1893     RAMBlock *rb = mr->ram_block;
1894 
1895     if (global_dirty_tracking && ((rb && qemu_ram_is_migratable(rb)) ||
1896                              memory_region_is_iommu(mr))) {
1897         mask |= (1 << DIRTY_MEMORY_MIGRATION);
1898     }
1899 
1900     if (tcg_enabled() && rb) {
1901         /* TCG only cares about dirty memory logging for RAM, not IOMMU.  */
1902         mask |= (1 << DIRTY_MEMORY_CODE);
1903     }
1904     return mask;
1905 }
1906 
1907 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1908 {
1909     return memory_region_get_dirty_log_mask(mr) & (1 << client);
1910 }
1911 
1912 static int memory_region_update_iommu_notify_flags(IOMMUMemoryRegion *iommu_mr,
1913                                                    Error **errp)
1914 {
1915     IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1916     IOMMUNotifier *iommu_notifier;
1917     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1918     int ret = 0;
1919 
1920     IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
1921         flags |= iommu_notifier->notifier_flags;
1922     }
1923 
1924     if (flags != iommu_mr->iommu_notify_flags && imrc->notify_flag_changed) {
1925         ret = imrc->notify_flag_changed(iommu_mr,
1926                                         iommu_mr->iommu_notify_flags,
1927                                         flags, errp);
1928     }
1929 
1930     if (!ret) {
1931         iommu_mr->iommu_notify_flags = flags;
1932     }
1933     return ret;
1934 }
1935 
1936 int memory_region_register_iommu_notifier(MemoryRegion *mr,
1937                                           IOMMUNotifier *n, Error **errp)
1938 {
1939     IOMMUMemoryRegion *iommu_mr;
1940     int ret;
1941 
1942     if (mr->alias) {
1943         return memory_region_register_iommu_notifier(mr->alias, n, errp);
1944     }
1945 
1946     /* We need to register for at least one bitfield */
1947     iommu_mr = IOMMU_MEMORY_REGION(mr);
1948     assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
1949     assert(n->start <= n->end);
1950     assert(n->iommu_idx >= 0 &&
1951            n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
1952 
1953     QLIST_INSERT_HEAD(&iommu_mr->iommu_notify, n, node);
1954     ret = memory_region_update_iommu_notify_flags(iommu_mr, errp);
1955     if (ret) {
1956         QLIST_REMOVE(n, node);
1957     }
1958     return ret;
1959 }
1960 
1961 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr)
1962 {
1963     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1964 
1965     if (imrc->get_min_page_size) {
1966         return imrc->get_min_page_size(iommu_mr);
1967     }
1968     return TARGET_PAGE_SIZE;
1969 }
1970 
1971 void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
1972 {
1973     MemoryRegion *mr = MEMORY_REGION(iommu_mr);
1974     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1975     hwaddr addr, granularity;
1976     IOMMUTLBEntry iotlb;
1977 
1978     /* If the IOMMU has its own replay callback, override */
1979     if (imrc->replay) {
1980         imrc->replay(iommu_mr, n);
1981         return;
1982     }
1983 
1984     granularity = memory_region_iommu_get_min_page_size(iommu_mr);
1985 
1986     for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1987         iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, n->iommu_idx);
1988         if (iotlb.perm != IOMMU_NONE) {
1989             n->notify(n, &iotlb);
1990         }
1991 
1992         /* if (2^64 - MR size) < granularity, it's possible to get an
1993          * infinite loop here.  This should catch such a wraparound */
1994         if ((addr + granularity) < addr) {
1995             break;
1996         }
1997     }
1998 }
1999 
2000 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
2001                                              IOMMUNotifier *n)
2002 {
2003     IOMMUMemoryRegion *iommu_mr;
2004 
2005     if (mr->alias) {
2006         memory_region_unregister_iommu_notifier(mr->alias, n);
2007         return;
2008     }
2009     QLIST_REMOVE(n, node);
2010     iommu_mr = IOMMU_MEMORY_REGION(mr);
2011     memory_region_update_iommu_notify_flags(iommu_mr, NULL);
2012 }
2013 
2014 void memory_region_notify_iommu_one(IOMMUNotifier *notifier,
2015                                     const IOMMUTLBEvent *event)
2016 {
2017     const IOMMUTLBEntry *entry = &event->entry;
2018     hwaddr entry_end = entry->iova + entry->addr_mask;
2019     IOMMUTLBEntry tmp = *entry;
2020 
2021     if (event->type == IOMMU_NOTIFIER_UNMAP) {
2022         assert(entry->perm == IOMMU_NONE);
2023     }
2024 
2025     /*
2026      * Skip the notification if the notification does not overlap
2027      * with registered range.
2028      */
2029     if (notifier->start > entry_end || notifier->end < entry->iova) {
2030         return;
2031     }
2032 
2033     if (notifier->notifier_flags & IOMMU_NOTIFIER_DEVIOTLB_UNMAP) {
2034         /* Crop (iova, addr_mask) to range */
2035         tmp.iova = MAX(tmp.iova, notifier->start);
2036         tmp.addr_mask = MIN(entry_end, notifier->end) - tmp.iova;
2037     } else {
2038         assert(entry->iova >= notifier->start && entry_end <= notifier->end);
2039     }
2040 
2041     if (event->type & notifier->notifier_flags) {
2042         notifier->notify(notifier, &tmp);
2043     }
2044 }
2045 
2046 void memory_region_unmap_iommu_notifier_range(IOMMUNotifier *notifier)
2047 {
2048     IOMMUTLBEvent event;
2049 
2050     event.type = IOMMU_NOTIFIER_UNMAP;
2051     event.entry.target_as = &address_space_memory;
2052     event.entry.iova = notifier->start;
2053     event.entry.perm = IOMMU_NONE;
2054     event.entry.addr_mask = notifier->end - notifier->start;
2055 
2056     memory_region_notify_iommu_one(notifier, &event);
2057 }
2058 
2059 void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
2060                                 int iommu_idx,
2061                                 const IOMMUTLBEvent event)
2062 {
2063     IOMMUNotifier *iommu_notifier;
2064 
2065     assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
2066 
2067     IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
2068         if (iommu_notifier->iommu_idx == iommu_idx) {
2069             memory_region_notify_iommu_one(iommu_notifier, &event);
2070         }
2071     }
2072 }
2073 
2074 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
2075                                  enum IOMMUMemoryRegionAttr attr,
2076                                  void *data)
2077 {
2078     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2079 
2080     if (!imrc->get_attr) {
2081         return -EINVAL;
2082     }
2083 
2084     return imrc->get_attr(iommu_mr, attr, data);
2085 }
2086 
2087 int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
2088                                        MemTxAttrs attrs)
2089 {
2090     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2091 
2092     if (!imrc->attrs_to_index) {
2093         return 0;
2094     }
2095 
2096     return imrc->attrs_to_index(iommu_mr, attrs);
2097 }
2098 
2099 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr)
2100 {
2101     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2102 
2103     if (!imrc->num_indexes) {
2104         return 1;
2105     }
2106 
2107     return imrc->num_indexes(iommu_mr);
2108 }
2109 
2110 RamDiscardManager *memory_region_get_ram_discard_manager(MemoryRegion *mr)
2111 {
2112     if (!memory_region_is_ram(mr)) {
2113         return NULL;
2114     }
2115     return mr->rdm;
2116 }
2117 
2118 void memory_region_set_ram_discard_manager(MemoryRegion *mr,
2119                                            RamDiscardManager *rdm)
2120 {
2121     g_assert(memory_region_is_ram(mr));
2122     g_assert(!rdm || !mr->rdm);
2123     mr->rdm = rdm;
2124 }
2125 
2126 uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,
2127                                                  const MemoryRegion *mr)
2128 {
2129     RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2130 
2131     g_assert(rdmc->get_min_granularity);
2132     return rdmc->get_min_granularity(rdm, mr);
2133 }
2134 
2135 bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
2136                                       const MemoryRegionSection *section)
2137 {
2138     RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2139 
2140     g_assert(rdmc->is_populated);
2141     return rdmc->is_populated(rdm, section);
2142 }
2143 
2144 int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
2145                                          MemoryRegionSection *section,
2146                                          ReplayRamPopulate replay_fn,
2147                                          void *opaque)
2148 {
2149     RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2150 
2151     g_assert(rdmc->replay_populated);
2152     return rdmc->replay_populated(rdm, section, replay_fn, opaque);
2153 }
2154 
2155 void ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
2156                                           MemoryRegionSection *section,
2157                                           ReplayRamDiscard replay_fn,
2158                                           void *opaque)
2159 {
2160     RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2161 
2162     g_assert(rdmc->replay_discarded);
2163     rdmc->replay_discarded(rdm, section, replay_fn, opaque);
2164 }
2165 
2166 void ram_discard_manager_register_listener(RamDiscardManager *rdm,
2167                                            RamDiscardListener *rdl,
2168                                            MemoryRegionSection *section)
2169 {
2170     RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2171 
2172     g_assert(rdmc->register_listener);
2173     rdmc->register_listener(rdm, rdl, section);
2174 }
2175 
2176 void ram_discard_manager_unregister_listener(RamDiscardManager *rdm,
2177                                              RamDiscardListener *rdl)
2178 {
2179     RamDiscardManagerClass *rdmc = RAM_DISCARD_MANAGER_GET_CLASS(rdm);
2180 
2181     g_assert(rdmc->unregister_listener);
2182     rdmc->unregister_listener(rdm, rdl);
2183 }
2184 
2185 /* Called with rcu_read_lock held.  */
2186 bool memory_get_xlat_addr(IOMMUTLBEntry *iotlb, void **vaddr,
2187                           ram_addr_t *ram_addr, bool *read_only,
2188                           bool *mr_has_discard_manager, Error **errp)
2189 {
2190     MemoryRegion *mr;
2191     hwaddr xlat;
2192     hwaddr len = iotlb->addr_mask + 1;
2193     bool writable = iotlb->perm & IOMMU_WO;
2194 
2195     if (mr_has_discard_manager) {
2196         *mr_has_discard_manager = false;
2197     }
2198     /*
2199      * The IOMMU TLB entry we have just covers translation through
2200      * this IOMMU to its immediate target.  We need to translate
2201      * it the rest of the way through to memory.
2202      */
2203     mr = address_space_translate(&address_space_memory, iotlb->translated_addr,
2204                                  &xlat, &len, writable, MEMTXATTRS_UNSPECIFIED);
2205     if (!memory_region_is_ram(mr)) {
2206         error_setg(errp, "iommu map to non memory area %" HWADDR_PRIx "", xlat);
2207         return false;
2208     } else if (memory_region_has_ram_discard_manager(mr)) {
2209         RamDiscardManager *rdm = memory_region_get_ram_discard_manager(mr);
2210         MemoryRegionSection tmp = {
2211             .mr = mr,
2212             .offset_within_region = xlat,
2213             .size = int128_make64(len),
2214         };
2215         if (mr_has_discard_manager) {
2216             *mr_has_discard_manager = true;
2217         }
2218         /*
2219          * Malicious VMs can map memory into the IOMMU, which is expected
2220          * to remain discarded. vfio will pin all pages, populating memory.
2221          * Disallow that. vmstate priorities make sure any RamDiscardManager
2222          * were already restored before IOMMUs are restored.
2223          */
2224         if (!ram_discard_manager_is_populated(rdm, &tmp)) {
2225             error_setg(errp, "iommu map to discarded memory (e.g., unplugged"
2226                          " via virtio-mem): %" HWADDR_PRIx "",
2227                          iotlb->translated_addr);
2228             return false;
2229         }
2230     }
2231 
2232     /*
2233      * Translation truncates length to the IOMMU page size,
2234      * check that it did not truncate too much.
2235      */
2236     if (len & iotlb->addr_mask) {
2237         error_setg(errp, "iommu has granularity incompatible with target AS");
2238         return false;
2239     }
2240 
2241     if (vaddr) {
2242         *vaddr = memory_region_get_ram_ptr(mr) + xlat;
2243     }
2244 
2245     if (ram_addr) {
2246         *ram_addr = memory_region_get_ram_addr(mr) + xlat;
2247     }
2248 
2249     if (read_only) {
2250         *read_only = !writable || mr->readonly;
2251     }
2252 
2253     return true;
2254 }
2255 
2256 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
2257 {
2258     uint8_t mask = 1 << client;
2259     uint8_t old_logging;
2260 
2261     assert(client == DIRTY_MEMORY_VGA);
2262     old_logging = mr->vga_logging_count;
2263     mr->vga_logging_count += log ? 1 : -1;
2264     if (!!old_logging == !!mr->vga_logging_count) {
2265         return;
2266     }
2267 
2268     memory_region_transaction_begin();
2269     mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
2270     memory_region_update_pending |= mr->enabled;
2271     memory_region_transaction_commit();
2272 }
2273 
2274 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
2275                              hwaddr size)
2276 {
2277     assert(mr->ram_block);
2278     cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
2279                                         size,
2280                                         memory_region_get_dirty_log_mask(mr));
2281 }
2282 
2283 /*
2284  * If memory region `mr' is NULL, do global sync.  Otherwise, sync
2285  * dirty bitmap for the specified memory region.
2286  */
2287 static void memory_region_sync_dirty_bitmap(MemoryRegion *mr, bool last_stage)
2288 {
2289     MemoryListener *listener;
2290     AddressSpace *as;
2291     FlatView *view;
2292     FlatRange *fr;
2293 
2294     /* If the same address space has multiple log_sync listeners, we
2295      * visit that address space's FlatView multiple times.  But because
2296      * log_sync listeners are rare, it's still cheaper than walking each
2297      * address space once.
2298      */
2299     QTAILQ_FOREACH(listener, &memory_listeners, link) {
2300         if (listener->log_sync) {
2301             as = listener->address_space;
2302             view = address_space_get_flatview(as);
2303             FOR_EACH_FLAT_RANGE(fr, view) {
2304                 if (fr->dirty_log_mask && (!mr || fr->mr == mr)) {
2305                     MemoryRegionSection mrs = section_from_flat_range(fr, view);
2306                     listener->log_sync(listener, &mrs);
2307                 }
2308             }
2309             flatview_unref(view);
2310             trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 0);
2311         } else if (listener->log_sync_global) {
2312             /*
2313              * No matter whether MR is specified, what we can do here
2314              * is to do a global sync, because we are not capable to
2315              * sync in a finer granularity.
2316              */
2317             listener->log_sync_global(listener, last_stage);
2318             trace_memory_region_sync_dirty(mr ? mr->name : "(all)", listener->name, 1);
2319         }
2320     }
2321 }
2322 
2323 void memory_region_clear_dirty_bitmap(MemoryRegion *mr, hwaddr start,
2324                                       hwaddr len)
2325 {
2326     MemoryRegionSection mrs;
2327     MemoryListener *listener;
2328     AddressSpace *as;
2329     FlatView *view;
2330     FlatRange *fr;
2331     hwaddr sec_start, sec_end, sec_size;
2332 
2333     QTAILQ_FOREACH(listener, &memory_listeners, link) {
2334         if (!listener->log_clear) {
2335             continue;
2336         }
2337         as = listener->address_space;
2338         view = address_space_get_flatview(as);
2339         FOR_EACH_FLAT_RANGE(fr, view) {
2340             if (!fr->dirty_log_mask || fr->mr != mr) {
2341                 /*
2342                  * Clear dirty bitmap operation only applies to those
2343                  * regions whose dirty logging is at least enabled
2344                  */
2345                 continue;
2346             }
2347 
2348             mrs = section_from_flat_range(fr, view);
2349 
2350             sec_start = MAX(mrs.offset_within_region, start);
2351             sec_end = mrs.offset_within_region + int128_get64(mrs.size);
2352             sec_end = MIN(sec_end, start + len);
2353 
2354             if (sec_start >= sec_end) {
2355                 /*
2356                  * If this memory region section has no intersection
2357                  * with the requested range, skip.
2358                  */
2359                 continue;
2360             }
2361 
2362             /* Valid case; shrink the section if needed */
2363             mrs.offset_within_address_space +=
2364                 sec_start - mrs.offset_within_region;
2365             mrs.offset_within_region = sec_start;
2366             sec_size = sec_end - sec_start;
2367             mrs.size = int128_make64(sec_size);
2368             listener->log_clear(listener, &mrs);
2369         }
2370         flatview_unref(view);
2371     }
2372 }
2373 
2374 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
2375                                                             hwaddr addr,
2376                                                             hwaddr size,
2377                                                             unsigned client)
2378 {
2379     DirtyBitmapSnapshot *snapshot;
2380     assert(mr->ram_block);
2381     memory_region_sync_dirty_bitmap(mr, false);
2382     snapshot = cpu_physical_memory_snapshot_and_clear_dirty(mr, addr, size, client);
2383     memory_global_after_dirty_log_sync();
2384     return snapshot;
2385 }
2386 
2387 bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
2388                                       hwaddr addr, hwaddr size)
2389 {
2390     assert(mr->ram_block);
2391     return cpu_physical_memory_snapshot_get_dirty(snap,
2392                 memory_region_get_ram_addr(mr) + addr, size);
2393 }
2394 
2395 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
2396 {
2397     if (mr->readonly != readonly) {
2398         memory_region_transaction_begin();
2399         mr->readonly = readonly;
2400         memory_region_update_pending |= mr->enabled;
2401         memory_region_transaction_commit();
2402     }
2403 }
2404 
2405 void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile)
2406 {
2407     if (mr->nonvolatile != nonvolatile) {
2408         memory_region_transaction_begin();
2409         mr->nonvolatile = nonvolatile;
2410         memory_region_update_pending |= mr->enabled;
2411         memory_region_transaction_commit();
2412     }
2413 }
2414 
2415 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
2416 {
2417     if (mr->romd_mode != romd_mode) {
2418         memory_region_transaction_begin();
2419         mr->romd_mode = romd_mode;
2420         memory_region_update_pending |= mr->enabled;
2421         memory_region_transaction_commit();
2422     }
2423 }
2424 
2425 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
2426                                hwaddr size, unsigned client)
2427 {
2428     assert(mr->ram_block);
2429     cpu_physical_memory_test_and_clear_dirty(
2430         memory_region_get_ram_addr(mr) + addr, size, client);
2431 }
2432 
2433 int memory_region_get_fd(MemoryRegion *mr)
2434 {
2435     RCU_READ_LOCK_GUARD();
2436     while (mr->alias) {
2437         mr = mr->alias;
2438     }
2439     return mr->ram_block->fd;
2440 }
2441 
2442 void *memory_region_get_ram_ptr(MemoryRegion *mr)
2443 {
2444     uint64_t offset = 0;
2445 
2446     RCU_READ_LOCK_GUARD();
2447     while (mr->alias) {
2448         offset += mr->alias_offset;
2449         mr = mr->alias;
2450     }
2451     assert(mr->ram_block);
2452     return qemu_map_ram_ptr(mr->ram_block, offset);
2453 }
2454 
2455 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
2456 {
2457     RAMBlock *block;
2458 
2459     block = qemu_ram_block_from_host(ptr, false, offset);
2460     if (!block) {
2461         return NULL;
2462     }
2463 
2464     return block->mr;
2465 }
2466 
2467 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
2468 {
2469     return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
2470 }
2471 
2472 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
2473 {
2474     assert(mr->ram_block);
2475 
2476     qemu_ram_resize(mr->ram_block, newsize, errp);
2477 }
2478 
2479 void memory_region_msync(MemoryRegion *mr, hwaddr addr, hwaddr size)
2480 {
2481     if (mr->ram_block) {
2482         qemu_ram_msync(mr->ram_block, addr, size);
2483     }
2484 }
2485 
2486 void memory_region_writeback(MemoryRegion *mr, hwaddr addr, hwaddr size)
2487 {
2488     /*
2489      * Might be extended case needed to cover
2490      * different types of memory regions
2491      */
2492     if (mr->dirty_log_mask) {
2493         memory_region_msync(mr, addr, size);
2494     }
2495 }
2496 
2497 /*
2498  * Call proper memory listeners about the change on the newly
2499  * added/removed CoalescedMemoryRange.
2500  */
2501 static void memory_region_update_coalesced_range(MemoryRegion *mr,
2502                                                  CoalescedMemoryRange *cmr,
2503                                                  bool add)
2504 {
2505     AddressSpace *as;
2506     FlatView *view;
2507     FlatRange *fr;
2508 
2509     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2510         view = address_space_get_flatview(as);
2511         FOR_EACH_FLAT_RANGE(fr, view) {
2512             if (fr->mr == mr) {
2513                 flat_range_coalesced_io_notify(fr, as, cmr, add);
2514             }
2515         }
2516         flatview_unref(view);
2517     }
2518 }
2519 
2520 void memory_region_set_coalescing(MemoryRegion *mr)
2521 {
2522     memory_region_clear_coalescing(mr);
2523     memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
2524 }
2525 
2526 void memory_region_add_coalescing(MemoryRegion *mr,
2527                                   hwaddr offset,
2528                                   uint64_t size)
2529 {
2530     CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
2531 
2532     cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
2533     QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
2534     memory_region_update_coalesced_range(mr, cmr, true);
2535     memory_region_set_flush_coalesced(mr);
2536 }
2537 
2538 void memory_region_clear_coalescing(MemoryRegion *mr)
2539 {
2540     CoalescedMemoryRange *cmr;
2541 
2542     if (QTAILQ_EMPTY(&mr->coalesced)) {
2543         return;
2544     }
2545 
2546     qemu_flush_coalesced_mmio_buffer();
2547     mr->flush_coalesced_mmio = false;
2548 
2549     while (!QTAILQ_EMPTY(&mr->coalesced)) {
2550         cmr = QTAILQ_FIRST(&mr->coalesced);
2551         QTAILQ_REMOVE(&mr->coalesced, cmr, link);
2552         memory_region_update_coalesced_range(mr, cmr, false);
2553         g_free(cmr);
2554     }
2555 }
2556 
2557 void memory_region_set_flush_coalesced(MemoryRegion *mr)
2558 {
2559     mr->flush_coalesced_mmio = true;
2560 }
2561 
2562 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
2563 {
2564     qemu_flush_coalesced_mmio_buffer();
2565     if (QTAILQ_EMPTY(&mr->coalesced)) {
2566         mr->flush_coalesced_mmio = false;
2567     }
2568 }
2569 
2570 void memory_region_add_eventfd(MemoryRegion *mr,
2571                                hwaddr addr,
2572                                unsigned size,
2573                                bool match_data,
2574                                uint64_t data,
2575                                EventNotifier *e)
2576 {
2577     MemoryRegionIoeventfd mrfd = {
2578         .addr.start = int128_make64(addr),
2579         .addr.size = int128_make64(size),
2580         .match_data = match_data,
2581         .data = data,
2582         .e = e,
2583     };
2584     unsigned i;
2585 
2586     if (size) {
2587         adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2588     }
2589     memory_region_transaction_begin();
2590     for (i = 0; i < mr->ioeventfd_nb; ++i) {
2591         if (memory_region_ioeventfd_before(&mrfd, &mr->ioeventfds[i])) {
2592             break;
2593         }
2594     }
2595     ++mr->ioeventfd_nb;
2596     mr->ioeventfds = g_realloc(mr->ioeventfds,
2597                                   sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2598     memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2599             sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2600     mr->ioeventfds[i] = mrfd;
2601     ioeventfd_update_pending |= mr->enabled;
2602     memory_region_transaction_commit();
2603 }
2604 
2605 void memory_region_del_eventfd(MemoryRegion *mr,
2606                                hwaddr addr,
2607                                unsigned size,
2608                                bool match_data,
2609                                uint64_t data,
2610                                EventNotifier *e)
2611 {
2612     MemoryRegionIoeventfd mrfd = {
2613         .addr.start = int128_make64(addr),
2614         .addr.size = int128_make64(size),
2615         .match_data = match_data,
2616         .data = data,
2617         .e = e,
2618     };
2619     unsigned i;
2620 
2621     if (size) {
2622         adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2623     }
2624     memory_region_transaction_begin();
2625     for (i = 0; i < mr->ioeventfd_nb; ++i) {
2626         if (memory_region_ioeventfd_equal(&mrfd, &mr->ioeventfds[i])) {
2627             break;
2628         }
2629     }
2630     assert(i != mr->ioeventfd_nb);
2631     memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2632             sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2633     --mr->ioeventfd_nb;
2634     mr->ioeventfds = g_realloc(mr->ioeventfds,
2635                                   sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
2636     ioeventfd_update_pending |= mr->enabled;
2637     memory_region_transaction_commit();
2638 }
2639 
2640 static void memory_region_update_container_subregions(MemoryRegion *subregion)
2641 {
2642     MemoryRegion *mr = subregion->container;
2643     MemoryRegion *other;
2644 
2645     memory_region_transaction_begin();
2646 
2647     memory_region_ref(subregion);
2648     QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2649         if (subregion->priority >= other->priority) {
2650             QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2651             goto done;
2652         }
2653     }
2654     QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2655 done:
2656     memory_region_update_pending |= mr->enabled && subregion->enabled;
2657     memory_region_transaction_commit();
2658 }
2659 
2660 static void memory_region_add_subregion_common(MemoryRegion *mr,
2661                                                hwaddr offset,
2662                                                MemoryRegion *subregion)
2663 {
2664     MemoryRegion *alias;
2665 
2666     assert(!subregion->container);
2667     subregion->container = mr;
2668     for (alias = subregion->alias; alias; alias = alias->alias) {
2669         alias->mapped_via_alias++;
2670     }
2671     subregion->addr = offset;
2672     memory_region_update_container_subregions(subregion);
2673 }
2674 
2675 void memory_region_add_subregion(MemoryRegion *mr,
2676                                  hwaddr offset,
2677                                  MemoryRegion *subregion)
2678 {
2679     subregion->priority = 0;
2680     memory_region_add_subregion_common(mr, offset, subregion);
2681 }
2682 
2683 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2684                                          hwaddr offset,
2685                                          MemoryRegion *subregion,
2686                                          int priority)
2687 {
2688     subregion->priority = priority;
2689     memory_region_add_subregion_common(mr, offset, subregion);
2690 }
2691 
2692 void memory_region_del_subregion(MemoryRegion *mr,
2693                                  MemoryRegion *subregion)
2694 {
2695     MemoryRegion *alias;
2696 
2697     memory_region_transaction_begin();
2698     assert(subregion->container == mr);
2699     subregion->container = NULL;
2700     for (alias = subregion->alias; alias; alias = alias->alias) {
2701         alias->mapped_via_alias--;
2702         assert(alias->mapped_via_alias >= 0);
2703     }
2704     QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
2705     memory_region_unref(subregion);
2706     memory_region_update_pending |= mr->enabled && subregion->enabled;
2707     memory_region_transaction_commit();
2708 }
2709 
2710 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2711 {
2712     if (enabled == mr->enabled) {
2713         return;
2714     }
2715     memory_region_transaction_begin();
2716     mr->enabled = enabled;
2717     memory_region_update_pending = true;
2718     memory_region_transaction_commit();
2719 }
2720 
2721 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2722 {
2723     Int128 s = int128_make64(size);
2724 
2725     if (size == UINT64_MAX) {
2726         s = int128_2_64();
2727     }
2728     if (int128_eq(s, mr->size)) {
2729         return;
2730     }
2731     memory_region_transaction_begin();
2732     mr->size = s;
2733     memory_region_update_pending = true;
2734     memory_region_transaction_commit();
2735 }
2736 
2737 static void memory_region_readd_subregion(MemoryRegion *mr)
2738 {
2739     MemoryRegion *container = mr->container;
2740 
2741     if (container) {
2742         memory_region_transaction_begin();
2743         memory_region_ref(mr);
2744         memory_region_del_subregion(container, mr);
2745         memory_region_add_subregion_common(container, mr->addr, mr);
2746         memory_region_unref(mr);
2747         memory_region_transaction_commit();
2748     }
2749 }
2750 
2751 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2752 {
2753     if (addr != mr->addr) {
2754         mr->addr = addr;
2755         memory_region_readd_subregion(mr);
2756     }
2757 }
2758 
2759 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
2760 {
2761     assert(mr->alias);
2762 
2763     if (offset == mr->alias_offset) {
2764         return;
2765     }
2766 
2767     memory_region_transaction_begin();
2768     mr->alias_offset = offset;
2769     memory_region_update_pending |= mr->enabled;
2770     memory_region_transaction_commit();
2771 }
2772 
2773 void memory_region_set_unmergeable(MemoryRegion *mr, bool unmergeable)
2774 {
2775     if (unmergeable == mr->unmergeable) {
2776         return;
2777     }
2778 
2779     memory_region_transaction_begin();
2780     mr->unmergeable = unmergeable;
2781     memory_region_update_pending |= mr->enabled;
2782     memory_region_transaction_commit();
2783 }
2784 
2785 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2786 {
2787     return mr->align;
2788 }
2789 
2790 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2791 {
2792     const AddrRange *addr = addr_;
2793     const FlatRange *fr = fr_;
2794 
2795     if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2796         return -1;
2797     } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2798         return 1;
2799     }
2800     return 0;
2801 }
2802 
2803 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
2804 {
2805     return bsearch(&addr, view->ranges, view->nr,
2806                    sizeof(FlatRange), cmp_flatrange_addr);
2807 }
2808 
2809 bool memory_region_is_mapped(MemoryRegion *mr)
2810 {
2811     return !!mr->container || mr->mapped_via_alias;
2812 }
2813 
2814 /* Same as memory_region_find, but it does not add a reference to the
2815  * returned region.  It must be called from an RCU critical section.
2816  */
2817 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2818                                                   hwaddr addr, uint64_t size)
2819 {
2820     MemoryRegionSection ret = { .mr = NULL };
2821     MemoryRegion *root;
2822     AddressSpace *as;
2823     AddrRange range;
2824     FlatView *view;
2825     FlatRange *fr;
2826 
2827     addr += mr->addr;
2828     for (root = mr; root->container; ) {
2829         root = root->container;
2830         addr += root->addr;
2831     }
2832 
2833     as = memory_region_to_address_space(root);
2834     if (!as) {
2835         return ret;
2836     }
2837     range = addrrange_make(int128_make64(addr), int128_make64(size));
2838 
2839     view = address_space_to_flatview(as);
2840     fr = flatview_lookup(view, range);
2841     if (!fr) {
2842         return ret;
2843     }
2844 
2845     while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2846         --fr;
2847     }
2848 
2849     ret.mr = fr->mr;
2850     ret.fv = view;
2851     range = addrrange_intersection(range, fr->addr);
2852     ret.offset_within_region = fr->offset_in_region;
2853     ret.offset_within_region += int128_get64(int128_sub(range.start,
2854                                                         fr->addr.start));
2855     ret.size = range.size;
2856     ret.offset_within_address_space = int128_get64(range.start);
2857     ret.readonly = fr->readonly;
2858     ret.nonvolatile = fr->nonvolatile;
2859     return ret;
2860 }
2861 
2862 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2863                                        hwaddr addr, uint64_t size)
2864 {
2865     MemoryRegionSection ret;
2866     RCU_READ_LOCK_GUARD();
2867     ret = memory_region_find_rcu(mr, addr, size);
2868     if (ret.mr) {
2869         memory_region_ref(ret.mr);
2870     }
2871     return ret;
2872 }
2873 
2874 MemoryRegionSection *memory_region_section_new_copy(MemoryRegionSection *s)
2875 {
2876     MemoryRegionSection *tmp = g_new(MemoryRegionSection, 1);
2877 
2878     *tmp = *s;
2879     if (tmp->mr) {
2880         memory_region_ref(tmp->mr);
2881     }
2882     if (tmp->fv) {
2883         bool ret  = flatview_ref(tmp->fv);
2884 
2885         g_assert(ret);
2886     }
2887     return tmp;
2888 }
2889 
2890 void memory_region_section_free_copy(MemoryRegionSection *s)
2891 {
2892     if (s->fv) {
2893         flatview_unref(s->fv);
2894     }
2895     if (s->mr) {
2896         memory_region_unref(s->mr);
2897     }
2898     g_free(s);
2899 }
2900 
2901 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2902 {
2903     MemoryRegion *mr;
2904 
2905     RCU_READ_LOCK_GUARD();
2906     mr = memory_region_find_rcu(container, addr, 1).mr;
2907     return mr && mr != container;
2908 }
2909 
2910 void memory_global_dirty_log_sync(bool last_stage)
2911 {
2912     memory_region_sync_dirty_bitmap(NULL, last_stage);
2913 }
2914 
2915 void memory_global_after_dirty_log_sync(void)
2916 {
2917     MEMORY_LISTENER_CALL_GLOBAL(log_global_after_sync, Forward);
2918 }
2919 
2920 /*
2921  * Dirty track stop flags that are postponed due to VM being stopped.  Should
2922  * only be used within vmstate_change hook.
2923  */
2924 static unsigned int postponed_stop_flags;
2925 static VMChangeStateEntry *vmstate_change;
2926 static void memory_global_dirty_log_stop_postponed_run(void);
2927 
2928 static bool memory_global_dirty_log_do_start(Error **errp)
2929 {
2930     MemoryListener *listener;
2931 
2932     QTAILQ_FOREACH(listener, &memory_listeners, link) {
2933         if (listener->log_global_start) {
2934             if (!listener->log_global_start(listener, errp)) {
2935                 goto err;
2936             }
2937         }
2938     }
2939     return true;
2940 
2941 err:
2942     while ((listener = QTAILQ_PREV(listener, link)) != NULL) {
2943         if (listener->log_global_stop) {
2944             listener->log_global_stop(listener);
2945         }
2946     }
2947 
2948     return false;
2949 }
2950 
2951 bool memory_global_dirty_log_start(unsigned int flags, Error **errp)
2952 {
2953     unsigned int old_flags;
2954 
2955     assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2956 
2957     if (vmstate_change) {
2958         /* If there is postponed stop(), operate on it first */
2959         postponed_stop_flags &= ~flags;
2960         memory_global_dirty_log_stop_postponed_run();
2961     }
2962 
2963     flags &= ~global_dirty_tracking;
2964     if (!flags) {
2965         return true;
2966     }
2967 
2968     old_flags = global_dirty_tracking;
2969     global_dirty_tracking |= flags;
2970     trace_global_dirty_changed(global_dirty_tracking);
2971 
2972     if (!old_flags) {
2973         if (!memory_global_dirty_log_do_start(errp)) {
2974             global_dirty_tracking &= ~flags;
2975             trace_global_dirty_changed(global_dirty_tracking);
2976             return false;
2977         }
2978 
2979         memory_region_transaction_begin();
2980         memory_region_update_pending = true;
2981         memory_region_transaction_commit();
2982     }
2983     return true;
2984 }
2985 
2986 static void memory_global_dirty_log_do_stop(unsigned int flags)
2987 {
2988     assert(flags && !(flags & (~GLOBAL_DIRTY_MASK)));
2989     assert((global_dirty_tracking & flags) == flags);
2990     global_dirty_tracking &= ~flags;
2991 
2992     trace_global_dirty_changed(global_dirty_tracking);
2993 
2994     if (!global_dirty_tracking) {
2995         memory_region_transaction_begin();
2996         memory_region_update_pending = true;
2997         memory_region_transaction_commit();
2998         MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2999     }
3000 }
3001 
3002 /*
3003  * Execute the postponed dirty log stop operations if there is, then reset
3004  * everything (including the flags and the vmstate change hook).
3005  */
3006 static void memory_global_dirty_log_stop_postponed_run(void)
3007 {
3008     /* This must be called with the vmstate handler registered */
3009     assert(vmstate_change);
3010 
3011     /* Note: postponed_stop_flags can be cleared in log start routine */
3012     if (postponed_stop_flags) {
3013         memory_global_dirty_log_do_stop(postponed_stop_flags);
3014         postponed_stop_flags = 0;
3015     }
3016 
3017     qemu_del_vm_change_state_handler(vmstate_change);
3018     vmstate_change = NULL;
3019 }
3020 
3021 static void memory_vm_change_state_handler(void *opaque, bool running,
3022                                            RunState state)
3023 {
3024     if (running) {
3025         memory_global_dirty_log_stop_postponed_run();
3026     }
3027 }
3028 
3029 void memory_global_dirty_log_stop(unsigned int flags)
3030 {
3031     if (!runstate_is_running()) {
3032         /* Postpone the dirty log stop, e.g., to when VM starts again */
3033         if (vmstate_change) {
3034             /* Batch with previous postponed flags */
3035             postponed_stop_flags |= flags;
3036         } else {
3037             postponed_stop_flags = flags;
3038             vmstate_change = qemu_add_vm_change_state_handler(
3039                 memory_vm_change_state_handler, NULL);
3040         }
3041         return;
3042     }
3043 
3044     memory_global_dirty_log_do_stop(flags);
3045 }
3046 
3047 static void listener_add_address_space(MemoryListener *listener,
3048                                        AddressSpace *as)
3049 {
3050     unsigned i;
3051     FlatView *view;
3052     FlatRange *fr;
3053     MemoryRegionIoeventfd *fd;
3054 
3055     if (listener->begin) {
3056         listener->begin(listener);
3057     }
3058     if (global_dirty_tracking) {
3059         /*
3060          * Currently only VFIO can fail log_global_start(), and it's not
3061          * yet allowed to hotplug any PCI device during migration. So this
3062          * should never fail when invoked, guard it with error_abort.  If
3063          * it can start to fail in the future, we need to be able to fail
3064          * the whole listener_add_address_space() and its callers.
3065          */
3066         if (listener->log_global_start) {
3067             listener->log_global_start(listener, &error_abort);
3068         }
3069     }
3070 
3071     view = address_space_get_flatview(as);
3072     FOR_EACH_FLAT_RANGE(fr, view) {
3073         MemoryRegionSection section = section_from_flat_range(fr, view);
3074 
3075         if (listener->region_add) {
3076             listener->region_add(listener, &section);
3077         }
3078 
3079         /* send coalesced io add notifications */
3080         flat_range_coalesced_io_notify_listener_add_del(fr, &section,
3081                                                         listener, as, true);
3082 
3083         if (fr->dirty_log_mask && listener->log_start) {
3084             listener->log_start(listener, &section, 0, fr->dirty_log_mask);
3085         }
3086     }
3087 
3088     /*
3089      * register all eventfds for this address space for the newly registered
3090      * listener.
3091      */
3092     for (i = 0; i < as->ioeventfd_nb; i++) {
3093         fd = &as->ioeventfds[i];
3094         MemoryRegionSection section = (MemoryRegionSection) {
3095             .fv = view,
3096             .offset_within_address_space = int128_get64(fd->addr.start),
3097             .size = fd->addr.size,
3098         };
3099 
3100         if (listener->eventfd_add) {
3101             listener->eventfd_add(listener, &section,
3102                                   fd->match_data, fd->data, fd->e);
3103         }
3104     }
3105 
3106     if (listener->commit) {
3107         listener->commit(listener);
3108     }
3109     flatview_unref(view);
3110 }
3111 
3112 static void listener_del_address_space(MemoryListener *listener,
3113                                        AddressSpace *as)
3114 {
3115     unsigned i;
3116     FlatView *view;
3117     FlatRange *fr;
3118     MemoryRegionIoeventfd *fd;
3119 
3120     if (listener->begin) {
3121         listener->begin(listener);
3122     }
3123     view = address_space_get_flatview(as);
3124     FOR_EACH_FLAT_RANGE(fr, view) {
3125         MemoryRegionSection section = section_from_flat_range(fr, view);
3126 
3127         if (fr->dirty_log_mask && listener->log_stop) {
3128             listener->log_stop(listener, &section, fr->dirty_log_mask, 0);
3129         }
3130 
3131         /* send coalesced io del notifications */
3132         flat_range_coalesced_io_notify_listener_add_del(fr, &section,
3133                                                         listener, as, false);
3134         if (listener->region_del) {
3135             listener->region_del(listener, &section);
3136         }
3137     }
3138 
3139     /*
3140      * de-register all eventfds for this address space for the current
3141      * listener.
3142      */
3143     for (i = 0; i < as->ioeventfd_nb; i++) {
3144         fd = &as->ioeventfds[i];
3145         MemoryRegionSection section = (MemoryRegionSection) {
3146             .fv = view,
3147             .offset_within_address_space = int128_get64(fd->addr.start),
3148             .size = fd->addr.size,
3149         };
3150 
3151         if (listener->eventfd_del) {
3152             listener->eventfd_del(listener, &section,
3153                                   fd->match_data, fd->data, fd->e);
3154         }
3155     }
3156 
3157     if (listener->commit) {
3158         listener->commit(listener);
3159     }
3160     flatview_unref(view);
3161 }
3162 
3163 void memory_listener_register(MemoryListener *listener, AddressSpace *as)
3164 {
3165     MemoryListener *other = NULL;
3166 
3167     /* Only one of them can be defined for a listener */
3168     assert(!(listener->log_sync && listener->log_sync_global));
3169 
3170     listener->address_space = as;
3171     if (QTAILQ_EMPTY(&memory_listeners)
3172         || listener->priority >= QTAILQ_LAST(&memory_listeners)->priority) {
3173         QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
3174     } else {
3175         QTAILQ_FOREACH(other, &memory_listeners, link) {
3176             if (listener->priority < other->priority) {
3177                 break;
3178             }
3179         }
3180         QTAILQ_INSERT_BEFORE(other, listener, link);
3181     }
3182 
3183     if (QTAILQ_EMPTY(&as->listeners)
3184         || listener->priority >= QTAILQ_LAST(&as->listeners)->priority) {
3185         QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
3186     } else {
3187         QTAILQ_FOREACH(other, &as->listeners, link_as) {
3188             if (listener->priority < other->priority) {
3189                 break;
3190             }
3191         }
3192         QTAILQ_INSERT_BEFORE(other, listener, link_as);
3193     }
3194 
3195     listener_add_address_space(listener, as);
3196 
3197     if (listener->eventfd_add || listener->eventfd_del) {
3198         as->ioeventfd_notifiers++;
3199     }
3200 }
3201 
3202 void memory_listener_unregister(MemoryListener *listener)
3203 {
3204     if (!listener->address_space) {
3205         return;
3206     }
3207 
3208     if (listener->eventfd_add || listener->eventfd_del) {
3209         listener->address_space->ioeventfd_notifiers--;
3210     }
3211 
3212     listener_del_address_space(listener, listener->address_space);
3213     QTAILQ_REMOVE(&memory_listeners, listener, link);
3214     QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
3215     listener->address_space = NULL;
3216 }
3217 
3218 void address_space_remove_listeners(AddressSpace *as)
3219 {
3220     while (!QTAILQ_EMPTY(&as->listeners)) {
3221         memory_listener_unregister(QTAILQ_FIRST(&as->listeners));
3222     }
3223 }
3224 
3225 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
3226 {
3227     memory_region_ref(root);
3228     as->root = root;
3229     as->current_map = NULL;
3230     as->ioeventfd_nb = 0;
3231     as->ioeventfds = NULL;
3232     QTAILQ_INIT(&as->listeners);
3233     QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
3234     as->max_bounce_buffer_size = DEFAULT_MAX_BOUNCE_BUFFER_SIZE;
3235     as->bounce_buffer_size = 0;
3236     qemu_mutex_init(&as->map_client_list_lock);
3237     QLIST_INIT(&as->map_client_list);
3238     as->name = g_strdup(name ? name : "anonymous");
3239     address_space_update_topology(as);
3240     address_space_update_ioeventfds(as);
3241 }
3242 
3243 static void do_address_space_destroy(AddressSpace *as)
3244 {
3245     assert(qatomic_read(&as->bounce_buffer_size) == 0);
3246     assert(QLIST_EMPTY(&as->map_client_list));
3247     qemu_mutex_destroy(&as->map_client_list_lock);
3248 
3249     assert(QTAILQ_EMPTY(&as->listeners));
3250 
3251     flatview_unref(as->current_map);
3252     g_free(as->name);
3253     g_free(as->ioeventfds);
3254     memory_region_unref(as->root);
3255 }
3256 
3257 void address_space_destroy(AddressSpace *as)
3258 {
3259     MemoryRegion *root = as->root;
3260 
3261     /* Flush out anything from MemoryListeners listening in on this */
3262     memory_region_transaction_begin();
3263     as->root = NULL;
3264     memory_region_transaction_commit();
3265     QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
3266 
3267     /* At this point, as->dispatch and as->current_map are dummy
3268      * entries that the guest should never use.  Wait for the old
3269      * values to expire before freeing the data.
3270      */
3271     as->root = root;
3272     call_rcu(as, do_address_space_destroy, rcu);
3273 }
3274 
3275 static const char *memory_region_type(MemoryRegion *mr)
3276 {
3277     if (mr->alias) {
3278         return memory_region_type(mr->alias);
3279     }
3280     if (memory_region_is_ram_device(mr)) {
3281         return "ramd";
3282     } else if (memory_region_is_romd(mr)) {
3283         return "romd";
3284     } else if (memory_region_is_rom(mr)) {
3285         return "rom";
3286     } else if (memory_region_is_ram(mr)) {
3287         return "ram";
3288     } else {
3289         return "i/o";
3290     }
3291 }
3292 
3293 typedef struct MemoryRegionList MemoryRegionList;
3294 
3295 struct MemoryRegionList {
3296     const MemoryRegion *mr;
3297     QTAILQ_ENTRY(MemoryRegionList) mrqueue;
3298 };
3299 
3300 typedef QTAILQ_HEAD(, MemoryRegionList) MemoryRegionListHead;
3301 
3302 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3303                            int128_sub((size), int128_one())) : 0)
3304 #define MTREE_INDENT "  "
3305 
3306 static void mtree_expand_owner(const char *label, Object *obj)
3307 {
3308     DeviceState *dev = (DeviceState *) object_dynamic_cast(obj, TYPE_DEVICE);
3309 
3310     qemu_printf(" %s:{%s", label, dev ? "dev" : "obj");
3311     if (dev && dev->id) {
3312         qemu_printf(" id=%s", dev->id);
3313     } else {
3314         char *canonical_path = object_get_canonical_path(obj);
3315         if (canonical_path) {
3316             qemu_printf(" path=%s", canonical_path);
3317             g_free(canonical_path);
3318         } else {
3319             qemu_printf(" type=%s", object_get_typename(obj));
3320         }
3321     }
3322     qemu_printf("}");
3323 }
3324 
3325 static void mtree_print_mr_owner(const MemoryRegion *mr)
3326 {
3327     Object *owner = mr->owner;
3328     Object *parent = memory_region_owner((MemoryRegion *)mr);
3329 
3330     if (!owner && !parent) {
3331         qemu_printf(" orphan");
3332         return;
3333     }
3334     if (owner) {
3335         mtree_expand_owner("owner", owner);
3336     }
3337     if (parent && parent != owner) {
3338         mtree_expand_owner("parent", parent);
3339     }
3340 }
3341 
3342 static void mtree_print_mr(const MemoryRegion *mr, unsigned int level,
3343                            hwaddr base,
3344                            MemoryRegionListHead *alias_print_queue,
3345                            bool owner, bool display_disabled)
3346 {
3347     MemoryRegionList *new_ml, *ml, *next_ml;
3348     MemoryRegionListHead submr_print_queue;
3349     const MemoryRegion *submr;
3350     unsigned int i;
3351     hwaddr cur_start, cur_end;
3352 
3353     if (!mr) {
3354         return;
3355     }
3356 
3357     cur_start = base + mr->addr;
3358     cur_end = cur_start + MR_SIZE(mr->size);
3359 
3360     /*
3361      * Try to detect overflow of memory region. This should never
3362      * happen normally. When it happens, we dump something to warn the
3363      * user who is observing this.
3364      */
3365     if (cur_start < base || cur_end < cur_start) {
3366         qemu_printf("[DETECTED OVERFLOW!] ");
3367     }
3368 
3369     if (mr->alias) {
3370         bool found = false;
3371 
3372         /* check if the alias is already in the queue */
3373         QTAILQ_FOREACH(ml, alias_print_queue, mrqueue) {
3374             if (ml->mr == mr->alias) {
3375                 found = true;
3376             }
3377         }
3378 
3379         if (!found) {
3380             ml = g_new(MemoryRegionList, 1);
3381             ml->mr = mr->alias;
3382             QTAILQ_INSERT_TAIL(alias_print_queue, ml, mrqueue);
3383         }
3384         if (mr->enabled || display_disabled) {
3385             for (i = 0; i < level; i++) {
3386                 qemu_printf(MTREE_INDENT);
3387             }
3388             qemu_printf(HWADDR_FMT_plx "-" HWADDR_FMT_plx
3389                         " (prio %d, %s%s): alias %s @%s " HWADDR_FMT_plx
3390                         "-" HWADDR_FMT_plx "%s",
3391                         cur_start, cur_end,
3392                         mr->priority,
3393                         mr->nonvolatile ? "nv-" : "",
3394                         memory_region_type((MemoryRegion *)mr),
3395                         memory_region_name(mr),
3396                         memory_region_name(mr->alias),
3397                         mr->alias_offset,
3398                         mr->alias_offset + MR_SIZE(mr->size),
3399                         mr->enabled ? "" : " [disabled]");
3400             if (owner) {
3401                 mtree_print_mr_owner(mr);
3402             }
3403             qemu_printf("\n");
3404         }
3405     } else {
3406         if (mr->enabled || display_disabled) {
3407             for (i = 0; i < level; i++) {
3408                 qemu_printf(MTREE_INDENT);
3409             }
3410             qemu_printf(HWADDR_FMT_plx "-" HWADDR_FMT_plx
3411                         " (prio %d, %s%s): %s%s",
3412                         cur_start, cur_end,
3413                         mr->priority,
3414                         mr->nonvolatile ? "nv-" : "",
3415                         memory_region_type((MemoryRegion *)mr),
3416                         memory_region_name(mr),
3417                         mr->enabled ? "" : " [disabled]");
3418             if (owner) {
3419                 mtree_print_mr_owner(mr);
3420             }
3421             qemu_printf("\n");
3422         }
3423     }
3424 
3425     QTAILQ_INIT(&submr_print_queue);
3426 
3427     QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
3428         new_ml = g_new(MemoryRegionList, 1);
3429         new_ml->mr = submr;
3430         QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3431             if (new_ml->mr->addr < ml->mr->addr ||
3432                 (new_ml->mr->addr == ml->mr->addr &&
3433                  new_ml->mr->priority > ml->mr->priority)) {
3434                 QTAILQ_INSERT_BEFORE(ml, new_ml, mrqueue);
3435                 new_ml = NULL;
3436                 break;
3437             }
3438         }
3439         if (new_ml) {
3440             QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, mrqueue);
3441         }
3442     }
3443 
3444     QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3445         mtree_print_mr(ml->mr, level + 1, cur_start,
3446                        alias_print_queue, owner, display_disabled);
3447     }
3448 
3449     QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, mrqueue, next_ml) {
3450         g_free(ml);
3451     }
3452 }
3453 
3454 struct FlatViewInfo {
3455     int counter;
3456     bool dispatch_tree;
3457     bool owner;
3458     AccelClass *ac;
3459 };
3460 
3461 static void mtree_print_flatview(gpointer key, gpointer value,
3462                                  gpointer user_data)
3463 {
3464     FlatView *view = key;
3465     GArray *fv_address_spaces = value;
3466     struct FlatViewInfo *fvi = user_data;
3467     FlatRange *range = &view->ranges[0];
3468     MemoryRegion *mr;
3469     int n = view->nr;
3470     int i;
3471     AddressSpace *as;
3472 
3473     qemu_printf("FlatView #%d\n", fvi->counter);
3474     ++fvi->counter;
3475 
3476     for (i = 0; i < fv_address_spaces->len; ++i) {
3477         as = g_array_index(fv_address_spaces, AddressSpace*, i);
3478         qemu_printf(" AS \"%s\", root: %s",
3479                     as->name, memory_region_name(as->root));
3480         if (as->root->alias) {
3481             qemu_printf(", alias %s", memory_region_name(as->root->alias));
3482         }
3483         qemu_printf("\n");
3484     }
3485 
3486     qemu_printf(" Root memory region: %s\n",
3487       view->root ? memory_region_name(view->root) : "(none)");
3488 
3489     if (n <= 0) {
3490         qemu_printf(MTREE_INDENT "No rendered FlatView\n\n");
3491         return;
3492     }
3493 
3494     while (n--) {
3495         mr = range->mr;
3496         if (range->offset_in_region) {
3497             qemu_printf(MTREE_INDENT HWADDR_FMT_plx "-" HWADDR_FMT_plx
3498                         " (prio %d, %s%s): %s @" HWADDR_FMT_plx,
3499                         int128_get64(range->addr.start),
3500                         int128_get64(range->addr.start)
3501                         + MR_SIZE(range->addr.size),
3502                         mr->priority,
3503                         range->nonvolatile ? "nv-" : "",
3504                         range->readonly ? "rom" : memory_region_type(mr),
3505                         memory_region_name(mr),
3506                         range->offset_in_region);
3507         } else {
3508             qemu_printf(MTREE_INDENT HWADDR_FMT_plx "-" HWADDR_FMT_plx
3509                         " (prio %d, %s%s): %s",
3510                         int128_get64(range->addr.start),
3511                         int128_get64(range->addr.start)
3512                         + MR_SIZE(range->addr.size),
3513                         mr->priority,
3514                         range->nonvolatile ? "nv-" : "",
3515                         range->readonly ? "rom" : memory_region_type(mr),
3516                         memory_region_name(mr));
3517         }
3518         if (fvi->owner) {
3519             mtree_print_mr_owner(mr);
3520         }
3521 
3522         if (fvi->ac) {
3523             for (i = 0; i < fv_address_spaces->len; ++i) {
3524                 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3525                 if (fvi->ac->has_memory(current_machine, as,
3526                                         int128_get64(range->addr.start),
3527                                         MR_SIZE(range->addr.size) + 1)) {
3528                     qemu_printf(" %s", fvi->ac->name);
3529                 }
3530             }
3531         }
3532         qemu_printf("\n");
3533         range++;
3534     }
3535 
3536 #if !defined(CONFIG_USER_ONLY)
3537     if (fvi->dispatch_tree && view->root) {
3538         mtree_print_dispatch(view->dispatch, view->root);
3539     }
3540 #endif
3541 
3542     qemu_printf("\n");
3543 }
3544 
3545 static gboolean mtree_info_flatview_free(gpointer key, gpointer value,
3546                                       gpointer user_data)
3547 {
3548     FlatView *view = key;
3549     GArray *fv_address_spaces = value;
3550 
3551     g_array_unref(fv_address_spaces);
3552     flatview_unref(view);
3553 
3554     return true;
3555 }
3556 
3557 static void mtree_info_flatview(bool dispatch_tree, bool owner)
3558 {
3559     struct FlatViewInfo fvi = {
3560         .counter = 0,
3561         .dispatch_tree = dispatch_tree,
3562         .owner = owner,
3563     };
3564     AddressSpace *as;
3565     FlatView *view;
3566     GArray *fv_address_spaces;
3567     GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3568     AccelClass *ac = ACCEL_GET_CLASS(current_accel());
3569 
3570     if (ac->has_memory) {
3571         fvi.ac = ac;
3572     }
3573 
3574     /* Gather all FVs in one table */
3575     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3576         view = address_space_get_flatview(as);
3577 
3578         fv_address_spaces = g_hash_table_lookup(views, view);
3579         if (!fv_address_spaces) {
3580             fv_address_spaces = g_array_new(false, false, sizeof(as));
3581             g_hash_table_insert(views, view, fv_address_spaces);
3582         }
3583 
3584         g_array_append_val(fv_address_spaces, as);
3585     }
3586 
3587     /* Print */
3588     g_hash_table_foreach(views, mtree_print_flatview, &fvi);
3589 
3590     /* Free */
3591     g_hash_table_foreach_remove(views, mtree_info_flatview_free, 0);
3592     g_hash_table_unref(views);
3593 }
3594 
3595 struct AddressSpaceInfo {
3596     MemoryRegionListHead *ml_head;
3597     bool owner;
3598     bool disabled;
3599 };
3600 
3601 /* Returns negative value if a < b; zero if a = b; positive value if a > b. */
3602 static gint address_space_compare_name(gconstpointer a, gconstpointer b)
3603 {
3604     const AddressSpace *as_a = a;
3605     const AddressSpace *as_b = b;
3606 
3607     return g_strcmp0(as_a->name, as_b->name);
3608 }
3609 
3610 static void mtree_print_as_name(gpointer data, gpointer user_data)
3611 {
3612     AddressSpace *as = data;
3613 
3614     qemu_printf("address-space: %s\n", as->name);
3615 }
3616 
3617 static void mtree_print_as(gpointer key, gpointer value, gpointer user_data)
3618 {
3619     MemoryRegion *mr = key;
3620     GSList *as_same_root_mr_list = value;
3621     struct AddressSpaceInfo *asi = user_data;
3622 
3623     g_slist_foreach(as_same_root_mr_list, mtree_print_as_name, NULL);
3624     mtree_print_mr(mr, 1, 0, asi->ml_head, asi->owner, asi->disabled);
3625     qemu_printf("\n");
3626 }
3627 
3628 static gboolean mtree_info_as_free(gpointer key, gpointer value,
3629                                    gpointer user_data)
3630 {
3631     GSList *as_same_root_mr_list = value;
3632 
3633     g_slist_free(as_same_root_mr_list);
3634 
3635     return true;
3636 }
3637 
3638 static void mtree_info_as(bool dispatch_tree, bool owner, bool disabled)
3639 {
3640     MemoryRegionListHead ml_head;
3641     MemoryRegionList *ml, *ml2;
3642     AddressSpace *as;
3643     GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3644     GSList *as_same_root_mr_list;
3645     struct AddressSpaceInfo asi = {
3646         .ml_head = &ml_head,
3647         .owner = owner,
3648         .disabled = disabled,
3649     };
3650 
3651     QTAILQ_INIT(&ml_head);
3652 
3653     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3654         /* Create hashtable, key=AS root MR, value = list of AS */
3655         as_same_root_mr_list = g_hash_table_lookup(views, as->root);
3656         as_same_root_mr_list = g_slist_insert_sorted(as_same_root_mr_list, as,
3657                                                      address_space_compare_name);
3658         g_hash_table_insert(views, as->root, as_same_root_mr_list);
3659     }
3660 
3661     /* print address spaces */
3662     g_hash_table_foreach(views, mtree_print_as, &asi);
3663     g_hash_table_foreach_remove(views, mtree_info_as_free, 0);
3664     g_hash_table_unref(views);
3665 
3666     /* print aliased regions */
3667     QTAILQ_FOREACH(ml, &ml_head, mrqueue) {
3668         qemu_printf("memory-region: %s\n", memory_region_name(ml->mr));
3669         mtree_print_mr(ml->mr, 1, 0, &ml_head, owner, disabled);
3670         qemu_printf("\n");
3671     }
3672 
3673     QTAILQ_FOREACH_SAFE(ml, &ml_head, mrqueue, ml2) {
3674         g_free(ml);
3675     }
3676 }
3677 
3678 void mtree_info(bool flatview, bool dispatch_tree, bool owner, bool disabled)
3679 {
3680     if (flatview) {
3681         mtree_info_flatview(dispatch_tree, owner);
3682     } else {
3683         mtree_info_as(dispatch_tree, owner, disabled);
3684     }
3685 }
3686 
3687 bool memory_region_init_ram(MemoryRegion *mr,
3688                             Object *owner,
3689                             const char *name,
3690                             uint64_t size,
3691                             Error **errp)
3692 {
3693     DeviceState *owner_dev;
3694 
3695     if (!memory_region_init_ram_nomigrate(mr, owner, name, size, errp)) {
3696         return false;
3697     }
3698     /* This will assert if owner is neither NULL nor a DeviceState.
3699      * We only want the owner here for the purposes of defining a
3700      * unique name for migration. TODO: Ideally we should implement
3701      * a naming scheme for Objects which are not DeviceStates, in
3702      * which case we can relax this restriction.
3703      */
3704     owner_dev = DEVICE(owner);
3705     vmstate_register_ram(mr, owner_dev);
3706 
3707     return true;
3708 }
3709 
3710 bool memory_region_init_ram_guest_memfd(MemoryRegion *mr,
3711                                         Object *owner,
3712                                         const char *name,
3713                                         uint64_t size,
3714                                         Error **errp)
3715 {
3716     DeviceState *owner_dev;
3717 
3718     if (!memory_region_init_ram_flags_nomigrate(mr, owner, name, size,
3719                                                 RAM_GUEST_MEMFD, errp)) {
3720         return false;
3721     }
3722     /* This will assert if owner is neither NULL nor a DeviceState.
3723      * We only want the owner here for the purposes of defining a
3724      * unique name for migration. TODO: Ideally we should implement
3725      * a naming scheme for Objects which are not DeviceStates, in
3726      * which case we can relax this restriction.
3727      */
3728     owner_dev = DEVICE(owner);
3729     vmstate_register_ram(mr, owner_dev);
3730 
3731     return true;
3732 }
3733 
3734 bool memory_region_init_rom(MemoryRegion *mr,
3735                             Object *owner,
3736                             const char *name,
3737                             uint64_t size,
3738                             Error **errp)
3739 {
3740     DeviceState *owner_dev;
3741 
3742     if (!memory_region_init_rom_nomigrate(mr, owner, name, size, errp)) {
3743         return false;
3744     }
3745     /* This will assert if owner is neither NULL nor a DeviceState.
3746      * We only want the owner here for the purposes of defining a
3747      * unique name for migration. TODO: Ideally we should implement
3748      * a naming scheme for Objects which are not DeviceStates, in
3749      * which case we can relax this restriction.
3750      */
3751     owner_dev = DEVICE(owner);
3752     vmstate_register_ram(mr, owner_dev);
3753 
3754     return true;
3755 }
3756 
3757 bool memory_region_init_rom_device(MemoryRegion *mr,
3758                                    Object *owner,
3759                                    const MemoryRegionOps *ops,
3760                                    void *opaque,
3761                                    const char *name,
3762                                    uint64_t size,
3763                                    Error **errp)
3764 {
3765     DeviceState *owner_dev;
3766 
3767     if (!memory_region_init_rom_device_nomigrate(mr, owner, ops, opaque,
3768                                                  name, size, errp)) {
3769         return false;
3770     }
3771     /* This will assert if owner is neither NULL nor a DeviceState.
3772      * We only want the owner here for the purposes of defining a
3773      * unique name for migration. TODO: Ideally we should implement
3774      * a naming scheme for Objects which are not DeviceStates, in
3775      * which case we can relax this restriction.
3776      */
3777     owner_dev = DEVICE(owner);
3778     vmstate_register_ram(mr, owner_dev);
3779 
3780     return true;
3781 }
3782 
3783 /*
3784  * Support system builds with CONFIG_FUZZ using a weak symbol and a stub for
3785  * the fuzz_dma_read_cb callback
3786  */
3787 #ifdef CONFIG_FUZZ
3788 void __attribute__((weak)) fuzz_dma_read_cb(size_t addr,
3789                       size_t len,
3790                       MemoryRegion *mr)
3791 {
3792 }
3793 #endif
3794 
3795 static const TypeInfo memory_region_info = {
3796     .parent             = TYPE_OBJECT,
3797     .name               = TYPE_MEMORY_REGION,
3798     .class_size         = sizeof(MemoryRegionClass),
3799     .instance_size      = sizeof(MemoryRegion),
3800     .instance_init      = memory_region_initfn,
3801     .instance_finalize  = memory_region_finalize,
3802 };
3803 
3804 static const TypeInfo iommu_memory_region_info = {
3805     .parent             = TYPE_MEMORY_REGION,
3806     .name               = TYPE_IOMMU_MEMORY_REGION,
3807     .class_size         = sizeof(IOMMUMemoryRegionClass),
3808     .instance_size      = sizeof(IOMMUMemoryRegion),
3809     .instance_init      = iommu_memory_region_initfn,
3810     .abstract           = true,
3811 };
3812 
3813 static const TypeInfo ram_discard_manager_info = {
3814     .parent             = TYPE_INTERFACE,
3815     .name               = TYPE_RAM_DISCARD_MANAGER,
3816     .class_size         = sizeof(RamDiscardManagerClass),
3817 };
3818 
3819 static void memory_register_types(void)
3820 {
3821     type_register_static(&memory_region_info);
3822     type_register_static(&iommu_memory_region_info);
3823     type_register_static(&ram_discard_manager_info);
3824 }
3825 
3826 type_init(memory_register_types)
3827