]> git.proxmox.com Git - mirror_qemu.git/blob - memory.c
pc-bios/s390-ccw.img: rebuild image
[mirror_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 void memory_region_transaction_commit(void)
910 {
911 AddressSpace *as;
912
913 assert(memory_region_transaction_depth);
914 assert(qemu_mutex_iothread_locked());
915
916 --memory_region_transaction_depth;
917 if (!memory_region_transaction_depth) {
918 if (memory_region_update_pending) {
919 MEMORY_LISTENER_CALL_GLOBAL(begin, Forward);
920
921 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
922 address_space_update_topology(as);
923 }
924 memory_region_update_pending = false;
925 MEMORY_LISTENER_CALL_GLOBAL(commit, Forward);
926 } else if (ioeventfd_update_pending) {
927 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
928 address_space_update_ioeventfds(as);
929 }
930 ioeventfd_update_pending = false;
931 }
932 }
933 }
934
935 static void memory_region_destructor_none(MemoryRegion *mr)
936 {
937 }
938
939 static void memory_region_destructor_ram(MemoryRegion *mr)
940 {
941 qemu_ram_free(mr->ram_block);
942 }
943
944 static bool memory_region_need_escape(char c)
945 {
946 return c == '/' || c == '[' || c == '\\' || c == ']';
947 }
948
949 static char *memory_region_escape_name(const char *name)
950 {
951 const char *p;
952 char *escaped, *q;
953 uint8_t c;
954 size_t bytes = 0;
955
956 for (p = name; *p; p++) {
957 bytes += memory_region_need_escape(*p) ? 4 : 1;
958 }
959 if (bytes == p - name) {
960 return g_memdup(name, bytes + 1);
961 }
962
963 escaped = g_malloc(bytes + 1);
964 for (p = name, q = escaped; *p; p++) {
965 c = *p;
966 if (unlikely(memory_region_need_escape(c))) {
967 *q++ = '\\';
968 *q++ = 'x';
969 *q++ = "0123456789abcdef"[c >> 4];
970 c = "0123456789abcdef"[c & 15];
971 }
972 *q++ = c;
973 }
974 *q = 0;
975 return escaped;
976 }
977
978 void memory_region_init(MemoryRegion *mr,
979 Object *owner,
980 const char *name,
981 uint64_t size)
982 {
983 object_initialize(mr, sizeof(*mr), TYPE_MEMORY_REGION);
984 mr->size = int128_make64(size);
985 if (size == UINT64_MAX) {
986 mr->size = int128_2_64();
987 }
988 mr->name = g_strdup(name);
989 mr->owner = owner;
990 mr->ram_block = NULL;
991
992 if (name) {
993 char *escaped_name = memory_region_escape_name(name);
994 char *name_array = g_strdup_printf("%s[*]", escaped_name);
995
996 if (!owner) {
997 owner = container_get(qdev_get_machine(), "/unattached");
998 }
999
1000 object_property_add_child(owner, name_array, OBJECT(mr), &error_abort);
1001 object_unref(OBJECT(mr));
1002 g_free(name_array);
1003 g_free(escaped_name);
1004 }
1005 }
1006
1007 static void memory_region_get_addr(Object *obj, Visitor *v, const char *name,
1008 void *opaque, Error **errp)
1009 {
1010 MemoryRegion *mr = MEMORY_REGION(obj);
1011 uint64_t value = mr->addr;
1012
1013 visit_type_uint64(v, name, &value, errp);
1014 }
1015
1016 static void memory_region_get_container(Object *obj, Visitor *v,
1017 const char *name, void *opaque,
1018 Error **errp)
1019 {
1020 MemoryRegion *mr = MEMORY_REGION(obj);
1021 gchar *path = (gchar *)"";
1022
1023 if (mr->container) {
1024 path = object_get_canonical_path(OBJECT(mr->container));
1025 }
1026 visit_type_str(v, name, &path, errp);
1027 if (mr->container) {
1028 g_free(path);
1029 }
1030 }
1031
1032 static Object *memory_region_resolve_container(Object *obj, void *opaque,
1033 const char *part)
1034 {
1035 MemoryRegion *mr = MEMORY_REGION(obj);
1036
1037 return OBJECT(mr->container);
1038 }
1039
1040 static void memory_region_get_priority(Object *obj, Visitor *v,
1041 const char *name, void *opaque,
1042 Error **errp)
1043 {
1044 MemoryRegion *mr = MEMORY_REGION(obj);
1045 int32_t value = mr->priority;
1046
1047 visit_type_int32(v, name, &value, errp);
1048 }
1049
1050 static void memory_region_get_size(Object *obj, Visitor *v, const char *name,
1051 void *opaque, Error **errp)
1052 {
1053 MemoryRegion *mr = MEMORY_REGION(obj);
1054 uint64_t value = memory_region_size(mr);
1055
1056 visit_type_uint64(v, name, &value, errp);
1057 }
1058
1059 static void memory_region_initfn(Object *obj)
1060 {
1061 MemoryRegion *mr = MEMORY_REGION(obj);
1062 ObjectProperty *op;
1063
1064 mr->ops = &unassigned_mem_ops;
1065 mr->enabled = true;
1066 mr->romd_mode = true;
1067 mr->global_locking = true;
1068 mr->destructor = memory_region_destructor_none;
1069 QTAILQ_INIT(&mr->subregions);
1070 QTAILQ_INIT(&mr->coalesced);
1071
1072 op = object_property_add(OBJECT(mr), "container",
1073 "link<" TYPE_MEMORY_REGION ">",
1074 memory_region_get_container,
1075 NULL, /* memory_region_set_container */
1076 NULL, NULL, &error_abort);
1077 op->resolve = memory_region_resolve_container;
1078
1079 object_property_add(OBJECT(mr), "addr", "uint64",
1080 memory_region_get_addr,
1081 NULL, /* memory_region_set_addr */
1082 NULL, NULL, &error_abort);
1083 object_property_add(OBJECT(mr), "priority", "uint32",
1084 memory_region_get_priority,
1085 NULL, /* memory_region_set_priority */
1086 NULL, NULL, &error_abort);
1087 object_property_add(OBJECT(mr), "size", "uint64",
1088 memory_region_get_size,
1089 NULL, /* memory_region_set_size, */
1090 NULL, NULL, &error_abort);
1091 }
1092
1093 static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,
1094 unsigned size)
1095 {
1096 #ifdef DEBUG_UNASSIGNED
1097 printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);
1098 #endif
1099 if (current_cpu != NULL) {
1100 cpu_unassigned_access(current_cpu, addr, false, false, 0, size);
1101 }
1102 return 0;
1103 }
1104
1105 static void unassigned_mem_write(void *opaque, hwaddr addr,
1106 uint64_t val, unsigned size)
1107 {
1108 #ifdef DEBUG_UNASSIGNED
1109 printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);
1110 #endif
1111 if (current_cpu != NULL) {
1112 cpu_unassigned_access(current_cpu, addr, true, false, 0, size);
1113 }
1114 }
1115
1116 static bool unassigned_mem_accepts(void *opaque, hwaddr addr,
1117 unsigned size, bool is_write)
1118 {
1119 return false;
1120 }
1121
1122 const MemoryRegionOps unassigned_mem_ops = {
1123 .valid.accepts = unassigned_mem_accepts,
1124 .endianness = DEVICE_NATIVE_ENDIAN,
1125 };
1126
1127 static uint64_t memory_region_ram_device_read(void *opaque,
1128 hwaddr addr, unsigned size)
1129 {
1130 MemoryRegion *mr = opaque;
1131 uint64_t data = (uint64_t)~0;
1132
1133 switch (size) {
1134 case 1:
1135 data = *(uint8_t *)(mr->ram_block->host + addr);
1136 break;
1137 case 2:
1138 data = *(uint16_t *)(mr->ram_block->host + addr);
1139 break;
1140 case 4:
1141 data = *(uint32_t *)(mr->ram_block->host + addr);
1142 break;
1143 case 8:
1144 data = *(uint64_t *)(mr->ram_block->host + addr);
1145 break;
1146 }
1147
1148 trace_memory_region_ram_device_read(get_cpu_index(), mr, addr, data, size);
1149
1150 return data;
1151 }
1152
1153 static void memory_region_ram_device_write(void *opaque, hwaddr addr,
1154 uint64_t data, unsigned size)
1155 {
1156 MemoryRegion *mr = opaque;
1157
1158 trace_memory_region_ram_device_write(get_cpu_index(), mr, addr, data, size);
1159
1160 switch (size) {
1161 case 1:
1162 *(uint8_t *)(mr->ram_block->host + addr) = (uint8_t)data;
1163 break;
1164 case 2:
1165 *(uint16_t *)(mr->ram_block->host + addr) = (uint16_t)data;
1166 break;
1167 case 4:
1168 *(uint32_t *)(mr->ram_block->host + addr) = (uint32_t)data;
1169 break;
1170 case 8:
1171 *(uint64_t *)(mr->ram_block->host + addr) = data;
1172 break;
1173 }
1174 }
1175
1176 static const MemoryRegionOps ram_device_mem_ops = {
1177 .read = memory_region_ram_device_read,
1178 .write = memory_region_ram_device_write,
1179 .endianness = DEVICE_HOST_ENDIAN,
1180 .valid = {
1181 .min_access_size = 1,
1182 .max_access_size = 8,
1183 .unaligned = true,
1184 },
1185 .impl = {
1186 .min_access_size = 1,
1187 .max_access_size = 8,
1188 .unaligned = true,
1189 },
1190 };
1191
1192 bool memory_region_access_valid(MemoryRegion *mr,
1193 hwaddr addr,
1194 unsigned size,
1195 bool is_write)
1196 {
1197 int access_size_min, access_size_max;
1198 int access_size, i;
1199
1200 if (!mr->ops->valid.unaligned && (addr & (size - 1))) {
1201 return false;
1202 }
1203
1204 if (!mr->ops->valid.accepts) {
1205 return true;
1206 }
1207
1208 access_size_min = mr->ops->valid.min_access_size;
1209 if (!mr->ops->valid.min_access_size) {
1210 access_size_min = 1;
1211 }
1212
1213 access_size_max = mr->ops->valid.max_access_size;
1214 if (!mr->ops->valid.max_access_size) {
1215 access_size_max = 4;
1216 }
1217
1218 access_size = MAX(MIN(size, access_size_max), access_size_min);
1219 for (i = 0; i < size; i += access_size) {
1220 if (!mr->ops->valid.accepts(mr->opaque, addr + i, access_size,
1221 is_write)) {
1222 return false;
1223 }
1224 }
1225
1226 return true;
1227 }
1228
1229 static MemTxResult memory_region_dispatch_read1(MemoryRegion *mr,
1230 hwaddr addr,
1231 uint64_t *pval,
1232 unsigned size,
1233 MemTxAttrs attrs)
1234 {
1235 *pval = 0;
1236
1237 if (mr->ops->read) {
1238 return access_with_adjusted_size(addr, pval, size,
1239 mr->ops->impl.min_access_size,
1240 mr->ops->impl.max_access_size,
1241 memory_region_read_accessor,
1242 mr, attrs);
1243 } else if (mr->ops->read_with_attrs) {
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_with_attrs_accessor,
1248 mr, attrs);
1249 } else {
1250 return access_with_adjusted_size(addr, pval, size, 1, 4,
1251 memory_region_oldmmio_read_accessor,
1252 mr, attrs);
1253 }
1254 }
1255
1256 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
1257 hwaddr addr,
1258 uint64_t *pval,
1259 unsigned size,
1260 MemTxAttrs attrs)
1261 {
1262 MemTxResult r;
1263
1264 if (!memory_region_access_valid(mr, addr, size, false)) {
1265 *pval = unassigned_mem_read(mr, addr, size);
1266 return MEMTX_DECODE_ERROR;
1267 }
1268
1269 r = memory_region_dispatch_read1(mr, addr, pval, size, attrs);
1270 adjust_endianness(mr, pval, size);
1271 return r;
1272 }
1273
1274 /* Return true if an eventfd was signalled */
1275 static bool memory_region_dispatch_write_eventfds(MemoryRegion *mr,
1276 hwaddr addr,
1277 uint64_t data,
1278 unsigned size,
1279 MemTxAttrs attrs)
1280 {
1281 MemoryRegionIoeventfd ioeventfd = {
1282 .addr = addrrange_make(int128_make64(addr), int128_make64(size)),
1283 .data = data,
1284 };
1285 unsigned i;
1286
1287 for (i = 0; i < mr->ioeventfd_nb; i++) {
1288 ioeventfd.match_data = mr->ioeventfds[i].match_data;
1289 ioeventfd.e = mr->ioeventfds[i].e;
1290
1291 if (memory_region_ioeventfd_equal(ioeventfd, mr->ioeventfds[i])) {
1292 event_notifier_set(ioeventfd.e);
1293 return true;
1294 }
1295 }
1296
1297 return false;
1298 }
1299
1300 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
1301 hwaddr addr,
1302 uint64_t data,
1303 unsigned size,
1304 MemTxAttrs attrs)
1305 {
1306 if (!memory_region_access_valid(mr, addr, size, true)) {
1307 unassigned_mem_write(mr, addr, data, size);
1308 return MEMTX_DECODE_ERROR;
1309 }
1310
1311 adjust_endianness(mr, &data, size);
1312
1313 if ((!kvm_eventfds_enabled()) &&
1314 memory_region_dispatch_write_eventfds(mr, addr, data, size, attrs)) {
1315 return MEMTX_OK;
1316 }
1317
1318 if (mr->ops->write) {
1319 return access_with_adjusted_size(addr, &data, size,
1320 mr->ops->impl.min_access_size,
1321 mr->ops->impl.max_access_size,
1322 memory_region_write_accessor, mr,
1323 attrs);
1324 } else if (mr->ops->write_with_attrs) {
1325 return
1326 access_with_adjusted_size(addr, &data, size,
1327 mr->ops->impl.min_access_size,
1328 mr->ops->impl.max_access_size,
1329 memory_region_write_with_attrs_accessor,
1330 mr, attrs);
1331 } else {
1332 return access_with_adjusted_size(addr, &data, size, 1, 4,
1333 memory_region_oldmmio_write_accessor,
1334 mr, attrs);
1335 }
1336 }
1337
1338 void memory_region_init_io(MemoryRegion *mr,
1339 Object *owner,
1340 const MemoryRegionOps *ops,
1341 void *opaque,
1342 const char *name,
1343 uint64_t size)
1344 {
1345 memory_region_init(mr, owner, name, size);
1346 mr->ops = ops ? ops : &unassigned_mem_ops;
1347 mr->opaque = opaque;
1348 mr->terminates = true;
1349 }
1350
1351 void memory_region_init_ram(MemoryRegion *mr,
1352 Object *owner,
1353 const char *name,
1354 uint64_t size,
1355 Error **errp)
1356 {
1357 memory_region_init(mr, owner, name, size);
1358 mr->ram = true;
1359 mr->terminates = true;
1360 mr->destructor = memory_region_destructor_ram;
1361 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1362 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1363 }
1364
1365 void memory_region_init_resizeable_ram(MemoryRegion *mr,
1366 Object *owner,
1367 const char *name,
1368 uint64_t size,
1369 uint64_t max_size,
1370 void (*resized)(const char*,
1371 uint64_t length,
1372 void *host),
1373 Error **errp)
1374 {
1375 memory_region_init(mr, owner, name, size);
1376 mr->ram = true;
1377 mr->terminates = true;
1378 mr->destructor = memory_region_destructor_ram;
1379 mr->ram_block = qemu_ram_alloc_resizeable(size, max_size, resized,
1380 mr, errp);
1381 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1382 }
1383
1384 #ifdef __linux__
1385 void memory_region_init_ram_from_file(MemoryRegion *mr,
1386 struct Object *owner,
1387 const char *name,
1388 uint64_t size,
1389 bool share,
1390 const char *path,
1391 Error **errp)
1392 {
1393 memory_region_init(mr, owner, name, size);
1394 mr->ram = true;
1395 mr->terminates = true;
1396 mr->destructor = memory_region_destructor_ram;
1397 mr->ram_block = qemu_ram_alloc_from_file(size, mr, share, path, errp);
1398 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1399 }
1400 #endif
1401
1402 void memory_region_init_ram_ptr(MemoryRegion *mr,
1403 Object *owner,
1404 const char *name,
1405 uint64_t size,
1406 void *ptr)
1407 {
1408 memory_region_init(mr, owner, name, size);
1409 mr->ram = true;
1410 mr->terminates = true;
1411 mr->destructor = memory_region_destructor_ram;
1412 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1413
1414 /* qemu_ram_alloc_from_ptr cannot fail with ptr != NULL. */
1415 assert(ptr != NULL);
1416 mr->ram_block = qemu_ram_alloc_from_ptr(size, ptr, mr, &error_fatal);
1417 }
1418
1419 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1420 Object *owner,
1421 const char *name,
1422 uint64_t size,
1423 void *ptr)
1424 {
1425 memory_region_init_ram_ptr(mr, owner, name, size, ptr);
1426 mr->ram_device = true;
1427 mr->ops = &ram_device_mem_ops;
1428 mr->opaque = mr;
1429 }
1430
1431 void memory_region_init_alias(MemoryRegion *mr,
1432 Object *owner,
1433 const char *name,
1434 MemoryRegion *orig,
1435 hwaddr offset,
1436 uint64_t size)
1437 {
1438 memory_region_init(mr, owner, name, size);
1439 mr->alias = orig;
1440 mr->alias_offset = offset;
1441 }
1442
1443 void memory_region_init_rom(MemoryRegion *mr,
1444 struct Object *owner,
1445 const char *name,
1446 uint64_t size,
1447 Error **errp)
1448 {
1449 memory_region_init(mr, owner, name, size);
1450 mr->ram = true;
1451 mr->readonly = true;
1452 mr->terminates = true;
1453 mr->destructor = memory_region_destructor_ram;
1454 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1455 mr->dirty_log_mask = tcg_enabled() ? (1 << DIRTY_MEMORY_CODE) : 0;
1456 }
1457
1458 void memory_region_init_rom_device(MemoryRegion *mr,
1459 Object *owner,
1460 const MemoryRegionOps *ops,
1461 void *opaque,
1462 const char *name,
1463 uint64_t size,
1464 Error **errp)
1465 {
1466 assert(ops);
1467 memory_region_init(mr, owner, name, size);
1468 mr->ops = ops;
1469 mr->opaque = opaque;
1470 mr->terminates = true;
1471 mr->rom_device = true;
1472 mr->destructor = memory_region_destructor_ram;
1473 mr->ram_block = qemu_ram_alloc(size, mr, errp);
1474 }
1475
1476 void memory_region_init_iommu(MemoryRegion *mr,
1477 Object *owner,
1478 const MemoryRegionIOMMUOps *ops,
1479 const char *name,
1480 uint64_t size)
1481 {
1482 memory_region_init(mr, owner, name, size);
1483 mr->iommu_ops = ops,
1484 mr->terminates = true; /* then re-forwards */
1485 QLIST_INIT(&mr->iommu_notify);
1486 mr->iommu_notify_flags = IOMMU_NOTIFIER_NONE;
1487 }
1488
1489 static void memory_region_finalize(Object *obj)
1490 {
1491 MemoryRegion *mr = MEMORY_REGION(obj);
1492
1493 assert(!mr->container);
1494
1495 /* We know the region is not visible in any address space (it
1496 * does not have a container and cannot be a root either because
1497 * it has no references, so we can blindly clear mr->enabled.
1498 * memory_region_set_enabled instead could trigger a transaction
1499 * and cause an infinite loop.
1500 */
1501 mr->enabled = false;
1502 memory_region_transaction_begin();
1503 while (!QTAILQ_EMPTY(&mr->subregions)) {
1504 MemoryRegion *subregion = QTAILQ_FIRST(&mr->subregions);
1505 memory_region_del_subregion(mr, subregion);
1506 }
1507 memory_region_transaction_commit();
1508
1509 mr->destructor(mr);
1510 memory_region_clear_coalescing(mr);
1511 g_free((char *)mr->name);
1512 g_free(mr->ioeventfds);
1513 }
1514
1515 Object *memory_region_owner(MemoryRegion *mr)
1516 {
1517 Object *obj = OBJECT(mr);
1518 return obj->parent;
1519 }
1520
1521 void memory_region_ref(MemoryRegion *mr)
1522 {
1523 /* MMIO callbacks most likely will access data that belongs
1524 * to the owner, hence the need to ref/unref the owner whenever
1525 * the memory region is in use.
1526 *
1527 * The memory region is a child of its owner. As long as the
1528 * owner doesn't call unparent itself on the memory region,
1529 * ref-ing the owner will also keep the memory region alive.
1530 * Memory regions without an owner are supposed to never go away;
1531 * we do not ref/unref them because it slows down DMA sensibly.
1532 */
1533 if (mr && mr->owner) {
1534 object_ref(mr->owner);
1535 }
1536 }
1537
1538 void memory_region_unref(MemoryRegion *mr)
1539 {
1540 if (mr && mr->owner) {
1541 object_unref(mr->owner);
1542 }
1543 }
1544
1545 uint64_t memory_region_size(MemoryRegion *mr)
1546 {
1547 if (int128_eq(mr->size, int128_2_64())) {
1548 return UINT64_MAX;
1549 }
1550 return int128_get64(mr->size);
1551 }
1552
1553 const char *memory_region_name(const MemoryRegion *mr)
1554 {
1555 if (!mr->name) {
1556 ((MemoryRegion *)mr)->name =
1557 object_get_canonical_path_component(OBJECT(mr));
1558 }
1559 return mr->name;
1560 }
1561
1562 bool memory_region_is_ram_device(MemoryRegion *mr)
1563 {
1564 return mr->ram_device;
1565 }
1566
1567 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr)
1568 {
1569 uint8_t mask = mr->dirty_log_mask;
1570 if (global_dirty_log && mr->ram_block) {
1571 mask |= (1 << DIRTY_MEMORY_MIGRATION);
1572 }
1573 return mask;
1574 }
1575
1576 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client)
1577 {
1578 return memory_region_get_dirty_log_mask(mr) & (1 << client);
1579 }
1580
1581 static void memory_region_update_iommu_notify_flags(MemoryRegion *mr)
1582 {
1583 IOMMUNotifierFlag flags = IOMMU_NOTIFIER_NONE;
1584 IOMMUNotifier *iommu_notifier;
1585
1586 IOMMU_NOTIFIER_FOREACH(iommu_notifier, mr) {
1587 flags |= iommu_notifier->notifier_flags;
1588 }
1589
1590 if (flags != mr->iommu_notify_flags &&
1591 mr->iommu_ops->notify_flag_changed) {
1592 mr->iommu_ops->notify_flag_changed(mr, mr->iommu_notify_flags,
1593 flags);
1594 }
1595
1596 mr->iommu_notify_flags = flags;
1597 }
1598
1599 void memory_region_register_iommu_notifier(MemoryRegion *mr,
1600 IOMMUNotifier *n)
1601 {
1602 if (mr->alias) {
1603 memory_region_register_iommu_notifier(mr->alias, n);
1604 return;
1605 }
1606
1607 /* We need to register for at least one bitfield */
1608 assert(n->notifier_flags != IOMMU_NOTIFIER_NONE);
1609 assert(n->start <= n->end);
1610 QLIST_INSERT_HEAD(&mr->iommu_notify, n, node);
1611 memory_region_update_iommu_notify_flags(mr);
1612 }
1613
1614 uint64_t memory_region_iommu_get_min_page_size(MemoryRegion *mr)
1615 {
1616 assert(memory_region_is_iommu(mr));
1617 if (mr->iommu_ops && mr->iommu_ops->get_min_page_size) {
1618 return mr->iommu_ops->get_min_page_size(mr);
1619 }
1620 return TARGET_PAGE_SIZE;
1621 }
1622
1623 void memory_region_iommu_replay(MemoryRegion *mr, IOMMUNotifier *n,
1624 bool is_write)
1625 {
1626 hwaddr addr, granularity;
1627 IOMMUTLBEntry iotlb;
1628
1629 /* If the IOMMU has its own replay callback, override */
1630 if (mr->iommu_ops->replay) {
1631 mr->iommu_ops->replay(mr, n);
1632 return;
1633 }
1634
1635 granularity = memory_region_iommu_get_min_page_size(mr);
1636
1637 for (addr = 0; addr < memory_region_size(mr); addr += granularity) {
1638 iotlb = mr->iommu_ops->translate(mr, addr, is_write);
1639 if (iotlb.perm != IOMMU_NONE) {
1640 n->notify(n, &iotlb);
1641 }
1642
1643 /* if (2^64 - MR size) < granularity, it's possible to get an
1644 * infinite loop here. This should catch such a wraparound */
1645 if ((addr + granularity) < addr) {
1646 break;
1647 }
1648 }
1649 }
1650
1651 void memory_region_iommu_replay_all(MemoryRegion *mr)
1652 {
1653 IOMMUNotifier *notifier;
1654
1655 IOMMU_NOTIFIER_FOREACH(notifier, mr) {
1656 memory_region_iommu_replay(mr, notifier, false);
1657 }
1658 }
1659
1660 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1661 IOMMUNotifier *n)
1662 {
1663 if (mr->alias) {
1664 memory_region_unregister_iommu_notifier(mr->alias, n);
1665 return;
1666 }
1667 QLIST_REMOVE(n, node);
1668 memory_region_update_iommu_notify_flags(mr);
1669 }
1670
1671 void memory_region_notify_one(IOMMUNotifier *notifier,
1672 IOMMUTLBEntry *entry)
1673 {
1674 IOMMUNotifierFlag request_flags;
1675
1676 /*
1677 * Skip the notification if the notification does not overlap
1678 * with registered range.
1679 */
1680 if (notifier->start > entry->iova + entry->addr_mask + 1 ||
1681 notifier->end < entry->iova) {
1682 return;
1683 }
1684
1685 if (entry->perm & IOMMU_RW) {
1686 request_flags = IOMMU_NOTIFIER_MAP;
1687 } else {
1688 request_flags = IOMMU_NOTIFIER_UNMAP;
1689 }
1690
1691 if (notifier->notifier_flags & request_flags) {
1692 notifier->notify(notifier, entry);
1693 }
1694 }
1695
1696 void memory_region_notify_iommu(MemoryRegion *mr,
1697 IOMMUTLBEntry entry)
1698 {
1699 IOMMUNotifier *iommu_notifier;
1700
1701 assert(memory_region_is_iommu(mr));
1702
1703 IOMMU_NOTIFIER_FOREACH(iommu_notifier, mr) {
1704 memory_region_notify_one(iommu_notifier, &entry);
1705 }
1706 }
1707
1708 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client)
1709 {
1710 uint8_t mask = 1 << client;
1711 uint8_t old_logging;
1712
1713 assert(client == DIRTY_MEMORY_VGA);
1714 old_logging = mr->vga_logging_count;
1715 mr->vga_logging_count += log ? 1 : -1;
1716 if (!!old_logging == !!mr->vga_logging_count) {
1717 return;
1718 }
1719
1720 memory_region_transaction_begin();
1721 mr->dirty_log_mask = (mr->dirty_log_mask & ~mask) | (log * mask);
1722 memory_region_update_pending |= mr->enabled;
1723 memory_region_transaction_commit();
1724 }
1725
1726 bool memory_region_get_dirty(MemoryRegion *mr, hwaddr addr,
1727 hwaddr size, unsigned client)
1728 {
1729 assert(mr->ram_block);
1730 return cpu_physical_memory_get_dirty(memory_region_get_ram_addr(mr) + addr,
1731 size, client);
1732 }
1733
1734 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1735 hwaddr size)
1736 {
1737 assert(mr->ram_block);
1738 cpu_physical_memory_set_dirty_range(memory_region_get_ram_addr(mr) + addr,
1739 size,
1740 memory_region_get_dirty_log_mask(mr));
1741 }
1742
1743 bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,
1744 hwaddr size, unsigned client)
1745 {
1746 assert(mr->ram_block);
1747 return cpu_physical_memory_test_and_clear_dirty(
1748 memory_region_get_ram_addr(mr) + addr, size, client);
1749 }
1750
1751 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
1752 hwaddr addr,
1753 hwaddr size,
1754 unsigned client)
1755 {
1756 assert(mr->ram_block);
1757 return cpu_physical_memory_snapshot_and_clear_dirty(
1758 memory_region_get_ram_addr(mr) + addr, size, client);
1759 }
1760
1761 bool memory_region_snapshot_get_dirty(MemoryRegion *mr, DirtyBitmapSnapshot *snap,
1762 hwaddr addr, hwaddr size)
1763 {
1764 assert(mr->ram_block);
1765 return cpu_physical_memory_snapshot_get_dirty(snap,
1766 memory_region_get_ram_addr(mr) + addr, size);
1767 }
1768
1769 void memory_region_sync_dirty_bitmap(MemoryRegion *mr)
1770 {
1771 MemoryListener *listener;
1772 AddressSpace *as;
1773 FlatView *view;
1774 FlatRange *fr;
1775
1776 /* If the same address space has multiple log_sync listeners, we
1777 * visit that address space's FlatView multiple times. But because
1778 * log_sync listeners are rare, it's still cheaper than walking each
1779 * address space once.
1780 */
1781 QTAILQ_FOREACH(listener, &memory_listeners, link) {
1782 if (!listener->log_sync) {
1783 continue;
1784 }
1785 as = listener->address_space;
1786 view = address_space_get_flatview(as);
1787 FOR_EACH_FLAT_RANGE(fr, view) {
1788 if (fr->mr == mr) {
1789 MemoryRegionSection mrs = section_from_flat_range(fr, as);
1790 listener->log_sync(listener, &mrs);
1791 }
1792 }
1793 flatview_unref(view);
1794 }
1795 }
1796
1797 void memory_region_set_readonly(MemoryRegion *mr, bool readonly)
1798 {
1799 if (mr->readonly != readonly) {
1800 memory_region_transaction_begin();
1801 mr->readonly = readonly;
1802 memory_region_update_pending |= mr->enabled;
1803 memory_region_transaction_commit();
1804 }
1805 }
1806
1807 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode)
1808 {
1809 if (mr->romd_mode != romd_mode) {
1810 memory_region_transaction_begin();
1811 mr->romd_mode = romd_mode;
1812 memory_region_update_pending |= mr->enabled;
1813 memory_region_transaction_commit();
1814 }
1815 }
1816
1817 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1818 hwaddr size, unsigned client)
1819 {
1820 assert(mr->ram_block);
1821 cpu_physical_memory_test_and_clear_dirty(
1822 memory_region_get_ram_addr(mr) + addr, size, client);
1823 }
1824
1825 int memory_region_get_fd(MemoryRegion *mr)
1826 {
1827 int fd;
1828
1829 rcu_read_lock();
1830 while (mr->alias) {
1831 mr = mr->alias;
1832 }
1833 fd = mr->ram_block->fd;
1834 rcu_read_unlock();
1835
1836 return fd;
1837 }
1838
1839 void memory_region_set_fd(MemoryRegion *mr, int fd)
1840 {
1841 rcu_read_lock();
1842 while (mr->alias) {
1843 mr = mr->alias;
1844 }
1845 mr->ram_block->fd = fd;
1846 rcu_read_unlock();
1847 }
1848
1849 void *memory_region_get_ram_ptr(MemoryRegion *mr)
1850 {
1851 void *ptr;
1852 uint64_t offset = 0;
1853
1854 rcu_read_lock();
1855 while (mr->alias) {
1856 offset += mr->alias_offset;
1857 mr = mr->alias;
1858 }
1859 assert(mr->ram_block);
1860 ptr = qemu_map_ram_ptr(mr->ram_block, offset);
1861 rcu_read_unlock();
1862
1863 return ptr;
1864 }
1865
1866 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset)
1867 {
1868 RAMBlock *block;
1869
1870 block = qemu_ram_block_from_host(ptr, false, offset);
1871 if (!block) {
1872 return NULL;
1873 }
1874
1875 return block->mr;
1876 }
1877
1878 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)
1879 {
1880 return mr->ram_block ? mr->ram_block->offset : RAM_ADDR_INVALID;
1881 }
1882
1883 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)
1884 {
1885 assert(mr->ram_block);
1886
1887 qemu_ram_resize(mr->ram_block, newsize, errp);
1888 }
1889
1890 static void memory_region_update_coalesced_range_as(MemoryRegion *mr, AddressSpace *as)
1891 {
1892 FlatView *view;
1893 FlatRange *fr;
1894 CoalescedMemoryRange *cmr;
1895 AddrRange tmp;
1896 MemoryRegionSection section;
1897
1898 view = address_space_get_flatview(as);
1899 FOR_EACH_FLAT_RANGE(fr, view) {
1900 if (fr->mr == mr) {
1901 section = (MemoryRegionSection) {
1902 .address_space = as,
1903 .offset_within_address_space = int128_get64(fr->addr.start),
1904 .size = fr->addr.size,
1905 };
1906
1907 MEMORY_LISTENER_CALL(as, coalesced_mmio_del, Reverse, &section,
1908 int128_get64(fr->addr.start),
1909 int128_get64(fr->addr.size));
1910 QTAILQ_FOREACH(cmr, &mr->coalesced, link) {
1911 tmp = addrrange_shift(cmr->addr,
1912 int128_sub(fr->addr.start,
1913 int128_make64(fr->offset_in_region)));
1914 if (!addrrange_intersects(tmp, fr->addr)) {
1915 continue;
1916 }
1917 tmp = addrrange_intersection(tmp, fr->addr);
1918 MEMORY_LISTENER_CALL(as, coalesced_mmio_add, Forward, &section,
1919 int128_get64(tmp.start),
1920 int128_get64(tmp.size));
1921 }
1922 }
1923 }
1924 flatview_unref(view);
1925 }
1926
1927 static void memory_region_update_coalesced_range(MemoryRegion *mr)
1928 {
1929 AddressSpace *as;
1930
1931 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
1932 memory_region_update_coalesced_range_as(mr, as);
1933 }
1934 }
1935
1936 void memory_region_set_coalescing(MemoryRegion *mr)
1937 {
1938 memory_region_clear_coalescing(mr);
1939 memory_region_add_coalescing(mr, 0, int128_get64(mr->size));
1940 }
1941
1942 void memory_region_add_coalescing(MemoryRegion *mr,
1943 hwaddr offset,
1944 uint64_t size)
1945 {
1946 CoalescedMemoryRange *cmr = g_malloc(sizeof(*cmr));
1947
1948 cmr->addr = addrrange_make(int128_make64(offset), int128_make64(size));
1949 QTAILQ_INSERT_TAIL(&mr->coalesced, cmr, link);
1950 memory_region_update_coalesced_range(mr);
1951 memory_region_set_flush_coalesced(mr);
1952 }
1953
1954 void memory_region_clear_coalescing(MemoryRegion *mr)
1955 {
1956 CoalescedMemoryRange *cmr;
1957 bool updated = false;
1958
1959 qemu_flush_coalesced_mmio_buffer();
1960 mr->flush_coalesced_mmio = false;
1961
1962 while (!QTAILQ_EMPTY(&mr->coalesced)) {
1963 cmr = QTAILQ_FIRST(&mr->coalesced);
1964 QTAILQ_REMOVE(&mr->coalesced, cmr, link);
1965 g_free(cmr);
1966 updated = true;
1967 }
1968
1969 if (updated) {
1970 memory_region_update_coalesced_range(mr);
1971 }
1972 }
1973
1974 void memory_region_set_flush_coalesced(MemoryRegion *mr)
1975 {
1976 mr->flush_coalesced_mmio = true;
1977 }
1978
1979 void memory_region_clear_flush_coalesced(MemoryRegion *mr)
1980 {
1981 qemu_flush_coalesced_mmio_buffer();
1982 if (QTAILQ_EMPTY(&mr->coalesced)) {
1983 mr->flush_coalesced_mmio = false;
1984 }
1985 }
1986
1987 void memory_region_set_global_locking(MemoryRegion *mr)
1988 {
1989 mr->global_locking = true;
1990 }
1991
1992 void memory_region_clear_global_locking(MemoryRegion *mr)
1993 {
1994 mr->global_locking = false;
1995 }
1996
1997 static bool userspace_eventfd_warning;
1998
1999 void memory_region_add_eventfd(MemoryRegion *mr,
2000 hwaddr addr,
2001 unsigned size,
2002 bool match_data,
2003 uint64_t data,
2004 EventNotifier *e)
2005 {
2006 MemoryRegionIoeventfd mrfd = {
2007 .addr.start = int128_make64(addr),
2008 .addr.size = int128_make64(size),
2009 .match_data = match_data,
2010 .data = data,
2011 .e = e,
2012 };
2013 unsigned i;
2014
2015 if (kvm_enabled() && (!(kvm_eventfds_enabled() ||
2016 userspace_eventfd_warning))) {
2017 userspace_eventfd_warning = true;
2018 error_report("Using eventfd without MMIO binding in KVM. "
2019 "Suboptimal performance expected");
2020 }
2021
2022 if (size) {
2023 adjust_endianness(mr, &mrfd.data, size);
2024 }
2025 memory_region_transaction_begin();
2026 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2027 if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
2028 break;
2029 }
2030 }
2031 ++mr->ioeventfd_nb;
2032 mr->ioeventfds = g_realloc(mr->ioeventfds,
2033 sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
2034 memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
2035 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
2036 mr->ioeventfds[i] = mrfd;
2037 ioeventfd_update_pending |= mr->enabled;
2038 memory_region_transaction_commit();
2039 }
2040
2041 void memory_region_del_eventfd(MemoryRegion *mr,
2042 hwaddr addr,
2043 unsigned size,
2044 bool match_data,
2045 uint64_t data,
2046 EventNotifier *e)
2047 {
2048 MemoryRegionIoeventfd mrfd = {
2049 .addr.start = int128_make64(addr),
2050 .addr.size = int128_make64(size),
2051 .match_data = match_data,
2052 .data = data,
2053 .e = e,
2054 };
2055 unsigned i;
2056
2057 if (size) {
2058 adjust_endianness(mr, &mrfd.data, size);
2059 }
2060 memory_region_transaction_begin();
2061 for (i = 0; i < mr->ioeventfd_nb; ++i) {
2062 if (memory_region_ioeventfd_equal(mrfd, mr->ioeventfds[i])) {
2063 break;
2064 }
2065 }
2066 assert(i != mr->ioeventfd_nb);
2067 memmove(&mr->ioeventfds[i], &mr->ioeventfds[i+1],
2068 sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb - (i+1)));
2069 --mr->ioeventfd_nb;
2070 mr->ioeventfds = g_realloc(mr->ioeventfds,
2071 sizeof(*mr->ioeventfds)*mr->ioeventfd_nb + 1);
2072 ioeventfd_update_pending |= mr->enabled;
2073 memory_region_transaction_commit();
2074 }
2075
2076 static void memory_region_update_container_subregions(MemoryRegion *subregion)
2077 {
2078 MemoryRegion *mr = subregion->container;
2079 MemoryRegion *other;
2080
2081 memory_region_transaction_begin();
2082
2083 memory_region_ref(subregion);
2084 QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {
2085 if (subregion->priority >= other->priority) {
2086 QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);
2087 goto done;
2088 }
2089 }
2090 QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);
2091 done:
2092 memory_region_update_pending |= mr->enabled && subregion->enabled;
2093 memory_region_transaction_commit();
2094 }
2095
2096 static void memory_region_add_subregion_common(MemoryRegion *mr,
2097 hwaddr offset,
2098 MemoryRegion *subregion)
2099 {
2100 assert(!subregion->container);
2101 subregion->container = mr;
2102 subregion->addr = offset;
2103 memory_region_update_container_subregions(subregion);
2104 }
2105
2106 void memory_region_add_subregion(MemoryRegion *mr,
2107 hwaddr offset,
2108 MemoryRegion *subregion)
2109 {
2110 subregion->priority = 0;
2111 memory_region_add_subregion_common(mr, offset, subregion);
2112 }
2113
2114 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2115 hwaddr offset,
2116 MemoryRegion *subregion,
2117 int priority)
2118 {
2119 subregion->priority = priority;
2120 memory_region_add_subregion_common(mr, offset, subregion);
2121 }
2122
2123 void memory_region_del_subregion(MemoryRegion *mr,
2124 MemoryRegion *subregion)
2125 {
2126 memory_region_transaction_begin();
2127 assert(subregion->container == mr);
2128 subregion->container = NULL;
2129 QTAILQ_REMOVE(&mr->subregions, subregion, subregions_link);
2130 memory_region_unref(subregion);
2131 memory_region_update_pending |= mr->enabled && subregion->enabled;
2132 memory_region_transaction_commit();
2133 }
2134
2135 void memory_region_set_enabled(MemoryRegion *mr, bool enabled)
2136 {
2137 if (enabled == mr->enabled) {
2138 return;
2139 }
2140 memory_region_transaction_begin();
2141 mr->enabled = enabled;
2142 memory_region_update_pending = true;
2143 memory_region_transaction_commit();
2144 }
2145
2146 void memory_region_set_size(MemoryRegion *mr, uint64_t size)
2147 {
2148 Int128 s = int128_make64(size);
2149
2150 if (size == UINT64_MAX) {
2151 s = int128_2_64();
2152 }
2153 if (int128_eq(s, mr->size)) {
2154 return;
2155 }
2156 memory_region_transaction_begin();
2157 mr->size = s;
2158 memory_region_update_pending = true;
2159 memory_region_transaction_commit();
2160 }
2161
2162 static void memory_region_readd_subregion(MemoryRegion *mr)
2163 {
2164 MemoryRegion *container = mr->container;
2165
2166 if (container) {
2167 memory_region_transaction_begin();
2168 memory_region_ref(mr);
2169 memory_region_del_subregion(container, mr);
2170 mr->container = container;
2171 memory_region_update_container_subregions(mr);
2172 memory_region_unref(mr);
2173 memory_region_transaction_commit();
2174 }
2175 }
2176
2177 void memory_region_set_address(MemoryRegion *mr, hwaddr addr)
2178 {
2179 if (addr != mr->addr) {
2180 mr->addr = addr;
2181 memory_region_readd_subregion(mr);
2182 }
2183 }
2184
2185 void memory_region_set_alias_offset(MemoryRegion *mr, hwaddr offset)
2186 {
2187 assert(mr->alias);
2188
2189 if (offset == mr->alias_offset) {
2190 return;
2191 }
2192
2193 memory_region_transaction_begin();
2194 mr->alias_offset = offset;
2195 memory_region_update_pending |= mr->enabled;
2196 memory_region_transaction_commit();
2197 }
2198
2199 uint64_t memory_region_get_alignment(const MemoryRegion *mr)
2200 {
2201 return mr->align;
2202 }
2203
2204 static int cmp_flatrange_addr(const void *addr_, const void *fr_)
2205 {
2206 const AddrRange *addr = addr_;
2207 const FlatRange *fr = fr_;
2208
2209 if (int128_le(addrrange_end(*addr), fr->addr.start)) {
2210 return -1;
2211 } else if (int128_ge(addr->start, addrrange_end(fr->addr))) {
2212 return 1;
2213 }
2214 return 0;
2215 }
2216
2217 static FlatRange *flatview_lookup(FlatView *view, AddrRange addr)
2218 {
2219 return bsearch(&addr, view->ranges, view->nr,
2220 sizeof(FlatRange), cmp_flatrange_addr);
2221 }
2222
2223 bool memory_region_is_mapped(MemoryRegion *mr)
2224 {
2225 return mr->container ? true : false;
2226 }
2227
2228 /* Same as memory_region_find, but it does not add a reference to the
2229 * returned region. It must be called from an RCU critical section.
2230 */
2231 static MemoryRegionSection memory_region_find_rcu(MemoryRegion *mr,
2232 hwaddr addr, uint64_t size)
2233 {
2234 MemoryRegionSection ret = { .mr = NULL };
2235 MemoryRegion *root;
2236 AddressSpace *as;
2237 AddrRange range;
2238 FlatView *view;
2239 FlatRange *fr;
2240
2241 addr += mr->addr;
2242 for (root = mr; root->container; ) {
2243 root = root->container;
2244 addr += root->addr;
2245 }
2246
2247 as = memory_region_to_address_space(root);
2248 if (!as) {
2249 return ret;
2250 }
2251 range = addrrange_make(int128_make64(addr), int128_make64(size));
2252
2253 view = atomic_rcu_read(&as->current_map);
2254 fr = flatview_lookup(view, range);
2255 if (!fr) {
2256 return ret;
2257 }
2258
2259 while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {
2260 --fr;
2261 }
2262
2263 ret.mr = fr->mr;
2264 ret.address_space = as;
2265 range = addrrange_intersection(range, fr->addr);
2266 ret.offset_within_region = fr->offset_in_region;
2267 ret.offset_within_region += int128_get64(int128_sub(range.start,
2268 fr->addr.start));
2269 ret.size = range.size;
2270 ret.offset_within_address_space = int128_get64(range.start);
2271 ret.readonly = fr->readonly;
2272 return ret;
2273 }
2274
2275 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2276 hwaddr addr, uint64_t size)
2277 {
2278 MemoryRegionSection ret;
2279 rcu_read_lock();
2280 ret = memory_region_find_rcu(mr, addr, size);
2281 if (ret.mr) {
2282 memory_region_ref(ret.mr);
2283 }
2284 rcu_read_unlock();
2285 return ret;
2286 }
2287
2288 bool memory_region_present(MemoryRegion *container, hwaddr addr)
2289 {
2290 MemoryRegion *mr;
2291
2292 rcu_read_lock();
2293 mr = memory_region_find_rcu(container, addr, 1).mr;
2294 rcu_read_unlock();
2295 return mr && mr != container;
2296 }
2297
2298 void memory_global_dirty_log_sync(void)
2299 {
2300 MemoryListener *listener;
2301 AddressSpace *as;
2302 FlatView *view;
2303 FlatRange *fr;
2304
2305 QTAILQ_FOREACH(listener, &memory_listeners, link) {
2306 if (!listener->log_sync) {
2307 continue;
2308 }
2309 as = listener->address_space;
2310 view = address_space_get_flatview(as);
2311 FOR_EACH_FLAT_RANGE(fr, view) {
2312 if (fr->dirty_log_mask) {
2313 MemoryRegionSection mrs = section_from_flat_range(fr, as);
2314 listener->log_sync(listener, &mrs);
2315 }
2316 }
2317 flatview_unref(view);
2318 }
2319 }
2320
2321 void memory_global_dirty_log_start(void)
2322 {
2323 global_dirty_log = true;
2324
2325 MEMORY_LISTENER_CALL_GLOBAL(log_global_start, Forward);
2326
2327 /* Refresh DIRTY_LOG_MIGRATION bit. */
2328 memory_region_transaction_begin();
2329 memory_region_update_pending = true;
2330 memory_region_transaction_commit();
2331 }
2332
2333 void memory_global_dirty_log_stop(void)
2334 {
2335 global_dirty_log = false;
2336
2337 /* Refresh DIRTY_LOG_MIGRATION bit. */
2338 memory_region_transaction_begin();
2339 memory_region_update_pending = true;
2340 memory_region_transaction_commit();
2341
2342 MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);
2343 }
2344
2345 static void listener_add_address_space(MemoryListener *listener,
2346 AddressSpace *as)
2347 {
2348 FlatView *view;
2349 FlatRange *fr;
2350
2351 if (listener->begin) {
2352 listener->begin(listener);
2353 }
2354 if (global_dirty_log) {
2355 if (listener->log_global_start) {
2356 listener->log_global_start(listener);
2357 }
2358 }
2359
2360 view = address_space_get_flatview(as);
2361 FOR_EACH_FLAT_RANGE(fr, view) {
2362 MemoryRegionSection section = {
2363 .mr = fr->mr,
2364 .address_space = as,
2365 .offset_within_region = fr->offset_in_region,
2366 .size = fr->addr.size,
2367 .offset_within_address_space = int128_get64(fr->addr.start),
2368 .readonly = fr->readonly,
2369 };
2370 if (fr->dirty_log_mask && listener->log_start) {
2371 listener->log_start(listener, &section, 0, fr->dirty_log_mask);
2372 }
2373 if (listener->region_add) {
2374 listener->region_add(listener, &section);
2375 }
2376 }
2377 if (listener->commit) {
2378 listener->commit(listener);
2379 }
2380 flatview_unref(view);
2381 }
2382
2383 void memory_listener_register(MemoryListener *listener, AddressSpace *as)
2384 {
2385 MemoryListener *other = NULL;
2386
2387 listener->address_space = as;
2388 if (QTAILQ_EMPTY(&memory_listeners)
2389 || listener->priority >= QTAILQ_LAST(&memory_listeners,
2390 memory_listeners)->priority) {
2391 QTAILQ_INSERT_TAIL(&memory_listeners, listener, link);
2392 } else {
2393 QTAILQ_FOREACH(other, &memory_listeners, link) {
2394 if (listener->priority < other->priority) {
2395 break;
2396 }
2397 }
2398 QTAILQ_INSERT_BEFORE(other, listener, link);
2399 }
2400
2401 if (QTAILQ_EMPTY(&as->listeners)
2402 || listener->priority >= QTAILQ_LAST(&as->listeners,
2403 memory_listeners)->priority) {
2404 QTAILQ_INSERT_TAIL(&as->listeners, listener, link_as);
2405 } else {
2406 QTAILQ_FOREACH(other, &as->listeners, link_as) {
2407 if (listener->priority < other->priority) {
2408 break;
2409 }
2410 }
2411 QTAILQ_INSERT_BEFORE(other, listener, link_as);
2412 }
2413
2414 listener_add_address_space(listener, as);
2415 }
2416
2417 void memory_listener_unregister(MemoryListener *listener)
2418 {
2419 if (!listener->address_space) {
2420 return;
2421 }
2422
2423 QTAILQ_REMOVE(&memory_listeners, listener, link);
2424 QTAILQ_REMOVE(&listener->address_space->listeners, listener, link_as);
2425 listener->address_space = NULL;
2426 }
2427
2428 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)
2429 {
2430 memory_region_ref(root);
2431 memory_region_transaction_begin();
2432 as->ref_count = 1;
2433 as->root = root;
2434 as->malloced = false;
2435 as->current_map = g_new(FlatView, 1);
2436 flatview_init(as->current_map);
2437 as->ioeventfd_nb = 0;
2438 as->ioeventfds = NULL;
2439 QTAILQ_INIT(&as->listeners);
2440 QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);
2441 as->name = g_strdup(name ? name : "anonymous");
2442 address_space_init_dispatch(as);
2443 memory_region_update_pending |= root->enabled;
2444 memory_region_transaction_commit();
2445 }
2446
2447 static void do_address_space_destroy(AddressSpace *as)
2448 {
2449 bool do_free = as->malloced;
2450
2451 address_space_destroy_dispatch(as);
2452 assert(QTAILQ_EMPTY(&as->listeners));
2453
2454 flatview_unref(as->current_map);
2455 g_free(as->name);
2456 g_free(as->ioeventfds);
2457 memory_region_unref(as->root);
2458 if (do_free) {
2459 g_free(as);
2460 }
2461 }
2462
2463 AddressSpace *address_space_init_shareable(MemoryRegion *root, const char *name)
2464 {
2465 AddressSpace *as;
2466
2467 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2468 if (root == as->root && as->malloced) {
2469 as->ref_count++;
2470 return as;
2471 }
2472 }
2473
2474 as = g_malloc0(sizeof *as);
2475 address_space_init(as, root, name);
2476 as->malloced = true;
2477 return as;
2478 }
2479
2480 void address_space_destroy(AddressSpace *as)
2481 {
2482 MemoryRegion *root = as->root;
2483
2484 as->ref_count--;
2485 if (as->ref_count) {
2486 return;
2487 }
2488 /* Flush out anything from MemoryListeners listening in on this */
2489 memory_region_transaction_begin();
2490 as->root = NULL;
2491 memory_region_transaction_commit();
2492 QTAILQ_REMOVE(&address_spaces, as, address_spaces_link);
2493 address_space_unregister(as);
2494
2495 /* At this point, as->dispatch and as->current_map are dummy
2496 * entries that the guest should never use. Wait for the old
2497 * values to expire before freeing the data.
2498 */
2499 as->root = root;
2500 call_rcu(as, do_address_space_destroy, rcu);
2501 }
2502
2503 static const char *memory_region_type(MemoryRegion *mr)
2504 {
2505 if (memory_region_is_ram_device(mr)) {
2506 return "ramd";
2507 } else if (memory_region_is_romd(mr)) {
2508 return "romd";
2509 } else if (memory_region_is_rom(mr)) {
2510 return "rom";
2511 } else if (memory_region_is_ram(mr)) {
2512 return "ram";
2513 } else {
2514 return "i/o";
2515 }
2516 }
2517
2518 typedef struct MemoryRegionList MemoryRegionList;
2519
2520 struct MemoryRegionList {
2521 const MemoryRegion *mr;
2522 QTAILQ_ENTRY(MemoryRegionList) queue;
2523 };
2524
2525 typedef QTAILQ_HEAD(queue, MemoryRegionList) MemoryRegionListHead;
2526
2527 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
2528 int128_sub((size), int128_one())) : 0)
2529 #define MTREE_INDENT " "
2530
2531 static void mtree_print_mr(fprintf_function mon_printf, void *f,
2532 const MemoryRegion *mr, unsigned int level,
2533 hwaddr base,
2534 MemoryRegionListHead *alias_print_queue)
2535 {
2536 MemoryRegionList *new_ml, *ml, *next_ml;
2537 MemoryRegionListHead submr_print_queue;
2538 const MemoryRegion *submr;
2539 unsigned int i;
2540 hwaddr cur_start, cur_end;
2541
2542 if (!mr) {
2543 return;
2544 }
2545
2546 for (i = 0; i < level; i++) {
2547 mon_printf(f, MTREE_INDENT);
2548 }
2549
2550 cur_start = base + mr->addr;
2551 cur_end = cur_start + MR_SIZE(mr->size);
2552
2553 /*
2554 * Try to detect overflow of memory region. This should never
2555 * happen normally. When it happens, we dump something to warn the
2556 * user who is observing this.
2557 */
2558 if (cur_start < base || cur_end < cur_start) {
2559 mon_printf(f, "[DETECTED OVERFLOW!] ");
2560 }
2561
2562 if (mr->alias) {
2563 MemoryRegionList *ml;
2564 bool found = false;
2565
2566 /* check if the alias is already in the queue */
2567 QTAILQ_FOREACH(ml, alias_print_queue, queue) {
2568 if (ml->mr == mr->alias) {
2569 found = true;
2570 }
2571 }
2572
2573 if (!found) {
2574 ml = g_new(MemoryRegionList, 1);
2575 ml->mr = mr->alias;
2576 QTAILQ_INSERT_TAIL(alias_print_queue, ml, queue);
2577 }
2578 mon_printf(f, TARGET_FMT_plx "-" TARGET_FMT_plx
2579 " (prio %d, %s): alias %s @%s " TARGET_FMT_plx
2580 "-" TARGET_FMT_plx "%s\n",
2581 cur_start, cur_end,
2582 mr->priority,
2583 memory_region_type((MemoryRegion *)mr),
2584 memory_region_name(mr),
2585 memory_region_name(mr->alias),
2586 mr->alias_offset,
2587 mr->alias_offset + MR_SIZE(mr->size),
2588 mr->enabled ? "" : " [disabled]");
2589 } else {
2590 mon_printf(f,
2591 TARGET_FMT_plx "-" TARGET_FMT_plx " (prio %d, %s): %s%s\n",
2592 cur_start, cur_end,
2593 mr->priority,
2594 memory_region_type((MemoryRegion *)mr),
2595 memory_region_name(mr),
2596 mr->enabled ? "" : " [disabled]");
2597 }
2598
2599 QTAILQ_INIT(&submr_print_queue);
2600
2601 QTAILQ_FOREACH(submr, &mr->subregions, subregions_link) {
2602 new_ml = g_new(MemoryRegionList, 1);
2603 new_ml->mr = submr;
2604 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2605 if (new_ml->mr->addr < ml->mr->addr ||
2606 (new_ml->mr->addr == ml->mr->addr &&
2607 new_ml->mr->priority > ml->mr->priority)) {
2608 QTAILQ_INSERT_BEFORE(ml, new_ml, queue);
2609 new_ml = NULL;
2610 break;
2611 }
2612 }
2613 if (new_ml) {
2614 QTAILQ_INSERT_TAIL(&submr_print_queue, new_ml, queue);
2615 }
2616 }
2617
2618 QTAILQ_FOREACH(ml, &submr_print_queue, queue) {
2619 mtree_print_mr(mon_printf, f, ml->mr, level + 1, cur_start,
2620 alias_print_queue);
2621 }
2622
2623 QTAILQ_FOREACH_SAFE(ml, &submr_print_queue, queue, next_ml) {
2624 g_free(ml);
2625 }
2626 }
2627
2628 static void mtree_print_flatview(fprintf_function p, void *f,
2629 AddressSpace *as)
2630 {
2631 FlatView *view = address_space_get_flatview(as);
2632 FlatRange *range = &view->ranges[0];
2633 MemoryRegion *mr;
2634 int n = view->nr;
2635
2636 if (n <= 0) {
2637 p(f, MTREE_INDENT "No rendered FlatView for "
2638 "address space '%s'\n", as->name);
2639 flatview_unref(view);
2640 return;
2641 }
2642
2643 while (n--) {
2644 mr = range->mr;
2645 if (range->offset_in_region) {
2646 p(f, MTREE_INDENT TARGET_FMT_plx "-"
2647 TARGET_FMT_plx " (prio %d, %s): %s @" TARGET_FMT_plx "\n",
2648 int128_get64(range->addr.start),
2649 int128_get64(range->addr.start) + MR_SIZE(range->addr.size),
2650 mr->priority,
2651 range->readonly ? "rom" : memory_region_type(mr),
2652 memory_region_name(mr),
2653 range->offset_in_region);
2654 } else {
2655 p(f, MTREE_INDENT TARGET_FMT_plx "-"
2656 TARGET_FMT_plx " (prio %d, %s): %s\n",
2657 int128_get64(range->addr.start),
2658 int128_get64(range->addr.start) + MR_SIZE(range->addr.size),
2659 mr->priority,
2660 range->readonly ? "rom" : memory_region_type(mr),
2661 memory_region_name(mr));
2662 }
2663 range++;
2664 }
2665
2666 flatview_unref(view);
2667 }
2668
2669 void mtree_info(fprintf_function mon_printf, void *f, bool flatview)
2670 {
2671 MemoryRegionListHead ml_head;
2672 MemoryRegionList *ml, *ml2;
2673 AddressSpace *as;
2674
2675 if (flatview) {
2676 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2677 mon_printf(f, "address-space (flat view): %s\n", as->name);
2678 mtree_print_flatview(mon_printf, f, as);
2679 mon_printf(f, "\n");
2680 }
2681 return;
2682 }
2683
2684 QTAILQ_INIT(&ml_head);
2685
2686 QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {
2687 mon_printf(f, "address-space: %s\n", as->name);
2688 mtree_print_mr(mon_printf, f, as->root, 1, 0, &ml_head);
2689 mon_printf(f, "\n");
2690 }
2691
2692 /* print aliased regions */
2693 QTAILQ_FOREACH(ml, &ml_head, queue) {
2694 mon_printf(f, "memory-region: %s\n", memory_region_name(ml->mr));
2695 mtree_print_mr(mon_printf, f, ml->mr, 1, 0, &ml_head);
2696 mon_printf(f, "\n");
2697 }
2698
2699 QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {
2700 g_free(ml);
2701 }
2702 }
2703
2704 static const TypeInfo memory_region_info = {
2705 .parent = TYPE_OBJECT,
2706 .name = TYPE_MEMORY_REGION,
2707 .instance_size = sizeof(MemoryRegion),
2708 .instance_init = memory_region_initfn,
2709 .instance_finalize = memory_region_finalize,
2710 };
2711
2712 static void memory_register_types(void)
2713 {
2714 type_register_static(&memory_region_info);
2715 }
2716
2717 type_init(memory_register_types)