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