OSDN Git Service

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