overall/alpha tcg cpus|hppa: Fix Lesser GPL version number
[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 fuzz_dma_read_cb(addr, size, mr, false);
1437 if (!memory_region_access_valid(mr, addr, size, false, attrs)) {
1438 *pval = unassigned_mem_read(mr, addr, size);
1439 return MEMTX_DECODE_ERROR;
1440 }
1441
1442 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1443 adjust_endianness(mr, pval, op);
1444 return r;
1445 }
1446
1447 /* Return true if an eventfd was signalled */
1448 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1449 hwaddr addr,
1450 uint64_t data,
1451 unsigned size,
1452 MemTxAttrs attrs)
1453 {
1454 MemoryRegionIoeventfd ioeventfd = {
1455 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1456 .data = data,
1457 };
1458 unsigned i;
1459
1460 for (i = 0; i < mr->ioeventfd_nb; i++) {
1461 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1462 ioeventfd.e = mr->ioeventfds[i].e;
1463
1464 if (memory_region_ioeventfd_equal(&ioeventfd, &mr->ioeventfds[i])) {
1465 event_notifier_set(ioeventfd.e);
1466 return true;
1467 }
1468 }
1469
1470 return false;
1471 }
1472
1473 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1474 hwaddr addr,
1475 uint64_t data,
1476 MemOp op,
1477 MemTxAttrs attrs)
1478 {
1479 unsigned size = memop_size(op);
1480
1481 if (!memory_region_access_valid(mr, addr, size, true, attrs)) {
1482 unassigned_mem_write(mr, addr, data, size);
1483 return MEMTX_DECODE_ERROR;
1484 }
1485
1486 adjust_endianness(mr, &data, op);
1487
1488 if ((!kvm_eventfds_enabled()) &&
1489 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1490 return MEMTX_OK;
1491 }
1492
1493 if (mr->ops->write) {
1494 return access_with_adjusted_size(addr, &data, size,
1495 mr->ops->impl.min_access_size,
1496 mr->ops->impl.max_access_size,
1497 memory_region_write_accessor, mr,
1498 attrs);
1499 } else {
1500 return
1501 access_with_adjusted_size(addr, &data, size,
1502 mr->ops->impl.min_access_size,
1503 mr->ops->impl.max_access_size,
1504 memory_region_write_with_attrs_accessor,
1505 mr, attrs);
1506 }
1507 }
1508
1509 void memory_region_init_io(MemoryRegion *mr,
1510 Object *owner,
1511 const MemoryRegionOps *ops,
1512 void *opaque,
1513 const char *name,
1514 uint64_t size)
1515 {
1516 memory_region_init(mr, owner, name, size);
1517 mr->ops = ops ? ops : &unassigned_mem_ops;
1518 mr->opaque = opaque;
1519 mr->terminates = true;
1520 }
1521
1522 void memory_region_init_ram_nomigrate(MemoryRegion *mr,
1523 Object *owner,
1524 const char *name,
1525 uint64_t size,
1526 Error **errp)
1527 {
1528 memory_region_init_ram_shared_nomigrate(mr, owner, name, size, false, errp);
1529 }
1530
1531 void memory_region_init_ram_shared_nomigrate(MemoryRegion *mr,
1532 Object *owner,
1533 const char *name,
1534 uint64_t size,
1535 bool share,
1536 Error **errp)
1537 {
1538 Error *err = NULL;
1539 memory_region_init(mr, owner, name, size);
1540 mr->ram = true;
1541 mr->terminates = true;
1542 mr->destructor = memory_region_destructor_ram;
1543 mr->ram_block = qemu_ram_alloc(size, share, mr, &err);
1544 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1545 if (err) {
1546 mr->size = int128_zero();
1547 object_unparent(OBJECT(mr));
1548 error_propagate(errp, err);
1549 }
1550 }
1551
1552 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1553 Object *owner,
1554 const char *name,
1555 uint64_t size,
1556 uint64_t max_size,
1557 void (*resized)(const char*,
1558 uint64_t length,
1559 void *host),
1560 Error **errp)
1561 {
1562 Error *err = NULL;
1563 memory_region_init(mr, owner, name, size);
1564 mr->ram = true;
1565 mr->terminates = true;
1566 mr->destructor = memory_region_destructor_ram;
1567 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1568 mr, &err);
1569 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1570 if (err) {
1571 mr->size = int128_zero();
1572 object_unparent(OBJECT(mr));
1573 error_propagate(errp, err);
1574 }
1575 }
1576
1577 #ifdef CONFIG_POSIX
1578 void memory_region_init_ram_from_file(MemoryRegion *mr,
1579 struct Object *owner,
1580 const char *name,
1581 uint64_t size,
1582 uint64_t align,
1583 uint32_t ram_flags,
1584 const char *path,
1585 Error **errp)
1586 {
1587 Error *err = NULL;
1588 memory_region_init(mr, owner, name, size);
1589 mr->ram = true;
1590 mr->terminates = true;
1591 mr->destructor = memory_region_destructor_ram;
1592 mr->align = align;
1593 mr->ram_block = qemu_ram_alloc_from_file(size, mr, ram_flags, path, &err);
1594 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1595 if (err) {
1596 mr->size = int128_zero();
1597 object_unparent(OBJECT(mr));
1598 error_propagate(errp, err);
1599 }
1600 }
1601
1602 void memory_region_init_ram_from_fd(MemoryRegion *mr,
1603 struct Object *owner,
1604 const char *name,
1605 uint64_t size,
1606 bool share,
1607 int fd,
1608 Error **errp)
1609 {
1610 Error *err = NULL;
1611 memory_region_init(mr, owner, name, size);
1612 mr->ram = true;
1613 mr->terminates = true;
1614 mr->destructor = memory_region_destructor_ram;
1615 mr->ram_block = qemu_ram_alloc_from_fd(size, mr,
1616 share ? RAM_SHARED : 0,
1617 fd, &err);
1618 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1619 if (err) {
1620 mr->size = int128_zero();
1621 object_unparent(OBJECT(mr));
1622 error_propagate(errp, err);
1623 }
1624 }
1625 #endif
1626
1627 void memory_region_init_ram_ptr(MemoryRegion *mr,
1628 Object *owner,
1629 const char *name,
1630 uint64_t size,
1631 void *ptr)
1632 {
1633 memory_region_init(mr, owner, name, size);
1634 mr->ram = true;
1635 mr->terminates = true;
1636 mr->destructor = memory_region_destructor_ram;
1637 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1638
1639 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1640 assert(ptr != NULL);
1641 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1642 }
1643
1644 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1645 Object *owner,
1646 const char *name,
1647 uint64_t size,
1648 void *ptr)
1649 {
1650 memory_region_init(mr, owner, name, size);
1651 mr->ram = true;
1652 mr->terminates = true;
1653 mr->ram_device = true;
1654 mr->ops = &ram_device_mem_ops;
1655 mr->opaque = mr;
1656 mr->destructor = memory_region_destructor_ram;
1657 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1658 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1659 assert(ptr != NULL);
1660 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1661 }
1662
1663 void memory_region_init_alias(MemoryRegion *mr,
1664 Object *owner,
1665 const char *name,
1666 MemoryRegion *orig,
1667 hwaddr offset,
1668 uint64_t size)
1669 {
1670 memory_region_init(mr, owner, name, size);
1671 mr->alias = orig;
1672 mr->alias_offset = offset;
1673 }
1674
1675 void memory_region_init_rom_nomigrate(MemoryRegion *mr,
1676 struct Object *owner,
1677 const char *name,
1678 uint64_t size,
1679 Error **errp)
1680 {
1681 memory_region_init_ram_shared_nomigrate(mr, owner, name, size, false, errp);
1682 mr->readonly = true;
1683 }
1684
1685 void memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1686 Object *owner,
1687 const MemoryRegionOps *ops,
1688 void *opaque,
1689 const char *name,
1690 uint64_t size,
1691 Error **errp)
1692 {
1693 Error *err = NULL;
1694 assert(ops);
1695 memory_region_init(mr, owner, name, size);
1696 mr->ops = ops;
1697 mr->opaque = opaque;
1698 mr->terminates = true;
1699 mr->rom_device = true;
1700 mr->destructor = memory_region_destructor_ram;
1701 mr->ram_block = qemu_ram_alloc(size, false, mr, &err);
1702 if (err) {
1703 mr->size = int128_zero();
1704 object_unparent(OBJECT(mr));
1705 error_propagate(errp, err);
1706 }
1707 }
1708
1709 void memory_region_init_iommu(void *_iommu_mr,
1710 size_t instance_size,
1711 const char *mrtypename,
1712 Object *owner,
1713 const char *name,
1714 uint64_t size)
1715 {
1716 struct IOMMUMemoryRegion *iommu_mr;
1717 struct MemoryRegion *mr;
1718
1719 object_initialize(_iommu_mr, instance_size, mrtypename);
1720 mr = MEMORY_REGION(_iommu_mr);
1721 memory_region_do_init(mr, owner, name, size);
1722 iommu_mr = IOMMU_MEMORY_REGION(mr);
1723 mr->terminates = true; /* then re-forwards */
1724 QLIST_INIT(&iommu_mr->iommu_notify);
1725 iommu_mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
1726 }
1727
1728 static void memory_region_finalize(Object *obj)
1729 {
1730 MemoryRegion *mr = MEMORY_REGION(obj);
1731
1732 assert(!mr->container);
1733
1734 /* We know the region is not visible in any address space (it
1735 * does not have a container and cannot be a root either because
1736 * it has no references, so we can blindly clear mr->enabled.
1737 * memory_region_set_enabled instead could trigger a transaction
1738 * and cause an infinite loop.
1739 */
1740 mr->enabled = false;
1741 memory_region_transaction_begin();
1742 while (!QTAILQ_EMPTY(&mr->subregions)) {
1743 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1744 memory_region_del_subregion(mr, subregion);
1745 }
1746 memory_region_transaction_commit();
1747
1748 mr->destructor(mr);
1749 memory_region_clear_coalescing(mr);
1750 g_free((char *)mr->name);
1751 g_free(mr->ioeventfds);
1752 }
1753
1754 Object *memory_region_owner(MemoryRegion *mr)
1755 {
1756 Object *obj = OBJECT(mr);
1757 return obj->parent;
1758 }
1759
1760 void memory_region_ref(MemoryRegion *mr)
1761 {
1762 /* MMIO callbacks most likely will access data that belongs
1763 * to the owner, hence the need to ref/unref the owner whenever
1764 * the memory region is in use.
1765 *
1766 * The memory region is a child of its owner. As long as the
1767 * owner doesn't call unparent itself on the memory region,
1768 * ref-ing the owner will also keep the memory region alive.
1769 * Memory regions without an owner are supposed to never go away;
1770 * we do not ref/unref them because it slows down DMA sensibly.
1771 */
1772 if (mr && mr->owner) {
1773 object_ref(mr->owner);
1774 }
1775 }
1776
1777 void memory_region_unref(MemoryRegion *mr)
1778 {
1779 if (mr && mr->owner) {
1780 object_unref(mr->owner);
1781 }
1782 }
1783
1784 uint64_t memory_region_size(MemoryRegion *mr)
1785 {
1786 if (int128_eq(mr->size, int128_2_64())) {
1787 return UINT64_MAX;
1788 }
1789 return int128_get64(mr->size);
1790 }
1791
1792 const char *memory_region_name(const MemoryRegion *mr)
1793 {
1794 if (!mr->name) {
1795 ((MemoryRegion *)mr)->name =
1796 g_strdup(object_get_canonical_path_component(OBJECT(mr)));
1797 }
1798 return mr->name;
1799 }
1800
1801 bool memory_region_is_ram_device(MemoryRegion *mr)
1802 {
1803 return mr->ram_device;
1804 }
1805
1806 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1807 {
1808 uint8_t mask = mr->dirty_log_mask;
1809 if (global_dirty_log && (mr->ram_block || memory_region_is_iommu(mr))) {
1810 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1811 }
1812 return mask;
1813 }
1814
1815 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1816 {
1817 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1818 }
1819
1820 static int memory_region_update_iommu_notify_flags(IOMMUMemoryRegion *iommu_mr,
1821 Error **errp)
1822 {
1823 IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1824 IOMMUNotifier *iommu_notifier;
1825 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1826 int ret = 0;
1827
1828 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
1829 flags |= iommu_notifier->notifier_flags;
1830 }
1831
1832 if (flags != iommu_mr->iommu_notify_flags && imrc->notify_flag_changed) {
1833 ret = imrc->notify_flag_changed(iommu_mr,
1834 iommu_mr->iommu_notify_flags,
1835 flags, errp);
1836 }
1837
1838 if (!ret) {
1839 iommu_mr->iommu_notify_flags = flags;
1840 }
1841 return ret;
1842 }
1843
1844 int memory_region_iommu_set_page_size_mask(IOMMUMemoryRegion *iommu_mr,
1845 uint64_t page_size_mask,
1846 Error **errp)
1847 {
1848 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1849 int ret = 0;
1850
1851 if (imrc->iommu_set_page_size_mask) {
1852 ret = imrc->iommu_set_page_size_mask(iommu_mr, page_size_mask, errp);
1853 }
1854 return ret;
1855 }
1856
1857 int memory_region_register_iommu_notifier(MemoryRegion *mr,
1858 IOMMUNotifier *n, Error **errp)
1859 {
1860 IOMMUMemoryRegion *iommu_mr;
1861 int ret;
1862
1863 if (mr->alias) {
1864 return memory_region_register_iommu_notifier(mr->alias, n, errp);
1865 }
1866
1867 /* We need to register for at least one bitfield */
1868 iommu_mr = IOMMU_MEMORY_REGION(mr);
1869 assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
1870 assert(n->start <= n->end);
1871 assert(n->iommu_idx >= 0 &&
1872 n->iommu_idx < memory_region_iommu_num_indexes(iommu_mr));
1873
1874 QLIST_INSERT_HEAD(&iommu_mr->iommu_notify, n, node);
1875 ret = memory_region_update_iommu_notify_flags(iommu_mr, errp);
1876 if (ret) {
1877 QLIST_REMOVE(n, node);
1878 }
1879 return ret;
1880 }
1881
1882 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr)
1883 {
1884 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1885
1886 if (imrc->get_min_page_size) {
1887 return imrc->get_min_page_size(iommu_mr);
1888 }
1889 return TARGET_PAGE_SIZE;
1890 }
1891
1892 void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n)
1893 {
1894 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
1895 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1896 hwaddr addr, granularity;
1897 IOMMUTLBEntry iotlb;
1898
1899 /* If the IOMMU has its own replay callback, override */
1900 if (imrc->replay) {
1901 imrc->replay(iommu_mr, n);
1902 return;
1903 }
1904
1905 granularity = memory_region_iommu_get_min_page_size(iommu_mr);
1906
1907 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1908 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, n->iommu_idx);
1909 if (iotlb.perm != IOMMU_NONE) {
1910 n->notify(n, &iotlb);
1911 }
1912
1913 /* if (2^64 - MR size) < granularity, it's possible to get an
1914 * infinite loop here. This should catch such a wraparound */
1915 if ((addr + granularity) < addr) {
1916 break;
1917 }
1918 }
1919 }
1920
1921 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1922 IOMMUNotifier *n)
1923 {
1924 IOMMUMemoryRegion *iommu_mr;
1925
1926 if (mr->alias) {
1927 memory_region_unregister_iommu_notifier(mr->alias, n);
1928 return;
1929 }
1930 QLIST_REMOVE(n, node);
1931 iommu_mr = IOMMU_MEMORY_REGION(mr);
1932 memory_region_update_iommu_notify_flags(iommu_mr, NULL);
1933 }
1934
1935 void memory_region_notify_one(IOMMUNotifier *notifier,
1936 IOMMUTLBEntry *entry)
1937 {
1938 IOMMUNotifierFlag request_flags;
1939 hwaddr entry_end = entry->iova + entry->addr_mask;
1940
1941 /*
1942 * Skip the notification if the notification does not overlap
1943 * with registered range.
1944 */
1945 if (notifier->start > entry_end || notifier->end < entry->iova) {
1946 return;
1947 }
1948
1949 assert(entry->iova >= notifier->start && entry_end <= notifier->end);
1950
1951 if (entry->perm & IOMMU_RW) {
1952 request_flags = IOMMU_NOTIFIER_MAP;
1953 } else {
1954 request_flags = IOMMU_NOTIFIER_UNMAP;
1955 }
1956
1957 if (notifier->notifier_flags & request_flags) {
1958 notifier->notify(notifier, entry);
1959 }
1960 }
1961
1962 void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
1963 int iommu_idx,
1964 IOMMUTLBEntry entry)
1965 {
1966 IOMMUNotifier *iommu_notifier;
1967
1968 assert(memory_region_is_iommu(MEMORY_REGION(iommu_mr)));
1969
1970 IOMMU_NOTIFIER_FOREACH(iommu_notifier, iommu_mr) {
1971 if (iommu_notifier->iommu_idx == iommu_idx) {
1972 memory_region_notify_one(iommu_notifier, &entry);
1973 }
1974 }
1975 }
1976
1977 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
1978 enum IOMMUMemoryRegionAttr attr,
1979 void *data)
1980 {
1981 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1982
1983 if (!imrc->get_attr) {
1984 return -EINVAL;
1985 }
1986
1987 return imrc->get_attr(iommu_mr, attr, data);
1988 }
1989
1990 int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
1991 MemTxAttrs attrs)
1992 {
1993 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
1994
1995 if (!imrc->attrs_to_index) {
1996 return 0;
1997 }
1998
1999 return imrc->attrs_to_index(iommu_mr, attrs);
2000 }
2001
2002 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr)
2003 {
2004 IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_GET_CLASS(iommu_mr);
2005
2006 if (!imrc->num_indexes) {
2007 return 1;
2008 }
2009
2010 return imrc->num_indexes(iommu_mr);
2011 }
2012
2013 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
2014 {
2015 uint8_t mask = 1 << client;
2016 uint8_t old_logging;
2017
2018 assert(client == DIRTY_MEMORY_VGA);
2019 old_logging = mr->vga_logging_count;
2020 mr->vga_logging_count += log ? 1 : -1;
2021 if (!!old_logging == !!mr->vga_logging_count) {
2022 return;
2023 }
2024
2025 memory_region_transaction_begin();
2026 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
2027 memory_region_update_pending |= mr->enabled;
2028 memory_region_transaction_commit();
2029 }
2030
2031 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
2032 hwaddr size)
2033 {
2034 assert(mr->ram_block);
2035 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
2036 size,
2037 memory_region_get_dirty_log_mask(mr));
2038 }
2039
2040 static void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
2041 {
2042 MemoryListener *listener;
2043 AddressSpace *as;
2044 FlatView *view;
2045 FlatRange *fr;
2046
2047 /* If the same address space has multiple log_sync listeners, we
2048 * visit that address space's FlatView multiple times. But because
2049 * log_sync listeners are rare, it's still cheaper than walking each
2050 * address space once.
2051 */
2052 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2053 if (!listener->log_sync) {
2054 continue;
2055 }
2056 as = listener->address_space;
2057 view = address_space_get_flatview(as);
2058 FOR_EACH_FLAT_RANGE(fr, view) {
2059 if (fr->dirty_log_mask && (!mr || fr->mr == mr)) {
2060 MemoryRegionSection mrs = section_from_flat_range(fr, view);
2061 listener->log_sync(listener, &mrs);
2062 }
2063 }
2064 flatview_unref(view);
2065 }
2066 }
2067
2068 void memory_region_clear_dirty_bitmap(MemoryRegion *mr, hwaddr start,
2069 hwaddr len)
2070 {
2071 MemoryRegionSection mrs;
2072 MemoryListener *listener;
2073 AddressSpace *as;
2074 FlatView *view;
2075 FlatRange *fr;
2076 hwaddr sec_start, sec_end, sec_size;
2077
2078 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2079 if (!listener->log_clear) {
2080 continue;
2081 }
2082 as = listener->address_space;
2083 view = address_space_get_flatview(as);
2084 FOR_EACH_FLAT_RANGE(fr, view) {
2085 if (!fr->dirty_log_mask || fr->mr != mr) {
2086 /*
2087 * Clear dirty bitmap operation only applies to those
2088 * regions whose dirty logging is at least enabled
2089 */
2090 continue;
2091 }
2092
2093 mrs = section_from_flat_range(fr, view);
2094
2095 sec_start = MAX(mrs.offset_within_region, start);
2096 sec_end = mrs.offset_within_region + int128_get64(mrs.size);
2097 sec_end = MIN(sec_end, start + len);
2098
2099 if (sec_start >= sec_end) {
2100 /*
2101 * If this memory region section has no intersection
2102 * with the requested range, skip.
2103 */
2104 continue;
2105 }
2106
2107 /* Valid case; shrink the section if needed */
2108 mrs.offset_within_address_space +=
2109 sec_start - mrs.offset_within_region;
2110 mrs.offset_within_region = sec_start;
2111 sec_size = sec_end - sec_start;
2112 mrs.size = int128_make64(sec_size);
2113 listener->log_clear(listener, &mrs);
2114 }
2115 flatview_unref(view);
2116 }
2117 }
2118
2119 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
2120 hwaddr addr,
2121 hwaddr size,
2122 unsigned client)
2123 {
2124 DirtyBitmapSnapshot *snapshot;
2125 assert(mr->ram_block);
2126 memory_region_sync_dirty_bitmap(mr);
2127 snapshot = cpu_physical_memory_snapshot_and_clear_dirty(mr, addr, size, client);
2128 memory_global_after_dirty_log_sync();
2129 return snapshot;
2130 }
2131
2132 bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
2133 hwaddr addr, hwaddr size)
2134 {
2135 assert(mr->ram_block);
2136 return cpu_physical_memory_snapshot_get_dirty(snap,
2137 memory_region_get_ram_addr(mr) + addr, size);
2138 }
2139
2140 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
2141 {
2142 if (mr->readonly != readonly) {
2143 memory_region_transaction_begin();
2144 mr->readonly = readonly;
2145 memory_region_update_pending |= mr->enabled;
2146 memory_region_transaction_commit();
2147 }
2148 }
2149
2150 void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile)
2151 {
2152 if (mr->nonvolatile != nonvolatile) {
2153 memory_region_transaction_begin();
2154 mr->nonvolatile = nonvolatile;
2155 memory_region_update_pending |= mr->enabled;
2156 memory_region_transaction_commit();
2157 }
2158 }
2159
2160 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
2161 {
2162 if (mr->romd_mode != romd_mode) {
2163 memory_region_transaction_begin();
2164 mr->romd_mode = romd_mode;
2165 memory_region_update_pending |= mr->enabled;
2166 memory_region_transaction_commit();
2167 }
2168 }
2169
2170 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
2171 hwaddr size, unsigned client)
2172 {
2173 assert(mr->ram_block);
2174 cpu_physical_memory_test_and_clear_dirty(
2175 memory_region_get_ram_addr(mr) + addr, size, client);
2176 }
2177
2178 int memory_region_get_fd(MemoryRegion *mr)
2179 {
2180 int fd;
2181
2182 RCU_READ_LOCK_GUARD();
2183 while (mr->alias) {
2184 mr = mr->alias;
2185 }
2186 fd = mr->ram_block->fd;
2187
2188 return fd;
2189 }
2190
2191 void *memory_region_get_ram_ptr(MemoryRegion *mr)
2192 {
2193 void *ptr;
2194 uint64_t offset = 0;
2195
2196 RCU_READ_LOCK_GUARD();
2197 while (mr->alias) {
2198 offset += mr->alias_offset;
2199 mr = mr->alias;
2200 }
2201 assert(mr->ram_block);
2202 ptr = qemu_map_ram_ptr(mr->ram_block, offset);
2203
2204 return ptr;
2205 }
2206
2207 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
2208 {
2209 RAMBlock *block;
2210
2211 block = qemu_ram_block_from_host(ptr, false, offset);
2212 if (!block) {
2213 return NULL;
2214 }
2215
2216 return block->mr;
2217 }
2218
2219 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
2220 {
2221 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
2222 }
2223
2224 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
2225 {
2226 assert(mr->ram_block);
2227
2228 qemu_ram_resize(mr->ram_block, newsize, errp);
2229 }
2230
2231 void memory_region_msync(MemoryRegion *mr, hwaddr addr, hwaddr size)
2232 {
2233 if (mr->ram_block) {
2234 qemu_ram_msync(mr->ram_block, addr, size);
2235 }
2236 }
2237
2238 void memory_region_writeback(MemoryRegion *mr, hwaddr addr, hwaddr size)
2239 {
2240 /*
2241 * Might be extended case needed to cover
2242 * different types of memory regions
2243 */
2244 if (mr->dirty_log_mask) {
2245 memory_region_msync(mr, addr, size);
2246 }
2247 }
2248
2249 /*
2250 * Call proper memory listeners about the change on the newly
2251 * added/removed CoalescedMemoryRange.
2252 */
2253 static void memory_region_update_coalesced_range(MemoryRegion *mr,
2254 CoalescedMemoryRange *cmr,
2255 bool add)
2256 {
2257 AddressSpace *as;
2258 FlatView *view;
2259 FlatRange *fr;
2260
2261 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2262 view = address_space_get_flatview(as);
2263 FOR_EACH_FLAT_RANGE(fr, view) {
2264 if (fr->mr == mr) {
2265 flat_range_coalesced_io_notify(fr, as, cmr, add);
2266 }
2267 }
2268 flatview_unref(view);
2269 }
2270 }
2271
2272 void memory_region_set_coalescing(MemoryRegion *mr)
2273 {
2274 memory_region_clear_coalescing(mr);
2275 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
2276 }
2277
2278 void memory_region_add_coalescing(MemoryRegion *mr,
2279 hwaddr offset,
2280 uint64_t size)
2281 {
2282 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
2283
2284 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
2285 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
2286 memory_region_update_coalesced_range(mr, cmr, true);
2287 memory_region_set_flush_coalesced(mr);
2288 }
2289
2290 void memory_region_clear_coalescing(MemoryRegion *mr)
2291 {
2292 CoalescedMemoryRange *cmr;
2293
2294 if (QTAILQ_EMPTY(&mr->coalesced)) {
2295 return;
2296 }
2297
2298 qemu_flush_coalesced_mmio_buffer();
2299 mr->flush_coalesced_mmio = false;
2300
2301 while (!QTAILQ_EMPTY(&mr->coalesced)) {
2302 cmr = QTAILQ_FIRST(&mr->coalesced);
2303 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
2304 memory_region_update_coalesced_range(mr, cmr, false);
2305 g_free(cmr);
2306 }
2307 }
2308
2309 void memory_region_set_flush_coalesced(MemoryRegion *mr)
2310 {
2311 mr->flush_coalesced_mmio = true;
2312 }
2313
2314 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
2315 {
2316 qemu_flush_coalesced_mmio_buffer();
2317 if (QTAILQ_EMPTY(&mr->coalesced)) {
2318 mr->flush_coalesced_mmio = false;
2319 }
2320 }
2321
2322 static bool userspace_eventfd_warning;
2323
2324 void memory_region_add_eventfd(MemoryRegion *mr,
2325 hwaddr addr,
2326 unsigned size,
2327 bool match_data,
2328 uint64_t data,
2329 EventNotifier *e)
2330 {
2331 MemoryRegionIoeventfd mrfd = {
2332 .addr.start = int128_make64(addr),
2333 .addr.size = int128_make64(size),
2334 .match_data = match_data,
2335 .data = data,
2336 .e = e,
2337 };
2338 unsigned i;
2339
2340 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
2341 userspace_eventfd_warning))) {
2342 userspace_eventfd_warning = true;
2343 error_report("Using eventfd without MMIO binding in KVM. "
2344 "Suboptimal performance expected");
2345 }
2346
2347 if (size) {
2348 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2349 }
2350 memory_region_transaction_begin();
2351 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2352 if (memory_region_ioeventfd_before(&mrfd, &mr->ioeventfds[i])) {
2353 break;
2354 }
2355 }
2356 ++mr->ioeventfd_nb;
2357 mr->ioeventfds = g_realloc(mr->ioeventfds,
2358 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2359 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2360 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2361 mr->ioeventfds[i] = mrfd;
2362 ioeventfd_update_pending |= mr->enabled;
2363 memory_region_transaction_commit();
2364 }
2365
2366 void memory_region_del_eventfd(MemoryRegion *mr,
2367 hwaddr addr,
2368 unsigned size,
2369 bool match_data,
2370 uint64_t data,
2371 EventNotifier *e)
2372 {
2373 MemoryRegionIoeventfd mrfd = {
2374 .addr.start = int128_make64(addr),
2375 .addr.size = int128_make64(size),
2376 .match_data = match_data,
2377 .data = data,
2378 .e = e,
2379 };
2380 unsigned i;
2381
2382 if (size) {
2383 adjust_endianness(mr, &mrfd.data, size_memop(size) | MO_TE);
2384 }
2385 memory_region_transaction_begin();
2386 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2387 if (memory_region_ioeventfd_equal(&mrfd, &mr->ioeventfds[i])) {
2388 break;
2389 }
2390 }
2391 assert(i != mr->ioeventfd_nb);
2392 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2393 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2394 --mr->ioeventfd_nb;
2395 mr->ioeventfds = g_realloc(mr->ioeventfds,
2396 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
2397 ioeventfd_update_pending |= mr->enabled;
2398 memory_region_transaction_commit();
2399 }
2400
2401 static void memory_region_update_container_subregions(MemoryRegion *subregion)
2402 {
2403 MemoryRegion *mr = subregion->container;
2404 MemoryRegion *other;
2405
2406 memory_region_transaction_begin();
2407
2408 memory_region_ref(subregion);
2409 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2410 if (subregion->priority >= other->priority) {
2411 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2412 goto done;
2413 }
2414 }
2415 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2416 done:
2417 memory_region_update_pending |= mr->enabled && subregion->enabled;
2418 memory_region_transaction_commit();
2419 }
2420
2421 static void memory_region_add_subregion_common(MemoryRegion *mr,
2422 hwaddr offset,
2423 MemoryRegion *subregion)
2424 {
2425 assert(!subregion->container);
2426 subregion->container = mr;
2427 subregion->addr = offset;
2428 memory_region_update_container_subregions(subregion);
2429 }
2430
2431 void memory_region_add_subregion(MemoryRegion *mr,
2432 hwaddr offset,
2433 MemoryRegion *subregion)
2434 {
2435 subregion->priority = 0;
2436 memory_region_add_subregion_common(mr, offset, subregion);
2437 }
2438
2439 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2440 hwaddr offset,
2441 MemoryRegion *subregion,
2442 int priority)
2443 {
2444 subregion->priority = priority;
2445 memory_region_add_subregion_common(mr, offset, subregion);
2446 }
2447
2448 void memory_region_del_subregion(MemoryRegion *mr,
2449 MemoryRegion *subregion)
2450 {
2451 memory_region_transaction_begin();
2452 assert(subregion->container == mr);
2453 subregion->container = NULL;
2454 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
2455 memory_region_unref(subregion);
2456 memory_region_update_pending |= mr->enabled && subregion->enabled;
2457 memory_region_transaction_commit();
2458 }
2459
2460 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2461 {
2462 if (enabled == mr->enabled) {
2463 return;
2464 }
2465 memory_region_transaction_begin();
2466 mr->enabled = enabled;
2467 memory_region_update_pending = true;
2468 memory_region_transaction_commit();
2469 }
2470
2471 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2472 {
2473 Int128 s = int128_make64(size);
2474
2475 if (size == UINT64_MAX) {
2476 s = int128_2_64();
2477 }
2478 if (int128_eq(s, mr->size)) {
2479 return;
2480 }
2481 memory_region_transaction_begin();
2482 mr->size = s;
2483 memory_region_update_pending = true;
2484 memory_region_transaction_commit();
2485 }
2486
2487 static void memory_region_readd_subregion(MemoryRegion *mr)
2488 {
2489 MemoryRegion *container = mr->container;
2490
2491 if (container) {
2492 memory_region_transaction_begin();
2493 memory_region_ref(mr);
2494 memory_region_del_subregion(container, mr);
2495 mr->container = container;
2496 memory_region_update_container_subregions(mr);
2497 memory_region_unref(mr);
2498 memory_region_transaction_commit();
2499 }
2500 }
2501
2502 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2503 {
2504 if (addr != mr->addr) {
2505 mr->addr = addr;
2506 memory_region_readd_subregion(mr);
2507 }
2508 }
2509
2510 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
2511 {
2512 assert(mr->alias);
2513
2514 if (offset == mr->alias_offset) {
2515 return;
2516 }
2517
2518 memory_region_transaction_begin();
2519 mr->alias_offset = offset;
2520 memory_region_update_pending |= mr->enabled;
2521 memory_region_transaction_commit();
2522 }
2523
2524 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2525 {
2526 return mr->align;
2527 }
2528
2529 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2530 {
2531 const AddrRange *addr = addr_;
2532 const FlatRange *fr = fr_;
2533
2534 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2535 return -1;
2536 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2537 return 1;
2538 }
2539 return 0;
2540 }
2541
2542 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
2543 {
2544 return bsearch(&addr, view->ranges, view->nr,
2545 sizeof(FlatRange), cmp_flatrange_addr);
2546 }
2547
2548 bool memory_region_is_mapped(MemoryRegion *mr)
2549 {
2550 return mr->container ? true : false;
2551 }
2552
2553 /* Same as memory_region_find, but it does not add a reference to the
2554 * returned region. It must be called from an RCU critical section.
2555 */
2556 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2557 hwaddr addr, uint64_t size)
2558 {
2559 MemoryRegionSection ret = { .mr = NULL };
2560 MemoryRegion *root;
2561 AddressSpace *as;
2562 AddrRange range;
2563 FlatView *view;
2564 FlatRange *fr;
2565
2566 addr += mr->addr;
2567 for (root = mr; root->container; ) {
2568 root = root->container;
2569 addr += root->addr;
2570 }
2571
2572 as = memory_region_to_address_space(root);
2573 if (!as) {
2574 return ret;
2575 }
2576 range = addrrange_make(int128_make64(addr), int128_make64(size));
2577
2578 view = address_space_to_flatview(as);
2579 fr = flatview_lookup(view, range);
2580 if (!fr) {
2581 return ret;
2582 }
2583
2584 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2585 --fr;
2586 }
2587
2588 ret.mr = fr->mr;
2589 ret.fv = view;
2590 range = addrrange_intersection(range, fr->addr);
2591 ret.offset_within_region = fr->offset_in_region;
2592 ret.offset_within_region += int128_get64(int128_sub(range.start,
2593 fr->addr.start));
2594 ret.size = range.size;
2595 ret.offset_within_address_space = int128_get64(range.start);
2596 ret.readonly = fr->readonly;
2597 ret.nonvolatile = fr->nonvolatile;
2598 return ret;
2599 }
2600
2601 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2602 hwaddr addr, uint64_t size)
2603 {
2604 MemoryRegionSection ret;
2605 RCU_READ_LOCK_GUARD();
2606 ret = memory_region_find_rcu(mr, addr, size);
2607 if (ret.mr) {
2608 memory_region_ref(ret.mr);
2609 }
2610 return ret;
2611 }
2612
2613 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2614 {
2615 MemoryRegion *mr;
2616
2617 RCU_READ_LOCK_GUARD();
2618 mr = memory_region_find_rcu(container, addr, 1).mr;
2619 return mr && mr != container;
2620 }
2621
2622 void memory_global_dirty_log_sync(void)
2623 {
2624 memory_region_sync_dirty_bitmap(NULL);
2625 }
2626
2627 void memory_global_after_dirty_log_sync(void)
2628 {
2629 MEMORY_LISTENER_CALL_GLOBAL(log_global_after_sync, Forward);
2630 }
2631
2632 static VMChangeStateEntry *vmstate_change;
2633
2634 void memory_global_dirty_log_start(void)
2635 {
2636 if (vmstate_change) {
2637 qemu_del_vm_change_state_handler(vmstate_change);
2638 vmstate_change = NULL;
2639 }
2640
2641 global_dirty_log = true;
2642
2643 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2644
2645 /* Refresh DIRTY_MEMORY_MIGRATION bit. */
2646 memory_region_transaction_begin();
2647 memory_region_update_pending = true;
2648 memory_region_transaction_commit();
2649 }
2650
2651 static void memory_global_dirty_log_do_stop(void)
2652 {
2653 global_dirty_log = false;
2654
2655 /* Refresh DIRTY_MEMORY_MIGRATION bit. */
2656 memory_region_transaction_begin();
2657 memory_region_update_pending = true;
2658 memory_region_transaction_commit();
2659
2660 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2661 }
2662
2663 static void memory_vm_change_state_handler(void *opaque, int running,
2664 RunState state)
2665 {
2666 if (running) {
2667 memory_global_dirty_log_do_stop();
2668
2669 if (vmstate_change) {
2670 qemu_del_vm_change_state_handler(vmstate_change);
2671 vmstate_change = NULL;
2672 }
2673 }
2674 }
2675
2676 void memory_global_dirty_log_stop(void)
2677 {
2678 if (!runstate_is_running()) {
2679 if (vmstate_change) {
2680 return;
2681 }
2682 vmstate_change = qemu_add_vm_change_state_handler(
2683 memory_vm_change_state_handler, NULL);
2684 return;
2685 }
2686
2687 memory_global_dirty_log_do_stop();
2688 }
2689
2690 static void listener_add_address_space(MemoryListener *listener,
2691 AddressSpace *as)
2692 {
2693 FlatView *view;
2694 FlatRange *fr;
2695
2696 if (listener->begin) {
2697 listener->begin(listener);
2698 }
2699 if (global_dirty_log) {
2700 if (listener->log_global_start) {
2701 listener->log_global_start(listener);
2702 }
2703 }
2704
2705 view = address_space_get_flatview(as);
2706 FOR_EACH_FLAT_RANGE(fr, view) {
2707 MemoryRegionSection section = section_from_flat_range(fr, view);
2708
2709 if (listener->region_add) {
2710 listener->region_add(listener, &section);
2711 }
2712 if (fr->dirty_log_mask && listener->log_start) {
2713 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2714 }
2715 }
2716 if (listener->commit) {
2717 listener->commit(listener);
2718 }
2719 flatview_unref(view);
2720 }
2721
2722 static void listener_del_address_space(MemoryListener *listener,
2723 AddressSpace *as)
2724 {
2725 FlatView *view;
2726 FlatRange *fr;
2727
2728 if (listener->begin) {
2729 listener->begin(listener);
2730 }
2731 view = address_space_get_flatview(as);
2732 FOR_EACH_FLAT_RANGE(fr, view) {
2733 MemoryRegionSection section = section_from_flat_range(fr, view);
2734
2735 if (fr->dirty_log_mask && listener->log_stop) {
2736 listener->log_stop(listener, &section, fr->dirty_log_mask, 0);
2737 }
2738 if (listener->region_del) {
2739 listener->region_del(listener, &section);
2740 }
2741 }
2742 if (listener->commit) {
2743 listener->commit(listener);
2744 }
2745 flatview_unref(view);
2746 }
2747
2748 void memory_listener_register(MemoryListener *listener, AddressSpace *as)
2749 {
2750 MemoryListener *other = NULL;
2751
2752 listener->address_space = as;
2753 if (QTAILQ_EMPTY(&memory_listeners)
2754 || listener->priority >= QTAILQ_LAST(&memory_listeners)->priority) {
2755 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2756 } else {
2757 QTAILQ_FOREACH(other, &memory_listeners, link) {
2758 if (listener->priority < other->priority) {
2759 break;
2760 }
2761 }
2762 QTAILQ_INSERT_BEFORE(other, listener, link);
2763 }
2764
2765 if (QTAILQ_EMPTY(&as->listeners)
2766 || listener->priority >= QTAILQ_LAST(&as->listeners)->priority) {
2767 QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
2768 } else {
2769 QTAILQ_FOREACH(other, &as->listeners, link_as) {
2770 if (listener->priority < other->priority) {
2771 break;
2772 }
2773 }
2774 QTAILQ_INSERT_BEFORE(other, listener, link_as);
2775 }
2776
2777 listener_add_address_space(listener, as);
2778 }
2779
2780 void memory_listener_unregister(MemoryListener *listener)
2781 {
2782 if (!listener->address_space) {
2783 return;
2784 }
2785
2786 listener_del_address_space(listener, listener->address_space);
2787 QTAILQ_REMOVE(&memory_listeners, listener, link);
2788 QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
2789 listener->address_space = NULL;
2790 }
2791
2792 void address_space_remove_listeners(AddressSpace *as)
2793 {
2794 while (!QTAILQ_EMPTY(&as->listeners)) {
2795 memory_listener_unregister(QTAILQ_FIRST(&as->listeners));
2796 }
2797 }
2798
2799 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2800 {
2801 memory_region_ref(root);
2802 as->root = root;
2803 as->current_map = NULL;
2804 as->ioeventfd_nb = 0;
2805 as->ioeventfds = NULL;
2806 QTAILQ_INIT(&as->listeners);
2807 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2808 as->name = g_strdup(name ? name : "anonymous");
2809 address_space_update_topology(as);
2810 address_space_update_ioeventfds(as);
2811 }
2812
2813 static void do_address_space_destroy(AddressSpace *as)
2814 {
2815 assert(QTAILQ_EMPTY(&as->listeners));
2816
2817 flatview_unref(as->current_map);
2818 g_free(as->name);
2819 g_free(as->ioeventfds);
2820 memory_region_unref(as->root);
2821 }
2822
2823 void address_space_destroy(AddressSpace *as)
2824 {
2825 MemoryRegion *root = as->root;
2826
2827 /* Flush out anything from MemoryListeners listening in on this */
2828 memory_region_transaction_begin();
2829 as->root = NULL;
2830 memory_region_transaction_commit();
2831 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2832
2833 /* At this point, as->dispatch and as->current_map are dummy
2834 * entries that the guest should never use. Wait for the old
2835 * values to expire before freeing the data.
2836 */
2837 as->root = root;
2838 call_rcu(as, do_address_space_destroy, rcu);
2839 }
2840
2841 static const char *memory_region_type(MemoryRegion *mr)
2842 {
2843 if (mr->alias) {
2844 return memory_region_type(mr->alias);
2845 }
2846 if (memory_region_is_ram_device(mr)) {
2847 return "ramd";
2848 } else if (memory_region_is_romd(mr)) {
2849 return "romd";
2850 } else if (memory_region_is_rom(mr)) {
2851 return "rom";
2852 } else if (memory_region_is_ram(mr)) {
2853 return "ram";
2854 } else {
2855 return "i/o";
2856 }
2857 }
2858
2859 typedef struct MemoryRegionList MemoryRegionList;
2860
2861 struct MemoryRegionList {
2862 const MemoryRegion *mr;
2863 QTAILQ_ENTRY(MemoryRegionList) mrqueue;
2864 };
2865
2866 typedef QTAILQ_HEAD(, MemoryRegionList) MemoryRegionListHead;
2867
2868 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
2869 int128_sub((size), int128_one())) : 0)
2870 #define MTREE_INDENT " "
2871
2872 static void mtree_expand_owner(const char *label, Object *obj)
2873 {
2874 DeviceState *dev = (DeviceState *) object_dynamic_cast(obj, TYPE_DEVICE);
2875
2876 qemu_printf(" %s:{%s", label, dev ? "dev" : "obj");
2877 if (dev && dev->id) {
2878 qemu_printf(" id=%s", dev->id);
2879 } else {
2880 char *canonical_path = object_get_canonical_path(obj);
2881 if (canonical_path) {
2882 qemu_printf(" path=%s", canonical_path);
2883 g_free(canonical_path);
2884 } else {
2885 qemu_printf(" type=%s", object_get_typename(obj));
2886 }
2887 }
2888 qemu_printf("}");
2889 }
2890
2891 static void mtree_print_mr_owner(const MemoryRegion *mr)
2892 {
2893 Object *owner = mr->owner;
2894 Object *parent = memory_region_owner((MemoryRegion *)mr);
2895
2896 if (!owner && !parent) {
2897 qemu_printf(" orphan");
2898 return;
2899 }
2900 if (owner) {
2901 mtree_expand_owner("owner", owner);
2902 }
2903 if (parent && parent != owner) {
2904 mtree_expand_owner("parent", parent);
2905 }
2906 }
2907
2908 static void mtree_print_mr(const MemoryRegion *mr, unsigned int level,
2909 hwaddr base,
2910 MemoryRegionListHead *alias_print_queue,
2911 bool owner, bool display_disabled)
2912 {
2913 MemoryRegionList *new_ml, *ml, *next_ml;
2914 MemoryRegionListHead submr_print_queue;
2915 const MemoryRegion *submr;
2916 unsigned int i;
2917 hwaddr cur_start, cur_end;
2918
2919 if (!mr) {
2920 return;
2921 }
2922
2923 cur_start = base + mr->addr;
2924 cur_end = cur_start + MR_SIZE(mr->size);
2925
2926 /*
2927 * Try to detect overflow of memory region. This should never
2928 * happen normally. When it happens, we dump something to warn the
2929 * user who is observing this.
2930 */
2931 if (cur_start < base || cur_end < cur_start) {
2932 qemu_printf("[DETECTED OVERFLOW!] ");
2933 }
2934
2935 if (mr->alias) {
2936 MemoryRegionList *ml;
2937 bool found = false;
2938
2939 /* check if the alias is already in the queue */
2940 QTAILQ_FOREACH(ml, alias_print_queue, mrqueue) {
2941 if (ml->mr == mr->alias) {
2942 found = true;
2943 }
2944 }
2945
2946 if (!found) {
2947 ml = g_new(MemoryRegionList, 1);
2948 ml->mr = mr->alias;
2949 QTAILQ_INSERT_TAIL(alias_print_queue, ml, mrqueue);
2950 }
2951 if (mr->enabled || display_disabled) {
2952 for (i = 0; i < level; i++) {
2953 qemu_printf(MTREE_INDENT);
2954 }
2955 qemu_printf(TARGET_FMT_plx "-" TARGET_FMT_plx
2956 " (prio %d, %s%s): alias %s @%s " TARGET_FMT_plx
2957 "-" TARGET_FMT_plx "%s",
2958 cur_start, cur_end,
2959 mr->priority,
2960 mr->nonvolatile ? "nv-" : "",
2961 memory_region_type((MemoryRegion *)mr),
2962 memory_region_name(mr),
2963 memory_region_name(mr->alias),
2964 mr->alias_offset,
2965 mr->alias_offset + MR_SIZE(mr->size),
2966 mr->enabled ? "" : " [disabled]");
2967 if (owner) {
2968 mtree_print_mr_owner(mr);
2969 }
2970 qemu_printf("\n");
2971 }
2972 } else {
2973 if (mr->enabled || display_disabled) {
2974 for (i = 0; i < level; i++) {
2975 qemu_printf(MTREE_INDENT);
2976 }
2977 qemu_printf(TARGET_FMT_plx "-" TARGET_FMT_plx
2978 " (prio %d, %s%s): %s%s",
2979 cur_start, cur_end,
2980 mr->priority,
2981 mr->nonvolatile ? "nv-" : "",
2982 memory_region_type((MemoryRegion *)mr),
2983 memory_region_name(mr),
2984 mr->enabled ? "" : " [disabled]");
2985 if (owner) {
2986 mtree_print_mr_owner(mr);
2987 }
2988 qemu_printf("\n");
2989 }
2990 }
2991
2992 QTAILQ_INIT(&submr_print_queue);
2993
2994 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2995 new_ml = g_new(MemoryRegionList, 1);
2996 new_ml->mr = submr;
2997 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
2998 if (new_ml->mr->addr < ml->mr->addr ||
2999 (new_ml->mr->addr == ml->mr->addr &&
3000 new_ml->mr->priority > ml->mr->priority)) {
3001 QTAILQ_INSERT_BEFORE(ml, new_ml, mrqueue);
3002 new_ml = NULL;
3003 break;
3004 }
3005 }
3006 if (new_ml) {
3007 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, mrqueue);
3008 }
3009 }
3010
3011 QTAILQ_FOREACH(ml, &submr_print_queue, mrqueue) {
3012 mtree_print_mr(ml->mr, level + 1, cur_start,
3013 alias_print_queue, owner, display_disabled);
3014 }
3015
3016 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, mrqueue, next_ml) {
3017 g_free(ml);
3018 }
3019 }
3020
3021 struct FlatViewInfo {
3022 int counter;
3023 bool dispatch_tree;
3024 bool owner;
3025 AccelClass *ac;
3026 };
3027
3028 static void mtree_print_flatview(gpointer key, gpointer value,
3029 gpointer user_data)
3030 {
3031 FlatView *view = key;
3032 GArray *fv_address_spaces = value;
3033 struct FlatViewInfo *fvi = user_data;
3034 FlatRange *range = &view->ranges[0];
3035 MemoryRegion *mr;
3036 int n = view->nr;
3037 int i;
3038 AddressSpace *as;
3039
3040 qemu_printf("FlatView #%d\n", fvi->counter);
3041 ++fvi->counter;
3042
3043 for (i = 0; i < fv_address_spaces->len; ++i) {
3044 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3045 qemu_printf(" AS \"%s\", root: %s",
3046 as->name, memory_region_name(as->root));
3047 if (as->root->alias) {
3048 qemu_printf(", alias %s", memory_region_name(as->root->alias));
3049 }
3050 qemu_printf("\n");
3051 }
3052
3053 qemu_printf(" Root memory region: %s\n",
3054 view->root ? memory_region_name(view->root) : "(none)");
3055
3056 if (n <= 0) {
3057 qemu_printf(MTREE_INDENT "No rendered FlatView\n\n");
3058 return;
3059 }
3060
3061 while (n--) {
3062 mr = range->mr;
3063 if (range->offset_in_region) {
3064 qemu_printf(MTREE_INDENT TARGET_FMT_plx "-" TARGET_FMT_plx
3065 " (prio %d, %s%s): %s @" TARGET_FMT_plx,
3066 int128_get64(range->addr.start),
3067 int128_get64(range->addr.start)
3068 + MR_SIZE(range->addr.size),
3069 mr->priority,
3070 range->nonvolatile ? "nv-" : "",
3071 range->readonly ? "rom" : memory_region_type(mr),
3072 memory_region_name(mr),
3073 range->offset_in_region);
3074 } else {
3075 qemu_printf(MTREE_INDENT TARGET_FMT_plx "-" TARGET_FMT_plx
3076 " (prio %d, %s%s): %s",
3077 int128_get64(range->addr.start),
3078 int128_get64(range->addr.start)
3079 + MR_SIZE(range->addr.size),
3080 mr->priority,
3081 range->nonvolatile ? "nv-" : "",
3082 range->readonly ? "rom" : memory_region_type(mr),
3083 memory_region_name(mr));
3084 }
3085 if (fvi->owner) {
3086 mtree_print_mr_owner(mr);
3087 }
3088
3089 if (fvi->ac) {
3090 for (i = 0; i < fv_address_spaces->len; ++i) {
3091 as = g_array_index(fv_address_spaces, AddressSpace*, i);
3092 if (fvi->ac->has_memory(current_machine, as,
3093 int128_get64(range->addr.start),
3094 MR_SIZE(range->addr.size) + 1)) {
3095 qemu_printf(" %s", fvi->ac->name);
3096 }
3097 }
3098 }
3099 qemu_printf("\n");
3100 range++;
3101 }
3102
3103 #if !defined(CONFIG_USER_ONLY)
3104 if (fvi->dispatch_tree && view->root) {
3105 mtree_print_dispatch(view->dispatch, view->root);
3106 }
3107 #endif
3108
3109 qemu_printf("\n");
3110 }
3111
3112 static gboolean mtree_info_flatview_free(gpointer key, gpointer value,
3113 gpointer user_data)
3114 {
3115 FlatView *view = key;
3116 GArray *fv_address_spaces = value;
3117
3118 g_array_unref(fv_address_spaces);
3119 flatview_unref(view);
3120
3121 return true;
3122 }
3123
3124 void mtree_info(bool flatview, bool dispatch_tree, bool owner, bool disabled)
3125 {
3126 MemoryRegionListHead ml_head;
3127 MemoryRegionList *ml, *ml2;
3128 AddressSpace *as;
3129
3130 if (flatview) {
3131 FlatView *view;
3132 struct FlatViewInfo fvi = {
3133 .counter = 0,
3134 .dispatch_tree = dispatch_tree,
3135 .owner = owner,
3136 };
3137 GArray *fv_address_spaces;
3138 GHashTable *views = g_hash_table_new(g_direct_hash, g_direct_equal);
3139 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
3140
3141 if (ac->has_memory) {
3142 fvi.ac = ac;
3143 }
3144
3145 /* Gather all FVs in one table */
3146 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3147 view = address_space_get_flatview(as);
3148
3149 fv_address_spaces = g_hash_table_lookup(views, view);
3150 if (!fv_address_spaces) {
3151 fv_address_spaces = g_array_new(false, false, sizeof(as));
3152 g_hash_table_insert(views, view, fv_address_spaces);
3153 }
3154
3155 g_array_append_val(fv_address_spaces, as);
3156 }
3157
3158 /* Print */
3159 g_hash_table_foreach(views, mtree_print_flatview, &fvi);
3160
3161 /* Free */
3162 g_hash_table_foreach_remove(views, mtree_info_flatview_free, 0);
3163 g_hash_table_unref(views);
3164
3165 return;
3166 }
3167
3168 QTAILQ_INIT(&ml_head);
3169
3170 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
3171 qemu_printf("address-space: %s\n", as->name);
3172 mtree_print_mr(as->root, 1, 0, &ml_head, owner, disabled);
3173 qemu_printf("\n");
3174 }
3175
3176 /* print aliased regions */
3177 QTAILQ_FOREACH(ml, &ml_head, mrqueue) {
3178 qemu_printf("memory-region: %s\n", memory_region_name(ml->mr));
3179 mtree_print_mr(ml->mr, 1, 0, &ml_head, owner, disabled);
3180 qemu_printf("\n");
3181 }
3182
3183 QTAILQ_FOREACH_SAFE(ml, &ml_head, mrqueue, ml2) {
3184 g_free(ml);
3185 }
3186 }
3187
3188 void memory_region_init_ram(MemoryRegion *mr,
3189 struct Object *owner,
3190 const char *name,
3191 uint64_t size,
3192 Error **errp)
3193 {
3194 DeviceState *owner_dev;
3195 Error *err = NULL;
3196
3197 memory_region_init_ram_nomigrate(mr, owner, name, size, &err);
3198 if (err) {
3199 error_propagate(errp, err);
3200 return;
3201 }
3202 /* This will assert if owner is neither NULL nor a DeviceState.
3203 * We only want the owner here for the purposes of defining a
3204 * unique name for migration. TODO: Ideally we should implement
3205 * a naming scheme for Objects which are not DeviceStates, in
3206 * which case we can relax this restriction.
3207 */
3208 owner_dev = DEVICE(owner);
3209 vmstate_register_ram(mr, owner_dev);
3210 }
3211
3212 void memory_region_init_rom(MemoryRegion *mr,
3213 struct Object *owner,
3214 const char *name,
3215 uint64_t size,
3216 Error **errp)
3217 {
3218 DeviceState *owner_dev;
3219 Error *err = NULL;
3220
3221 memory_region_init_rom_nomigrate(mr, owner, name, size, &err);
3222 if (err) {
3223 error_propagate(errp, err);
3224 return;
3225 }
3226 /* This will assert if owner is neither NULL nor a DeviceState.
3227 * We only want the owner here for the purposes of defining a
3228 * unique name for migration. TODO: Ideally we should implement
3229 * a naming scheme for Objects which are not DeviceStates, in
3230 * which case we can relax this restriction.
3231 */
3232 owner_dev = DEVICE(owner);
3233 vmstate_register_ram(mr, owner_dev);
3234 }
3235
3236 void memory_region_init_rom_device(MemoryRegion *mr,
3237 struct Object *owner,
3238 const MemoryRegionOps *ops,
3239 void *opaque,
3240 const char *name,
3241 uint64_t size,
3242 Error **errp)
3243 {
3244 DeviceState *owner_dev;
3245 Error *err = NULL;
3246
3247 memory_region_init_rom_device_nomigrate(mr, owner, ops, opaque,
3248 name, size, &err);
3249 if (err) {
3250 error_propagate(errp, err);
3251 return;
3252 }
3253 /* This will assert if owner is neither NULL nor a DeviceState.
3254 * We only want the owner here for the purposes of defining a
3255 * unique name for migration. TODO: Ideally we should implement
3256 * a naming scheme for Objects which are not DeviceStates, in
3257 * which case we can relax this restriction.
3258 */
3259 owner_dev = DEVICE(owner);
3260 vmstate_register_ram(mr, owner_dev);
3261 }
3262
3263 /*
3264 * Support softmmu builds with CONFIG_FUZZ using a weak symbol and a stub for
3265 * the fuzz_dma_read_cb callback
3266 */
3267 #ifdef CONFIG_FUZZ
3268 void __attribute__((weak)) fuzz_dma_read_cb(size_t addr,
3269 size_t len,
3270 MemoryRegion *mr,
3271 bool is_write)
3272 {
3273 }
3274 #endif
3275
3276 static const TypeInfo memory_region_info = {
3277 .parent = TYPE_OBJECT,
3278 .name = TYPE_MEMORY_REGION,
3279 .class_size = sizeof(MemoryRegionClass),
3280 .instance_size = sizeof(MemoryRegion),
3281 .instance_init = memory_region_initfn,
3282 .instance_finalize = memory_region_finalize,
3283 };
3284
3285 static const TypeInfo iommu_memory_region_info = {
3286 .parent = TYPE_MEMORY_REGION,
3287 .name = TYPE_IOMMU_MEMORY_REGION,
3288 .class_size = sizeof(IOMMUMemoryRegionClass),
3289 .instance_size = sizeof(IOMMUMemoryRegion),
3290 .instance_init = iommu_memory_region_initfn,
3291 .abstract = true,
3292 };
3293
3294 static void memory_register_types(void)
3295 {
3296 type_register_static(&memory_region_info);
3297 type_register_static(&iommu_memory_region_info);
3298 }
3299
3300 type_init(memory_register_types)