xref: /qemu/system/physmem.c (revision 0d58c660689f6da1e3feff8a997014003d928b3b)
1 /*
2  * RAM allocation and memory access
3  *
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "exec/page-vary.h"
22 #include "qapi/error.h"
23 
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
26 #include "qemu/hbitmap.h"
27 #include "qemu/madvise.h"
28 
29 #ifdef CONFIG_TCG
30 #include "hw/core/tcg-cpu-ops.h"
31 #endif /* CONFIG_TCG */
32 
33 #include "exec/exec-all.h"
34 #include "exec/target_page.h"
35 #include "hw/qdev-core.h"
36 #include "hw/qdev-properties.h"
37 #include "hw/boards.h"
38 #include "hw/xen/xen.h"
39 #include "sysemu/kvm.h"
40 #include "sysemu/tcg.h"
41 #include "sysemu/qtest.h"
42 #include "qemu/timer.h"
43 #include "qemu/config-file.h"
44 #include "qemu/error-report.h"
45 #include "qemu/qemu-print.h"
46 #include "qemu/log.h"
47 #include "qemu/memalign.h"
48 #include "exec/memory.h"
49 #include "exec/ioport.h"
50 #include "sysemu/dma.h"
51 #include "sysemu/hostmem.h"
52 #include "sysemu/hw_accel.h"
53 #include "sysemu/xen-mapcache.h"
54 #include "trace/trace-root.h"
55 
56 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
57 #include <linux/falloc.h>
58 #endif
59 
60 #include "qemu/rcu_queue.h"
61 #include "qemu/main-loop.h"
62 #include "exec/translate-all.h"
63 #include "sysemu/replay.h"
64 
65 #include "exec/memory-internal.h"
66 #include "exec/ram_addr.h"
67 
68 #include "qemu/pmem.h"
69 
70 #include "migration/vmstate.h"
71 
72 #include "qemu/range.h"
73 #ifndef _WIN32
74 #include "qemu/mmap-alloc.h"
75 #endif
76 
77 #include "monitor/monitor.h"
78 
79 #ifdef CONFIG_LIBDAXCTL
80 #include <daxctl/libdaxctl.h>
81 #endif
82 
83 //#define DEBUG_SUBPAGE
84 
85 /* ram_list is read under rcu_read_lock()/rcu_read_unlock().  Writes
86  * are protected by the ramlist lock.
87  */
88 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
89 
90 static MemoryRegion *system_memory;
91 static MemoryRegion *system_io;
92 
93 AddressSpace address_space_io;
94 AddressSpace address_space_memory;
95 
96 static MemoryRegion io_mem_unassigned;
97 
98 typedef struct PhysPageEntry PhysPageEntry;
99 
100 struct PhysPageEntry {
101     /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
102     uint32_t skip : 6;
103      /* index into phys_sections (!skip) or phys_map_nodes (skip) */
104     uint32_t ptr : 26;
105 };
106 
107 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
108 
109 /* Size of the L2 (and L3, etc) page tables.  */
110 #define ADDR_SPACE_BITS 64
111 
112 #define P_L2_BITS 9
113 #define P_L2_SIZE (1 << P_L2_BITS)
114 
115 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
116 
117 typedef PhysPageEntry Node[P_L2_SIZE];
118 
119 typedef struct PhysPageMap {
120     struct rcu_head rcu;
121 
122     unsigned sections_nb;
123     unsigned sections_nb_alloc;
124     unsigned nodes_nb;
125     unsigned nodes_nb_alloc;
126     Node *nodes;
127     MemoryRegionSection *sections;
128 } PhysPageMap;
129 
130 struct AddressSpaceDispatch {
131     MemoryRegionSection *mru_section;
132     /* This is a multi-level map on the physical address space.
133      * The bottom level has pointers to MemoryRegionSections.
134      */
135     PhysPageEntry phys_map;
136     PhysPageMap map;
137 };
138 
139 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
140 typedef struct subpage_t {
141     MemoryRegion iomem;
142     FlatView *fv;
143     hwaddr base;
144     uint16_t sub_section[];
145 } subpage_t;
146 
147 #define PHYS_SECTION_UNASSIGNED 0
148 
149 static void io_mem_init(void);
150 static void memory_map_init(void);
151 static void tcg_log_global_after_sync(MemoryListener *listener);
152 static void tcg_commit(MemoryListener *listener);
153 
154 /**
155  * CPUAddressSpace: all the information a CPU needs about an AddressSpace
156  * @cpu: the CPU whose AddressSpace this is
157  * @as: the AddressSpace itself
158  * @memory_dispatch: its dispatch pointer (cached, RCU protected)
159  * @tcg_as_listener: listener for tracking changes to the AddressSpace
160  */
161 struct CPUAddressSpace {
162     CPUState *cpu;
163     AddressSpace *as;
164     struct AddressSpaceDispatch *memory_dispatch;
165     MemoryListener tcg_as_listener;
166 };
167 
168 struct DirtyBitmapSnapshot {
169     ram_addr_t start;
170     ram_addr_t end;
171     unsigned long dirty[];
172 };
173 
174 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
175 {
176     static unsigned alloc_hint = 16;
177     if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
178         map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
179         map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
180         alloc_hint = map->nodes_nb_alloc;
181     }
182 }
183 
184 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
185 {
186     unsigned i;
187     uint32_t ret;
188     PhysPageEntry e;
189     PhysPageEntry *p;
190 
191     ret = map->nodes_nb++;
192     p = map->nodes[ret];
193     assert(ret != PHYS_MAP_NODE_NIL);
194     assert(ret != map->nodes_nb_alloc);
195 
196     e.skip = leaf ? 0 : 1;
197     e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
198     for (i = 0; i < P_L2_SIZE; ++i) {
199         memcpy(&p[i], &e, sizeof(e));
200     }
201     return ret;
202 }
203 
204 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
205                                 hwaddr *index, uint64_t *nb, uint16_t leaf,
206                                 int level)
207 {
208     PhysPageEntry *p;
209     hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
210 
211     if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
212         lp->ptr = phys_map_node_alloc(map, level == 0);
213     }
214     p = map->nodes[lp->ptr];
215     lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
216 
217     while (*nb && lp < &p[P_L2_SIZE]) {
218         if ((*index & (step - 1)) == 0 && *nb >= step) {
219             lp->skip = 0;
220             lp->ptr = leaf;
221             *index += step;
222             *nb -= step;
223         } else {
224             phys_page_set_level(map, lp, index, nb, leaf, level - 1);
225         }
226         ++lp;
227     }
228 }
229 
230 static void phys_page_set(AddressSpaceDispatch *d,
231                           hwaddr index, uint64_t nb,
232                           uint16_t leaf)
233 {
234     /* Wildly overreserve - it doesn't matter much. */
235     phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
236 
237     phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
238 }
239 
240 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
241  * and update our entry so we can skip it and go directly to the destination.
242  */
243 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
244 {
245     unsigned valid_ptr = P_L2_SIZE;
246     int valid = 0;
247     PhysPageEntry *p;
248     int i;
249 
250     if (lp->ptr == PHYS_MAP_NODE_NIL) {
251         return;
252     }
253 
254     p = nodes[lp->ptr];
255     for (i = 0; i < P_L2_SIZE; i++) {
256         if (p[i].ptr == PHYS_MAP_NODE_NIL) {
257             continue;
258         }
259 
260         valid_ptr = i;
261         valid++;
262         if (p[i].skip) {
263             phys_page_compact(&p[i], nodes);
264         }
265     }
266 
267     /* We can only compress if there's only one child. */
268     if (valid != 1) {
269         return;
270     }
271 
272     assert(valid_ptr < P_L2_SIZE);
273 
274     /* Don't compress if it won't fit in the # of bits we have. */
275     if (P_L2_LEVELS >= (1 << 6) &&
276         lp->skip + p[valid_ptr].skip >= (1 << 6)) {
277         return;
278     }
279 
280     lp->ptr = p[valid_ptr].ptr;
281     if (!p[valid_ptr].skip) {
282         /* If our only child is a leaf, make this a leaf. */
283         /* By design, we should have made this node a leaf to begin with so we
284          * should never reach here.
285          * But since it's so simple to handle this, let's do it just in case we
286          * change this rule.
287          */
288         lp->skip = 0;
289     } else {
290         lp->skip += p[valid_ptr].skip;
291     }
292 }
293 
294 void address_space_dispatch_compact(AddressSpaceDispatch *d)
295 {
296     if (d->phys_map.skip) {
297         phys_page_compact(&d->phys_map, d->map.nodes);
298     }
299 }
300 
301 static inline bool section_covers_addr(const MemoryRegionSection *section,
302                                        hwaddr addr)
303 {
304     /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
305      * the section must cover the entire address space.
306      */
307     return int128_gethi(section->size) ||
308            range_covers_byte(section->offset_within_address_space,
309                              int128_getlo(section->size), addr);
310 }
311 
312 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
313 {
314     PhysPageEntry lp = d->phys_map, *p;
315     Node *nodes = d->map.nodes;
316     MemoryRegionSection *sections = d->map.sections;
317     hwaddr index = addr >> TARGET_PAGE_BITS;
318     int i;
319 
320     for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
321         if (lp.ptr == PHYS_MAP_NODE_NIL) {
322             return &sections[PHYS_SECTION_UNASSIGNED];
323         }
324         p = nodes[lp.ptr];
325         lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
326     }
327 
328     if (section_covers_addr(&sections[lp.ptr], addr)) {
329         return &sections[lp.ptr];
330     } else {
331         return &sections[PHYS_SECTION_UNASSIGNED];
332     }
333 }
334 
335 /* Called from RCU critical section */
336 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
337                                                         hwaddr addr,
338                                                         bool resolve_subpage)
339 {
340     MemoryRegionSection *section = qatomic_read(&d->mru_section);
341     subpage_t *subpage;
342 
343     if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
344         !section_covers_addr(section, addr)) {
345         section = phys_page_find(d, addr);
346         qatomic_set(&d->mru_section, section);
347     }
348     if (resolve_subpage && section->mr->subpage) {
349         subpage = container_of(section->mr, subpage_t, iomem);
350         section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
351     }
352     return section;
353 }
354 
355 /* Called from RCU critical section */
356 static MemoryRegionSection *
357 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
358                                  hwaddr *plen, bool resolve_subpage)
359 {
360     MemoryRegionSection *section;
361     MemoryRegion *mr;
362     Int128 diff;
363 
364     section = address_space_lookup_region(d, addr, resolve_subpage);
365     /* Compute offset within MemoryRegionSection */
366     addr -= section->offset_within_address_space;
367 
368     /* Compute offset within MemoryRegion */
369     *xlat = addr + section->offset_within_region;
370 
371     mr = section->mr;
372 
373     /* MMIO registers can be expected to perform full-width accesses based only
374      * on their address, without considering adjacent registers that could
375      * decode to completely different MemoryRegions.  When such registers
376      * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
377      * regions overlap wildly.  For this reason we cannot clamp the accesses
378      * here.
379      *
380      * If the length is small (as is the case for address_space_ldl/stl),
381      * everything works fine.  If the incoming length is large, however,
382      * the caller really has to do the clamping through memory_access_size.
383      */
384     if (memory_region_is_ram(mr)) {
385         diff = int128_sub(section->size, int128_make64(addr));
386         *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
387     }
388     return section;
389 }
390 
391 /**
392  * address_space_translate_iommu - translate an address through an IOMMU
393  * memory region and then through the target address space.
394  *
395  * @iommu_mr: the IOMMU memory region that we start the translation from
396  * @addr: the address to be translated through the MMU
397  * @xlat: the translated address offset within the destination memory region.
398  *        It cannot be %NULL.
399  * @plen_out: valid read/write length of the translated address. It
400  *            cannot be %NULL.
401  * @page_mask_out: page mask for the translated address. This
402  *            should only be meaningful for IOMMU translated
403  *            addresses, since there may be huge pages that this bit
404  *            would tell. It can be %NULL if we don't care about it.
405  * @is_write: whether the translation operation is for write
406  * @is_mmio: whether this can be MMIO, set true if it can
407  * @target_as: the address space targeted by the IOMMU
408  * @attrs: transaction attributes
409  *
410  * This function is called from RCU critical section.  It is the common
411  * part of flatview_do_translate and address_space_translate_cached.
412  */
413 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
414                                                          hwaddr *xlat,
415                                                          hwaddr *plen_out,
416                                                          hwaddr *page_mask_out,
417                                                          bool is_write,
418                                                          bool is_mmio,
419                                                          AddressSpace **target_as,
420                                                          MemTxAttrs attrs)
421 {
422     MemoryRegionSection *section;
423     hwaddr page_mask = (hwaddr)-1;
424 
425     do {
426         hwaddr addr = *xlat;
427         IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
428         int iommu_idx = 0;
429         IOMMUTLBEntry iotlb;
430 
431         if (imrc->attrs_to_index) {
432             iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
433         }
434 
435         iotlb = imrc->translate(iommu_mr, addr, is_write ?
436                                 IOMMU_WO : IOMMU_RO, iommu_idx);
437 
438         if (!(iotlb.perm & (1 << is_write))) {
439             goto unassigned;
440         }
441 
442         addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
443                 | (addr & iotlb.addr_mask));
444         page_mask &= iotlb.addr_mask;
445         *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
446         *target_as = iotlb.target_as;
447 
448         section = address_space_translate_internal(
449                 address_space_to_dispatch(iotlb.target_as), addr, xlat,
450                 plen_out, is_mmio);
451 
452         iommu_mr = memory_region_get_iommu(section->mr);
453     } while (unlikely(iommu_mr));
454 
455     if (page_mask_out) {
456         *page_mask_out = page_mask;
457     }
458     return *section;
459 
460 unassigned:
461     return (MemoryRegionSection) { .mr = &io_mem_unassigned };
462 }
463 
464 /**
465  * flatview_do_translate - translate an address in FlatView
466  *
467  * @fv: the flat view that we want to translate on
468  * @addr: the address to be translated in above address space
469  * @xlat: the translated address offset within memory region. It
470  *        cannot be @NULL.
471  * @plen_out: valid read/write length of the translated address. It
472  *            can be @NULL when we don't care about it.
473  * @page_mask_out: page mask for the translated address. This
474  *            should only be meaningful for IOMMU translated
475  *            addresses, since there may be huge pages that this bit
476  *            would tell. It can be @NULL if we don't care about it.
477  * @is_write: whether the translation operation is for write
478  * @is_mmio: whether this can be MMIO, set true if it can
479  * @target_as: the address space targeted by the IOMMU
480  * @attrs: memory transaction attributes
481  *
482  * This function is called from RCU critical section
483  */
484 static MemoryRegionSection flatview_do_translate(FlatView *fv,
485                                                  hwaddr addr,
486                                                  hwaddr *xlat,
487                                                  hwaddr *plen_out,
488                                                  hwaddr *page_mask_out,
489                                                  bool is_write,
490                                                  bool is_mmio,
491                                                  AddressSpace **target_as,
492                                                  MemTxAttrs attrs)
493 {
494     MemoryRegionSection *section;
495     IOMMUMemoryRegion *iommu_mr;
496     hwaddr plen = (hwaddr)(-1);
497 
498     if (!plen_out) {
499         plen_out = &plen;
500     }
501 
502     section = address_space_translate_internal(
503             flatview_to_dispatch(fv), addr, xlat,
504             plen_out, is_mmio);
505 
506     iommu_mr = memory_region_get_iommu(section->mr);
507     if (unlikely(iommu_mr)) {
508         return address_space_translate_iommu(iommu_mr, xlat,
509                                              plen_out, page_mask_out,
510                                              is_write, is_mmio,
511                                              target_as, attrs);
512     }
513     if (page_mask_out) {
514         /* Not behind an IOMMU, use default page size. */
515         *page_mask_out = ~TARGET_PAGE_MASK;
516     }
517 
518     return *section;
519 }
520 
521 /* Called from RCU critical section */
522 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
523                                             bool is_write, MemTxAttrs attrs)
524 {
525     MemoryRegionSection section;
526     hwaddr xlat, page_mask;
527 
528     /*
529      * This can never be MMIO, and we don't really care about plen,
530      * but page mask.
531      */
532     section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
533                                     NULL, &page_mask, is_write, false, &as,
534                                     attrs);
535 
536     /* Illegal translation */
537     if (section.mr == &io_mem_unassigned) {
538         goto iotlb_fail;
539     }
540 
541     /* Convert memory region offset into address space offset */
542     xlat += section.offset_within_address_space -
543         section.offset_within_region;
544 
545     return (IOMMUTLBEntry) {
546         .target_as = as,
547         .iova = addr & ~page_mask,
548         .translated_addr = xlat & ~page_mask,
549         .addr_mask = page_mask,
550         /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
551         .perm = IOMMU_RW,
552     };
553 
554 iotlb_fail:
555     return (IOMMUTLBEntry) {0};
556 }
557 
558 /* Called from RCU critical section */
559 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
560                                  hwaddr *plen, bool is_write,
561                                  MemTxAttrs attrs)
562 {
563     MemoryRegion *mr;
564     MemoryRegionSection section;
565     AddressSpace *as = NULL;
566 
567     /* This can be MMIO, so setup MMIO bit. */
568     section = flatview_do_translate(fv, addr, xlat, plen, NULL,
569                                     is_write, true, &as, attrs);
570     mr = section.mr;
571 
572     if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
573         hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
574         *plen = MIN(page, *plen);
575     }
576 
577     return mr;
578 }
579 
580 typedef struct TCGIOMMUNotifier {
581     IOMMUNotifier n;
582     MemoryRegion *mr;
583     CPUState *cpu;
584     int iommu_idx;
585     bool active;
586 } TCGIOMMUNotifier;
587 
588 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
589 {
590     TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
591 
592     if (!notifier->active) {
593         return;
594     }
595     tlb_flush(notifier->cpu);
596     notifier->active = false;
597     /* We leave the notifier struct on the list to avoid reallocating it later.
598      * Generally the number of IOMMUs a CPU deals with will be small.
599      * In any case we can't unregister the iommu notifier from a notify
600      * callback.
601      */
602 }
603 
604 static void tcg_register_iommu_notifier(CPUState *cpu,
605                                         IOMMUMemoryRegion *iommu_mr,
606                                         int iommu_idx)
607 {
608     /* Make sure this CPU has an IOMMU notifier registered for this
609      * IOMMU/IOMMU index combination, so that we can flush its TLB
610      * when the IOMMU tells us the mappings we've cached have changed.
611      */
612     MemoryRegion *mr = MEMORY_REGION(iommu_mr);
613     TCGIOMMUNotifier *notifier = NULL;
614     int i;
615 
616     for (i = 0; i < cpu->iommu_notifiers->len; i++) {
617         notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
618         if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
619             break;
620         }
621     }
622     if (i == cpu->iommu_notifiers->len) {
623         /* Not found, add a new entry at the end of the array */
624         cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
625         notifier = g_new0(TCGIOMMUNotifier, 1);
626         g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
627 
628         notifier->mr = mr;
629         notifier->iommu_idx = iommu_idx;
630         notifier->cpu = cpu;
631         /* Rather than trying to register interest in the specific part
632          * of the iommu's address space that we've accessed and then
633          * expand it later as subsequent accesses touch more of it, we
634          * just register interest in the whole thing, on the assumption
635          * that iommu reconfiguration will be rare.
636          */
637         iommu_notifier_init(&notifier->n,
638                             tcg_iommu_unmap_notify,
639                             IOMMU_NOTIFIER_UNMAP,
640                             0,
641                             HWADDR_MAX,
642                             iommu_idx);
643         memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
644                                               &error_fatal);
645     }
646 
647     if (!notifier->active) {
648         notifier->active = true;
649     }
650 }
651 
652 void tcg_iommu_free_notifier_list(CPUState *cpu)
653 {
654     /* Destroy the CPU's notifier list */
655     int i;
656     TCGIOMMUNotifier *notifier;
657 
658     for (i = 0; i < cpu->iommu_notifiers->len; i++) {
659         notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
660         memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
661         g_free(notifier);
662     }
663     g_array_free(cpu->iommu_notifiers, true);
664 }
665 
666 void tcg_iommu_init_notifier_list(CPUState *cpu)
667 {
668     cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
669 }
670 
671 /* Called from RCU critical section */
672 MemoryRegionSection *
673 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,
674                                   hwaddr *xlat, hwaddr *plen,
675                                   MemTxAttrs attrs, int *prot)
676 {
677     MemoryRegionSection *section;
678     IOMMUMemoryRegion *iommu_mr;
679     IOMMUMemoryRegionClass *imrc;
680     IOMMUTLBEntry iotlb;
681     int iommu_idx;
682     hwaddr addr = orig_addr;
683     AddressSpaceDispatch *d = cpu->cpu_ases[asidx].memory_dispatch;
684 
685     for (;;) {
686         section = address_space_translate_internal(d, addr, &addr, plen, false);
687 
688         iommu_mr = memory_region_get_iommu(section->mr);
689         if (!iommu_mr) {
690             break;
691         }
692 
693         imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
694 
695         iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
696         tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
697         /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
698          * doesn't short-cut its translation table walk.
699          */
700         iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
701         addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
702                 | (addr & iotlb.addr_mask));
703         /* Update the caller's prot bits to remove permissions the IOMMU
704          * is giving us a failure response for. If we get down to no
705          * permissions left at all we can give up now.
706          */
707         if (!(iotlb.perm & IOMMU_RO)) {
708             *prot &= ~(PAGE_READ | PAGE_EXEC);
709         }
710         if (!(iotlb.perm & IOMMU_WO)) {
711             *prot &= ~PAGE_WRITE;
712         }
713 
714         if (!*prot) {
715             goto translate_fail;
716         }
717 
718         d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
719     }
720 
721     assert(!memory_region_is_iommu(section->mr));
722     *xlat = addr;
723     return section;
724 
725 translate_fail:
726     /*
727      * We should be given a page-aligned address -- certainly
728      * tlb_set_page_with_attrs() does so.  The page offset of xlat
729      * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.
730      * The page portion of xlat will be logged by memory_region_access_valid()
731      * when this memory access is rejected, so use the original untranslated
732      * physical address.
733      */
734     assert((orig_addr & ~TARGET_PAGE_MASK) == 0);
735     *xlat = orig_addr;
736     return &d->map.sections[PHYS_SECTION_UNASSIGNED];
737 }
738 
739 void cpu_address_space_init(CPUState *cpu, int asidx,
740                             const char *prefix, MemoryRegion *mr)
741 {
742     CPUAddressSpace *newas;
743     AddressSpace *as = g_new0(AddressSpace, 1);
744     char *as_name;
745 
746     assert(mr);
747     as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
748     address_space_init(as, mr, as_name);
749     g_free(as_name);
750 
751     /* Target code should have set num_ases before calling us */
752     assert(asidx < cpu->num_ases);
753 
754     if (asidx == 0) {
755         /* address space 0 gets the convenience alias */
756         cpu->as = as;
757     }
758 
759     /* KVM cannot currently support multiple address spaces. */
760     assert(asidx == 0 || !kvm_enabled());
761 
762     if (!cpu->cpu_ases) {
763         cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
764     }
765 
766     newas = &cpu->cpu_ases[asidx];
767     newas->cpu = cpu;
768     newas->as = as;
769     if (tcg_enabled()) {
770         newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
771         newas->tcg_as_listener.commit = tcg_commit;
772         newas->tcg_as_listener.name = "tcg";
773         memory_listener_register(&newas->tcg_as_listener, as);
774     }
775 }
776 
777 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
778 {
779     /* Return the AddressSpace corresponding to the specified index */
780     return cpu->cpu_ases[asidx].as;
781 }
782 
783 /* Called from RCU critical section */
784 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
785 {
786     RAMBlock *block;
787 
788     block = qatomic_rcu_read(&ram_list.mru_block);
789     if (block && addr - block->offset < block->max_length) {
790         return block;
791     }
792     RAMBLOCK_FOREACH(block) {
793         if (addr - block->offset < block->max_length) {
794             goto found;
795         }
796     }
797 
798     fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
799     abort();
800 
801 found:
802     /* It is safe to write mru_block outside the iothread lock.  This
803      * is what happens:
804      *
805      *     mru_block = xxx
806      *     rcu_read_unlock()
807      *                                        xxx removed from list
808      *                  rcu_read_lock()
809      *                  read mru_block
810      *                                        mru_block = NULL;
811      *                                        call_rcu(reclaim_ramblock, xxx);
812      *                  rcu_read_unlock()
813      *
814      * qatomic_rcu_set is not needed here.  The block was already published
815      * when it was placed into the list.  Here we're just making an extra
816      * copy of the pointer.
817      */
818     ram_list.mru_block = block;
819     return block;
820 }
821 
822 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
823 {
824     CPUState *cpu;
825     ram_addr_t start1;
826     RAMBlock *block;
827     ram_addr_t end;
828 
829     assert(tcg_enabled());
830     end = TARGET_PAGE_ALIGN(start + length);
831     start &= TARGET_PAGE_MASK;
832 
833     RCU_READ_LOCK_GUARD();
834     block = qemu_get_ram_block(start);
835     assert(block == qemu_get_ram_block(end - 1));
836     start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
837     CPU_FOREACH(cpu) {
838         tlb_reset_dirty(cpu, start1, length);
839     }
840 }
841 
842 /* Note: start and end must be within the same ram block.  */
843 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
844                                               ram_addr_t length,
845                                               unsigned client)
846 {
847     DirtyMemoryBlocks *blocks;
848     unsigned long end, page, start_page;
849     bool dirty = false;
850     RAMBlock *ramblock;
851     uint64_t mr_offset, mr_size;
852 
853     if (length == 0) {
854         return false;
855     }
856 
857     end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
858     start_page = start >> TARGET_PAGE_BITS;
859     page = start_page;
860 
861     WITH_RCU_READ_LOCK_GUARD() {
862         blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
863         ramblock = qemu_get_ram_block(start);
864         /* Range sanity check on the ramblock */
865         assert(start >= ramblock->offset &&
866                start + length <= ramblock->offset + ramblock->used_length);
867 
868         while (page < end) {
869             unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
870             unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
871             unsigned long num = MIN(end - page,
872                                     DIRTY_MEMORY_BLOCK_SIZE - offset);
873 
874             dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
875                                                   offset, num);
876             page += num;
877         }
878 
879         mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
880         mr_size = (end - start_page) << TARGET_PAGE_BITS;
881         memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
882     }
883 
884     if (dirty && tcg_enabled()) {
885         tlb_reset_dirty_range_all(start, length);
886     }
887 
888     return dirty;
889 }
890 
891 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
892     (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
893 {
894     DirtyMemoryBlocks *blocks;
895     ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
896     unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
897     ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
898     ram_addr_t last  = QEMU_ALIGN_UP(start + length, align);
899     DirtyBitmapSnapshot *snap;
900     unsigned long page, end, dest;
901 
902     snap = g_malloc0(sizeof(*snap) +
903                      ((last - first) >> (TARGET_PAGE_BITS + 3)));
904     snap->start = first;
905     snap->end   = last;
906 
907     page = first >> TARGET_PAGE_BITS;
908     end  = last  >> TARGET_PAGE_BITS;
909     dest = 0;
910 
911     WITH_RCU_READ_LOCK_GUARD() {
912         blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
913 
914         while (page < end) {
915             unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
916             unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
917             unsigned long num = MIN(end - page,
918                                     DIRTY_MEMORY_BLOCK_SIZE - offset);
919 
920             assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
921             assert(QEMU_IS_ALIGNED(num,    (1 << BITS_PER_LEVEL)));
922             offset >>= BITS_PER_LEVEL;
923 
924             bitmap_copy_and_clear_atomic(snap->dirty + dest,
925                                          blocks->blocks[idx] + offset,
926                                          num);
927             page += num;
928             dest += num >> BITS_PER_LEVEL;
929         }
930     }
931 
932     if (tcg_enabled()) {
933         tlb_reset_dirty_range_all(start, length);
934     }
935 
936     memory_region_clear_dirty_bitmap(mr, offset, length);
937 
938     return snap;
939 }
940 
941 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
942                                             ram_addr_t start,
943                                             ram_addr_t length)
944 {
945     unsigned long page, end;
946 
947     assert(start >= snap->start);
948     assert(start + length <= snap->end);
949 
950     end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
951     page = (start - snap->start) >> TARGET_PAGE_BITS;
952 
953     while (page < end) {
954         if (test_bit(page, snap->dirty)) {
955             return true;
956         }
957         page++;
958     }
959     return false;
960 }
961 
962 /* Called from RCU critical section */
963 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
964                                        MemoryRegionSection *section)
965 {
966     AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
967     return section - d->map.sections;
968 }
969 
970 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
971                             uint16_t section);
972 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
973 
974 static uint16_t phys_section_add(PhysPageMap *map,
975                                  MemoryRegionSection *section)
976 {
977     /* The physical section number is ORed with a page-aligned
978      * pointer to produce the iotlb entries.  Thus it should
979      * never overflow into the page-aligned value.
980      */
981     assert(map->sections_nb < TARGET_PAGE_SIZE);
982 
983     if (map->sections_nb == map->sections_nb_alloc) {
984         map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
985         map->sections = g_renew(MemoryRegionSection, map->sections,
986                                 map->sections_nb_alloc);
987     }
988     map->sections[map->sections_nb] = *section;
989     memory_region_ref(section->mr);
990     return map->sections_nb++;
991 }
992 
993 static void phys_section_destroy(MemoryRegion *mr)
994 {
995     bool have_sub_page = mr->subpage;
996 
997     memory_region_unref(mr);
998 
999     if (have_sub_page) {
1000         subpage_t *subpage = container_of(mr, subpage_t, iomem);
1001         object_unref(OBJECT(&subpage->iomem));
1002         g_free(subpage);
1003     }
1004 }
1005 
1006 static void phys_sections_free(PhysPageMap *map)
1007 {
1008     while (map->sections_nb > 0) {
1009         MemoryRegionSection *section = &map->sections[--map->sections_nb];
1010         phys_section_destroy(section->mr);
1011     }
1012     g_free(map->sections);
1013     g_free(map->nodes);
1014 }
1015 
1016 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1017 {
1018     AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1019     subpage_t *subpage;
1020     hwaddr base = section->offset_within_address_space
1021         & TARGET_PAGE_MASK;
1022     MemoryRegionSection *existing = phys_page_find(d, base);
1023     MemoryRegionSection subsection = {
1024         .offset_within_address_space = base,
1025         .size = int128_make64(TARGET_PAGE_SIZE),
1026     };
1027     hwaddr start, end;
1028 
1029     assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1030 
1031     if (!(existing->mr->subpage)) {
1032         subpage = subpage_init(fv, base);
1033         subsection.fv = fv;
1034         subsection.mr = &subpage->iomem;
1035         phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1036                       phys_section_add(&d->map, &subsection));
1037     } else {
1038         subpage = container_of(existing->mr, subpage_t, iomem);
1039     }
1040     start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1041     end = start + int128_get64(section->size) - 1;
1042     subpage_register(subpage, start, end,
1043                      phys_section_add(&d->map, section));
1044 }
1045 
1046 
1047 static void register_multipage(FlatView *fv,
1048                                MemoryRegionSection *section)
1049 {
1050     AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1051     hwaddr start_addr = section->offset_within_address_space;
1052     uint16_t section_index = phys_section_add(&d->map, section);
1053     uint64_t num_pages = int128_get64(int128_rshift(section->size,
1054                                                     TARGET_PAGE_BITS));
1055 
1056     assert(num_pages);
1057     phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1058 }
1059 
1060 /*
1061  * The range in *section* may look like this:
1062  *
1063  *      |s|PPPPPPP|s|
1064  *
1065  * where s stands for subpage and P for page.
1066  */
1067 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1068 {
1069     MemoryRegionSection remain = *section;
1070     Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1071 
1072     /* register first subpage */
1073     if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1074         uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1075                         - remain.offset_within_address_space;
1076 
1077         MemoryRegionSection now = remain;
1078         now.size = int128_min(int128_make64(left), now.size);
1079         register_subpage(fv, &now);
1080         if (int128_eq(remain.size, now.size)) {
1081             return;
1082         }
1083         remain.size = int128_sub(remain.size, now.size);
1084         remain.offset_within_address_space += int128_get64(now.size);
1085         remain.offset_within_region += int128_get64(now.size);
1086     }
1087 
1088     /* register whole pages */
1089     if (int128_ge(remain.size, page_size)) {
1090         MemoryRegionSection now = remain;
1091         now.size = int128_and(now.size, int128_neg(page_size));
1092         register_multipage(fv, &now);
1093         if (int128_eq(remain.size, now.size)) {
1094             return;
1095         }
1096         remain.size = int128_sub(remain.size, now.size);
1097         remain.offset_within_address_space += int128_get64(now.size);
1098         remain.offset_within_region += int128_get64(now.size);
1099     }
1100 
1101     /* register last subpage */
1102     register_subpage(fv, &remain);
1103 }
1104 
1105 void qemu_flush_coalesced_mmio_buffer(void)
1106 {
1107     if (kvm_enabled())
1108         kvm_flush_coalesced_mmio_buffer();
1109 }
1110 
1111 void qemu_mutex_lock_ramlist(void)
1112 {
1113     qemu_mutex_lock(&ram_list.mutex);
1114 }
1115 
1116 void qemu_mutex_unlock_ramlist(void)
1117 {
1118     qemu_mutex_unlock(&ram_list.mutex);
1119 }
1120 
1121 GString *ram_block_format(void)
1122 {
1123     RAMBlock *block;
1124     char *psize;
1125     GString *buf = g_string_new("");
1126 
1127     RCU_READ_LOCK_GUARD();
1128     g_string_append_printf(buf, "%24s %8s  %18s %18s %18s %18s %3s\n",
1129                            "Block Name", "PSize", "Offset", "Used", "Total",
1130                            "HVA", "RO");
1131 
1132     RAMBLOCK_FOREACH(block) {
1133         psize = size_to_str(block->page_size);
1134         g_string_append_printf(buf, "%24s %8s  0x%016" PRIx64 " 0x%016" PRIx64
1135                                " 0x%016" PRIx64 " 0x%016" PRIx64 " %3s\n",
1136                                block->idstr, psize,
1137                                (uint64_t)block->offset,
1138                                (uint64_t)block->used_length,
1139                                (uint64_t)block->max_length,
1140                                (uint64_t)(uintptr_t)block->host,
1141                                block->mr->readonly ? "ro" : "rw");
1142 
1143         g_free(psize);
1144     }
1145 
1146     return buf;
1147 }
1148 
1149 static int find_min_backend_pagesize(Object *obj, void *opaque)
1150 {
1151     long *hpsize_min = opaque;
1152 
1153     if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1154         HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1155         long hpsize = host_memory_backend_pagesize(backend);
1156 
1157         if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1158             *hpsize_min = hpsize;
1159         }
1160     }
1161 
1162     return 0;
1163 }
1164 
1165 static int find_max_backend_pagesize(Object *obj, void *opaque)
1166 {
1167     long *hpsize_max = opaque;
1168 
1169     if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1170         HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1171         long hpsize = host_memory_backend_pagesize(backend);
1172 
1173         if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1174             *hpsize_max = hpsize;
1175         }
1176     }
1177 
1178     return 0;
1179 }
1180 
1181 /*
1182  * TODO: We assume right now that all mapped host memory backends are
1183  * used as RAM, however some might be used for different purposes.
1184  */
1185 long qemu_minrampagesize(void)
1186 {
1187     long hpsize = LONG_MAX;
1188     Object *memdev_root = object_resolve_path("/objects", NULL);
1189 
1190     object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1191     return hpsize;
1192 }
1193 
1194 long qemu_maxrampagesize(void)
1195 {
1196     long pagesize = 0;
1197     Object *memdev_root = object_resolve_path("/objects", NULL);
1198 
1199     object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1200     return pagesize;
1201 }
1202 
1203 #ifdef CONFIG_POSIX
1204 static int64_t get_file_size(int fd)
1205 {
1206     int64_t size;
1207 #if defined(__linux__)
1208     struct stat st;
1209 
1210     if (fstat(fd, &st) < 0) {
1211         return -errno;
1212     }
1213 
1214     /* Special handling for devdax character devices */
1215     if (S_ISCHR(st.st_mode)) {
1216         g_autofree char *subsystem_path = NULL;
1217         g_autofree char *subsystem = NULL;
1218 
1219         subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1220                                          major(st.st_rdev), minor(st.st_rdev));
1221         subsystem = g_file_read_link(subsystem_path, NULL);
1222 
1223         if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1224             g_autofree char *size_path = NULL;
1225             g_autofree char *size_str = NULL;
1226 
1227             size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1228                                     major(st.st_rdev), minor(st.st_rdev));
1229 
1230             if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1231                 return g_ascii_strtoll(size_str, NULL, 0);
1232             }
1233         }
1234     }
1235 #endif /* defined(__linux__) */
1236 
1237     /* st.st_size may be zero for special files yet lseek(2) works */
1238     size = lseek(fd, 0, SEEK_END);
1239     if (size < 0) {
1240         return -errno;
1241     }
1242     return size;
1243 }
1244 
1245 static int64_t get_file_align(int fd)
1246 {
1247     int64_t align = -1;
1248 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1249     struct stat st;
1250 
1251     if (fstat(fd, &st) < 0) {
1252         return -errno;
1253     }
1254 
1255     /* Special handling for devdax character devices */
1256     if (S_ISCHR(st.st_mode)) {
1257         g_autofree char *path = NULL;
1258         g_autofree char *rpath = NULL;
1259         struct daxctl_ctx *ctx;
1260         struct daxctl_region *region;
1261         int rc = 0;
1262 
1263         path = g_strdup_printf("/sys/dev/char/%d:%d",
1264                     major(st.st_rdev), minor(st.st_rdev));
1265         rpath = realpath(path, NULL);
1266         if (!rpath) {
1267             return -errno;
1268         }
1269 
1270         rc = daxctl_new(&ctx);
1271         if (rc) {
1272             return -1;
1273         }
1274 
1275         daxctl_region_foreach(ctx, region) {
1276             if (strstr(rpath, daxctl_region_get_path(region))) {
1277                 align = daxctl_region_get_align(region);
1278                 break;
1279             }
1280         }
1281         daxctl_unref(ctx);
1282     }
1283 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1284 
1285     return align;
1286 }
1287 
1288 static int file_ram_open(const char *path,
1289                          const char *region_name,
1290                          bool readonly,
1291                          bool *created,
1292                          Error **errp)
1293 {
1294     char *filename;
1295     char *sanitized_name;
1296     char *c;
1297     int fd = -1;
1298 
1299     *created = false;
1300     for (;;) {
1301         fd = open(path, readonly ? O_RDONLY : O_RDWR);
1302         if (fd >= 0) {
1303             /* @path names an existing file, use it */
1304             break;
1305         }
1306         if (errno == ENOENT) {
1307             /* @path names a file that doesn't exist, create it */
1308             fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1309             if (fd >= 0) {
1310                 *created = true;
1311                 break;
1312             }
1313         } else if (errno == EISDIR) {
1314             /* @path names a directory, create a file there */
1315             /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1316             sanitized_name = g_strdup(region_name);
1317             for (c = sanitized_name; *c != '\0'; c++) {
1318                 if (*c == '/') {
1319                     *c = '_';
1320                 }
1321             }
1322 
1323             filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1324                                        sanitized_name);
1325             g_free(sanitized_name);
1326 
1327             fd = mkstemp(filename);
1328             if (fd >= 0) {
1329                 unlink(filename);
1330                 g_free(filename);
1331                 break;
1332             }
1333             g_free(filename);
1334         }
1335         if (errno != EEXIST && errno != EINTR) {
1336             error_setg_errno(errp, errno,
1337                              "can't open backing store %s for guest RAM",
1338                              path);
1339             return -1;
1340         }
1341         /*
1342          * Try again on EINTR and EEXIST.  The latter happens when
1343          * something else creates the file between our two open().
1344          */
1345     }
1346 
1347     return fd;
1348 }
1349 
1350 static void *file_ram_alloc(RAMBlock *block,
1351                             ram_addr_t memory,
1352                             int fd,
1353                             bool readonly,
1354                             bool truncate,
1355                             off_t offset,
1356                             Error **errp)
1357 {
1358     uint32_t qemu_map_flags;
1359     void *area;
1360 
1361     block->page_size = qemu_fd_getpagesize(fd);
1362     if (block->mr->align % block->page_size) {
1363         error_setg(errp, "alignment 0x%" PRIx64
1364                    " must be multiples of page size 0x%zx",
1365                    block->mr->align, block->page_size);
1366         return NULL;
1367     } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1368         error_setg(errp, "alignment 0x%" PRIx64
1369                    " must be a power of two", block->mr->align);
1370         return NULL;
1371     } else if (offset % block->page_size) {
1372         error_setg(errp, "offset 0x%" PRIx64
1373                    " must be multiples of page size 0x%zx",
1374                    offset, block->page_size);
1375         return NULL;
1376     }
1377     block->mr->align = MAX(block->page_size, block->mr->align);
1378 #if defined(__s390x__)
1379     if (kvm_enabled()) {
1380         block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1381     }
1382 #endif
1383 
1384     if (memory < block->page_size) {
1385         error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1386                    "or larger than page size 0x%zx",
1387                    memory, block->page_size);
1388         return NULL;
1389     }
1390 
1391     memory = ROUND_UP(memory, block->page_size);
1392 
1393     /*
1394      * ftruncate is not supported by hugetlbfs in older
1395      * hosts, so don't bother bailing out on errors.
1396      * If anything goes wrong with it under other filesystems,
1397      * mmap will fail.
1398      *
1399      * Do not truncate the non-empty backend file to avoid corrupting
1400      * the existing data in the file. Disabling shrinking is not
1401      * enough. For example, the current vNVDIMM implementation stores
1402      * the guest NVDIMM labels at the end of the backend file. If the
1403      * backend file is later extended, QEMU will not be able to find
1404      * those labels. Therefore, extending the non-empty backend file
1405      * is disabled as well.
1406      */
1407     if (truncate && ftruncate(fd, offset + memory)) {
1408         perror("ftruncate");
1409     }
1410 
1411     qemu_map_flags = readonly ? QEMU_MAP_READONLY : 0;
1412     qemu_map_flags |= (block->flags & RAM_SHARED) ? QEMU_MAP_SHARED : 0;
1413     qemu_map_flags |= (block->flags & RAM_PMEM) ? QEMU_MAP_SYNC : 0;
1414     qemu_map_flags |= (block->flags & RAM_NORESERVE) ? QEMU_MAP_NORESERVE : 0;
1415     area = qemu_ram_mmap(fd, memory, block->mr->align, qemu_map_flags, offset);
1416     if (area == MAP_FAILED) {
1417         error_setg_errno(errp, errno,
1418                          "unable to map backing store for guest RAM");
1419         return NULL;
1420     }
1421 
1422     block->fd = fd;
1423     block->fd_offset = offset;
1424     return area;
1425 }
1426 #endif
1427 
1428 /* Allocate space within the ram_addr_t space that governs the
1429  * dirty bitmaps.
1430  * Called with the ramlist lock held.
1431  */
1432 static ram_addr_t find_ram_offset(ram_addr_t size)
1433 {
1434     RAMBlock *block, *next_block;
1435     ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1436 
1437     assert(size != 0); /* it would hand out same offset multiple times */
1438 
1439     if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1440         return 0;
1441     }
1442 
1443     RAMBLOCK_FOREACH(block) {
1444         ram_addr_t candidate, next = RAM_ADDR_MAX;
1445 
1446         /* Align blocks to start on a 'long' in the bitmap
1447          * which makes the bitmap sync'ing take the fast path.
1448          */
1449         candidate = block->offset + block->max_length;
1450         candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1451 
1452         /* Search for the closest following block
1453          * and find the gap.
1454          */
1455         RAMBLOCK_FOREACH(next_block) {
1456             if (next_block->offset >= candidate) {
1457                 next = MIN(next, next_block->offset);
1458             }
1459         }
1460 
1461         /* If it fits remember our place and remember the size
1462          * of gap, but keep going so that we might find a smaller
1463          * gap to fill so avoiding fragmentation.
1464          */
1465         if (next - candidate >= size && next - candidate < mingap) {
1466             offset = candidate;
1467             mingap = next - candidate;
1468         }
1469 
1470         trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1471     }
1472 
1473     if (offset == RAM_ADDR_MAX) {
1474         fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1475                 (uint64_t)size);
1476         abort();
1477     }
1478 
1479     trace_find_ram_offset(size, offset);
1480 
1481     return offset;
1482 }
1483 
1484 static unsigned long last_ram_page(void)
1485 {
1486     RAMBlock *block;
1487     ram_addr_t last = 0;
1488 
1489     RCU_READ_LOCK_GUARD();
1490     RAMBLOCK_FOREACH(block) {
1491         last = MAX(last, block->offset + block->max_length);
1492     }
1493     return last >> TARGET_PAGE_BITS;
1494 }
1495 
1496 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1497 {
1498     int ret;
1499 
1500     /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1501     if (!machine_dump_guest_core(current_machine)) {
1502         ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1503         if (ret) {
1504             perror("qemu_madvise");
1505             fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1506                             "but dump_guest_core=off specified\n");
1507         }
1508     }
1509 }
1510 
1511 const char *qemu_ram_get_idstr(RAMBlock *rb)
1512 {
1513     return rb->idstr;
1514 }
1515 
1516 void *qemu_ram_get_host_addr(RAMBlock *rb)
1517 {
1518     return rb->host;
1519 }
1520 
1521 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1522 {
1523     return rb->offset;
1524 }
1525 
1526 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1527 {
1528     return rb->used_length;
1529 }
1530 
1531 ram_addr_t qemu_ram_get_max_length(RAMBlock *rb)
1532 {
1533     return rb->max_length;
1534 }
1535 
1536 bool qemu_ram_is_shared(RAMBlock *rb)
1537 {
1538     return rb->flags & RAM_SHARED;
1539 }
1540 
1541 bool qemu_ram_is_noreserve(RAMBlock *rb)
1542 {
1543     return rb->flags & RAM_NORESERVE;
1544 }
1545 
1546 /* Note: Only set at the start of postcopy */
1547 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1548 {
1549     return rb->flags & RAM_UF_ZEROPAGE;
1550 }
1551 
1552 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1553 {
1554     rb->flags |= RAM_UF_ZEROPAGE;
1555 }
1556 
1557 bool qemu_ram_is_migratable(RAMBlock *rb)
1558 {
1559     return rb->flags & RAM_MIGRATABLE;
1560 }
1561 
1562 void qemu_ram_set_migratable(RAMBlock *rb)
1563 {
1564     rb->flags |= RAM_MIGRATABLE;
1565 }
1566 
1567 void qemu_ram_unset_migratable(RAMBlock *rb)
1568 {
1569     rb->flags &= ~RAM_MIGRATABLE;
1570 }
1571 
1572 bool qemu_ram_is_named_file(RAMBlock *rb)
1573 {
1574     return rb->flags & RAM_NAMED_FILE;
1575 }
1576 
1577 int qemu_ram_get_fd(RAMBlock *rb)
1578 {
1579     return rb->fd;
1580 }
1581 
1582 /* Called with iothread lock held.  */
1583 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1584 {
1585     RAMBlock *block;
1586 
1587     assert(new_block);
1588     assert(!new_block->idstr[0]);
1589 
1590     if (dev) {
1591         char *id = qdev_get_dev_path(dev);
1592         if (id) {
1593             snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1594             g_free(id);
1595         }
1596     }
1597     pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1598 
1599     RCU_READ_LOCK_GUARD();
1600     RAMBLOCK_FOREACH(block) {
1601         if (block != new_block &&
1602             !strcmp(block->idstr, new_block->idstr)) {
1603             fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1604                     new_block->idstr);
1605             abort();
1606         }
1607     }
1608 }
1609 
1610 /* Called with iothread lock held.  */
1611 void qemu_ram_unset_idstr(RAMBlock *block)
1612 {
1613     /* FIXME: arch_init.c assumes that this is not called throughout
1614      * migration.  Ignore the problem since hot-unplug during migration
1615      * does not work anyway.
1616      */
1617     if (block) {
1618         memset(block->idstr, 0, sizeof(block->idstr));
1619     }
1620 }
1621 
1622 size_t qemu_ram_pagesize(RAMBlock *rb)
1623 {
1624     return rb->page_size;
1625 }
1626 
1627 /* Returns the largest size of page in use */
1628 size_t qemu_ram_pagesize_largest(void)
1629 {
1630     RAMBlock *block;
1631     size_t largest = 0;
1632 
1633     RAMBLOCK_FOREACH(block) {
1634         largest = MAX(largest, qemu_ram_pagesize(block));
1635     }
1636 
1637     return largest;
1638 }
1639 
1640 static int memory_try_enable_merging(void *addr, size_t len)
1641 {
1642     if (!machine_mem_merge(current_machine)) {
1643         /* disabled by the user */
1644         return 0;
1645     }
1646 
1647     return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1648 }
1649 
1650 /*
1651  * Resizing RAM while migrating can result in the migration being canceled.
1652  * Care has to be taken if the guest might have already detected the memory.
1653  *
1654  * As memory core doesn't know how is memory accessed, it is up to
1655  * resize callback to update device state and/or add assertions to detect
1656  * misuse, if necessary.
1657  */
1658 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1659 {
1660     const ram_addr_t oldsize = block->used_length;
1661     const ram_addr_t unaligned_size = newsize;
1662 
1663     assert(block);
1664 
1665     newsize = HOST_PAGE_ALIGN(newsize);
1666 
1667     if (block->used_length == newsize) {
1668         /*
1669          * We don't have to resize the ram block (which only knows aligned
1670          * sizes), however, we have to notify if the unaligned size changed.
1671          */
1672         if (unaligned_size != memory_region_size(block->mr)) {
1673             memory_region_set_size(block->mr, unaligned_size);
1674             if (block->resized) {
1675                 block->resized(block->idstr, unaligned_size, block->host);
1676             }
1677         }
1678         return 0;
1679     }
1680 
1681     if (!(block->flags & RAM_RESIZEABLE)) {
1682         error_setg_errno(errp, EINVAL,
1683                          "Size mismatch: %s: 0x" RAM_ADDR_FMT
1684                          " != 0x" RAM_ADDR_FMT, block->idstr,
1685                          newsize, block->used_length);
1686         return -EINVAL;
1687     }
1688 
1689     if (block->max_length < newsize) {
1690         error_setg_errno(errp, EINVAL,
1691                          "Size too large: %s: 0x" RAM_ADDR_FMT
1692                          " > 0x" RAM_ADDR_FMT, block->idstr,
1693                          newsize, block->max_length);
1694         return -EINVAL;
1695     }
1696 
1697     /* Notify before modifying the ram block and touching the bitmaps. */
1698     if (block->host) {
1699         ram_block_notify_resize(block->host, oldsize, newsize);
1700     }
1701 
1702     cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1703     block->used_length = newsize;
1704     cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1705                                         DIRTY_CLIENTS_ALL);
1706     memory_region_set_size(block->mr, unaligned_size);
1707     if (block->resized) {
1708         block->resized(block->idstr, unaligned_size, block->host);
1709     }
1710     return 0;
1711 }
1712 
1713 /*
1714  * Trigger sync on the given ram block for range [start, start + length]
1715  * with the backing store if one is available.
1716  * Otherwise no-op.
1717  * @Note: this is supposed to be a synchronous op.
1718  */
1719 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1720 {
1721     /* The requested range should fit in within the block range */
1722     g_assert((start + length) <= block->used_length);
1723 
1724 #ifdef CONFIG_LIBPMEM
1725     /* The lack of support for pmem should not block the sync */
1726     if (ramblock_is_pmem(block)) {
1727         void *addr = ramblock_ptr(block, start);
1728         pmem_persist(addr, length);
1729         return;
1730     }
1731 #endif
1732     if (block->fd >= 0) {
1733         /**
1734          * Case there is no support for PMEM or the memory has not been
1735          * specified as persistent (or is not one) - use the msync.
1736          * Less optimal but still achieves the same goal
1737          */
1738         void *addr = ramblock_ptr(block, start);
1739         if (qemu_msync(addr, length, block->fd)) {
1740             warn_report("%s: failed to sync memory range: start: "
1741                     RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1742                     __func__, start, length);
1743         }
1744     }
1745 }
1746 
1747 /* Called with ram_list.mutex held */
1748 static void dirty_memory_extend(ram_addr_t old_ram_size,
1749                                 ram_addr_t new_ram_size)
1750 {
1751     ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1752                                              DIRTY_MEMORY_BLOCK_SIZE);
1753     ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1754                                              DIRTY_MEMORY_BLOCK_SIZE);
1755     int i;
1756 
1757     /* Only need to extend if block count increased */
1758     if (new_num_blocks <= old_num_blocks) {
1759         return;
1760     }
1761 
1762     for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1763         DirtyMemoryBlocks *old_blocks;
1764         DirtyMemoryBlocks *new_blocks;
1765         int j;
1766 
1767         old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1768         new_blocks = g_malloc(sizeof(*new_blocks) +
1769                               sizeof(new_blocks->blocks[0]) * new_num_blocks);
1770 
1771         if (old_num_blocks) {
1772             memcpy(new_blocks->blocks, old_blocks->blocks,
1773                    old_num_blocks * sizeof(old_blocks->blocks[0]));
1774         }
1775 
1776         for (j = old_num_blocks; j < new_num_blocks; j++) {
1777             new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1778         }
1779 
1780         qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1781 
1782         if (old_blocks) {
1783             g_free_rcu(old_blocks, rcu);
1784         }
1785     }
1786 }
1787 
1788 static void ram_block_add(RAMBlock *new_block, Error **errp)
1789 {
1790     const bool noreserve = qemu_ram_is_noreserve(new_block);
1791     const bool shared = qemu_ram_is_shared(new_block);
1792     RAMBlock *block;
1793     RAMBlock *last_block = NULL;
1794     ram_addr_t old_ram_size, new_ram_size;
1795     Error *err = NULL;
1796 
1797     old_ram_size = last_ram_page();
1798 
1799     qemu_mutex_lock_ramlist();
1800     new_block->offset = find_ram_offset(new_block->max_length);
1801 
1802     if (!new_block->host) {
1803         if (xen_enabled()) {
1804             xen_ram_alloc(new_block->offset, new_block->max_length,
1805                           new_block->mr, &err);
1806             if (err) {
1807                 error_propagate(errp, err);
1808                 qemu_mutex_unlock_ramlist();
1809                 return;
1810             }
1811         } else {
1812             new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1813                                                   &new_block->mr->align,
1814                                                   shared, noreserve);
1815             if (!new_block->host) {
1816                 error_setg_errno(errp, errno,
1817                                  "cannot set up guest memory '%s'",
1818                                  memory_region_name(new_block->mr));
1819                 qemu_mutex_unlock_ramlist();
1820                 return;
1821             }
1822             memory_try_enable_merging(new_block->host, new_block->max_length);
1823         }
1824     }
1825 
1826     new_ram_size = MAX(old_ram_size,
1827               (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1828     if (new_ram_size > old_ram_size) {
1829         dirty_memory_extend(old_ram_size, new_ram_size);
1830     }
1831     /* Keep the list sorted from biggest to smallest block.  Unlike QTAILQ,
1832      * QLIST (which has an RCU-friendly variant) does not have insertion at
1833      * tail, so save the last element in last_block.
1834      */
1835     RAMBLOCK_FOREACH(block) {
1836         last_block = block;
1837         if (block->max_length < new_block->max_length) {
1838             break;
1839         }
1840     }
1841     if (block) {
1842         QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1843     } else if (last_block) {
1844         QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1845     } else { /* list is empty */
1846         QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1847     }
1848     ram_list.mru_block = NULL;
1849 
1850     /* Write list before version */
1851     smp_wmb();
1852     ram_list.version++;
1853     qemu_mutex_unlock_ramlist();
1854 
1855     cpu_physical_memory_set_dirty_range(new_block->offset,
1856                                         new_block->used_length,
1857                                         DIRTY_CLIENTS_ALL);
1858 
1859     if (new_block->host) {
1860         qemu_ram_setup_dump(new_block->host, new_block->max_length);
1861         qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1862         /*
1863          * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1864          * Configure it unless the machine is a qtest server, in which case
1865          * KVM is not used and it may be forked (eg for fuzzing purposes).
1866          */
1867         if (!qtest_enabled()) {
1868             qemu_madvise(new_block->host, new_block->max_length,
1869                          QEMU_MADV_DONTFORK);
1870         }
1871         ram_block_notify_add(new_block->host, new_block->used_length,
1872                              new_block->max_length);
1873     }
1874 }
1875 
1876 #ifdef CONFIG_POSIX
1877 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
1878                                  uint32_t ram_flags, int fd, off_t offset,
1879                                  bool readonly, Error **errp)
1880 {
1881     RAMBlock *new_block;
1882     Error *local_err = NULL;
1883     int64_t file_size, file_align;
1884 
1885     /* Just support these ram flags by now. */
1886     assert((ram_flags & ~(RAM_SHARED | RAM_PMEM | RAM_NORESERVE |
1887                           RAM_PROTECTED | RAM_NAMED_FILE)) == 0);
1888 
1889     if (xen_enabled()) {
1890         error_setg(errp, "-mem-path not supported with Xen");
1891         return NULL;
1892     }
1893 
1894     if (kvm_enabled() && !kvm_has_sync_mmu()) {
1895         error_setg(errp,
1896                    "host lacks kvm mmu notifiers, -mem-path unsupported");
1897         return NULL;
1898     }
1899 
1900     size = HOST_PAGE_ALIGN(size);
1901     file_size = get_file_size(fd);
1902     if (file_size > offset && file_size < (offset + size)) {
1903         error_setg(errp, "backing store size 0x%" PRIx64
1904                    " does not match 'size' option 0x" RAM_ADDR_FMT,
1905                    file_size, size);
1906         return NULL;
1907     }
1908 
1909     file_align = get_file_align(fd);
1910     if (file_align > 0 && file_align > mr->align) {
1911         error_setg(errp, "backing store align 0x%" PRIx64
1912                    " is larger than 'align' option 0x%" PRIx64,
1913                    file_align, mr->align);
1914         return NULL;
1915     }
1916 
1917     new_block = g_malloc0(sizeof(*new_block));
1918     new_block->mr = mr;
1919     new_block->used_length = size;
1920     new_block->max_length = size;
1921     new_block->flags = ram_flags;
1922     new_block->host = file_ram_alloc(new_block, size, fd, readonly,
1923                                      !file_size, offset, errp);
1924     if (!new_block->host) {
1925         g_free(new_block);
1926         return NULL;
1927     }
1928 
1929     ram_block_add(new_block, &local_err);
1930     if (local_err) {
1931         g_free(new_block);
1932         error_propagate(errp, local_err);
1933         return NULL;
1934     }
1935     return new_block;
1936 
1937 }
1938 
1939 
1940 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
1941                                    uint32_t ram_flags, const char *mem_path,
1942                                    off_t offset, bool readonly, Error **errp)
1943 {
1944     int fd;
1945     bool created;
1946     RAMBlock *block;
1947 
1948     fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
1949                        errp);
1950     if (fd < 0) {
1951         return NULL;
1952     }
1953 
1954     block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, offset, readonly,
1955                                    errp);
1956     if (!block) {
1957         if (created) {
1958             unlink(mem_path);
1959         }
1960         close(fd);
1961         return NULL;
1962     }
1963 
1964     return block;
1965 }
1966 #endif
1967 
1968 static
1969 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
1970                                   void (*resized)(const char*,
1971                                                   uint64_t length,
1972                                                   void *host),
1973                                   void *host, uint32_t ram_flags,
1974                                   MemoryRegion *mr, Error **errp)
1975 {
1976     RAMBlock *new_block;
1977     Error *local_err = NULL;
1978 
1979     assert((ram_flags & ~(RAM_SHARED | RAM_RESIZEABLE | RAM_PREALLOC |
1980                           RAM_NORESERVE)) == 0);
1981     assert(!host ^ (ram_flags & RAM_PREALLOC));
1982 
1983     size = HOST_PAGE_ALIGN(size);
1984     max_size = HOST_PAGE_ALIGN(max_size);
1985     new_block = g_malloc0(sizeof(*new_block));
1986     new_block->mr = mr;
1987     new_block->resized = resized;
1988     new_block->used_length = size;
1989     new_block->max_length = max_size;
1990     assert(max_size >= size);
1991     new_block->fd = -1;
1992     new_block->page_size = qemu_real_host_page_size();
1993     new_block->host = host;
1994     new_block->flags = ram_flags;
1995     ram_block_add(new_block, &local_err);
1996     if (local_err) {
1997         g_free(new_block);
1998         error_propagate(errp, local_err);
1999         return NULL;
2000     }
2001     return new_block;
2002 }
2003 
2004 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2005                                    MemoryRegion *mr, Error **errp)
2006 {
2007     return qemu_ram_alloc_internal(size, size, NULL, host, RAM_PREALLOC, mr,
2008                                    errp);
2009 }
2010 
2011 RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
2012                          MemoryRegion *mr, Error **errp)
2013 {
2014     assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE)) == 0);
2015     return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
2016 }
2017 
2018 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2019                                      void (*resized)(const char*,
2020                                                      uint64_t length,
2021                                                      void *host),
2022                                      MemoryRegion *mr, Error **errp)
2023 {
2024     return qemu_ram_alloc_internal(size, maxsz, resized, NULL,
2025                                    RAM_RESIZEABLE, mr, errp);
2026 }
2027 
2028 static void reclaim_ramblock(RAMBlock *block)
2029 {
2030     if (block->flags & RAM_PREALLOC) {
2031         ;
2032     } else if (xen_enabled()) {
2033         xen_invalidate_map_cache_entry(block->host);
2034 #ifndef _WIN32
2035     } else if (block->fd >= 0) {
2036         qemu_ram_munmap(block->fd, block->host, block->max_length);
2037         close(block->fd);
2038 #endif
2039     } else {
2040         qemu_anon_ram_free(block->host, block->max_length);
2041     }
2042     g_free(block);
2043 }
2044 
2045 void qemu_ram_free(RAMBlock *block)
2046 {
2047     if (!block) {
2048         return;
2049     }
2050 
2051     if (block->host) {
2052         ram_block_notify_remove(block->host, block->used_length,
2053                                 block->max_length);
2054     }
2055 
2056     qemu_mutex_lock_ramlist();
2057     QLIST_REMOVE_RCU(block, next);
2058     ram_list.mru_block = NULL;
2059     /* Write list before version */
2060     smp_wmb();
2061     ram_list.version++;
2062     call_rcu(block, reclaim_ramblock, rcu);
2063     qemu_mutex_unlock_ramlist();
2064 }
2065 
2066 #ifndef _WIN32
2067 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2068 {
2069     RAMBlock *block;
2070     ram_addr_t offset;
2071     int flags;
2072     void *area, *vaddr;
2073 
2074     RAMBLOCK_FOREACH(block) {
2075         offset = addr - block->offset;
2076         if (offset < block->max_length) {
2077             vaddr = ramblock_ptr(block, offset);
2078             if (block->flags & RAM_PREALLOC) {
2079                 ;
2080             } else if (xen_enabled()) {
2081                 abort();
2082             } else {
2083                 flags = MAP_FIXED;
2084                 flags |= block->flags & RAM_SHARED ?
2085                          MAP_SHARED : MAP_PRIVATE;
2086                 flags |= block->flags & RAM_NORESERVE ? MAP_NORESERVE : 0;
2087                 if (block->fd >= 0) {
2088                     area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2089                                 flags, block->fd, offset + block->fd_offset);
2090                 } else {
2091                     flags |= MAP_ANONYMOUS;
2092                     area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2093                                 flags, -1, 0);
2094                 }
2095                 if (area != vaddr) {
2096                     error_report("Could not remap addr: "
2097                                  RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2098                                  length, addr);
2099                     exit(1);
2100                 }
2101                 memory_try_enable_merging(vaddr, length);
2102                 qemu_ram_setup_dump(vaddr, length);
2103             }
2104         }
2105     }
2106 }
2107 #endif /* !_WIN32 */
2108 
2109 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2110  * This should not be used for general purpose DMA.  Use address_space_map
2111  * or address_space_rw instead. For local memory (e.g. video ram) that the
2112  * device owns, use memory_region_get_ram_ptr.
2113  *
2114  * Called within RCU critical section.
2115  */
2116 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2117 {
2118     RAMBlock *block = ram_block;
2119 
2120     if (block == NULL) {
2121         block = qemu_get_ram_block(addr);
2122         addr -= block->offset;
2123     }
2124 
2125     if (xen_enabled() && block->host == NULL) {
2126         /* We need to check if the requested address is in the RAM
2127          * because we don't want to map the entire memory in QEMU.
2128          * In that case just map until the end of the page.
2129          */
2130         if (block->offset == 0) {
2131             return xen_map_cache(addr, 0, 0, false);
2132         }
2133 
2134         block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2135     }
2136     return ramblock_ptr(block, addr);
2137 }
2138 
2139 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2140  * but takes a size argument.
2141  *
2142  * Called within RCU critical section.
2143  */
2144 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2145                                  hwaddr *size, bool lock)
2146 {
2147     RAMBlock *block = ram_block;
2148     if (*size == 0) {
2149         return NULL;
2150     }
2151 
2152     if (block == NULL) {
2153         block = qemu_get_ram_block(addr);
2154         addr -= block->offset;
2155     }
2156     *size = MIN(*size, block->max_length - addr);
2157 
2158     if (xen_enabled() && block->host == NULL) {
2159         /* We need to check if the requested address is in the RAM
2160          * because we don't want to map the entire memory in QEMU.
2161          * In that case just map the requested area.
2162          */
2163         if (block->offset == 0) {
2164             return xen_map_cache(addr, *size, lock, lock);
2165         }
2166 
2167         block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2168     }
2169 
2170     return ramblock_ptr(block, addr);
2171 }
2172 
2173 /* Return the offset of a hostpointer within a ramblock */
2174 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2175 {
2176     ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2177     assert((uintptr_t)host >= (uintptr_t)rb->host);
2178     assert(res < rb->max_length);
2179 
2180     return res;
2181 }
2182 
2183 /*
2184  * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2185  * in that RAMBlock.
2186  *
2187  * ptr: Host pointer to look up
2188  * round_offset: If true round the result offset down to a page boundary
2189  * *ram_addr: set to result ram_addr
2190  * *offset: set to result offset within the RAMBlock
2191  *
2192  * Returns: RAMBlock (or NULL if not found)
2193  *
2194  * By the time this function returns, the returned pointer is not protected
2195  * by RCU anymore.  If the caller is not within an RCU critical section and
2196  * does not hold the iothread lock, it must have other means of protecting the
2197  * pointer, such as a reference to the region that includes the incoming
2198  * ram_addr_t.
2199  */
2200 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2201                                    ram_addr_t *offset)
2202 {
2203     RAMBlock *block;
2204     uint8_t *host = ptr;
2205 
2206     if (xen_enabled()) {
2207         ram_addr_t ram_addr;
2208         RCU_READ_LOCK_GUARD();
2209         ram_addr = xen_ram_addr_from_mapcache(ptr);
2210         block = qemu_get_ram_block(ram_addr);
2211         if (block) {
2212             *offset = ram_addr - block->offset;
2213         }
2214         return block;
2215     }
2216 
2217     RCU_READ_LOCK_GUARD();
2218     block = qatomic_rcu_read(&ram_list.mru_block);
2219     if (block && block->host && host - block->host < block->max_length) {
2220         goto found;
2221     }
2222 
2223     RAMBLOCK_FOREACH(block) {
2224         /* This case append when the block is not mapped. */
2225         if (block->host == NULL) {
2226             continue;
2227         }
2228         if (host - block->host < block->max_length) {
2229             goto found;
2230         }
2231     }
2232 
2233     return NULL;
2234 
2235 found:
2236     *offset = (host - block->host);
2237     if (round_offset) {
2238         *offset &= TARGET_PAGE_MASK;
2239     }
2240     return block;
2241 }
2242 
2243 /*
2244  * Finds the named RAMBlock
2245  *
2246  * name: The name of RAMBlock to find
2247  *
2248  * Returns: RAMBlock (or NULL if not found)
2249  */
2250 RAMBlock *qemu_ram_block_by_name(const char *name)
2251 {
2252     RAMBlock *block;
2253 
2254     RAMBLOCK_FOREACH(block) {
2255         if (!strcmp(name, block->idstr)) {
2256             return block;
2257         }
2258     }
2259 
2260     return NULL;
2261 }
2262 
2263 /* Some of the softmmu routines need to translate from a host pointer
2264    (typically a TLB entry) back to a ram offset.  */
2265 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2266 {
2267     RAMBlock *block;
2268     ram_addr_t offset;
2269 
2270     block = qemu_ram_block_from_host(ptr, false, &offset);
2271     if (!block) {
2272         return RAM_ADDR_INVALID;
2273     }
2274 
2275     return block->offset + offset;
2276 }
2277 
2278 ram_addr_t qemu_ram_addr_from_host_nofail(void *ptr)
2279 {
2280     ram_addr_t ram_addr;
2281 
2282     ram_addr = qemu_ram_addr_from_host(ptr);
2283     if (ram_addr == RAM_ADDR_INVALID) {
2284         error_report("Bad ram pointer %p", ptr);
2285         abort();
2286     }
2287     return ram_addr;
2288 }
2289 
2290 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2291                                  MemTxAttrs attrs, void *buf, hwaddr len);
2292 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2293                                   const void *buf, hwaddr len);
2294 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2295                                   bool is_write, MemTxAttrs attrs);
2296 
2297 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2298                                 unsigned len, MemTxAttrs attrs)
2299 {
2300     subpage_t *subpage = opaque;
2301     uint8_t buf[8];
2302     MemTxResult res;
2303 
2304 #if defined(DEBUG_SUBPAGE)
2305     printf("%s: subpage %p len %u addr " HWADDR_FMT_plx "\n", __func__,
2306            subpage, len, addr);
2307 #endif
2308     res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2309     if (res) {
2310         return res;
2311     }
2312     *data = ldn_p(buf, len);
2313     return MEMTX_OK;
2314 }
2315 
2316 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2317                                  uint64_t value, unsigned len, MemTxAttrs attrs)
2318 {
2319     subpage_t *subpage = opaque;
2320     uint8_t buf[8];
2321 
2322 #if defined(DEBUG_SUBPAGE)
2323     printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
2324            " value %"PRIx64"\n",
2325            __func__, subpage, len, addr, value);
2326 #endif
2327     stn_p(buf, len, value);
2328     return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2329 }
2330 
2331 static bool subpage_accepts(void *opaque, hwaddr addr,
2332                             unsigned len, bool is_write,
2333                             MemTxAttrs attrs)
2334 {
2335     subpage_t *subpage = opaque;
2336 #if defined(DEBUG_SUBPAGE)
2337     printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx "\n",
2338            __func__, subpage, is_write ? 'w' : 'r', len, addr);
2339 #endif
2340 
2341     return flatview_access_valid(subpage->fv, addr + subpage->base,
2342                                  len, is_write, attrs);
2343 }
2344 
2345 static const MemoryRegionOps subpage_ops = {
2346     .read_with_attrs = subpage_read,
2347     .write_with_attrs = subpage_write,
2348     .impl.min_access_size = 1,
2349     .impl.max_access_size = 8,
2350     .valid.min_access_size = 1,
2351     .valid.max_access_size = 8,
2352     .valid.accepts = subpage_accepts,
2353     .endianness = DEVICE_NATIVE_ENDIAN,
2354 };
2355 
2356 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2357                             uint16_t section)
2358 {
2359     int idx, eidx;
2360 
2361     if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2362         return -1;
2363     idx = SUBPAGE_IDX(start);
2364     eidx = SUBPAGE_IDX(end);
2365 #if defined(DEBUG_SUBPAGE)
2366     printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2367            __func__, mmio, start, end, idx, eidx, section);
2368 #endif
2369     for (; idx <= eidx; idx++) {
2370         mmio->sub_section[idx] = section;
2371     }
2372 
2373     return 0;
2374 }
2375 
2376 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2377 {
2378     subpage_t *mmio;
2379 
2380     /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2381     mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2382     mmio->fv = fv;
2383     mmio->base = base;
2384     memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2385                           NULL, TARGET_PAGE_SIZE);
2386     mmio->iomem.subpage = true;
2387 #if defined(DEBUG_SUBPAGE)
2388     printf("%s: %p base " HWADDR_FMT_plx " len %08x\n", __func__,
2389            mmio, base, TARGET_PAGE_SIZE);
2390 #endif
2391 
2392     return mmio;
2393 }
2394 
2395 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2396 {
2397     assert(fv);
2398     MemoryRegionSection section = {
2399         .fv = fv,
2400         .mr = mr,
2401         .offset_within_address_space = 0,
2402         .offset_within_region = 0,
2403         .size = int128_2_64(),
2404     };
2405 
2406     return phys_section_add(map, &section);
2407 }
2408 
2409 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2410                                       hwaddr index, MemTxAttrs attrs)
2411 {
2412     int asidx = cpu_asidx_from_attrs(cpu, attrs);
2413     CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2414     AddressSpaceDispatch *d = cpuas->memory_dispatch;
2415     int section_index = index & ~TARGET_PAGE_MASK;
2416     MemoryRegionSection *ret;
2417 
2418     assert(section_index < d->map.sections_nb);
2419     ret = d->map.sections + section_index;
2420     assert(ret->mr);
2421     assert(ret->mr->ops);
2422 
2423     return ret;
2424 }
2425 
2426 static void io_mem_init(void)
2427 {
2428     memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2429                           NULL, UINT64_MAX);
2430 }
2431 
2432 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2433 {
2434     AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2435     uint16_t n;
2436 
2437     n = dummy_section(&d->map, fv, &io_mem_unassigned);
2438     assert(n == PHYS_SECTION_UNASSIGNED);
2439 
2440     d->phys_map  = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2441 
2442     return d;
2443 }
2444 
2445 void address_space_dispatch_free(AddressSpaceDispatch *d)
2446 {
2447     phys_sections_free(&d->map);
2448     g_free(d);
2449 }
2450 
2451 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2452 {
2453 }
2454 
2455 static void tcg_log_global_after_sync(MemoryListener *listener)
2456 {
2457     CPUAddressSpace *cpuas;
2458 
2459     /* Wait for the CPU to end the current TB.  This avoids the following
2460      * incorrect race:
2461      *
2462      *      vCPU                         migration
2463      *      ----------------------       -------------------------
2464      *      TLB check -> slow path
2465      *        notdirty_mem_write
2466      *          write to RAM
2467      *          mark dirty
2468      *                                   clear dirty flag
2469      *      TLB check -> fast path
2470      *                                   read memory
2471      *        write to RAM
2472      *
2473      * by pushing the migration thread's memory read after the vCPU thread has
2474      * written the memory.
2475      */
2476     if (replay_mode == REPLAY_MODE_NONE) {
2477         /*
2478          * VGA can make calls to this function while updating the screen.
2479          * In record/replay mode this causes a deadlock, because
2480          * run_on_cpu waits for rr mutex. Therefore no races are possible
2481          * in this case and no need for making run_on_cpu when
2482          * record/replay is enabled.
2483          */
2484         cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2485         run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2486     }
2487 }
2488 
2489 static void tcg_commit_cpu(CPUState *cpu, run_on_cpu_data data)
2490 {
2491     CPUAddressSpace *cpuas = data.host_ptr;
2492 
2493     cpuas->memory_dispatch = address_space_to_dispatch(cpuas->as);
2494     tlb_flush(cpu);
2495 }
2496 
2497 static void tcg_commit(MemoryListener *listener)
2498 {
2499     CPUAddressSpace *cpuas;
2500     CPUState *cpu;
2501 
2502     assert(tcg_enabled());
2503     /* since each CPU stores ram addresses in its TLB cache, we must
2504        reset the modified entries */
2505     cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2506     cpu = cpuas->cpu;
2507 
2508     /*
2509      * Defer changes to as->memory_dispatch until the cpu is quiescent.
2510      * Otherwise we race between (1) other cpu threads and (2) ongoing
2511      * i/o for the current cpu thread, with data cached by mmu_lookup().
2512      *
2513      * In addition, queueing the work function will kick the cpu back to
2514      * the main loop, which will end the RCU critical section and reclaim
2515      * the memory data structures.
2516      *
2517      * That said, the listener is also called during realize, before
2518      * all of the tcg machinery for run-on is initialized: thus halt_cond.
2519      */
2520     if (cpu->halt_cond) {
2521         async_run_on_cpu(cpu, tcg_commit_cpu, RUN_ON_CPU_HOST_PTR(cpuas));
2522     } else {
2523         tcg_commit_cpu(cpu, RUN_ON_CPU_HOST_PTR(cpuas));
2524     }
2525 }
2526 
2527 static void memory_map_init(void)
2528 {
2529     system_memory = g_malloc(sizeof(*system_memory));
2530 
2531     memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2532     address_space_init(&address_space_memory, system_memory, "memory");
2533 
2534     system_io = g_malloc(sizeof(*system_io));
2535     memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2536                           65536);
2537     address_space_init(&address_space_io, system_io, "I/O");
2538 }
2539 
2540 MemoryRegion *get_system_memory(void)
2541 {
2542     return system_memory;
2543 }
2544 
2545 MemoryRegion *get_system_io(void)
2546 {
2547     return system_io;
2548 }
2549 
2550 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2551                                      hwaddr length)
2552 {
2553     uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2554     addr += memory_region_get_ram_addr(mr);
2555 
2556     /* No early return if dirty_log_mask is or becomes 0, because
2557      * cpu_physical_memory_set_dirty_range will still call
2558      * xen_modified_memory.
2559      */
2560     if (dirty_log_mask) {
2561         dirty_log_mask =
2562             cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2563     }
2564     if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2565         assert(tcg_enabled());
2566         tb_invalidate_phys_range(addr, addr + length - 1);
2567         dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2568     }
2569     cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2570 }
2571 
2572 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2573 {
2574     /*
2575      * In principle this function would work on other memory region types too,
2576      * but the ROM device use case is the only one where this operation is
2577      * necessary.  Other memory regions should use the
2578      * address_space_read/write() APIs.
2579      */
2580     assert(memory_region_is_romd(mr));
2581 
2582     invalidate_and_set_dirty(mr, addr, size);
2583 }
2584 
2585 int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2586 {
2587     unsigned access_size_max = mr->ops->valid.max_access_size;
2588 
2589     /* Regions are assumed to support 1-4 byte accesses unless
2590        otherwise specified.  */
2591     if (access_size_max == 0) {
2592         access_size_max = 4;
2593     }
2594 
2595     /* Bound the maximum access by the alignment of the address.  */
2596     if (!mr->ops->impl.unaligned) {
2597         unsigned align_size_max = addr & -addr;
2598         if (align_size_max != 0 && align_size_max < access_size_max) {
2599             access_size_max = align_size_max;
2600         }
2601     }
2602 
2603     /* Don't attempt accesses larger than the maximum.  */
2604     if (l > access_size_max) {
2605         l = access_size_max;
2606     }
2607     l = pow2floor(l);
2608 
2609     return l;
2610 }
2611 
2612 bool prepare_mmio_access(MemoryRegion *mr)
2613 {
2614     bool release_lock = false;
2615 
2616     if (!qemu_mutex_iothread_locked()) {
2617         qemu_mutex_lock_iothread();
2618         release_lock = true;
2619     }
2620     if (mr->flush_coalesced_mmio) {
2621         qemu_flush_coalesced_mmio_buffer();
2622     }
2623 
2624     return release_lock;
2625 }
2626 
2627 /**
2628  * flatview_access_allowed
2629  * @mr: #MemoryRegion to be accessed
2630  * @attrs: memory transaction attributes
2631  * @addr: address within that memory region
2632  * @len: the number of bytes to access
2633  *
2634  * Check if a memory transaction is allowed.
2635  *
2636  * Returns: true if transaction is allowed, false if denied.
2637  */
2638 static bool flatview_access_allowed(MemoryRegion *mr, MemTxAttrs attrs,
2639                                     hwaddr addr, hwaddr len)
2640 {
2641     if (likely(!attrs.memory)) {
2642         return true;
2643     }
2644     if (memory_region_is_ram(mr)) {
2645         return true;
2646     }
2647     qemu_log_mask(LOG_GUEST_ERROR,
2648                   "Invalid access to non-RAM device at "
2649                   "addr 0x%" HWADDR_PRIX ", size %" HWADDR_PRIu ", "
2650                   "region '%s'\n", addr, len, memory_region_name(mr));
2651     return false;
2652 }
2653 
2654 /* Called within RCU critical section.  */
2655 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2656                                            MemTxAttrs attrs,
2657                                            const void *ptr,
2658                                            hwaddr len, hwaddr addr1,
2659                                            hwaddr l, MemoryRegion *mr)
2660 {
2661     uint8_t *ram_ptr;
2662     uint64_t val;
2663     MemTxResult result = MEMTX_OK;
2664     bool release_lock = false;
2665     const uint8_t *buf = ptr;
2666 
2667     for (;;) {
2668         if (!flatview_access_allowed(mr, attrs, addr1, l)) {
2669             result |= MEMTX_ACCESS_ERROR;
2670             /* Keep going. */
2671         } else if (!memory_access_is_direct(mr, true)) {
2672             release_lock |= prepare_mmio_access(mr);
2673             l = memory_access_size(mr, l, addr1);
2674             /* XXX: could force current_cpu to NULL to avoid
2675                potential bugs */
2676             val = ldn_he_p(buf, l);
2677             result |= memory_region_dispatch_write(mr, addr1, val,
2678                                                    size_memop(l), attrs);
2679         } else {
2680             /* RAM case */
2681             ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2682             memmove(ram_ptr, buf, l);
2683             invalidate_and_set_dirty(mr, addr1, l);
2684         }
2685 
2686         if (release_lock) {
2687             qemu_mutex_unlock_iothread();
2688             release_lock = false;
2689         }
2690 
2691         len -= l;
2692         buf += l;
2693         addr += l;
2694 
2695         if (!len) {
2696             break;
2697         }
2698 
2699         l = len;
2700         mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2701     }
2702 
2703     return result;
2704 }
2705 
2706 /* Called from RCU critical section.  */
2707 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2708                                   const void *buf, hwaddr len)
2709 {
2710     hwaddr l;
2711     hwaddr addr1;
2712     MemoryRegion *mr;
2713 
2714     l = len;
2715     mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2716     if (!flatview_access_allowed(mr, attrs, addr, len)) {
2717         return MEMTX_ACCESS_ERROR;
2718     }
2719     return flatview_write_continue(fv, addr, attrs, buf, len,
2720                                    addr1, l, mr);
2721 }
2722 
2723 /* Called within RCU critical section.  */
2724 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2725                                    MemTxAttrs attrs, void *ptr,
2726                                    hwaddr len, hwaddr addr1, hwaddr l,
2727                                    MemoryRegion *mr)
2728 {
2729     uint8_t *ram_ptr;
2730     uint64_t val;
2731     MemTxResult result = MEMTX_OK;
2732     bool release_lock = false;
2733     uint8_t *buf = ptr;
2734 
2735     fuzz_dma_read_cb(addr, len, mr);
2736     for (;;) {
2737         if (!flatview_access_allowed(mr, attrs, addr1, l)) {
2738             result |= MEMTX_ACCESS_ERROR;
2739             /* Keep going. */
2740         } else if (!memory_access_is_direct(mr, false)) {
2741             /* I/O case */
2742             release_lock |= prepare_mmio_access(mr);
2743             l = memory_access_size(mr, l, addr1);
2744             result |= memory_region_dispatch_read(mr, addr1, &val,
2745                                                   size_memop(l), attrs);
2746             stn_he_p(buf, l, val);
2747         } else {
2748             /* RAM case */
2749             ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2750             memcpy(buf, ram_ptr, l);
2751         }
2752 
2753         if (release_lock) {
2754             qemu_mutex_unlock_iothread();
2755             release_lock = false;
2756         }
2757 
2758         len -= l;
2759         buf += l;
2760         addr += l;
2761 
2762         if (!len) {
2763             break;
2764         }
2765 
2766         l = len;
2767         mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2768     }
2769 
2770     return result;
2771 }
2772 
2773 /* Called from RCU critical section.  */
2774 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2775                                  MemTxAttrs attrs, void *buf, hwaddr len)
2776 {
2777     hwaddr l;
2778     hwaddr addr1;
2779     MemoryRegion *mr;
2780 
2781     l = len;
2782     mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2783     if (!flatview_access_allowed(mr, attrs, addr, len)) {
2784         return MEMTX_ACCESS_ERROR;
2785     }
2786     return flatview_read_continue(fv, addr, attrs, buf, len,
2787                                   addr1, l, mr);
2788 }
2789 
2790 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2791                                     MemTxAttrs attrs, void *buf, hwaddr len)
2792 {
2793     MemTxResult result = MEMTX_OK;
2794     FlatView *fv;
2795 
2796     if (len > 0) {
2797         RCU_READ_LOCK_GUARD();
2798         fv = address_space_to_flatview(as);
2799         result = flatview_read(fv, addr, attrs, buf, len);
2800     }
2801 
2802     return result;
2803 }
2804 
2805 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2806                                 MemTxAttrs attrs,
2807                                 const void *buf, hwaddr len)
2808 {
2809     MemTxResult result = MEMTX_OK;
2810     FlatView *fv;
2811 
2812     if (len > 0) {
2813         RCU_READ_LOCK_GUARD();
2814         fv = address_space_to_flatview(as);
2815         result = flatview_write(fv, addr, attrs, buf, len);
2816     }
2817 
2818     return result;
2819 }
2820 
2821 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2822                              void *buf, hwaddr len, bool is_write)
2823 {
2824     if (is_write) {
2825         return address_space_write(as, addr, attrs, buf, len);
2826     } else {
2827         return address_space_read_full(as, addr, attrs, buf, len);
2828     }
2829 }
2830 
2831 MemTxResult address_space_set(AddressSpace *as, hwaddr addr,
2832                               uint8_t c, hwaddr len, MemTxAttrs attrs)
2833 {
2834 #define FILLBUF_SIZE 512
2835     uint8_t fillbuf[FILLBUF_SIZE];
2836     int l;
2837     MemTxResult error = MEMTX_OK;
2838 
2839     memset(fillbuf, c, FILLBUF_SIZE);
2840     while (len > 0) {
2841         l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
2842         error |= address_space_write(as, addr, attrs, fillbuf, l);
2843         len -= l;
2844         addr += l;
2845     }
2846 
2847     return error;
2848 }
2849 
2850 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2851                             hwaddr len, bool is_write)
2852 {
2853     address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2854                      buf, len, is_write);
2855 }
2856 
2857 enum write_rom_type {
2858     WRITE_DATA,
2859     FLUSH_CACHE,
2860 };
2861 
2862 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2863                                                            hwaddr addr,
2864                                                            MemTxAttrs attrs,
2865                                                            const void *ptr,
2866                                                            hwaddr len,
2867                                                            enum write_rom_type type)
2868 {
2869     hwaddr l;
2870     uint8_t *ram_ptr;
2871     hwaddr addr1;
2872     MemoryRegion *mr;
2873     const uint8_t *buf = ptr;
2874 
2875     RCU_READ_LOCK_GUARD();
2876     while (len > 0) {
2877         l = len;
2878         mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2879 
2880         if (!(memory_region_is_ram(mr) ||
2881               memory_region_is_romd(mr))) {
2882             l = memory_access_size(mr, l, addr1);
2883         } else {
2884             /* ROM/RAM case */
2885             ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2886             switch (type) {
2887             case WRITE_DATA:
2888                 memcpy(ram_ptr, buf, l);
2889                 invalidate_and_set_dirty(mr, addr1, l);
2890                 break;
2891             case FLUSH_CACHE:
2892                 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2893                 break;
2894             }
2895         }
2896         len -= l;
2897         buf += l;
2898         addr += l;
2899     }
2900     return MEMTX_OK;
2901 }
2902 
2903 /* used for ROM loading : can write in RAM and ROM */
2904 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2905                                     MemTxAttrs attrs,
2906                                     const void *buf, hwaddr len)
2907 {
2908     return address_space_write_rom_internal(as, addr, attrs,
2909                                             buf, len, WRITE_DATA);
2910 }
2911 
2912 void cpu_flush_icache_range(hwaddr start, hwaddr len)
2913 {
2914     /*
2915      * This function should do the same thing as an icache flush that was
2916      * triggered from within the guest. For TCG we are always cache coherent,
2917      * so there is no need to flush anything. For KVM / Xen we need to flush
2918      * the host's instruction cache at least.
2919      */
2920     if (tcg_enabled()) {
2921         return;
2922     }
2923 
2924     address_space_write_rom_internal(&address_space_memory,
2925                                      start, MEMTXATTRS_UNSPECIFIED,
2926                                      NULL, len, FLUSH_CACHE);
2927 }
2928 
2929 typedef struct {
2930     MemoryRegion *mr;
2931     void *buffer;
2932     hwaddr addr;
2933     hwaddr len;
2934     bool in_use;
2935 } BounceBuffer;
2936 
2937 static BounceBuffer bounce;
2938 
2939 typedef struct MapClient {
2940     QEMUBH *bh;
2941     QLIST_ENTRY(MapClient) link;
2942 } MapClient;
2943 
2944 QemuMutex map_client_list_lock;
2945 static QLIST_HEAD(, MapClient) map_client_list
2946     = QLIST_HEAD_INITIALIZER(map_client_list);
2947 
2948 static void cpu_unregister_map_client_do(MapClient *client)
2949 {
2950     QLIST_REMOVE(client, link);
2951     g_free(client);
2952 }
2953 
2954 static void cpu_notify_map_clients_locked(void)
2955 {
2956     MapClient *client;
2957 
2958     while (!QLIST_EMPTY(&map_client_list)) {
2959         client = QLIST_FIRST(&map_client_list);
2960         qemu_bh_schedule(client->bh);
2961         cpu_unregister_map_client_do(client);
2962     }
2963 }
2964 
2965 void cpu_register_map_client(QEMUBH *bh)
2966 {
2967     MapClient *client = g_malloc(sizeof(*client));
2968 
2969     qemu_mutex_lock(&map_client_list_lock);
2970     client->bh = bh;
2971     QLIST_INSERT_HEAD(&map_client_list, client, link);
2972     /* Write map_client_list before reading in_use.  */
2973     smp_mb();
2974     if (!qatomic_read(&bounce.in_use)) {
2975         cpu_notify_map_clients_locked();
2976     }
2977     qemu_mutex_unlock(&map_client_list_lock);
2978 }
2979 
2980 void cpu_exec_init_all(void)
2981 {
2982     qemu_mutex_init(&ram_list.mutex);
2983     /* The data structures we set up here depend on knowing the page size,
2984      * so no more changes can be made after this point.
2985      * In an ideal world, nothing we did before we had finished the
2986      * machine setup would care about the target page size, and we could
2987      * do this much later, rather than requiring board models to state
2988      * up front what their requirements are.
2989      */
2990     finalize_target_page_bits();
2991     io_mem_init();
2992     memory_map_init();
2993     qemu_mutex_init(&map_client_list_lock);
2994 }
2995 
2996 void cpu_unregister_map_client(QEMUBH *bh)
2997 {
2998     MapClient *client;
2999 
3000     qemu_mutex_lock(&map_client_list_lock);
3001     QLIST_FOREACH(client, &map_client_list, link) {
3002         if (client->bh == bh) {
3003             cpu_unregister_map_client_do(client);
3004             break;
3005         }
3006     }
3007     qemu_mutex_unlock(&map_client_list_lock);
3008 }
3009 
3010 static void cpu_notify_map_clients(void)
3011 {
3012     qemu_mutex_lock(&map_client_list_lock);
3013     cpu_notify_map_clients_locked();
3014     qemu_mutex_unlock(&map_client_list_lock);
3015 }
3016 
3017 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3018                                   bool is_write, MemTxAttrs attrs)
3019 {
3020     MemoryRegion *mr;
3021     hwaddr l, xlat;
3022 
3023     while (len > 0) {
3024         l = len;
3025         mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3026         if (!memory_access_is_direct(mr, is_write)) {
3027             l = memory_access_size(mr, l, addr);
3028             if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3029                 return false;
3030             }
3031         }
3032 
3033         len -= l;
3034         addr += l;
3035     }
3036     return true;
3037 }
3038 
3039 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3040                                 hwaddr len, bool is_write,
3041                                 MemTxAttrs attrs)
3042 {
3043     FlatView *fv;
3044 
3045     RCU_READ_LOCK_GUARD();
3046     fv = address_space_to_flatview(as);
3047     return flatview_access_valid(fv, addr, len, is_write, attrs);
3048 }
3049 
3050 static hwaddr
3051 flatview_extend_translation(FlatView *fv, hwaddr addr,
3052                             hwaddr target_len,
3053                             MemoryRegion *mr, hwaddr base, hwaddr len,
3054                             bool is_write, MemTxAttrs attrs)
3055 {
3056     hwaddr done = 0;
3057     hwaddr xlat;
3058     MemoryRegion *this_mr;
3059 
3060     for (;;) {
3061         target_len -= len;
3062         addr += len;
3063         done += len;
3064         if (target_len == 0) {
3065             return done;
3066         }
3067 
3068         len = target_len;
3069         this_mr = flatview_translate(fv, addr, &xlat,
3070                                      &len, is_write, attrs);
3071         if (this_mr != mr || xlat != base + done) {
3072             return done;
3073         }
3074     }
3075 }
3076 
3077 /* Map a physical memory region into a host virtual address.
3078  * May map a subset of the requested range, given by and returned in *plen.
3079  * May return NULL if resources needed to perform the mapping are exhausted.
3080  * Use only for reads OR writes - not for read-modify-write operations.
3081  * Use cpu_register_map_client() to know when retrying the map operation is
3082  * likely to succeed.
3083  */
3084 void *address_space_map(AddressSpace *as,
3085                         hwaddr addr,
3086                         hwaddr *plen,
3087                         bool is_write,
3088                         MemTxAttrs attrs)
3089 {
3090     hwaddr len = *plen;
3091     hwaddr l, xlat;
3092     MemoryRegion *mr;
3093     FlatView *fv;
3094 
3095     if (len == 0) {
3096         return NULL;
3097     }
3098 
3099     l = len;
3100     RCU_READ_LOCK_GUARD();
3101     fv = address_space_to_flatview(as);
3102     mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3103 
3104     if (!memory_access_is_direct(mr, is_write)) {
3105         if (qatomic_xchg(&bounce.in_use, true)) {
3106             *plen = 0;
3107             return NULL;
3108         }
3109         /* Avoid unbounded allocations */
3110         l = MIN(l, TARGET_PAGE_SIZE);
3111         bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3112         bounce.addr = addr;
3113         bounce.len = l;
3114 
3115         memory_region_ref(mr);
3116         bounce.mr = mr;
3117         if (!is_write) {
3118             flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3119                                bounce.buffer, l);
3120         }
3121 
3122         *plen = l;
3123         return bounce.buffer;
3124     }
3125 
3126 
3127     memory_region_ref(mr);
3128     *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3129                                         l, is_write, attrs);
3130     fuzz_dma_read_cb(addr, *plen, mr);
3131     return qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3132 }
3133 
3134 /* Unmaps a memory region previously mapped by address_space_map().
3135  * Will also mark the memory as dirty if is_write is true.  access_len gives
3136  * the amount of memory that was actually read or written by the caller.
3137  */
3138 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3139                          bool is_write, hwaddr access_len)
3140 {
3141     if (buffer != bounce.buffer) {
3142         MemoryRegion *mr;
3143         ram_addr_t addr1;
3144 
3145         mr = memory_region_from_host(buffer, &addr1);
3146         assert(mr != NULL);
3147         if (is_write) {
3148             invalidate_and_set_dirty(mr, addr1, access_len);
3149         }
3150         if (xen_enabled()) {
3151             xen_invalidate_map_cache_entry(buffer);
3152         }
3153         memory_region_unref(mr);
3154         return;
3155     }
3156     if (is_write) {
3157         address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3158                             bounce.buffer, access_len);
3159     }
3160     qemu_vfree(bounce.buffer);
3161     bounce.buffer = NULL;
3162     memory_region_unref(bounce.mr);
3163     /* Clear in_use before reading map_client_list.  */
3164     qatomic_set_mb(&bounce.in_use, false);
3165     cpu_notify_map_clients();
3166 }
3167 
3168 void *cpu_physical_memory_map(hwaddr addr,
3169                               hwaddr *plen,
3170                               bool is_write)
3171 {
3172     return address_space_map(&address_space_memory, addr, plen, is_write,
3173                              MEMTXATTRS_UNSPECIFIED);
3174 }
3175 
3176 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3177                                bool is_write, hwaddr access_len)
3178 {
3179     return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3180 }
3181 
3182 #define ARG1_DECL                AddressSpace *as
3183 #define ARG1                     as
3184 #define SUFFIX
3185 #define TRANSLATE(...)           address_space_translate(as, __VA_ARGS__)
3186 #define RCU_READ_LOCK(...)       rcu_read_lock()
3187 #define RCU_READ_UNLOCK(...)     rcu_read_unlock()
3188 #include "memory_ldst.c.inc"
3189 
3190 int64_t address_space_cache_init(MemoryRegionCache *cache,
3191                                  AddressSpace *as,
3192                                  hwaddr addr,
3193                                  hwaddr len,
3194                                  bool is_write)
3195 {
3196     AddressSpaceDispatch *d;
3197     hwaddr l;
3198     MemoryRegion *mr;
3199     Int128 diff;
3200 
3201     assert(len > 0);
3202 
3203     l = len;
3204     cache->fv = address_space_get_flatview(as);
3205     d = flatview_to_dispatch(cache->fv);
3206     cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3207 
3208     /*
3209      * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3210      * Take that into account to compute how many bytes are there between
3211      * cache->xlat and the end of the section.
3212      */
3213     diff = int128_sub(cache->mrs.size,
3214                       int128_make64(cache->xlat - cache->mrs.offset_within_region));
3215     l = int128_get64(int128_min(diff, int128_make64(l)));
3216 
3217     mr = cache->mrs.mr;
3218     memory_region_ref(mr);
3219     if (memory_access_is_direct(mr, is_write)) {
3220         /* We don't care about the memory attributes here as we're only
3221          * doing this if we found actual RAM, which behaves the same
3222          * regardless of attributes; so UNSPECIFIED is fine.
3223          */
3224         l = flatview_extend_translation(cache->fv, addr, len, mr,
3225                                         cache->xlat, l, is_write,
3226                                         MEMTXATTRS_UNSPECIFIED);
3227         cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3228     } else {
3229         cache->ptr = NULL;
3230     }
3231 
3232     cache->len = l;
3233     cache->is_write = is_write;
3234     return l;
3235 }
3236 
3237 void address_space_cache_invalidate(MemoryRegionCache *cache,
3238                                     hwaddr addr,
3239                                     hwaddr access_len)
3240 {
3241     assert(cache->is_write);
3242     if (likely(cache->ptr)) {
3243         invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3244     }
3245 }
3246 
3247 void address_space_cache_destroy(MemoryRegionCache *cache)
3248 {
3249     if (!cache->mrs.mr) {
3250         return;
3251     }
3252 
3253     if (xen_enabled()) {
3254         xen_invalidate_map_cache_entry(cache->ptr);
3255     }
3256     memory_region_unref(cache->mrs.mr);
3257     flatview_unref(cache->fv);
3258     cache->mrs.mr = NULL;
3259     cache->fv = NULL;
3260 }
3261 
3262 /* Called from RCU critical section.  This function has the same
3263  * semantics as address_space_translate, but it only works on a
3264  * predefined range of a MemoryRegion that was mapped with
3265  * address_space_cache_init.
3266  */
3267 static inline MemoryRegion *address_space_translate_cached(
3268     MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3269     hwaddr *plen, bool is_write, MemTxAttrs attrs)
3270 {
3271     MemoryRegionSection section;
3272     MemoryRegion *mr;
3273     IOMMUMemoryRegion *iommu_mr;
3274     AddressSpace *target_as;
3275 
3276     assert(!cache->ptr);
3277     *xlat = addr + cache->xlat;
3278 
3279     mr = cache->mrs.mr;
3280     iommu_mr = memory_region_get_iommu(mr);
3281     if (!iommu_mr) {
3282         /* MMIO region.  */
3283         return mr;
3284     }
3285 
3286     section = address_space_translate_iommu(iommu_mr, xlat, plen,
3287                                             NULL, is_write, true,
3288                                             &target_as, attrs);
3289     return section.mr;
3290 }
3291 
3292 /* Called from RCU critical section. address_space_read_cached uses this
3293  * out of line function when the target is an MMIO or IOMMU region.
3294  */
3295 MemTxResult
3296 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3297                                    void *buf, hwaddr len)
3298 {
3299     hwaddr addr1, l;
3300     MemoryRegion *mr;
3301 
3302     l = len;
3303     mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3304                                         MEMTXATTRS_UNSPECIFIED);
3305     return flatview_read_continue(cache->fv,
3306                                   addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3307                                   addr1, l, mr);
3308 }
3309 
3310 /* Called from RCU critical section. address_space_write_cached uses this
3311  * out of line function when the target is an MMIO or IOMMU region.
3312  */
3313 MemTxResult
3314 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3315                                     const void *buf, hwaddr len)
3316 {
3317     hwaddr addr1, l;
3318     MemoryRegion *mr;
3319 
3320     l = len;
3321     mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3322                                         MEMTXATTRS_UNSPECIFIED);
3323     return flatview_write_continue(cache->fv,
3324                                    addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3325                                    addr1, l, mr);
3326 }
3327 
3328 #define ARG1_DECL                MemoryRegionCache *cache
3329 #define ARG1                     cache
3330 #define SUFFIX                   _cached_slow
3331 #define TRANSLATE(...)           address_space_translate_cached(cache, __VA_ARGS__)
3332 #define RCU_READ_LOCK()          ((void)0)
3333 #define RCU_READ_UNLOCK()        ((void)0)
3334 #include "memory_ldst.c.inc"
3335 
3336 /* virtual memory access for debug (includes writing to ROM) */
3337 int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
3338                         void *ptr, size_t len, bool is_write)
3339 {
3340     hwaddr phys_addr;
3341     vaddr l, page;
3342     uint8_t *buf = ptr;
3343 
3344     cpu_synchronize_state(cpu);
3345     while (len > 0) {
3346         int asidx;
3347         MemTxAttrs attrs;
3348         MemTxResult res;
3349 
3350         page = addr & TARGET_PAGE_MASK;
3351         phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3352         asidx = cpu_asidx_from_attrs(cpu, attrs);
3353         /* if no physical page mapped, return an error */
3354         if (phys_addr == -1)
3355             return -1;
3356         l = (page + TARGET_PAGE_SIZE) - addr;
3357         if (l > len)
3358             l = len;
3359         phys_addr += (addr & ~TARGET_PAGE_MASK);
3360         if (is_write) {
3361             res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3362                                           attrs, buf, l);
3363         } else {
3364             res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3365                                      attrs, buf, l);
3366         }
3367         if (res != MEMTX_OK) {
3368             return -1;
3369         }
3370         len -= l;
3371         buf += l;
3372         addr += l;
3373     }
3374     return 0;
3375 }
3376 
3377 /*
3378  * Allows code that needs to deal with migration bitmaps etc to still be built
3379  * target independent.
3380  */
3381 size_t qemu_target_page_size(void)
3382 {
3383     return TARGET_PAGE_SIZE;
3384 }
3385 
3386 int qemu_target_page_mask(void)
3387 {
3388     return TARGET_PAGE_MASK;
3389 }
3390 
3391 int qemu_target_page_bits(void)
3392 {
3393     return TARGET_PAGE_BITS;
3394 }
3395 
3396 int qemu_target_page_bits_min(void)
3397 {
3398     return TARGET_PAGE_BITS_MIN;
3399 }
3400 
3401 /* Convert target pages to MiB (2**20). */
3402 size_t qemu_target_pages_to_MiB(size_t pages)
3403 {
3404     int page_bits = TARGET_PAGE_BITS;
3405 
3406     /* So far, the largest (non-huge) page size is 64k, i.e. 16 bits. */
3407     g_assert(page_bits < 20);
3408 
3409     return pages >> (20 - page_bits);
3410 }
3411 
3412 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3413 {
3414     MemoryRegion*mr;
3415     hwaddr l = 1;
3416 
3417     RCU_READ_LOCK_GUARD();
3418     mr = address_space_translate(&address_space_memory,
3419                                  phys_addr, &phys_addr, &l, false,
3420                                  MEMTXATTRS_UNSPECIFIED);
3421 
3422     return !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3423 }
3424 
3425 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3426 {
3427     RAMBlock *block;
3428     int ret = 0;
3429 
3430     RCU_READ_LOCK_GUARD();
3431     RAMBLOCK_FOREACH(block) {
3432         ret = func(block, opaque);
3433         if (ret) {
3434             break;
3435         }
3436     }
3437     return ret;
3438 }
3439 
3440 /*
3441  * Unmap pages of memory from start to start+length such that
3442  * they a) read as 0, b) Trigger whatever fault mechanism
3443  * the OS provides for postcopy.
3444  * The pages must be unmapped by the end of the function.
3445  * Returns: 0 on success, none-0 on failure
3446  *
3447  */
3448 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3449 {
3450     int ret = -1;
3451 
3452     uint8_t *host_startaddr = rb->host + start;
3453 
3454     if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3455         error_report("ram_block_discard_range: Unaligned start address: %p",
3456                      host_startaddr);
3457         goto err;
3458     }
3459 
3460     if ((start + length) <= rb->max_length) {
3461         bool need_madvise, need_fallocate;
3462         if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3463             error_report("ram_block_discard_range: Unaligned length: %zx",
3464                          length);
3465             goto err;
3466         }
3467 
3468         errno = ENOTSUP; /* If we are missing MADVISE etc */
3469 
3470         /* The logic here is messy;
3471          *    madvise DONTNEED fails for hugepages
3472          *    fallocate works on hugepages and shmem
3473          *    shared anonymous memory requires madvise REMOVE
3474          */
3475         need_madvise = (rb->page_size == qemu_host_page_size);
3476         need_fallocate = rb->fd != -1;
3477         if (need_fallocate) {
3478             /* For a file, this causes the area of the file to be zero'd
3479              * if read, and for hugetlbfs also causes it to be unmapped
3480              * so a userfault will trigger.
3481              */
3482 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3483             /*
3484              * We'll discard data from the actual file, even though we only
3485              * have a MAP_PRIVATE mapping, possibly messing with other
3486              * MAP_PRIVATE/MAP_SHARED mappings. There is no easy way to
3487              * change that behavior whithout violating the promised
3488              * semantics of ram_block_discard_range().
3489              *
3490              * Only warn, because it works as long as nobody else uses that
3491              * file.
3492              */
3493             if (!qemu_ram_is_shared(rb)) {
3494                 warn_report_once("ram_block_discard_range: Discarding RAM"
3495                                  " in private file mappings is possibly"
3496                                  " dangerous, because it will modify the"
3497                                  " underlying file and will affect other"
3498                                  " users of the file");
3499             }
3500 
3501             ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3502                             start, length);
3503             if (ret) {
3504                 ret = -errno;
3505                 error_report("ram_block_discard_range: Failed to fallocate "
3506                              "%s:%" PRIx64 " +%zx (%d)",
3507                              rb->idstr, start, length, ret);
3508                 goto err;
3509             }
3510 #else
3511             ret = -ENOSYS;
3512             error_report("ram_block_discard_range: fallocate not available/file"
3513                          "%s:%" PRIx64 " +%zx (%d)",
3514                          rb->idstr, start, length, ret);
3515             goto err;
3516 #endif
3517         }
3518         if (need_madvise) {
3519             /* For normal RAM this causes it to be unmapped,
3520              * for shared memory it causes the local mapping to disappear
3521              * and to fall back on the file contents (which we just
3522              * fallocate'd away).
3523              */
3524 #if defined(CONFIG_MADVISE)
3525             if (qemu_ram_is_shared(rb) && rb->fd < 0) {
3526                 ret = madvise(host_startaddr, length, QEMU_MADV_REMOVE);
3527             } else {
3528                 ret = madvise(host_startaddr, length, QEMU_MADV_DONTNEED);
3529             }
3530             if (ret) {
3531                 ret = -errno;
3532                 error_report("ram_block_discard_range: Failed to discard range "
3533                              "%s:%" PRIx64 " +%zx (%d)",
3534                              rb->idstr, start, length, ret);
3535                 goto err;
3536             }
3537 #else
3538             ret = -ENOSYS;
3539             error_report("ram_block_discard_range: MADVISE not available"
3540                          "%s:%" PRIx64 " +%zx (%d)",
3541                          rb->idstr, start, length, ret);
3542             goto err;
3543 #endif
3544         }
3545         trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3546                                       need_madvise, need_fallocate, ret);
3547     } else {
3548         error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3549                      "/%zx/" RAM_ADDR_FMT")",
3550                      rb->idstr, start, length, rb->max_length);
3551     }
3552 
3553 err:
3554     return ret;
3555 }
3556 
3557 bool ramblock_is_pmem(RAMBlock *rb)
3558 {
3559     return rb->flags & RAM_PMEM;
3560 }
3561 
3562 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3563 {
3564     if (start == end - 1) {
3565         qemu_printf("\t%3d      ", start);
3566     } else {
3567         qemu_printf("\t%3d..%-3d ", start, end - 1);
3568     }
3569     qemu_printf(" skip=%d ", skip);
3570     if (ptr == PHYS_MAP_NODE_NIL) {
3571         qemu_printf(" ptr=NIL");
3572     } else if (!skip) {
3573         qemu_printf(" ptr=#%d", ptr);
3574     } else {
3575         qemu_printf(" ptr=[%d]", ptr);
3576     }
3577     qemu_printf("\n");
3578 }
3579 
3580 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3581                            int128_sub((size), int128_one())) : 0)
3582 
3583 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3584 {
3585     int i;
3586 
3587     qemu_printf("  Dispatch\n");
3588     qemu_printf("    Physical sections\n");
3589 
3590     for (i = 0; i < d->map.sections_nb; ++i) {
3591         MemoryRegionSection *s = d->map.sections + i;
3592         const char *names[] = { " [unassigned]", " [not dirty]",
3593                                 " [ROM]", " [watch]" };
3594 
3595         qemu_printf("      #%d @" HWADDR_FMT_plx ".." HWADDR_FMT_plx
3596                     " %s%s%s%s%s",
3597             i,
3598             s->offset_within_address_space,
3599             s->offset_within_address_space + MR_SIZE(s->size),
3600             s->mr->name ? s->mr->name : "(noname)",
3601             i < ARRAY_SIZE(names) ? names[i] : "",
3602             s->mr == root ? " [ROOT]" : "",
3603             s == d->mru_section ? " [MRU]" : "",
3604             s->mr->is_iommu ? " [iommu]" : "");
3605 
3606         if (s->mr->alias) {
3607             qemu_printf(" alias=%s", s->mr->alias->name ?
3608                     s->mr->alias->name : "noname");
3609         }
3610         qemu_printf("\n");
3611     }
3612 
3613     qemu_printf("    Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3614                P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3615     for (i = 0; i < d->map.nodes_nb; ++i) {
3616         int j, jprev;
3617         PhysPageEntry prev;
3618         Node *n = d->map.nodes + i;
3619 
3620         qemu_printf("      [%d]\n", i);
3621 
3622         for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3623             PhysPageEntry *pe = *n + j;
3624 
3625             if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3626                 continue;
3627             }
3628 
3629             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3630 
3631             jprev = j;
3632             prev = *pe;
3633         }
3634 
3635         if (jprev != ARRAY_SIZE(*n)) {
3636             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3637         }
3638     }
3639 }
3640 
3641 /* Require any discards to work. */
3642 static unsigned int ram_block_discard_required_cnt;
3643 /* Require only coordinated discards to work. */
3644 static unsigned int ram_block_coordinated_discard_required_cnt;
3645 /* Disable any discards. */
3646 static unsigned int ram_block_discard_disabled_cnt;
3647 /* Disable only uncoordinated discards. */
3648 static unsigned int ram_block_uncoordinated_discard_disabled_cnt;
3649 static QemuMutex ram_block_discard_disable_mutex;
3650 
3651 static void ram_block_discard_disable_mutex_lock(void)
3652 {
3653     static gsize initialized;
3654 
3655     if (g_once_init_enter(&initialized)) {
3656         qemu_mutex_init(&ram_block_discard_disable_mutex);
3657         g_once_init_leave(&initialized, 1);
3658     }
3659     qemu_mutex_lock(&ram_block_discard_disable_mutex);
3660 }
3661 
3662 static void ram_block_discard_disable_mutex_unlock(void)
3663 {
3664     qemu_mutex_unlock(&ram_block_discard_disable_mutex);
3665 }
3666 
3667 int ram_block_discard_disable(bool state)
3668 {
3669     int ret = 0;
3670 
3671     ram_block_discard_disable_mutex_lock();
3672     if (!state) {
3673         ram_block_discard_disabled_cnt--;
3674     } else if (ram_block_discard_required_cnt ||
3675                ram_block_coordinated_discard_required_cnt) {
3676         ret = -EBUSY;
3677     } else {
3678         ram_block_discard_disabled_cnt++;
3679     }
3680     ram_block_discard_disable_mutex_unlock();
3681     return ret;
3682 }
3683 
3684 int ram_block_uncoordinated_discard_disable(bool state)
3685 {
3686     int ret = 0;
3687 
3688     ram_block_discard_disable_mutex_lock();
3689     if (!state) {
3690         ram_block_uncoordinated_discard_disabled_cnt--;
3691     } else if (ram_block_discard_required_cnt) {
3692         ret = -EBUSY;
3693     } else {
3694         ram_block_uncoordinated_discard_disabled_cnt++;
3695     }
3696     ram_block_discard_disable_mutex_unlock();
3697     return ret;
3698 }
3699 
3700 int ram_block_discard_require(bool state)
3701 {
3702     int ret = 0;
3703 
3704     ram_block_discard_disable_mutex_lock();
3705     if (!state) {
3706         ram_block_discard_required_cnt--;
3707     } else if (ram_block_discard_disabled_cnt ||
3708                ram_block_uncoordinated_discard_disabled_cnt) {
3709         ret = -EBUSY;
3710     } else {
3711         ram_block_discard_required_cnt++;
3712     }
3713     ram_block_discard_disable_mutex_unlock();
3714     return ret;
3715 }
3716 
3717 int ram_block_coordinated_discard_require(bool state)
3718 {
3719     int ret = 0;
3720 
3721     ram_block_discard_disable_mutex_lock();
3722     if (!state) {
3723         ram_block_coordinated_discard_required_cnt--;
3724     } else if (ram_block_discard_disabled_cnt) {
3725         ret = -EBUSY;
3726     } else {
3727         ram_block_coordinated_discard_required_cnt++;
3728     }
3729     ram_block_discard_disable_mutex_unlock();
3730     return ret;
3731 }
3732 
3733 bool ram_block_discard_is_disabled(void)
3734 {
3735     return qatomic_read(&ram_block_discard_disabled_cnt) ||
3736            qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt);
3737 }
3738 
3739 bool ram_block_discard_is_required(void)
3740 {
3741     return qatomic_read(&ram_block_discard_required_cnt) ||
3742            qatomic_read(&ram_block_coordinated_discard_required_cnt);
3743 }
3744