OSDN Git Service

memory: Drop MemoryRegion.ram_addr
[qmiga/qemu.git] / memory.c
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 "exec/memory.h"
18 #include "exec/address-spaces.h"
19 #include "exec/ioport.h"
20 #include "qapi/visitor.h"
21 #include "qemu/bitops.h"
22 #include "qemu/error-report.h"
23 #include "qom/object.h"
24 #include "trace.h"
25
26 #include "exec/memory-internal.h"
27 #include "exec/ram_addr.h"
28 #include "sysemu/kvm.h"
29 #include "sysemu/sysemu.h"
30
31 //#define DEBUG_UNASSIGNED
32
33 #define RAM_ADDR_INVALID (~(ram_addr_t)0)
34
35 static unsigned memory_region_transaction_depth;
36 static bool memory_region_update_pending;
37 static bool ioeventfd_update_pending;
38 static bool global_dirty_log = false;
39
40 static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
41     = QTAILQ_HEAD_INITIALIZER(memory_listeners);
42
43 static QTAILQ_HEAD(, AddressSpace) address_spaces
44     = QTAILQ_HEAD_INITIALIZER(address_spaces);
45
46 typedef struct AddrRange AddrRange;
47
48 /*
49  * Note that signed integers are needed for negative offsetting in aliases
50  * (large MemoryRegion::alias_offset).
51  */
52 struct AddrRange {
53     Int128 start;
54     Int128 size;
55 };
56
57 static AddrRange addrrange_make(Int128 start, Int128 size)
58 {
59     return (AddrRange) { start, size };
60 }
61
62 static bool addrrange_equal(AddrRange r1, AddrRange r2)
63 {
64     return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
65 }
66
67 static Int128 addrrange_end(AddrRange r)
68 {
69     return int128_add(r.start, r.size);
70 }
71
72 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
73 {
74     int128_addto(&range.start, delta);
75     return range;
76 }
77
78 static bool addrrange_contains(AddrRange range, Int128 addr)
79 {
80     return int128_ge(addr, range.start)
81         && int128_lt(addr, addrrange_end(range));
82 }
83
84 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
85 {
86     return addrrange_contains(r1, r2.start)
87         || addrrange_contains(r2, r1.start);
88 }
89
90 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
91 {
92     Int128 start = int128_max(r1.start, r2.start);
93     Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
94     return addrrange_make(start, int128_sub(end, start));
95 }
96
97 enum ListenerDirection { Forward, Reverse };
98
99 static bool memory_listener_match(MemoryListener *listener,
100                                   MemoryRegionSection *section)
101 {
102     return !listener->address_space_filter
103         || listener->address_space_filter == section->address_space;
104 }
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,        \
120                                    memory_listeners, link) {            \
121                 if (_listener->_callback) {                             \
122                     _listener->_callback(_listener, ##_args);           \
123                 }                                                       \
124             }                                                           \
125             break;                                                      \
126         default:                                                        \
127             abort();                                                    \
128         }                                                               \
129     } while (0)
130
131 #define MEMORY_LISTENER_CALL(_callback, _direction, _section, _args...) \
132     do {                                                                \
133         MemoryListener *_listener;                                      \
134                                                                         \
135         switch (_direction) {                                           \
136         case Forward:                                                   \
137             QTAILQ_FOREACH(_listener, &memory_listeners, link) {        \
138                 if (_listener->_callback                                \
139                     && memory_listener_match(_listener, _section)) {    \
140                     _listener->_callback(_listener, _section, ##_args); \
141                 }                                                       \
142             }                                                           \
143             break;                                                      \
144         case Reverse:                                                   \
145             QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners,        \
146                                    memory_listeners, link) {            \
147                 if (_listener->_callback                                \
148                     && memory_listener_match(_listener, _section)) {    \
149                     _listener->_callback(_listener, _section, ##_args); \
150                 }                                                       \
151             }                                                           \
152             break;                                                      \
153         default:                                                        \
154             abort();                                                    \
155         }                                                               \
156     } while (0)
157
158 /* No need to ref/unref .mr, the FlatRange keeps it alive.  */
159 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback, _args...)  \
160     MEMORY_LISTENER_CALL(callback, dir, (&(MemoryRegionSection) {       \
161         .mr = (fr)->mr,                                                 \
162         .address_space = (as),                                          \
163         .offset_within_region = (fr)->offset_in_region,                 \
164         .size = (fr)->addr.size,                                        \
165         .offset_within_address_space = int128_get64((fr)->addr.start),  \
166         .readonly = (fr)->readonly,                                     \
167               }), ##_args)
168
169 struct CoalescedMemoryRange {
170     AddrRange addr;
171     QTAILQ_ENTRY(CoalescedMemoryRange) link;
172 };
173
174 struct MemoryRegionIoeventfd {
175     AddrRange addr;
176     bool match_data;
177     uint64_t data;
178     EventNotifier *e;
179 };
180
181 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
182                                            MemoryRegionIoeventfd b)
183 {
184     if (int128_lt(a.addr.start, b.addr.start)) {
185         return true;
186     } else if (int128_gt(a.addr.start, b.addr.start)) {
187         return false;
188     } else if (int128_lt(a.addr.size, b.addr.size)) {
189         return true;
190     } else if (int128_gt(a.addr.size, b.addr.size)) {
191         return false;
192     } else if (a.match_data < b.match_data) {
193         return true;
194     } else  if (a.match_data > b.match_data) {
195         return false;
196     } else if (a.match_data) {
197         if (a.data < b.data) {
198             return true;
199         } else if (a.data > b.data) {
200             return false;
201         }
202     }
203     if (a.e < b.e) {
204         return true;
205     } else if (a.e > b.e) {
206         return false;
207     }
208     return false;
209 }
210
211 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
212                                           MemoryRegionIoeventfd b)
213 {
214     return !memory_region_ioeventfd_before(a, b)
215         && !memory_region_ioeventfd_before(b, a);
216 }
217
218 typedef struct FlatRange FlatRange;
219 typedef struct FlatView FlatView;
220
221 /* Range of memory in the global map.  Addresses are absolute. */
222 struct FlatRange {
223     MemoryRegion *mr;
224     hwaddr offset_in_region;
225     AddrRange addr;
226     uint8_t dirty_log_mask;
227     bool romd_mode;
228     bool readonly;
229 };
230
231 /* Flattened global view of current active memory hierarchy.  Kept in sorted
232  * order.
233  */
234 struct FlatView {
235     struct rcu_head rcu;
236     unsigned ref;
237     FlatRange *ranges;
238     unsigned nr;
239     unsigned nr_allocated;
240 };
241
242 typedef struct AddressSpaceOps AddressSpaceOps;
243
244 #define FOR_EACH_FLAT_RANGE(var, view)          \
245     for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
246
247 static bool flatrange_equal(FlatRange *a, FlatRange *b)
248 {
249     return a->mr == b->mr
250         && addrrange_equal(a->addr, b->addr)
251         && a->offset_in_region == b->offset_in_region
252         && a->romd_mode == b->romd_mode
253         && a->readonly == b->readonly;
254 }
255
256 static void flatview_init(FlatView *view)
257 {
258     view->ref = 1;
259     view->ranges = NULL;
260     view->nr = 0;
261     view->nr_allocated = 0;
262 }
263
264 /* Insert a range into a given position.  Caller is responsible for maintaining
265  * sorting order.
266  */
267 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
268 {
269     if (view->nr == view->nr_allocated) {
270         view->nr_allocated = MAX(2 * view->nr, 10);
271         view->ranges = g_realloc(view->ranges,
272                                     view->nr_allocated * sizeof(*view->ranges));
273     }
274     memmove(view->ranges + pos + 1, view->ranges + pos,
275             (view->nr - pos) * sizeof(FlatRange));
276     view->ranges[pos] = *range;
277     memory_region_ref(range->mr);
278     ++view->nr;
279 }
280
281 static void flatview_destroy(FlatView *view)
282 {
283     int i;
284
285     for (i = 0; i < view->nr; i++) {
286         memory_region_unref(view->ranges[i].mr);
287     }
288     g_free(view->ranges);
289     g_free(view);
290 }
291
292 static void flatview_ref(FlatView *view)
293 {
294     atomic_inc(&view->ref);
295 }
296
297 static void flatview_unref(FlatView *view)
298 {
299     if (atomic_fetch_dec(&view->ref) == 1) {
300         flatview_destroy(view);
301     }
302 }
303
304 static bool can_merge(FlatRange *r1, FlatRange *r2)
305 {
306     return int128_eq(addrrange_end(r1->addr), r2->addr.start)
307         && r1->mr == r2->mr
308         && int128_eq(int128_add(int128_make64(r1->offset_in_region),
309                                 r1->addr.size),
310                      int128_make64(r2->offset_in_region))
311         && r1->dirty_log_mask == r2->dirty_log_mask
312         && r1->romd_mode == r2->romd_mode
313         && r1->readonly == r2->readonly;
314 }
315
316 /* Attempt to simplify a view by merging adjacent ranges */
317 static void flatview_simplify(FlatView *view)
318 {
319     unsigned i, j;
320
321     i = 0;
322     while (i < view->nr) {
323         j = i + 1;
324         while (j < view->nr
325                && can_merge(&view->ranges[j-1], &view->ranges[j])) {
326             int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
327             ++j;
328         }
329         ++i;
330         memmove(&view->ranges[i], &view->ranges[j],
331                 (view->nr - j) * sizeof(view->ranges[j]));
332         view->nr -= j - i;
333     }
334 }
335
336 static bool memory_region_big_endian(MemoryRegion *mr)
337 {
338 #ifdef TARGET_WORDS_BIGENDIAN
339     return mr->ops->endianness != DEVICE_LITTLE_ENDIAN;
340 #else
341     return mr->ops->endianness == DEVICE_BIG_ENDIAN;
342 #endif
343 }
344
345 static bool memory_region_wrong_endianness(MemoryRegion *mr)
346 {
347 #ifdef TARGET_WORDS_BIGENDIAN
348     return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
349 #else
350     return mr->ops->endianness == DEVICE_BIG_ENDIAN;
351 #endif
352 }
353
354 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
355 {
356     if (memory_region_wrong_endianness(mr)) {
357         switch (size) {
358         case 1:
359             break;
360         case 2:
361             *data = bswap16(*data);
362             break;
363         case 4:
364             *data = bswap32(*data);
365             break;
366         case 8:
367             *data = bswap64(*data);
368             break;
369         default:
370             abort();
371         }
372     }
373 }
374
375 static hwaddr memory_region_to_absolute_addr(MemoryRegion *mr, hwaddr offset)
376 {
377     MemoryRegion *root;
378     hwaddr abs_addr = offset;
379
380     abs_addr += mr->addr;
381     for (root = mr; root->container; ) {
382         root = root->container;
383         abs_addr += root->addr;
384     }
385
386     return abs_addr;
387 }
388
389 static MemTxResult memory_region_oldmmio_read_accessor(MemoryRegion *mr,
390                                                        hwaddr addr,
391                                                        uint64_t *value,
392                                                        unsigned size,
393                                                        unsigned shift,
394                                                        uint64_t mask,
395                                                        MemTxAttrs attrs)
396 {
397     uint64_t tmp;
398
399     tmp = mr->ops->old_mmio.read[ctz32(size)](mr->opaque, addr);
400     if (mr->subpage) {
401         trace_memory_region_subpage_read(mr, addr, tmp, size);
402     } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
403         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
404         trace_memory_region_ops_read(mr, abs_addr, tmp, size);
405     }
406     *value |= (tmp & mask) << shift;
407     return MEMTX_OK;
408 }
409
410 static MemTxResult  memory_region_read_accessor(MemoryRegion *mr,
411                                                 hwaddr addr,
412                                                 uint64_t *value,
413                                                 unsigned size,
414                                                 unsigned shift,
415                                                 uint64_t mask,
416                                                 MemTxAttrs attrs)
417 {
418     uint64_t tmp;
419
420     tmp = mr->ops->read(mr->opaque, addr, size);
421     if (mr->subpage) {
422         trace_memory_region_subpage_read(mr, addr, tmp, size);
423     } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
424         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
425         trace_memory_region_ops_read(mr, abs_addr, tmp, size);
426     }
427     *value |= (tmp & mask) << shift;
428     return MEMTX_OK;
429 }
430
431 static MemTxResult memory_region_read_with_attrs_accessor(MemoryRegion *mr,
432                                                           hwaddr addr,
433                                                           uint64_t *value,
434                                                           unsigned size,
435                                                           unsigned shift,
436                                                           uint64_t mask,
437                                                           MemTxAttrs attrs)
438 {
439     uint64_t tmp = 0;
440     MemTxResult r;
441
442     r = mr->ops->read_with_attrs(mr->opaque, addr, &tmp, size, attrs);
443     if (mr->subpage) {
444         trace_memory_region_subpage_read(mr, addr, tmp, size);
445     } else if (TRACE_MEMORY_REGION_OPS_READ_ENABLED) {
446         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
447         trace_memory_region_ops_read(mr, abs_addr, tmp, size);
448     }
449     *value |= (tmp & mask) << shift;
450     return r;
451 }
452
453 static MemTxResult memory_region_oldmmio_write_accessor(MemoryRegion *mr,
454                                                         hwaddr addr,
455                                                         uint64_t *value,
456                                                         unsigned size,
457                                                         unsigned shift,
458                                                         uint64_t mask,
459                                                         MemTxAttrs attrs)
460 {
461     uint64_t tmp;
462
463     tmp = (*value >> shift) & mask;
464     if (mr->subpage) {
465         trace_memory_region_subpage_write(mr, addr, tmp, size);
466     } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
467         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
468         trace_memory_region_ops_write(mr, abs_addr, tmp, size);
469     }
470     mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);
471     return MEMTX_OK;
472 }
473
474 static MemTxResult memory_region_write_accessor(MemoryRegion *mr,
475                                                 hwaddr addr,
476                                                 uint64_t *value,
477                                                 unsigned size,
478                                                 unsigned shift,
479                                                 uint64_t mask,
480                                                 MemTxAttrs attrs)
481 {
482     uint64_t tmp;
483
484     tmp = (*value >> shift) & mask;
485     if (mr->subpage) {
486         trace_memory_region_subpage_write(mr, addr, tmp, size);
487     } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
488         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
489         trace_memory_region_ops_write(mr, abs_addr, tmp, size);
490     }
491     mr->ops->write(mr->opaque, addr, tmp, size);
492     return MEMTX_OK;
493 }
494
495 static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,
496                                                            hwaddr addr,
497                                                            uint64_t *value,
498                                                            unsigned size,
499                                                            unsigned shift,
500                                                            uint64_t mask,
501                                                            MemTxAttrs attrs)
502 {
503     uint64_t tmp;
504
505     tmp = (*value >> shift) & mask;
506     if (mr->subpage) {
507         trace_memory_region_subpage_write(mr, addr, tmp, size);
508     } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {
509         hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);
510         trace_memory_region_ops_write(mr, abs_addr, tmp, size);
511     }
512     return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);
513 }
514
515 static MemTxResult access_with_adjusted_size(hwaddr addr,
516                                       uint64_t *value,
517                                       unsigned size,
518                                       unsigned access_size_min,
519                                       unsigned access_size_max,
520                                       MemTxResult (*access)(MemoryRegion *mr,
521                                                             hwaddr addr,
522                                                             uint64_t *value,
523                                                             unsigned size,
524                                                             unsigned shift,
525                                                             uint64_t mask,
526                                                             MemTxAttrs attrs),
527                                       MemoryRegion *mr,
528                                       MemTxAttrs attrs)
529 {
530     uint64_t access_mask;
531     unsigned access_size;
532     unsigned i;
533     MemTxResult r = MEMTX_OK;
534
535     if (!access_size_min) {
536         access_size_min = 1;
537     }
538     if (!access_size_max) {
539         access_size_max = 4;
540     }
541
542     /* FIXME: support unaligned access? */
543     access_size = MAX(MIN(size, access_size_max), access_size_min);
544     access_mask = -1ULL >> (64 - access_size * 8);
545     if (memory_region_big_endian(mr)) {
546         for (i = 0; i < size; i += access_size) {
547             r |= access(mr, addr + i, value, access_size,
548                         (size - access_size - i) * 8, access_mask, attrs);
549         }
550     } else {
551         for (i = 0; i < size; i += access_size) {
552             r |= access(mr, addr + i, value, access_size, i * 8,
553                         access_mask, attrs);
554         }
555     }
556     return r;
557 }
558
559 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
560 {
561     AddressSpace *as;
562
563     while (mr->container) {
564         mr = mr->container;
565     }
566     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
567         if (mr == as->root) {
568             return as;
569         }
570     }
571     return NULL;
572 }
573
574 /* Render a memory region into the global view.  Ranges in @view obscure
575  * ranges in @mr.
576  */
577 static void render_memory_region(FlatView *view,
578                                  MemoryRegion *mr,
579                                  Int128 base,
580                                  AddrRange clip,
581                                  bool readonly)
582 {
583     MemoryRegion *subregion;
584     unsigned i;
585     hwaddr offset_in_region;
586     Int128 remain;
587     Int128 now;
588     FlatRange fr;
589     AddrRange tmp;
590
591     if (!mr->enabled) {
592         return;
593     }
594
595     int128_addto(&base, int128_make64(mr->addr));
596     readonly |= mr->readonly;
597
598     tmp = addrrange_make(base, mr->size);
599
600     if (!addrrange_intersects(tmp, clip)) {
601         return;
602     }
603
604     clip = addrrange_intersection(tmp, clip);
605
606     if (mr->alias) {
607         int128_subfrom(&base, int128_make64(mr->alias->addr));
608         int128_subfrom(&base, int128_make64(mr->alias_offset));
609         render_memory_region(view, mr->alias, base, clip, readonly);
610         return;
611     }
612
613     /* Render subregions in priority order. */
614     QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
615         render_memory_region(view, subregion, base, clip, readonly);
616     }
617
618     if (!mr->terminates) {
619         return;
620     }
621
622     offset_in_region = int128_get64(int128_sub(clip.start, base));
623     base = clip.start;
624     remain = clip.size;
625
626     fr.mr = mr;
627     fr.dirty_log_mask = memory_region_get_dirty_log_mask(mr);
628     fr.romd_mode = mr->romd_mode;
629     fr.readonly = readonly;
630
631     /* Render the region itself into any gaps left by the current view. */
632     for (i = 0; i < view->nr && int128_nz(remain); ++i) {
633         if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
634             continue;
635         }
636         if (int128_lt(base, view->ranges[i].addr.start)) {
637             now = int128_min(remain,
638                              int128_sub(view->ranges[i].addr.start, base));
639             fr.offset_in_region = offset_in_region;
640             fr.addr = addrrange_make(base, now);
641             flatview_insert(view, i, &fr);
642             ++i;
643             int128_addto(&base, now);
644             offset_in_region += int128_get64(now);
645             int128_subfrom(&remain, now);
646         }
647         now = int128_sub(int128_min(int128_add(base, remain),
648                                     addrrange_end(view->ranges[i].addr)),
649                          base);
650         int128_addto(&base, now);
651         offset_in_region += int128_get64(now);
652         int128_subfrom(&remain, now);
653     }
654     if (int128_nz(remain)) {
655         fr.offset_in_region = offset_in_region;
656         fr.addr = addrrange_make(base, remain);
657         flatview_insert(view, i, &fr);
658     }
659 }
660
661 /* Render a memory topology into a list of disjoint absolute ranges. */
662 static FlatView *generate_memory_topology(MemoryRegion *mr)
663 {
664     FlatView *view;
665
666     view = g_new(FlatView, 1);
667     flatview_init(view);
668
669     if (mr) {
670         render_memory_region(view, mr, int128_zero(),
671                              addrrange_make(int128_zero(), int128_2_64()), false);
672     }
673     flatview_simplify(view);
674
675     return view;
676 }
677
678 static void address_space_add_del_ioeventfds(AddressSpace *as,
679                                              MemoryRegionIoeventfd *fds_new,
680                                              unsigned fds_new_nb,
681                                              MemoryRegionIoeventfd *fds_old,
682                                              unsigned fds_old_nb)
683 {
684     unsigned iold, inew;
685     MemoryRegionIoeventfd *fd;
686     MemoryRegionSection section;
687
688     /* Generate a symmetric difference of the old and new fd sets, adding
689      * and deleting as necessary.
690      */
691
692     iold = inew = 0;
693     while (iold < fds_old_nb || inew < fds_new_nb) {
694         if (iold < fds_old_nb
695             && (inew == fds_new_nb
696                 || memory_region_ioeventfd_before(fds_old[iold],
697                                                   fds_new[inew]))) {
698             fd = &fds_old[iold];
699             section = (MemoryRegionSection) {
700                 .address_space = as,
701                 .offset_within_address_space = int128_get64(fd->addr.start),
702                 .size = fd->addr.size,
703             };
704             MEMORY_LISTENER_CALL(eventfd_del, Forward, &section,
705                                  fd->match_data, fd->data, fd->e);
706             ++iold;
707         } else if (inew < fds_new_nb
708                    && (iold == fds_old_nb
709                        || memory_region_ioeventfd_before(fds_new[inew],
710                                                          fds_old[iold]))) {
711             fd = &fds_new[inew];
712             section = (MemoryRegionSection) {
713                 .address_space = as,
714                 .offset_within_address_space = int128_get64(fd->addr.start),
715                 .size = fd->addr.size,
716             };
717             MEMORY_LISTENER_CALL(eventfd_add, Reverse, &section,
718                                  fd->match_data, fd->data, fd->e);
719             ++inew;
720         } else {
721             ++iold;
722             ++inew;
723         }
724     }
725 }
726
727 static FlatView *address_space_get_flatview(AddressSpace *as)
728 {
729     FlatView *view;
730
731     rcu_read_lock();
732     view = atomic_rcu_read(&as->current_map);
733     flatview_ref(view);
734     rcu_read_unlock();
735     return view;
736 }
737
738 static void address_space_update_ioeventfds(AddressSpace *as)
739 {
740     FlatView *view;
741     FlatRange *fr;
742     unsigned ioeventfd_nb = 0;
743     MemoryRegionIoeventfd *ioeventfds = NULL;
744     AddrRange tmp;
745     unsigned i;
746
747     view = address_space_get_flatview(as);
748     FOR_EACH_FLAT_RANGE(fr, view) {
749         for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
750             tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
751                                   int128_sub(fr->addr.start,
752                                              int128_make64(fr->offset_in_region)));
753             if (addrrange_intersects(fr->addr, tmp)) {
754                 ++ioeventfd_nb;
755                 ioeventfds = g_realloc(ioeventfds,
756                                           ioeventfd_nb * sizeof(*ioeventfds));
757                 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
758                 ioeventfds[ioeventfd_nb-1].addr = tmp;
759             }
760         }
761     }
762
763     address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
764                                      as->ioeventfds, as->ioeventfd_nb);
765
766     g_free(as->ioeventfds);
767     as->ioeventfds = ioeventfds;
768     as->ioeventfd_nb = ioeventfd_nb;
769     flatview_unref(view);
770 }
771
772 static void address_space_update_topology_pass(AddressSpace *as,
773                                                const FlatView *old_view,
774                                                const FlatView *new_view,
775                                                bool adding)
776 {
777     unsigned iold, inew;
778     FlatRange *frold, *frnew;
779
780     /* Generate a symmetric difference of the old and new memory maps.
781      * Kill ranges in the old map, and instantiate ranges in the new map.
782      */
783     iold = inew = 0;
784     while (iold < old_view->nr || inew < new_view->nr) {
785         if (iold < old_view->nr) {
786             frold = &old_view->ranges[iold];
787         } else {
788             frold = NULL;
789         }
790         if (inew < new_view->nr) {
791             frnew = &new_view->ranges[inew];
792         } else {
793             frnew = NULL;
794         }
795
796         if (frold
797             && (!frnew
798                 || int128_lt(frold->addr.start, frnew->addr.start)
799                 || (int128_eq(frold->addr.start, frnew->addr.start)
800                     && !flatrange_equal(frold, frnew)))) {
801             /* In old but not in new, or in both but attributes changed. */
802
803             if (!adding) {
804                 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
805             }
806
807             ++iold;
808         } else if (frold && frnew && flatrange_equal(frold, frnew)) {
809             /* In both and unchanged (except logging may have changed) */
810
811             if (adding) {
812                 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
813                 if (frnew->dirty_log_mask & ~frold->dirty_log_mask) {
814                     MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start,
815                                                   frold->dirty_log_mask,
816                                                   frnew->dirty_log_mask);
817                 }
818                 if (frold->dirty_log_mask & ~frnew->dirty_log_mask) {
819                     MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop,
820                                                   frold->dirty_log_mask,
821                                                   frnew->dirty_log_mask);
822                 }
823             }
824
825             ++iold;
826             ++inew;
827         } else {
828             /* In new */
829
830             if (adding) {
831                 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
832             }
833
834             ++inew;
835         }
836     }
837 }
838
839
840 static void address_space_update_topology(AddressSpace *as)
841 {
842     FlatView *old_view = address_space_get_flatview(as);
843     FlatView *new_view = generate_memory_topology(as->root);
844
845     address_space_update_topology_pass(as, old_view, new_view, false);
846     address_space_update_topology_pass(as, old_view, new_view, true);
847
848     /* Writes are protected by the BQL.  */
849     atomic_rcu_set(&as->current_map, new_view);
850     call_rcu(old_view, flatview_unref, rcu);
851
852     /* Note that all the old MemoryRegions are still alive up to this
853      * point.  This relieves most MemoryListeners from the need to
854      * ref/unref the MemoryRegions they get---unless they use them
855      * outside the iothread mutex, in which case precise reference
856      * counting is necessary.
857      */
858     flatview_unref(old_view);
859
860     address_space_update_ioeventfds(as);
861 }
862
863 void memory_region_transaction_begin(void)
864 {
865     qemu_flush_coalesced_mmio_buffer();
866     ++memory_region_transaction_depth;
867 }
868
869 static void memory_region_clear_pending(void)
870 {
871     memory_region_update_pending = false;
872     ioeventfd_update_pending = false;
873 }
874
875 void memory_region_transaction_commit(void)
876 {
877     AddressSpace *as;
878
879     assert(memory_region_transaction_depth);
880     --memory_region_transaction_depth;
881     if (!memory_region_transaction_depth) {
882         if (memory_region_update_pending) {
883             MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
884
885             QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
886                 address_space_update_topology(as);
887             }
888
889             MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
890         } else if (ioeventfd_update_pending) {
891             QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
892                 address_space_update_ioeventfds(as);
893             }
894         }
895         memory_region_clear_pending();
896    }
897 }
898
899 static void memory_region_destructor_none(MemoryRegion *mr)
900 {
901 }
902
903 static void memory_region_destructor_ram(MemoryRegion *mr)
904 {
905     qemu_ram_free(memory_region_get_ram_addr(mr));
906 }
907
908 static void memory_region_destructor_rom_device(MemoryRegion *mr)
909 {
910     qemu_ram_free(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK);
911 }
912
913 static bool memory_region_need_escape(char c)
914 {
915     return c == '/' || c == '[' || c == '\\' || c == ']';
916 }
917
918 static char *memory_region_escape_name(const char *name)
919 {
920     const char *p;
921     char *escaped, *q;
922     uint8_t c;
923     size_t bytes = 0;
924
925     for (p = name; *p; p++) {
926         bytes += memory_region_need_escape(*p) ? 4 : 1;
927     }
928     if (bytes == p - name) {
929        return g_memdup(name, bytes + 1);
930     }
931
932     escaped = g_malloc(bytes + 1);
933     for (p = name, q = escaped; *p; p++) {
934         c = *p;
935         if (unlikely(memory_region_need_escape(c))) {
936             *q++ = '\\';
937             *q++ = 'x';
938             *q++ = "0123456789abcdef"[c >> 4];
939             c = "0123456789abcdef"[c & 15];
940         }
941         *q++ = c;
942     }
943     *q = 0;
944     return escaped;
945 }
946
947 void memory_region_init(MemoryRegion *mr,
948                         Object *owner,
949                         const char *name,
950                         uint64_t size)
951 {
952     object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
953     mr->size = int128_make64(size);
954     if (size == UINT64_MAX) {
955         mr->size = int128_2_64();
956     }
957     mr->name = g_strdup(name);
958     mr->owner = owner;
959     mr->ram_block = NULL;
960
961     if (name) {
962         char *escaped_name = memory_region_escape_name(name);
963         char *name_array = g_strdup_printf("%s[*]", escaped_name);
964
965         if (!owner) {
966             owner = container_get(qdev_get_machine(), "/unattached");
967         }
968
969         object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
970         object_unref(OBJECT(mr));
971         g_free(name_array);
972         g_free(escaped_name);
973     }
974 }
975
976 static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
977                                    void *opaque, Error **errp)
978 {
979     MemoryRegion *mr = MEMORY_REGION(obj);
980     uint64_t value = mr->addr;
981
982     visit_type_uint64(v, name, &value, errp);
983 }
984
985 static void memory_region_get_container(Object *obj, Visitor *v,
986                                         const char *name, void *opaque,
987                                         Error **errp)
988 {
989     MemoryRegion *mr = MEMORY_REGION(obj);
990     gchar *path = (gchar *)"";
991
992     if (mr->container) {
993         path = object_get_canonical_path(OBJECT(mr->container));
994     }
995     visit_type_str(v, name, &path, errp);
996     if (mr->container) {
997         g_free(path);
998     }
999 }
1000
1001 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1002                                                const char *part)
1003 {
1004     MemoryRegion *mr = MEMORY_REGION(obj);
1005
1006     return OBJECT(mr->container);
1007 }
1008
1009 static void memory_region_get_priority(Object *obj, Visitor *v,
1010                                        const char *name, void *opaque,
1011                                        Error **errp)
1012 {
1013     MemoryRegion *mr = MEMORY_REGION(obj);
1014     int32_t value = mr->priority;
1015
1016     visit_type_int32(v, name, &value, errp);
1017 }
1018
1019 static bool memory_region_get_may_overlap(Object *obj, Error **errp)
1020 {
1021     MemoryRegion *mr = MEMORY_REGION(obj);
1022
1023     return mr->may_overlap;
1024 }
1025
1026 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1027                                    void *opaque, Error **errp)
1028 {
1029     MemoryRegion *mr = MEMORY_REGION(obj);
1030     uint64_t value = memory_region_size(mr);
1031
1032     visit_type_uint64(v, name, &value, errp);
1033 }
1034
1035 static void memory_region_initfn(Object *obj)
1036 {
1037     MemoryRegion *mr = MEMORY_REGION(obj);
1038     ObjectProperty *op;
1039
1040     mr->ops = &unassigned_mem_ops;
1041     mr->enabled = true;
1042     mr->romd_mode = true;
1043     mr->global_locking = true;
1044     mr->destructor = memory_region_destructor_none;
1045     QTAILQ_INIT(&mr->subregions);
1046     QTAILQ_INIT(&mr->coalesced);
1047
1048     op = object_property_add(OBJECT(mr), "container",
1049                              "link<" TYPE_MEMORY_REGION ">",
1050                              memory_region_get_container,
1051                              NULL, /* memory_region_set_container */
1052                              NULL, NULL, &error_abort);
1053     op->resolve = memory_region_resolve_container;
1054
1055     object_property_add(OBJECT(mr), "addr", "uint64",
1056                         memory_region_get_addr,
1057                         NULL, /* memory_region_set_addr */
1058                         NULL, NULL, &error_abort);
1059     object_property_add(OBJECT(mr), "priority", "uint32",
1060                         memory_region_get_priority,
1061                         NULL, /* memory_region_set_priority */
1062                         NULL, NULL, &error_abort);
1063     object_property_add_bool(OBJECT(mr), "may-overlap",
1064                              memory_region_get_may_overlap,
1065                              NULL, /* memory_region_set_may_overlap */
1066                              &error_abort);
1067     object_property_add(OBJECT(mr), "size", "uint64",
1068                         memory_region_get_size,
1069                         NULL, /* memory_region_set_size, */
1070                         NULL, NULL, &error_abort);
1071 }
1072
1073 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1074                                     unsigned size)
1075 {
1076 #ifdef DEBUG_UNASSIGNED
1077     printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1078 #endif
1079     if (current_cpu != NULL) {
1080         cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1081     }
1082     return 0;
1083 }
1084
1085 static void unassigned_mem_write(void *opaque, hwaddr addr,
1086                                  uint64_t val, unsigned size)
1087 {
1088 #ifdef DEBUG_UNASSIGNED
1089     printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1090 #endif
1091     if (current_cpu != NULL) {
1092         cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1093     }
1094 }
1095
1096 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1097                                    unsigned size, bool is_write)
1098 {
1099     return false;
1100 }
1101
1102 const MemoryRegionOps unassigned_mem_ops = {
1103     .valid.accepts = unassigned_mem_accepts,
1104     .endianness = DEVICE_NATIVE_ENDIAN,
1105 };
1106
1107 bool memory_region_access_valid(MemoryRegion *mr,
1108                                 hwaddr addr,
1109                                 unsigned size,
1110                                 bool is_write)
1111 {
1112     int access_size_min, access_size_max;
1113     int access_size, i;
1114
1115     if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1116         return false;
1117     }
1118
1119     if (!mr->ops->valid.accepts) {
1120         return true;
1121     }
1122
1123     access_size_min = mr->ops->valid.min_access_size;
1124     if (!mr->ops->valid.min_access_size) {
1125         access_size_min = 1;
1126     }
1127
1128     access_size_max = mr->ops->valid.max_access_size;
1129     if (!mr->ops->valid.max_access_size) {
1130         access_size_max = 4;
1131     }
1132
1133     access_size = MAX(MIN(size, access_size_max), access_size_min);
1134     for (i = 0; i < size; i += access_size) {
1135         if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
1136                                     is_write)) {
1137             return false;
1138         }
1139     }
1140
1141     return true;
1142 }
1143
1144 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1145                                                 hwaddr addr,
1146                                                 uint64_t *pval,
1147                                                 unsigned size,
1148                                                 MemTxAttrs attrs)
1149 {
1150     *pval = 0;
1151
1152     if (mr->ops->read) {
1153         return access_with_adjusted_size(addr, pval, size,
1154                                          mr->ops->impl.min_access_size,
1155                                          mr->ops->impl.max_access_size,
1156                                          memory_region_read_accessor,
1157                                          mr, attrs);
1158     } else if (mr->ops->read_with_attrs) {
1159         return access_with_adjusted_size(addr, pval, size,
1160                                          mr->ops->impl.min_access_size,
1161                                          mr->ops->impl.max_access_size,
1162                                          memory_region_read_with_attrs_accessor,
1163                                          mr, attrs);
1164     } else {
1165         return access_with_adjusted_size(addr, pval, size, 1, 4,
1166                                          memory_region_oldmmio_read_accessor,
1167                                          mr, attrs);
1168     }
1169 }
1170
1171 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1172                                         hwaddr addr,
1173                                         uint64_t *pval,
1174                                         unsigned size,
1175                                         MemTxAttrs attrs)
1176 {
1177     MemTxResult r;
1178
1179     if (!memory_region_access_valid(mr, addr, size, false)) {
1180         *pval = unassigned_mem_read(mr, addr, size);
1181         return MEMTX_DECODE_ERROR;
1182     }
1183
1184     r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1185     adjust_endianness(mr, pval, size);
1186     return r;
1187 }
1188
1189 /* Return true if an eventfd was signalled */
1190 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1191                                                     hwaddr addr,
1192                                                     uint64_t data,
1193                                                     unsigned size,
1194                                                     MemTxAttrs attrs)
1195 {
1196     MemoryRegionIoeventfd ioeventfd = {
1197         .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1198         .data = data,
1199     };
1200     unsigned i;
1201
1202     for (i = 0; i < mr->ioeventfd_nb; i++) {
1203         ioeventfd.match_data = mr->ioeventfds[i].match_data;
1204         ioeventfd.e = mr->ioeventfds[i].e;
1205
1206         if (memory_region_ioeventfd_equal(ioeventfd, mr->ioeventfds[i])) {
1207             event_notifier_set(ioeventfd.e);
1208             return true;
1209         }
1210     }
1211
1212     return false;
1213 }
1214
1215 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1216                                          hwaddr addr,
1217                                          uint64_t data,
1218                                          unsigned size,
1219                                          MemTxAttrs attrs)
1220 {
1221     if (!memory_region_access_valid(mr, addr, size, true)) {
1222         unassigned_mem_write(mr, addr, data, size);
1223         return MEMTX_DECODE_ERROR;
1224     }
1225
1226     adjust_endianness(mr, &data, size);
1227
1228     if ((!kvm_eventfds_enabled()) &&
1229         memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1230         return MEMTX_OK;
1231     }
1232
1233     if (mr->ops->write) {
1234         return access_with_adjusted_size(addr, &data, size,
1235                                          mr->ops->impl.min_access_size,
1236                                          mr->ops->impl.max_access_size,
1237                                          memory_region_write_accessor, mr,
1238                                          attrs);
1239     } else if (mr->ops->write_with_attrs) {
1240         return
1241             access_with_adjusted_size(addr, &data, size,
1242                                       mr->ops->impl.min_access_size,
1243                                       mr->ops->impl.max_access_size,
1244                                       memory_region_write_with_attrs_accessor,
1245                                       mr, attrs);
1246     } else {
1247         return access_with_adjusted_size(addr, &data, size, 1, 4,
1248                                          memory_region_oldmmio_write_accessor,
1249                                          mr, attrs);
1250     }
1251 }
1252
1253 void memory_region_init_io(MemoryRegion *mr,
1254                            Object *owner,
1255                            const MemoryRegionOps *ops,
1256                            void *opaque,
1257                            const char *name,
1258                            uint64_t size)
1259 {
1260     memory_region_init(mr, owner, name, size);
1261     mr->ops = ops ? ops : &unassigned_mem_ops;
1262     mr->opaque = opaque;
1263     mr->terminates = true;
1264 }
1265
1266 void memory_region_init_ram(MemoryRegion *mr,
1267                             Object *owner,
1268                             const char *name,
1269                             uint64_t size,
1270                             Error **errp)
1271 {
1272     memory_region_init(mr, owner, name, size);
1273     mr->ram = true;
1274     mr->terminates = true;
1275     mr->destructor = memory_region_destructor_ram;
1276     mr->ram_block = qemu_ram_alloc(size, mr, errp);
1277     mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1278 }
1279
1280 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1281                                        Object *owner,
1282                                        const char *name,
1283                                        uint64_t size,
1284                                        uint64_t max_size,
1285                                        void (*resized)(const char*,
1286                                                        uint64_t length,
1287                                                        void *host),
1288                                        Error **errp)
1289 {
1290     memory_region_init(mr, owner, name, size);
1291     mr->ram = true;
1292     mr->terminates = true;
1293     mr->destructor = memory_region_destructor_ram;
1294     mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1295                                               mr, errp);
1296     mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1297 }
1298
1299 #ifdef __linux__
1300 void memory_region_init_ram_from_file(MemoryRegion *mr,
1301                                       struct Object *owner,
1302                                       const char *name,
1303                                       uint64_t size,
1304                                       bool share,
1305                                       const char *path,
1306                                       Error **errp)
1307 {
1308     memory_region_init(mr, owner, name, size);
1309     mr->ram = true;
1310     mr->terminates = true;
1311     mr->destructor = memory_region_destructor_ram;
1312     mr->ram_block = qemu_ram_alloc_from_file(size, mr, share, path, errp);
1313     mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1314 }
1315 #endif
1316
1317 void memory_region_init_ram_ptr(MemoryRegion *mr,
1318                                 Object *owner,
1319                                 const char *name,
1320                                 uint64_t size,
1321                                 void *ptr)
1322 {
1323     memory_region_init(mr, owner, name, size);
1324     mr->ram = true;
1325     mr->terminates = true;
1326     mr->destructor = memory_region_destructor_ram;
1327     mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1328
1329     /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL.  */
1330     assert(ptr != NULL);
1331     mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1332 }
1333
1334 void memory_region_set_skip_dump(MemoryRegion *mr)
1335 {
1336     mr->skip_dump = true;
1337 }
1338
1339 void memory_region_init_alias(MemoryRegion *mr,
1340                               Object *owner,
1341                               const char *name,
1342                               MemoryRegion *orig,
1343                               hwaddr offset,
1344                               uint64_t size)
1345 {
1346     memory_region_init(mr, owner, name, size);
1347     mr->alias = orig;
1348     mr->alias_offset = offset;
1349 }
1350
1351 void memory_region_init_rom_device(MemoryRegion *mr,
1352                                    Object *owner,
1353                                    const MemoryRegionOps *ops,
1354                                    void *opaque,
1355                                    const char *name,
1356                                    uint64_t size,
1357                                    Error **errp)
1358 {
1359     memory_region_init(mr, owner, name, size);
1360     mr->ops = ops;
1361     mr->opaque = opaque;
1362     mr->terminates = true;
1363     mr->rom_device = true;
1364     mr->destructor = memory_region_destructor_rom_device;
1365     mr->ram_block = qemu_ram_alloc(size, mr, errp);
1366 }
1367
1368 void memory_region_init_iommu(MemoryRegion *mr,
1369                               Object *owner,
1370                               const MemoryRegionIOMMUOps *ops,
1371                               const char *name,
1372                               uint64_t size)
1373 {
1374     memory_region_init(mr, owner, name, size);
1375     mr->iommu_ops = ops,
1376     mr->terminates = true;  /* then re-forwards */
1377     notifier_list_init(&mr->iommu_notify);
1378 }
1379
1380 static void memory_region_finalize(Object *obj)
1381 {
1382     MemoryRegion *mr = MEMORY_REGION(obj);
1383
1384     assert(!mr->container);
1385
1386     /* We know the region is not visible in any address space (it
1387      * does not have a container and cannot be a root either because
1388      * it has no references, so we can blindly clear mr->enabled.
1389      * memory_region_set_enabled instead could trigger a transaction
1390      * and cause an infinite loop.
1391      */
1392     mr->enabled = false;
1393     memory_region_transaction_begin();
1394     while (!QTAILQ_EMPTY(&mr->subregions)) {
1395         MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1396         memory_region_del_subregion(mr, subregion);
1397     }
1398     memory_region_transaction_commit();
1399
1400     mr->destructor(mr);
1401     memory_region_clear_coalescing(mr);
1402     g_free((char *)mr->name);
1403     g_free(mr->ioeventfds);
1404 }
1405
1406 Object *memory_region_owner(MemoryRegion *mr)
1407 {
1408     Object *obj = OBJECT(mr);
1409     return obj->parent;
1410 }
1411
1412 void memory_region_ref(MemoryRegion *mr)
1413 {
1414     /* MMIO callbacks most likely will access data that belongs
1415      * to the owner, hence the need to ref/unref the owner whenever
1416      * the memory region is in use.
1417      *
1418      * The memory region is a child of its owner.  As long as the
1419      * owner doesn't call unparent itself on the memory region,
1420      * ref-ing the owner will also keep the memory region alive.
1421      * Memory regions without an owner are supposed to never go away;
1422      * we do not ref/unref them because it slows down DMA sensibly.
1423      */
1424     if (mr && mr->owner) {
1425         object_ref(mr->owner);
1426     }
1427 }
1428
1429 void memory_region_unref(MemoryRegion *mr)
1430 {
1431     if (mr && mr->owner) {
1432         object_unref(mr->owner);
1433     }
1434 }
1435
1436 uint64_t memory_region_size(MemoryRegion *mr)
1437 {
1438     if (int128_eq(mr->size, int128_2_64())) {
1439         return UINT64_MAX;
1440     }
1441     return int128_get64(mr->size);
1442 }
1443
1444 const char *memory_region_name(const MemoryRegion *mr)
1445 {
1446     if (!mr->name) {
1447         ((MemoryRegion *)mr)->name =
1448             object_get_canonical_path_component(OBJECT(mr));
1449     }
1450     return mr->name;
1451 }
1452
1453 bool memory_region_is_skip_dump(MemoryRegion *mr)
1454 {
1455     return mr->skip_dump;
1456 }
1457
1458 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1459 {
1460     uint8_t mask = mr->dirty_log_mask;
1461     if (global_dirty_log) {
1462         mask |= (1 << DIRTY_MEMORY_MIGRATION);
1463     }
1464     return mask;
1465 }
1466
1467 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1468 {
1469     return memory_region_get_dirty_log_mask(mr) & (1 << client);
1470 }
1471
1472 void memory_region_register_iommu_notifier(MemoryRegion *mr, Notifier *n)
1473 {
1474     notifier_list_add(&mr->iommu_notify, n);
1475 }
1476
1477 void memory_region_iommu_replay(MemoryRegion *mr, Notifier *n,
1478                                 hwaddr granularity, bool is_write)
1479 {
1480     hwaddr addr;
1481     IOMMUTLBEntry iotlb;
1482
1483     for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1484         iotlb = mr->iommu_ops->translate(mr, addr, is_write);
1485         if (iotlb.perm != IOMMU_NONE) {
1486             n->notify(n, &iotlb);
1487         }
1488
1489         /* if (2^64 - MR size) < granularity, it's possible to get an
1490          * infinite loop here.  This should catch such a wraparound */
1491         if ((addr + granularity) < addr) {
1492             break;
1493         }
1494     }
1495 }
1496
1497 void memory_region_unregister_iommu_notifier(Notifier *n)
1498 {
1499     notifier_remove(n);
1500 }
1501
1502 void memory_region_notify_iommu(MemoryRegion *mr,
1503                                 IOMMUTLBEntry entry)
1504 {
1505     assert(memory_region_is_iommu(mr));
1506     notifier_list_notify(&mr->iommu_notify, &entry);
1507 }
1508
1509 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1510 {
1511     uint8_t mask = 1 << client;
1512     uint8_t old_logging;
1513
1514     assert(client == DIRTY_MEMORY_VGA);
1515     old_logging = mr->vga_logging_count;
1516     mr->vga_logging_count += log ? 1 : -1;
1517     if (!!old_logging == !!mr->vga_logging_count) {
1518         return;
1519     }
1520
1521     memory_region_transaction_begin();
1522     mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1523     memory_region_update_pending |= mr->enabled;
1524     memory_region_transaction_commit();
1525 }
1526
1527 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1528                              hwaddr size, unsigned client)
1529 {
1530     assert(mr->ram_block);
1531     return cpu_physical_memory_get_dirty(memory_region_get_ram_addr(mr) + addr,
1532                                          size, client);
1533 }
1534
1535 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1536                              hwaddr size)
1537 {
1538     assert(mr->ram_block);
1539     cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
1540                                         size,
1541                                         memory_region_get_dirty_log_mask(mr));
1542 }
1543
1544 bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,
1545                                         hwaddr size, unsigned client)
1546 {
1547     assert(mr->ram_block);
1548     return cpu_physical_memory_test_and_clear_dirty(
1549                 memory_region_get_ram_addr(mr) + addr, size, client);
1550 }
1551
1552
1553 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1554 {
1555     AddressSpace *as;
1556     FlatRange *fr;
1557
1558     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1559         FlatView *view = address_space_get_flatview(as);
1560         FOR_EACH_FLAT_RANGE(fr, view) {
1561             if (fr->mr == mr) {
1562                 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1563             }
1564         }
1565         flatview_unref(view);
1566     }
1567 }
1568
1569 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1570 {
1571     if (mr->readonly != readonly) {
1572         memory_region_transaction_begin();
1573         mr->readonly = readonly;
1574         memory_region_update_pending |= mr->enabled;
1575         memory_region_transaction_commit();
1576     }
1577 }
1578
1579 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
1580 {
1581     if (mr->romd_mode != romd_mode) {
1582         memory_region_transaction_begin();
1583         mr->romd_mode = romd_mode;
1584         memory_region_update_pending |= mr->enabled;
1585         memory_region_transaction_commit();
1586     }
1587 }
1588
1589 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1590                                hwaddr size, unsigned client)
1591 {
1592     assert(mr->ram_block);
1593     cpu_physical_memory_test_and_clear_dirty(
1594         memory_region_get_ram_addr(mr) + addr, size, client);
1595 }
1596
1597 int memory_region_get_fd(MemoryRegion *mr)
1598 {
1599     if (mr->alias) {
1600         return memory_region_get_fd(mr->alias);
1601     }
1602
1603     assert(mr->ram_block);
1604
1605     return qemu_get_ram_fd(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK);
1606 }
1607
1608 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1609 {
1610     void *ptr;
1611     uint64_t offset = 0;
1612
1613     rcu_read_lock();
1614     while (mr->alias) {
1615         offset += mr->alias_offset;
1616         mr = mr->alias;
1617     }
1618     assert(mr->ram_block);
1619     ptr = qemu_get_ram_ptr(mr->ram_block,
1620                            memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK);
1621     rcu_read_unlock();
1622
1623     return ptr + offset;
1624 }
1625
1626 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
1627 {
1628     return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
1629 }
1630
1631 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
1632 {
1633     assert(mr->ram_block);
1634
1635     qemu_ram_resize(memory_region_get_ram_addr(mr), newsize, errp);
1636 }
1637
1638 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1639 {
1640     FlatView *view;
1641     FlatRange *fr;
1642     CoalescedMemoryRange *cmr;
1643     AddrRange tmp;
1644     MemoryRegionSection section;
1645
1646     view = address_space_get_flatview(as);
1647     FOR_EACH_FLAT_RANGE(fr, view) {
1648         if (fr->mr == mr) {
1649             section = (MemoryRegionSection) {
1650                 .address_space = as,
1651                 .offset_within_address_space = int128_get64(fr->addr.start),
1652                 .size = fr->addr.size,
1653             };
1654
1655             MEMORY_LISTENER_CALL(coalesced_mmio_del, Reverse, &section,
1656                                  int128_get64(fr->addr.start),
1657                                  int128_get64(fr->addr.size));
1658             QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1659                 tmp = addrrange_shift(cmr->addr,
1660                                       int128_sub(fr->addr.start,
1661                                                  int128_make64(fr->offset_in_region)));
1662                 if (!addrrange_intersects(tmp, fr->addr)) {
1663                     continue;
1664                 }
1665                 tmp = addrrange_intersection(tmp, fr->addr);
1666                 MEMORY_LISTENER_CALL(coalesced_mmio_add, Forward, &section,
1667                                      int128_get64(tmp.start),
1668                                      int128_get64(tmp.size));
1669             }
1670         }
1671     }
1672     flatview_unref(view);
1673 }
1674
1675 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1676 {
1677     AddressSpace *as;
1678
1679     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1680         memory_region_update_coalesced_range_as(mr, as);
1681     }
1682 }
1683
1684 void memory_region_set_coalescing(MemoryRegion *mr)
1685 {
1686     memory_region_clear_coalescing(mr);
1687     memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1688 }
1689
1690 void memory_region_add_coalescing(MemoryRegion *mr,
1691                                   hwaddr offset,
1692                                   uint64_t size)
1693 {
1694     CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1695
1696     cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1697     QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1698     memory_region_update_coalesced_range(mr);
1699     memory_region_set_flush_coalesced(mr);
1700 }
1701
1702 void memory_region_clear_coalescing(MemoryRegion *mr)
1703 {
1704     CoalescedMemoryRange *cmr;
1705     bool updated = false;
1706
1707     qemu_flush_coalesced_mmio_buffer();
1708     mr->flush_coalesced_mmio = false;
1709
1710     while (!QTAILQ_EMPTY(&mr->coalesced)) {
1711         cmr = QTAILQ_FIRST(&mr->coalesced);
1712         QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1713         g_free(cmr);
1714         updated = true;
1715     }
1716
1717     if (updated) {
1718         memory_region_update_coalesced_range(mr);
1719     }
1720 }
1721
1722 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1723 {
1724     mr->flush_coalesced_mmio = true;
1725 }
1726
1727 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1728 {
1729     qemu_flush_coalesced_mmio_buffer();
1730     if (QTAILQ_EMPTY(&mr->coalesced)) {
1731         mr->flush_coalesced_mmio = false;
1732     }
1733 }
1734
1735 void memory_region_set_global_locking(MemoryRegion *mr)
1736 {
1737     mr->global_locking = true;
1738 }
1739
1740 void memory_region_clear_global_locking(MemoryRegion *mr)
1741 {
1742     mr->global_locking = false;
1743 }
1744
1745 static bool userspace_eventfd_warning;
1746
1747 void memory_region_add_eventfd(MemoryRegion *mr,
1748                                hwaddr addr,
1749                                unsigned size,
1750                                bool match_data,
1751                                uint64_t data,
1752                                EventNotifier *e)
1753 {
1754     MemoryRegionIoeventfd mrfd = {
1755         .addr.start = int128_make64(addr),
1756         .addr.size = int128_make64(size),
1757         .match_data = match_data,
1758         .data = data,
1759         .e = e,
1760     };
1761     unsigned i;
1762
1763     if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
1764                             userspace_eventfd_warning))) {
1765         userspace_eventfd_warning = true;
1766         error_report("Using eventfd without MMIO binding in KVM. "
1767                      "Suboptimal performance expected");
1768     }
1769
1770     if (size) {
1771         adjust_endianness(mr, &mrfd.data, size);
1772     }
1773     memory_region_transaction_begin();
1774     for (i = 0; i < mr->ioeventfd_nb; ++i) {
1775         if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
1776             break;
1777         }
1778     }
1779     ++mr->ioeventfd_nb;
1780     mr->ioeventfds = g_realloc(mr->ioeventfds,
1781                                   sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
1782     memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
1783             sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
1784     mr->ioeventfds[i] = mrfd;
1785     ioeventfd_update_pending |= mr->enabled;
1786     memory_region_transaction_commit();
1787 }
1788
1789 void memory_region_del_eventfd(MemoryRegion *mr,
1790                                hwaddr addr,
1791                                unsigned size,
1792                                bool match_data,
1793                                uint64_t data,
1794                                EventNotifier *e)
1795 {
1796     MemoryRegionIoeventfd mrfd = {
1797         .addr.start = int128_make64(addr),
1798         .addr.size = int128_make64(size),
1799         .match_data = match_data,
1800         .data = data,
1801         .e = e,
1802     };
1803     unsigned i;
1804
1805     if (size) {
1806         adjust_endianness(mr, &mrfd.data, size);
1807     }
1808     memory_region_transaction_begin();
1809     for (i = 0; i < mr->ioeventfd_nb; ++i) {
1810         if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
1811             break;
1812         }
1813     }
1814     assert(i != mr->ioeventfd_nb);
1815     memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
1816             sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
1817     --mr->ioeventfd_nb;
1818     mr->ioeventfds = g_realloc(mr->ioeventfds,
1819                                   sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
1820     ioeventfd_update_pending |= mr->enabled;
1821     memory_region_transaction_commit();
1822 }
1823
1824 static void memory_region_update_container_subregions(MemoryRegion *subregion)
1825 {
1826     hwaddr offset = subregion->addr;
1827     MemoryRegion *mr = subregion->container;
1828     MemoryRegion *other;
1829
1830     memory_region_transaction_begin();
1831
1832     memory_region_ref(subregion);
1833     QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1834         if (subregion->may_overlap || other->may_overlap) {
1835             continue;
1836         }
1837         if (int128_ge(int128_make64(offset),
1838                       int128_add(int128_make64(other->addr), other->size))
1839             || int128_le(int128_add(int128_make64(offset), subregion->size),
1840                          int128_make64(other->addr))) {
1841             continue;
1842         }
1843 #if 0
1844         printf("warning: subregion collision %llx/%llx (%s) "
1845                "vs %llx/%llx (%s)\n",
1846                (unsigned long long)offset,
1847                (unsigned long long)int128_get64(subregion->size),
1848                subregion->name,
1849                (unsigned long long)other->addr,
1850                (unsigned long long)int128_get64(other->size),
1851                other->name);
1852 #endif
1853     }
1854     QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1855         if (subregion->priority >= other->priority) {
1856             QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
1857             goto done;
1858         }
1859     }
1860     QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
1861 done:
1862     memory_region_update_pending |= mr->enabled && subregion->enabled;
1863     memory_region_transaction_commit();
1864 }
1865
1866 static void memory_region_add_subregion_common(MemoryRegion *mr,
1867                                                hwaddr offset,
1868                                                MemoryRegion *subregion)
1869 {
1870     assert(!subregion->container);
1871     subregion->container = mr;
1872     subregion->addr = offset;
1873     memory_region_update_container_subregions(subregion);
1874 }
1875
1876 void memory_region_add_subregion(MemoryRegion *mr,
1877                                  hwaddr offset,
1878                                  MemoryRegion *subregion)
1879 {
1880     subregion->may_overlap = false;
1881     subregion->priority = 0;
1882     memory_region_add_subregion_common(mr, offset, subregion);
1883 }
1884
1885 void memory_region_add_subregion_overlap(MemoryRegion *mr,
1886                                          hwaddr offset,
1887                                          MemoryRegion *subregion,
1888                                          int priority)
1889 {
1890     subregion->may_overlap = true;
1891     subregion->priority = priority;
1892     memory_region_add_subregion_common(mr, offset, subregion);
1893 }
1894
1895 void memory_region_del_subregion(MemoryRegion *mr,
1896                                  MemoryRegion *subregion)
1897 {
1898     memory_region_transaction_begin();
1899     assert(subregion->container == mr);
1900     subregion->container = NULL;
1901     QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
1902     memory_region_unref(subregion);
1903     memory_region_update_pending |= mr->enabled && subregion->enabled;
1904     memory_region_transaction_commit();
1905 }
1906
1907 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
1908 {
1909     if (enabled == mr->enabled) {
1910         return;
1911     }
1912     memory_region_transaction_begin();
1913     mr->enabled = enabled;
1914     memory_region_update_pending = true;
1915     memory_region_transaction_commit();
1916 }
1917
1918 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
1919 {
1920     Int128 s = int128_make64(size);
1921
1922     if (size == UINT64_MAX) {
1923         s = int128_2_64();
1924     }
1925     if (int128_eq(s, mr->size)) {
1926         return;
1927     }
1928     memory_region_transaction_begin();
1929     mr->size = s;
1930     memory_region_update_pending = true;
1931     memory_region_transaction_commit();
1932 }
1933
1934 static void memory_region_readd_subregion(MemoryRegion *mr)
1935 {
1936     MemoryRegion *container = mr->container;
1937
1938     if (container) {
1939         memory_region_transaction_begin();
1940         memory_region_ref(mr);
1941         memory_region_del_subregion(container, mr);
1942         mr->container = container;
1943         memory_region_update_container_subregions(mr);
1944         memory_region_unref(mr);
1945         memory_region_transaction_commit();
1946     }
1947 }
1948
1949 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
1950 {
1951     if (addr != mr->addr) {
1952         mr->addr = addr;
1953         memory_region_readd_subregion(mr);
1954     }
1955 }
1956
1957 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
1958 {
1959     assert(mr->alias);
1960
1961     if (offset == mr->alias_offset) {
1962         return;
1963     }
1964
1965     memory_region_transaction_begin();
1966     mr->alias_offset = offset;
1967     memory_region_update_pending |= mr->enabled;
1968     memory_region_transaction_commit();
1969 }
1970
1971 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
1972 {
1973     return mr->align;
1974 }
1975
1976 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
1977 {
1978     const AddrRange *addr = addr_;
1979     const FlatRange *fr = fr_;
1980
1981     if (int128_le(addrrange_end(*addr), fr->addr.start)) {
1982         return -1;
1983     } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
1984         return 1;
1985     }
1986     return 0;
1987 }
1988
1989 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
1990 {
1991     return bsearch(&addr, view->ranges, view->nr,
1992                    sizeof(FlatRange), cmp_flatrange_addr);
1993 }
1994
1995 bool memory_region_is_mapped(MemoryRegion *mr)
1996 {
1997     return mr->container ? true : false;
1998 }
1999
2000 /* Same as memory_region_find, but it does not add a reference to the
2001  * returned region.  It must be called from an RCU critical section.
2002  */
2003 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2004                                                   hwaddr addr, uint64_t size)
2005 {
2006     MemoryRegionSection ret = { .mr = NULL };
2007     MemoryRegion *root;
2008     AddressSpace *as;
2009     AddrRange range;
2010     FlatView *view;
2011     FlatRange *fr;
2012
2013     addr += mr->addr;
2014     for (root = mr; root->container; ) {
2015         root = root->container;
2016         addr += root->addr;
2017     }
2018
2019     as = memory_region_to_address_space(root);
2020     if (!as) {
2021         return ret;
2022     }
2023     range = addrrange_make(int128_make64(addr), int128_make64(size));
2024
2025     view = atomic_rcu_read(&as->current_map);
2026     fr = flatview_lookup(view, range);
2027     if (!fr) {
2028         return ret;
2029     }
2030
2031     while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2032         --fr;
2033     }
2034
2035     ret.mr = fr->mr;
2036     ret.address_space = as;
2037     range = addrrange_intersection(range, fr->addr);
2038     ret.offset_within_region = fr->offset_in_region;
2039     ret.offset_within_region += int128_get64(int128_sub(range.start,
2040                                                         fr->addr.start));
2041     ret.size = range.size;
2042     ret.offset_within_address_space = int128_get64(range.start);
2043     ret.readonly = fr->readonly;
2044     return ret;
2045 }
2046
2047 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2048                                        hwaddr addr, uint64_t size)
2049 {
2050     MemoryRegionSection ret;
2051     rcu_read_lock();
2052     ret = memory_region_find_rcu(mr, addr, size);
2053     if (ret.mr) {
2054         memory_region_ref(ret.mr);
2055     }
2056     rcu_read_unlock();
2057     return ret;
2058 }
2059
2060 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2061 {
2062     MemoryRegion *mr;
2063
2064     rcu_read_lock();
2065     mr = memory_region_find_rcu(container, addr, 1).mr;
2066     rcu_read_unlock();
2067     return mr && mr != container;
2068 }
2069
2070 void address_space_sync_dirty_bitmap(AddressSpace *as)
2071 {
2072     FlatView *view;
2073     FlatRange *fr;
2074
2075     view = address_space_get_flatview(as);
2076     FOR_EACH_FLAT_RANGE(fr, view) {
2077         MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
2078     }
2079     flatview_unref(view);
2080 }
2081
2082 void memory_global_dirty_log_start(void)
2083 {
2084     global_dirty_log = true;
2085
2086     MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2087
2088     /* Refresh DIRTY_LOG_MIGRATION bit.  */
2089     memory_region_transaction_begin();
2090     memory_region_update_pending = true;
2091     memory_region_transaction_commit();
2092 }
2093
2094 void memory_global_dirty_log_stop(void)
2095 {
2096     global_dirty_log = false;
2097
2098     /* Refresh DIRTY_LOG_MIGRATION bit.  */
2099     memory_region_transaction_begin();
2100     memory_region_update_pending = true;
2101     memory_region_transaction_commit();
2102
2103     MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2104 }
2105
2106 static void listener_add_address_space(MemoryListener *listener,
2107                                        AddressSpace *as)
2108 {
2109     FlatView *view;
2110     FlatRange *fr;
2111
2112     if (listener->address_space_filter
2113         && listener->address_space_filter != as) {
2114         return;
2115     }
2116
2117     if (listener->begin) {
2118         listener->begin(listener);
2119     }
2120     if (global_dirty_log) {
2121         if (listener->log_global_start) {
2122             listener->log_global_start(listener);
2123         }
2124     }
2125
2126     view = address_space_get_flatview(as);
2127     FOR_EACH_FLAT_RANGE(fr, view) {
2128         MemoryRegionSection section = {
2129             .mr = fr->mr,
2130             .address_space = as,
2131             .offset_within_region = fr->offset_in_region,
2132             .size = fr->addr.size,
2133             .offset_within_address_space = int128_get64(fr->addr.start),
2134             .readonly = fr->readonly,
2135         };
2136         if (fr->dirty_log_mask && listener->log_start) {
2137             listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2138         }
2139         if (listener->region_add) {
2140             listener->region_add(listener, &section);
2141         }
2142     }
2143     if (listener->commit) {
2144         listener->commit(listener);
2145     }
2146     flatview_unref(view);
2147 }
2148
2149 void memory_listener_register(MemoryListener *listener, AddressSpace *filter)
2150 {
2151     MemoryListener *other = NULL;
2152     AddressSpace *as;
2153
2154     listener->address_space_filter = filter;
2155     if (QTAILQ_EMPTY(&memory_listeners)
2156         || listener->priority >= QTAILQ_LAST(&memory_listeners,
2157                                              memory_listeners)->priority) {
2158         QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2159     } else {
2160         QTAILQ_FOREACH(other, &memory_listeners, link) {
2161             if (listener->priority < other->priority) {
2162                 break;
2163             }
2164         }
2165         QTAILQ_INSERT_BEFORE(other, listener, link);
2166     }
2167
2168     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2169         listener_add_address_space(listener, as);
2170     }
2171 }
2172
2173 void memory_listener_unregister(MemoryListener *listener)
2174 {
2175     QTAILQ_REMOVE(&memory_listeners, listener, link);
2176 }
2177
2178 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2179 {
2180     memory_region_ref(root);
2181     memory_region_transaction_begin();
2182     as->ref_count = 1;
2183     as->root = root;
2184     as->malloced = false;
2185     as->current_map = g_new(FlatView, 1);
2186     flatview_init(as->current_map);
2187     as->ioeventfd_nb = 0;
2188     as->ioeventfds = NULL;
2189     QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2190     as->name = g_strdup(name ? name : "anonymous");
2191     address_space_init_dispatch(as);
2192     memory_region_update_pending |= root->enabled;
2193     memory_region_transaction_commit();
2194 }
2195
2196 static void do_address_space_destroy(AddressSpace *as)
2197 {
2198     MemoryListener *listener;
2199     bool do_free = as->malloced;
2200
2201     address_space_destroy_dispatch(as);
2202
2203     QTAILQ_FOREACH(listener, &memory_listeners, link) {
2204         assert(listener->address_space_filter != as);
2205     }
2206
2207     flatview_unref(as->current_map);
2208     g_free(as->name);
2209     g_free(as->ioeventfds);
2210     memory_region_unref(as->root);
2211     if (do_free) {
2212         g_free(as);
2213     }
2214 }
2215
2216 AddressSpace *address_space_init_shareable(MemoryRegion *root, const char *name)
2217 {
2218     AddressSpace *as;
2219
2220     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2221         if (root == as->root && as->malloced) {
2222             as->ref_count++;
2223             return as;
2224         }
2225     }
2226
2227     as = g_malloc0(sizeof *as);
2228     address_space_init(as, root, name);
2229     as->malloced = true;
2230     return as;
2231 }
2232
2233 void address_space_destroy(AddressSpace *as)
2234 {
2235     MemoryRegion *root = as->root;
2236
2237     as->ref_count--;
2238     if (as->ref_count) {
2239         return;
2240     }
2241     /* Flush out anything from MemoryListeners listening in on this */
2242     memory_region_transaction_begin();
2243     as->root = NULL;
2244     memory_region_transaction_commit();
2245     QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2246     address_space_unregister(as);
2247
2248     /* At this point, as->dispatch and as->current_map are dummy
2249      * entries that the guest should never use.  Wait for the old
2250      * values to expire before freeing the data.
2251      */
2252     as->root = root;
2253     call_rcu(as, do_address_space_destroy, rcu);
2254 }
2255
2256 typedef struct MemoryRegionList MemoryRegionList;
2257
2258 struct MemoryRegionList {
2259     const MemoryRegion *mr;
2260     QTAILQ_ENTRY(MemoryRegionList) queue;
2261 };
2262
2263 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
2264
2265 static void mtree_print_mr(fprintf_function mon_printf, void *f,
2266                            const MemoryRegion *mr, unsigned int level,
2267                            hwaddr base,
2268                            MemoryRegionListHead *alias_print_queue)
2269 {
2270     MemoryRegionList *new_ml, *ml, *next_ml;
2271     MemoryRegionListHead submr_print_queue;
2272     const MemoryRegion *submr;
2273     unsigned int i;
2274
2275     if (!mr) {
2276         return;
2277     }
2278
2279     for (i = 0; i < level; i++) {
2280         mon_printf(f, "  ");
2281     }
2282
2283     if (mr->alias) {
2284         MemoryRegionList *ml;
2285         bool found = false;
2286
2287         /* check if the alias is already in the queue */
2288         QTAILQ_FOREACH(ml, alias_print_queue, queue) {
2289             if (ml->mr == mr->alias) {
2290                 found = true;
2291             }
2292         }
2293
2294         if (!found) {
2295             ml = g_new(MemoryRegionList, 1);
2296             ml->mr = mr->alias;
2297             QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
2298         }
2299         mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
2300                    " (prio %d, %c%c): alias %s @%s " TARGET_FMT_plx
2301                    "-" TARGET_FMT_plx "%s\n",
2302                    base + mr->addr,
2303                    base + mr->addr
2304                    + (int128_nz(mr->size) ?
2305                       (hwaddr)int128_get64(int128_sub(mr->size,
2306                                                       int128_one())) : 0),
2307                    mr->priority,
2308                    mr->romd_mode ? 'R' : '-',
2309                    !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2310                                                                        : '-',
2311                    memory_region_name(mr),
2312                    memory_region_name(mr->alias),
2313                    mr->alias_offset,
2314                    mr->alias_offset
2315                    + (int128_nz(mr->size) ?
2316                       (hwaddr)int128_get64(int128_sub(mr->size,
2317                                                       int128_one())) : 0),
2318                    mr->enabled ? "" : " [disabled]");
2319     } else {
2320         mon_printf(f,
2321                    TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %c%c): %s%s\n",
2322                    base + mr->addr,
2323                    base + mr->addr
2324                    + (int128_nz(mr->size) ?
2325                       (hwaddr)int128_get64(int128_sub(mr->size,
2326                                                       int128_one())) : 0),
2327                    mr->priority,
2328                    mr->romd_mode ? 'R' : '-',
2329                    !mr->readonly && !(mr->rom_device && mr->romd_mode) ? 'W'
2330                                                                        : '-',
2331                    memory_region_name(mr),
2332                    mr->enabled ? "" : " [disabled]");
2333     }
2334
2335     QTAILQ_INIT(&submr_print_queue);
2336
2337     QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2338         new_ml = g_new(MemoryRegionList, 1);
2339         new_ml->mr = submr;
2340         QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2341             if (new_ml->mr->addr < ml->mr->addr ||
2342                 (new_ml->mr->addr == ml->mr->addr &&
2343                  new_ml->mr->priority > ml->mr->priority)) {
2344                 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
2345                 new_ml = NULL;
2346                 break;
2347             }
2348         }
2349         if (new_ml) {
2350             QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
2351         }
2352     }
2353
2354     QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2355         mtree_print_mr(mon_printf, f, ml->mr, level + 1, base + mr->addr,
2356                        alias_print_queue);
2357     }
2358
2359     QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
2360         g_free(ml);
2361     }
2362 }
2363
2364 void mtree_info(fprintf_function mon_printf, void *f)
2365 {
2366     MemoryRegionListHead ml_head;
2367     MemoryRegionList *ml, *ml2;
2368     AddressSpace *as;
2369
2370     QTAILQ_INIT(&ml_head);
2371
2372     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2373         mon_printf(f, "address-space: %s\n", as->name);
2374         mtree_print_mr(mon_printf, f, as->root, 1, 0, &ml_head);
2375         mon_printf(f, "\n");
2376     }
2377
2378     /* print aliased regions */
2379     QTAILQ_FOREACH(ml, &ml_head, queue) {
2380         mon_printf(f, "memory-region: %s\n", memory_region_name(ml->mr));
2381         mtree_print_mr(mon_printf, f, ml->mr, 1, 0, &ml_head);
2382         mon_printf(f, "\n");
2383     }
2384
2385     QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
2386         g_free(ml);
2387     }
2388 }
2389
2390 static const TypeInfo memory_region_info = {
2391     .parent             = TYPE_OBJECT,
2392     .name               = TYPE_MEMORY_REGION,
2393     .instance_size      = sizeof(MemoryRegion),
2394     .instance_init      = memory_region_initfn,
2395     .instance_finalize  = memory_region_finalize,
2396 };
2397
2398 static void memory_register_types(void)
2399 {
2400     type_register_static(&memory_region_info);
2401 }
2402
2403 type_init(memory_register_types)