exec: move include files to include/exec/
[sdk/emulator/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 "exec/memory.h"
17 #include "exec/address-spaces.h"
18 #include "exec/ioport.h"
19 #include "bitops.h"
20 #include "kvm.h"
21 #include <assert.h>
22
23 #include "exec/memory-internal.h"
24
25 static unsigned memory_region_transaction_depth;
26 static bool memory_region_update_pending;
27 static bool global_dirty_log = false;
28
29 static QTAILQ_HEAD(memory_listeners, MemoryListener) memory_listeners
30     = QTAILQ_HEAD_INITIALIZER(memory_listeners);
31
32 static QTAILQ_HEAD(, AddressSpace) address_spaces
33     = QTAILQ_HEAD_INITIALIZER(address_spaces);
34
35 typedef struct AddrRange AddrRange;
36
37 /*
38  * Note using signed integers limits us to physical addresses at most
39  * 63 bits wide.  They are needed for negative offsetting in aliases
40  * (large MemoryRegion::alias_offset).
41  */
42 struct AddrRange {
43     Int128 start;
44     Int128 size;
45 };
46
47 static AddrRange addrrange_make(Int128 start, Int128 size)
48 {
49     return (AddrRange) { start, size };
50 }
51
52 static bool addrrange_equal(AddrRange r1, AddrRange r2)
53 {
54     return int128_eq(r1.start, r2.start) && int128_eq(r1.size, r2.size);
55 }
56
57 static Int128 addrrange_end(AddrRange r)
58 {
59     return int128_add(r.start, r.size);
60 }
61
62 static AddrRange addrrange_shift(AddrRange range, Int128 delta)
63 {
64     int128_addto(&range.start, delta);
65     return range;
66 }
67
68 static bool addrrange_contains(AddrRange range, Int128 addr)
69 {
70     return int128_ge(addr, range.start)
71         && int128_lt(addr, addrrange_end(range));
72 }
73
74 static bool addrrange_intersects(AddrRange r1, AddrRange r2)
75 {
76     return addrrange_contains(r1, r2.start)
77         || addrrange_contains(r2, r1.start);
78 }
79
80 static AddrRange addrrange_intersection(AddrRange r1, AddrRange r2)
81 {
82     Int128 start = int128_max(r1.start, r2.start);
83     Int128 end = int128_min(addrrange_end(r1), addrrange_end(r2));
84     return addrrange_make(start, int128_sub(end, start));
85 }
86
87 enum ListenerDirection { Forward, Reverse };
88
89 static bool memory_listener_match(MemoryListener *listener,
90                                   MemoryRegionSection *section)
91 {
92     return !listener->address_space_filter
93         || listener->address_space_filter == section->address_space;
94 }
95
96 #define MEMORY_LISTENER_CALL_GLOBAL(_callback, _direction, _args...)    \
97     do {                                                                \
98         MemoryListener *_listener;                                      \
99                                                                         \
100         switch (_direction) {                                           \
101         case Forward:                                                   \
102             QTAILQ_FOREACH(_listener, &memory_listeners, link) {        \
103                 if (_listener->_callback) {                             \
104                     _listener->_callback(_listener, ##_args);           \
105                 }                                                       \
106             }                                                           \
107             break;                                                      \
108         case Reverse:                                                   \
109             QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners,        \
110                                    memory_listeners, link) {            \
111                 if (_listener->_callback) {                             \
112                     _listener->_callback(_listener, ##_args);           \
113                 }                                                       \
114             }                                                           \
115             break;                                                      \
116         default:                                                        \
117             abort();                                                    \
118         }                                                               \
119     } while (0)
120
121 #define MEMORY_LISTENER_CALL(_callback, _direction, _section, _args...) \
122     do {                                                                \
123         MemoryListener *_listener;                                      \
124                                                                         \
125         switch (_direction) {                                           \
126         case Forward:                                                   \
127             QTAILQ_FOREACH(_listener, &memory_listeners, link) {        \
128                 if (_listener->_callback                                \
129                     && memory_listener_match(_listener, _section)) {    \
130                     _listener->_callback(_listener, _section, ##_args); \
131                 }                                                       \
132             }                                                           \
133             break;                                                      \
134         case Reverse:                                                   \
135             QTAILQ_FOREACH_REVERSE(_listener, &memory_listeners,        \
136                                    memory_listeners, link) {            \
137                 if (_listener->_callback                                \
138                     && memory_listener_match(_listener, _section)) {    \
139                     _listener->_callback(_listener, _section, ##_args); \
140                 }                                                       \
141             }                                                           \
142             break;                                                      \
143         default:                                                        \
144             abort();                                                    \
145         }                                                               \
146     } while (0)
147
148 #define MEMORY_LISTENER_UPDATE_REGION(fr, as, dir, callback)            \
149     MEMORY_LISTENER_CALL(callback, dir, (&(MemoryRegionSection) {       \
150         .mr = (fr)->mr,                                                 \
151         .address_space = (as),                                          \
152         .offset_within_region = (fr)->offset_in_region,                 \
153         .size = int128_get64((fr)->addr.size),                          \
154         .offset_within_address_space = int128_get64((fr)->addr.start),  \
155         .readonly = (fr)->readonly,                                     \
156               }))
157
158 struct CoalescedMemoryRange {
159     AddrRange addr;
160     QTAILQ_ENTRY(CoalescedMemoryRange) link;
161 };
162
163 struct MemoryRegionIoeventfd {
164     AddrRange addr;
165     bool match_data;
166     uint64_t data;
167     EventNotifier *e;
168 };
169
170 static bool memory_region_ioeventfd_before(MemoryRegionIoeventfd a,
171                                            MemoryRegionIoeventfd b)
172 {
173     if (int128_lt(a.addr.start, b.addr.start)) {
174         return true;
175     } else if (int128_gt(a.addr.start, b.addr.start)) {
176         return false;
177     } else if (int128_lt(a.addr.size, b.addr.size)) {
178         return true;
179     } else if (int128_gt(a.addr.size, b.addr.size)) {
180         return false;
181     } else if (a.match_data < b.match_data) {
182         return true;
183     } else  if (a.match_data > b.match_data) {
184         return false;
185     } else if (a.match_data) {
186         if (a.data < b.data) {
187             return true;
188         } else if (a.data > b.data) {
189             return false;
190         }
191     }
192     if (a.e < b.e) {
193         return true;
194     } else if (a.e > b.e) {
195         return false;
196     }
197     return false;
198 }
199
200 static bool memory_region_ioeventfd_equal(MemoryRegionIoeventfd a,
201                                           MemoryRegionIoeventfd b)
202 {
203     return !memory_region_ioeventfd_before(a, b)
204         && !memory_region_ioeventfd_before(b, a);
205 }
206
207 typedef struct FlatRange FlatRange;
208 typedef struct FlatView FlatView;
209
210 /* Range of memory in the global map.  Addresses are absolute. */
211 struct FlatRange {
212     MemoryRegion *mr;
213     hwaddr offset_in_region;
214     AddrRange addr;
215     uint8_t dirty_log_mask;
216     bool readable;
217     bool readonly;
218 };
219
220 /* Flattened global view of current active memory hierarchy.  Kept in sorted
221  * order.
222  */
223 struct FlatView {
224     FlatRange *ranges;
225     unsigned nr;
226     unsigned nr_allocated;
227 };
228
229 typedef struct AddressSpaceOps AddressSpaceOps;
230
231 #define FOR_EACH_FLAT_RANGE(var, view)          \
232     for (var = (view)->ranges; var < (view)->ranges + (view)->nr; ++var)
233
234 static bool flatrange_equal(FlatRange *a, FlatRange *b)
235 {
236     return a->mr == b->mr
237         && addrrange_equal(a->addr, b->addr)
238         && a->offset_in_region == b->offset_in_region
239         && a->readable == b->readable
240         && a->readonly == b->readonly;
241 }
242
243 static void flatview_init(FlatView *view)
244 {
245     view->ranges = NULL;
246     view->nr = 0;
247     view->nr_allocated = 0;
248 }
249
250 /* Insert a range into a given position.  Caller is responsible for maintaining
251  * sorting order.
252  */
253 static void flatview_insert(FlatView *view, unsigned pos, FlatRange *range)
254 {
255     if (view->nr == view->nr_allocated) {
256         view->nr_allocated = MAX(2 * view->nr, 10);
257         view->ranges = g_realloc(view->ranges,
258                                     view->nr_allocated * sizeof(*view->ranges));
259     }
260     memmove(view->ranges + pos + 1, view->ranges + pos,
261             (view->nr - pos) * sizeof(FlatRange));
262     view->ranges[pos] = *range;
263     ++view->nr;
264 }
265
266 static void flatview_destroy(FlatView *view)
267 {
268     g_free(view->ranges);
269 }
270
271 static bool can_merge(FlatRange *r1, FlatRange *r2)
272 {
273     return int128_eq(addrrange_end(r1->addr), r2->addr.start)
274         && r1->mr == r2->mr
275         && int128_eq(int128_add(int128_make64(r1->offset_in_region),
276                                 r1->addr.size),
277                      int128_make64(r2->offset_in_region))
278         && r1->dirty_log_mask == r2->dirty_log_mask
279         && r1->readable == r2->readable
280         && r1->readonly == r2->readonly;
281 }
282
283 /* Attempt to simplify a view by merging ajacent ranges */
284 static void flatview_simplify(FlatView *view)
285 {
286     unsigned i, j;
287
288     i = 0;
289     while (i < view->nr) {
290         j = i + 1;
291         while (j < view->nr
292                && can_merge(&view->ranges[j-1], &view->ranges[j])) {
293             int128_addto(&view->ranges[i].addr.size, view->ranges[j].addr.size);
294             ++j;
295         }
296         ++i;
297         memmove(&view->ranges[i], &view->ranges[j],
298                 (view->nr - j) * sizeof(view->ranges[j]));
299         view->nr -= j - i;
300     }
301 }
302
303 static void memory_region_read_accessor(void *opaque,
304                                         hwaddr addr,
305                                         uint64_t *value,
306                                         unsigned size,
307                                         unsigned shift,
308                                         uint64_t mask)
309 {
310     MemoryRegion *mr = opaque;
311     uint64_t tmp;
312
313     if (mr->flush_coalesced_mmio) {
314         qemu_flush_coalesced_mmio_buffer();
315     }
316     tmp = mr->ops->read(mr->opaque, addr, size);
317     *value |= (tmp & mask) << shift;
318 }
319
320 static void memory_region_write_accessor(void *opaque,
321                                          hwaddr addr,
322                                          uint64_t *value,
323                                          unsigned size,
324                                          unsigned shift,
325                                          uint64_t mask)
326 {
327     MemoryRegion *mr = opaque;
328     uint64_t tmp;
329
330     if (mr->flush_coalesced_mmio) {
331         qemu_flush_coalesced_mmio_buffer();
332     }
333     tmp = (*value >> shift) & mask;
334     mr->ops->write(mr->opaque, addr, tmp, size);
335 }
336
337 static void access_with_adjusted_size(hwaddr addr,
338                                       uint64_t *value,
339                                       unsigned size,
340                                       unsigned access_size_min,
341                                       unsigned access_size_max,
342                                       void (*access)(void *opaque,
343                                                      hwaddr addr,
344                                                      uint64_t *value,
345                                                      unsigned size,
346                                                      unsigned shift,
347                                                      uint64_t mask),
348                                       void *opaque)
349 {
350     uint64_t access_mask;
351     unsigned access_size;
352     unsigned i;
353
354     if (!access_size_min) {
355         access_size_min = 1;
356     }
357     if (!access_size_max) {
358         access_size_max = 4;
359     }
360     access_size = MAX(MIN(size, access_size_max), access_size_min);
361     access_mask = -1ULL >> (64 - access_size * 8);
362     for (i = 0; i < size; i += access_size) {
363         /* FIXME: big-endian support */
364         access(opaque, addr + i, value, access_size, i * 8, access_mask);
365     }
366 }
367
368 static const MemoryRegionPortio *find_portio(MemoryRegion *mr, uint64_t offset,
369                                              unsigned width, bool write)
370 {
371     const MemoryRegionPortio *mrp;
372
373     for (mrp = mr->ops->old_portio; mrp->size; ++mrp) {
374         if (offset >= mrp->offset && offset < mrp->offset + mrp->len
375             && width == mrp->size
376             && (write ? (bool)mrp->write : (bool)mrp->read)) {
377             return mrp;
378         }
379     }
380     return NULL;
381 }
382
383 static void memory_region_iorange_read(IORange *iorange,
384                                        uint64_t offset,
385                                        unsigned width,
386                                        uint64_t *data)
387 {
388     MemoryRegionIORange *mrio
389         = container_of(iorange, MemoryRegionIORange, iorange);
390     MemoryRegion *mr = mrio->mr;
391
392     offset += mrio->offset;
393     if (mr->ops->old_portio) {
394         const MemoryRegionPortio *mrp = find_portio(mr, offset - mrio->offset,
395                                                     width, false);
396
397         *data = ((uint64_t)1 << (width * 8)) - 1;
398         if (mrp) {
399             *data = mrp->read(mr->opaque, offset);
400         } else if (width == 2) {
401             mrp = find_portio(mr, offset - mrio->offset, 1, false);
402             assert(mrp);
403             *data = mrp->read(mr->opaque, offset) |
404                     (mrp->read(mr->opaque, offset + 1) << 8);
405         }
406         return;
407     }
408     *data = 0;
409     access_with_adjusted_size(offset, data, width,
410                               mr->ops->impl.min_access_size,
411                               mr->ops->impl.max_access_size,
412                               memory_region_read_accessor, mr);
413 }
414
415 static void memory_region_iorange_write(IORange *iorange,
416                                         uint64_t offset,
417                                         unsigned width,
418                                         uint64_t data)
419 {
420     MemoryRegionIORange *mrio
421         = container_of(iorange, MemoryRegionIORange, iorange);
422     MemoryRegion *mr = mrio->mr;
423
424     offset += mrio->offset;
425     if (mr->ops->old_portio) {
426         const MemoryRegionPortio *mrp = find_portio(mr, offset - mrio->offset,
427                                                     width, true);
428
429         if (mrp) {
430             mrp->write(mr->opaque, offset, data);
431         } else if (width == 2) {
432             mrp = find_portio(mr, offset - mrio->offset, 1, true);
433             assert(mrp);
434             mrp->write(mr->opaque, offset, data & 0xff);
435             mrp->write(mr->opaque, offset + 1, data >> 8);
436         }
437         return;
438     }
439     access_with_adjusted_size(offset, &data, width,
440                               mr->ops->impl.min_access_size,
441                               mr->ops->impl.max_access_size,
442                               memory_region_write_accessor, mr);
443 }
444
445 static void memory_region_iorange_destructor(IORange *iorange)
446 {
447     g_free(container_of(iorange, MemoryRegionIORange, iorange));
448 }
449
450 const IORangeOps memory_region_iorange_ops = {
451     .read = memory_region_iorange_read,
452     .write = memory_region_iorange_write,
453     .destructor = memory_region_iorange_destructor,
454 };
455
456 static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)
457 {
458     AddressSpace *as;
459
460     while (mr->parent) {
461         mr = mr->parent;
462     }
463     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
464         if (mr == as->root) {
465             return as;
466         }
467     }
468     abort();
469 }
470
471 /* Render a memory region into the global view.  Ranges in @view obscure
472  * ranges in @mr.
473  */
474 static void render_memory_region(FlatView *view,
475                                  MemoryRegion *mr,
476                                  Int128 base,
477                                  AddrRange clip,
478                                  bool readonly)
479 {
480     MemoryRegion *subregion;
481     unsigned i;
482     hwaddr offset_in_region;
483     Int128 remain;
484     Int128 now;
485     FlatRange fr;
486     AddrRange tmp;
487
488     if (!mr->enabled) {
489         return;
490     }
491
492     int128_addto(&base, int128_make64(mr->addr));
493     readonly |= mr->readonly;
494
495     tmp = addrrange_make(base, mr->size);
496
497     if (!addrrange_intersects(tmp, clip)) {
498         return;
499     }
500
501     clip = addrrange_intersection(tmp, clip);
502
503     if (mr->alias) {
504         int128_subfrom(&base, int128_make64(mr->alias->addr));
505         int128_subfrom(&base, int128_make64(mr->alias_offset));
506         render_memory_region(view, mr->alias, base, clip, readonly);
507         return;
508     }
509
510     /* Render subregions in priority order. */
511     QTAILQ_FOREACH(subregion, &mr->subregions, subregions_link) {
512         render_memory_region(view, subregion, base, clip, readonly);
513     }
514
515     if (!mr->terminates) {
516         return;
517     }
518
519     offset_in_region = int128_get64(int128_sub(clip.start, base));
520     base = clip.start;
521     remain = clip.size;
522
523     /* Render the region itself into any gaps left by the current view. */
524     for (i = 0; i < view->nr && int128_nz(remain); ++i) {
525         if (int128_ge(base, addrrange_end(view->ranges[i].addr))) {
526             continue;
527         }
528         if (int128_lt(base, view->ranges[i].addr.start)) {
529             now = int128_min(remain,
530                              int128_sub(view->ranges[i].addr.start, base));
531             fr.mr = mr;
532             fr.offset_in_region = offset_in_region;
533             fr.addr = addrrange_make(base, now);
534             fr.dirty_log_mask = mr->dirty_log_mask;
535             fr.readable = mr->readable;
536             fr.readonly = readonly;
537             flatview_insert(view, i, &fr);
538             ++i;
539             int128_addto(&base, now);
540             offset_in_region += int128_get64(now);
541             int128_subfrom(&remain, now);
542         }
543         now = int128_sub(int128_min(int128_add(base, remain),
544                                     addrrange_end(view->ranges[i].addr)),
545                          base);
546         int128_addto(&base, now);
547         offset_in_region += int128_get64(now);
548         int128_subfrom(&remain, now);
549     }
550     if (int128_nz(remain)) {
551         fr.mr = mr;
552         fr.offset_in_region = offset_in_region;
553         fr.addr = addrrange_make(base, remain);
554         fr.dirty_log_mask = mr->dirty_log_mask;
555         fr.readable = mr->readable;
556         fr.readonly = readonly;
557         flatview_insert(view, i, &fr);
558     }
559 }
560
561 /* Render a memory topology into a list of disjoint absolute ranges. */
562 static FlatView generate_memory_topology(MemoryRegion *mr)
563 {
564     FlatView view;
565
566     flatview_init(&view);
567
568     if (mr) {
569         render_memory_region(&view, mr, int128_zero(),
570                              addrrange_make(int128_zero(), int128_2_64()), false);
571     }
572     flatview_simplify(&view);
573
574     return view;
575 }
576
577 static void address_space_add_del_ioeventfds(AddressSpace *as,
578                                              MemoryRegionIoeventfd *fds_new,
579                                              unsigned fds_new_nb,
580                                              MemoryRegionIoeventfd *fds_old,
581                                              unsigned fds_old_nb)
582 {
583     unsigned iold, inew;
584     MemoryRegionIoeventfd *fd;
585     MemoryRegionSection section;
586
587     /* Generate a symmetric difference of the old and new fd sets, adding
588      * and deleting as necessary.
589      */
590
591     iold = inew = 0;
592     while (iold < fds_old_nb || inew < fds_new_nb) {
593         if (iold < fds_old_nb
594             && (inew == fds_new_nb
595                 || memory_region_ioeventfd_before(fds_old[iold],
596                                                   fds_new[inew]))) {
597             fd = &fds_old[iold];
598             section = (MemoryRegionSection) {
599                 .address_space = as,
600                 .offset_within_address_space = int128_get64(fd->addr.start),
601                 .size = int128_get64(fd->addr.size),
602             };
603             MEMORY_LISTENER_CALL(eventfd_del, Forward, &section,
604                                  fd->match_data, fd->data, fd->e);
605             ++iold;
606         } else if (inew < fds_new_nb
607                    && (iold == fds_old_nb
608                        || memory_region_ioeventfd_before(fds_new[inew],
609                                                          fds_old[iold]))) {
610             fd = &fds_new[inew];
611             section = (MemoryRegionSection) {
612                 .address_space = as,
613                 .offset_within_address_space = int128_get64(fd->addr.start),
614                 .size = int128_get64(fd->addr.size),
615             };
616             MEMORY_LISTENER_CALL(eventfd_add, Reverse, &section,
617                                  fd->match_data, fd->data, fd->e);
618             ++inew;
619         } else {
620             ++iold;
621             ++inew;
622         }
623     }
624 }
625
626 static void address_space_update_ioeventfds(AddressSpace *as)
627 {
628     FlatRange *fr;
629     unsigned ioeventfd_nb = 0;
630     MemoryRegionIoeventfd *ioeventfds = NULL;
631     AddrRange tmp;
632     unsigned i;
633
634     FOR_EACH_FLAT_RANGE(fr, as->current_map) {
635         for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {
636             tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,
637                                   int128_sub(fr->addr.start,
638                                              int128_make64(fr->offset_in_region)));
639             if (addrrange_intersects(fr->addr, tmp)) {
640                 ++ioeventfd_nb;
641                 ioeventfds = g_realloc(ioeventfds,
642                                           ioeventfd_nb * sizeof(*ioeventfds));
643                 ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];
644                 ioeventfds[ioeventfd_nb-1].addr = tmp;
645             }
646         }
647     }
648
649     address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,
650                                      as->ioeventfds, as->ioeventfd_nb);
651
652     g_free(as->ioeventfds);
653     as->ioeventfds = ioeventfds;
654     as->ioeventfd_nb = ioeventfd_nb;
655 }
656
657 static void address_space_update_topology_pass(AddressSpace *as,
658                                                FlatView old_view,
659                                                FlatView new_view,
660                                                bool adding)
661 {
662     unsigned iold, inew;
663     FlatRange *frold, *frnew;
664
665     /* Generate a symmetric difference of the old and new memory maps.
666      * Kill ranges in the old map, and instantiate ranges in the new map.
667      */
668     iold = inew = 0;
669     while (iold < old_view.nr || inew < new_view.nr) {
670         if (iold < old_view.nr) {
671             frold = &old_view.ranges[iold];
672         } else {
673             frold = NULL;
674         }
675         if (inew < new_view.nr) {
676             frnew = &new_view.ranges[inew];
677         } else {
678             frnew = NULL;
679         }
680
681         if (frold
682             && (!frnew
683                 || int128_lt(frold->addr.start, frnew->addr.start)
684                 || (int128_eq(frold->addr.start, frnew->addr.start)
685                     && !flatrange_equal(frold, frnew)))) {
686             /* In old, but (not in new, or in new but attributes changed). */
687
688             if (!adding) {
689                 MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);
690             }
691
692             ++iold;
693         } else if (frold && frnew && flatrange_equal(frold, frnew)) {
694             /* In both (logging may have changed) */
695
696             if (adding) {
697                 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);
698                 if (frold->dirty_log_mask && !frnew->dirty_log_mask) {
699                     MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop);
700                 } else if (frnew->dirty_log_mask && !frold->dirty_log_mask) {
701                     MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start);
702                 }
703             }
704
705             ++iold;
706             ++inew;
707         } else {
708             /* In new */
709
710             if (adding) {
711                 MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);
712             }
713
714             ++inew;
715         }
716     }
717 }
718
719
720 static void address_space_update_topology(AddressSpace *as)
721 {
722     FlatView old_view = *as->current_map;
723     FlatView new_view = generate_memory_topology(as->root);
724
725     address_space_update_topology_pass(as, old_view, new_view, false);
726     address_space_update_topology_pass(as, old_view, new_view, true);
727
728     *as->current_map = new_view;
729     flatview_destroy(&old_view);
730     address_space_update_ioeventfds(as);
731 }
732
733 void memory_region_transaction_begin(void)
734 {
735     qemu_flush_coalesced_mmio_buffer();
736     ++memory_region_transaction_depth;
737 }
738
739 void memory_region_transaction_commit(void)
740 {
741     AddressSpace *as;
742
743     assert(memory_region_transaction_depth);
744     --memory_region_transaction_depth;
745     if (!memory_region_transaction_depth && memory_region_update_pending) {
746         memory_region_update_pending = false;
747         MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
748
749         QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
750             address_space_update_topology(as);
751         }
752
753         MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
754     }
755 }
756
757 static void memory_region_destructor_none(MemoryRegion *mr)
758 {
759 }
760
761 static void memory_region_destructor_ram(MemoryRegion *mr)
762 {
763     qemu_ram_free(mr->ram_addr);
764 }
765
766 static void memory_region_destructor_ram_from_ptr(MemoryRegion *mr)
767 {
768     qemu_ram_free_from_ptr(mr->ram_addr);
769 }
770
771 static void memory_region_destructor_iomem(MemoryRegion *mr)
772 {
773 }
774
775 static void memory_region_destructor_rom_device(MemoryRegion *mr)
776 {
777     qemu_ram_free(mr->ram_addr & TARGET_PAGE_MASK);
778 }
779
780 static bool memory_region_wrong_endianness(MemoryRegion *mr)
781 {
782 #ifdef TARGET_WORDS_BIGENDIAN
783     return mr->ops->endianness == DEVICE_LITTLE_ENDIAN;
784 #else
785     return mr->ops->endianness == DEVICE_BIG_ENDIAN;
786 #endif
787 }
788
789 void memory_region_init(MemoryRegion *mr,
790                         const char *name,
791                         uint64_t size)
792 {
793     mr->ops = NULL;
794     mr->parent = NULL;
795     mr->size = int128_make64(size);
796     if (size == UINT64_MAX) {
797         mr->size = int128_2_64();
798     }
799     mr->addr = 0;
800     mr->subpage = false;
801     mr->enabled = true;
802     mr->terminates = false;
803     mr->ram = false;
804     mr->readable = true;
805     mr->readonly = false;
806     mr->rom_device = false;
807     mr->destructor = memory_region_destructor_none;
808     mr->priority = 0;
809     mr->may_overlap = false;
810     mr->alias = NULL;
811     QTAILQ_INIT(&mr->subregions);
812     memset(&mr->subregions_link, 0, sizeof mr->subregions_link);
813     QTAILQ_INIT(&mr->coalesced);
814     mr->name = g_strdup(name);
815     mr->dirty_log_mask = 0;
816     mr->ioeventfd_nb = 0;
817     mr->ioeventfds = NULL;
818     mr->flush_coalesced_mmio = false;
819 }
820
821 static bool memory_region_access_valid(MemoryRegion *mr,
822                                        hwaddr addr,
823                                        unsigned size,
824                                        bool is_write)
825 {
826     if (mr->ops->valid.accepts
827         && !mr->ops->valid.accepts(mr->opaque, addr, size, is_write)) {
828         return false;
829     }
830
831     if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
832         return false;
833     }
834
835     /* Treat zero as compatibility all valid */
836     if (!mr->ops->valid.max_access_size) {
837         return true;
838     }
839
840     if (size > mr->ops->valid.max_access_size
841         || size < mr->ops->valid.min_access_size) {
842         return false;
843     }
844     return true;
845 }
846
847 static uint64_t memory_region_dispatch_read1(MemoryRegion *mr,
848                                              hwaddr addr,
849                                              unsigned size)
850 {
851     uint64_t data = 0;
852
853     if (!memory_region_access_valid(mr, addr, size, false)) {
854         return -1U; /* FIXME: better signalling */
855     }
856
857     if (!mr->ops->read) {
858         return mr->ops->old_mmio.read[bitops_ffsl(size)](mr->opaque, addr);
859     }
860
861     /* FIXME: support unaligned access */
862     access_with_adjusted_size(addr, &data, size,
863                               mr->ops->impl.min_access_size,
864                               mr->ops->impl.max_access_size,
865                               memory_region_read_accessor, mr);
866
867     return data;
868 }
869
870 static void adjust_endianness(MemoryRegion *mr, uint64_t *data, unsigned size)
871 {
872     if (memory_region_wrong_endianness(mr)) {
873         switch (size) {
874         case 1:
875             break;
876         case 2:
877             *data = bswap16(*data);
878             break;
879         case 4:
880             *data = bswap32(*data);
881             break;
882         default:
883             abort();
884         }
885     }
886 }
887
888 static uint64_t memory_region_dispatch_read(MemoryRegion *mr,
889                                             hwaddr addr,
890                                             unsigned size)
891 {
892     uint64_t ret;
893
894     ret = memory_region_dispatch_read1(mr, addr, size);
895     adjust_endianness(mr, &ret, size);
896     return ret;
897 }
898
899 static void memory_region_dispatch_write(MemoryRegion *mr,
900                                          hwaddr addr,
901                                          uint64_t data,
902                                          unsigned size)
903 {
904     if (!memory_region_access_valid(mr, addr, size, true)) {
905         return; /* FIXME: better signalling */
906     }
907
908     adjust_endianness(mr, &data, size);
909
910     if (!mr->ops->write) {
911         mr->ops->old_mmio.write[bitops_ffsl(size)](mr->opaque, addr, data);
912         return;
913     }
914
915     /* FIXME: support unaligned access */
916     access_with_adjusted_size(addr, &data, size,
917                               mr->ops->impl.min_access_size,
918                               mr->ops->impl.max_access_size,
919                               memory_region_write_accessor, mr);
920 }
921
922 void memory_region_init_io(MemoryRegion *mr,
923                            const MemoryRegionOps *ops,
924                            void *opaque,
925                            const char *name,
926                            uint64_t size)
927 {
928     memory_region_init(mr, name, size);
929     mr->ops = ops;
930     mr->opaque = opaque;
931     mr->terminates = true;
932     mr->destructor = memory_region_destructor_iomem;
933     mr->ram_addr = ~(ram_addr_t)0;
934 }
935
936 void memory_region_init_ram(MemoryRegion *mr,
937                             const char *name,
938                             uint64_t size)
939 {
940     memory_region_init(mr, name, size);
941     mr->ram = true;
942     mr->terminates = true;
943     mr->destructor = memory_region_destructor_ram;
944     mr->ram_addr = qemu_ram_alloc(size, mr);
945 }
946
947 void memory_region_init_ram_ptr(MemoryRegion *mr,
948                                 const char *name,
949                                 uint64_t size,
950                                 void *ptr)
951 {
952     memory_region_init(mr, name, size);
953     mr->ram = true;
954     mr->terminates = true;
955     mr->destructor = memory_region_destructor_ram_from_ptr;
956     mr->ram_addr = qemu_ram_alloc_from_ptr(size, ptr, mr);
957 }
958
959 void memory_region_init_alias(MemoryRegion *mr,
960                               const char *name,
961                               MemoryRegion *orig,
962                               hwaddr offset,
963                               uint64_t size)
964 {
965     memory_region_init(mr, name, size);
966     mr->alias = orig;
967     mr->alias_offset = offset;
968 }
969
970 void memory_region_init_rom_device(MemoryRegion *mr,
971                                    const MemoryRegionOps *ops,
972                                    void *opaque,
973                                    const char *name,
974                                    uint64_t size)
975 {
976     memory_region_init(mr, name, size);
977     mr->ops = ops;
978     mr->opaque = opaque;
979     mr->terminates = true;
980     mr->rom_device = true;
981     mr->destructor = memory_region_destructor_rom_device;
982     mr->ram_addr = qemu_ram_alloc(size, mr);
983 }
984
985 static uint64_t invalid_read(void *opaque, hwaddr addr,
986                              unsigned size)
987 {
988     MemoryRegion *mr = opaque;
989
990     if (!mr->warning_printed) {
991         fprintf(stderr, "Invalid read from memory region %s\n", mr->name);
992         mr->warning_printed = true;
993     }
994     return -1U;
995 }
996
997 static void invalid_write(void *opaque, hwaddr addr, uint64_t data,
998                           unsigned size)
999 {
1000     MemoryRegion *mr = opaque;
1001
1002     if (!mr->warning_printed) {
1003         fprintf(stderr, "Invalid write to memory region %s\n", mr->name);
1004         mr->warning_printed = true;
1005     }
1006 }
1007
1008 static const MemoryRegionOps reservation_ops = {
1009     .read = invalid_read,
1010     .write = invalid_write,
1011     .endianness = DEVICE_NATIVE_ENDIAN,
1012 };
1013
1014 void memory_region_init_reservation(MemoryRegion *mr,
1015                                     const char *name,
1016                                     uint64_t size)
1017 {
1018     memory_region_init_io(mr, &reservation_ops, mr, name, size);
1019 }
1020
1021 void memory_region_destroy(MemoryRegion *mr)
1022 {
1023     assert(QTAILQ_EMPTY(&mr->subregions));
1024     assert(memory_region_transaction_depth == 0);
1025     mr->destructor(mr);
1026     memory_region_clear_coalescing(mr);
1027     g_free((char *)mr->name);
1028     g_free(mr->ioeventfds);
1029 }
1030
1031 uint64_t memory_region_size(MemoryRegion *mr)
1032 {
1033     if (int128_eq(mr->size, int128_2_64())) {
1034         return UINT64_MAX;
1035     }
1036     return int128_get64(mr->size);
1037 }
1038
1039 const char *memory_region_name(MemoryRegion *mr)
1040 {
1041     return mr->name;
1042 }
1043
1044 bool memory_region_is_ram(MemoryRegion *mr)
1045 {
1046     return mr->ram;
1047 }
1048
1049 bool memory_region_is_logging(MemoryRegion *mr)
1050 {
1051     return mr->dirty_log_mask;
1052 }
1053
1054 bool memory_region_is_rom(MemoryRegion *mr)
1055 {
1056     return mr->ram && mr->readonly;
1057 }
1058
1059 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1060 {
1061     uint8_t mask = 1 << client;
1062
1063     memory_region_transaction_begin();
1064     mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1065     memory_region_update_pending |= mr->enabled;
1066     memory_region_transaction_commit();
1067 }
1068
1069 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1070                              hwaddr size, unsigned client)
1071 {
1072     assert(mr->terminates);
1073     return cpu_physical_memory_get_dirty(mr->ram_addr + addr, size,
1074                                          1 << client);
1075 }
1076
1077 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1078                              hwaddr size)
1079 {
1080     assert(mr->terminates);
1081     return cpu_physical_memory_set_dirty_range(mr->ram_addr + addr, size, -1);
1082 }
1083
1084 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1085 {
1086     AddressSpace *as;
1087     FlatRange *fr;
1088
1089     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1090         FOR_EACH_FLAT_RANGE(fr, as->current_map) {
1091             if (fr->mr == mr) {
1092                 MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1093             }
1094         }
1095     }
1096 }
1097
1098 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1099 {
1100     if (mr->readonly != readonly) {
1101         memory_region_transaction_begin();
1102         mr->readonly = readonly;
1103         memory_region_update_pending |= mr->enabled;
1104         memory_region_transaction_commit();
1105     }
1106 }
1107
1108 void memory_region_rom_device_set_readable(MemoryRegion *mr, bool readable)
1109 {
1110     if (mr->readable != readable) {
1111         memory_region_transaction_begin();
1112         mr->readable = readable;
1113         memory_region_update_pending |= mr->enabled;
1114         memory_region_transaction_commit();
1115     }
1116 }
1117
1118 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1119                                hwaddr size, unsigned client)
1120 {
1121     assert(mr->terminates);
1122     cpu_physical_memory_reset_dirty(mr->ram_addr + addr,
1123                                     mr->ram_addr + addr + size,
1124                                     1 << client);
1125 }
1126
1127 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1128 {
1129     if (mr->alias) {
1130         return memory_region_get_ram_ptr(mr->alias) + mr->alias_offset;
1131     }
1132
1133     assert(mr->terminates);
1134
1135     return qemu_get_ram_ptr(mr->ram_addr & TARGET_PAGE_MASK);
1136 }
1137
1138 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1139 {
1140     FlatRange *fr;
1141     CoalescedMemoryRange *cmr;
1142     AddrRange tmp;
1143     MemoryRegionSection section;
1144
1145     FOR_EACH_FLAT_RANGE(fr, as->current_map) {
1146         if (fr->mr == mr) {
1147             section = (MemoryRegionSection) {
1148                 .address_space = as,
1149                 .offset_within_address_space = int128_get64(fr->addr.start),
1150                 .size = int128_get64(fr->addr.size),
1151             };
1152
1153             MEMORY_LISTENER_CALL(coalesced_mmio_del, Reverse, &section,
1154                                  int128_get64(fr->addr.start),
1155                                  int128_get64(fr->addr.size));
1156             QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1157                 tmp = addrrange_shift(cmr->addr,
1158                                       int128_sub(fr->addr.start,
1159                                                  int128_make64(fr->offset_in_region)));
1160                 if (!addrrange_intersects(tmp, fr->addr)) {
1161                     continue;
1162                 }
1163                 tmp = addrrange_intersection(tmp, fr->addr);
1164                 MEMORY_LISTENER_CALL(coalesced_mmio_add, Forward, &section,
1165                                      int128_get64(tmp.start),
1166                                      int128_get64(tmp.size));
1167             }
1168         }
1169     }
1170 }
1171
1172 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1173 {
1174     AddressSpace *as;
1175
1176     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1177         memory_region_update_coalesced_range_as(mr, as);
1178     }
1179 }
1180
1181 void memory_region_set_coalescing(MemoryRegion *mr)
1182 {
1183     memory_region_clear_coalescing(mr);
1184     memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1185 }
1186
1187 void memory_region_add_coalescing(MemoryRegion *mr,
1188                                   hwaddr offset,
1189                                   uint64_t size)
1190 {
1191     CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1192
1193     cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1194     QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1195     memory_region_update_coalesced_range(mr);
1196     memory_region_set_flush_coalesced(mr);
1197 }
1198
1199 void memory_region_clear_coalescing(MemoryRegion *mr)
1200 {
1201     CoalescedMemoryRange *cmr;
1202
1203     qemu_flush_coalesced_mmio_buffer();
1204     mr->flush_coalesced_mmio = false;
1205
1206     while (!QTAILQ_EMPTY(&mr->coalesced)) {
1207         cmr = QTAILQ_FIRST(&mr->coalesced);
1208         QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1209         g_free(cmr);
1210     }
1211     memory_region_update_coalesced_range(mr);
1212 }
1213
1214 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1215 {
1216     mr->flush_coalesced_mmio = true;
1217 }
1218
1219 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1220 {
1221     qemu_flush_coalesced_mmio_buffer();
1222     if (QTAILQ_EMPTY(&mr->coalesced)) {
1223         mr->flush_coalesced_mmio = false;
1224     }
1225 }
1226
1227 void memory_region_add_eventfd(MemoryRegion *mr,
1228                                hwaddr addr,
1229                                unsigned size,
1230                                bool match_data,
1231                                uint64_t data,
1232                                EventNotifier *e)
1233 {
1234     MemoryRegionIoeventfd mrfd = {
1235         .addr.start = int128_make64(addr),
1236         .addr.size = int128_make64(size),
1237         .match_data = match_data,
1238         .data = data,
1239         .e = e,
1240     };
1241     unsigned i;
1242
1243     adjust_endianness(mr, &mrfd.data, size);
1244     memory_region_transaction_begin();
1245     for (i = 0; i < mr->ioeventfd_nb; ++i) {
1246         if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
1247             break;
1248         }
1249     }
1250     ++mr->ioeventfd_nb;
1251     mr->ioeventfds = g_realloc(mr->ioeventfds,
1252                                   sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
1253     memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
1254             sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
1255     mr->ioeventfds[i] = mrfd;
1256     memory_region_update_pending |= mr->enabled;
1257     memory_region_transaction_commit();
1258 }
1259
1260 void memory_region_del_eventfd(MemoryRegion *mr,
1261                                hwaddr addr,
1262                                unsigned size,
1263                                bool match_data,
1264                                uint64_t data,
1265                                EventNotifier *e)
1266 {
1267     MemoryRegionIoeventfd mrfd = {
1268         .addr.start = int128_make64(addr),
1269         .addr.size = int128_make64(size),
1270         .match_data = match_data,
1271         .data = data,
1272         .e = e,
1273     };
1274     unsigned i;
1275
1276     adjust_endianness(mr, &mrfd.data, size);
1277     memory_region_transaction_begin();
1278     for (i = 0; i < mr->ioeventfd_nb; ++i) {
1279         if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
1280             break;
1281         }
1282     }
1283     assert(i != mr->ioeventfd_nb);
1284     memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
1285             sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
1286     --mr->ioeventfd_nb;
1287     mr->ioeventfds = g_realloc(mr->ioeventfds,
1288                                   sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
1289     memory_region_update_pending |= mr->enabled;
1290     memory_region_transaction_commit();
1291 }
1292
1293 static void memory_region_add_subregion_common(MemoryRegion *mr,
1294                                                hwaddr offset,
1295                                                MemoryRegion *subregion)
1296 {
1297     MemoryRegion *other;
1298
1299     memory_region_transaction_begin();
1300
1301     assert(!subregion->parent);
1302     subregion->parent = mr;
1303     subregion->addr = offset;
1304     QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1305         if (subregion->may_overlap || other->may_overlap) {
1306             continue;
1307         }
1308         if (int128_gt(int128_make64(offset),
1309                       int128_add(int128_make64(other->addr), other->size))
1310             || int128_le(int128_add(int128_make64(offset), subregion->size),
1311                          int128_make64(other->addr))) {
1312             continue;
1313         }
1314 #if 0
1315         printf("warning: subregion collision %llx/%llx (%s) "
1316                "vs %llx/%llx (%s)\n",
1317                (unsigned long long)offset,
1318                (unsigned long long)int128_get64(subregion->size),
1319                subregion->name,
1320                (unsigned long long)other->addr,
1321                (unsigned long long)int128_get64(other->size),
1322                other->name);
1323 #endif
1324     }
1325     QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
1326         if (subregion->priority >= other->priority) {
1327             QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
1328             goto done;
1329         }
1330     }
1331     QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
1332 done:
1333     memory_region_update_pending |= mr->enabled && subregion->enabled;
1334     memory_region_transaction_commit();
1335 }
1336
1337
1338 void memory_region_add_subregion(MemoryRegion *mr,
1339                                  hwaddr offset,
1340                                  MemoryRegion *subregion)
1341 {
1342     subregion->may_overlap = false;
1343     subregion->priority = 0;
1344     memory_region_add_subregion_common(mr, offset, subregion);
1345 }
1346
1347 void memory_region_add_subregion_overlap(MemoryRegion *mr,
1348                                          hwaddr offset,
1349                                          MemoryRegion *subregion,
1350                                          unsigned priority)
1351 {
1352     subregion->may_overlap = true;
1353     subregion->priority = priority;
1354     memory_region_add_subregion_common(mr, offset, subregion);
1355 }
1356
1357 void memory_region_del_subregion(MemoryRegion *mr,
1358                                  MemoryRegion *subregion)
1359 {
1360     memory_region_transaction_begin();
1361     assert(subregion->parent == mr);
1362     subregion->parent = NULL;
1363     QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
1364     memory_region_update_pending |= mr->enabled && subregion->enabled;
1365     memory_region_transaction_commit();
1366 }
1367
1368 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
1369 {
1370     if (enabled == mr->enabled) {
1371         return;
1372     }
1373     memory_region_transaction_begin();
1374     mr->enabled = enabled;
1375     memory_region_update_pending = true;
1376     memory_region_transaction_commit();
1377 }
1378
1379 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
1380 {
1381     MemoryRegion *parent = mr->parent;
1382     unsigned priority = mr->priority;
1383     bool may_overlap = mr->may_overlap;
1384
1385     if (addr == mr->addr || !parent) {
1386         mr->addr = addr;
1387         return;
1388     }
1389
1390     memory_region_transaction_begin();
1391     memory_region_del_subregion(parent, mr);
1392     if (may_overlap) {
1393         memory_region_add_subregion_overlap(parent, addr, mr, priority);
1394     } else {
1395         memory_region_add_subregion(parent, addr, mr);
1396     }
1397     memory_region_transaction_commit();
1398 }
1399
1400 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
1401 {
1402     assert(mr->alias);
1403
1404     if (offset == mr->alias_offset) {
1405         return;
1406     }
1407
1408     memory_region_transaction_begin();
1409     mr->alias_offset = offset;
1410     memory_region_update_pending |= mr->enabled;
1411     memory_region_transaction_commit();
1412 }
1413
1414 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
1415 {
1416     return mr->ram_addr;
1417 }
1418
1419 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
1420 {
1421     const AddrRange *addr = addr_;
1422     const FlatRange *fr = fr_;
1423
1424     if (int128_le(addrrange_end(*addr), fr->addr.start)) {
1425         return -1;
1426     } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
1427         return 1;
1428     }
1429     return 0;
1430 }
1431
1432 static FlatRange *address_space_lookup(AddressSpace *as, AddrRange addr)
1433 {
1434     return bsearch(&addr, as->current_map->ranges, as->current_map->nr,
1435                    sizeof(FlatRange), cmp_flatrange_addr);
1436 }
1437
1438 MemoryRegionSection memory_region_find(MemoryRegion *address_space,
1439                                        hwaddr addr, uint64_t size)
1440 {
1441     AddressSpace *as = memory_region_to_address_space(address_space);
1442     AddrRange range = addrrange_make(int128_make64(addr),
1443                                      int128_make64(size));
1444     FlatRange *fr = address_space_lookup(as, range);
1445     MemoryRegionSection ret = { .mr = NULL, .size = 0 };
1446
1447     if (!fr) {
1448         return ret;
1449     }
1450
1451     while (fr > as->current_map->ranges
1452            && addrrange_intersects(fr[-1].addr, range)) {
1453         --fr;
1454     }
1455
1456     ret.mr = fr->mr;
1457     range = addrrange_intersection(range, fr->addr);
1458     ret.offset_within_region = fr->offset_in_region;
1459     ret.offset_within_region += int128_get64(int128_sub(range.start,
1460                                                         fr->addr.start));
1461     ret.size = int128_get64(range.size);
1462     ret.offset_within_address_space = int128_get64(range.start);
1463     ret.readonly = fr->readonly;
1464     return ret;
1465 }
1466
1467 void memory_global_sync_dirty_bitmap(MemoryRegion *address_space)
1468 {
1469     AddressSpace *as = memory_region_to_address_space(address_space);
1470     FlatRange *fr;
1471
1472     FOR_EACH_FLAT_RANGE(fr, as->current_map) {
1473         MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);
1474     }
1475 }
1476
1477 void memory_global_dirty_log_start(void)
1478 {
1479     global_dirty_log = true;
1480     MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
1481 }
1482
1483 void memory_global_dirty_log_stop(void)
1484 {
1485     global_dirty_log = false;
1486     MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
1487 }
1488
1489 static void listener_add_address_space(MemoryListener *listener,
1490                                        AddressSpace *as)
1491 {
1492     FlatRange *fr;
1493
1494     if (listener->address_space_filter
1495         && listener->address_space_filter != as) {
1496         return;
1497     }
1498
1499     if (global_dirty_log) {
1500         if (listener->log_global_start) {
1501             listener->log_global_start(listener);
1502         }
1503     }
1504
1505     FOR_EACH_FLAT_RANGE(fr, as->current_map) {
1506         MemoryRegionSection section = {
1507             .mr = fr->mr,
1508             .address_space = as,
1509             .offset_within_region = fr->offset_in_region,
1510             .size = int128_get64(fr->addr.size),
1511             .offset_within_address_space = int128_get64(fr->addr.start),
1512             .readonly = fr->readonly,
1513         };
1514         if (listener->region_add) {
1515             listener->region_add(listener, &section);
1516         }
1517     }
1518 }
1519
1520 void memory_listener_register(MemoryListener *listener, AddressSpace *filter)
1521 {
1522     MemoryListener *other = NULL;
1523     AddressSpace *as;
1524
1525     listener->address_space_filter = filter;
1526     if (QTAILQ_EMPTY(&memory_listeners)
1527         || listener->priority >= QTAILQ_LAST(&memory_listeners,
1528                                              memory_listeners)->priority) {
1529         QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
1530     } else {
1531         QTAILQ_FOREACH(other, &memory_listeners, link) {
1532             if (listener->priority < other->priority) {
1533                 break;
1534             }
1535         }
1536         QTAILQ_INSERT_BEFORE(other, listener, link);
1537     }
1538
1539     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1540         listener_add_address_space(listener, as);
1541     }
1542 }
1543
1544 void memory_listener_unregister(MemoryListener *listener)
1545 {
1546     QTAILQ_REMOVE(&memory_listeners, listener, link);
1547 }
1548
1549 void address_space_init(AddressSpace *as, MemoryRegion *root)
1550 {
1551     memory_region_transaction_begin();
1552     as->root = root;
1553     as->current_map = g_new(FlatView, 1);
1554     flatview_init(as->current_map);
1555     QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
1556     as->name = NULL;
1557     memory_region_transaction_commit();
1558     address_space_init_dispatch(as);
1559 }
1560
1561 void address_space_destroy(AddressSpace *as)
1562 {
1563     /* Flush out anything from MemoryListeners listening in on this */
1564     memory_region_transaction_begin();
1565     as->root = NULL;
1566     memory_region_transaction_commit();
1567     QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
1568     address_space_destroy_dispatch(as);
1569     flatview_destroy(as->current_map);
1570     g_free(as->current_map);
1571 }
1572
1573 uint64_t io_mem_read(MemoryRegion *mr, hwaddr addr, unsigned size)
1574 {
1575     return memory_region_dispatch_read(mr, addr, size);
1576 }
1577
1578 void io_mem_write(MemoryRegion *mr, hwaddr addr,
1579                   uint64_t val, unsigned size)
1580 {
1581     memory_region_dispatch_write(mr, addr, val, size);
1582 }
1583
1584 typedef struct MemoryRegionList MemoryRegionList;
1585
1586 struct MemoryRegionList {
1587     const MemoryRegion *mr;
1588     bool printed;
1589     QTAILQ_ENTRY(MemoryRegionList) queue;
1590 };
1591
1592 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
1593
1594 static void mtree_print_mr(fprintf_function mon_printf, void *f,
1595                            const MemoryRegion *mr, unsigned int level,
1596                            hwaddr base,
1597                            MemoryRegionListHead *alias_print_queue)
1598 {
1599     MemoryRegionList *new_ml, *ml, *next_ml;
1600     MemoryRegionListHead submr_print_queue;
1601     const MemoryRegion *submr;
1602     unsigned int i;
1603
1604     if (!mr || !mr->enabled) {
1605         return;
1606     }
1607
1608     for (i = 0; i < level; i++) {
1609         mon_printf(f, "  ");
1610     }
1611
1612     if (mr->alias) {
1613         MemoryRegionList *ml;
1614         bool found = false;
1615
1616         /* check if the alias is already in the queue */
1617         QTAILQ_FOREACH(ml, alias_print_queue, queue) {
1618             if (ml->mr == mr->alias && !ml->printed) {
1619                 found = true;
1620             }
1621         }
1622
1623         if (!found) {
1624             ml = g_new(MemoryRegionList, 1);
1625             ml->mr = mr->alias;
1626             ml->printed = false;
1627             QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
1628         }
1629         mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
1630                    " (prio %d, %c%c): alias %s @%s " TARGET_FMT_plx
1631                    "-" TARGET_FMT_plx "\n",
1632                    base + mr->addr,
1633                    base + mr->addr
1634                    + (hwaddr)int128_get64(mr->size) - 1,
1635                    mr->priority,
1636                    mr->readable ? 'R' : '-',
1637                    !mr->readonly && !(mr->rom_device && mr->readable) ? 'W'
1638                                                                       : '-',
1639                    mr->name,
1640                    mr->alias->name,
1641                    mr->alias_offset,
1642                    mr->alias_offset
1643                    + (hwaddr)int128_get64(mr->size) - 1);
1644     } else {
1645         mon_printf(f,
1646                    TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %c%c): %s\n",
1647                    base + mr->addr,
1648                    base + mr->addr
1649                    + (hwaddr)int128_get64(mr->size) - 1,
1650                    mr->priority,
1651                    mr->readable ? 'R' : '-',
1652                    !mr->readonly && !(mr->rom_device && mr->readable) ? 'W'
1653                                                                       : '-',
1654                    mr->name);
1655     }
1656
1657     QTAILQ_INIT(&submr_print_queue);
1658
1659     QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
1660         new_ml = g_new(MemoryRegionList, 1);
1661         new_ml->mr = submr;
1662         QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
1663             if (new_ml->mr->addr < ml->mr->addr ||
1664                 (new_ml->mr->addr == ml->mr->addr &&
1665                  new_ml->mr->priority > ml->mr->priority)) {
1666                 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
1667                 new_ml = NULL;
1668                 break;
1669             }
1670         }
1671         if (new_ml) {
1672             QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
1673         }
1674     }
1675
1676     QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
1677         mtree_print_mr(mon_printf, f, ml->mr, level + 1, base + mr->addr,
1678                        alias_print_queue);
1679     }
1680
1681     QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
1682         g_free(ml);
1683     }
1684 }
1685
1686 void mtree_info(fprintf_function mon_printf, void *f)
1687 {
1688     MemoryRegionListHead ml_head;
1689     MemoryRegionList *ml, *ml2;
1690     AddressSpace *as;
1691
1692     QTAILQ_INIT(&ml_head);
1693
1694     QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1695         if (!as->name) {
1696             continue;
1697         }
1698         mon_printf(f, "%s\n", as->name);
1699         mtree_print_mr(mon_printf, f, as->root, 0, 0, &ml_head);
1700     }
1701
1702     mon_printf(f, "aliases\n");
1703     /* print aliased regions */
1704     QTAILQ_FOREACH(ml, &ml_head, queue) {
1705         if (!ml->printed) {
1706             mon_printf(f, "%s\n", ml->mr->name);
1707             mtree_print_mr(mon_printf, f, ml->mr, 0, 0, &ml_head);
1708         }
1709     }
1710
1711     QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
1712         g_free(ml);
1713     }
1714 }