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