OSDN Git Service

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