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