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