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