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