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