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