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