hw/ppc/spapr_drc.c: use g_autofree in drc_unrealize()
[qemu.git] / softmmu / physmem.c
bloba13289a594aec9268d3bf44444a876703e09facc
1 /*
2 * RAM allocation and memory access
4 * Copyright (c) 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
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.
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/>.
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
26 #include "qemu/madvise.h"
28 #ifdef CONFIG_TCG
29 #include "hw/core/tcg-cpu-ops.h"
30 #endif /* CONFIG_TCG */
32 #include "exec/exec-all.h"
33 #include "exec/target_page.h"
34 #include "hw/qdev-core.h"
35 #include "hw/qdev-properties.h"
36 #include "hw/boards.h"
37 #include "hw/xen/xen.h"
38 #include "sysemu/kvm.h"
39 #include "sysemu/tcg.h"
40 #include "sysemu/qtest.h"
41 #include "qemu/timer.h"
42 #include "qemu/config-file.h"
43 #include "qemu/error-report.h"
44 #include "qemu/qemu-print.h"
45 #include "exec/memory.h"
46 #include "exec/ioport.h"
47 #include "sysemu/dma.h"
48 #include "sysemu/hostmem.h"
49 #include "sysemu/hw_accel.h"
50 #include "sysemu/xen-mapcache.h"
51 #include "trace/trace-root.h"
53 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
54 #include <linux/falloc.h>
55 #endif
57 #include "qemu/rcu_queue.h"
58 #include "qemu/main-loop.h"
59 #include "exec/translate-all.h"
60 #include "sysemu/replay.h"
62 #include "exec/memory-internal.h"
63 #include "exec/ram_addr.h"
64 #include "exec/log.h"
66 #include "qemu/pmem.h"
68 #include "migration/vmstate.h"
70 #include "qemu/range.h"
71 #ifndef _WIN32
72 #include "qemu/mmap-alloc.h"
73 #endif
75 #include "monitor/monitor.h"
77 #ifdef CONFIG_LIBDAXCTL
78 #include <daxctl/libdaxctl.h>
79 #endif
81 //#define DEBUG_SUBPAGE
83 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
84 * are protected by the ramlist lock.
86 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
88 static MemoryRegion *system_memory;
89 static MemoryRegion *system_io;
91 AddressSpace address_space_io;
92 AddressSpace address_space_memory;
94 static MemoryRegion io_mem_unassigned;
96 typedef struct PhysPageEntry PhysPageEntry;
98 struct PhysPageEntry {
99 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
100 uint32_t skip : 6;
101 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
102 uint32_t ptr : 26;
105 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
107 /* Size of the L2 (and L3, etc) page tables. */
108 #define ADDR_SPACE_BITS 64
110 #define P_L2_BITS 9
111 #define P_L2_SIZE (1 << P_L2_BITS)
113 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
115 typedef PhysPageEntry Node[P_L2_SIZE];
117 typedef struct PhysPageMap {
118 struct rcu_head rcu;
120 unsigned sections_nb;
121 unsigned sections_nb_alloc;
122 unsigned nodes_nb;
123 unsigned nodes_nb_alloc;
124 Node *nodes;
125 MemoryRegionSection *sections;
126 } PhysPageMap;
128 struct AddressSpaceDispatch {
129 MemoryRegionSection *mru_section;
130 /* This is a multi-level map on the physical address space.
131 * The bottom level has pointers to MemoryRegionSections.
133 PhysPageEntry phys_map;
134 PhysPageMap map;
137 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
138 typedef struct subpage_t {
139 MemoryRegion iomem;
140 FlatView *fv;
141 hwaddr base;
142 uint16_t sub_section[];
143 } subpage_t;
145 #define PHYS_SECTION_UNASSIGNED 0
147 static void io_mem_init(void);
148 static void memory_map_init(void);
149 static void tcg_log_global_after_sync(MemoryListener *listener);
150 static void tcg_commit(MemoryListener *listener);
153 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
154 * @cpu: the CPU whose AddressSpace this is
155 * @as: the AddressSpace itself
156 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
157 * @tcg_as_listener: listener for tracking changes to the AddressSpace
159 struct CPUAddressSpace {
160 CPUState *cpu;
161 AddressSpace *as;
162 struct AddressSpaceDispatch *memory_dispatch;
163 MemoryListener tcg_as_listener;
166 struct DirtyBitmapSnapshot {
167 ram_addr_t start;
168 ram_addr_t end;
169 unsigned long dirty[];
172 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
174 static unsigned alloc_hint = 16;
175 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
176 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
177 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
178 alloc_hint = map->nodes_nb_alloc;
182 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
184 unsigned i;
185 uint32_t ret;
186 PhysPageEntry e;
187 PhysPageEntry *p;
189 ret = map->nodes_nb++;
190 p = map->nodes[ret];
191 assert(ret != PHYS_MAP_NODE_NIL);
192 assert(ret != map->nodes_nb_alloc);
194 e.skip = leaf ? 0 : 1;
195 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
196 for (i = 0; i < P_L2_SIZE; ++i) {
197 memcpy(&p[i], &e, sizeof(e));
199 return ret;
202 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
203 hwaddr *index, uint64_t *nb, uint16_t leaf,
204 int level)
206 PhysPageEntry *p;
207 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
209 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
210 lp->ptr = phys_map_node_alloc(map, level == 0);
212 p = map->nodes[lp->ptr];
213 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
215 while (*nb && lp < &p[P_L2_SIZE]) {
216 if ((*index & (step - 1)) == 0 && *nb >= step) {
217 lp->skip = 0;
218 lp->ptr = leaf;
219 *index += step;
220 *nb -= step;
221 } else {
222 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
224 ++lp;
228 static void phys_page_set(AddressSpaceDispatch *d,
229 hwaddr index, uint64_t nb,
230 uint16_t leaf)
232 /* Wildly overreserve - it doesn't matter much. */
233 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
235 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
238 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
239 * and update our entry so we can skip it and go directly to the destination.
241 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
243 unsigned valid_ptr = P_L2_SIZE;
244 int valid = 0;
245 PhysPageEntry *p;
246 int i;
248 if (lp->ptr == PHYS_MAP_NODE_NIL) {
249 return;
252 p = nodes[lp->ptr];
253 for (i = 0; i < P_L2_SIZE; i++) {
254 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
255 continue;
258 valid_ptr = i;
259 valid++;
260 if (p[i].skip) {
261 phys_page_compact(&p[i], nodes);
265 /* We can only compress if there's only one child. */
266 if (valid != 1) {
267 return;
270 assert(valid_ptr < P_L2_SIZE);
272 /* Don't compress if it won't fit in the # of bits we have. */
273 if (P_L2_LEVELS >= (1 << 6) &&
274 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
275 return;
278 lp->ptr = p[valid_ptr].ptr;
279 if (!p[valid_ptr].skip) {
280 /* If our only child is a leaf, make this a leaf. */
281 /* By design, we should have made this node a leaf to begin with so we
282 * should never reach here.
283 * But since it's so simple to handle this, let's do it just in case we
284 * change this rule.
286 lp->skip = 0;
287 } else {
288 lp->skip += p[valid_ptr].skip;
292 void address_space_dispatch_compact(AddressSpaceDispatch *d)
294 if (d->phys_map.skip) {
295 phys_page_compact(&d->phys_map, d->map.nodes);
299 static inline bool section_covers_addr(const MemoryRegionSection *section,
300 hwaddr addr)
302 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
303 * the section must cover the entire address space.
305 return int128_gethi(section->size) ||
306 range_covers_byte(section->offset_within_address_space,
307 int128_getlo(section->size), addr);
310 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
312 PhysPageEntry lp = d->phys_map, *p;
313 Node *nodes = d->map.nodes;
314 MemoryRegionSection *sections = d->map.sections;
315 hwaddr index = addr >> TARGET_PAGE_BITS;
316 int i;
318 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
319 if (lp.ptr == PHYS_MAP_NODE_NIL) {
320 return &sections[PHYS_SECTION_UNASSIGNED];
322 p = nodes[lp.ptr];
323 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
326 if (section_covers_addr(&sections[lp.ptr], addr)) {
327 return &sections[lp.ptr];
328 } else {
329 return &sections[PHYS_SECTION_UNASSIGNED];
333 /* Called from RCU critical section */
334 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
335 hwaddr addr,
336 bool resolve_subpage)
338 MemoryRegionSection *section = qatomic_read(&d->mru_section);
339 subpage_t *subpage;
341 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
342 !section_covers_addr(section, addr)) {
343 section = phys_page_find(d, addr);
344 qatomic_set(&d->mru_section, section);
346 if (resolve_subpage && section->mr->subpage) {
347 subpage = container_of(section->mr, subpage_t, iomem);
348 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
350 return section;
353 /* Called from RCU critical section */
354 static MemoryRegionSection *
355 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
356 hwaddr *plen, bool resolve_subpage)
358 MemoryRegionSection *section;
359 MemoryRegion *mr;
360 Int128 diff;
362 section = address_space_lookup_region(d, addr, resolve_subpage);
363 /* Compute offset within MemoryRegionSection */
364 addr -= section->offset_within_address_space;
366 /* Compute offset within MemoryRegion */
367 *xlat = addr + section->offset_within_region;
369 mr = section->mr;
371 /* MMIO registers can be expected to perform full-width accesses based only
372 * on their address, without considering adjacent registers that could
373 * decode to completely different MemoryRegions. When such registers
374 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
375 * regions overlap wildly. For this reason we cannot clamp the accesses
376 * here.
378 * If the length is small (as is the case for address_space_ldl/stl),
379 * everything works fine. If the incoming length is large, however,
380 * the caller really has to do the clamping through memory_access_size.
382 if (memory_region_is_ram(mr)) {
383 diff = int128_sub(section->size, int128_make64(addr));
384 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
386 return section;
390 * address_space_translate_iommu - translate an address through an IOMMU
391 * memory region and then through the target address space.
393 * @iommu_mr: the IOMMU memory region that we start the translation from
394 * @addr: the address to be translated through the MMU
395 * @xlat: the translated address offset within the destination memory region.
396 * It cannot be %NULL.
397 * @plen_out: valid read/write length of the translated address. It
398 * cannot be %NULL.
399 * @page_mask_out: page mask for the translated address. This
400 * should only be meaningful for IOMMU translated
401 * addresses, since there may be huge pages that this bit
402 * would tell. It can be %NULL if we don't care about it.
403 * @is_write: whether the translation operation is for write
404 * @is_mmio: whether this can be MMIO, set true if it can
405 * @target_as: the address space targeted by the IOMMU
406 * @attrs: transaction attributes
408 * This function is called from RCU critical section. It is the common
409 * part of flatview_do_translate and address_space_translate_cached.
411 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
412 hwaddr *xlat,
413 hwaddr *plen_out,
414 hwaddr *page_mask_out,
415 bool is_write,
416 bool is_mmio,
417 AddressSpace **target_as,
418 MemTxAttrs attrs)
420 MemoryRegionSection *section;
421 hwaddr page_mask = (hwaddr)-1;
423 do {
424 hwaddr addr = *xlat;
425 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
426 int iommu_idx = 0;
427 IOMMUTLBEntry iotlb;
429 if (imrc->attrs_to_index) {
430 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
433 iotlb = imrc->translate(iommu_mr, addr, is_write ?
434 IOMMU_WO : IOMMU_RO, iommu_idx);
436 if (!(iotlb.perm & (1 << is_write))) {
437 goto unassigned;
440 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
441 | (addr & iotlb.addr_mask));
442 page_mask &= iotlb.addr_mask;
443 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
444 *target_as = iotlb.target_as;
446 section = address_space_translate_internal(
447 address_space_to_dispatch(iotlb.target_as), addr, xlat,
448 plen_out, is_mmio);
450 iommu_mr = memory_region_get_iommu(section->mr);
451 } while (unlikely(iommu_mr));
453 if (page_mask_out) {
454 *page_mask_out = page_mask;
456 return *section;
458 unassigned:
459 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
463 * flatview_do_translate - translate an address in FlatView
465 * @fv: the flat view that we want to translate on
466 * @addr: the address to be translated in above address space
467 * @xlat: the translated address offset within memory region. It
468 * cannot be @NULL.
469 * @plen_out: valid read/write length of the translated address. It
470 * can be @NULL when we don't care about it.
471 * @page_mask_out: page mask for the translated address. This
472 * should only be meaningful for IOMMU translated
473 * addresses, since there may be huge pages that this bit
474 * would tell. It can be @NULL if we don't care about it.
475 * @is_write: whether the translation operation is for write
476 * @is_mmio: whether this can be MMIO, set true if it can
477 * @target_as: the address space targeted by the IOMMU
478 * @attrs: memory transaction attributes
480 * This function is called from RCU critical section
482 static MemoryRegionSection flatview_do_translate(FlatView *fv,
483 hwaddr addr,
484 hwaddr *xlat,
485 hwaddr *plen_out,
486 hwaddr *page_mask_out,
487 bool is_write,
488 bool is_mmio,
489 AddressSpace **target_as,
490 MemTxAttrs attrs)
492 MemoryRegionSection *section;
493 IOMMUMemoryRegion *iommu_mr;
494 hwaddr plen = (hwaddr)(-1);
496 if (!plen_out) {
497 plen_out = &plen;
500 section = address_space_translate_internal(
501 flatview_to_dispatch(fv), addr, xlat,
502 plen_out, is_mmio);
504 iommu_mr = memory_region_get_iommu(section->mr);
505 if (unlikely(iommu_mr)) {
506 return address_space_translate_iommu(iommu_mr, xlat,
507 plen_out, page_mask_out,
508 is_write, is_mmio,
509 target_as, attrs);
511 if (page_mask_out) {
512 /* Not behind an IOMMU, use default page size. */
513 *page_mask_out = ~TARGET_PAGE_MASK;
516 return *section;
519 /* Called from RCU critical section */
520 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
521 bool is_write, MemTxAttrs attrs)
523 MemoryRegionSection section;
524 hwaddr xlat, page_mask;
527 * This can never be MMIO, and we don't really care about plen,
528 * but page mask.
530 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
531 NULL, &page_mask, is_write, false, &as,
532 attrs);
534 /* Illegal translation */
535 if (section.mr == &io_mem_unassigned) {
536 goto iotlb_fail;
539 /* Convert memory region offset into address space offset */
540 xlat += section.offset_within_address_space -
541 section.offset_within_region;
543 return (IOMMUTLBEntry) {
544 .target_as = as,
545 .iova = addr & ~page_mask,
546 .translated_addr = xlat & ~page_mask,
547 .addr_mask = page_mask,
548 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
549 .perm = IOMMU_RW,
552 iotlb_fail:
553 return (IOMMUTLBEntry) {0};
556 /* Called from RCU critical section */
557 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
558 hwaddr *plen, bool is_write,
559 MemTxAttrs attrs)
561 MemoryRegion *mr;
562 MemoryRegionSection section;
563 AddressSpace *as = NULL;
565 /* This can be MMIO, so setup MMIO bit. */
566 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
567 is_write, true, &as, attrs);
568 mr = section.mr;
570 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
571 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
572 *plen = MIN(page, *plen);
575 return mr;
578 typedef struct TCGIOMMUNotifier {
579 IOMMUNotifier n;
580 MemoryRegion *mr;
581 CPUState *cpu;
582 int iommu_idx;
583 bool active;
584 } TCGIOMMUNotifier;
586 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
588 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
590 if (!notifier->active) {
591 return;
593 tlb_flush(notifier->cpu);
594 notifier->active = false;
595 /* We leave the notifier struct on the list to avoid reallocating it later.
596 * Generally the number of IOMMUs a CPU deals with will be small.
597 * In any case we can't unregister the iommu notifier from a notify
598 * callback.
602 static void tcg_register_iommu_notifier(CPUState *cpu,
603 IOMMUMemoryRegion *iommu_mr,
604 int iommu_idx)
606 /* Make sure this CPU has an IOMMU notifier registered for this
607 * IOMMU/IOMMU index combination, so that we can flush its TLB
608 * when the IOMMU tells us the mappings we've cached have changed.
610 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
611 TCGIOMMUNotifier *notifier = NULL;
612 int i;
614 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
615 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
616 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
617 break;
620 if (i == cpu->iommu_notifiers->len) {
621 /* Not found, add a new entry at the end of the array */
622 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
623 notifier = g_new0(TCGIOMMUNotifier, 1);
624 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
626 notifier->mr = mr;
627 notifier->iommu_idx = iommu_idx;
628 notifier->cpu = cpu;
629 /* Rather than trying to register interest in the specific part
630 * of the iommu's address space that we've accessed and then
631 * expand it later as subsequent accesses touch more of it, we
632 * just register interest in the whole thing, on the assumption
633 * that iommu reconfiguration will be rare.
635 iommu_notifier_init(&notifier->n,
636 tcg_iommu_unmap_notify,
637 IOMMU_NOTIFIER_UNMAP,
639 HWADDR_MAX,
640 iommu_idx);
641 memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
642 &error_fatal);
645 if (!notifier->active) {
646 notifier->active = true;
650 void tcg_iommu_free_notifier_list(CPUState *cpu)
652 /* Destroy the CPU's notifier list */
653 int i;
654 TCGIOMMUNotifier *notifier;
656 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
657 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
658 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
659 g_free(notifier);
661 g_array_free(cpu->iommu_notifiers, true);
664 void tcg_iommu_init_notifier_list(CPUState *cpu)
666 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
669 /* Called from RCU critical section */
670 MemoryRegionSection *
671 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
672 hwaddr *xlat, hwaddr *plen,
673 MemTxAttrs attrs, int *prot)
675 MemoryRegionSection *section;
676 IOMMUMemoryRegion *iommu_mr;
677 IOMMUMemoryRegionClass *imrc;
678 IOMMUTLBEntry iotlb;
679 int iommu_idx;
680 AddressSpaceDispatch *d =
681 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
683 for (;;) {
684 section = address_space_translate_internal(d, addr, &addr, plen, false);
686 iommu_mr = memory_region_get_iommu(section->mr);
687 if (!iommu_mr) {
688 break;
691 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
693 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
694 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
695 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
696 * doesn't short-cut its translation table walk.
698 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
699 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
700 | (addr & iotlb.addr_mask));
701 /* Update the caller's prot bits to remove permissions the IOMMU
702 * is giving us a failure response for. If we get down to no
703 * permissions left at all we can give up now.
705 if (!(iotlb.perm & IOMMU_RO)) {
706 *prot &= ~(PAGE_READ | PAGE_EXEC);
708 if (!(iotlb.perm & IOMMU_WO)) {
709 *prot &= ~PAGE_WRITE;
712 if (!*prot) {
713 goto translate_fail;
716 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
719 assert(!memory_region_is_iommu(section->mr));
720 *xlat = addr;
721 return section;
723 translate_fail:
724 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
727 void cpu_address_space_init(CPUState *cpu, int asidx,
728 const char *prefix, MemoryRegion *mr)
730 CPUAddressSpace *newas;
731 AddressSpace *as = g_new0(AddressSpace, 1);
732 char *as_name;
734 assert(mr);
735 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
736 address_space_init(as, mr, as_name);
737 g_free(as_name);
739 /* Target code should have set num_ases before calling us */
740 assert(asidx < cpu->num_ases);
742 if (asidx == 0) {
743 /* address space 0 gets the convenience alias */
744 cpu->as = as;
747 /* KVM cannot currently support multiple address spaces. */
748 assert(asidx == 0 || !kvm_enabled());
750 if (!cpu->cpu_ases) {
751 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
754 newas = &cpu->cpu_ases[asidx];
755 newas->cpu = cpu;
756 newas->as = as;
757 if (tcg_enabled()) {
758 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
759 newas->tcg_as_listener.commit = tcg_commit;
760 newas->tcg_as_listener.name = "tcg";
761 memory_listener_register(&newas->tcg_as_listener, as);
765 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
767 /* Return the AddressSpace corresponding to the specified index */
768 return cpu->cpu_ases[asidx].as;
771 /* Add a watchpoint. */
772 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
773 int flags, CPUWatchpoint **watchpoint)
775 CPUWatchpoint *wp;
776 vaddr in_page;
778 /* forbid ranges which are empty or run off the end of the address space */
779 if (len == 0 || (addr + len - 1) < addr) {
780 error_report("tried to set invalid watchpoint at %"
781 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
782 return -EINVAL;
784 wp = g_malloc(sizeof(*wp));
786 wp->vaddr = addr;
787 wp->len = len;
788 wp->flags = flags;
790 /* keep all GDB-injected watchpoints in front */
791 if (flags & BP_GDB) {
792 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
793 } else {
794 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
797 in_page = -(addr | TARGET_PAGE_MASK);
798 if (len <= in_page) {
799 tlb_flush_page(cpu, addr);
800 } else {
801 tlb_flush(cpu);
804 if (watchpoint)
805 *watchpoint = wp;
806 return 0;
809 /* Remove a specific watchpoint. */
810 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
811 int flags)
813 CPUWatchpoint *wp;
815 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
816 if (addr == wp->vaddr && len == wp->len
817 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
818 cpu_watchpoint_remove_by_ref(cpu, wp);
819 return 0;
822 return -ENOENT;
825 /* Remove a specific watchpoint by reference. */
826 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
828 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
830 tlb_flush_page(cpu, watchpoint->vaddr);
832 g_free(watchpoint);
835 /* Remove all matching watchpoints. */
836 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
838 CPUWatchpoint *wp, *next;
840 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
841 if (wp->flags & mask) {
842 cpu_watchpoint_remove_by_ref(cpu, wp);
847 #ifdef CONFIG_TCG
848 /* Return true if this watchpoint address matches the specified
849 * access (ie the address range covered by the watchpoint overlaps
850 * partially or completely with the address range covered by the
851 * access).
853 static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
854 vaddr addr, vaddr len)
856 /* We know the lengths are non-zero, but a little caution is
857 * required to avoid errors in the case where the range ends
858 * exactly at the top of the address space and so addr + len
859 * wraps round to zero.
861 vaddr wpend = wp->vaddr + wp->len - 1;
862 vaddr addrend = addr + len - 1;
864 return !(addr > wpend || wp->vaddr > addrend);
867 /* Return flags for watchpoints that match addr + prot. */
868 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
870 CPUWatchpoint *wp;
871 int ret = 0;
873 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
874 if (watchpoint_address_matches(wp, addr, len)) {
875 ret |= wp->flags;
878 return ret;
881 /* Generate a debug exception if a watchpoint has been hit. */
882 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
883 MemTxAttrs attrs, int flags, uintptr_t ra)
885 CPUClass *cc = CPU_GET_CLASS(cpu);
886 CPUWatchpoint *wp;
888 assert(tcg_enabled());
889 if (cpu->watchpoint_hit) {
891 * We re-entered the check after replacing the TB.
892 * Now raise the debug interrupt so that it will
893 * trigger after the current instruction.
895 qemu_mutex_lock_iothread();
896 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
897 qemu_mutex_unlock_iothread();
898 return;
901 if (cc->tcg_ops->adjust_watchpoint_address) {
902 /* this is currently used only by ARM BE32 */
903 addr = cc->tcg_ops->adjust_watchpoint_address(cpu, addr, len);
905 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
906 if (watchpoint_address_matches(wp, addr, len)
907 && (wp->flags & flags)) {
908 if (replay_running_debug()) {
910 * replay_breakpoint reads icount.
911 * Force recompile to succeed, because icount may
912 * be read only at the end of the block.
914 if (!cpu->can_do_io) {
915 /* Force execution of one insn next time. */
916 cpu->cflags_next_tb = 1 | CF_LAST_IO | CF_NOIRQ | curr_cflags(cpu);
917 cpu_loop_exit_restore(cpu, ra);
920 * Don't process the watchpoints when we are
921 * in a reverse debugging operation.
923 replay_breakpoint();
924 return;
926 if (flags == BP_MEM_READ) {
927 wp->flags |= BP_WATCHPOINT_HIT_READ;
928 } else {
929 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
931 wp->hitaddr = MAX(addr, wp->vaddr);
932 wp->hitattrs = attrs;
934 if (wp->flags & BP_CPU && cc->tcg_ops->debug_check_watchpoint &&
935 !cc->tcg_ops->debug_check_watchpoint(cpu, wp)) {
936 wp->flags &= ~BP_WATCHPOINT_HIT;
937 continue;
939 cpu->watchpoint_hit = wp;
941 mmap_lock();
942 /* This call also restores vCPU state */
943 tb_check_watchpoint(cpu, ra);
944 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
945 cpu->exception_index = EXCP_DEBUG;
946 mmap_unlock();
947 cpu_loop_exit(cpu);
948 } else {
949 /* Force execution of one insn next time. */
950 cpu->cflags_next_tb = 1 | CF_LAST_IO | CF_NOIRQ | curr_cflags(cpu);
951 mmap_unlock();
952 cpu_loop_exit_noexc(cpu);
954 } else {
955 wp->flags &= ~BP_WATCHPOINT_HIT;
960 #endif /* CONFIG_TCG */
962 /* Called from RCU critical section */
963 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
965 RAMBlock *block;
967 block = qatomic_rcu_read(&ram_list.mru_block);
968 if (block && addr - block->offset < block->max_length) {
969 return block;
971 RAMBLOCK_FOREACH(block) {
972 if (addr - block->offset < block->max_length) {
973 goto found;
977 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
978 abort();
980 found:
981 /* It is safe to write mru_block outside the iothread lock. This
982 * is what happens:
984 * mru_block = xxx
985 * rcu_read_unlock()
986 * xxx removed from list
987 * rcu_read_lock()
988 * read mru_block
989 * mru_block = NULL;
990 * call_rcu(reclaim_ramblock, xxx);
991 * rcu_read_unlock()
993 * qatomic_rcu_set is not needed here. The block was already published
994 * when it was placed into the list. Here we're just making an extra
995 * copy of the pointer.
997 ram_list.mru_block = block;
998 return block;
1001 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1003 CPUState *cpu;
1004 ram_addr_t start1;
1005 RAMBlock *block;
1006 ram_addr_t end;
1008 assert(tcg_enabled());
1009 end = TARGET_PAGE_ALIGN(start + length);
1010 start &= TARGET_PAGE_MASK;
1012 RCU_READ_LOCK_GUARD();
1013 block = qemu_get_ram_block(start);
1014 assert(block == qemu_get_ram_block(end - 1));
1015 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1016 CPU_FOREACH(cpu) {
1017 tlb_reset_dirty(cpu, start1, length);
1021 /* Note: start and end must be within the same ram block. */
1022 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1023 ram_addr_t length,
1024 unsigned client)
1026 DirtyMemoryBlocks *blocks;
1027 unsigned long end, page, start_page;
1028 bool dirty = false;
1029 RAMBlock *ramblock;
1030 uint64_t mr_offset, mr_size;
1032 if (length == 0) {
1033 return false;
1036 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1037 start_page = start >> TARGET_PAGE_BITS;
1038 page = start_page;
1040 WITH_RCU_READ_LOCK_GUARD() {
1041 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1042 ramblock = qemu_get_ram_block(start);
1043 /* Range sanity check on the ramblock */
1044 assert(start >= ramblock->offset &&
1045 start + length <= ramblock->offset + ramblock->used_length);
1047 while (page < end) {
1048 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1049 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1050 unsigned long num = MIN(end - page,
1051 DIRTY_MEMORY_BLOCK_SIZE - offset);
1053 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1054 offset, num);
1055 page += num;
1058 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
1059 mr_size = (end - start_page) << TARGET_PAGE_BITS;
1060 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
1063 if (dirty && tcg_enabled()) {
1064 tlb_reset_dirty_range_all(start, length);
1067 return dirty;
1070 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1071 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
1073 DirtyMemoryBlocks *blocks;
1074 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
1075 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1076 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1077 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1078 DirtyBitmapSnapshot *snap;
1079 unsigned long page, end, dest;
1081 snap = g_malloc0(sizeof(*snap) +
1082 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1083 snap->start = first;
1084 snap->end = last;
1086 page = first >> TARGET_PAGE_BITS;
1087 end = last >> TARGET_PAGE_BITS;
1088 dest = 0;
1090 WITH_RCU_READ_LOCK_GUARD() {
1091 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1093 while (page < end) {
1094 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1095 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1096 unsigned long num = MIN(end - page,
1097 DIRTY_MEMORY_BLOCK_SIZE - offset);
1099 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1100 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1101 offset >>= BITS_PER_LEVEL;
1103 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1104 blocks->blocks[idx] + offset,
1105 num);
1106 page += num;
1107 dest += num >> BITS_PER_LEVEL;
1111 if (tcg_enabled()) {
1112 tlb_reset_dirty_range_all(start, length);
1115 memory_region_clear_dirty_bitmap(mr, offset, length);
1117 return snap;
1120 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1121 ram_addr_t start,
1122 ram_addr_t length)
1124 unsigned long page, end;
1126 assert(start >= snap->start);
1127 assert(start + length <= snap->end);
1129 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1130 page = (start - snap->start) >> TARGET_PAGE_BITS;
1132 while (page < end) {
1133 if (test_bit(page, snap->dirty)) {
1134 return true;
1136 page++;
1138 return false;
1141 /* Called from RCU critical section */
1142 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1143 MemoryRegionSection *section)
1145 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1146 return section - d->map.sections;
1149 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1150 uint16_t section);
1151 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1153 static uint16_t phys_section_add(PhysPageMap *map,
1154 MemoryRegionSection *section)
1156 /* The physical section number is ORed with a page-aligned
1157 * pointer to produce the iotlb entries. Thus it should
1158 * never overflow into the page-aligned value.
1160 assert(map->sections_nb < TARGET_PAGE_SIZE);
1162 if (map->sections_nb == map->sections_nb_alloc) {
1163 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1164 map->sections = g_renew(MemoryRegionSection, map->sections,
1165 map->sections_nb_alloc);
1167 map->sections[map->sections_nb] = *section;
1168 memory_region_ref(section->mr);
1169 return map->sections_nb++;
1172 static void phys_section_destroy(MemoryRegion *mr)
1174 bool have_sub_page = mr->subpage;
1176 memory_region_unref(mr);
1178 if (have_sub_page) {
1179 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1180 object_unref(OBJECT(&subpage->iomem));
1181 g_free(subpage);
1185 static void phys_sections_free(PhysPageMap *map)
1187 while (map->sections_nb > 0) {
1188 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1189 phys_section_destroy(section->mr);
1191 g_free(map->sections);
1192 g_free(map->nodes);
1195 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1197 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1198 subpage_t *subpage;
1199 hwaddr base = section->offset_within_address_space
1200 & TARGET_PAGE_MASK;
1201 MemoryRegionSection *existing = phys_page_find(d, base);
1202 MemoryRegionSection subsection = {
1203 .offset_within_address_space = base,
1204 .size = int128_make64(TARGET_PAGE_SIZE),
1206 hwaddr start, end;
1208 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1210 if (!(existing->mr->subpage)) {
1211 subpage = subpage_init(fv, base);
1212 subsection.fv = fv;
1213 subsection.mr = &subpage->iomem;
1214 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1215 phys_section_add(&d->map, &subsection));
1216 } else {
1217 subpage = container_of(existing->mr, subpage_t, iomem);
1219 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1220 end = start + int128_get64(section->size) - 1;
1221 subpage_register(subpage, start, end,
1222 phys_section_add(&d->map, section));
1226 static void register_multipage(FlatView *fv,
1227 MemoryRegionSection *section)
1229 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1230 hwaddr start_addr = section->offset_within_address_space;
1231 uint16_t section_index = phys_section_add(&d->map, section);
1232 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1233 TARGET_PAGE_BITS));
1235 assert(num_pages);
1236 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1240 * The range in *section* may look like this:
1242 * |s|PPPPPPP|s|
1244 * where s stands for subpage and P for page.
1246 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1248 MemoryRegionSection remain = *section;
1249 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1251 /* register first subpage */
1252 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1253 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1254 - remain.offset_within_address_space;
1256 MemoryRegionSection now = remain;
1257 now.size = int128_min(int128_make64(left), now.size);
1258 register_subpage(fv, &now);
1259 if (int128_eq(remain.size, now.size)) {
1260 return;
1262 remain.size = int128_sub(remain.size, now.size);
1263 remain.offset_within_address_space += int128_get64(now.size);
1264 remain.offset_within_region += int128_get64(now.size);
1267 /* register whole pages */
1268 if (int128_ge(remain.size, page_size)) {
1269 MemoryRegionSection now = remain;
1270 now.size = int128_and(now.size, int128_neg(page_size));
1271 register_multipage(fv, &now);
1272 if (int128_eq(remain.size, now.size)) {
1273 return;
1275 remain.size = int128_sub(remain.size, now.size);
1276 remain.offset_within_address_space += int128_get64(now.size);
1277 remain.offset_within_region += int128_get64(now.size);
1280 /* register last subpage */
1281 register_subpage(fv, &remain);
1284 void qemu_flush_coalesced_mmio_buffer(void)
1286 if (kvm_enabled())
1287 kvm_flush_coalesced_mmio_buffer();
1290 void qemu_mutex_lock_ramlist(void)
1292 qemu_mutex_lock(&ram_list.mutex);
1295 void qemu_mutex_unlock_ramlist(void)
1297 qemu_mutex_unlock(&ram_list.mutex);
1300 GString *ram_block_format(void)
1302 RAMBlock *block;
1303 char *psize;
1304 GString *buf = g_string_new("");
1306 RCU_READ_LOCK_GUARD();
1307 g_string_append_printf(buf, "%24s %8s %18s %18s %18s\n",
1308 "Block Name", "PSize", "Offset", "Used", "Total");
1309 RAMBLOCK_FOREACH(block) {
1310 psize = size_to_str(block->page_size);
1311 g_string_append_printf(buf, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1312 " 0x%016" PRIx64 "\n", block->idstr, psize,
1313 (uint64_t)block->offset,
1314 (uint64_t)block->used_length,
1315 (uint64_t)block->max_length);
1316 g_free(psize);
1319 return buf;
1322 #ifdef __linux__
1324 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1325 * may or may not name the same files / on the same filesystem now as
1326 * when we actually open and map them. Iterate over the file
1327 * descriptors instead, and use qemu_fd_getpagesize().
1329 static int find_min_backend_pagesize(Object *obj, void *opaque)
1331 long *hpsize_min = opaque;
1333 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1334 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1335 long hpsize = host_memory_backend_pagesize(backend);
1337 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1338 *hpsize_min = hpsize;
1342 return 0;
1345 static int find_max_backend_pagesize(Object *obj, void *opaque)
1347 long *hpsize_max = opaque;
1349 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1350 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1351 long hpsize = host_memory_backend_pagesize(backend);
1353 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1354 *hpsize_max = hpsize;
1358 return 0;
1362 * TODO: We assume right now that all mapped host memory backends are
1363 * used as RAM, however some might be used for different purposes.
1365 long qemu_minrampagesize(void)
1367 long hpsize = LONG_MAX;
1368 Object *memdev_root = object_resolve_path("/objects", NULL);
1370 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1371 return hpsize;
1374 long qemu_maxrampagesize(void)
1376 long pagesize = 0;
1377 Object *memdev_root = object_resolve_path("/objects", NULL);
1379 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1380 return pagesize;
1382 #else
1383 long qemu_minrampagesize(void)
1385 return qemu_real_host_page_size;
1387 long qemu_maxrampagesize(void)
1389 return qemu_real_host_page_size;
1391 #endif
1393 #ifdef CONFIG_POSIX
1394 static int64_t get_file_size(int fd)
1396 int64_t size;
1397 #if defined(__linux__)
1398 struct stat st;
1400 if (fstat(fd, &st) < 0) {
1401 return -errno;
1404 /* Special handling for devdax character devices */
1405 if (S_ISCHR(st.st_mode)) {
1406 g_autofree char *subsystem_path = NULL;
1407 g_autofree char *subsystem = NULL;
1409 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1410 major(st.st_rdev), minor(st.st_rdev));
1411 subsystem = g_file_read_link(subsystem_path, NULL);
1413 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1414 g_autofree char *size_path = NULL;
1415 g_autofree char *size_str = NULL;
1417 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1418 major(st.st_rdev), minor(st.st_rdev));
1420 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1421 return g_ascii_strtoll(size_str, NULL, 0);
1425 #endif /* defined(__linux__) */
1427 /* st.st_size may be zero for special files yet lseek(2) works */
1428 size = lseek(fd, 0, SEEK_END);
1429 if (size < 0) {
1430 return -errno;
1432 return size;
1435 static int64_t get_file_align(int fd)
1437 int64_t align = -1;
1438 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1439 struct stat st;
1441 if (fstat(fd, &st) < 0) {
1442 return -errno;
1445 /* Special handling for devdax character devices */
1446 if (S_ISCHR(st.st_mode)) {
1447 g_autofree char *path = NULL;
1448 g_autofree char *rpath = NULL;
1449 struct daxctl_ctx *ctx;
1450 struct daxctl_region *region;
1451 int rc = 0;
1453 path = g_strdup_printf("/sys/dev/char/%d:%d",
1454 major(st.st_rdev), minor(st.st_rdev));
1455 rpath = realpath(path, NULL);
1456 if (!rpath) {
1457 return -errno;
1460 rc = daxctl_new(&ctx);
1461 if (rc) {
1462 return -1;
1465 daxctl_region_foreach(ctx, region) {
1466 if (strstr(rpath, daxctl_region_get_path(region))) {
1467 align = daxctl_region_get_align(region);
1468 break;
1471 daxctl_unref(ctx);
1473 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1475 return align;
1478 static int file_ram_open(const char *path,
1479 const char *region_name,
1480 bool readonly,
1481 bool *created,
1482 Error **errp)
1484 char *filename;
1485 char *sanitized_name;
1486 char *c;
1487 int fd = -1;
1489 *created = false;
1490 for (;;) {
1491 fd = open(path, readonly ? O_RDONLY : O_RDWR);
1492 if (fd >= 0) {
1493 /* @path names an existing file, use it */
1494 break;
1496 if (errno == ENOENT) {
1497 /* @path names a file that doesn't exist, create it */
1498 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1499 if (fd >= 0) {
1500 *created = true;
1501 break;
1503 } else if (errno == EISDIR) {
1504 /* @path names a directory, create a file there */
1505 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1506 sanitized_name = g_strdup(region_name);
1507 for (c = sanitized_name; *c != '\0'; c++) {
1508 if (*c == '/') {
1509 *c = '_';
1513 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1514 sanitized_name);
1515 g_free(sanitized_name);
1517 fd = mkstemp(filename);
1518 if (fd >= 0) {
1519 unlink(filename);
1520 g_free(filename);
1521 break;
1523 g_free(filename);
1525 if (errno != EEXIST && errno != EINTR) {
1526 error_setg_errno(errp, errno,
1527 "can't open backing store %s for guest RAM",
1528 path);
1529 return -1;
1532 * Try again on EINTR and EEXIST. The latter happens when
1533 * something else creates the file between our two open().
1537 return fd;
1540 static void *file_ram_alloc(RAMBlock *block,
1541 ram_addr_t memory,
1542 int fd,
1543 bool readonly,
1544 bool truncate,
1545 off_t offset,
1546 Error **errp)
1548 uint32_t qemu_map_flags;
1549 void *area;
1551 block->page_size = qemu_fd_getpagesize(fd);
1552 if (block->mr->align % block->page_size) {
1553 error_setg(errp, "alignment 0x%" PRIx64
1554 " must be multiples of page size 0x%zx",
1555 block->mr->align, block->page_size);
1556 return NULL;
1557 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1558 error_setg(errp, "alignment 0x%" PRIx64
1559 " must be a power of two", block->mr->align);
1560 return NULL;
1562 block->mr->align = MAX(block->page_size, block->mr->align);
1563 #if defined(__s390x__)
1564 if (kvm_enabled()) {
1565 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1567 #endif
1569 if (memory < block->page_size) {
1570 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1571 "or larger than page size 0x%zx",
1572 memory, block->page_size);
1573 return NULL;
1576 memory = ROUND_UP(memory, block->page_size);
1579 * ftruncate is not supported by hugetlbfs in older
1580 * hosts, so don't bother bailing out on errors.
1581 * If anything goes wrong with it under other filesystems,
1582 * mmap will fail.
1584 * Do not truncate the non-empty backend file to avoid corrupting
1585 * the existing data in the file. Disabling shrinking is not
1586 * enough. For example, the current vNVDIMM implementation stores
1587 * the guest NVDIMM labels at the end of the backend file. If the
1588 * backend file is later extended, QEMU will not be able to find
1589 * those labels. Therefore, extending the non-empty backend file
1590 * is disabled as well.
1592 if (truncate && ftruncate(fd, memory)) {
1593 perror("ftruncate");
1596 qemu_map_flags = readonly ? QEMU_MAP_READONLY : 0;
1597 qemu_map_flags |= (block->flags & RAM_SHARED) ? QEMU_MAP_SHARED : 0;
1598 qemu_map_flags |= (block->flags & RAM_PMEM) ? QEMU_MAP_SYNC : 0;
1599 qemu_map_flags |= (block->flags & RAM_NORESERVE) ? QEMU_MAP_NORESERVE : 0;
1600 area = qemu_ram_mmap(fd, memory, block->mr->align, qemu_map_flags, offset);
1601 if (area == MAP_FAILED) {
1602 error_setg_errno(errp, errno,
1603 "unable to map backing store for guest RAM");
1604 return NULL;
1607 block->fd = fd;
1608 return area;
1610 #endif
1612 /* Allocate space within the ram_addr_t space that governs the
1613 * dirty bitmaps.
1614 * Called with the ramlist lock held.
1616 static ram_addr_t find_ram_offset(ram_addr_t size)
1618 RAMBlock *block, *next_block;
1619 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1621 assert(size != 0); /* it would hand out same offset multiple times */
1623 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1624 return 0;
1627 RAMBLOCK_FOREACH(block) {
1628 ram_addr_t candidate, next = RAM_ADDR_MAX;
1630 /* Align blocks to start on a 'long' in the bitmap
1631 * which makes the bitmap sync'ing take the fast path.
1633 candidate = block->offset + block->max_length;
1634 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1636 /* Search for the closest following block
1637 * and find the gap.
1639 RAMBLOCK_FOREACH(next_block) {
1640 if (next_block->offset >= candidate) {
1641 next = MIN(next, next_block->offset);
1645 /* If it fits remember our place and remember the size
1646 * of gap, but keep going so that we might find a smaller
1647 * gap to fill so avoiding fragmentation.
1649 if (next - candidate >= size && next - candidate < mingap) {
1650 offset = candidate;
1651 mingap = next - candidate;
1654 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1657 if (offset == RAM_ADDR_MAX) {
1658 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1659 (uint64_t)size);
1660 abort();
1663 trace_find_ram_offset(size, offset);
1665 return offset;
1668 static unsigned long last_ram_page(void)
1670 RAMBlock *block;
1671 ram_addr_t last = 0;
1673 RCU_READ_LOCK_GUARD();
1674 RAMBLOCK_FOREACH(block) {
1675 last = MAX(last, block->offset + block->max_length);
1677 return last >> TARGET_PAGE_BITS;
1680 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1682 int ret;
1684 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1685 if (!machine_dump_guest_core(current_machine)) {
1686 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1687 if (ret) {
1688 perror("qemu_madvise");
1689 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1690 "but dump_guest_core=off specified\n");
1695 const char *qemu_ram_get_idstr(RAMBlock *rb)
1697 return rb->idstr;
1700 void *qemu_ram_get_host_addr(RAMBlock *rb)
1702 return rb->host;
1705 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1707 return rb->offset;
1710 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1712 return rb->used_length;
1715 ram_addr_t qemu_ram_get_max_length(RAMBlock *rb)
1717 return rb->max_length;
1720 bool qemu_ram_is_shared(RAMBlock *rb)
1722 return rb->flags & RAM_SHARED;
1725 bool qemu_ram_is_noreserve(RAMBlock *rb)
1727 return rb->flags & RAM_NORESERVE;
1730 /* Note: Only set at the start of postcopy */
1731 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1733 return rb->flags & RAM_UF_ZEROPAGE;
1736 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1738 rb->flags |= RAM_UF_ZEROPAGE;
1741 bool qemu_ram_is_migratable(RAMBlock *rb)
1743 return rb->flags & RAM_MIGRATABLE;
1746 void qemu_ram_set_migratable(RAMBlock *rb)
1748 rb->flags |= RAM_MIGRATABLE;
1751 void qemu_ram_unset_migratable(RAMBlock *rb)
1753 rb->flags &= ~RAM_MIGRATABLE;
1756 /* Called with iothread lock held. */
1757 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1759 RAMBlock *block;
1761 assert(new_block);
1762 assert(!new_block->idstr[0]);
1764 if (dev) {
1765 char *id = qdev_get_dev_path(dev);
1766 if (id) {
1767 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1768 g_free(id);
1771 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1773 RCU_READ_LOCK_GUARD();
1774 RAMBLOCK_FOREACH(block) {
1775 if (block != new_block &&
1776 !strcmp(block->idstr, new_block->idstr)) {
1777 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1778 new_block->idstr);
1779 abort();
1784 /* Called with iothread lock held. */
1785 void qemu_ram_unset_idstr(RAMBlock *block)
1787 /* FIXME: arch_init.c assumes that this is not called throughout
1788 * migration. Ignore the problem since hot-unplug during migration
1789 * does not work anyway.
1791 if (block) {
1792 memset(block->idstr, 0, sizeof(block->idstr));
1796 size_t qemu_ram_pagesize(RAMBlock *rb)
1798 return rb->page_size;
1801 /* Returns the largest size of page in use */
1802 size_t qemu_ram_pagesize_largest(void)
1804 RAMBlock *block;
1805 size_t largest = 0;
1807 RAMBLOCK_FOREACH(block) {
1808 largest = MAX(largest, qemu_ram_pagesize(block));
1811 return largest;
1814 static int memory_try_enable_merging(void *addr, size_t len)
1816 if (!machine_mem_merge(current_machine)) {
1817 /* disabled by the user */
1818 return 0;
1821 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1825 * Resizing RAM while migrating can result in the migration being canceled.
1826 * Care has to be taken if the guest might have already detected the memory.
1828 * As memory core doesn't know how is memory accessed, it is up to
1829 * resize callback to update device state and/or add assertions to detect
1830 * misuse, if necessary.
1832 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1834 const ram_addr_t oldsize = block->used_length;
1835 const ram_addr_t unaligned_size = newsize;
1837 assert(block);
1839 newsize = HOST_PAGE_ALIGN(newsize);
1841 if (block->used_length == newsize) {
1843 * We don't have to resize the ram block (which only knows aligned
1844 * sizes), however, we have to notify if the unaligned size changed.
1846 if (unaligned_size != memory_region_size(block->mr)) {
1847 memory_region_set_size(block->mr, unaligned_size);
1848 if (block->resized) {
1849 block->resized(block->idstr, unaligned_size, block->host);
1852 return 0;
1855 if (!(block->flags & RAM_RESIZEABLE)) {
1856 error_setg_errno(errp, EINVAL,
1857 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1858 " != 0x" RAM_ADDR_FMT, block->idstr,
1859 newsize, block->used_length);
1860 return -EINVAL;
1863 if (block->max_length < newsize) {
1864 error_setg_errno(errp, EINVAL,
1865 "Size too large: %s: 0x" RAM_ADDR_FMT
1866 " > 0x" RAM_ADDR_FMT, block->idstr,
1867 newsize, block->max_length);
1868 return -EINVAL;
1871 /* Notify before modifying the ram block and touching the bitmaps. */
1872 if (block->host) {
1873 ram_block_notify_resize(block->host, oldsize, newsize);
1876 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1877 block->used_length = newsize;
1878 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1879 DIRTY_CLIENTS_ALL);
1880 memory_region_set_size(block->mr, unaligned_size);
1881 if (block->resized) {
1882 block->resized(block->idstr, unaligned_size, block->host);
1884 return 0;
1888 * Trigger sync on the given ram block for range [start, start + length]
1889 * with the backing store if one is available.
1890 * Otherwise no-op.
1891 * @Note: this is supposed to be a synchronous op.
1893 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1895 /* The requested range should fit in within the block range */
1896 g_assert((start + length) <= block->used_length);
1898 #ifdef CONFIG_LIBPMEM
1899 /* The lack of support for pmem should not block the sync */
1900 if (ramblock_is_pmem(block)) {
1901 void *addr = ramblock_ptr(block, start);
1902 pmem_persist(addr, length);
1903 return;
1905 #endif
1906 if (block->fd >= 0) {
1908 * Case there is no support for PMEM or the memory has not been
1909 * specified as persistent (or is not one) - use the msync.
1910 * Less optimal but still achieves the same goal
1912 void *addr = ramblock_ptr(block, start);
1913 if (qemu_msync(addr, length, block->fd)) {
1914 warn_report("%s: failed to sync memory range: start: "
1915 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1916 __func__, start, length);
1921 /* Called with ram_list.mutex held */
1922 static void dirty_memory_extend(ram_addr_t old_ram_size,
1923 ram_addr_t new_ram_size)
1925 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1926 DIRTY_MEMORY_BLOCK_SIZE);
1927 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1928 DIRTY_MEMORY_BLOCK_SIZE);
1929 int i;
1931 /* Only need to extend if block count increased */
1932 if (new_num_blocks <= old_num_blocks) {
1933 return;
1936 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1937 DirtyMemoryBlocks *old_blocks;
1938 DirtyMemoryBlocks *new_blocks;
1939 int j;
1941 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1942 new_blocks = g_malloc(sizeof(*new_blocks) +
1943 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1945 if (old_num_blocks) {
1946 memcpy(new_blocks->blocks, old_blocks->blocks,
1947 old_num_blocks * sizeof(old_blocks->blocks[0]));
1950 for (j = old_num_blocks; j < new_num_blocks; j++) {
1951 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1954 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1956 if (old_blocks) {
1957 g_free_rcu(old_blocks, rcu);
1962 static void ram_block_add(RAMBlock *new_block, Error **errp)
1964 const bool noreserve = qemu_ram_is_noreserve(new_block);
1965 const bool shared = qemu_ram_is_shared(new_block);
1966 RAMBlock *block;
1967 RAMBlock *last_block = NULL;
1968 ram_addr_t old_ram_size, new_ram_size;
1969 Error *err = NULL;
1971 old_ram_size = last_ram_page();
1973 qemu_mutex_lock_ramlist();
1974 new_block->offset = find_ram_offset(new_block->max_length);
1976 if (!new_block->host) {
1977 if (xen_enabled()) {
1978 xen_ram_alloc(new_block->offset, new_block->max_length,
1979 new_block->mr, &err);
1980 if (err) {
1981 error_propagate(errp, err);
1982 qemu_mutex_unlock_ramlist();
1983 return;
1985 } else {
1986 new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1987 &new_block->mr->align,
1988 shared, noreserve);
1989 if (!new_block->host) {
1990 error_setg_errno(errp, errno,
1991 "cannot set up guest memory '%s'",
1992 memory_region_name(new_block->mr));
1993 qemu_mutex_unlock_ramlist();
1994 return;
1996 memory_try_enable_merging(new_block->host, new_block->max_length);
2000 new_ram_size = MAX(old_ram_size,
2001 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2002 if (new_ram_size > old_ram_size) {
2003 dirty_memory_extend(old_ram_size, new_ram_size);
2005 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2006 * QLIST (which has an RCU-friendly variant) does not have insertion at
2007 * tail, so save the last element in last_block.
2009 RAMBLOCK_FOREACH(block) {
2010 last_block = block;
2011 if (block->max_length < new_block->max_length) {
2012 break;
2015 if (block) {
2016 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2017 } else if (last_block) {
2018 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2019 } else { /* list is empty */
2020 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2022 ram_list.mru_block = NULL;
2024 /* Write list before version */
2025 smp_wmb();
2026 ram_list.version++;
2027 qemu_mutex_unlock_ramlist();
2029 cpu_physical_memory_set_dirty_range(new_block->offset,
2030 new_block->used_length,
2031 DIRTY_CLIENTS_ALL);
2033 if (new_block->host) {
2034 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2035 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2037 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2038 * Configure it unless the machine is a qtest server, in which case
2039 * KVM is not used and it may be forked (eg for fuzzing purposes).
2041 if (!qtest_enabled()) {
2042 qemu_madvise(new_block->host, new_block->max_length,
2043 QEMU_MADV_DONTFORK);
2045 ram_block_notify_add(new_block->host, new_block->used_length,
2046 new_block->max_length);
2050 #ifdef CONFIG_POSIX
2051 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2052 uint32_t ram_flags, int fd, off_t offset,
2053 bool readonly, Error **errp)
2055 RAMBlock *new_block;
2056 Error *local_err = NULL;
2057 int64_t file_size, file_align;
2059 /* Just support these ram flags by now. */
2060 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM | RAM_NORESERVE |
2061 RAM_PROTECTED)) == 0);
2063 if (xen_enabled()) {
2064 error_setg(errp, "-mem-path not supported with Xen");
2065 return NULL;
2068 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2069 error_setg(errp,
2070 "host lacks kvm mmu notifiers, -mem-path unsupported");
2071 return NULL;
2074 size = HOST_PAGE_ALIGN(size);
2075 file_size = get_file_size(fd);
2076 if (file_size > 0 && file_size < size) {
2077 error_setg(errp, "backing store size 0x%" PRIx64
2078 " does not match 'size' option 0x" RAM_ADDR_FMT,
2079 file_size, size);
2080 return NULL;
2083 file_align = get_file_align(fd);
2084 if (file_align > 0 && file_align > mr->align) {
2085 error_setg(errp, "backing store align 0x%" PRIx64
2086 " is larger than 'align' option 0x%" PRIx64,
2087 file_align, mr->align);
2088 return NULL;
2091 new_block = g_malloc0(sizeof(*new_block));
2092 new_block->mr = mr;
2093 new_block->used_length = size;
2094 new_block->max_length = size;
2095 new_block->flags = ram_flags;
2096 new_block->host = file_ram_alloc(new_block, size, fd, readonly,
2097 !file_size, offset, errp);
2098 if (!new_block->host) {
2099 g_free(new_block);
2100 return NULL;
2103 ram_block_add(new_block, &local_err);
2104 if (local_err) {
2105 g_free(new_block);
2106 error_propagate(errp, local_err);
2107 return NULL;
2109 return new_block;
2114 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2115 uint32_t ram_flags, const char *mem_path,
2116 bool readonly, Error **errp)
2118 int fd;
2119 bool created;
2120 RAMBlock *block;
2122 fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
2123 errp);
2124 if (fd < 0) {
2125 return NULL;
2128 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, 0, readonly, errp);
2129 if (!block) {
2130 if (created) {
2131 unlink(mem_path);
2133 close(fd);
2134 return NULL;
2137 return block;
2139 #endif
2141 static
2142 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2143 void (*resized)(const char*,
2144 uint64_t length,
2145 void *host),
2146 void *host, uint32_t ram_flags,
2147 MemoryRegion *mr, Error **errp)
2149 RAMBlock *new_block;
2150 Error *local_err = NULL;
2152 assert((ram_flags & ~(RAM_SHARED | RAM_RESIZEABLE | RAM_PREALLOC |
2153 RAM_NORESERVE)) == 0);
2154 assert(!host ^ (ram_flags & RAM_PREALLOC));
2156 size = HOST_PAGE_ALIGN(size);
2157 max_size = HOST_PAGE_ALIGN(max_size);
2158 new_block = g_malloc0(sizeof(*new_block));
2159 new_block->mr = mr;
2160 new_block->resized = resized;
2161 new_block->used_length = size;
2162 new_block->max_length = max_size;
2163 assert(max_size >= size);
2164 new_block->fd = -1;
2165 new_block->page_size = qemu_real_host_page_size;
2166 new_block->host = host;
2167 new_block->flags = ram_flags;
2168 ram_block_add(new_block, &local_err);
2169 if (local_err) {
2170 g_free(new_block);
2171 error_propagate(errp, local_err);
2172 return NULL;
2174 return new_block;
2177 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2178 MemoryRegion *mr, Error **errp)
2180 return qemu_ram_alloc_internal(size, size, NULL, host, RAM_PREALLOC, mr,
2181 errp);
2184 RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
2185 MemoryRegion *mr, Error **errp)
2187 assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE)) == 0);
2188 return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
2191 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2192 void (*resized)(const char*,
2193 uint64_t length,
2194 void *host),
2195 MemoryRegion *mr, Error **errp)
2197 return qemu_ram_alloc_internal(size, maxsz, resized, NULL,
2198 RAM_RESIZEABLE, mr, errp);
2201 static void reclaim_ramblock(RAMBlock *block)
2203 if (block->flags & RAM_PREALLOC) {
2205 } else if (xen_enabled()) {
2206 xen_invalidate_map_cache_entry(block->host);
2207 #ifndef _WIN32
2208 } else if (block->fd >= 0) {
2209 qemu_ram_munmap(block->fd, block->host, block->max_length);
2210 close(block->fd);
2211 #endif
2212 } else {
2213 qemu_anon_ram_free(block->host, block->max_length);
2215 g_free(block);
2218 void qemu_ram_free(RAMBlock *block)
2220 if (!block) {
2221 return;
2224 if (block->host) {
2225 ram_block_notify_remove(block->host, block->used_length,
2226 block->max_length);
2229 qemu_mutex_lock_ramlist();
2230 QLIST_REMOVE_RCU(block, next);
2231 ram_list.mru_block = NULL;
2232 /* Write list before version */
2233 smp_wmb();
2234 ram_list.version++;
2235 call_rcu(block, reclaim_ramblock, rcu);
2236 qemu_mutex_unlock_ramlist();
2239 #ifndef _WIN32
2240 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2242 RAMBlock *block;
2243 ram_addr_t offset;
2244 int flags;
2245 void *area, *vaddr;
2247 RAMBLOCK_FOREACH(block) {
2248 offset = addr - block->offset;
2249 if (offset < block->max_length) {
2250 vaddr = ramblock_ptr(block, offset);
2251 if (block->flags & RAM_PREALLOC) {
2253 } else if (xen_enabled()) {
2254 abort();
2255 } else {
2256 flags = MAP_FIXED;
2257 flags |= block->flags & RAM_SHARED ?
2258 MAP_SHARED : MAP_PRIVATE;
2259 flags |= block->flags & RAM_NORESERVE ? MAP_NORESERVE : 0;
2260 if (block->fd >= 0) {
2261 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2262 flags, block->fd, offset);
2263 } else {
2264 flags |= MAP_ANONYMOUS;
2265 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2266 flags, -1, 0);
2268 if (area != vaddr) {
2269 error_report("Could not remap addr: "
2270 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2271 length, addr);
2272 exit(1);
2274 memory_try_enable_merging(vaddr, length);
2275 qemu_ram_setup_dump(vaddr, length);
2280 #endif /* !_WIN32 */
2282 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2283 * This should not be used for general purpose DMA. Use address_space_map
2284 * or address_space_rw instead. For local memory (e.g. video ram) that the
2285 * device owns, use memory_region_get_ram_ptr.
2287 * Called within RCU critical section.
2289 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2291 RAMBlock *block = ram_block;
2293 if (block == NULL) {
2294 block = qemu_get_ram_block(addr);
2295 addr -= block->offset;
2298 if (xen_enabled() && block->host == NULL) {
2299 /* We need to check if the requested address is in the RAM
2300 * because we don't want to map the entire memory in QEMU.
2301 * In that case just map until the end of the page.
2303 if (block->offset == 0) {
2304 return xen_map_cache(addr, 0, 0, false);
2307 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2309 return ramblock_ptr(block, addr);
2312 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2313 * but takes a size argument.
2315 * Called within RCU critical section.
2317 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2318 hwaddr *size, bool lock)
2320 RAMBlock *block = ram_block;
2321 if (*size == 0) {
2322 return NULL;
2325 if (block == NULL) {
2326 block = qemu_get_ram_block(addr);
2327 addr -= block->offset;
2329 *size = MIN(*size, block->max_length - addr);
2331 if (xen_enabled() && block->host == NULL) {
2332 /* We need to check if the requested address is in the RAM
2333 * because we don't want to map the entire memory in QEMU.
2334 * In that case just map the requested area.
2336 if (block->offset == 0) {
2337 return xen_map_cache(addr, *size, lock, lock);
2340 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2343 return ramblock_ptr(block, addr);
2346 /* Return the offset of a hostpointer within a ramblock */
2347 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2349 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2350 assert((uintptr_t)host >= (uintptr_t)rb->host);
2351 assert(res < rb->max_length);
2353 return res;
2357 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2358 * in that RAMBlock.
2360 * ptr: Host pointer to look up
2361 * round_offset: If true round the result offset down to a page boundary
2362 * *ram_addr: set to result ram_addr
2363 * *offset: set to result offset within the RAMBlock
2365 * Returns: RAMBlock (or NULL if not found)
2367 * By the time this function returns, the returned pointer is not protected
2368 * by RCU anymore. If the caller is not within an RCU critical section and
2369 * does not hold the iothread lock, it must have other means of protecting the
2370 * pointer, such as a reference to the region that includes the incoming
2371 * ram_addr_t.
2373 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2374 ram_addr_t *offset)
2376 RAMBlock *block;
2377 uint8_t *host = ptr;
2379 if (xen_enabled()) {
2380 ram_addr_t ram_addr;
2381 RCU_READ_LOCK_GUARD();
2382 ram_addr = xen_ram_addr_from_mapcache(ptr);
2383 block = qemu_get_ram_block(ram_addr);
2384 if (block) {
2385 *offset = ram_addr - block->offset;
2387 return block;
2390 RCU_READ_LOCK_GUARD();
2391 block = qatomic_rcu_read(&ram_list.mru_block);
2392 if (block && block->host && host - block->host < block->max_length) {
2393 goto found;
2396 RAMBLOCK_FOREACH(block) {
2397 /* This case append when the block is not mapped. */
2398 if (block->host == NULL) {
2399 continue;
2401 if (host - block->host < block->max_length) {
2402 goto found;
2406 return NULL;
2408 found:
2409 *offset = (host - block->host);
2410 if (round_offset) {
2411 *offset &= TARGET_PAGE_MASK;
2413 return block;
2417 * Finds the named RAMBlock
2419 * name: The name of RAMBlock to find
2421 * Returns: RAMBlock (or NULL if not found)
2423 RAMBlock *qemu_ram_block_by_name(const char *name)
2425 RAMBlock *block;
2427 RAMBLOCK_FOREACH(block) {
2428 if (!strcmp(name, block->idstr)) {
2429 return block;
2433 return NULL;
2436 /* Some of the softmmu routines need to translate from a host pointer
2437 (typically a TLB entry) back to a ram offset. */
2438 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2440 RAMBlock *block;
2441 ram_addr_t offset;
2443 block = qemu_ram_block_from_host(ptr, false, &offset);
2444 if (!block) {
2445 return RAM_ADDR_INVALID;
2448 return block->offset + offset;
2451 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2452 MemTxAttrs attrs, void *buf, hwaddr len);
2453 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2454 const void *buf, hwaddr len);
2455 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2456 bool is_write, MemTxAttrs attrs);
2458 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2459 unsigned len, MemTxAttrs attrs)
2461 subpage_t *subpage = opaque;
2462 uint8_t buf[8];
2463 MemTxResult res;
2465 #if defined(DEBUG_SUBPAGE)
2466 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2467 subpage, len, addr);
2468 #endif
2469 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2470 if (res) {
2471 return res;
2473 *data = ldn_p(buf, len);
2474 return MEMTX_OK;
2477 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2478 uint64_t value, unsigned len, MemTxAttrs attrs)
2480 subpage_t *subpage = opaque;
2481 uint8_t buf[8];
2483 #if defined(DEBUG_SUBPAGE)
2484 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2485 " value %"PRIx64"\n",
2486 __func__, subpage, len, addr, value);
2487 #endif
2488 stn_p(buf, len, value);
2489 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2492 static bool subpage_accepts(void *opaque, hwaddr addr,
2493 unsigned len, bool is_write,
2494 MemTxAttrs attrs)
2496 subpage_t *subpage = opaque;
2497 #if defined(DEBUG_SUBPAGE)
2498 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2499 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2500 #endif
2502 return flatview_access_valid(subpage->fv, addr + subpage->base,
2503 len, is_write, attrs);
2506 static const MemoryRegionOps subpage_ops = {
2507 .read_with_attrs = subpage_read,
2508 .write_with_attrs = subpage_write,
2509 .impl.min_access_size = 1,
2510 .impl.max_access_size = 8,
2511 .valid.min_access_size = 1,
2512 .valid.max_access_size = 8,
2513 .valid.accepts = subpage_accepts,
2514 .endianness = DEVICE_NATIVE_ENDIAN,
2517 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2518 uint16_t section)
2520 int idx, eidx;
2522 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2523 return -1;
2524 idx = SUBPAGE_IDX(start);
2525 eidx = SUBPAGE_IDX(end);
2526 #if defined(DEBUG_SUBPAGE)
2527 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2528 __func__, mmio, start, end, idx, eidx, section);
2529 #endif
2530 for (; idx <= eidx; idx++) {
2531 mmio->sub_section[idx] = section;
2534 return 0;
2537 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2539 subpage_t *mmio;
2541 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2542 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2543 mmio->fv = fv;
2544 mmio->base = base;
2545 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2546 NULL, TARGET_PAGE_SIZE);
2547 mmio->iomem.subpage = true;
2548 #if defined(DEBUG_SUBPAGE)
2549 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2550 mmio, base, TARGET_PAGE_SIZE);
2551 #endif
2553 return mmio;
2556 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2558 assert(fv);
2559 MemoryRegionSection section = {
2560 .fv = fv,
2561 .mr = mr,
2562 .offset_within_address_space = 0,
2563 .offset_within_region = 0,
2564 .size = int128_2_64(),
2567 return phys_section_add(map, &section);
2570 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2571 hwaddr index, MemTxAttrs attrs)
2573 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2574 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2575 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2576 MemoryRegionSection *sections = d->map.sections;
2578 return &sections[index & ~TARGET_PAGE_MASK];
2581 static void io_mem_init(void)
2583 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2584 NULL, UINT64_MAX);
2587 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2589 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2590 uint16_t n;
2592 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2593 assert(n == PHYS_SECTION_UNASSIGNED);
2595 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2597 return d;
2600 void address_space_dispatch_free(AddressSpaceDispatch *d)
2602 phys_sections_free(&d->map);
2603 g_free(d);
2606 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2610 static void tcg_log_global_after_sync(MemoryListener *listener)
2612 CPUAddressSpace *cpuas;
2614 /* Wait for the CPU to end the current TB. This avoids the following
2615 * incorrect race:
2617 * vCPU migration
2618 * ---------------------- -------------------------
2619 * TLB check -> slow path
2620 * notdirty_mem_write
2621 * write to RAM
2622 * mark dirty
2623 * clear dirty flag
2624 * TLB check -> fast path
2625 * read memory
2626 * write to RAM
2628 * by pushing the migration thread's memory read after the vCPU thread has
2629 * written the memory.
2631 if (replay_mode == REPLAY_MODE_NONE) {
2633 * VGA can make calls to this function while updating the screen.
2634 * In record/replay mode this causes a deadlock, because
2635 * run_on_cpu waits for rr mutex. Therefore no races are possible
2636 * in this case and no need for making run_on_cpu when
2637 * record/replay is enabled.
2639 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2640 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2644 static void tcg_commit(MemoryListener *listener)
2646 CPUAddressSpace *cpuas;
2647 AddressSpaceDispatch *d;
2649 assert(tcg_enabled());
2650 /* since each CPU stores ram addresses in its TLB cache, we must
2651 reset the modified entries */
2652 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2653 cpu_reloading_memory_map();
2654 /* The CPU and TLB are protected by the iothread lock.
2655 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2656 * may have split the RCU critical section.
2658 d = address_space_to_dispatch(cpuas->as);
2659 qatomic_rcu_set(&cpuas->memory_dispatch, d);
2660 tlb_flush(cpuas->cpu);
2663 static void memory_map_init(void)
2665 system_memory = g_malloc(sizeof(*system_memory));
2667 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2668 address_space_init(&address_space_memory, system_memory, "memory");
2670 system_io = g_malloc(sizeof(*system_io));
2671 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2672 65536);
2673 address_space_init(&address_space_io, system_io, "I/O");
2676 MemoryRegion *get_system_memory(void)
2678 return system_memory;
2681 MemoryRegion *get_system_io(void)
2683 return system_io;
2686 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2687 hwaddr length)
2689 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2690 addr += memory_region_get_ram_addr(mr);
2692 /* No early return if dirty_log_mask is or becomes 0, because
2693 * cpu_physical_memory_set_dirty_range will still call
2694 * xen_modified_memory.
2696 if (dirty_log_mask) {
2697 dirty_log_mask =
2698 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2700 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2701 assert(tcg_enabled());
2702 tb_invalidate_phys_range(addr, addr + length);
2703 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2705 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2708 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2711 * In principle this function would work on other memory region types too,
2712 * but the ROM device use case is the only one where this operation is
2713 * necessary. Other memory regions should use the
2714 * address_space_read/write() APIs.
2716 assert(memory_region_is_romd(mr));
2718 invalidate_and_set_dirty(mr, addr, size);
2721 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2723 unsigned access_size_max = mr->ops->valid.max_access_size;
2725 /* Regions are assumed to support 1-4 byte accesses unless
2726 otherwise specified. */
2727 if (access_size_max == 0) {
2728 access_size_max = 4;
2731 /* Bound the maximum access by the alignment of the address. */
2732 if (!mr->ops->impl.unaligned) {
2733 unsigned align_size_max = addr & -addr;
2734 if (align_size_max != 0 && align_size_max < access_size_max) {
2735 access_size_max = align_size_max;
2739 /* Don't attempt accesses larger than the maximum. */
2740 if (l > access_size_max) {
2741 l = access_size_max;
2743 l = pow2floor(l);
2745 return l;
2748 static bool prepare_mmio_access(MemoryRegion *mr)
2750 bool release_lock = false;
2752 if (!qemu_mutex_iothread_locked()) {
2753 qemu_mutex_lock_iothread();
2754 release_lock = true;
2756 if (mr->flush_coalesced_mmio) {
2757 qemu_flush_coalesced_mmio_buffer();
2760 return release_lock;
2763 /* Called within RCU critical section. */
2764 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2765 MemTxAttrs attrs,
2766 const void *ptr,
2767 hwaddr len, hwaddr addr1,
2768 hwaddr l, MemoryRegion *mr)
2770 uint8_t *ram_ptr;
2771 uint64_t val;
2772 MemTxResult result = MEMTX_OK;
2773 bool release_lock = false;
2774 const uint8_t *buf = ptr;
2776 for (;;) {
2777 if (!memory_access_is_direct(mr, true)) {
2778 release_lock |= prepare_mmio_access(mr);
2779 l = memory_access_size(mr, l, addr1);
2780 /* XXX: could force current_cpu to NULL to avoid
2781 potential bugs */
2782 val = ldn_he_p(buf, l);
2783 result |= memory_region_dispatch_write(mr, addr1, val,
2784 size_memop(l), attrs);
2785 } else {
2786 /* RAM case */
2787 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2788 memcpy(ram_ptr, buf, l);
2789 invalidate_and_set_dirty(mr, addr1, l);
2792 if (release_lock) {
2793 qemu_mutex_unlock_iothread();
2794 release_lock = false;
2797 len -= l;
2798 buf += l;
2799 addr += l;
2801 if (!len) {
2802 break;
2805 l = len;
2806 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2809 return result;
2812 /* Called from RCU critical section. */
2813 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2814 const void *buf, hwaddr len)
2816 hwaddr l;
2817 hwaddr addr1;
2818 MemoryRegion *mr;
2819 MemTxResult result = MEMTX_OK;
2821 l = len;
2822 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2823 result = flatview_write_continue(fv, addr, attrs, buf, len,
2824 addr1, l, mr);
2826 return result;
2829 /* Called within RCU critical section. */
2830 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2831 MemTxAttrs attrs, void *ptr,
2832 hwaddr len, hwaddr addr1, hwaddr l,
2833 MemoryRegion *mr)
2835 uint8_t *ram_ptr;
2836 uint64_t val;
2837 MemTxResult result = MEMTX_OK;
2838 bool release_lock = false;
2839 uint8_t *buf = ptr;
2841 fuzz_dma_read_cb(addr, len, mr);
2842 for (;;) {
2843 if (!memory_access_is_direct(mr, false)) {
2844 /* I/O case */
2845 release_lock |= prepare_mmio_access(mr);
2846 l = memory_access_size(mr, l, addr1);
2847 result |= memory_region_dispatch_read(mr, addr1, &val,
2848 size_memop(l), attrs);
2849 stn_he_p(buf, l, val);
2850 } else {
2851 /* RAM case */
2852 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2853 memcpy(buf, ram_ptr, l);
2856 if (release_lock) {
2857 qemu_mutex_unlock_iothread();
2858 release_lock = false;
2861 len -= l;
2862 buf += l;
2863 addr += l;
2865 if (!len) {
2866 break;
2869 l = len;
2870 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2873 return result;
2876 /* Called from RCU critical section. */
2877 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2878 MemTxAttrs attrs, void *buf, hwaddr len)
2880 hwaddr l;
2881 hwaddr addr1;
2882 MemoryRegion *mr;
2884 l = len;
2885 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2886 return flatview_read_continue(fv, addr, attrs, buf, len,
2887 addr1, l, mr);
2890 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2891 MemTxAttrs attrs, void *buf, hwaddr len)
2893 MemTxResult result = MEMTX_OK;
2894 FlatView *fv;
2896 if (len > 0) {
2897 RCU_READ_LOCK_GUARD();
2898 fv = address_space_to_flatview(as);
2899 result = flatview_read(fv, addr, attrs, buf, len);
2902 return result;
2905 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2906 MemTxAttrs attrs,
2907 const void *buf, hwaddr len)
2909 MemTxResult result = MEMTX_OK;
2910 FlatView *fv;
2912 if (len > 0) {
2913 RCU_READ_LOCK_GUARD();
2914 fv = address_space_to_flatview(as);
2915 result = flatview_write(fv, addr, attrs, buf, len);
2918 return result;
2921 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2922 void *buf, hwaddr len, bool is_write)
2924 if (is_write) {
2925 return address_space_write(as, addr, attrs, buf, len);
2926 } else {
2927 return address_space_read_full(as, addr, attrs, buf, len);
2931 MemTxResult address_space_set(AddressSpace *as, hwaddr addr,
2932 uint8_t c, hwaddr len, MemTxAttrs attrs)
2934 #define FILLBUF_SIZE 512
2935 uint8_t fillbuf[FILLBUF_SIZE];
2936 int l;
2937 MemTxResult error = MEMTX_OK;
2939 memset(fillbuf, c, FILLBUF_SIZE);
2940 while (len > 0) {
2941 l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
2942 error |= address_space_write(as, addr, attrs, fillbuf, l);
2943 len -= l;
2944 addr += l;
2947 return error;
2950 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2951 hwaddr len, bool is_write)
2953 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2954 buf, len, is_write);
2957 enum write_rom_type {
2958 WRITE_DATA,
2959 FLUSH_CACHE,
2962 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2963 hwaddr addr,
2964 MemTxAttrs attrs,
2965 const void *ptr,
2966 hwaddr len,
2967 enum write_rom_type type)
2969 hwaddr l;
2970 uint8_t *ram_ptr;
2971 hwaddr addr1;
2972 MemoryRegion *mr;
2973 const uint8_t *buf = ptr;
2975 RCU_READ_LOCK_GUARD();
2976 while (len > 0) {
2977 l = len;
2978 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2980 if (!(memory_region_is_ram(mr) ||
2981 memory_region_is_romd(mr))) {
2982 l = memory_access_size(mr, l, addr1);
2983 } else {
2984 /* ROM/RAM case */
2985 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2986 switch (type) {
2987 case WRITE_DATA:
2988 memcpy(ram_ptr, buf, l);
2989 invalidate_and_set_dirty(mr, addr1, l);
2990 break;
2991 case FLUSH_CACHE:
2992 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2993 break;
2996 len -= l;
2997 buf += l;
2998 addr += l;
3000 return MEMTX_OK;
3003 /* used for ROM loading : can write in RAM and ROM */
3004 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
3005 MemTxAttrs attrs,
3006 const void *buf, hwaddr len)
3008 return address_space_write_rom_internal(as, addr, attrs,
3009 buf, len, WRITE_DATA);
3012 void cpu_flush_icache_range(hwaddr start, hwaddr len)
3015 * This function should do the same thing as an icache flush that was
3016 * triggered from within the guest. For TCG we are always cache coherent,
3017 * so there is no need to flush anything. For KVM / Xen we need to flush
3018 * the host's instruction cache at least.
3020 if (tcg_enabled()) {
3021 return;
3024 address_space_write_rom_internal(&address_space_memory,
3025 start, MEMTXATTRS_UNSPECIFIED,
3026 NULL, len, FLUSH_CACHE);
3029 typedef struct {
3030 MemoryRegion *mr;
3031 void *buffer;
3032 hwaddr addr;
3033 hwaddr len;
3034 bool in_use;
3035 } BounceBuffer;
3037 static BounceBuffer bounce;
3039 typedef struct MapClient {
3040 QEMUBH *bh;
3041 QLIST_ENTRY(MapClient) link;
3042 } MapClient;
3044 QemuMutex map_client_list_lock;
3045 static QLIST_HEAD(, MapClient) map_client_list
3046 = QLIST_HEAD_INITIALIZER(map_client_list);
3048 static void cpu_unregister_map_client_do(MapClient *client)
3050 QLIST_REMOVE(client, link);
3051 g_free(client);
3054 static void cpu_notify_map_clients_locked(void)
3056 MapClient *client;
3058 while (!QLIST_EMPTY(&map_client_list)) {
3059 client = QLIST_FIRST(&map_client_list);
3060 qemu_bh_schedule(client->bh);
3061 cpu_unregister_map_client_do(client);
3065 void cpu_register_map_client(QEMUBH *bh)
3067 MapClient *client = g_malloc(sizeof(*client));
3069 qemu_mutex_lock(&map_client_list_lock);
3070 client->bh = bh;
3071 QLIST_INSERT_HEAD(&map_client_list, client, link);
3072 if (!qatomic_read(&bounce.in_use)) {
3073 cpu_notify_map_clients_locked();
3075 qemu_mutex_unlock(&map_client_list_lock);
3078 void cpu_exec_init_all(void)
3080 qemu_mutex_init(&ram_list.mutex);
3081 /* The data structures we set up here depend on knowing the page size,
3082 * so no more changes can be made after this point.
3083 * In an ideal world, nothing we did before we had finished the
3084 * machine setup would care about the target page size, and we could
3085 * do this much later, rather than requiring board models to state
3086 * up front what their requirements are.
3088 finalize_target_page_bits();
3089 io_mem_init();
3090 memory_map_init();
3091 qemu_mutex_init(&map_client_list_lock);
3094 void cpu_unregister_map_client(QEMUBH *bh)
3096 MapClient *client;
3098 qemu_mutex_lock(&map_client_list_lock);
3099 QLIST_FOREACH(client, &map_client_list, link) {
3100 if (client->bh == bh) {
3101 cpu_unregister_map_client_do(client);
3102 break;
3105 qemu_mutex_unlock(&map_client_list_lock);
3108 static void cpu_notify_map_clients(void)
3110 qemu_mutex_lock(&map_client_list_lock);
3111 cpu_notify_map_clients_locked();
3112 qemu_mutex_unlock(&map_client_list_lock);
3115 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3116 bool is_write, MemTxAttrs attrs)
3118 MemoryRegion *mr;
3119 hwaddr l, xlat;
3121 while (len > 0) {
3122 l = len;
3123 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3124 if (!memory_access_is_direct(mr, is_write)) {
3125 l = memory_access_size(mr, l, addr);
3126 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3127 return false;
3131 len -= l;
3132 addr += l;
3134 return true;
3137 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3138 hwaddr len, bool is_write,
3139 MemTxAttrs attrs)
3141 FlatView *fv;
3142 bool result;
3144 RCU_READ_LOCK_GUARD();
3145 fv = address_space_to_flatview(as);
3146 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3147 return result;
3150 static hwaddr
3151 flatview_extend_translation(FlatView *fv, hwaddr addr,
3152 hwaddr target_len,
3153 MemoryRegion *mr, hwaddr base, hwaddr len,
3154 bool is_write, MemTxAttrs attrs)
3156 hwaddr done = 0;
3157 hwaddr xlat;
3158 MemoryRegion *this_mr;
3160 for (;;) {
3161 target_len -= len;
3162 addr += len;
3163 done += len;
3164 if (target_len == 0) {
3165 return done;
3168 len = target_len;
3169 this_mr = flatview_translate(fv, addr, &xlat,
3170 &len, is_write, attrs);
3171 if (this_mr != mr || xlat != base + done) {
3172 return done;
3177 /* Map a physical memory region into a host virtual address.
3178 * May map a subset of the requested range, given by and returned in *plen.
3179 * May return NULL if resources needed to perform the mapping are exhausted.
3180 * Use only for reads OR writes - not for read-modify-write operations.
3181 * Use cpu_register_map_client() to know when retrying the map operation is
3182 * likely to succeed.
3184 void *address_space_map(AddressSpace *as,
3185 hwaddr addr,
3186 hwaddr *plen,
3187 bool is_write,
3188 MemTxAttrs attrs)
3190 hwaddr len = *plen;
3191 hwaddr l, xlat;
3192 MemoryRegion *mr;
3193 void *ptr;
3194 FlatView *fv;
3196 if (len == 0) {
3197 return NULL;
3200 l = len;
3201 RCU_READ_LOCK_GUARD();
3202 fv = address_space_to_flatview(as);
3203 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3205 if (!memory_access_is_direct(mr, is_write)) {
3206 if (qatomic_xchg(&bounce.in_use, true)) {
3207 *plen = 0;
3208 return NULL;
3210 /* Avoid unbounded allocations */
3211 l = MIN(l, TARGET_PAGE_SIZE);
3212 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3213 bounce.addr = addr;
3214 bounce.len = l;
3216 memory_region_ref(mr);
3217 bounce.mr = mr;
3218 if (!is_write) {
3219 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3220 bounce.buffer, l);
3223 *plen = l;
3224 return bounce.buffer;
3228 memory_region_ref(mr);
3229 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3230 l, is_write, attrs);
3231 fuzz_dma_read_cb(addr, *plen, mr);
3232 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3234 return ptr;
3237 /* Unmaps a memory region previously mapped by address_space_map().
3238 * Will also mark the memory as dirty if is_write is true. access_len gives
3239 * the amount of memory that was actually read or written by the caller.
3241 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3242 bool is_write, hwaddr access_len)
3244 if (buffer != bounce.buffer) {
3245 MemoryRegion *mr;
3246 ram_addr_t addr1;
3248 mr = memory_region_from_host(buffer, &addr1);
3249 assert(mr != NULL);
3250 if (is_write) {
3251 invalidate_and_set_dirty(mr, addr1, access_len);
3253 if (xen_enabled()) {
3254 xen_invalidate_map_cache_entry(buffer);
3256 memory_region_unref(mr);
3257 return;
3259 if (is_write) {
3260 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3261 bounce.buffer, access_len);
3263 qemu_vfree(bounce.buffer);
3264 bounce.buffer = NULL;
3265 memory_region_unref(bounce.mr);
3266 qatomic_mb_set(&bounce.in_use, false);
3267 cpu_notify_map_clients();
3270 void *cpu_physical_memory_map(hwaddr addr,
3271 hwaddr *plen,
3272 bool is_write)
3274 return address_space_map(&address_space_memory, addr, plen, is_write,
3275 MEMTXATTRS_UNSPECIFIED);
3278 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3279 bool is_write, hwaddr access_len)
3281 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3284 #define ARG1_DECL AddressSpace *as
3285 #define ARG1 as
3286 #define SUFFIX
3287 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3288 #define RCU_READ_LOCK(...) rcu_read_lock()
3289 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3290 #include "memory_ldst.c.inc"
3292 int64_t address_space_cache_init(MemoryRegionCache *cache,
3293 AddressSpace *as,
3294 hwaddr addr,
3295 hwaddr len,
3296 bool is_write)
3298 AddressSpaceDispatch *d;
3299 hwaddr l;
3300 MemoryRegion *mr;
3301 Int128 diff;
3303 assert(len > 0);
3305 l = len;
3306 cache->fv = address_space_get_flatview(as);
3307 d = flatview_to_dispatch(cache->fv);
3308 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3311 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3312 * Take that into account to compute how many bytes are there between
3313 * cache->xlat and the end of the section.
3315 diff = int128_sub(cache->mrs.size,
3316 int128_make64(cache->xlat - cache->mrs.offset_within_region));
3317 l = int128_get64(int128_min(diff, int128_make64(l)));
3319 mr = cache->mrs.mr;
3320 memory_region_ref(mr);
3321 if (memory_access_is_direct(mr, is_write)) {
3322 /* We don't care about the memory attributes here as we're only
3323 * doing this if we found actual RAM, which behaves the same
3324 * regardless of attributes; so UNSPECIFIED is fine.
3326 l = flatview_extend_translation(cache->fv, addr, len, mr,
3327 cache->xlat, l, is_write,
3328 MEMTXATTRS_UNSPECIFIED);
3329 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3330 } else {
3331 cache->ptr = NULL;
3334 cache->len = l;
3335 cache->is_write = is_write;
3336 return l;
3339 void address_space_cache_invalidate(MemoryRegionCache *cache,
3340 hwaddr addr,
3341 hwaddr access_len)
3343 assert(cache->is_write);
3344 if (likely(cache->ptr)) {
3345 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3349 void address_space_cache_destroy(MemoryRegionCache *cache)
3351 if (!cache->mrs.mr) {
3352 return;
3355 if (xen_enabled()) {
3356 xen_invalidate_map_cache_entry(cache->ptr);
3358 memory_region_unref(cache->mrs.mr);
3359 flatview_unref(cache->fv);
3360 cache->mrs.mr = NULL;
3361 cache->fv = NULL;
3364 /* Called from RCU critical section. This function has the same
3365 * semantics as address_space_translate, but it only works on a
3366 * predefined range of a MemoryRegion that was mapped with
3367 * address_space_cache_init.
3369 static inline MemoryRegion *address_space_translate_cached(
3370 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3371 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3373 MemoryRegionSection section;
3374 MemoryRegion *mr;
3375 IOMMUMemoryRegion *iommu_mr;
3376 AddressSpace *target_as;
3378 assert(!cache->ptr);
3379 *xlat = addr + cache->xlat;
3381 mr = cache->mrs.mr;
3382 iommu_mr = memory_region_get_iommu(mr);
3383 if (!iommu_mr) {
3384 /* MMIO region. */
3385 return mr;
3388 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3389 NULL, is_write, true,
3390 &target_as, attrs);
3391 return section.mr;
3394 /* Called from RCU critical section. address_space_read_cached uses this
3395 * out of line function when the target is an MMIO or IOMMU region.
3397 MemTxResult
3398 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3399 void *buf, hwaddr len)
3401 hwaddr addr1, l;
3402 MemoryRegion *mr;
3404 l = len;
3405 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3406 MEMTXATTRS_UNSPECIFIED);
3407 return flatview_read_continue(cache->fv,
3408 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3409 addr1, l, mr);
3412 /* Called from RCU critical section. address_space_write_cached uses this
3413 * out of line function when the target is an MMIO or IOMMU region.
3415 MemTxResult
3416 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3417 const void *buf, hwaddr len)
3419 hwaddr addr1, l;
3420 MemoryRegion *mr;
3422 l = len;
3423 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3424 MEMTXATTRS_UNSPECIFIED);
3425 return flatview_write_continue(cache->fv,
3426 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3427 addr1, l, mr);
3430 #define ARG1_DECL MemoryRegionCache *cache
3431 #define ARG1 cache
3432 #define SUFFIX _cached_slow
3433 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3434 #define RCU_READ_LOCK() ((void)0)
3435 #define RCU_READ_UNLOCK() ((void)0)
3436 #include "memory_ldst.c.inc"
3438 /* virtual memory access for debug (includes writing to ROM) */
3439 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3440 void *ptr, target_ulong len, bool is_write)
3442 hwaddr phys_addr;
3443 target_ulong l, page;
3444 uint8_t *buf = ptr;
3446 cpu_synchronize_state(cpu);
3447 while (len > 0) {
3448 int asidx;
3449 MemTxAttrs attrs;
3450 MemTxResult res;
3452 page = addr & TARGET_PAGE_MASK;
3453 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3454 asidx = cpu_asidx_from_attrs(cpu, attrs);
3455 /* if no physical page mapped, return an error */
3456 if (phys_addr == -1)
3457 return -1;
3458 l = (page + TARGET_PAGE_SIZE) - addr;
3459 if (l > len)
3460 l = len;
3461 phys_addr += (addr & ~TARGET_PAGE_MASK);
3462 if (is_write) {
3463 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3464 attrs, buf, l);
3465 } else {
3466 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3467 attrs, buf, l);
3469 if (res != MEMTX_OK) {
3470 return -1;
3472 len -= l;
3473 buf += l;
3474 addr += l;
3476 return 0;
3480 * Allows code that needs to deal with migration bitmaps etc to still be built
3481 * target independent.
3483 size_t qemu_target_page_size(void)
3485 return TARGET_PAGE_SIZE;
3488 int qemu_target_page_bits(void)
3490 return TARGET_PAGE_BITS;
3493 int qemu_target_page_bits_min(void)
3495 return TARGET_PAGE_BITS_MIN;
3498 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3500 MemoryRegion*mr;
3501 hwaddr l = 1;
3502 bool res;
3504 RCU_READ_LOCK_GUARD();
3505 mr = address_space_translate(&address_space_memory,
3506 phys_addr, &phys_addr, &l, false,
3507 MEMTXATTRS_UNSPECIFIED);
3509 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3510 return res;
3513 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3515 RAMBlock *block;
3516 int ret = 0;
3518 RCU_READ_LOCK_GUARD();
3519 RAMBLOCK_FOREACH(block) {
3520 ret = func(block, opaque);
3521 if (ret) {
3522 break;
3525 return ret;
3529 * Unmap pages of memory from start to start+length such that
3530 * they a) read as 0, b) Trigger whatever fault mechanism
3531 * the OS provides for postcopy.
3532 * The pages must be unmapped by the end of the function.
3533 * Returns: 0 on success, none-0 on failure
3536 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3538 int ret = -1;
3540 uint8_t *host_startaddr = rb->host + start;
3542 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3543 error_report("ram_block_discard_range: Unaligned start address: %p",
3544 host_startaddr);
3545 goto err;
3548 if ((start + length) <= rb->max_length) {
3549 bool need_madvise, need_fallocate;
3550 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3551 error_report("ram_block_discard_range: Unaligned length: %zx",
3552 length);
3553 goto err;
3556 errno = ENOTSUP; /* If we are missing MADVISE etc */
3558 /* The logic here is messy;
3559 * madvise DONTNEED fails for hugepages
3560 * fallocate works on hugepages and shmem
3561 * shared anonymous memory requires madvise REMOVE
3563 need_madvise = (rb->page_size == qemu_host_page_size);
3564 need_fallocate = rb->fd != -1;
3565 if (need_fallocate) {
3566 /* For a file, this causes the area of the file to be zero'd
3567 * if read, and for hugetlbfs also causes it to be unmapped
3568 * so a userfault will trigger.
3570 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3571 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3572 start, length);
3573 if (ret) {
3574 ret = -errno;
3575 error_report("ram_block_discard_range: Failed to fallocate "
3576 "%s:%" PRIx64 " +%zx (%d)",
3577 rb->idstr, start, length, ret);
3578 goto err;
3580 #else
3581 ret = -ENOSYS;
3582 error_report("ram_block_discard_range: fallocate not available/file"
3583 "%s:%" PRIx64 " +%zx (%d)",
3584 rb->idstr, start, length, ret);
3585 goto err;
3586 #endif
3588 if (need_madvise) {
3589 /* For normal RAM this causes it to be unmapped,
3590 * for shared memory it causes the local mapping to disappear
3591 * and to fall back on the file contents (which we just
3592 * fallocate'd away).
3594 #if defined(CONFIG_MADVISE)
3595 if (qemu_ram_is_shared(rb) && rb->fd < 0) {
3596 ret = madvise(host_startaddr, length, QEMU_MADV_REMOVE);
3597 } else {
3598 ret = madvise(host_startaddr, length, QEMU_MADV_DONTNEED);
3600 if (ret) {
3601 ret = -errno;
3602 error_report("ram_block_discard_range: Failed to discard range "
3603 "%s:%" PRIx64 " +%zx (%d)",
3604 rb->idstr, start, length, ret);
3605 goto err;
3607 #else
3608 ret = -ENOSYS;
3609 error_report("ram_block_discard_range: MADVISE not available"
3610 "%s:%" PRIx64 " +%zx (%d)",
3611 rb->idstr, start, length, ret);
3612 goto err;
3613 #endif
3615 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3616 need_madvise, need_fallocate, ret);
3617 } else {
3618 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3619 "/%zx/" RAM_ADDR_FMT")",
3620 rb->idstr, start, length, rb->max_length);
3623 err:
3624 return ret;
3627 bool ramblock_is_pmem(RAMBlock *rb)
3629 return rb->flags & RAM_PMEM;
3632 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3634 if (start == end - 1) {
3635 qemu_printf("\t%3d ", start);
3636 } else {
3637 qemu_printf("\t%3d..%-3d ", start, end - 1);
3639 qemu_printf(" skip=%d ", skip);
3640 if (ptr == PHYS_MAP_NODE_NIL) {
3641 qemu_printf(" ptr=NIL");
3642 } else if (!skip) {
3643 qemu_printf(" ptr=#%d", ptr);
3644 } else {
3645 qemu_printf(" ptr=[%d]", ptr);
3647 qemu_printf("\n");
3650 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3651 int128_sub((size), int128_one())) : 0)
3653 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3655 int i;
3657 qemu_printf(" Dispatch\n");
3658 qemu_printf(" Physical sections\n");
3660 for (i = 0; i < d->map.sections_nb; ++i) {
3661 MemoryRegionSection *s = d->map.sections + i;
3662 const char *names[] = { " [unassigned]", " [not dirty]",
3663 " [ROM]", " [watch]" };
3665 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3666 " %s%s%s%s%s",
3668 s->offset_within_address_space,
3669 s->offset_within_address_space + MR_SIZE(s->mr->size),
3670 s->mr->name ? s->mr->name : "(noname)",
3671 i < ARRAY_SIZE(names) ? names[i] : "",
3672 s->mr == root ? " [ROOT]" : "",
3673 s == d->mru_section ? " [MRU]" : "",
3674 s->mr->is_iommu ? " [iommu]" : "");
3676 if (s->mr->alias) {
3677 qemu_printf(" alias=%s", s->mr->alias->name ?
3678 s->mr->alias->name : "noname");
3680 qemu_printf("\n");
3683 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3684 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3685 for (i = 0; i < d->map.nodes_nb; ++i) {
3686 int j, jprev;
3687 PhysPageEntry prev;
3688 Node *n = d->map.nodes + i;
3690 qemu_printf(" [%d]\n", i);
3692 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3693 PhysPageEntry *pe = *n + j;
3695 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3696 continue;
3699 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3701 jprev = j;
3702 prev = *pe;
3705 if (jprev != ARRAY_SIZE(*n)) {
3706 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3711 /* Require any discards to work. */
3712 static unsigned int ram_block_discard_required_cnt;
3713 /* Require only coordinated discards to work. */
3714 static unsigned int ram_block_coordinated_discard_required_cnt;
3715 /* Disable any discards. */
3716 static unsigned int ram_block_discard_disabled_cnt;
3717 /* Disable only uncoordinated discards. */
3718 static unsigned int ram_block_uncoordinated_discard_disabled_cnt;
3719 static QemuMutex ram_block_discard_disable_mutex;
3721 static void ram_block_discard_disable_mutex_lock(void)
3723 static gsize initialized;
3725 if (g_once_init_enter(&initialized)) {
3726 qemu_mutex_init(&ram_block_discard_disable_mutex);
3727 g_once_init_leave(&initialized, 1);
3729 qemu_mutex_lock(&ram_block_discard_disable_mutex);
3732 static void ram_block_discard_disable_mutex_unlock(void)
3734 qemu_mutex_unlock(&ram_block_discard_disable_mutex);
3737 int ram_block_discard_disable(bool state)
3739 int ret = 0;
3741 ram_block_discard_disable_mutex_lock();
3742 if (!state) {
3743 ram_block_discard_disabled_cnt--;
3744 } else if (ram_block_discard_required_cnt ||
3745 ram_block_coordinated_discard_required_cnt) {
3746 ret = -EBUSY;
3747 } else {
3748 ram_block_discard_disabled_cnt++;
3750 ram_block_discard_disable_mutex_unlock();
3751 return ret;
3754 int ram_block_uncoordinated_discard_disable(bool state)
3756 int ret = 0;
3758 ram_block_discard_disable_mutex_lock();
3759 if (!state) {
3760 ram_block_uncoordinated_discard_disabled_cnt--;
3761 } else if (ram_block_discard_required_cnt) {
3762 ret = -EBUSY;
3763 } else {
3764 ram_block_uncoordinated_discard_disabled_cnt++;
3766 ram_block_discard_disable_mutex_unlock();
3767 return ret;
3770 int ram_block_discard_require(bool state)
3772 int ret = 0;
3774 ram_block_discard_disable_mutex_lock();
3775 if (!state) {
3776 ram_block_discard_required_cnt--;
3777 } else if (ram_block_discard_disabled_cnt ||
3778 ram_block_uncoordinated_discard_disabled_cnt) {
3779 ret = -EBUSY;
3780 } else {
3781 ram_block_discard_required_cnt++;
3783 ram_block_discard_disable_mutex_unlock();
3784 return ret;
3787 int ram_block_coordinated_discard_require(bool state)
3789 int ret = 0;
3791 ram_block_discard_disable_mutex_lock();
3792 if (!state) {
3793 ram_block_coordinated_discard_required_cnt--;
3794 } else if (ram_block_discard_disabled_cnt) {
3795 ret = -EBUSY;
3796 } else {
3797 ram_block_coordinated_discard_required_cnt++;
3799 ram_block_discard_disable_mutex_unlock();
3800 return ret;
3803 bool ram_block_discard_is_disabled(void)
3805 return qatomic_read(&ram_block_discard_disabled_cnt) ||
3806 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt);
3809 bool ram_block_discard_is_required(void)
3811 return qatomic_read(&ram_block_discard_required_cnt) ||
3812 qatomic_read(&ram_block_coordinated_discard_required_cnt);