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