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