xref: /qemu/system/physmem.c (revision dbc6ae9c3b595e82e746178ce428e2f9a72db572)
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 "hw/xen/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 =
684         qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
685 
686     for (;;) {
687         section = address_space_translate_internal(d, addr, &addr, plen, false);
688 
689         iommu_mr = memory_region_get_iommu(section->mr);
690         if (!iommu_mr) {
691             break;
692         }
693 
694         imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
695 
696         iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
697         tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
698         /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
699          * doesn't short-cut its translation table walk.
700          */
701         iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
702         addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
703                 | (addr & iotlb.addr_mask));
704         /* Update the caller's prot bits to remove permissions the IOMMU
705          * is giving us a failure response for. If we get down to no
706          * permissions left at all we can give up now.
707          */
708         if (!(iotlb.perm & IOMMU_RO)) {
709             *prot &= ~(PAGE_READ | PAGE_EXEC);
710         }
711         if (!(iotlb.perm & IOMMU_WO)) {
712             *prot &= ~PAGE_WRITE;
713         }
714 
715         if (!*prot) {
716             goto translate_fail;
717         }
718 
719         d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
720     }
721 
722     assert(!memory_region_is_iommu(section->mr));
723     *xlat = addr;
724     return section;
725 
726 translate_fail:
727     /*
728      * We should be given a page-aligned address -- certainly
729      * tlb_set_page_with_attrs() does so.  The page offset of xlat
730      * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.
731      * The page portion of xlat will be logged by memory_region_access_valid()
732      * when this memory access is rejected, so use the original untranslated
733      * physical address.
734      */
735     assert((orig_addr & ~TARGET_PAGE_MASK) == 0);
736     *xlat = orig_addr;
737     return &d->map.sections[PHYS_SECTION_UNASSIGNED];
738 }
739 
740 void cpu_address_space_init(CPUState *cpu, int asidx,
741                             const char *prefix, MemoryRegion *mr)
742 {
743     CPUAddressSpace *newas;
744     AddressSpace *as = g_new0(AddressSpace, 1);
745     char *as_name;
746 
747     assert(mr);
748     as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
749     address_space_init(as, mr, as_name);
750     g_free(as_name);
751 
752     /* Target code should have set num_ases before calling us */
753     assert(asidx < cpu->num_ases);
754 
755     if (asidx == 0) {
756         /* address space 0 gets the convenience alias */
757         cpu->as = as;
758     }
759 
760     /* KVM cannot currently support multiple address spaces. */
761     assert(asidx == 0 || !kvm_enabled());
762 
763     if (!cpu->cpu_ases) {
764         cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
765     }
766 
767     newas = &cpu->cpu_ases[asidx];
768     newas->cpu = cpu;
769     newas->as = as;
770     if (tcg_enabled()) {
771         newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
772         newas->tcg_as_listener.commit = tcg_commit;
773         newas->tcg_as_listener.name = "tcg";
774         memory_listener_register(&newas->tcg_as_listener, as);
775     }
776 }
777 
778 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
779 {
780     /* Return the AddressSpace corresponding to the specified index */
781     return cpu->cpu_ases[asidx].as;
782 }
783 
784 /* Called from RCU critical section */
785 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
786 {
787     RAMBlock *block;
788 
789     block = qatomic_rcu_read(&ram_list.mru_block);
790     if (block && addr - block->offset < block->max_length) {
791         return block;
792     }
793     RAMBLOCK_FOREACH(block) {
794         if (addr - block->offset < block->max_length) {
795             goto found;
796         }
797     }
798 
799     fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
800     abort();
801 
802 found:
803     /* It is safe to write mru_block outside the iothread lock.  This
804      * is what happens:
805      *
806      *     mru_block = xxx
807      *     rcu_read_unlock()
808      *                                        xxx removed from list
809      *                  rcu_read_lock()
810      *                  read mru_block
811      *                                        mru_block = NULL;
812      *                                        call_rcu(reclaim_ramblock, xxx);
813      *                  rcu_read_unlock()
814      *
815      * qatomic_rcu_set is not needed here.  The block was already published
816      * when it was placed into the list.  Here we're just making an extra
817      * copy of the pointer.
818      */
819     ram_list.mru_block = block;
820     return block;
821 }
822 
823 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
824 {
825     CPUState *cpu;
826     ram_addr_t start1;
827     RAMBlock *block;
828     ram_addr_t end;
829 
830     assert(tcg_enabled());
831     end = TARGET_PAGE_ALIGN(start + length);
832     start &= TARGET_PAGE_MASK;
833 
834     RCU_READ_LOCK_GUARD();
835     block = qemu_get_ram_block(start);
836     assert(block == qemu_get_ram_block(end - 1));
837     start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
838     CPU_FOREACH(cpu) {
839         tlb_reset_dirty(cpu, start1, length);
840     }
841 }
842 
843 /* Note: start and end must be within the same ram block.  */
844 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
845                                               ram_addr_t length,
846                                               unsigned client)
847 {
848     DirtyMemoryBlocks *blocks;
849     unsigned long end, page, start_page;
850     bool dirty = false;
851     RAMBlock *ramblock;
852     uint64_t mr_offset, mr_size;
853 
854     if (length == 0) {
855         return false;
856     }
857 
858     end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
859     start_page = start >> TARGET_PAGE_BITS;
860     page = start_page;
861 
862     WITH_RCU_READ_LOCK_GUARD() {
863         blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
864         ramblock = qemu_get_ram_block(start);
865         /* Range sanity check on the ramblock */
866         assert(start >= ramblock->offset &&
867                start + length <= ramblock->offset + ramblock->used_length);
868 
869         while (page < end) {
870             unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
871             unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
872             unsigned long num = MIN(end - page,
873                                     DIRTY_MEMORY_BLOCK_SIZE - offset);
874 
875             dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
876                                                   offset, num);
877             page += num;
878         }
879 
880         mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
881         mr_size = (end - start_page) << TARGET_PAGE_BITS;
882         memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
883     }
884 
885     if (dirty && tcg_enabled()) {
886         tlb_reset_dirty_range_all(start, length);
887     }
888 
889     return dirty;
890 }
891 
892 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
893     (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
894 {
895     DirtyMemoryBlocks *blocks;
896     ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
897     unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
898     ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
899     ram_addr_t last  = QEMU_ALIGN_UP(start + length, align);
900     DirtyBitmapSnapshot *snap;
901     unsigned long page, end, dest;
902 
903     snap = g_malloc0(sizeof(*snap) +
904                      ((last - first) >> (TARGET_PAGE_BITS + 3)));
905     snap->start = first;
906     snap->end   = last;
907 
908     page = first >> TARGET_PAGE_BITS;
909     end  = last  >> TARGET_PAGE_BITS;
910     dest = 0;
911 
912     WITH_RCU_READ_LOCK_GUARD() {
913         blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
914 
915         while (page < end) {
916             unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
917             unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
918             unsigned long num = MIN(end - page,
919                                     DIRTY_MEMORY_BLOCK_SIZE - offset);
920 
921             assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
922             assert(QEMU_IS_ALIGNED(num,    (1 << BITS_PER_LEVEL)));
923             offset >>= BITS_PER_LEVEL;
924 
925             bitmap_copy_and_clear_atomic(snap->dirty + dest,
926                                          blocks->blocks[idx] + offset,
927                                          num);
928             page += num;
929             dest += num >> BITS_PER_LEVEL;
930         }
931     }
932 
933     if (tcg_enabled()) {
934         tlb_reset_dirty_range_all(start, length);
935     }
936 
937     memory_region_clear_dirty_bitmap(mr, offset, length);
938 
939     return snap;
940 }
941 
942 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
943                                             ram_addr_t start,
944                                             ram_addr_t length)
945 {
946     unsigned long page, end;
947 
948     assert(start >= snap->start);
949     assert(start + length <= snap->end);
950 
951     end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
952     page = (start - snap->start) >> TARGET_PAGE_BITS;
953 
954     while (page < end) {
955         if (test_bit(page, snap->dirty)) {
956             return true;
957         }
958         page++;
959     }
960     return false;
961 }
962 
963 /* Called from RCU critical section */
964 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
965                                        MemoryRegionSection *section)
966 {
967     AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
968     return section - d->map.sections;
969 }
970 
971 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
972                             uint16_t section);
973 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
974 
975 static uint16_t phys_section_add(PhysPageMap *map,
976                                  MemoryRegionSection *section)
977 {
978     /* The physical section number is ORed with a page-aligned
979      * pointer to produce the iotlb entries.  Thus it should
980      * never overflow into the page-aligned value.
981      */
982     assert(map->sections_nb < TARGET_PAGE_SIZE);
983 
984     if (map->sections_nb == map->sections_nb_alloc) {
985         map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
986         map->sections = g_renew(MemoryRegionSection, map->sections,
987                                 map->sections_nb_alloc);
988     }
989     map->sections[map->sections_nb] = *section;
990     memory_region_ref(section->mr);
991     return map->sections_nb++;
992 }
993 
994 static void phys_section_destroy(MemoryRegion *mr)
995 {
996     bool have_sub_page = mr->subpage;
997 
998     memory_region_unref(mr);
999 
1000     if (have_sub_page) {
1001         subpage_t *subpage = container_of(mr, subpage_t, iomem);
1002         object_unref(OBJECT(&subpage->iomem));
1003         g_free(subpage);
1004     }
1005 }
1006 
1007 static void phys_sections_free(PhysPageMap *map)
1008 {
1009     while (map->sections_nb > 0) {
1010         MemoryRegionSection *section = &map->sections[--map->sections_nb];
1011         phys_section_destroy(section->mr);
1012     }
1013     g_free(map->sections);
1014     g_free(map->nodes);
1015 }
1016 
1017 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1018 {
1019     AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1020     subpage_t *subpage;
1021     hwaddr base = section->offset_within_address_space
1022         & TARGET_PAGE_MASK;
1023     MemoryRegionSection *existing = phys_page_find(d, base);
1024     MemoryRegionSection subsection = {
1025         .offset_within_address_space = base,
1026         .size = int128_make64(TARGET_PAGE_SIZE),
1027     };
1028     hwaddr start, end;
1029 
1030     assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1031 
1032     if (!(existing->mr->subpage)) {
1033         subpage = subpage_init(fv, base);
1034         subsection.fv = fv;
1035         subsection.mr = &subpage->iomem;
1036         phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1037                       phys_section_add(&d->map, &subsection));
1038     } else {
1039         subpage = container_of(existing->mr, subpage_t, iomem);
1040     }
1041     start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1042     end = start + int128_get64(section->size) - 1;
1043     subpage_register(subpage, start, end,
1044                      phys_section_add(&d->map, section));
1045 }
1046 
1047 
1048 static void register_multipage(FlatView *fv,
1049                                MemoryRegionSection *section)
1050 {
1051     AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1052     hwaddr start_addr = section->offset_within_address_space;
1053     uint16_t section_index = phys_section_add(&d->map, section);
1054     uint64_t num_pages = int128_get64(int128_rshift(section->size,
1055                                                     TARGET_PAGE_BITS));
1056 
1057     assert(num_pages);
1058     phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1059 }
1060 
1061 /*
1062  * The range in *section* may look like this:
1063  *
1064  *      |s|PPPPPPP|s|
1065  *
1066  * where s stands for subpage and P for page.
1067  */
1068 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1069 {
1070     MemoryRegionSection remain = *section;
1071     Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1072 
1073     /* register first subpage */
1074     if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1075         uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1076                         - remain.offset_within_address_space;
1077 
1078         MemoryRegionSection now = remain;
1079         now.size = int128_min(int128_make64(left), now.size);
1080         register_subpage(fv, &now);
1081         if (int128_eq(remain.size, now.size)) {
1082             return;
1083         }
1084         remain.size = int128_sub(remain.size, now.size);
1085         remain.offset_within_address_space += int128_get64(now.size);
1086         remain.offset_within_region += int128_get64(now.size);
1087     }
1088 
1089     /* register whole pages */
1090     if (int128_ge(remain.size, page_size)) {
1091         MemoryRegionSection now = remain;
1092         now.size = int128_and(now.size, int128_neg(page_size));
1093         register_multipage(fv, &now);
1094         if (int128_eq(remain.size, now.size)) {
1095             return;
1096         }
1097         remain.size = int128_sub(remain.size, now.size);
1098         remain.offset_within_address_space += int128_get64(now.size);
1099         remain.offset_within_region += int128_get64(now.size);
1100     }
1101 
1102     /* register last subpage */
1103     register_subpage(fv, &remain);
1104 }
1105 
1106 void qemu_flush_coalesced_mmio_buffer(void)
1107 {
1108     if (kvm_enabled())
1109         kvm_flush_coalesced_mmio_buffer();
1110 }
1111 
1112 void qemu_mutex_lock_ramlist(void)
1113 {
1114     qemu_mutex_lock(&ram_list.mutex);
1115 }
1116 
1117 void qemu_mutex_unlock_ramlist(void)
1118 {
1119     qemu_mutex_unlock(&ram_list.mutex);
1120 }
1121 
1122 GString *ram_block_format(void)
1123 {
1124     RAMBlock *block;
1125     char *psize;
1126     GString *buf = g_string_new("");
1127 
1128     RCU_READ_LOCK_GUARD();
1129     g_string_append_printf(buf, "%24s %8s  %18s %18s %18s %18s %3s\n",
1130                            "Block Name", "PSize", "Offset", "Used", "Total",
1131                            "HVA", "RO");
1132 
1133     RAMBLOCK_FOREACH(block) {
1134         psize = size_to_str(block->page_size);
1135         g_string_append_printf(buf, "%24s %8s  0x%016" PRIx64 " 0x%016" PRIx64
1136                                " 0x%016" PRIx64 " 0x%016" PRIx64 " %3s\n",
1137                                block->idstr, psize,
1138                                (uint64_t)block->offset,
1139                                (uint64_t)block->used_length,
1140                                (uint64_t)block->max_length,
1141                                (uint64_t)(uintptr_t)block->host,
1142                                block->mr->readonly ? "ro" : "rw");
1143 
1144         g_free(psize);
1145     }
1146 
1147     return buf;
1148 }
1149 
1150 static int find_min_backend_pagesize(Object *obj, void *opaque)
1151 {
1152     long *hpsize_min = opaque;
1153 
1154     if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1155         HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1156         long hpsize = host_memory_backend_pagesize(backend);
1157 
1158         if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1159             *hpsize_min = hpsize;
1160         }
1161     }
1162 
1163     return 0;
1164 }
1165 
1166 static int find_max_backend_pagesize(Object *obj, void *opaque)
1167 {
1168     long *hpsize_max = opaque;
1169 
1170     if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1171         HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1172         long hpsize = host_memory_backend_pagesize(backend);
1173 
1174         if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1175             *hpsize_max = hpsize;
1176         }
1177     }
1178 
1179     return 0;
1180 }
1181 
1182 /*
1183  * TODO: We assume right now that all mapped host memory backends are
1184  * used as RAM, however some might be used for different purposes.
1185  */
1186 long qemu_minrampagesize(void)
1187 {
1188     long hpsize = LONG_MAX;
1189     Object *memdev_root = object_resolve_path("/objects", NULL);
1190 
1191     object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1192     return hpsize;
1193 }
1194 
1195 long qemu_maxrampagesize(void)
1196 {
1197     long pagesize = 0;
1198     Object *memdev_root = object_resolve_path("/objects", NULL);
1199 
1200     object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1201     return pagesize;
1202 }
1203 
1204 #ifdef CONFIG_POSIX
1205 static int64_t get_file_size(int fd)
1206 {
1207     int64_t size;
1208 #if defined(__linux__)
1209     struct stat st;
1210 
1211     if (fstat(fd, &st) < 0) {
1212         return -errno;
1213     }
1214 
1215     /* Special handling for devdax character devices */
1216     if (S_ISCHR(st.st_mode)) {
1217         g_autofree char *subsystem_path = NULL;
1218         g_autofree char *subsystem = NULL;
1219 
1220         subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1221                                          major(st.st_rdev), minor(st.st_rdev));
1222         subsystem = g_file_read_link(subsystem_path, NULL);
1223 
1224         if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1225             g_autofree char *size_path = NULL;
1226             g_autofree char *size_str = NULL;
1227 
1228             size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1229                                     major(st.st_rdev), minor(st.st_rdev));
1230 
1231             if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1232                 return g_ascii_strtoll(size_str, NULL, 0);
1233             }
1234         }
1235     }
1236 #endif /* defined(__linux__) */
1237 
1238     /* st.st_size may be zero for special files yet lseek(2) works */
1239     size = lseek(fd, 0, SEEK_END);
1240     if (size < 0) {
1241         return -errno;
1242     }
1243     return size;
1244 }
1245 
1246 static int64_t get_file_align(int fd)
1247 {
1248     int64_t align = -1;
1249 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1250     struct stat st;
1251 
1252     if (fstat(fd, &st) < 0) {
1253         return -errno;
1254     }
1255 
1256     /* Special handling for devdax character devices */
1257     if (S_ISCHR(st.st_mode)) {
1258         g_autofree char *path = NULL;
1259         g_autofree char *rpath = NULL;
1260         struct daxctl_ctx *ctx;
1261         struct daxctl_region *region;
1262         int rc = 0;
1263 
1264         path = g_strdup_printf("/sys/dev/char/%d:%d",
1265                     major(st.st_rdev), minor(st.st_rdev));
1266         rpath = realpath(path, NULL);
1267         if (!rpath) {
1268             return -errno;
1269         }
1270 
1271         rc = daxctl_new(&ctx);
1272         if (rc) {
1273             return -1;
1274         }
1275 
1276         daxctl_region_foreach(ctx, region) {
1277             if (strstr(rpath, daxctl_region_get_path(region))) {
1278                 align = daxctl_region_get_align(region);
1279                 break;
1280             }
1281         }
1282         daxctl_unref(ctx);
1283     }
1284 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1285 
1286     return align;
1287 }
1288 
1289 static int file_ram_open(const char *path,
1290                          const char *region_name,
1291                          bool readonly,
1292                          bool *created,
1293                          Error **errp)
1294 {
1295     char *filename;
1296     char *sanitized_name;
1297     char *c;
1298     int fd = -1;
1299 
1300     *created = false;
1301     for (;;) {
1302         fd = open(path, readonly ? O_RDONLY : O_RDWR);
1303         if (fd >= 0) {
1304             /* @path names an existing file, use it */
1305             break;
1306         }
1307         if (errno == ENOENT) {
1308             /* @path names a file that doesn't exist, create it */
1309             fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1310             if (fd >= 0) {
1311                 *created = true;
1312                 break;
1313             }
1314         } else if (errno == EISDIR) {
1315             /* @path names a directory, create a file there */
1316             /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1317             sanitized_name = g_strdup(region_name);
1318             for (c = sanitized_name; *c != '\0'; c++) {
1319                 if (*c == '/') {
1320                     *c = '_';
1321                 }
1322             }
1323 
1324             filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1325                                        sanitized_name);
1326             g_free(sanitized_name);
1327 
1328             fd = mkstemp(filename);
1329             if (fd >= 0) {
1330                 unlink(filename);
1331                 g_free(filename);
1332                 break;
1333             }
1334             g_free(filename);
1335         }
1336         if (errno != EEXIST && errno != EINTR) {
1337             error_setg_errno(errp, errno,
1338                              "can't open backing store %s for guest RAM",
1339                              path);
1340             return -1;
1341         }
1342         /*
1343          * Try again on EINTR and EEXIST.  The latter happens when
1344          * something else creates the file between our two open().
1345          */
1346     }
1347 
1348     return fd;
1349 }
1350 
1351 static void *file_ram_alloc(RAMBlock *block,
1352                             ram_addr_t memory,
1353                             int fd,
1354                             bool readonly,
1355                             bool truncate,
1356                             off_t offset,
1357                             Error **errp)
1358 {
1359     uint32_t qemu_map_flags;
1360     void *area;
1361 
1362     block->page_size = qemu_fd_getpagesize(fd);
1363     if (block->mr->align % block->page_size) {
1364         error_setg(errp, "alignment 0x%" PRIx64
1365                    " must be multiples of page size 0x%zx",
1366                    block->mr->align, block->page_size);
1367         return NULL;
1368     } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1369         error_setg(errp, "alignment 0x%" PRIx64
1370                    " must be a power of two", block->mr->align);
1371         return NULL;
1372     }
1373     block->mr->align = MAX(block->page_size, block->mr->align);
1374 #if defined(__s390x__)
1375     if (kvm_enabled()) {
1376         block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1377     }
1378 #endif
1379 
1380     if (memory < block->page_size) {
1381         error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1382                    "or larger than page size 0x%zx",
1383                    memory, block->page_size);
1384         return NULL;
1385     }
1386 
1387     memory = ROUND_UP(memory, block->page_size);
1388 
1389     /*
1390      * ftruncate is not supported by hugetlbfs in older
1391      * hosts, so don't bother bailing out on errors.
1392      * If anything goes wrong with it under other filesystems,
1393      * mmap will fail.
1394      *
1395      * Do not truncate the non-empty backend file to avoid corrupting
1396      * the existing data in the file. Disabling shrinking is not
1397      * enough. For example, the current vNVDIMM implementation stores
1398      * the guest NVDIMM labels at the end of the backend file. If the
1399      * backend file is later extended, QEMU will not be able to find
1400      * those labels. Therefore, extending the non-empty backend file
1401      * is disabled as well.
1402      */
1403     if (truncate && ftruncate(fd, memory)) {
1404         perror("ftruncate");
1405     }
1406 
1407     qemu_map_flags = readonly ? QEMU_MAP_READONLY : 0;
1408     qemu_map_flags |= (block->flags & RAM_SHARED) ? QEMU_MAP_SHARED : 0;
1409     qemu_map_flags |= (block->flags & RAM_PMEM) ? QEMU_MAP_SYNC : 0;
1410     qemu_map_flags |= (block->flags & RAM_NORESERVE) ? QEMU_MAP_NORESERVE : 0;
1411     area = qemu_ram_mmap(fd, memory, block->mr->align, qemu_map_flags, offset);
1412     if (area == MAP_FAILED) {
1413         error_setg_errno(errp, errno,
1414                          "unable to map backing store for guest RAM");
1415         return NULL;
1416     }
1417 
1418     block->fd = fd;
1419     return area;
1420 }
1421 #endif
1422 
1423 /* Allocate space within the ram_addr_t space that governs the
1424  * dirty bitmaps.
1425  * Called with the ramlist lock held.
1426  */
1427 static ram_addr_t find_ram_offset(ram_addr_t size)
1428 {
1429     RAMBlock *block, *next_block;
1430     ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1431 
1432     assert(size != 0); /* it would hand out same offset multiple times */
1433 
1434     if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1435         return 0;
1436     }
1437 
1438     RAMBLOCK_FOREACH(block) {
1439         ram_addr_t candidate, next = RAM_ADDR_MAX;
1440 
1441         /* Align blocks to start on a 'long' in the bitmap
1442          * which makes the bitmap sync'ing take the fast path.
1443          */
1444         candidate = block->offset + block->max_length;
1445         candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1446 
1447         /* Search for the closest following block
1448          * and find the gap.
1449          */
1450         RAMBLOCK_FOREACH(next_block) {
1451             if (next_block->offset >= candidate) {
1452                 next = MIN(next, next_block->offset);
1453             }
1454         }
1455 
1456         /* If it fits remember our place and remember the size
1457          * of gap, but keep going so that we might find a smaller
1458          * gap to fill so avoiding fragmentation.
1459          */
1460         if (next - candidate >= size && next - candidate < mingap) {
1461             offset = candidate;
1462             mingap = next - candidate;
1463         }
1464 
1465         trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1466     }
1467 
1468     if (offset == RAM_ADDR_MAX) {
1469         fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1470                 (uint64_t)size);
1471         abort();
1472     }
1473 
1474     trace_find_ram_offset(size, offset);
1475 
1476     return offset;
1477 }
1478 
1479 static unsigned long last_ram_page(void)
1480 {
1481     RAMBlock *block;
1482     ram_addr_t last = 0;
1483 
1484     RCU_READ_LOCK_GUARD();
1485     RAMBLOCK_FOREACH(block) {
1486         last = MAX(last, block->offset + block->max_length);
1487     }
1488     return last >> TARGET_PAGE_BITS;
1489 }
1490 
1491 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1492 {
1493     int ret;
1494 
1495     /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1496     if (!machine_dump_guest_core(current_machine)) {
1497         ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1498         if (ret) {
1499             perror("qemu_madvise");
1500             fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1501                             "but dump_guest_core=off specified\n");
1502         }
1503     }
1504 }
1505 
1506 const char *qemu_ram_get_idstr(RAMBlock *rb)
1507 {
1508     return rb->idstr;
1509 }
1510 
1511 void *qemu_ram_get_host_addr(RAMBlock *rb)
1512 {
1513     return rb->host;
1514 }
1515 
1516 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1517 {
1518     return rb->offset;
1519 }
1520 
1521 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1522 {
1523     return rb->used_length;
1524 }
1525 
1526 ram_addr_t qemu_ram_get_max_length(RAMBlock *rb)
1527 {
1528     return rb->max_length;
1529 }
1530 
1531 bool qemu_ram_is_shared(RAMBlock *rb)
1532 {
1533     return rb->flags & RAM_SHARED;
1534 }
1535 
1536 bool qemu_ram_is_noreserve(RAMBlock *rb)
1537 {
1538     return rb->flags & RAM_NORESERVE;
1539 }
1540 
1541 /* Note: Only set at the start of postcopy */
1542 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1543 {
1544     return rb->flags & RAM_UF_ZEROPAGE;
1545 }
1546 
1547 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1548 {
1549     rb->flags |= RAM_UF_ZEROPAGE;
1550 }
1551 
1552 bool qemu_ram_is_migratable(RAMBlock *rb)
1553 {
1554     return rb->flags & RAM_MIGRATABLE;
1555 }
1556 
1557 void qemu_ram_set_migratable(RAMBlock *rb)
1558 {
1559     rb->flags |= RAM_MIGRATABLE;
1560 }
1561 
1562 void qemu_ram_unset_migratable(RAMBlock *rb)
1563 {
1564     rb->flags &= ~RAM_MIGRATABLE;
1565 }
1566 
1567 int qemu_ram_get_fd(RAMBlock *rb)
1568 {
1569     return rb->fd;
1570 }
1571 
1572 /* Called with iothread lock held.  */
1573 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1574 {
1575     RAMBlock *block;
1576 
1577     assert(new_block);
1578     assert(!new_block->idstr[0]);
1579 
1580     if (dev) {
1581         char *id = qdev_get_dev_path(dev);
1582         if (id) {
1583             snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1584             g_free(id);
1585         }
1586     }
1587     pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1588 
1589     RCU_READ_LOCK_GUARD();
1590     RAMBLOCK_FOREACH(block) {
1591         if (block != new_block &&
1592             !strcmp(block->idstr, new_block->idstr)) {
1593             fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1594                     new_block->idstr);
1595             abort();
1596         }
1597     }
1598 }
1599 
1600 /* Called with iothread lock held.  */
1601 void qemu_ram_unset_idstr(RAMBlock *block)
1602 {
1603     /* FIXME: arch_init.c assumes that this is not called throughout
1604      * migration.  Ignore the problem since hot-unplug during migration
1605      * does not work anyway.
1606      */
1607     if (block) {
1608         memset(block->idstr, 0, sizeof(block->idstr));
1609     }
1610 }
1611 
1612 size_t qemu_ram_pagesize(RAMBlock *rb)
1613 {
1614     return rb->page_size;
1615 }
1616 
1617 /* Returns the largest size of page in use */
1618 size_t qemu_ram_pagesize_largest(void)
1619 {
1620     RAMBlock *block;
1621     size_t largest = 0;
1622 
1623     RAMBLOCK_FOREACH(block) {
1624         largest = MAX(largest, qemu_ram_pagesize(block));
1625     }
1626 
1627     return largest;
1628 }
1629 
1630 static int memory_try_enable_merging(void *addr, size_t len)
1631 {
1632     if (!machine_mem_merge(current_machine)) {
1633         /* disabled by the user */
1634         return 0;
1635     }
1636 
1637     return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1638 }
1639 
1640 /*
1641  * Resizing RAM while migrating can result in the migration being canceled.
1642  * Care has to be taken if the guest might have already detected the memory.
1643  *
1644  * As memory core doesn't know how is memory accessed, it is up to
1645  * resize callback to update device state and/or add assertions to detect
1646  * misuse, if necessary.
1647  */
1648 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1649 {
1650     const ram_addr_t oldsize = block->used_length;
1651     const ram_addr_t unaligned_size = newsize;
1652 
1653     assert(block);
1654 
1655     newsize = HOST_PAGE_ALIGN(newsize);
1656 
1657     if (block->used_length == newsize) {
1658         /*
1659          * We don't have to resize the ram block (which only knows aligned
1660          * sizes), however, we have to notify if the unaligned size changed.
1661          */
1662         if (unaligned_size != memory_region_size(block->mr)) {
1663             memory_region_set_size(block->mr, unaligned_size);
1664             if (block->resized) {
1665                 block->resized(block->idstr, unaligned_size, block->host);
1666             }
1667         }
1668         return 0;
1669     }
1670 
1671     if (!(block->flags & RAM_RESIZEABLE)) {
1672         error_setg_errno(errp, EINVAL,
1673                          "Size mismatch: %s: 0x" RAM_ADDR_FMT
1674                          " != 0x" RAM_ADDR_FMT, block->idstr,
1675                          newsize, block->used_length);
1676         return -EINVAL;
1677     }
1678 
1679     if (block->max_length < newsize) {
1680         error_setg_errno(errp, EINVAL,
1681                          "Size too large: %s: 0x" RAM_ADDR_FMT
1682                          " > 0x" RAM_ADDR_FMT, block->idstr,
1683                          newsize, block->max_length);
1684         return -EINVAL;
1685     }
1686 
1687     /* Notify before modifying the ram block and touching the bitmaps. */
1688     if (block->host) {
1689         ram_block_notify_resize(block->host, oldsize, newsize);
1690     }
1691 
1692     cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1693     block->used_length = newsize;
1694     cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1695                                         DIRTY_CLIENTS_ALL);
1696     memory_region_set_size(block->mr, unaligned_size);
1697     if (block->resized) {
1698         block->resized(block->idstr, unaligned_size, block->host);
1699     }
1700     return 0;
1701 }
1702 
1703 /*
1704  * Trigger sync on the given ram block for range [start, start + length]
1705  * with the backing store if one is available.
1706  * Otherwise no-op.
1707  * @Note: this is supposed to be a synchronous op.
1708  */
1709 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1710 {
1711     /* The requested range should fit in within the block range */
1712     g_assert((start + length) <= block->used_length);
1713 
1714 #ifdef CONFIG_LIBPMEM
1715     /* The lack of support for pmem should not block the sync */
1716     if (ramblock_is_pmem(block)) {
1717         void *addr = ramblock_ptr(block, start);
1718         pmem_persist(addr, length);
1719         return;
1720     }
1721 #endif
1722     if (block->fd >= 0) {
1723         /**
1724          * Case there is no support for PMEM or the memory has not been
1725          * specified as persistent (or is not one) - use the msync.
1726          * Less optimal but still achieves the same goal
1727          */
1728         void *addr = ramblock_ptr(block, start);
1729         if (qemu_msync(addr, length, block->fd)) {
1730             warn_report("%s: failed to sync memory range: start: "
1731                     RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1732                     __func__, start, length);
1733         }
1734     }
1735 }
1736 
1737 /* Called with ram_list.mutex held */
1738 static void dirty_memory_extend(ram_addr_t old_ram_size,
1739                                 ram_addr_t new_ram_size)
1740 {
1741     ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1742                                              DIRTY_MEMORY_BLOCK_SIZE);
1743     ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1744                                              DIRTY_MEMORY_BLOCK_SIZE);
1745     int i;
1746 
1747     /* Only need to extend if block count increased */
1748     if (new_num_blocks <= old_num_blocks) {
1749         return;
1750     }
1751 
1752     for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1753         DirtyMemoryBlocks *old_blocks;
1754         DirtyMemoryBlocks *new_blocks;
1755         int j;
1756 
1757         old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1758         new_blocks = g_malloc(sizeof(*new_blocks) +
1759                               sizeof(new_blocks->blocks[0]) * new_num_blocks);
1760 
1761         if (old_num_blocks) {
1762             memcpy(new_blocks->blocks, old_blocks->blocks,
1763                    old_num_blocks * sizeof(old_blocks->blocks[0]));
1764         }
1765 
1766         for (j = old_num_blocks; j < new_num_blocks; j++) {
1767             new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1768         }
1769 
1770         qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1771 
1772         if (old_blocks) {
1773             g_free_rcu(old_blocks, rcu);
1774         }
1775     }
1776 }
1777 
1778 static void ram_block_add(RAMBlock *new_block, Error **errp)
1779 {
1780     const bool noreserve = qemu_ram_is_noreserve(new_block);
1781     const bool shared = qemu_ram_is_shared(new_block);
1782     RAMBlock *block;
1783     RAMBlock *last_block = NULL;
1784     ram_addr_t old_ram_size, new_ram_size;
1785     Error *err = NULL;
1786 
1787     old_ram_size = last_ram_page();
1788 
1789     qemu_mutex_lock_ramlist();
1790     new_block->offset = find_ram_offset(new_block->max_length);
1791 
1792     if (!new_block->host) {
1793         if (xen_enabled()) {
1794             xen_ram_alloc(new_block->offset, new_block->max_length,
1795                           new_block->mr, &err);
1796             if (err) {
1797                 error_propagate(errp, err);
1798                 qemu_mutex_unlock_ramlist();
1799                 return;
1800             }
1801         } else {
1802             new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1803                                                   &new_block->mr->align,
1804                                                   shared, noreserve);
1805             if (!new_block->host) {
1806                 error_setg_errno(errp, errno,
1807                                  "cannot set up guest memory '%s'",
1808                                  memory_region_name(new_block->mr));
1809                 qemu_mutex_unlock_ramlist();
1810                 return;
1811             }
1812             memory_try_enable_merging(new_block->host, new_block->max_length);
1813         }
1814     }
1815 
1816     new_ram_size = MAX(old_ram_size,
1817               (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1818     if (new_ram_size > old_ram_size) {
1819         dirty_memory_extend(old_ram_size, new_ram_size);
1820     }
1821     /* Keep the list sorted from biggest to smallest block.  Unlike QTAILQ,
1822      * QLIST (which has an RCU-friendly variant) does not have insertion at
1823      * tail, so save the last element in last_block.
1824      */
1825     RAMBLOCK_FOREACH(block) {
1826         last_block = block;
1827         if (block->max_length < new_block->max_length) {
1828             break;
1829         }
1830     }
1831     if (block) {
1832         QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1833     } else if (last_block) {
1834         QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1835     } else { /* list is empty */
1836         QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1837     }
1838     ram_list.mru_block = NULL;
1839 
1840     /* Write list before version */
1841     smp_wmb();
1842     ram_list.version++;
1843     qemu_mutex_unlock_ramlist();
1844 
1845     cpu_physical_memory_set_dirty_range(new_block->offset,
1846                                         new_block->used_length,
1847                                         DIRTY_CLIENTS_ALL);
1848 
1849     if (new_block->host) {
1850         qemu_ram_setup_dump(new_block->host, new_block->max_length);
1851         qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1852         /*
1853          * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1854          * Configure it unless the machine is a qtest server, in which case
1855          * KVM is not used and it may be forked (eg for fuzzing purposes).
1856          */
1857         if (!qtest_enabled()) {
1858             qemu_madvise(new_block->host, new_block->max_length,
1859                          QEMU_MADV_DONTFORK);
1860         }
1861         ram_block_notify_add(new_block->host, new_block->used_length,
1862                              new_block->max_length);
1863     }
1864 }
1865 
1866 #ifdef CONFIG_POSIX
1867 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
1868                                  uint32_t ram_flags, int fd, off_t offset,
1869                                  bool readonly, Error **errp)
1870 {
1871     RAMBlock *new_block;
1872     Error *local_err = NULL;
1873     int64_t file_size, file_align;
1874 
1875     /* Just support these ram flags by now. */
1876     assert((ram_flags & ~(RAM_SHARED | RAM_PMEM | RAM_NORESERVE |
1877                           RAM_PROTECTED)) == 0);
1878 
1879     if (xen_enabled()) {
1880         error_setg(errp, "-mem-path not supported with Xen");
1881         return NULL;
1882     }
1883 
1884     if (kvm_enabled() && !kvm_has_sync_mmu()) {
1885         error_setg(errp,
1886                    "host lacks kvm mmu notifiers, -mem-path unsupported");
1887         return NULL;
1888     }
1889 
1890     size = HOST_PAGE_ALIGN(size);
1891     file_size = get_file_size(fd);
1892     if (file_size > 0 && file_size < size) {
1893         error_setg(errp, "backing store size 0x%" PRIx64
1894                    " does not match 'size' option 0x" RAM_ADDR_FMT,
1895                    file_size, size);
1896         return NULL;
1897     }
1898 
1899     file_align = get_file_align(fd);
1900     if (file_align > 0 && file_align > mr->align) {
1901         error_setg(errp, "backing store align 0x%" PRIx64
1902                    " is larger than 'align' option 0x%" PRIx64,
1903                    file_align, mr->align);
1904         return NULL;
1905     }
1906 
1907     new_block = g_malloc0(sizeof(*new_block));
1908     new_block->mr = mr;
1909     new_block->used_length = size;
1910     new_block->max_length = size;
1911     new_block->flags = ram_flags;
1912     new_block->host = file_ram_alloc(new_block, size, fd, readonly,
1913                                      !file_size, offset, errp);
1914     if (!new_block->host) {
1915         g_free(new_block);
1916         return NULL;
1917     }
1918 
1919     ram_block_add(new_block, &local_err);
1920     if (local_err) {
1921         g_free(new_block);
1922         error_propagate(errp, local_err);
1923         return NULL;
1924     }
1925     return new_block;
1926 
1927 }
1928 
1929 
1930 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
1931                                    uint32_t ram_flags, const char *mem_path,
1932                                    bool readonly, Error **errp)
1933 {
1934     int fd;
1935     bool created;
1936     RAMBlock *block;
1937 
1938     fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
1939                        errp);
1940     if (fd < 0) {
1941         return NULL;
1942     }
1943 
1944     block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, 0, readonly, errp);
1945     if (!block) {
1946         if (created) {
1947             unlink(mem_path);
1948         }
1949         close(fd);
1950         return NULL;
1951     }
1952 
1953     return block;
1954 }
1955 #endif
1956 
1957 static
1958 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
1959                                   void (*resized)(const char*,
1960                                                   uint64_t length,
1961                                                   void *host),
1962                                   void *host, uint32_t ram_flags,
1963                                   MemoryRegion *mr, Error **errp)
1964 {
1965     RAMBlock *new_block;
1966     Error *local_err = NULL;
1967 
1968     assert((ram_flags & ~(RAM_SHARED | RAM_RESIZEABLE | RAM_PREALLOC |
1969                           RAM_NORESERVE)) == 0);
1970     assert(!host ^ (ram_flags & RAM_PREALLOC));
1971 
1972     size = HOST_PAGE_ALIGN(size);
1973     max_size = HOST_PAGE_ALIGN(max_size);
1974     new_block = g_malloc0(sizeof(*new_block));
1975     new_block->mr = mr;
1976     new_block->resized = resized;
1977     new_block->used_length = size;
1978     new_block->max_length = max_size;
1979     assert(max_size >= size);
1980     new_block->fd = -1;
1981     new_block->page_size = qemu_real_host_page_size();
1982     new_block->host = host;
1983     new_block->flags = ram_flags;
1984     ram_block_add(new_block, &local_err);
1985     if (local_err) {
1986         g_free(new_block);
1987         error_propagate(errp, local_err);
1988         return NULL;
1989     }
1990     return new_block;
1991 }
1992 
1993 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
1994                                    MemoryRegion *mr, Error **errp)
1995 {
1996     return qemu_ram_alloc_internal(size, size, NULL, host, RAM_PREALLOC, mr,
1997                                    errp);
1998 }
1999 
2000 RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
2001                          MemoryRegion *mr, Error **errp)
2002 {
2003     assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE)) == 0);
2004     return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
2005 }
2006 
2007 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2008                                      void (*resized)(const char*,
2009                                                      uint64_t length,
2010                                                      void *host),
2011                                      MemoryRegion *mr, Error **errp)
2012 {
2013     return qemu_ram_alloc_internal(size, maxsz, resized, NULL,
2014                                    RAM_RESIZEABLE, mr, errp);
2015 }
2016 
2017 static void reclaim_ramblock(RAMBlock *block)
2018 {
2019     if (block->flags & RAM_PREALLOC) {
2020         ;
2021     } else if (xen_enabled()) {
2022         xen_invalidate_map_cache_entry(block->host);
2023 #ifndef _WIN32
2024     } else if (block->fd >= 0) {
2025         qemu_ram_munmap(block->fd, block->host, block->max_length);
2026         close(block->fd);
2027 #endif
2028     } else {
2029         qemu_anon_ram_free(block->host, block->max_length);
2030     }
2031     g_free(block);
2032 }
2033 
2034 void qemu_ram_free(RAMBlock *block)
2035 {
2036     if (!block) {
2037         return;
2038     }
2039 
2040     if (block->host) {
2041         ram_block_notify_remove(block->host, block->used_length,
2042                                 block->max_length);
2043     }
2044 
2045     qemu_mutex_lock_ramlist();
2046     QLIST_REMOVE_RCU(block, next);
2047     ram_list.mru_block = NULL;
2048     /* Write list before version */
2049     smp_wmb();
2050     ram_list.version++;
2051     call_rcu(block, reclaim_ramblock, rcu);
2052     qemu_mutex_unlock_ramlist();
2053 }
2054 
2055 #ifndef _WIN32
2056 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2057 {
2058     RAMBlock *block;
2059     ram_addr_t offset;
2060     int flags;
2061     void *area, *vaddr;
2062 
2063     RAMBLOCK_FOREACH(block) {
2064         offset = addr - block->offset;
2065         if (offset < block->max_length) {
2066             vaddr = ramblock_ptr(block, offset);
2067             if (block->flags & RAM_PREALLOC) {
2068                 ;
2069             } else if (xen_enabled()) {
2070                 abort();
2071             } else {
2072                 flags = MAP_FIXED;
2073                 flags |= block->flags & RAM_SHARED ?
2074                          MAP_SHARED : MAP_PRIVATE;
2075                 flags |= block->flags & RAM_NORESERVE ? MAP_NORESERVE : 0;
2076                 if (block->fd >= 0) {
2077                     area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2078                                 flags, block->fd, offset);
2079                 } else {
2080                     flags |= MAP_ANONYMOUS;
2081                     area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2082                                 flags, -1, 0);
2083                 }
2084                 if (area != vaddr) {
2085                     error_report("Could not remap addr: "
2086                                  RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2087                                  length, addr);
2088                     exit(1);
2089                 }
2090                 memory_try_enable_merging(vaddr, length);
2091                 qemu_ram_setup_dump(vaddr, length);
2092             }
2093         }
2094     }
2095 }
2096 #endif /* !_WIN32 */
2097 
2098 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2099  * This should not be used for general purpose DMA.  Use address_space_map
2100  * or address_space_rw instead. For local memory (e.g. video ram) that the
2101  * device owns, use memory_region_get_ram_ptr.
2102  *
2103  * Called within RCU critical section.
2104  */
2105 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2106 {
2107     RAMBlock *block = ram_block;
2108 
2109     if (block == NULL) {
2110         block = qemu_get_ram_block(addr);
2111         addr -= block->offset;
2112     }
2113 
2114     if (xen_enabled() && block->host == NULL) {
2115         /* We need to check if the requested address is in the RAM
2116          * because we don't want to map the entire memory in QEMU.
2117          * In that case just map until the end of the page.
2118          */
2119         if (block->offset == 0) {
2120             return xen_map_cache(addr, 0, 0, false);
2121         }
2122 
2123         block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2124     }
2125     return ramblock_ptr(block, addr);
2126 }
2127 
2128 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2129  * but takes a size argument.
2130  *
2131  * Called within RCU critical section.
2132  */
2133 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2134                                  hwaddr *size, bool lock)
2135 {
2136     RAMBlock *block = ram_block;
2137     if (*size == 0) {
2138         return NULL;
2139     }
2140 
2141     if (block == NULL) {
2142         block = qemu_get_ram_block(addr);
2143         addr -= block->offset;
2144     }
2145     *size = MIN(*size, block->max_length - addr);
2146 
2147     if (xen_enabled() && block->host == NULL) {
2148         /* We need to check if the requested address is in the RAM
2149          * because we don't want to map the entire memory in QEMU.
2150          * In that case just map the requested area.
2151          */
2152         if (block->offset == 0) {
2153             return xen_map_cache(addr, *size, lock, lock);
2154         }
2155 
2156         block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2157     }
2158 
2159     return ramblock_ptr(block, addr);
2160 }
2161 
2162 /* Return the offset of a hostpointer within a ramblock */
2163 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2164 {
2165     ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2166     assert((uintptr_t)host >= (uintptr_t)rb->host);
2167     assert(res < rb->max_length);
2168 
2169     return res;
2170 }
2171 
2172 /*
2173  * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2174  * in that RAMBlock.
2175  *
2176  * ptr: Host pointer to look up
2177  * round_offset: If true round the result offset down to a page boundary
2178  * *ram_addr: set to result ram_addr
2179  * *offset: set to result offset within the RAMBlock
2180  *
2181  * Returns: RAMBlock (or NULL if not found)
2182  *
2183  * By the time this function returns, the returned pointer is not protected
2184  * by RCU anymore.  If the caller is not within an RCU critical section and
2185  * does not hold the iothread lock, it must have other means of protecting the
2186  * pointer, such as a reference to the region that includes the incoming
2187  * ram_addr_t.
2188  */
2189 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2190                                    ram_addr_t *offset)
2191 {
2192     RAMBlock *block;
2193     uint8_t *host = ptr;
2194 
2195     if (xen_enabled()) {
2196         ram_addr_t ram_addr;
2197         RCU_READ_LOCK_GUARD();
2198         ram_addr = xen_ram_addr_from_mapcache(ptr);
2199         block = qemu_get_ram_block(ram_addr);
2200         if (block) {
2201             *offset = ram_addr - block->offset;
2202         }
2203         return block;
2204     }
2205 
2206     RCU_READ_LOCK_GUARD();
2207     block = qatomic_rcu_read(&ram_list.mru_block);
2208     if (block && block->host && host - block->host < block->max_length) {
2209         goto found;
2210     }
2211 
2212     RAMBLOCK_FOREACH(block) {
2213         /* This case append when the block is not mapped. */
2214         if (block->host == NULL) {
2215             continue;
2216         }
2217         if (host - block->host < block->max_length) {
2218             goto found;
2219         }
2220     }
2221 
2222     return NULL;
2223 
2224 found:
2225     *offset = (host - block->host);
2226     if (round_offset) {
2227         *offset &= TARGET_PAGE_MASK;
2228     }
2229     return block;
2230 }
2231 
2232 /*
2233  * Finds the named RAMBlock
2234  *
2235  * name: The name of RAMBlock to find
2236  *
2237  * Returns: RAMBlock (or NULL if not found)
2238  */
2239 RAMBlock *qemu_ram_block_by_name(const char *name)
2240 {
2241     RAMBlock *block;
2242 
2243     RAMBLOCK_FOREACH(block) {
2244         if (!strcmp(name, block->idstr)) {
2245             return block;
2246         }
2247     }
2248 
2249     return NULL;
2250 }
2251 
2252 /* Some of the softmmu routines need to translate from a host pointer
2253    (typically a TLB entry) back to a ram offset.  */
2254 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2255 {
2256     RAMBlock *block;
2257     ram_addr_t offset;
2258 
2259     block = qemu_ram_block_from_host(ptr, false, &offset);
2260     if (!block) {
2261         return RAM_ADDR_INVALID;
2262     }
2263 
2264     return block->offset + offset;
2265 }
2266 
2267 ram_addr_t qemu_ram_addr_from_host_nofail(void *ptr)
2268 {
2269     ram_addr_t ram_addr;
2270 
2271     ram_addr = qemu_ram_addr_from_host(ptr);
2272     if (ram_addr == RAM_ADDR_INVALID) {
2273         error_report("Bad ram pointer %p", ptr);
2274         abort();
2275     }
2276     return ram_addr;
2277 }
2278 
2279 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2280                                  MemTxAttrs attrs, void *buf, hwaddr len);
2281 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2282                                   const void *buf, hwaddr len);
2283 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2284                                   bool is_write, MemTxAttrs attrs);
2285 
2286 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2287                                 unsigned len, MemTxAttrs attrs)
2288 {
2289     subpage_t *subpage = opaque;
2290     uint8_t buf[8];
2291     MemTxResult res;
2292 
2293 #if defined(DEBUG_SUBPAGE)
2294     printf("%s: subpage %p len %u addr " HWADDR_FMT_plx "\n", __func__,
2295            subpage, len, addr);
2296 #endif
2297     res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2298     if (res) {
2299         return res;
2300     }
2301     *data = ldn_p(buf, len);
2302     return MEMTX_OK;
2303 }
2304 
2305 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2306                                  uint64_t value, unsigned len, MemTxAttrs attrs)
2307 {
2308     subpage_t *subpage = opaque;
2309     uint8_t buf[8];
2310 
2311 #if defined(DEBUG_SUBPAGE)
2312     printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
2313            " value %"PRIx64"\n",
2314            __func__, subpage, len, addr, value);
2315 #endif
2316     stn_p(buf, len, value);
2317     return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2318 }
2319 
2320 static bool subpage_accepts(void *opaque, hwaddr addr,
2321                             unsigned len, bool is_write,
2322                             MemTxAttrs attrs)
2323 {
2324     subpage_t *subpage = opaque;
2325 #if defined(DEBUG_SUBPAGE)
2326     printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx "\n",
2327            __func__, subpage, is_write ? 'w' : 'r', len, addr);
2328 #endif
2329 
2330     return flatview_access_valid(subpage->fv, addr + subpage->base,
2331                                  len, is_write, attrs);
2332 }
2333 
2334 static const MemoryRegionOps subpage_ops = {
2335     .read_with_attrs = subpage_read,
2336     .write_with_attrs = subpage_write,
2337     .impl.min_access_size = 1,
2338     .impl.max_access_size = 8,
2339     .valid.min_access_size = 1,
2340     .valid.max_access_size = 8,
2341     .valid.accepts = subpage_accepts,
2342     .endianness = DEVICE_NATIVE_ENDIAN,
2343 };
2344 
2345 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2346                             uint16_t section)
2347 {
2348     int idx, eidx;
2349 
2350     if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2351         return -1;
2352     idx = SUBPAGE_IDX(start);
2353     eidx = SUBPAGE_IDX(end);
2354 #if defined(DEBUG_SUBPAGE)
2355     printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2356            __func__, mmio, start, end, idx, eidx, section);
2357 #endif
2358     for (; idx <= eidx; idx++) {
2359         mmio->sub_section[idx] = section;
2360     }
2361 
2362     return 0;
2363 }
2364 
2365 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2366 {
2367     subpage_t *mmio;
2368 
2369     /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2370     mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2371     mmio->fv = fv;
2372     mmio->base = base;
2373     memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2374                           NULL, TARGET_PAGE_SIZE);
2375     mmio->iomem.subpage = true;
2376 #if defined(DEBUG_SUBPAGE)
2377     printf("%s: %p base " HWADDR_FMT_plx " len %08x\n", __func__,
2378            mmio, base, TARGET_PAGE_SIZE);
2379 #endif
2380 
2381     return mmio;
2382 }
2383 
2384 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2385 {
2386     assert(fv);
2387     MemoryRegionSection section = {
2388         .fv = fv,
2389         .mr = mr,
2390         .offset_within_address_space = 0,
2391         .offset_within_region = 0,
2392         .size = int128_2_64(),
2393     };
2394 
2395     return phys_section_add(map, &section);
2396 }
2397 
2398 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2399                                       hwaddr index, MemTxAttrs attrs)
2400 {
2401     int asidx = cpu_asidx_from_attrs(cpu, attrs);
2402     CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2403     AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2404     MemoryRegionSection *sections = d->map.sections;
2405 
2406     return &sections[index & ~TARGET_PAGE_MASK];
2407 }
2408 
2409 static void io_mem_init(void)
2410 {
2411     memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2412                           NULL, UINT64_MAX);
2413 }
2414 
2415 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2416 {
2417     AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2418     uint16_t n;
2419 
2420     n = dummy_section(&d->map, fv, &io_mem_unassigned);
2421     assert(n == PHYS_SECTION_UNASSIGNED);
2422 
2423     d->phys_map  = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2424 
2425     return d;
2426 }
2427 
2428 void address_space_dispatch_free(AddressSpaceDispatch *d)
2429 {
2430     phys_sections_free(&d->map);
2431     g_free(d);
2432 }
2433 
2434 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2435 {
2436 }
2437 
2438 static void tcg_log_global_after_sync(MemoryListener *listener)
2439 {
2440     CPUAddressSpace *cpuas;
2441 
2442     /* Wait for the CPU to end the current TB.  This avoids the following
2443      * incorrect race:
2444      *
2445      *      vCPU                         migration
2446      *      ----------------------       -------------------------
2447      *      TLB check -> slow path
2448      *        notdirty_mem_write
2449      *          write to RAM
2450      *          mark dirty
2451      *                                   clear dirty flag
2452      *      TLB check -> fast path
2453      *                                   read memory
2454      *        write to RAM
2455      *
2456      * by pushing the migration thread's memory read after the vCPU thread has
2457      * written the memory.
2458      */
2459     if (replay_mode == REPLAY_MODE_NONE) {
2460         /*
2461          * VGA can make calls to this function while updating the screen.
2462          * In record/replay mode this causes a deadlock, because
2463          * run_on_cpu waits for rr mutex. Therefore no races are possible
2464          * in this case and no need for making run_on_cpu when
2465          * record/replay is enabled.
2466          */
2467         cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2468         run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2469     }
2470 }
2471 
2472 static void tcg_commit(MemoryListener *listener)
2473 {
2474     CPUAddressSpace *cpuas;
2475     AddressSpaceDispatch *d;
2476 
2477     assert(tcg_enabled());
2478     /* since each CPU stores ram addresses in its TLB cache, we must
2479        reset the modified entries */
2480     cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2481     cpu_reloading_memory_map();
2482     /* The CPU and TLB are protected by the iothread lock.
2483      * We reload the dispatch pointer now because cpu_reloading_memory_map()
2484      * may have split the RCU critical section.
2485      */
2486     d = address_space_to_dispatch(cpuas->as);
2487     qatomic_rcu_set(&cpuas->memory_dispatch, d);
2488     tlb_flush(cpuas->cpu);
2489 }
2490 
2491 static void memory_map_init(void)
2492 {
2493     system_memory = g_malloc(sizeof(*system_memory));
2494 
2495     memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2496     address_space_init(&address_space_memory, system_memory, "memory");
2497 
2498     system_io = g_malloc(sizeof(*system_io));
2499     memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2500                           65536);
2501     address_space_init(&address_space_io, system_io, "I/O");
2502 }
2503 
2504 MemoryRegion *get_system_memory(void)
2505 {
2506     return system_memory;
2507 }
2508 
2509 MemoryRegion *get_system_io(void)
2510 {
2511     return system_io;
2512 }
2513 
2514 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2515                                      hwaddr length)
2516 {
2517     uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2518     addr += memory_region_get_ram_addr(mr);
2519 
2520     /* No early return if dirty_log_mask is or becomes 0, because
2521      * cpu_physical_memory_set_dirty_range will still call
2522      * xen_modified_memory.
2523      */
2524     if (dirty_log_mask) {
2525         dirty_log_mask =
2526             cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2527     }
2528     if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2529         assert(tcg_enabled());
2530         tb_invalidate_phys_range(addr, addr + length);
2531         dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2532     }
2533     cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2534 }
2535 
2536 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2537 {
2538     /*
2539      * In principle this function would work on other memory region types too,
2540      * but the ROM device use case is the only one where this operation is
2541      * necessary.  Other memory regions should use the
2542      * address_space_read/write() APIs.
2543      */
2544     assert(memory_region_is_romd(mr));
2545 
2546     invalidate_and_set_dirty(mr, addr, size);
2547 }
2548 
2549 int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2550 {
2551     unsigned access_size_max = mr->ops->valid.max_access_size;
2552 
2553     /* Regions are assumed to support 1-4 byte accesses unless
2554        otherwise specified.  */
2555     if (access_size_max == 0) {
2556         access_size_max = 4;
2557     }
2558 
2559     /* Bound the maximum access by the alignment of the address.  */
2560     if (!mr->ops->impl.unaligned) {
2561         unsigned align_size_max = addr & -addr;
2562         if (align_size_max != 0 && align_size_max < access_size_max) {
2563             access_size_max = align_size_max;
2564         }
2565     }
2566 
2567     /* Don't attempt accesses larger than the maximum.  */
2568     if (l > access_size_max) {
2569         l = access_size_max;
2570     }
2571     l = pow2floor(l);
2572 
2573     return l;
2574 }
2575 
2576 bool prepare_mmio_access(MemoryRegion *mr)
2577 {
2578     bool release_lock = false;
2579 
2580     if (!qemu_mutex_iothread_locked()) {
2581         qemu_mutex_lock_iothread();
2582         release_lock = true;
2583     }
2584     if (mr->flush_coalesced_mmio) {
2585         qemu_flush_coalesced_mmio_buffer();
2586     }
2587 
2588     return release_lock;
2589 }
2590 
2591 /**
2592  * flatview_access_allowed
2593  * @mr: #MemoryRegion to be accessed
2594  * @attrs: memory transaction attributes
2595  * @addr: address within that memory region
2596  * @len: the number of bytes to access
2597  *
2598  * Check if a memory transaction is allowed.
2599  *
2600  * Returns: true if transaction is allowed, false if denied.
2601  */
2602 static bool flatview_access_allowed(MemoryRegion *mr, MemTxAttrs attrs,
2603                                     hwaddr addr, hwaddr len)
2604 {
2605     if (likely(!attrs.memory)) {
2606         return true;
2607     }
2608     if (memory_region_is_ram(mr)) {
2609         return true;
2610     }
2611     qemu_log_mask(LOG_GUEST_ERROR,
2612                   "Invalid access to non-RAM device at "
2613                   "addr 0x%" HWADDR_PRIX ", size %" HWADDR_PRIu ", "
2614                   "region '%s'\n", addr, len, memory_region_name(mr));
2615     return false;
2616 }
2617 
2618 /* Called within RCU critical section.  */
2619 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2620                                            MemTxAttrs attrs,
2621                                            const void *ptr,
2622                                            hwaddr len, hwaddr addr1,
2623                                            hwaddr l, MemoryRegion *mr)
2624 {
2625     uint8_t *ram_ptr;
2626     uint64_t val;
2627     MemTxResult result = MEMTX_OK;
2628     bool release_lock = false;
2629     const uint8_t *buf = ptr;
2630 
2631     for (;;) {
2632         if (!flatview_access_allowed(mr, attrs, addr1, l)) {
2633             result |= MEMTX_ACCESS_ERROR;
2634             /* Keep going. */
2635         } else if (!memory_access_is_direct(mr, true)) {
2636             release_lock |= prepare_mmio_access(mr);
2637             l = memory_access_size(mr, l, addr1);
2638             /* XXX: could force current_cpu to NULL to avoid
2639                potential bugs */
2640             val = ldn_he_p(buf, l);
2641             result |= memory_region_dispatch_write(mr, addr1, val,
2642                                                    size_memop(l), attrs);
2643         } else {
2644             /* RAM case */
2645             ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2646             memmove(ram_ptr, buf, l);
2647             invalidate_and_set_dirty(mr, addr1, l);
2648         }
2649 
2650         if (release_lock) {
2651             qemu_mutex_unlock_iothread();
2652             release_lock = false;
2653         }
2654 
2655         len -= l;
2656         buf += l;
2657         addr += l;
2658 
2659         if (!len) {
2660             break;
2661         }
2662 
2663         l = len;
2664         mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2665     }
2666 
2667     return result;
2668 }
2669 
2670 /* Called from RCU critical section.  */
2671 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2672                                   const void *buf, hwaddr len)
2673 {
2674     hwaddr l;
2675     hwaddr addr1;
2676     MemoryRegion *mr;
2677 
2678     l = len;
2679     mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2680     if (!flatview_access_allowed(mr, attrs, addr, len)) {
2681         return MEMTX_ACCESS_ERROR;
2682     }
2683     return flatview_write_continue(fv, addr, attrs, buf, len,
2684                                    addr1, l, mr);
2685 }
2686 
2687 /* Called within RCU critical section.  */
2688 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2689                                    MemTxAttrs attrs, void *ptr,
2690                                    hwaddr len, hwaddr addr1, hwaddr l,
2691                                    MemoryRegion *mr)
2692 {
2693     uint8_t *ram_ptr;
2694     uint64_t val;
2695     MemTxResult result = MEMTX_OK;
2696     bool release_lock = false;
2697     uint8_t *buf = ptr;
2698 
2699     fuzz_dma_read_cb(addr, len, mr);
2700     for (;;) {
2701         if (!flatview_access_allowed(mr, attrs, addr1, l)) {
2702             result |= MEMTX_ACCESS_ERROR;
2703             /* Keep going. */
2704         } else if (!memory_access_is_direct(mr, false)) {
2705             /* I/O case */
2706             release_lock |= prepare_mmio_access(mr);
2707             l = memory_access_size(mr, l, addr1);
2708             result |= memory_region_dispatch_read(mr, addr1, &val,
2709                                                   size_memop(l), attrs);
2710             stn_he_p(buf, l, val);
2711         } else {
2712             /* RAM case */
2713             ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2714             memcpy(buf, ram_ptr, l);
2715         }
2716 
2717         if (release_lock) {
2718             qemu_mutex_unlock_iothread();
2719             release_lock = false;
2720         }
2721 
2722         len -= l;
2723         buf += l;
2724         addr += l;
2725 
2726         if (!len) {
2727             break;
2728         }
2729 
2730         l = len;
2731         mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2732     }
2733 
2734     return result;
2735 }
2736 
2737 /* Called from RCU critical section.  */
2738 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2739                                  MemTxAttrs attrs, void *buf, hwaddr len)
2740 {
2741     hwaddr l;
2742     hwaddr addr1;
2743     MemoryRegion *mr;
2744 
2745     l = len;
2746     mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2747     if (!flatview_access_allowed(mr, attrs, addr, len)) {
2748         return MEMTX_ACCESS_ERROR;
2749     }
2750     return flatview_read_continue(fv, addr, attrs, buf, len,
2751                                   addr1, l, mr);
2752 }
2753 
2754 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2755                                     MemTxAttrs attrs, void *buf, hwaddr len)
2756 {
2757     MemTxResult result = MEMTX_OK;
2758     FlatView *fv;
2759 
2760     if (len > 0) {
2761         RCU_READ_LOCK_GUARD();
2762         fv = address_space_to_flatview(as);
2763         result = flatview_read(fv, addr, attrs, buf, len);
2764     }
2765 
2766     return result;
2767 }
2768 
2769 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2770                                 MemTxAttrs attrs,
2771                                 const void *buf, hwaddr len)
2772 {
2773     MemTxResult result = MEMTX_OK;
2774     FlatView *fv;
2775 
2776     if (len > 0) {
2777         RCU_READ_LOCK_GUARD();
2778         fv = address_space_to_flatview(as);
2779         result = flatview_write(fv, addr, attrs, buf, len);
2780     }
2781 
2782     return result;
2783 }
2784 
2785 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2786                              void *buf, hwaddr len, bool is_write)
2787 {
2788     if (is_write) {
2789         return address_space_write(as, addr, attrs, buf, len);
2790     } else {
2791         return address_space_read_full(as, addr, attrs, buf, len);
2792     }
2793 }
2794 
2795 MemTxResult address_space_set(AddressSpace *as, hwaddr addr,
2796                               uint8_t c, hwaddr len, MemTxAttrs attrs)
2797 {
2798 #define FILLBUF_SIZE 512
2799     uint8_t fillbuf[FILLBUF_SIZE];
2800     int l;
2801     MemTxResult error = MEMTX_OK;
2802 
2803     memset(fillbuf, c, FILLBUF_SIZE);
2804     while (len > 0) {
2805         l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
2806         error |= address_space_write(as, addr, attrs, fillbuf, l);
2807         len -= l;
2808         addr += l;
2809     }
2810 
2811     return error;
2812 }
2813 
2814 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2815                             hwaddr len, bool is_write)
2816 {
2817     address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2818                      buf, len, is_write);
2819 }
2820 
2821 enum write_rom_type {
2822     WRITE_DATA,
2823     FLUSH_CACHE,
2824 };
2825 
2826 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2827                                                            hwaddr addr,
2828                                                            MemTxAttrs attrs,
2829                                                            const void *ptr,
2830                                                            hwaddr len,
2831                                                            enum write_rom_type type)
2832 {
2833     hwaddr l;
2834     uint8_t *ram_ptr;
2835     hwaddr addr1;
2836     MemoryRegion *mr;
2837     const uint8_t *buf = ptr;
2838 
2839     RCU_READ_LOCK_GUARD();
2840     while (len > 0) {
2841         l = len;
2842         mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2843 
2844         if (!(memory_region_is_ram(mr) ||
2845               memory_region_is_romd(mr))) {
2846             l = memory_access_size(mr, l, addr1);
2847         } else {
2848             /* ROM/RAM case */
2849             ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2850             switch (type) {
2851             case WRITE_DATA:
2852                 memcpy(ram_ptr, buf, l);
2853                 invalidate_and_set_dirty(mr, addr1, l);
2854                 break;
2855             case FLUSH_CACHE:
2856                 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2857                 break;
2858             }
2859         }
2860         len -= l;
2861         buf += l;
2862         addr += l;
2863     }
2864     return MEMTX_OK;
2865 }
2866 
2867 /* used for ROM loading : can write in RAM and ROM */
2868 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2869                                     MemTxAttrs attrs,
2870                                     const void *buf, hwaddr len)
2871 {
2872     return address_space_write_rom_internal(as, addr, attrs,
2873                                             buf, len, WRITE_DATA);
2874 }
2875 
2876 void cpu_flush_icache_range(hwaddr start, hwaddr len)
2877 {
2878     /*
2879      * This function should do the same thing as an icache flush that was
2880      * triggered from within the guest. For TCG we are always cache coherent,
2881      * so there is no need to flush anything. For KVM / Xen we need to flush
2882      * the host's instruction cache at least.
2883      */
2884     if (tcg_enabled()) {
2885         return;
2886     }
2887 
2888     address_space_write_rom_internal(&address_space_memory,
2889                                      start, MEMTXATTRS_UNSPECIFIED,
2890                                      NULL, len, FLUSH_CACHE);
2891 }
2892 
2893 typedef struct {
2894     MemoryRegion *mr;
2895     void *buffer;
2896     hwaddr addr;
2897     hwaddr len;
2898     bool in_use;
2899 } BounceBuffer;
2900 
2901 static BounceBuffer bounce;
2902 
2903 typedef struct MapClient {
2904     QEMUBH *bh;
2905     QLIST_ENTRY(MapClient) link;
2906 } MapClient;
2907 
2908 QemuMutex map_client_list_lock;
2909 static QLIST_HEAD(, MapClient) map_client_list
2910     = QLIST_HEAD_INITIALIZER(map_client_list);
2911 
2912 static void cpu_unregister_map_client_do(MapClient *client)
2913 {
2914     QLIST_REMOVE(client, link);
2915     g_free(client);
2916 }
2917 
2918 static void cpu_notify_map_clients_locked(void)
2919 {
2920     MapClient *client;
2921 
2922     while (!QLIST_EMPTY(&map_client_list)) {
2923         client = QLIST_FIRST(&map_client_list);
2924         qemu_bh_schedule(client->bh);
2925         cpu_unregister_map_client_do(client);
2926     }
2927 }
2928 
2929 void cpu_register_map_client(QEMUBH *bh)
2930 {
2931     MapClient *client = g_malloc(sizeof(*client));
2932 
2933     qemu_mutex_lock(&map_client_list_lock);
2934     client->bh = bh;
2935     QLIST_INSERT_HEAD(&map_client_list, client, link);
2936     if (!qatomic_read(&bounce.in_use)) {
2937         cpu_notify_map_clients_locked();
2938     }
2939     qemu_mutex_unlock(&map_client_list_lock);
2940 }
2941 
2942 void cpu_exec_init_all(void)
2943 {
2944     qemu_mutex_init(&ram_list.mutex);
2945     /* The data structures we set up here depend on knowing the page size,
2946      * so no more changes can be made after this point.
2947      * In an ideal world, nothing we did before we had finished the
2948      * machine setup would care about the target page size, and we could
2949      * do this much later, rather than requiring board models to state
2950      * up front what their requirements are.
2951      */
2952     finalize_target_page_bits();
2953     io_mem_init();
2954     memory_map_init();
2955     qemu_mutex_init(&map_client_list_lock);
2956 }
2957 
2958 void cpu_unregister_map_client(QEMUBH *bh)
2959 {
2960     MapClient *client;
2961 
2962     qemu_mutex_lock(&map_client_list_lock);
2963     QLIST_FOREACH(client, &map_client_list, link) {
2964         if (client->bh == bh) {
2965             cpu_unregister_map_client_do(client);
2966             break;
2967         }
2968     }
2969     qemu_mutex_unlock(&map_client_list_lock);
2970 }
2971 
2972 static void cpu_notify_map_clients(void)
2973 {
2974     qemu_mutex_lock(&map_client_list_lock);
2975     cpu_notify_map_clients_locked();
2976     qemu_mutex_unlock(&map_client_list_lock);
2977 }
2978 
2979 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2980                                   bool is_write, MemTxAttrs attrs)
2981 {
2982     MemoryRegion *mr;
2983     hwaddr l, xlat;
2984 
2985     while (len > 0) {
2986         l = len;
2987         mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
2988         if (!memory_access_is_direct(mr, is_write)) {
2989             l = memory_access_size(mr, l, addr);
2990             if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
2991                 return false;
2992             }
2993         }
2994 
2995         len -= l;
2996         addr += l;
2997     }
2998     return true;
2999 }
3000 
3001 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3002                                 hwaddr len, bool is_write,
3003                                 MemTxAttrs attrs)
3004 {
3005     FlatView *fv;
3006 
3007     RCU_READ_LOCK_GUARD();
3008     fv = address_space_to_flatview(as);
3009     return flatview_access_valid(fv, addr, len, is_write, attrs);
3010 }
3011 
3012 static hwaddr
3013 flatview_extend_translation(FlatView *fv, hwaddr addr,
3014                             hwaddr target_len,
3015                             MemoryRegion *mr, hwaddr base, hwaddr len,
3016                             bool is_write, MemTxAttrs attrs)
3017 {
3018     hwaddr done = 0;
3019     hwaddr xlat;
3020     MemoryRegion *this_mr;
3021 
3022     for (;;) {
3023         target_len -= len;
3024         addr += len;
3025         done += len;
3026         if (target_len == 0) {
3027             return done;
3028         }
3029 
3030         len = target_len;
3031         this_mr = flatview_translate(fv, addr, &xlat,
3032                                      &len, is_write, attrs);
3033         if (this_mr != mr || xlat != base + done) {
3034             return done;
3035         }
3036     }
3037 }
3038 
3039 /* Map a physical memory region into a host virtual address.
3040  * May map a subset of the requested range, given by and returned in *plen.
3041  * May return NULL if resources needed to perform the mapping are exhausted.
3042  * Use only for reads OR writes - not for read-modify-write operations.
3043  * Use cpu_register_map_client() to know when retrying the map operation is
3044  * likely to succeed.
3045  */
3046 void *address_space_map(AddressSpace *as,
3047                         hwaddr addr,
3048                         hwaddr *plen,
3049                         bool is_write,
3050                         MemTxAttrs attrs)
3051 {
3052     hwaddr len = *plen;
3053     hwaddr l, xlat;
3054     MemoryRegion *mr;
3055     FlatView *fv;
3056 
3057     if (len == 0) {
3058         return NULL;
3059     }
3060 
3061     l = len;
3062     RCU_READ_LOCK_GUARD();
3063     fv = address_space_to_flatview(as);
3064     mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3065 
3066     if (!memory_access_is_direct(mr, is_write)) {
3067         if (qatomic_xchg(&bounce.in_use, true)) {
3068             *plen = 0;
3069             return NULL;
3070         }
3071         /* Avoid unbounded allocations */
3072         l = MIN(l, TARGET_PAGE_SIZE);
3073         bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3074         bounce.addr = addr;
3075         bounce.len = l;
3076 
3077         memory_region_ref(mr);
3078         bounce.mr = mr;
3079         if (!is_write) {
3080             flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3081                                bounce.buffer, l);
3082         }
3083 
3084         *plen = l;
3085         return bounce.buffer;
3086     }
3087 
3088 
3089     memory_region_ref(mr);
3090     *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3091                                         l, is_write, attrs);
3092     fuzz_dma_read_cb(addr, *plen, mr);
3093     return qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3094 }
3095 
3096 /* Unmaps a memory region previously mapped by address_space_map().
3097  * Will also mark the memory as dirty if is_write is true.  access_len gives
3098  * the amount of memory that was actually read or written by the caller.
3099  */
3100 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3101                          bool is_write, hwaddr access_len)
3102 {
3103     if (buffer != bounce.buffer) {
3104         MemoryRegion *mr;
3105         ram_addr_t addr1;
3106 
3107         mr = memory_region_from_host(buffer, &addr1);
3108         assert(mr != NULL);
3109         if (is_write) {
3110             invalidate_and_set_dirty(mr, addr1, access_len);
3111         }
3112         if (xen_enabled()) {
3113             xen_invalidate_map_cache_entry(buffer);
3114         }
3115         memory_region_unref(mr);
3116         return;
3117     }
3118     if (is_write) {
3119         address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3120                             bounce.buffer, access_len);
3121     }
3122     qemu_vfree(bounce.buffer);
3123     bounce.buffer = NULL;
3124     memory_region_unref(bounce.mr);
3125     qatomic_mb_set(&bounce.in_use, false);
3126     cpu_notify_map_clients();
3127 }
3128 
3129 void *cpu_physical_memory_map(hwaddr addr,
3130                               hwaddr *plen,
3131                               bool is_write)
3132 {
3133     return address_space_map(&address_space_memory, addr, plen, is_write,
3134                              MEMTXATTRS_UNSPECIFIED);
3135 }
3136 
3137 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3138                                bool is_write, hwaddr access_len)
3139 {
3140     return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3141 }
3142 
3143 #define ARG1_DECL                AddressSpace *as
3144 #define ARG1                     as
3145 #define SUFFIX
3146 #define TRANSLATE(...)           address_space_translate(as, __VA_ARGS__)
3147 #define RCU_READ_LOCK(...)       rcu_read_lock()
3148 #define RCU_READ_UNLOCK(...)     rcu_read_unlock()
3149 #include "memory_ldst.c.inc"
3150 
3151 int64_t address_space_cache_init(MemoryRegionCache *cache,
3152                                  AddressSpace *as,
3153                                  hwaddr addr,
3154                                  hwaddr len,
3155                                  bool is_write)
3156 {
3157     AddressSpaceDispatch *d;
3158     hwaddr l;
3159     MemoryRegion *mr;
3160     Int128 diff;
3161 
3162     assert(len > 0);
3163 
3164     l = len;
3165     cache->fv = address_space_get_flatview(as);
3166     d = flatview_to_dispatch(cache->fv);
3167     cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3168 
3169     /*
3170      * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3171      * Take that into account to compute how many bytes are there between
3172      * cache->xlat and the end of the section.
3173      */
3174     diff = int128_sub(cache->mrs.size,
3175 		      int128_make64(cache->xlat - cache->mrs.offset_within_region));
3176     l = int128_get64(int128_min(diff, int128_make64(l)));
3177 
3178     mr = cache->mrs.mr;
3179     memory_region_ref(mr);
3180     if (memory_access_is_direct(mr, is_write)) {
3181         /* We don't care about the memory attributes here as we're only
3182          * doing this if we found actual RAM, which behaves the same
3183          * regardless of attributes; so UNSPECIFIED is fine.
3184          */
3185         l = flatview_extend_translation(cache->fv, addr, len, mr,
3186                                         cache->xlat, l, is_write,
3187                                         MEMTXATTRS_UNSPECIFIED);
3188         cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3189     } else {
3190         cache->ptr = NULL;
3191     }
3192 
3193     cache->len = l;
3194     cache->is_write = is_write;
3195     return l;
3196 }
3197 
3198 void address_space_cache_invalidate(MemoryRegionCache *cache,
3199                                     hwaddr addr,
3200                                     hwaddr access_len)
3201 {
3202     assert(cache->is_write);
3203     if (likely(cache->ptr)) {
3204         invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3205     }
3206 }
3207 
3208 void address_space_cache_destroy(MemoryRegionCache *cache)
3209 {
3210     if (!cache->mrs.mr) {
3211         return;
3212     }
3213 
3214     if (xen_enabled()) {
3215         xen_invalidate_map_cache_entry(cache->ptr);
3216     }
3217     memory_region_unref(cache->mrs.mr);
3218     flatview_unref(cache->fv);
3219     cache->mrs.mr = NULL;
3220     cache->fv = NULL;
3221 }
3222 
3223 /* Called from RCU critical section.  This function has the same
3224  * semantics as address_space_translate, but it only works on a
3225  * predefined range of a MemoryRegion that was mapped with
3226  * address_space_cache_init.
3227  */
3228 static inline MemoryRegion *address_space_translate_cached(
3229     MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3230     hwaddr *plen, bool is_write, MemTxAttrs attrs)
3231 {
3232     MemoryRegionSection section;
3233     MemoryRegion *mr;
3234     IOMMUMemoryRegion *iommu_mr;
3235     AddressSpace *target_as;
3236 
3237     assert(!cache->ptr);
3238     *xlat = addr + cache->xlat;
3239 
3240     mr = cache->mrs.mr;
3241     iommu_mr = memory_region_get_iommu(mr);
3242     if (!iommu_mr) {
3243         /* MMIO region.  */
3244         return mr;
3245     }
3246 
3247     section = address_space_translate_iommu(iommu_mr, xlat, plen,
3248                                             NULL, is_write, true,
3249                                             &target_as, attrs);
3250     return section.mr;
3251 }
3252 
3253 /* Called from RCU critical section. address_space_read_cached uses this
3254  * out of line function when the target is an MMIO or IOMMU region.
3255  */
3256 MemTxResult
3257 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3258                                    void *buf, hwaddr len)
3259 {
3260     hwaddr addr1, l;
3261     MemoryRegion *mr;
3262 
3263     l = len;
3264     mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3265                                         MEMTXATTRS_UNSPECIFIED);
3266     return flatview_read_continue(cache->fv,
3267                                   addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3268                                   addr1, l, mr);
3269 }
3270 
3271 /* Called from RCU critical section. address_space_write_cached uses this
3272  * out of line function when the target is an MMIO or IOMMU region.
3273  */
3274 MemTxResult
3275 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3276                                     const void *buf, hwaddr len)
3277 {
3278     hwaddr addr1, l;
3279     MemoryRegion *mr;
3280 
3281     l = len;
3282     mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3283                                         MEMTXATTRS_UNSPECIFIED);
3284     return flatview_write_continue(cache->fv,
3285                                    addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3286                                    addr1, l, mr);
3287 }
3288 
3289 #define ARG1_DECL                MemoryRegionCache *cache
3290 #define ARG1                     cache
3291 #define SUFFIX                   _cached_slow
3292 #define TRANSLATE(...)           address_space_translate_cached(cache, __VA_ARGS__)
3293 #define RCU_READ_LOCK()          ((void)0)
3294 #define RCU_READ_UNLOCK()        ((void)0)
3295 #include "memory_ldst.c.inc"
3296 
3297 /* virtual memory access for debug (includes writing to ROM) */
3298 int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
3299                         void *ptr, size_t len, bool is_write)
3300 {
3301     hwaddr phys_addr;
3302     vaddr l, page;
3303     uint8_t *buf = ptr;
3304 
3305     cpu_synchronize_state(cpu);
3306     while (len > 0) {
3307         int asidx;
3308         MemTxAttrs attrs;
3309         MemTxResult res;
3310 
3311         page = addr & TARGET_PAGE_MASK;
3312         phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3313         asidx = cpu_asidx_from_attrs(cpu, attrs);
3314         /* if no physical page mapped, return an error */
3315         if (phys_addr == -1)
3316             return -1;
3317         l = (page + TARGET_PAGE_SIZE) - addr;
3318         if (l > len)
3319             l = len;
3320         phys_addr += (addr & ~TARGET_PAGE_MASK);
3321         if (is_write) {
3322             res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3323                                           attrs, buf, l);
3324         } else {
3325             res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3326                                      attrs, buf, l);
3327         }
3328         if (res != MEMTX_OK) {
3329             return -1;
3330         }
3331         len -= l;
3332         buf += l;
3333         addr += l;
3334     }
3335     return 0;
3336 }
3337 
3338 /*
3339  * Allows code that needs to deal with migration bitmaps etc to still be built
3340  * target independent.
3341  */
3342 size_t qemu_target_page_size(void)
3343 {
3344     return TARGET_PAGE_SIZE;
3345 }
3346 
3347 int qemu_target_page_bits(void)
3348 {
3349     return TARGET_PAGE_BITS;
3350 }
3351 
3352 int qemu_target_page_bits_min(void)
3353 {
3354     return TARGET_PAGE_BITS_MIN;
3355 }
3356 
3357 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3358 {
3359     MemoryRegion*mr;
3360     hwaddr l = 1;
3361 
3362     RCU_READ_LOCK_GUARD();
3363     mr = address_space_translate(&address_space_memory,
3364                                  phys_addr, &phys_addr, &l, false,
3365                                  MEMTXATTRS_UNSPECIFIED);
3366 
3367     return !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3368 }
3369 
3370 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3371 {
3372     RAMBlock *block;
3373     int ret = 0;
3374 
3375     RCU_READ_LOCK_GUARD();
3376     RAMBLOCK_FOREACH(block) {
3377         ret = func(block, opaque);
3378         if (ret) {
3379             break;
3380         }
3381     }
3382     return ret;
3383 }
3384 
3385 /*
3386  * Unmap pages of memory from start to start+length such that
3387  * they a) read as 0, b) Trigger whatever fault mechanism
3388  * the OS provides for postcopy.
3389  * The pages must be unmapped by the end of the function.
3390  * Returns: 0 on success, none-0 on failure
3391  *
3392  */
3393 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3394 {
3395     int ret = -1;
3396 
3397     uint8_t *host_startaddr = rb->host + start;
3398 
3399     if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3400         error_report("ram_block_discard_range: Unaligned start address: %p",
3401                      host_startaddr);
3402         goto err;
3403     }
3404 
3405     if ((start + length) <= rb->max_length) {
3406         bool need_madvise, need_fallocate;
3407         if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3408             error_report("ram_block_discard_range: Unaligned length: %zx",
3409                          length);
3410             goto err;
3411         }
3412 
3413         errno = ENOTSUP; /* If we are missing MADVISE etc */
3414 
3415         /* The logic here is messy;
3416          *    madvise DONTNEED fails for hugepages
3417          *    fallocate works on hugepages and shmem
3418          *    shared anonymous memory requires madvise REMOVE
3419          */
3420         need_madvise = (rb->page_size == qemu_host_page_size);
3421         need_fallocate = rb->fd != -1;
3422         if (need_fallocate) {
3423             /* For a file, this causes the area of the file to be zero'd
3424              * if read, and for hugetlbfs also causes it to be unmapped
3425              * so a userfault will trigger.
3426              */
3427 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3428             ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3429                             start, length);
3430             if (ret) {
3431                 ret = -errno;
3432                 error_report("ram_block_discard_range: Failed to fallocate "
3433                              "%s:%" PRIx64 " +%zx (%d)",
3434                              rb->idstr, start, length, ret);
3435                 goto err;
3436             }
3437 #else
3438             ret = -ENOSYS;
3439             error_report("ram_block_discard_range: fallocate not available/file"
3440                          "%s:%" PRIx64 " +%zx (%d)",
3441                          rb->idstr, start, length, ret);
3442             goto err;
3443 #endif
3444         }
3445         if (need_madvise) {
3446             /* For normal RAM this causes it to be unmapped,
3447              * for shared memory it causes the local mapping to disappear
3448              * and to fall back on the file contents (which we just
3449              * fallocate'd away).
3450              */
3451 #if defined(CONFIG_MADVISE)
3452             if (qemu_ram_is_shared(rb) && rb->fd < 0) {
3453                 ret = madvise(host_startaddr, length, QEMU_MADV_REMOVE);
3454             } else {
3455                 ret = madvise(host_startaddr, length, QEMU_MADV_DONTNEED);
3456             }
3457             if (ret) {
3458                 ret = -errno;
3459                 error_report("ram_block_discard_range: Failed to discard range "
3460                              "%s:%" PRIx64 " +%zx (%d)",
3461                              rb->idstr, start, length, ret);
3462                 goto err;
3463             }
3464 #else
3465             ret = -ENOSYS;
3466             error_report("ram_block_discard_range: MADVISE not available"
3467                          "%s:%" PRIx64 " +%zx (%d)",
3468                          rb->idstr, start, length, ret);
3469             goto err;
3470 #endif
3471         }
3472         trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3473                                       need_madvise, need_fallocate, ret);
3474     } else {
3475         error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3476                      "/%zx/" RAM_ADDR_FMT")",
3477                      rb->idstr, start, length, rb->max_length);
3478     }
3479 
3480 err:
3481     return ret;
3482 }
3483 
3484 bool ramblock_is_pmem(RAMBlock *rb)
3485 {
3486     return rb->flags & RAM_PMEM;
3487 }
3488 
3489 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3490 {
3491     if (start == end - 1) {
3492         qemu_printf("\t%3d      ", start);
3493     } else {
3494         qemu_printf("\t%3d..%-3d ", start, end - 1);
3495     }
3496     qemu_printf(" skip=%d ", skip);
3497     if (ptr == PHYS_MAP_NODE_NIL) {
3498         qemu_printf(" ptr=NIL");
3499     } else if (!skip) {
3500         qemu_printf(" ptr=#%d", ptr);
3501     } else {
3502         qemu_printf(" ptr=[%d]", ptr);
3503     }
3504     qemu_printf("\n");
3505 }
3506 
3507 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3508                            int128_sub((size), int128_one())) : 0)
3509 
3510 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3511 {
3512     int i;
3513 
3514     qemu_printf("  Dispatch\n");
3515     qemu_printf("    Physical sections\n");
3516 
3517     for (i = 0; i < d->map.sections_nb; ++i) {
3518         MemoryRegionSection *s = d->map.sections + i;
3519         const char *names[] = { " [unassigned]", " [not dirty]",
3520                                 " [ROM]", " [watch]" };
3521 
3522         qemu_printf("      #%d @" HWADDR_FMT_plx ".." HWADDR_FMT_plx
3523                     " %s%s%s%s%s",
3524             i,
3525             s->offset_within_address_space,
3526             s->offset_within_address_space + MR_SIZE(s->size),
3527             s->mr->name ? s->mr->name : "(noname)",
3528             i < ARRAY_SIZE(names) ? names[i] : "",
3529             s->mr == root ? " [ROOT]" : "",
3530             s == d->mru_section ? " [MRU]" : "",
3531             s->mr->is_iommu ? " [iommu]" : "");
3532 
3533         if (s->mr->alias) {
3534             qemu_printf(" alias=%s", s->mr->alias->name ?
3535                     s->mr->alias->name : "noname");
3536         }
3537         qemu_printf("\n");
3538     }
3539 
3540     qemu_printf("    Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3541                P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3542     for (i = 0; i < d->map.nodes_nb; ++i) {
3543         int j, jprev;
3544         PhysPageEntry prev;
3545         Node *n = d->map.nodes + i;
3546 
3547         qemu_printf("      [%d]\n", i);
3548 
3549         for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3550             PhysPageEntry *pe = *n + j;
3551 
3552             if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3553                 continue;
3554             }
3555 
3556             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3557 
3558             jprev = j;
3559             prev = *pe;
3560         }
3561 
3562         if (jprev != ARRAY_SIZE(*n)) {
3563             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3564         }
3565     }
3566 }
3567 
3568 /* Require any discards to work. */
3569 static unsigned int ram_block_discard_required_cnt;
3570 /* Require only coordinated discards to work. */
3571 static unsigned int ram_block_coordinated_discard_required_cnt;
3572 /* Disable any discards. */
3573 static unsigned int ram_block_discard_disabled_cnt;
3574 /* Disable only uncoordinated discards. */
3575 static unsigned int ram_block_uncoordinated_discard_disabled_cnt;
3576 static QemuMutex ram_block_discard_disable_mutex;
3577 
3578 static void ram_block_discard_disable_mutex_lock(void)
3579 {
3580     static gsize initialized;
3581 
3582     if (g_once_init_enter(&initialized)) {
3583         qemu_mutex_init(&ram_block_discard_disable_mutex);
3584         g_once_init_leave(&initialized, 1);
3585     }
3586     qemu_mutex_lock(&ram_block_discard_disable_mutex);
3587 }
3588 
3589 static void ram_block_discard_disable_mutex_unlock(void)
3590 {
3591     qemu_mutex_unlock(&ram_block_discard_disable_mutex);
3592 }
3593 
3594 int ram_block_discard_disable(bool state)
3595 {
3596     int ret = 0;
3597 
3598     ram_block_discard_disable_mutex_lock();
3599     if (!state) {
3600         ram_block_discard_disabled_cnt--;
3601     } else if (ram_block_discard_required_cnt ||
3602                ram_block_coordinated_discard_required_cnt) {
3603         ret = -EBUSY;
3604     } else {
3605         ram_block_discard_disabled_cnt++;
3606     }
3607     ram_block_discard_disable_mutex_unlock();
3608     return ret;
3609 }
3610 
3611 int ram_block_uncoordinated_discard_disable(bool state)
3612 {
3613     int ret = 0;
3614 
3615     ram_block_discard_disable_mutex_lock();
3616     if (!state) {
3617         ram_block_uncoordinated_discard_disabled_cnt--;
3618     } else if (ram_block_discard_required_cnt) {
3619         ret = -EBUSY;
3620     } else {
3621         ram_block_uncoordinated_discard_disabled_cnt++;
3622     }
3623     ram_block_discard_disable_mutex_unlock();
3624     return ret;
3625 }
3626 
3627 int ram_block_discard_require(bool state)
3628 {
3629     int ret = 0;
3630 
3631     ram_block_discard_disable_mutex_lock();
3632     if (!state) {
3633         ram_block_discard_required_cnt--;
3634     } else if (ram_block_discard_disabled_cnt ||
3635                ram_block_uncoordinated_discard_disabled_cnt) {
3636         ret = -EBUSY;
3637     } else {
3638         ram_block_discard_required_cnt++;
3639     }
3640     ram_block_discard_disable_mutex_unlock();
3641     return ret;
3642 }
3643 
3644 int ram_block_coordinated_discard_require(bool state)
3645 {
3646     int ret = 0;
3647 
3648     ram_block_discard_disable_mutex_lock();
3649     if (!state) {
3650         ram_block_coordinated_discard_required_cnt--;
3651     } else if (ram_block_discard_disabled_cnt) {
3652         ret = -EBUSY;
3653     } else {
3654         ram_block_coordinated_discard_required_cnt++;
3655     }
3656     ram_block_discard_disable_mutex_unlock();
3657     return ret;
3658 }
3659 
3660 bool ram_block_discard_is_disabled(void)
3661 {
3662     return qatomic_read(&ram_block_discard_disabled_cnt) ||
3663            qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt);
3664 }
3665 
3666 bool ram_block_discard_is_required(void)
3667 {
3668     return qatomic_read(&ram_block_discard_required_cnt) ||
3669            qatomic_read(&ram_block_coordinated_discard_required_cnt);
3670 }
3671