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