xref: /qemu/system/physmem.c (revision 6169f1193657d0ba630a2ce33cef639ae918bce4)
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 (ram_flags & RAM_SHARED) {
2118             const char *name = memory_region_name(mr);
2119             int fd = qemu_ram_get_shared_fd(name, errp);
2120 
2121             if (fd < 0) {
2122                 return NULL;
2123             }
2124 
2125             /* Use same alignment as qemu_anon_ram_alloc */
2126             mr->align = QEMU_VMALLOC_ALIGN;
2127 
2128             /*
2129              * This can fail if the shm mount size is too small, or alloc from
2130              * fd is not supported, but previous QEMU versions that called
2131              * qemu_anon_ram_alloc for anonymous shared memory could have
2132              * succeeded.  Quietly fail and fall back.
2133              */
2134             new_block = qemu_ram_alloc_from_fd(size, max_size, resized, mr,
2135                                                ram_flags, fd, 0, false, NULL);
2136             if (new_block) {
2137                 trace_qemu_ram_alloc_shared(name, new_block->used_length,
2138                                             new_block->max_length, fd,
2139                                             new_block->host);
2140                 return new_block;
2141             }
2142 
2143             close(fd);
2144             /* fall back to anon allocation */
2145         }
2146     }
2147 #endif
2148 
2149     align = qemu_real_host_page_size();
2150     align = MAX(align, TARGET_PAGE_SIZE);
2151     size = ROUND_UP(size, align);
2152     max_size = ROUND_UP(max_size, align);
2153 
2154     new_block = g_malloc0(sizeof(*new_block));
2155     new_block->mr = mr;
2156     new_block->resized = resized;
2157     new_block->used_length = size;
2158     new_block->max_length = max_size;
2159     new_block->fd = -1;
2160     new_block->guest_memfd = -1;
2161     new_block->page_size = qemu_real_host_page_size();
2162     new_block->host = host;
2163     new_block->flags = ram_flags;
2164     ram_block_add(new_block, &local_err);
2165     if (local_err) {
2166         g_free(new_block);
2167         error_propagate(errp, local_err);
2168         return NULL;
2169     }
2170     return new_block;
2171 }
2172 
2173 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2174                                    MemoryRegion *mr, Error **errp)
2175 {
2176     return qemu_ram_alloc_internal(size, size, NULL, host, RAM_PREALLOC, mr,
2177                                    errp);
2178 }
2179 
2180 RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
2181                          MemoryRegion *mr, Error **errp)
2182 {
2183     assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE | RAM_GUEST_MEMFD |
2184                           RAM_PRIVATE)) == 0);
2185     return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
2186 }
2187 
2188 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2189                                     qemu_ram_resize_cb resized,
2190                                     MemoryRegion *mr, Error **errp)
2191 {
2192     return qemu_ram_alloc_internal(size, maxsz, resized, NULL,
2193                                    RAM_RESIZEABLE, mr, errp);
2194 }
2195 
2196 static void reclaim_ramblock(RAMBlock *block)
2197 {
2198     if (block->flags & RAM_PREALLOC) {
2199         ;
2200     } else if (xen_enabled()) {
2201         xen_invalidate_map_cache_entry(block->host);
2202 #ifndef _WIN32
2203     } else if (block->fd >= 0) {
2204         qemu_ram_munmap(block->fd, block->host, block->max_length);
2205         close(block->fd);
2206 #endif
2207     } else {
2208         qemu_anon_ram_free(block->host, block->max_length);
2209     }
2210 
2211     if (block->guest_memfd >= 0) {
2212         close(block->guest_memfd);
2213         ram_block_discard_require(false);
2214     }
2215 
2216     g_free(block);
2217 }
2218 
2219 void qemu_ram_free(RAMBlock *block)
2220 {
2221     if (!block) {
2222         return;
2223     }
2224 
2225     if (block->host) {
2226         ram_block_notify_remove(block->host, block->used_length,
2227                                 block->max_length);
2228     }
2229 
2230     qemu_mutex_lock_ramlist();
2231     QLIST_REMOVE_RCU(block, next);
2232     ram_list.mru_block = NULL;
2233     /* Write list before version */
2234     smp_wmb();
2235     ram_list.version++;
2236     call_rcu(block, reclaim_ramblock, rcu);
2237     qemu_mutex_unlock_ramlist();
2238 }
2239 
2240 #ifndef _WIN32
2241 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2242 {
2243     RAMBlock *block;
2244     ram_addr_t offset;
2245     int flags;
2246     void *area, *vaddr;
2247     int prot;
2248 
2249     RAMBLOCK_FOREACH(block) {
2250         offset = addr - block->offset;
2251         if (offset < block->max_length) {
2252             vaddr = ramblock_ptr(block, offset);
2253             if (block->flags & RAM_PREALLOC) {
2254                 ;
2255             } else if (xen_enabled()) {
2256                 abort();
2257             } else {
2258                 flags = MAP_FIXED;
2259                 flags |= block->flags & RAM_SHARED ?
2260                          MAP_SHARED : MAP_PRIVATE;
2261                 flags |= block->flags & RAM_NORESERVE ? MAP_NORESERVE : 0;
2262                 prot = PROT_READ;
2263                 prot |= block->flags & RAM_READONLY ? 0 : PROT_WRITE;
2264                 if (block->fd >= 0) {
2265                     area = mmap(vaddr, length, prot, flags, block->fd,
2266                                 offset + block->fd_offset);
2267                 } else {
2268                     flags |= MAP_ANONYMOUS;
2269                     area = mmap(vaddr, length, prot, flags, -1, 0);
2270                 }
2271                 if (area != vaddr) {
2272                     error_report("Could not remap addr: "
2273                                  RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2274                                  length, addr);
2275                     exit(1);
2276                 }
2277                 memory_try_enable_merging(vaddr, length);
2278                 qemu_ram_setup_dump(vaddr, length);
2279             }
2280         }
2281     }
2282 }
2283 #endif /* !_WIN32 */
2284 
2285 /*
2286  * Return a host pointer to guest's ram.
2287  * For Xen, foreign mappings get created if they don't already exist.
2288  *
2289  * @block: block for the RAM to lookup (optional and may be NULL).
2290  * @addr: address within the memory region.
2291  * @size: pointer to requested size (optional and may be NULL).
2292  *        size may get modified and return a value smaller than
2293  *        what was requested.
2294  * @lock: wether to lock the mapping in xen-mapcache until invalidated.
2295  * @is_write: hint wether to map RW or RO in the xen-mapcache.
2296  *            (optional and may always be set to true).
2297  *
2298  * Called within RCU critical section.
2299  */
2300 static void *qemu_ram_ptr_length(RAMBlock *block, ram_addr_t addr,
2301                                  hwaddr *size, bool lock,
2302                                  bool is_write)
2303 {
2304     hwaddr len = 0;
2305 
2306     if (size && *size == 0) {
2307         return NULL;
2308     }
2309 
2310     if (block == NULL) {
2311         block = qemu_get_ram_block(addr);
2312         addr -= block->offset;
2313     }
2314     if (size) {
2315         *size = MIN(*size, block->max_length - addr);
2316         len = *size;
2317     }
2318 
2319     if (xen_enabled() && block->host == NULL) {
2320         /* We need to check if the requested address is in the RAM
2321          * because we don't want to map the entire memory in QEMU.
2322          * In that case just map the requested area.
2323          */
2324         if (xen_mr_is_memory(block->mr)) {
2325             return xen_map_cache(block->mr, block->offset + addr,
2326                                  len, block->offset,
2327                                  lock, lock, is_write);
2328         }
2329 
2330         block->host = xen_map_cache(block->mr, block->offset,
2331                                     block->max_length,
2332                                     block->offset,
2333                                     1, lock, is_write);
2334     }
2335 
2336     return ramblock_ptr(block, addr);
2337 }
2338 
2339 /*
2340  * Return a host pointer to ram allocated with qemu_ram_alloc.
2341  * This should not be used for general purpose DMA.  Use address_space_map
2342  * or address_space_rw instead. For local memory (e.g. video ram) that the
2343  * device owns, use memory_region_get_ram_ptr.
2344  *
2345  * Called within RCU critical section.
2346  */
2347 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2348 {
2349     return qemu_ram_ptr_length(ram_block, addr, NULL, false, true);
2350 }
2351 
2352 /* Return the offset of a hostpointer within a ramblock */
2353 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2354 {
2355     ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2356     assert((uintptr_t)host >= (uintptr_t)rb->host);
2357     assert(res < rb->max_length);
2358 
2359     return res;
2360 }
2361 
2362 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2363                                    ram_addr_t *offset)
2364 {
2365     RAMBlock *block;
2366     uint8_t *host = ptr;
2367 
2368     if (xen_enabled()) {
2369         ram_addr_t ram_addr;
2370         RCU_READ_LOCK_GUARD();
2371         ram_addr = xen_ram_addr_from_mapcache(ptr);
2372         if (ram_addr == RAM_ADDR_INVALID) {
2373             return NULL;
2374         }
2375 
2376         block = qemu_get_ram_block(ram_addr);
2377         if (block) {
2378             *offset = ram_addr - block->offset;
2379         }
2380         return block;
2381     }
2382 
2383     RCU_READ_LOCK_GUARD();
2384     block = qatomic_rcu_read(&ram_list.mru_block);
2385     if (block && block->host && host - block->host < block->max_length) {
2386         goto found;
2387     }
2388 
2389     RAMBLOCK_FOREACH(block) {
2390         /* This case append when the block is not mapped. */
2391         if (block->host == NULL) {
2392             continue;
2393         }
2394         if (host - block->host < block->max_length) {
2395             goto found;
2396         }
2397     }
2398 
2399     return NULL;
2400 
2401 found:
2402     *offset = (host - block->host);
2403     if (round_offset) {
2404         *offset &= TARGET_PAGE_MASK;
2405     }
2406     return block;
2407 }
2408 
2409 /*
2410  * Finds the named RAMBlock
2411  *
2412  * name: The name of RAMBlock to find
2413  *
2414  * Returns: RAMBlock (or NULL if not found)
2415  */
2416 RAMBlock *qemu_ram_block_by_name(const char *name)
2417 {
2418     RAMBlock *block;
2419 
2420     RAMBLOCK_FOREACH(block) {
2421         if (!strcmp(name, block->idstr)) {
2422             return block;
2423         }
2424     }
2425 
2426     return NULL;
2427 }
2428 
2429 /*
2430  * Some of the system routines need to translate from a host pointer
2431  * (typically a TLB entry) back to a ram offset.
2432  */
2433 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2434 {
2435     RAMBlock *block;
2436     ram_addr_t offset;
2437 
2438     block = qemu_ram_block_from_host(ptr, false, &offset);
2439     if (!block) {
2440         return RAM_ADDR_INVALID;
2441     }
2442 
2443     return block->offset + offset;
2444 }
2445 
2446 ram_addr_t qemu_ram_addr_from_host_nofail(void *ptr)
2447 {
2448     ram_addr_t ram_addr;
2449 
2450     ram_addr = qemu_ram_addr_from_host(ptr);
2451     if (ram_addr == RAM_ADDR_INVALID) {
2452         error_report("Bad ram pointer %p", ptr);
2453         abort();
2454     }
2455     return ram_addr;
2456 }
2457 
2458 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2459                                  MemTxAttrs attrs, void *buf, hwaddr len);
2460 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2461                                   const void *buf, hwaddr len);
2462 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2463                                   bool is_write, MemTxAttrs attrs);
2464 
2465 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2466                                 unsigned len, MemTxAttrs attrs)
2467 {
2468     subpage_t *subpage = opaque;
2469     uint8_t buf[8];
2470     MemTxResult res;
2471 
2472 #if defined(DEBUG_SUBPAGE)
2473     printf("%s: subpage %p len %u addr " HWADDR_FMT_plx "\n", __func__,
2474            subpage, len, addr);
2475 #endif
2476     res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2477     if (res) {
2478         return res;
2479     }
2480     *data = ldn_p(buf, len);
2481     return MEMTX_OK;
2482 }
2483 
2484 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2485                                  uint64_t value, unsigned len, MemTxAttrs attrs)
2486 {
2487     subpage_t *subpage = opaque;
2488     uint8_t buf[8];
2489 
2490 #if defined(DEBUG_SUBPAGE)
2491     printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
2492            " value %"PRIx64"\n",
2493            __func__, subpage, len, addr, value);
2494 #endif
2495     stn_p(buf, len, value);
2496     return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2497 }
2498 
2499 static bool subpage_accepts(void *opaque, hwaddr addr,
2500                             unsigned len, bool is_write,
2501                             MemTxAttrs attrs)
2502 {
2503     subpage_t *subpage = opaque;
2504 #if defined(DEBUG_SUBPAGE)
2505     printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx "\n",
2506            __func__, subpage, is_write ? 'w' : 'r', len, addr);
2507 #endif
2508 
2509     return flatview_access_valid(subpage->fv, addr + subpage->base,
2510                                  len, is_write, attrs);
2511 }
2512 
2513 static const MemoryRegionOps subpage_ops = {
2514     .read_with_attrs = subpage_read,
2515     .write_with_attrs = subpage_write,
2516     .impl.min_access_size = 1,
2517     .impl.max_access_size = 8,
2518     .valid.min_access_size = 1,
2519     .valid.max_access_size = 8,
2520     .valid.accepts = subpage_accepts,
2521     .endianness = DEVICE_NATIVE_ENDIAN,
2522 };
2523 
2524 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2525                             uint16_t section)
2526 {
2527     int idx, eidx;
2528 
2529     if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2530         return -1;
2531     idx = SUBPAGE_IDX(start);
2532     eidx = SUBPAGE_IDX(end);
2533 #if defined(DEBUG_SUBPAGE)
2534     printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2535            __func__, mmio, start, end, idx, eidx, section);
2536 #endif
2537     for (; idx <= eidx; idx++) {
2538         mmio->sub_section[idx] = section;
2539     }
2540 
2541     return 0;
2542 }
2543 
2544 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2545 {
2546     subpage_t *mmio;
2547 
2548     /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2549     mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2550     mmio->fv = fv;
2551     mmio->base = base;
2552     memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2553                           NULL, TARGET_PAGE_SIZE);
2554     mmio->iomem.subpage = true;
2555 #if defined(DEBUG_SUBPAGE)
2556     printf("%s: %p base " HWADDR_FMT_plx " len %08x\n", __func__,
2557            mmio, base, TARGET_PAGE_SIZE);
2558 #endif
2559 
2560     return mmio;
2561 }
2562 
2563 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2564 {
2565     assert(fv);
2566     MemoryRegionSection section = {
2567         .fv = fv,
2568         .mr = mr,
2569         .offset_within_address_space = 0,
2570         .offset_within_region = 0,
2571         .size = int128_2_64(),
2572     };
2573 
2574     return phys_section_add(map, &section);
2575 }
2576 
2577 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2578                                       hwaddr index, MemTxAttrs attrs)
2579 {
2580     int asidx = cpu_asidx_from_attrs(cpu, attrs);
2581     CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2582     AddressSpaceDispatch *d = cpuas->memory_dispatch;
2583     int section_index = index & ~TARGET_PAGE_MASK;
2584     MemoryRegionSection *ret;
2585 
2586     assert(section_index < d->map.sections_nb);
2587     ret = d->map.sections + section_index;
2588     assert(ret->mr);
2589     assert(ret->mr->ops);
2590 
2591     return ret;
2592 }
2593 
2594 static void io_mem_init(void)
2595 {
2596     memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2597                           NULL, UINT64_MAX);
2598 }
2599 
2600 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2601 {
2602     AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2603     uint16_t n;
2604 
2605     n = dummy_section(&d->map, fv, &io_mem_unassigned);
2606     assert(n == PHYS_SECTION_UNASSIGNED);
2607 
2608     d->phys_map  = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2609 
2610     return d;
2611 }
2612 
2613 void address_space_dispatch_free(AddressSpaceDispatch *d)
2614 {
2615     phys_sections_free(&d->map);
2616     g_free(d);
2617 }
2618 
2619 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2620 {
2621 }
2622 
2623 static void tcg_log_global_after_sync(MemoryListener *listener)
2624 {
2625     CPUAddressSpace *cpuas;
2626 
2627     /* Wait for the CPU to end the current TB.  This avoids the following
2628      * incorrect race:
2629      *
2630      *      vCPU                         migration
2631      *      ----------------------       -------------------------
2632      *      TLB check -> slow path
2633      *        notdirty_mem_write
2634      *          write to RAM
2635      *          mark dirty
2636      *                                   clear dirty flag
2637      *      TLB check -> fast path
2638      *                                   read memory
2639      *        write to RAM
2640      *
2641      * by pushing the migration thread's memory read after the vCPU thread has
2642      * written the memory.
2643      */
2644     if (replay_mode == REPLAY_MODE_NONE) {
2645         /*
2646          * VGA can make calls to this function while updating the screen.
2647          * In record/replay mode this causes a deadlock, because
2648          * run_on_cpu waits for rr mutex. Therefore no races are possible
2649          * in this case and no need for making run_on_cpu when
2650          * record/replay is enabled.
2651          */
2652         cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2653         run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2654     }
2655 }
2656 
2657 static void tcg_commit_cpu(CPUState *cpu, run_on_cpu_data data)
2658 {
2659     CPUAddressSpace *cpuas = data.host_ptr;
2660 
2661     cpuas->memory_dispatch = address_space_to_dispatch(cpuas->as);
2662     tlb_flush(cpu);
2663 }
2664 
2665 static void tcg_commit(MemoryListener *listener)
2666 {
2667     CPUAddressSpace *cpuas;
2668     CPUState *cpu;
2669 
2670     assert(tcg_enabled());
2671     /* since each CPU stores ram addresses in its TLB cache, we must
2672        reset the modified entries */
2673     cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2674     cpu = cpuas->cpu;
2675 
2676     /*
2677      * Defer changes to as->memory_dispatch until the cpu is quiescent.
2678      * Otherwise we race between (1) other cpu threads and (2) ongoing
2679      * i/o for the current cpu thread, with data cached by mmu_lookup().
2680      *
2681      * In addition, queueing the work function will kick the cpu back to
2682      * the main loop, which will end the RCU critical section and reclaim
2683      * the memory data structures.
2684      *
2685      * That said, the listener is also called during realize, before
2686      * all of the tcg machinery for run-on is initialized: thus halt_cond.
2687      */
2688     if (cpu->halt_cond) {
2689         async_run_on_cpu(cpu, tcg_commit_cpu, RUN_ON_CPU_HOST_PTR(cpuas));
2690     } else {
2691         tcg_commit_cpu(cpu, RUN_ON_CPU_HOST_PTR(cpuas));
2692     }
2693 }
2694 
2695 static void memory_map_init(void)
2696 {
2697     system_memory = g_malloc(sizeof(*system_memory));
2698 
2699     memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2700     address_space_init(&address_space_memory, system_memory, "memory");
2701 
2702     system_io = g_malloc(sizeof(*system_io));
2703     memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2704                           65536);
2705     address_space_init(&address_space_io, system_io, "I/O");
2706 }
2707 
2708 MemoryRegion *get_system_memory(void)
2709 {
2710     return system_memory;
2711 }
2712 
2713 MemoryRegion *get_system_io(void)
2714 {
2715     return system_io;
2716 }
2717 
2718 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2719                                      hwaddr length)
2720 {
2721     uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2722     ram_addr_t ramaddr = memory_region_get_ram_addr(mr);
2723 
2724     /* We know we're only called for RAM MemoryRegions */
2725     assert(ramaddr != RAM_ADDR_INVALID);
2726     addr += ramaddr;
2727 
2728     /* No early return if dirty_log_mask is or becomes 0, because
2729      * cpu_physical_memory_set_dirty_range will still call
2730      * xen_modified_memory.
2731      */
2732     if (dirty_log_mask) {
2733         dirty_log_mask =
2734             cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2735     }
2736     if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2737         assert(tcg_enabled());
2738         tb_invalidate_phys_range(addr, addr + length - 1);
2739         dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2740     }
2741     cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2742 }
2743 
2744 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2745 {
2746     /*
2747      * In principle this function would work on other memory region types too,
2748      * but the ROM device use case is the only one where this operation is
2749      * necessary.  Other memory regions should use the
2750      * address_space_read/write() APIs.
2751      */
2752     assert(memory_region_is_romd(mr));
2753 
2754     invalidate_and_set_dirty(mr, addr, size);
2755 }
2756 
2757 int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2758 {
2759     unsigned access_size_max = mr->ops->valid.max_access_size;
2760 
2761     /* Regions are assumed to support 1-4 byte accesses unless
2762        otherwise specified.  */
2763     if (access_size_max == 0) {
2764         access_size_max = 4;
2765     }
2766 
2767     /* Bound the maximum access by the alignment of the address.  */
2768     if (!mr->ops->impl.unaligned) {
2769         unsigned align_size_max = addr & -addr;
2770         if (align_size_max != 0 && align_size_max < access_size_max) {
2771             access_size_max = align_size_max;
2772         }
2773     }
2774 
2775     /* Don't attempt accesses larger than the maximum.  */
2776     if (l > access_size_max) {
2777         l = access_size_max;
2778     }
2779     l = pow2floor(l);
2780 
2781     return l;
2782 }
2783 
2784 bool prepare_mmio_access(MemoryRegion *mr)
2785 {
2786     bool release_lock = false;
2787 
2788     if (!bql_locked()) {
2789         bql_lock();
2790         release_lock = true;
2791     }
2792     if (mr->flush_coalesced_mmio) {
2793         qemu_flush_coalesced_mmio_buffer();
2794     }
2795 
2796     return release_lock;
2797 }
2798 
2799 /**
2800  * flatview_access_allowed
2801  * @mr: #MemoryRegion to be accessed
2802  * @attrs: memory transaction attributes
2803  * @addr: address within that memory region
2804  * @len: the number of bytes to access
2805  *
2806  * Check if a memory transaction is allowed.
2807  *
2808  * Returns: true if transaction is allowed, false if denied.
2809  */
2810 static bool flatview_access_allowed(MemoryRegion *mr, MemTxAttrs attrs,
2811                                     hwaddr addr, hwaddr len)
2812 {
2813     if (likely(!attrs.memory)) {
2814         return true;
2815     }
2816     if (memory_region_is_ram(mr)) {
2817         return true;
2818     }
2819     qemu_log_mask(LOG_INVALID_MEM,
2820                   "Invalid access to non-RAM device at "
2821                   "addr 0x%" HWADDR_PRIX ", size %" HWADDR_PRIu ", "
2822                   "region '%s'\n", addr, len, memory_region_name(mr));
2823     return false;
2824 }
2825 
2826 static MemTxResult flatview_write_continue_step(MemTxAttrs attrs,
2827                                                 const uint8_t *buf,
2828                                                 hwaddr len, hwaddr mr_addr,
2829                                                 hwaddr *l, MemoryRegion *mr)
2830 {
2831     if (!flatview_access_allowed(mr, attrs, mr_addr, *l)) {
2832         return MEMTX_ACCESS_ERROR;
2833     }
2834 
2835     if (!memory_access_is_direct(mr, true)) {
2836         uint64_t val;
2837         MemTxResult result;
2838         bool release_lock = prepare_mmio_access(mr);
2839 
2840         *l = memory_access_size(mr, *l, mr_addr);
2841         /*
2842          * XXX: could force current_cpu to NULL to avoid
2843          * potential bugs
2844          */
2845 
2846         /*
2847          * Assure Coverity (and ourselves) that we are not going to OVERRUN
2848          * the buffer by following ldn_he_p().
2849          */
2850 #ifdef QEMU_STATIC_ANALYSIS
2851         assert((*l == 1 && len >= 1) ||
2852                (*l == 2 && len >= 2) ||
2853                (*l == 4 && len >= 4) ||
2854                (*l == 8 && len >= 8));
2855 #endif
2856         val = ldn_he_p(buf, *l);
2857         result = memory_region_dispatch_write(mr, mr_addr, val,
2858                                               size_memop(*l), attrs);
2859         if (release_lock) {
2860             bql_unlock();
2861         }
2862 
2863         return result;
2864     } else {
2865         /* RAM case */
2866         uint8_t *ram_ptr = qemu_ram_ptr_length(mr->ram_block, mr_addr, l,
2867                                                false, true);
2868 
2869         memmove(ram_ptr, buf, *l);
2870         invalidate_and_set_dirty(mr, mr_addr, *l);
2871 
2872         return MEMTX_OK;
2873     }
2874 }
2875 
2876 /* Called within RCU critical section.  */
2877 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2878                                            MemTxAttrs attrs,
2879                                            const void *ptr,
2880                                            hwaddr len, hwaddr mr_addr,
2881                                            hwaddr l, MemoryRegion *mr)
2882 {
2883     MemTxResult result = MEMTX_OK;
2884     const uint8_t *buf = ptr;
2885 
2886     for (;;) {
2887         result |= flatview_write_continue_step(attrs, buf, len, mr_addr, &l,
2888                                                mr);
2889 
2890         len -= l;
2891         buf += l;
2892         addr += l;
2893 
2894         if (!len) {
2895             break;
2896         }
2897 
2898         l = len;
2899         mr = flatview_translate(fv, addr, &mr_addr, &l, true, attrs);
2900     }
2901 
2902     return result;
2903 }
2904 
2905 /* Called from RCU critical section.  */
2906 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2907                                   const void *buf, hwaddr len)
2908 {
2909     hwaddr l;
2910     hwaddr mr_addr;
2911     MemoryRegion *mr;
2912 
2913     l = len;
2914     mr = flatview_translate(fv, addr, &mr_addr, &l, true, attrs);
2915     if (!flatview_access_allowed(mr, attrs, addr, len)) {
2916         return MEMTX_ACCESS_ERROR;
2917     }
2918     return flatview_write_continue(fv, addr, attrs, buf, len,
2919                                    mr_addr, l, mr);
2920 }
2921 
2922 static MemTxResult flatview_read_continue_step(MemTxAttrs attrs, uint8_t *buf,
2923                                                hwaddr len, hwaddr mr_addr,
2924                                                hwaddr *l,
2925                                                MemoryRegion *mr)
2926 {
2927     if (!flatview_access_allowed(mr, attrs, mr_addr, *l)) {
2928         return MEMTX_ACCESS_ERROR;
2929     }
2930 
2931     if (!memory_access_is_direct(mr, false)) {
2932         /* I/O case */
2933         uint64_t val;
2934         MemTxResult result;
2935         bool release_lock = prepare_mmio_access(mr);
2936 
2937         *l = memory_access_size(mr, *l, mr_addr);
2938         result = memory_region_dispatch_read(mr, mr_addr, &val, size_memop(*l),
2939                                              attrs);
2940 
2941         /*
2942          * Assure Coverity (and ourselves) that we are not going to OVERRUN
2943          * the buffer by following stn_he_p().
2944          */
2945 #ifdef QEMU_STATIC_ANALYSIS
2946         assert((*l == 1 && len >= 1) ||
2947                (*l == 2 && len >= 2) ||
2948                (*l == 4 && len >= 4) ||
2949                (*l == 8 && len >= 8));
2950 #endif
2951         stn_he_p(buf, *l, val);
2952 
2953         if (release_lock) {
2954             bql_unlock();
2955         }
2956         return result;
2957     } else {
2958         /* RAM case */
2959         uint8_t *ram_ptr = qemu_ram_ptr_length(mr->ram_block, mr_addr, l,
2960                                                false, false);
2961 
2962         memcpy(buf, ram_ptr, *l);
2963 
2964         return MEMTX_OK;
2965     }
2966 }
2967 
2968 /* Called within RCU critical section.  */
2969 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2970                                    MemTxAttrs attrs, void *ptr,
2971                                    hwaddr len, hwaddr mr_addr, hwaddr l,
2972                                    MemoryRegion *mr)
2973 {
2974     MemTxResult result = MEMTX_OK;
2975     uint8_t *buf = ptr;
2976 
2977     fuzz_dma_read_cb(addr, len, mr);
2978     for (;;) {
2979         result |= flatview_read_continue_step(attrs, buf, len, mr_addr, &l, mr);
2980 
2981         len -= l;
2982         buf += l;
2983         addr += l;
2984 
2985         if (!len) {
2986             break;
2987         }
2988 
2989         l = len;
2990         mr = flatview_translate(fv, addr, &mr_addr, &l, false, attrs);
2991     }
2992 
2993     return result;
2994 }
2995 
2996 /* Called from RCU critical section.  */
2997 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2998                                  MemTxAttrs attrs, void *buf, hwaddr len)
2999 {
3000     hwaddr l;
3001     hwaddr mr_addr;
3002     MemoryRegion *mr;
3003 
3004     l = len;
3005     mr = flatview_translate(fv, addr, &mr_addr, &l, false, attrs);
3006     if (!flatview_access_allowed(mr, attrs, addr, len)) {
3007         return MEMTX_ACCESS_ERROR;
3008     }
3009     return flatview_read_continue(fv, addr, attrs, buf, len,
3010                                   mr_addr, l, mr);
3011 }
3012 
3013 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3014                                     MemTxAttrs attrs, void *buf, hwaddr len)
3015 {
3016     MemTxResult result = MEMTX_OK;
3017     FlatView *fv;
3018 
3019     if (len > 0) {
3020         RCU_READ_LOCK_GUARD();
3021         fv = address_space_to_flatview(as);
3022         result = flatview_read(fv, addr, attrs, buf, len);
3023     }
3024 
3025     return result;
3026 }
3027 
3028 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3029                                 MemTxAttrs attrs,
3030                                 const void *buf, hwaddr len)
3031 {
3032     MemTxResult result = MEMTX_OK;
3033     FlatView *fv;
3034 
3035     if (len > 0) {
3036         RCU_READ_LOCK_GUARD();
3037         fv = address_space_to_flatview(as);
3038         result = flatview_write(fv, addr, attrs, buf, len);
3039     }
3040 
3041     return result;
3042 }
3043 
3044 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3045                              void *buf, hwaddr len, bool is_write)
3046 {
3047     if (is_write) {
3048         return address_space_write(as, addr, attrs, buf, len);
3049     } else {
3050         return address_space_read_full(as, addr, attrs, buf, len);
3051     }
3052 }
3053 
3054 MemTxResult address_space_set(AddressSpace *as, hwaddr addr,
3055                               uint8_t c, hwaddr len, MemTxAttrs attrs)
3056 {
3057 #define FILLBUF_SIZE 512
3058     uint8_t fillbuf[FILLBUF_SIZE];
3059     int l;
3060     MemTxResult error = MEMTX_OK;
3061 
3062     memset(fillbuf, c, FILLBUF_SIZE);
3063     while (len > 0) {
3064         l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
3065         error |= address_space_write(as, addr, attrs, fillbuf, l);
3066         len -= l;
3067         addr += l;
3068     }
3069 
3070     return error;
3071 }
3072 
3073 void cpu_physical_memory_rw(hwaddr addr, void *buf,
3074                             hwaddr len, bool is_write)
3075 {
3076     address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3077                      buf, len, is_write);
3078 }
3079 
3080 enum write_rom_type {
3081     WRITE_DATA,
3082     FLUSH_CACHE,
3083 };
3084 
3085 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
3086                                                            hwaddr addr,
3087                                                            MemTxAttrs attrs,
3088                                                            const void *ptr,
3089                                                            hwaddr len,
3090                                                            enum write_rom_type type)
3091 {
3092     hwaddr l;
3093     uint8_t *ram_ptr;
3094     hwaddr addr1;
3095     MemoryRegion *mr;
3096     const uint8_t *buf = ptr;
3097 
3098     RCU_READ_LOCK_GUARD();
3099     while (len > 0) {
3100         l = len;
3101         mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
3102 
3103         if (!(memory_region_is_ram(mr) ||
3104               memory_region_is_romd(mr))) {
3105             l = memory_access_size(mr, l, addr1);
3106         } else {
3107             /* ROM/RAM case */
3108             ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3109             switch (type) {
3110             case WRITE_DATA:
3111                 memcpy(ram_ptr, buf, l);
3112                 invalidate_and_set_dirty(mr, addr1, l);
3113                 break;
3114             case FLUSH_CACHE:
3115                 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
3116                 break;
3117             }
3118         }
3119         len -= l;
3120         buf += l;
3121         addr += l;
3122     }
3123     return MEMTX_OK;
3124 }
3125 
3126 /* used for ROM loading : can write in RAM and ROM */
3127 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
3128                                     MemTxAttrs attrs,
3129                                     const void *buf, hwaddr len)
3130 {
3131     return address_space_write_rom_internal(as, addr, attrs,
3132                                             buf, len, WRITE_DATA);
3133 }
3134 
3135 void cpu_flush_icache_range(hwaddr start, hwaddr len)
3136 {
3137     /*
3138      * This function should do the same thing as an icache flush that was
3139      * triggered from within the guest. For TCG we are always cache coherent,
3140      * so there is no need to flush anything. For KVM / Xen we need to flush
3141      * the host's instruction cache at least.
3142      */
3143     if (tcg_enabled()) {
3144         return;
3145     }
3146 
3147     address_space_write_rom_internal(&address_space_memory,
3148                                      start, MEMTXATTRS_UNSPECIFIED,
3149                                      NULL, len, FLUSH_CACHE);
3150 }
3151 
3152 /*
3153  * A magic value stored in the first 8 bytes of the bounce buffer struct. Used
3154  * to detect illegal pointers passed to address_space_unmap.
3155  */
3156 #define BOUNCE_BUFFER_MAGIC 0xb4017ceb4ffe12ed
3157 
3158 typedef struct {
3159     uint64_t magic;
3160     MemoryRegion *mr;
3161     hwaddr addr;
3162     size_t len;
3163     uint8_t buffer[];
3164 } BounceBuffer;
3165 
3166 static void
3167 address_space_unregister_map_client_do(AddressSpaceMapClient *client)
3168 {
3169     QLIST_REMOVE(client, link);
3170     g_free(client);
3171 }
3172 
3173 static void address_space_notify_map_clients_locked(AddressSpace *as)
3174 {
3175     AddressSpaceMapClient *client;
3176 
3177     while (!QLIST_EMPTY(&as->map_client_list)) {
3178         client = QLIST_FIRST(&as->map_client_list);
3179         qemu_bh_schedule(client->bh);
3180         address_space_unregister_map_client_do(client);
3181     }
3182 }
3183 
3184 void address_space_register_map_client(AddressSpace *as, QEMUBH *bh)
3185 {
3186     AddressSpaceMapClient *client = g_malloc(sizeof(*client));
3187 
3188     QEMU_LOCK_GUARD(&as->map_client_list_lock);
3189     client->bh = bh;
3190     QLIST_INSERT_HEAD(&as->map_client_list, client, link);
3191     /* Write map_client_list before reading bounce_buffer_size. */
3192     smp_mb();
3193     if (qatomic_read(&as->bounce_buffer_size) < as->max_bounce_buffer_size) {
3194         address_space_notify_map_clients_locked(as);
3195     }
3196 }
3197 
3198 void cpu_exec_init_all(void)
3199 {
3200     qemu_mutex_init(&ram_list.mutex);
3201     /* The data structures we set up here depend on knowing the page size,
3202      * so no more changes can be made after this point.
3203      * In an ideal world, nothing we did before we had finished the
3204      * machine setup would care about the target page size, and we could
3205      * do this much later, rather than requiring board models to state
3206      * up front what their requirements are.
3207      */
3208     finalize_target_page_bits();
3209     io_mem_init();
3210     memory_map_init();
3211 }
3212 
3213 void address_space_unregister_map_client(AddressSpace *as, QEMUBH *bh)
3214 {
3215     AddressSpaceMapClient *client;
3216 
3217     QEMU_LOCK_GUARD(&as->map_client_list_lock);
3218     QLIST_FOREACH(client, &as->map_client_list, link) {
3219         if (client->bh == bh) {
3220             address_space_unregister_map_client_do(client);
3221             break;
3222         }
3223     }
3224 }
3225 
3226 static void address_space_notify_map_clients(AddressSpace *as)
3227 {
3228     QEMU_LOCK_GUARD(&as->map_client_list_lock);
3229     address_space_notify_map_clients_locked(as);
3230 }
3231 
3232 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3233                                   bool is_write, MemTxAttrs attrs)
3234 {
3235     MemoryRegion *mr;
3236     hwaddr l, xlat;
3237 
3238     while (len > 0) {
3239         l = len;
3240         mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3241         if (!memory_access_is_direct(mr, is_write)) {
3242             l = memory_access_size(mr, l, addr);
3243             if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3244                 return false;
3245             }
3246         }
3247 
3248         len -= l;
3249         addr += l;
3250     }
3251     return true;
3252 }
3253 
3254 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3255                                 hwaddr len, bool is_write,
3256                                 MemTxAttrs attrs)
3257 {
3258     FlatView *fv;
3259 
3260     RCU_READ_LOCK_GUARD();
3261     fv = address_space_to_flatview(as);
3262     return flatview_access_valid(fv, addr, len, is_write, attrs);
3263 }
3264 
3265 static hwaddr
3266 flatview_extend_translation(FlatView *fv, hwaddr addr,
3267                             hwaddr target_len,
3268                             MemoryRegion *mr, hwaddr base, hwaddr len,
3269                             bool is_write, MemTxAttrs attrs)
3270 {
3271     hwaddr done = 0;
3272     hwaddr xlat;
3273     MemoryRegion *this_mr;
3274 
3275     for (;;) {
3276         target_len -= len;
3277         addr += len;
3278         done += len;
3279         if (target_len == 0) {
3280             return done;
3281         }
3282 
3283         len = target_len;
3284         this_mr = flatview_translate(fv, addr, &xlat,
3285                                      &len, is_write, attrs);
3286         if (this_mr != mr || xlat != base + done) {
3287             return done;
3288         }
3289     }
3290 }
3291 
3292 /* Map a physical memory region into a host virtual address.
3293  * May map a subset of the requested range, given by and returned in *plen.
3294  * May return NULL if resources needed to perform the mapping are exhausted.
3295  * Use only for reads OR writes - not for read-modify-write operations.
3296  * Use address_space_register_map_client() to know when retrying the map
3297  * operation is likely to succeed.
3298  */
3299 void *address_space_map(AddressSpace *as,
3300                         hwaddr addr,
3301                         hwaddr *plen,
3302                         bool is_write,
3303                         MemTxAttrs attrs)
3304 {
3305     hwaddr len = *plen;
3306     hwaddr l, xlat;
3307     MemoryRegion *mr;
3308     FlatView *fv;
3309 
3310     trace_address_space_map(as, addr, len, is_write, *(uint32_t *) &attrs);
3311 
3312     if (len == 0) {
3313         return NULL;
3314     }
3315 
3316     l = len;
3317     RCU_READ_LOCK_GUARD();
3318     fv = address_space_to_flatview(as);
3319     mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3320 
3321     if (!memory_access_is_direct(mr, is_write)) {
3322         size_t used = qatomic_read(&as->bounce_buffer_size);
3323         for (;;) {
3324             hwaddr alloc = MIN(as->max_bounce_buffer_size - used, l);
3325             size_t new_size = used + alloc;
3326             size_t actual =
3327                 qatomic_cmpxchg(&as->bounce_buffer_size, used, new_size);
3328             if (actual == used) {
3329                 l = alloc;
3330                 break;
3331             }
3332             used = actual;
3333         }
3334 
3335         if (l == 0) {
3336             *plen = 0;
3337             return NULL;
3338         }
3339 
3340         BounceBuffer *bounce = g_malloc0(l + sizeof(BounceBuffer));
3341         bounce->magic = BOUNCE_BUFFER_MAGIC;
3342         memory_region_ref(mr);
3343         bounce->mr = mr;
3344         bounce->addr = addr;
3345         bounce->len = l;
3346 
3347         if (!is_write) {
3348             flatview_read(fv, addr, attrs,
3349                           bounce->buffer, l);
3350         }
3351 
3352         *plen = l;
3353         return bounce->buffer;
3354     }
3355 
3356     memory_region_ref(mr);
3357     *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3358                                         l, is_write, attrs);
3359     fuzz_dma_read_cb(addr, *plen, mr);
3360     return qemu_ram_ptr_length(mr->ram_block, xlat, plen, true, is_write);
3361 }
3362 
3363 /* Unmaps a memory region previously mapped by address_space_map().
3364  * Will also mark the memory as dirty if is_write is true.  access_len gives
3365  * the amount of memory that was actually read or written by the caller.
3366  */
3367 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3368                          bool is_write, hwaddr access_len)
3369 {
3370     MemoryRegion *mr;
3371     ram_addr_t addr1;
3372 
3373     mr = memory_region_from_host(buffer, &addr1);
3374     if (mr != NULL) {
3375         if (is_write) {
3376             invalidate_and_set_dirty(mr, addr1, access_len);
3377         }
3378         if (xen_enabled()) {
3379             xen_invalidate_map_cache_entry(buffer);
3380         }
3381         memory_region_unref(mr);
3382         return;
3383     }
3384 
3385 
3386     BounceBuffer *bounce = container_of(buffer, BounceBuffer, buffer);
3387     assert(bounce->magic == BOUNCE_BUFFER_MAGIC);
3388 
3389     if (is_write) {
3390         address_space_write(as, bounce->addr, MEMTXATTRS_UNSPECIFIED,
3391                             bounce->buffer, access_len);
3392     }
3393 
3394     qatomic_sub(&as->bounce_buffer_size, bounce->len);
3395     bounce->magic = ~BOUNCE_BUFFER_MAGIC;
3396     memory_region_unref(bounce->mr);
3397     g_free(bounce);
3398     /* Write bounce_buffer_size before reading map_client_list. */
3399     smp_mb();
3400     address_space_notify_map_clients(as);
3401 }
3402 
3403 void *cpu_physical_memory_map(hwaddr addr,
3404                               hwaddr *plen,
3405                               bool is_write)
3406 {
3407     return address_space_map(&address_space_memory, addr, plen, is_write,
3408                              MEMTXATTRS_UNSPECIFIED);
3409 }
3410 
3411 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3412                                bool is_write, hwaddr access_len)
3413 {
3414     return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3415 }
3416 
3417 #define ARG1_DECL                AddressSpace *as
3418 #define ARG1                     as
3419 #define SUFFIX
3420 #define TRANSLATE(...)           address_space_translate(as, __VA_ARGS__)
3421 #define RCU_READ_LOCK(...)       rcu_read_lock()
3422 #define RCU_READ_UNLOCK(...)     rcu_read_unlock()
3423 #include "memory_ldst.c.inc"
3424 
3425 int64_t address_space_cache_init(MemoryRegionCache *cache,
3426                                  AddressSpace *as,
3427                                  hwaddr addr,
3428                                  hwaddr len,
3429                                  bool is_write)
3430 {
3431     AddressSpaceDispatch *d;
3432     hwaddr l;
3433     MemoryRegion *mr;
3434     Int128 diff;
3435 
3436     assert(len > 0);
3437 
3438     l = len;
3439     cache->fv = address_space_get_flatview(as);
3440     d = flatview_to_dispatch(cache->fv);
3441     cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3442 
3443     /*
3444      * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3445      * Take that into account to compute how many bytes are there between
3446      * cache->xlat and the end of the section.
3447      */
3448     diff = int128_sub(cache->mrs.size,
3449                       int128_make64(cache->xlat - cache->mrs.offset_within_region));
3450     l = int128_get64(int128_min(diff, int128_make64(l)));
3451 
3452     mr = cache->mrs.mr;
3453     memory_region_ref(mr);
3454     if (memory_access_is_direct(mr, is_write)) {
3455         /* We don't care about the memory attributes here as we're only
3456          * doing this if we found actual RAM, which behaves the same
3457          * regardless of attributes; so UNSPECIFIED is fine.
3458          */
3459         l = flatview_extend_translation(cache->fv, addr, len, mr,
3460                                         cache->xlat, l, is_write,
3461                                         MEMTXATTRS_UNSPECIFIED);
3462         cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true,
3463                                          is_write);
3464     } else {
3465         cache->ptr = NULL;
3466     }
3467 
3468     cache->len = l;
3469     cache->is_write = is_write;
3470     return l;
3471 }
3472 
3473 void address_space_cache_invalidate(MemoryRegionCache *cache,
3474                                     hwaddr addr,
3475                                     hwaddr access_len)
3476 {
3477     assert(cache->is_write);
3478     if (likely(cache->ptr)) {
3479         invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3480     }
3481 }
3482 
3483 void address_space_cache_destroy(MemoryRegionCache *cache)
3484 {
3485     if (!cache->mrs.mr) {
3486         return;
3487     }
3488 
3489     if (xen_enabled()) {
3490         xen_invalidate_map_cache_entry(cache->ptr);
3491     }
3492     memory_region_unref(cache->mrs.mr);
3493     flatview_unref(cache->fv);
3494     cache->mrs.mr = NULL;
3495     cache->fv = NULL;
3496 }
3497 
3498 /* Called from RCU critical section.  This function has the same
3499  * semantics as address_space_translate, but it only works on a
3500  * predefined range of a MemoryRegion that was mapped with
3501  * address_space_cache_init.
3502  */
3503 static inline MemoryRegion *address_space_translate_cached(
3504     MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3505     hwaddr *plen, bool is_write, MemTxAttrs attrs)
3506 {
3507     MemoryRegionSection section;
3508     MemoryRegion *mr;
3509     IOMMUMemoryRegion *iommu_mr;
3510     AddressSpace *target_as;
3511 
3512     assert(!cache->ptr);
3513     *xlat = addr + cache->xlat;
3514 
3515     mr = cache->mrs.mr;
3516     iommu_mr = memory_region_get_iommu(mr);
3517     if (!iommu_mr) {
3518         /* MMIO region.  */
3519         return mr;
3520     }
3521 
3522     section = address_space_translate_iommu(iommu_mr, xlat, plen,
3523                                             NULL, is_write, true,
3524                                             &target_as, attrs);
3525     return section.mr;
3526 }
3527 
3528 /* Called within RCU critical section.  */
3529 static MemTxResult address_space_write_continue_cached(MemTxAttrs attrs,
3530                                                        const void *ptr,
3531                                                        hwaddr len,
3532                                                        hwaddr mr_addr,
3533                                                        hwaddr l,
3534                                                        MemoryRegion *mr)
3535 {
3536     MemTxResult result = MEMTX_OK;
3537     const uint8_t *buf = ptr;
3538 
3539     for (;;) {
3540         result |= flatview_write_continue_step(attrs, buf, len, mr_addr, &l,
3541                                                mr);
3542 
3543         len -= l;
3544         buf += l;
3545         mr_addr += l;
3546 
3547         if (!len) {
3548             break;
3549         }
3550 
3551         l = len;
3552     }
3553 
3554     return result;
3555 }
3556 
3557 /* Called within RCU critical section.  */
3558 static MemTxResult address_space_read_continue_cached(MemTxAttrs attrs,
3559                                                       void *ptr, hwaddr len,
3560                                                       hwaddr mr_addr, hwaddr l,
3561                                                       MemoryRegion *mr)
3562 {
3563     MemTxResult result = MEMTX_OK;
3564     uint8_t *buf = ptr;
3565 
3566     for (;;) {
3567         result |= flatview_read_continue_step(attrs, buf, len, mr_addr, &l, mr);
3568         len -= l;
3569         buf += l;
3570         mr_addr += l;
3571 
3572         if (!len) {
3573             break;
3574         }
3575         l = len;
3576     }
3577 
3578     return result;
3579 }
3580 
3581 /* Called from RCU critical section. address_space_read_cached uses this
3582  * out of line function when the target is an MMIO or IOMMU region.
3583  */
3584 MemTxResult
3585 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3586                                    void *buf, hwaddr len)
3587 {
3588     hwaddr mr_addr, l;
3589     MemoryRegion *mr;
3590 
3591     l = len;
3592     mr = address_space_translate_cached(cache, addr, &mr_addr, &l, false,
3593                                         MEMTXATTRS_UNSPECIFIED);
3594     return address_space_read_continue_cached(MEMTXATTRS_UNSPECIFIED,
3595                                               buf, len, mr_addr, l, mr);
3596 }
3597 
3598 /* Called from RCU critical section. address_space_write_cached uses this
3599  * out of line function when the target is an MMIO or IOMMU region.
3600  */
3601 MemTxResult
3602 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3603                                     const void *buf, hwaddr len)
3604 {
3605     hwaddr mr_addr, l;
3606     MemoryRegion *mr;
3607 
3608     l = len;
3609     mr = address_space_translate_cached(cache, addr, &mr_addr, &l, true,
3610                                         MEMTXATTRS_UNSPECIFIED);
3611     return address_space_write_continue_cached(MEMTXATTRS_UNSPECIFIED,
3612                                                buf, len, mr_addr, l, mr);
3613 }
3614 
3615 #define ARG1_DECL                MemoryRegionCache *cache
3616 #define ARG1                     cache
3617 #define SUFFIX                   _cached_slow
3618 #define TRANSLATE(...)           address_space_translate_cached(cache, __VA_ARGS__)
3619 #define RCU_READ_LOCK()          ((void)0)
3620 #define RCU_READ_UNLOCK()        ((void)0)
3621 #include "memory_ldst.c.inc"
3622 
3623 /* virtual memory access for debug (includes writing to ROM) */
3624 int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
3625                         void *ptr, size_t len, bool is_write)
3626 {
3627     hwaddr phys_addr;
3628     vaddr l, page;
3629     uint8_t *buf = ptr;
3630 
3631     cpu_synchronize_state(cpu);
3632     while (len > 0) {
3633         int asidx;
3634         MemTxAttrs attrs;
3635         MemTxResult res;
3636 
3637         page = addr & TARGET_PAGE_MASK;
3638         phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3639         asidx = cpu_asidx_from_attrs(cpu, attrs);
3640         /* if no physical page mapped, return an error */
3641         if (phys_addr == -1)
3642             return -1;
3643         l = (page + TARGET_PAGE_SIZE) - addr;
3644         if (l > len)
3645             l = len;
3646         phys_addr += (addr & ~TARGET_PAGE_MASK);
3647         if (is_write) {
3648             res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3649                                           attrs, buf, l);
3650         } else {
3651             res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3652                                      attrs, buf, l);
3653         }
3654         if (res != MEMTX_OK) {
3655             return -1;
3656         }
3657         len -= l;
3658         buf += l;
3659         addr += l;
3660     }
3661     return 0;
3662 }
3663 
3664 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3665 {
3666     MemoryRegion*mr;
3667     hwaddr l = 1;
3668 
3669     RCU_READ_LOCK_GUARD();
3670     mr = address_space_translate(&address_space_memory,
3671                                  phys_addr, &phys_addr, &l, false,
3672                                  MEMTXATTRS_UNSPECIFIED);
3673 
3674     return !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3675 }
3676 
3677 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3678 {
3679     RAMBlock *block;
3680     int ret = 0;
3681 
3682     RCU_READ_LOCK_GUARD();
3683     RAMBLOCK_FOREACH(block) {
3684         ret = func(block, opaque);
3685         if (ret) {
3686             break;
3687         }
3688     }
3689     return ret;
3690 }
3691 
3692 /*
3693  * Unmap pages of memory from start to start+length such that
3694  * they a) read as 0, b) Trigger whatever fault mechanism
3695  * the OS provides for postcopy.
3696  * The pages must be unmapped by the end of the function.
3697  * Returns: 0 on success, none-0 on failure
3698  *
3699  */
3700 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3701 {
3702     int ret = -1;
3703 
3704     uint8_t *host_startaddr = rb->host + start;
3705 
3706     if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3707         error_report("%s: Unaligned start address: %p",
3708                      __func__, host_startaddr);
3709         goto err;
3710     }
3711 
3712     if ((start + length) <= rb->max_length) {
3713         bool need_madvise, need_fallocate;
3714         if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3715             error_report("%s: Unaligned length: %zx", __func__, length);
3716             goto err;
3717         }
3718 
3719         errno = ENOTSUP; /* If we are missing MADVISE etc */
3720 
3721         /* The logic here is messy;
3722          *    madvise DONTNEED fails for hugepages
3723          *    fallocate works on hugepages and shmem
3724          *    shared anonymous memory requires madvise REMOVE
3725          */
3726         need_madvise = (rb->page_size == qemu_real_host_page_size());
3727         need_fallocate = rb->fd != -1;
3728         if (need_fallocate) {
3729             /* For a file, this causes the area of the file to be zero'd
3730              * if read, and for hugetlbfs also causes it to be unmapped
3731              * so a userfault will trigger.
3732              */
3733 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3734             /*
3735              * fallocate() will fail with readonly files. Let's print a
3736              * proper error message.
3737              */
3738             if (rb->flags & RAM_READONLY_FD) {
3739                 error_report("%s: Discarding RAM with readonly files is not"
3740                              " supported", __func__);
3741                 goto err;
3742 
3743             }
3744             /*
3745              * We'll discard data from the actual file, even though we only
3746              * have a MAP_PRIVATE mapping, possibly messing with other
3747              * MAP_PRIVATE/MAP_SHARED mappings. There is no easy way to
3748              * change that behavior whithout violating the promised
3749              * semantics of ram_block_discard_range().
3750              *
3751              * Only warn, because it works as long as nobody else uses that
3752              * file.
3753              */
3754             if (!qemu_ram_is_shared(rb)) {
3755                 warn_report_once("%s: Discarding RAM"
3756                                  " in private file mappings is possibly"
3757                                  " dangerous, because it will modify the"
3758                                  " underlying file and will affect other"
3759                                  " users of the file", __func__);
3760             }
3761 
3762             ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3763                             start, length);
3764             if (ret) {
3765                 ret = -errno;
3766                 error_report("%s: Failed to fallocate %s:%" PRIx64 " +%zx (%d)",
3767                              __func__, rb->idstr, start, length, ret);
3768                 goto err;
3769             }
3770 #else
3771             ret = -ENOSYS;
3772             error_report("%s: fallocate not available/file"
3773                          "%s:%" PRIx64 " +%zx (%d)",
3774                          __func__, rb->idstr, start, length, ret);
3775             goto err;
3776 #endif
3777         }
3778         if (need_madvise) {
3779             /* For normal RAM this causes it to be unmapped,
3780              * for shared memory it causes the local mapping to disappear
3781              * and to fall back on the file contents (which we just
3782              * fallocate'd away).
3783              */
3784 #if defined(CONFIG_MADVISE)
3785             if (qemu_ram_is_shared(rb) && rb->fd < 0) {
3786                 ret = madvise(host_startaddr, length, QEMU_MADV_REMOVE);
3787             } else {
3788                 ret = madvise(host_startaddr, length, QEMU_MADV_DONTNEED);
3789             }
3790             if (ret) {
3791                 ret = -errno;
3792                 error_report("%s: Failed to discard range "
3793                              "%s:%" PRIx64 " +%zx (%d)",
3794                              __func__, rb->idstr, start, length, ret);
3795                 goto err;
3796             }
3797 #else
3798             ret = -ENOSYS;
3799             error_report("%s: MADVISE not available %s:%" PRIx64 " +%zx (%d)",
3800                          __func__, rb->idstr, start, length, ret);
3801             goto err;
3802 #endif
3803         }
3804         trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3805                                       need_madvise, need_fallocate, ret);
3806     } else {
3807         error_report("%s: Overrun block '%s' (%" PRIu64 "/%zx/" RAM_ADDR_FMT")",
3808                      __func__, rb->idstr, start, length, rb->max_length);
3809     }
3810 
3811 err:
3812     return ret;
3813 }
3814 
3815 int ram_block_discard_guest_memfd_range(RAMBlock *rb, uint64_t start,
3816                                         size_t length)
3817 {
3818     int ret = -1;
3819 
3820 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3821     ret = fallocate(rb->guest_memfd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3822                     start, length);
3823 
3824     if (ret) {
3825         ret = -errno;
3826         error_report("%s: Failed to fallocate %s:%" PRIx64 " +%zx (%d)",
3827                      __func__, rb->idstr, start, length, ret);
3828     }
3829 #else
3830     ret = -ENOSYS;
3831     error_report("%s: fallocate not available %s:%" PRIx64 " +%zx (%d)",
3832                  __func__, rb->idstr, start, length, ret);
3833 #endif
3834 
3835     return ret;
3836 }
3837 
3838 bool ramblock_is_pmem(RAMBlock *rb)
3839 {
3840     return rb->flags & RAM_PMEM;
3841 }
3842 
3843 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3844 {
3845     if (start == end - 1) {
3846         qemu_printf("\t%3d      ", start);
3847     } else {
3848         qemu_printf("\t%3d..%-3d ", start, end - 1);
3849     }
3850     qemu_printf(" skip=%d ", skip);
3851     if (ptr == PHYS_MAP_NODE_NIL) {
3852         qemu_printf(" ptr=NIL");
3853     } else if (!skip) {
3854         qemu_printf(" ptr=#%d", ptr);
3855     } else {
3856         qemu_printf(" ptr=[%d]", ptr);
3857     }
3858     qemu_printf("\n");
3859 }
3860 
3861 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3862                            int128_sub((size), int128_one())) : 0)
3863 
3864 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3865 {
3866     int i;
3867 
3868     qemu_printf("  Dispatch\n");
3869     qemu_printf("    Physical sections\n");
3870 
3871     for (i = 0; i < d->map.sections_nb; ++i) {
3872         MemoryRegionSection *s = d->map.sections + i;
3873         const char *names[] = { " [unassigned]", " [not dirty]",
3874                                 " [ROM]", " [watch]" };
3875 
3876         qemu_printf("      #%d @" HWADDR_FMT_plx ".." HWADDR_FMT_plx
3877                     " %s%s%s%s%s",
3878             i,
3879             s->offset_within_address_space,
3880             s->offset_within_address_space + MR_SIZE(s->size),
3881             s->mr->name ? s->mr->name : "(noname)",
3882             i < ARRAY_SIZE(names) ? names[i] : "",
3883             s->mr == root ? " [ROOT]" : "",
3884             s == d->mru_section ? " [MRU]" : "",
3885             s->mr->is_iommu ? " [iommu]" : "");
3886 
3887         if (s->mr->alias) {
3888             qemu_printf(" alias=%s", s->mr->alias->name ?
3889                     s->mr->alias->name : "noname");
3890         }
3891         qemu_printf("\n");
3892     }
3893 
3894     qemu_printf("    Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3895                P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3896     for (i = 0; i < d->map.nodes_nb; ++i) {
3897         int j, jprev;
3898         PhysPageEntry prev;
3899         Node *n = d->map.nodes + i;
3900 
3901         qemu_printf("      [%d]\n", i);
3902 
3903         for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3904             PhysPageEntry *pe = *n + j;
3905 
3906             if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3907                 continue;
3908             }
3909 
3910             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3911 
3912             jprev = j;
3913             prev = *pe;
3914         }
3915 
3916         if (jprev != ARRAY_SIZE(*n)) {
3917             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3918         }
3919     }
3920 }
3921 
3922 /* Require any discards to work. */
3923 static unsigned int ram_block_discard_required_cnt;
3924 /* Require only coordinated discards to work. */
3925 static unsigned int ram_block_coordinated_discard_required_cnt;
3926 /* Disable any discards. */
3927 static unsigned int ram_block_discard_disabled_cnt;
3928 /* Disable only uncoordinated discards. */
3929 static unsigned int ram_block_uncoordinated_discard_disabled_cnt;
3930 static QemuMutex ram_block_discard_disable_mutex;
3931 
3932 static void ram_block_discard_disable_mutex_lock(void)
3933 {
3934     static gsize initialized;
3935 
3936     if (g_once_init_enter(&initialized)) {
3937         qemu_mutex_init(&ram_block_discard_disable_mutex);
3938         g_once_init_leave(&initialized, 1);
3939     }
3940     qemu_mutex_lock(&ram_block_discard_disable_mutex);
3941 }
3942 
3943 static void ram_block_discard_disable_mutex_unlock(void)
3944 {
3945     qemu_mutex_unlock(&ram_block_discard_disable_mutex);
3946 }
3947 
3948 int ram_block_discard_disable(bool state)
3949 {
3950     int ret = 0;
3951 
3952     ram_block_discard_disable_mutex_lock();
3953     if (!state) {
3954         ram_block_discard_disabled_cnt--;
3955     } else if (ram_block_discard_required_cnt ||
3956                ram_block_coordinated_discard_required_cnt) {
3957         ret = -EBUSY;
3958     } else {
3959         ram_block_discard_disabled_cnt++;
3960     }
3961     ram_block_discard_disable_mutex_unlock();
3962     return ret;
3963 }
3964 
3965 int ram_block_uncoordinated_discard_disable(bool state)
3966 {
3967     int ret = 0;
3968 
3969     ram_block_discard_disable_mutex_lock();
3970     if (!state) {
3971         ram_block_uncoordinated_discard_disabled_cnt--;
3972     } else if (ram_block_discard_required_cnt) {
3973         ret = -EBUSY;
3974     } else {
3975         ram_block_uncoordinated_discard_disabled_cnt++;
3976     }
3977     ram_block_discard_disable_mutex_unlock();
3978     return ret;
3979 }
3980 
3981 int ram_block_discard_require(bool state)
3982 {
3983     int ret = 0;
3984 
3985     ram_block_discard_disable_mutex_lock();
3986     if (!state) {
3987         ram_block_discard_required_cnt--;
3988     } else if (ram_block_discard_disabled_cnt ||
3989                ram_block_uncoordinated_discard_disabled_cnt) {
3990         ret = -EBUSY;
3991     } else {
3992         ram_block_discard_required_cnt++;
3993     }
3994     ram_block_discard_disable_mutex_unlock();
3995     return ret;
3996 }
3997 
3998 int ram_block_coordinated_discard_require(bool state)
3999 {
4000     int ret = 0;
4001 
4002     ram_block_discard_disable_mutex_lock();
4003     if (!state) {
4004         ram_block_coordinated_discard_required_cnt--;
4005     } else if (ram_block_discard_disabled_cnt) {
4006         ret = -EBUSY;
4007     } else {
4008         ram_block_coordinated_discard_required_cnt++;
4009     }
4010     ram_block_discard_disable_mutex_unlock();
4011     return ret;
4012 }
4013 
4014 bool ram_block_discard_is_disabled(void)
4015 {
4016     return qatomic_read(&ram_block_discard_disabled_cnt) ||
4017            qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt);
4018 }
4019 
4020 bool ram_block_discard_is_required(void)
4021 {
4022     return qatomic_read(&ram_block_discard_required_cnt) ||
4023            qatomic_read(&ram_block_coordinated_discard_required_cnt);
4024 }
4025