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