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