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