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