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