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"
28 #include "hw/core/tcg-cpu-ops.h"
29 #endif /* CONFIG_TCG */
31 #include "exec/exec-all.h"
32 #include "exec/target_page.h"
33 #include "hw/qdev-core.h"
34 #include "hw/qdev-properties.h"
35 #include "hw/boards.h"
36 #include "hw/xen/xen.h"
37 #include "sysemu/kvm.h"
38 #include "sysemu/tcg.h"
39 #include "sysemu/qtest.h"
40 #include "qemu/timer.h"
41 #include "qemu/config-file.h"
42 #include "qemu/error-report.h"
43 #include "qemu/qemu-print.h"
44 #include "exec/memory.h"
45 #include "exec/ioport.h"
46 #include "sysemu/dma.h"
47 #include "sysemu/hostmem.h"
48 #include "sysemu/hw_accel.h"
49 #include "sysemu/xen-mapcache.h"
50 #include "trace/trace-root.h"
52 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
53 #include <linux/falloc.h>
56 #include "qemu/rcu_queue.h"
57 #include "qemu/main-loop.h"
58 #include "exec/translate-all.h"
59 #include "sysemu/replay.h"
61 #include "exec/memory-internal.h"
62 #include "exec/ram_addr.h"
65 #include "qemu/pmem.h"
67 #include "migration/vmstate.h"
69 #include "qemu/range.h"
71 #include "qemu/mmap-alloc.h"
74 #include "monitor/monitor.h"
76 #ifdef CONFIG_LIBDAXCTL
77 #include <daxctl/libdaxctl.h>
80 //#define DEBUG_SUBPAGE
82 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
83 * are protected by the ramlist lock.
85 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
87 static MemoryRegion
*system_memory
;
88 static MemoryRegion
*system_io
;
90 AddressSpace address_space_io
;
91 AddressSpace address_space_memory
;
93 static MemoryRegion io_mem_unassigned
;
95 typedef struct PhysPageEntry PhysPageEntry
;
97 struct PhysPageEntry
{
98 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
100 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
104 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
106 /* Size of the L2 (and L3, etc) page tables. */
107 #define ADDR_SPACE_BITS 64
110 #define P_L2_SIZE (1 << P_L2_BITS)
112 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
114 typedef PhysPageEntry Node
[P_L2_SIZE
];
116 typedef struct PhysPageMap
{
119 unsigned sections_nb
;
120 unsigned sections_nb_alloc
;
122 unsigned nodes_nb_alloc
;
124 MemoryRegionSection
*sections
;
127 struct AddressSpaceDispatch
{
128 MemoryRegionSection
*mru_section
;
129 /* This is a multi-level map on the physical address space.
130 * The bottom level has pointers to MemoryRegionSections.
132 PhysPageEntry phys_map
;
136 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
137 typedef struct subpage_t
{
141 uint16_t sub_section
[];
144 #define PHYS_SECTION_UNASSIGNED 0
146 static void io_mem_init(void);
147 static void memory_map_init(void);
148 static void tcg_log_global_after_sync(MemoryListener
*listener
);
149 static void tcg_commit(MemoryListener
*listener
);
152 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
153 * @cpu: the CPU whose AddressSpace this is
154 * @as: the AddressSpace itself
155 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
156 * @tcg_as_listener: listener for tracking changes to the AddressSpace
158 struct CPUAddressSpace
{
161 struct AddressSpaceDispatch
*memory_dispatch
;
162 MemoryListener tcg_as_listener
;
165 struct DirtyBitmapSnapshot
{
168 unsigned long dirty
[];
171 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
173 static unsigned alloc_hint
= 16;
174 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
175 map
->nodes_nb_alloc
= MAX(alloc_hint
, map
->nodes_nb
+ nodes
);
176 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
177 alloc_hint
= map
->nodes_nb_alloc
;
181 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
188 ret
= map
->nodes_nb
++;
190 assert(ret
!= PHYS_MAP_NODE_NIL
);
191 assert(ret
!= map
->nodes_nb_alloc
);
193 e
.skip
= leaf
? 0 : 1;
194 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
195 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
196 memcpy(&p
[i
], &e
, sizeof(e
));
201 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
202 hwaddr
*index
, uint64_t *nb
, uint16_t leaf
,
206 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
208 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
209 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
211 p
= map
->nodes
[lp
->ptr
];
212 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
214 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
215 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
221 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
227 static void phys_page_set(AddressSpaceDispatch
*d
,
228 hwaddr index
, uint64_t nb
,
231 /* Wildly overreserve - it doesn't matter much. */
232 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
234 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
237 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
238 * and update our entry so we can skip it and go directly to the destination.
240 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
242 unsigned valid_ptr
= P_L2_SIZE
;
247 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
252 for (i
= 0; i
< P_L2_SIZE
; i
++) {
253 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
260 phys_page_compact(&p
[i
], nodes
);
264 /* We can only compress if there's only one child. */
269 assert(valid_ptr
< P_L2_SIZE
);
271 /* Don't compress if it won't fit in the # of bits we have. */
272 if (P_L2_LEVELS
>= (1 << 6) &&
273 lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 6)) {
277 lp
->ptr
= p
[valid_ptr
].ptr
;
278 if (!p
[valid_ptr
].skip
) {
279 /* If our only child is a leaf, make this a leaf. */
280 /* By design, we should have made this node a leaf to begin with so we
281 * should never reach here.
282 * But since it's so simple to handle this, let's do it just in case we
287 lp
->skip
+= p
[valid_ptr
].skip
;
291 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
293 if (d
->phys_map
.skip
) {
294 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
298 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
301 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
302 * the section must cover the entire address space.
304 return int128_gethi(section
->size
) ||
305 range_covers_byte(section
->offset_within_address_space
,
306 int128_getlo(section
->size
), addr
);
309 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
311 PhysPageEntry lp
= d
->phys_map
, *p
;
312 Node
*nodes
= d
->map
.nodes
;
313 MemoryRegionSection
*sections
= d
->map
.sections
;
314 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
317 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
318 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
319 return §ions
[PHYS_SECTION_UNASSIGNED
];
322 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
325 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
326 return §ions
[lp
.ptr
];
328 return §ions
[PHYS_SECTION_UNASSIGNED
];
332 /* Called from RCU critical section */
333 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
335 bool resolve_subpage
)
337 MemoryRegionSection
*section
= qatomic_read(&d
->mru_section
);
340 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
341 !section_covers_addr(section
, addr
)) {
342 section
= phys_page_find(d
, addr
);
343 qatomic_set(&d
->mru_section
, section
);
345 if (resolve_subpage
&& section
->mr
->subpage
) {
346 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
347 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
352 /* Called from RCU critical section */
353 static MemoryRegionSection
*
354 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
355 hwaddr
*plen
, bool resolve_subpage
)
357 MemoryRegionSection
*section
;
361 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
362 /* Compute offset within MemoryRegionSection */
363 addr
-= section
->offset_within_address_space
;
365 /* Compute offset within MemoryRegion */
366 *xlat
= addr
+ section
->offset_within_region
;
370 /* MMIO registers can be expected to perform full-width accesses based only
371 * on their address, without considering adjacent registers that could
372 * decode to completely different MemoryRegions. When such registers
373 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
374 * regions overlap wildly. For this reason we cannot clamp the accesses
377 * If the length is small (as is the case for address_space_ldl/stl),
378 * everything works fine. If the incoming length is large, however,
379 * the caller really has to do the clamping through memory_access_size.
381 if (memory_region_is_ram(mr
)) {
382 diff
= int128_sub(section
->size
, int128_make64(addr
));
383 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
389 * address_space_translate_iommu - translate an address through an IOMMU
390 * memory region and then through the target address space.
392 * @iommu_mr: the IOMMU memory region that we start the translation from
393 * @addr: the address to be translated through the MMU
394 * @xlat: the translated address offset within the destination memory region.
395 * It cannot be %NULL.
396 * @plen_out: valid read/write length of the translated address. It
398 * @page_mask_out: page mask for the translated address. This
399 * should only be meaningful for IOMMU translated
400 * addresses, since there may be huge pages that this bit
401 * would tell. It can be %NULL if we don't care about it.
402 * @is_write: whether the translation operation is for write
403 * @is_mmio: whether this can be MMIO, set true if it can
404 * @target_as: the address space targeted by the IOMMU
405 * @attrs: transaction attributes
407 * This function is called from RCU critical section. It is the common
408 * part of flatview_do_translate and address_space_translate_cached.
410 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
413 hwaddr
*page_mask_out
,
416 AddressSpace
**target_as
,
419 MemoryRegionSection
*section
;
420 hwaddr page_mask
= (hwaddr
)-1;
424 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
428 if (imrc
->attrs_to_index
) {
429 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
432 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
433 IOMMU_WO
: IOMMU_RO
, iommu_idx
);
435 if (!(iotlb
.perm
& (1 << is_write
))) {
439 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
440 | (addr
& iotlb
.addr_mask
));
441 page_mask
&= iotlb
.addr_mask
;
442 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
443 *target_as
= iotlb
.target_as
;
445 section
= address_space_translate_internal(
446 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
449 iommu_mr
= memory_region_get_iommu(section
->mr
);
450 } while (unlikely(iommu_mr
));
453 *page_mask_out
= page_mask
;
458 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
462 * flatview_do_translate - translate an address in FlatView
464 * @fv: the flat view that we want to translate on
465 * @addr: the address to be translated in above address space
466 * @xlat: the translated address offset within memory region. It
468 * @plen_out: valid read/write length of the translated address. It
469 * can be @NULL when we don't care about it.
470 * @page_mask_out: page mask for the translated address. This
471 * should only be meaningful for IOMMU translated
472 * addresses, since there may be huge pages that this bit
473 * would tell. It can be @NULL if we don't care about it.
474 * @is_write: whether the translation operation is for write
475 * @is_mmio: whether this can be MMIO, set true if it can
476 * @target_as: the address space targeted by the IOMMU
477 * @attrs: memory transaction attributes
479 * This function is called from RCU critical section
481 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
485 hwaddr
*page_mask_out
,
488 AddressSpace
**target_as
,
491 MemoryRegionSection
*section
;
492 IOMMUMemoryRegion
*iommu_mr
;
493 hwaddr plen
= (hwaddr
)(-1);
499 section
= address_space_translate_internal(
500 flatview_to_dispatch(fv
), addr
, xlat
,
503 iommu_mr
= memory_region_get_iommu(section
->mr
);
504 if (unlikely(iommu_mr
)) {
505 return address_space_translate_iommu(iommu_mr
, xlat
,
506 plen_out
, page_mask_out
,
511 /* Not behind an IOMMU, use default page size. */
512 *page_mask_out
= ~TARGET_PAGE_MASK
;
518 /* Called from RCU critical section */
519 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
520 bool is_write
, MemTxAttrs attrs
)
522 MemoryRegionSection section
;
523 hwaddr xlat
, page_mask
;
526 * This can never be MMIO, and we don't really care about plen,
529 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
530 NULL
, &page_mask
, is_write
, false, &as
,
533 /* Illegal translation */
534 if (section
.mr
== &io_mem_unassigned
) {
538 /* Convert memory region offset into address space offset */
539 xlat
+= section
.offset_within_address_space
-
540 section
.offset_within_region
;
542 return (IOMMUTLBEntry
) {
544 .iova
= addr
& ~page_mask
,
545 .translated_addr
= xlat
& ~page_mask
,
546 .addr_mask
= page_mask
,
547 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
552 return (IOMMUTLBEntry
) {0};
555 /* Called from RCU critical section */
556 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
557 hwaddr
*plen
, bool is_write
,
561 MemoryRegionSection section
;
562 AddressSpace
*as
= NULL
;
564 /* This can be MMIO, so setup MMIO bit. */
565 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
566 is_write
, true, &as
, attrs
);
569 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
570 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
571 *plen
= MIN(page
, *plen
);
577 typedef struct TCGIOMMUNotifier
{
585 static void tcg_iommu_unmap_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
587 TCGIOMMUNotifier
*notifier
= container_of(n
, TCGIOMMUNotifier
, n
);
589 if (!notifier
->active
) {
592 tlb_flush(notifier
->cpu
);
593 notifier
->active
= false;
594 /* We leave the notifier struct on the list to avoid reallocating it later.
595 * Generally the number of IOMMUs a CPU deals with will be small.
596 * In any case we can't unregister the iommu notifier from a notify
601 static void tcg_register_iommu_notifier(CPUState
*cpu
,
602 IOMMUMemoryRegion
*iommu_mr
,
605 /* Make sure this CPU has an IOMMU notifier registered for this
606 * IOMMU/IOMMU index combination, so that we can flush its TLB
607 * when the IOMMU tells us the mappings we've cached have changed.
609 MemoryRegion
*mr
= MEMORY_REGION(iommu_mr
);
610 TCGIOMMUNotifier
*notifier
= NULL
;
613 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
614 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
615 if (notifier
->mr
== mr
&& notifier
->iommu_idx
== iommu_idx
) {
619 if (i
== cpu
->iommu_notifiers
->len
) {
620 /* Not found, add a new entry at the end of the array */
621 cpu
->iommu_notifiers
= g_array_set_size(cpu
->iommu_notifiers
, i
+ 1);
622 notifier
= g_new0(TCGIOMMUNotifier
, 1);
623 g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
) = notifier
;
626 notifier
->iommu_idx
= iommu_idx
;
628 /* Rather than trying to register interest in the specific part
629 * of the iommu's address space that we've accessed and then
630 * expand it later as subsequent accesses touch more of it, we
631 * just register interest in the whole thing, on the assumption
632 * that iommu reconfiguration will be rare.
634 iommu_notifier_init(¬ifier
->n
,
635 tcg_iommu_unmap_notify
,
636 IOMMU_NOTIFIER_UNMAP
,
640 memory_region_register_iommu_notifier(notifier
->mr
, ¬ifier
->n
,
644 if (!notifier
->active
) {
645 notifier
->active
= true;
649 void tcg_iommu_free_notifier_list(CPUState
*cpu
)
651 /* Destroy the CPU's notifier list */
653 TCGIOMMUNotifier
*notifier
;
655 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
656 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
657 memory_region_unregister_iommu_notifier(notifier
->mr
, ¬ifier
->n
);
660 g_array_free(cpu
->iommu_notifiers
, true);
663 void tcg_iommu_init_notifier_list(CPUState
*cpu
)
665 cpu
->iommu_notifiers
= g_array_new(false, true, sizeof(TCGIOMMUNotifier
*));
668 /* Called from RCU critical section */
669 MemoryRegionSection
*
670 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr addr
,
671 hwaddr
*xlat
, hwaddr
*plen
,
672 MemTxAttrs attrs
, int *prot
)
674 MemoryRegionSection
*section
;
675 IOMMUMemoryRegion
*iommu_mr
;
676 IOMMUMemoryRegionClass
*imrc
;
679 AddressSpaceDispatch
*d
=
680 qatomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
683 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
685 iommu_mr
= memory_region_get_iommu(section
->mr
);
690 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
692 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
693 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
694 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
695 * doesn't short-cut its translation table walk.
697 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
698 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
699 | (addr
& iotlb
.addr_mask
));
700 /* Update the caller's prot bits to remove permissions the IOMMU
701 * is giving us a failure response for. If we get down to no
702 * permissions left at all we can give up now.
704 if (!(iotlb
.perm
& IOMMU_RO
)) {
705 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
707 if (!(iotlb
.perm
& IOMMU_WO
)) {
708 *prot
&= ~PAGE_WRITE
;
715 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
718 assert(!memory_region_is_iommu(section
->mr
));
723 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
726 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
727 const char *prefix
, MemoryRegion
*mr
)
729 CPUAddressSpace
*newas
;
730 AddressSpace
*as
= g_new0(AddressSpace
, 1);
734 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
735 address_space_init(as
, mr
, as_name
);
738 /* Target code should have set num_ases before calling us */
739 assert(asidx
< cpu
->num_ases
);
742 /* address space 0 gets the convenience alias */
746 /* KVM cannot currently support multiple address spaces. */
747 assert(asidx
== 0 || !kvm_enabled());
749 if (!cpu
->cpu_ases
) {
750 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
753 newas
= &cpu
->cpu_ases
[asidx
];
757 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
758 newas
->tcg_as_listener
.commit
= tcg_commit
;
759 newas
->tcg_as_listener
.name
= "tcg";
760 memory_listener_register(&newas
->tcg_as_listener
, as
);
764 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
766 /* Return the AddressSpace corresponding to the specified index */
767 return cpu
->cpu_ases
[asidx
].as
;
770 /* Add a watchpoint. */
771 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
772 int flags
, CPUWatchpoint
**watchpoint
)
777 /* forbid ranges which are empty or run off the end of the address space */
778 if (len
== 0 || (addr
+ len
- 1) < addr
) {
779 error_report("tried to set invalid watchpoint at %"
780 VADDR_PRIx
", len=%" VADDR_PRIu
, addr
, len
);
783 wp
= g_malloc(sizeof(*wp
));
789 /* keep all GDB-injected watchpoints in front */
790 if (flags
& BP_GDB
) {
791 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
793 QTAILQ_INSERT_TAIL(&cpu
->watchpoints
, wp
, entry
);
796 in_page
= -(addr
| TARGET_PAGE_MASK
);
797 if (len
<= in_page
) {
798 tlb_flush_page(cpu
, addr
);
808 /* Remove a specific watchpoint. */
809 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
814 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
815 if (addr
== wp
->vaddr
&& len
== wp
->len
816 && flags
== (wp
->flags
& ~BP_WATCHPOINT_HIT
)) {
817 cpu_watchpoint_remove_by_ref(cpu
, wp
);
824 /* Remove a specific watchpoint by reference. */
825 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
827 QTAILQ_REMOVE(&cpu
->watchpoints
, watchpoint
, entry
);
829 tlb_flush_page(cpu
, watchpoint
->vaddr
);
834 /* Remove all matching watchpoints. */
835 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
837 CPUWatchpoint
*wp
, *next
;
839 QTAILQ_FOREACH_SAFE(wp
, &cpu
->watchpoints
, entry
, next
) {
840 if (wp
->flags
& mask
) {
841 cpu_watchpoint_remove_by_ref(cpu
, wp
);
847 /* Return true if this watchpoint address matches the specified
848 * access (ie the address range covered by the watchpoint overlaps
849 * partially or completely with the address range covered by the
852 static inline bool watchpoint_address_matches(CPUWatchpoint
*wp
,
853 vaddr addr
, vaddr len
)
855 /* We know the lengths are non-zero, but a little caution is
856 * required to avoid errors in the case where the range ends
857 * exactly at the top of the address space and so addr + len
858 * wraps round to zero.
860 vaddr wpend
= wp
->vaddr
+ wp
->len
- 1;
861 vaddr addrend
= addr
+ len
- 1;
863 return !(addr
> wpend
|| wp
->vaddr
> addrend
);
866 /* Return flags for watchpoints that match addr + prot. */
867 int cpu_watchpoint_address_matches(CPUState
*cpu
, vaddr addr
, vaddr len
)
872 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
873 if (watchpoint_address_matches(wp
, addr
, len
)) {
880 /* Generate a debug exception if a watchpoint has been hit. */
881 void cpu_check_watchpoint(CPUState
*cpu
, vaddr addr
, vaddr len
,
882 MemTxAttrs attrs
, int flags
, uintptr_t ra
)
884 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
887 assert(tcg_enabled());
888 if (cpu
->watchpoint_hit
) {
890 * We re-entered the check after replacing the TB.
891 * Now raise the debug interrupt so that it will
892 * trigger after the current instruction.
894 qemu_mutex_lock_iothread();
895 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
896 qemu_mutex_unlock_iothread();
900 if (cc
->tcg_ops
->adjust_watchpoint_address
) {
901 /* this is currently used only by ARM BE32 */
902 addr
= cc
->tcg_ops
->adjust_watchpoint_address(cpu
, addr
, len
);
904 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
905 if (watchpoint_address_matches(wp
, addr
, len
)
906 && (wp
->flags
& flags
)) {
907 if (replay_running_debug()) {
909 * replay_breakpoint reads icount.
910 * Force recompile to succeed, because icount may
911 * be read only at the end of the block.
913 if (!cpu
->can_do_io
) {
914 /* Force execution of one insn next time. */
915 cpu
->cflags_next_tb
= 1 | CF_LAST_IO
| curr_cflags(cpu
);
916 cpu_loop_exit_restore(cpu
, ra
);
919 * Don't process the watchpoints when we are
920 * in a reverse debugging operation.
925 if (flags
== BP_MEM_READ
) {
926 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
928 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
930 wp
->hitaddr
= MAX(addr
, wp
->vaddr
);
931 wp
->hitattrs
= attrs
;
933 if (wp
->flags
& BP_CPU
&& cc
->tcg_ops
->debug_check_watchpoint
&&
934 !cc
->tcg_ops
->debug_check_watchpoint(cpu
, wp
)) {
935 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
938 cpu
->watchpoint_hit
= wp
;
941 /* This call also restores vCPU state */
942 tb_check_watchpoint(cpu
, ra
);
943 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
944 cpu
->exception_index
= EXCP_DEBUG
;
948 /* Force execution of one insn next time. */
949 cpu
->cflags_next_tb
= 1 | CF_LAST_IO
| curr_cflags(cpu
);
951 cpu_loop_exit_noexc(cpu
);
954 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
959 #endif /* CONFIG_TCG */
961 /* Called from RCU critical section */
962 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
966 block
= qatomic_rcu_read(&ram_list
.mru_block
);
967 if (block
&& addr
- block
->offset
< block
->max_length
) {
970 RAMBLOCK_FOREACH(block
) {
971 if (addr
- block
->offset
< block
->max_length
) {
976 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
980 /* It is safe to write mru_block outside the iothread lock. This
985 * xxx removed from list
989 * call_rcu(reclaim_ramblock, xxx);
992 * qatomic_rcu_set is not needed here. The block was already published
993 * when it was placed into the list. Here we're just making an extra
994 * copy of the pointer.
996 ram_list
.mru_block
= block
;
1000 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
1007 assert(tcg_enabled());
1008 end
= TARGET_PAGE_ALIGN(start
+ length
);
1009 start
&= TARGET_PAGE_MASK
;
1011 RCU_READ_LOCK_GUARD();
1012 block
= qemu_get_ram_block(start
);
1013 assert(block
== qemu_get_ram_block(end
- 1));
1014 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
1016 tlb_reset_dirty(cpu
, start1
, length
);
1020 /* Note: start and end must be within the same ram block. */
1021 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
1025 DirtyMemoryBlocks
*blocks
;
1026 unsigned long end
, page
, start_page
;
1029 uint64_t mr_offset
, mr_size
;
1035 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
1036 start_page
= start
>> TARGET_PAGE_BITS
;
1039 WITH_RCU_READ_LOCK_GUARD() {
1040 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1041 ramblock
= qemu_get_ram_block(start
);
1042 /* Range sanity check on the ramblock */
1043 assert(start
>= ramblock
->offset
&&
1044 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
1046 while (page
< end
) {
1047 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1048 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1049 unsigned long num
= MIN(end
- page
,
1050 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1052 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
1057 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
1058 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
1059 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
1062 if (dirty
&& tcg_enabled()) {
1063 tlb_reset_dirty_range_all(start
, length
);
1069 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
1070 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
1072 DirtyMemoryBlocks
*blocks
;
1073 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
1074 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
1075 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
1076 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
1077 DirtyBitmapSnapshot
*snap
;
1078 unsigned long page
, end
, dest
;
1080 snap
= g_malloc0(sizeof(*snap
) +
1081 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1082 snap
->start
= first
;
1085 page
= first
>> TARGET_PAGE_BITS
;
1086 end
= last
>> TARGET_PAGE_BITS
;
1089 WITH_RCU_READ_LOCK_GUARD() {
1090 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1092 while (page
< end
) {
1093 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1094 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1095 unsigned long num
= MIN(end
- page
,
1096 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1098 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1099 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1100 offset
>>= BITS_PER_LEVEL
;
1102 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1103 blocks
->blocks
[idx
] + offset
,
1106 dest
+= num
>> BITS_PER_LEVEL
;
1110 if (tcg_enabled()) {
1111 tlb_reset_dirty_range_all(start
, length
);
1114 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
1119 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1123 unsigned long page
, end
;
1125 assert(start
>= snap
->start
);
1126 assert(start
+ length
<= snap
->end
);
1128 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1129 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1131 while (page
< end
) {
1132 if (test_bit(page
, snap
->dirty
)) {
1140 /* Called from RCU critical section */
1141 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1142 MemoryRegionSection
*section
)
1144 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
1145 return section
- d
->map
.sections
;
1148 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1150 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1152 static uint16_t phys_section_add(PhysPageMap
*map
,
1153 MemoryRegionSection
*section
)
1155 /* The physical section number is ORed with a page-aligned
1156 * pointer to produce the iotlb entries. Thus it should
1157 * never overflow into the page-aligned value.
1159 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1161 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1162 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1163 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1164 map
->sections_nb_alloc
);
1166 map
->sections
[map
->sections_nb
] = *section
;
1167 memory_region_ref(section
->mr
);
1168 return map
->sections_nb
++;
1171 static void phys_section_destroy(MemoryRegion
*mr
)
1173 bool have_sub_page
= mr
->subpage
;
1175 memory_region_unref(mr
);
1177 if (have_sub_page
) {
1178 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1179 object_unref(OBJECT(&subpage
->iomem
));
1184 static void phys_sections_free(PhysPageMap
*map
)
1186 while (map
->sections_nb
> 0) {
1187 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1188 phys_section_destroy(section
->mr
);
1190 g_free(map
->sections
);
1194 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1196 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1198 hwaddr base
= section
->offset_within_address_space
1200 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1201 MemoryRegionSection subsection
= {
1202 .offset_within_address_space
= base
,
1203 .size
= int128_make64(TARGET_PAGE_SIZE
),
1207 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1209 if (!(existing
->mr
->subpage
)) {
1210 subpage
= subpage_init(fv
, base
);
1212 subsection
.mr
= &subpage
->iomem
;
1213 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1214 phys_section_add(&d
->map
, &subsection
));
1216 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1218 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1219 end
= start
+ int128_get64(section
->size
) - 1;
1220 subpage_register(subpage
, start
, end
,
1221 phys_section_add(&d
->map
, section
));
1225 static void register_multipage(FlatView
*fv
,
1226 MemoryRegionSection
*section
)
1228 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1229 hwaddr start_addr
= section
->offset_within_address_space
;
1230 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1231 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1235 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1239 * The range in *section* may look like this:
1243 * where s stands for subpage and P for page.
1245 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1247 MemoryRegionSection remain
= *section
;
1248 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1250 /* register first subpage */
1251 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1252 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1253 - remain
.offset_within_address_space
;
1255 MemoryRegionSection now
= remain
;
1256 now
.size
= int128_min(int128_make64(left
), now
.size
);
1257 register_subpage(fv
, &now
);
1258 if (int128_eq(remain
.size
, now
.size
)) {
1261 remain
.size
= int128_sub(remain
.size
, now
.size
);
1262 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1263 remain
.offset_within_region
+= int128_get64(now
.size
);
1266 /* register whole pages */
1267 if (int128_ge(remain
.size
, page_size
)) {
1268 MemoryRegionSection now
= remain
;
1269 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1270 register_multipage(fv
, &now
);
1271 if (int128_eq(remain
.size
, now
.size
)) {
1274 remain
.size
= int128_sub(remain
.size
, now
.size
);
1275 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1276 remain
.offset_within_region
+= int128_get64(now
.size
);
1279 /* register last subpage */
1280 register_subpage(fv
, &remain
);
1283 void qemu_flush_coalesced_mmio_buffer(void)
1286 kvm_flush_coalesced_mmio_buffer();
1289 void qemu_mutex_lock_ramlist(void)
1291 qemu_mutex_lock(&ram_list
.mutex
);
1294 void qemu_mutex_unlock_ramlist(void)
1296 qemu_mutex_unlock(&ram_list
.mutex
);
1299 void ram_block_dump(Monitor
*mon
)
1304 RCU_READ_LOCK_GUARD();
1305 monitor_printf(mon
, "%24s %8s %18s %18s %18s\n",
1306 "Block Name", "PSize", "Offset", "Used", "Total");
1307 RAMBLOCK_FOREACH(block
) {
1308 psize
= size_to_str(block
->page_size
);
1309 monitor_printf(mon
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1310 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1311 (uint64_t)block
->offset
,
1312 (uint64_t)block
->used_length
,
1313 (uint64_t)block
->max_length
);
1320 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1321 * may or may not name the same files / on the same filesystem now as
1322 * when we actually open and map them. Iterate over the file
1323 * descriptors instead, and use qemu_fd_getpagesize().
1325 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1327 long *hpsize_min
= opaque
;
1329 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1330 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1331 long hpsize
= host_memory_backend_pagesize(backend
);
1333 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1334 *hpsize_min
= hpsize
;
1341 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1343 long *hpsize_max
= opaque
;
1345 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1346 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1347 long hpsize
= host_memory_backend_pagesize(backend
);
1349 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1350 *hpsize_max
= hpsize
;
1358 * TODO: We assume right now that all mapped host memory backends are
1359 * used as RAM, however some might be used for different purposes.
1361 long qemu_minrampagesize(void)
1363 long hpsize
= LONG_MAX
;
1364 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1366 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1370 long qemu_maxrampagesize(void)
1373 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1375 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1379 long qemu_minrampagesize(void)
1381 return qemu_real_host_page_size
;
1383 long qemu_maxrampagesize(void)
1385 return qemu_real_host_page_size
;
1390 static int64_t get_file_size(int fd
)
1393 #if defined(__linux__)
1396 if (fstat(fd
, &st
) < 0) {
1400 /* Special handling for devdax character devices */
1401 if (S_ISCHR(st
.st_mode
)) {
1402 g_autofree
char *subsystem_path
= NULL
;
1403 g_autofree
char *subsystem
= NULL
;
1405 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1406 major(st
.st_rdev
), minor(st
.st_rdev
));
1407 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1409 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1410 g_autofree
char *size_path
= NULL
;
1411 g_autofree
char *size_str
= NULL
;
1413 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1414 major(st
.st_rdev
), minor(st
.st_rdev
));
1416 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1417 return g_ascii_strtoll(size_str
, NULL
, 0);
1421 #endif /* defined(__linux__) */
1423 /* st.st_size may be zero for special files yet lseek(2) works */
1424 size
= lseek(fd
, 0, SEEK_END
);
1431 static int64_t get_file_align(int fd
)
1434 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1437 if (fstat(fd
, &st
) < 0) {
1441 /* Special handling for devdax character devices */
1442 if (S_ISCHR(st
.st_mode
)) {
1443 g_autofree
char *path
= NULL
;
1444 g_autofree
char *rpath
= NULL
;
1445 struct daxctl_ctx
*ctx
;
1446 struct daxctl_region
*region
;
1449 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1450 major(st
.st_rdev
), minor(st
.st_rdev
));
1451 rpath
= realpath(path
, NULL
);
1456 rc
= daxctl_new(&ctx
);
1461 daxctl_region_foreach(ctx
, region
) {
1462 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1463 align
= daxctl_region_get_align(region
);
1469 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1474 static int file_ram_open(const char *path
,
1475 const char *region_name
,
1481 char *sanitized_name
;
1487 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1489 /* @path names an existing file, use it */
1492 if (errno
== ENOENT
) {
1493 /* @path names a file that doesn't exist, create it */
1494 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1499 } else if (errno
== EISDIR
) {
1500 /* @path names a directory, create a file there */
1501 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1502 sanitized_name
= g_strdup(region_name
);
1503 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1509 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1511 g_free(sanitized_name
);
1513 fd
= mkstemp(filename
);
1521 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1522 error_setg_errno(errp
, errno
,
1523 "can't open backing store %s for guest RAM",
1528 * Try again on EINTR and EEXIST. The latter happens when
1529 * something else creates the file between our two open().
1536 static void *file_ram_alloc(RAMBlock
*block
,
1544 uint32_t qemu_map_flags
;
1547 block
->page_size
= qemu_fd_getpagesize(fd
);
1548 if (block
->mr
->align
% block
->page_size
) {
1549 error_setg(errp
, "alignment 0x%" PRIx64
1550 " must be multiples of page size 0x%zx",
1551 block
->mr
->align
, block
->page_size
);
1553 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1554 error_setg(errp
, "alignment 0x%" PRIx64
1555 " must be a power of two", block
->mr
->align
);
1558 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1559 #if defined(__s390x__)
1560 if (kvm_enabled()) {
1561 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1565 if (memory
< block
->page_size
) {
1566 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1567 "or larger than page size 0x%zx",
1568 memory
, block
->page_size
);
1572 memory
= ROUND_UP(memory
, block
->page_size
);
1575 * ftruncate is not supported by hugetlbfs in older
1576 * hosts, so don't bother bailing out on errors.
1577 * If anything goes wrong with it under other filesystems,
1580 * Do not truncate the non-empty backend file to avoid corrupting
1581 * the existing data in the file. Disabling shrinking is not
1582 * enough. For example, the current vNVDIMM implementation stores
1583 * the guest NVDIMM labels at the end of the backend file. If the
1584 * backend file is later extended, QEMU will not be able to find
1585 * those labels. Therefore, extending the non-empty backend file
1586 * is disabled as well.
1588 if (truncate
&& ftruncate(fd
, memory
)) {
1589 perror("ftruncate");
1592 qemu_map_flags
= readonly
? QEMU_MAP_READONLY
: 0;
1593 qemu_map_flags
|= (block
->flags
& RAM_SHARED
) ? QEMU_MAP_SHARED
: 0;
1594 qemu_map_flags
|= (block
->flags
& RAM_PMEM
) ? QEMU_MAP_SYNC
: 0;
1595 qemu_map_flags
|= (block
->flags
& RAM_NORESERVE
) ? QEMU_MAP_NORESERVE
: 0;
1596 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, qemu_map_flags
, offset
);
1597 if (area
== MAP_FAILED
) {
1598 error_setg_errno(errp
, errno
,
1599 "unable to map backing store for guest RAM");
1608 /* Allocate space within the ram_addr_t space that governs the
1610 * Called with the ramlist lock held.
1612 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1614 RAMBlock
*block
, *next_block
;
1615 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1617 assert(size
!= 0); /* it would hand out same offset multiple times */
1619 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1623 RAMBLOCK_FOREACH(block
) {
1624 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1626 /* Align blocks to start on a 'long' in the bitmap
1627 * which makes the bitmap sync'ing take the fast path.
1629 candidate
= block
->offset
+ block
->max_length
;
1630 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1632 /* Search for the closest following block
1635 RAMBLOCK_FOREACH(next_block
) {
1636 if (next_block
->offset
>= candidate
) {
1637 next
= MIN(next
, next_block
->offset
);
1641 /* If it fits remember our place and remember the size
1642 * of gap, but keep going so that we might find a smaller
1643 * gap to fill so avoiding fragmentation.
1645 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1647 mingap
= next
- candidate
;
1650 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1653 if (offset
== RAM_ADDR_MAX
) {
1654 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1659 trace_find_ram_offset(size
, offset
);
1664 static unsigned long last_ram_page(void)
1667 ram_addr_t last
= 0;
1669 RCU_READ_LOCK_GUARD();
1670 RAMBLOCK_FOREACH(block
) {
1671 last
= MAX(last
, block
->offset
+ block
->max_length
);
1673 return last
>> TARGET_PAGE_BITS
;
1676 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1680 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1681 if (!machine_dump_guest_core(current_machine
)) {
1682 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1684 perror("qemu_madvise");
1685 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1686 "but dump_guest_core=off specified\n");
1691 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1696 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1701 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1706 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1708 return rb
->used_length
;
1711 ram_addr_t
qemu_ram_get_max_length(RAMBlock
*rb
)
1713 return rb
->max_length
;
1716 bool qemu_ram_is_shared(RAMBlock
*rb
)
1718 return rb
->flags
& RAM_SHARED
;
1721 bool qemu_ram_is_noreserve(RAMBlock
*rb
)
1723 return rb
->flags
& RAM_NORESERVE
;
1726 /* Note: Only set at the start of postcopy */
1727 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1729 return rb
->flags
& RAM_UF_ZEROPAGE
;
1732 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1734 rb
->flags
|= RAM_UF_ZEROPAGE
;
1737 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1739 return rb
->flags
& RAM_MIGRATABLE
;
1742 void qemu_ram_set_migratable(RAMBlock
*rb
)
1744 rb
->flags
|= RAM_MIGRATABLE
;
1747 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1749 rb
->flags
&= ~RAM_MIGRATABLE
;
1752 /* Called with iothread lock held. */
1753 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1758 assert(!new_block
->idstr
[0]);
1761 char *id
= qdev_get_dev_path(dev
);
1763 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1767 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1769 RCU_READ_LOCK_GUARD();
1770 RAMBLOCK_FOREACH(block
) {
1771 if (block
!= new_block
&&
1772 !strcmp(block
->idstr
, new_block
->idstr
)) {
1773 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1780 /* Called with iothread lock held. */
1781 void qemu_ram_unset_idstr(RAMBlock
*block
)
1783 /* FIXME: arch_init.c assumes that this is not called throughout
1784 * migration. Ignore the problem since hot-unplug during migration
1785 * does not work anyway.
1788 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1792 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1794 return rb
->page_size
;
1797 /* Returns the largest size of page in use */
1798 size_t qemu_ram_pagesize_largest(void)
1803 RAMBLOCK_FOREACH(block
) {
1804 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1810 static int memory_try_enable_merging(void *addr
, size_t len
)
1812 if (!machine_mem_merge(current_machine
)) {
1813 /* disabled by the user */
1817 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1821 * Resizing RAM while migrating can result in the migration being canceled.
1822 * Care has to be taken if the guest might have already detected the memory.
1824 * As memory core doesn't know how is memory accessed, it is up to
1825 * resize callback to update device state and/or add assertions to detect
1826 * misuse, if necessary.
1828 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1830 const ram_addr_t oldsize
= block
->used_length
;
1831 const ram_addr_t unaligned_size
= newsize
;
1835 newsize
= HOST_PAGE_ALIGN(newsize
);
1837 if (block
->used_length
== newsize
) {
1839 * We don't have to resize the ram block (which only knows aligned
1840 * sizes), however, we have to notify if the unaligned size changed.
1842 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1843 memory_region_set_size(block
->mr
, unaligned_size
);
1844 if (block
->resized
) {
1845 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1851 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1852 error_setg_errno(errp
, EINVAL
,
1853 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1854 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1855 newsize
, block
->used_length
);
1859 if (block
->max_length
< newsize
) {
1860 error_setg_errno(errp
, EINVAL
,
1861 "Size too large: %s: 0x" RAM_ADDR_FMT
1862 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1863 newsize
, block
->max_length
);
1867 /* Notify before modifying the ram block and touching the bitmaps. */
1869 ram_block_notify_resize(block
->host
, oldsize
, newsize
);
1872 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1873 block
->used_length
= newsize
;
1874 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1876 memory_region_set_size(block
->mr
, unaligned_size
);
1877 if (block
->resized
) {
1878 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1884 * Trigger sync on the given ram block for range [start, start + length]
1885 * with the backing store if one is available.
1887 * @Note: this is supposed to be a synchronous op.
1889 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1891 /* The requested range should fit in within the block range */
1892 g_assert((start
+ length
) <= block
->used_length
);
1894 #ifdef CONFIG_LIBPMEM
1895 /* The lack of support for pmem should not block the sync */
1896 if (ramblock_is_pmem(block
)) {
1897 void *addr
= ramblock_ptr(block
, start
);
1898 pmem_persist(addr
, length
);
1902 if (block
->fd
>= 0) {
1904 * Case there is no support for PMEM or the memory has not been
1905 * specified as persistent (or is not one) - use the msync.
1906 * Less optimal but still achieves the same goal
1908 void *addr
= ramblock_ptr(block
, start
);
1909 if (qemu_msync(addr
, length
, block
->fd
)) {
1910 warn_report("%s: failed to sync memory range: start: "
1911 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1912 __func__
, start
, length
);
1917 /* Called with ram_list.mutex held */
1918 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1919 ram_addr_t new_ram_size
)
1921 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1922 DIRTY_MEMORY_BLOCK_SIZE
);
1923 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1924 DIRTY_MEMORY_BLOCK_SIZE
);
1927 /* Only need to extend if block count increased */
1928 if (new_num_blocks
<= old_num_blocks
) {
1932 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1933 DirtyMemoryBlocks
*old_blocks
;
1934 DirtyMemoryBlocks
*new_blocks
;
1937 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1938 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1939 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1941 if (old_num_blocks
) {
1942 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1943 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1946 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1947 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1950 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1953 g_free_rcu(old_blocks
, rcu
);
1958 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
)
1960 const bool noreserve
= qemu_ram_is_noreserve(new_block
);
1961 const bool shared
= qemu_ram_is_shared(new_block
);
1963 RAMBlock
*last_block
= NULL
;
1964 ram_addr_t old_ram_size
, new_ram_size
;
1967 old_ram_size
= last_ram_page();
1969 qemu_mutex_lock_ramlist();
1970 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1972 if (!new_block
->host
) {
1973 if (xen_enabled()) {
1974 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1975 new_block
->mr
, &err
);
1977 error_propagate(errp
, err
);
1978 qemu_mutex_unlock_ramlist();
1982 new_block
->host
= qemu_anon_ram_alloc(new_block
->max_length
,
1983 &new_block
->mr
->align
,
1985 if (!new_block
->host
) {
1986 error_setg_errno(errp
, errno
,
1987 "cannot set up guest memory '%s'",
1988 memory_region_name(new_block
->mr
));
1989 qemu_mutex_unlock_ramlist();
1992 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1996 new_ram_size
= MAX(old_ram_size
,
1997 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1998 if (new_ram_size
> old_ram_size
) {
1999 dirty_memory_extend(old_ram_size
, new_ram_size
);
2001 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2002 * QLIST (which has an RCU-friendly variant) does not have insertion at
2003 * tail, so save the last element in last_block.
2005 RAMBLOCK_FOREACH(block
) {
2007 if (block
->max_length
< new_block
->max_length
) {
2012 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
2013 } else if (last_block
) {
2014 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
2015 } else { /* list is empty */
2016 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
2018 ram_list
.mru_block
= NULL
;
2020 /* Write list before version */
2023 qemu_mutex_unlock_ramlist();
2025 cpu_physical_memory_set_dirty_range(new_block
->offset
,
2026 new_block
->used_length
,
2029 if (new_block
->host
) {
2030 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
2031 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
2033 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2034 * Configure it unless the machine is a qtest server, in which case
2035 * KVM is not used and it may be forked (eg for fuzzing purposes).
2037 if (!qtest_enabled()) {
2038 qemu_madvise(new_block
->host
, new_block
->max_length
,
2039 QEMU_MADV_DONTFORK
);
2041 ram_block_notify_add(new_block
->host
, new_block
->used_length
,
2042 new_block
->max_length
);
2047 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
2048 uint32_t ram_flags
, int fd
, off_t offset
,
2049 bool readonly
, Error
**errp
)
2051 RAMBlock
*new_block
;
2052 Error
*local_err
= NULL
;
2053 int64_t file_size
, file_align
;
2055 /* Just support these ram flags by now. */
2056 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
| RAM_NORESERVE
|
2057 RAM_PROTECTED
)) == 0);
2059 if (xen_enabled()) {
2060 error_setg(errp
, "-mem-path not supported with Xen");
2064 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2066 "host lacks kvm mmu notifiers, -mem-path unsupported");
2070 size
= HOST_PAGE_ALIGN(size
);
2071 file_size
= get_file_size(fd
);
2072 if (file_size
> 0 && file_size
< size
) {
2073 error_setg(errp
, "backing store size 0x%" PRIx64
2074 " does not match 'size' option 0x" RAM_ADDR_FMT
,
2079 file_align
= get_file_align(fd
);
2080 if (file_align
> 0 && file_align
> mr
->align
) {
2081 error_setg(errp
, "backing store align 0x%" PRIx64
2082 " is larger than 'align' option 0x%" PRIx64
,
2083 file_align
, mr
->align
);
2087 new_block
= g_malloc0(sizeof(*new_block
));
2089 new_block
->used_length
= size
;
2090 new_block
->max_length
= size
;
2091 new_block
->flags
= ram_flags
;
2092 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, readonly
,
2093 !file_size
, offset
, errp
);
2094 if (!new_block
->host
) {
2099 ram_block_add(new_block
, &local_err
);
2102 error_propagate(errp
, local_err
);
2110 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2111 uint32_t ram_flags
, const char *mem_path
,
2112 bool readonly
, Error
**errp
)
2118 fd
= file_ram_open(mem_path
, memory_region_name(mr
), readonly
, &created
,
2124 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, 0, readonly
, errp
);
2138 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2139 void (*resized
)(const char*,
2142 void *host
, uint32_t ram_flags
,
2143 MemoryRegion
*mr
, Error
**errp
)
2145 RAMBlock
*new_block
;
2146 Error
*local_err
= NULL
;
2148 assert((ram_flags
& ~(RAM_SHARED
| RAM_RESIZEABLE
| RAM_PREALLOC
|
2149 RAM_NORESERVE
)) == 0);
2150 assert(!host
^ (ram_flags
& RAM_PREALLOC
));
2152 size
= HOST_PAGE_ALIGN(size
);
2153 max_size
= HOST_PAGE_ALIGN(max_size
);
2154 new_block
= g_malloc0(sizeof(*new_block
));
2156 new_block
->resized
= resized
;
2157 new_block
->used_length
= size
;
2158 new_block
->max_length
= max_size
;
2159 assert(max_size
>= size
);
2161 new_block
->page_size
= qemu_real_host_page_size
;
2162 new_block
->host
= host
;
2163 new_block
->flags
= ram_flags
;
2164 ram_block_add(new_block
, &local_err
);
2167 error_propagate(errp
, local_err
);
2173 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2174 MemoryRegion
*mr
, Error
**errp
)
2176 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, RAM_PREALLOC
, mr
,
2180 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, uint32_t ram_flags
,
2181 MemoryRegion
*mr
, Error
**errp
)
2183 assert((ram_flags
& ~(RAM_SHARED
| RAM_NORESERVE
)) == 0);
2184 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, ram_flags
, mr
, errp
);
2187 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2188 void (*resized
)(const char*,
2191 MemoryRegion
*mr
, Error
**errp
)
2193 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
,
2194 RAM_RESIZEABLE
, mr
, errp
);
2197 static void reclaim_ramblock(RAMBlock
*block
)
2199 if (block
->flags
& RAM_PREALLOC
) {
2201 } else if (xen_enabled()) {
2202 xen_invalidate_map_cache_entry(block
->host
);
2204 } else if (block
->fd
>= 0) {
2205 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2209 qemu_anon_ram_free(block
->host
, block
->max_length
);
2214 void qemu_ram_free(RAMBlock
*block
)
2221 ram_block_notify_remove(block
->host
, block
->used_length
,
2225 qemu_mutex_lock_ramlist();
2226 QLIST_REMOVE_RCU(block
, next
);
2227 ram_list
.mru_block
= NULL
;
2228 /* Write list before version */
2231 call_rcu(block
, reclaim_ramblock
, rcu
);
2232 qemu_mutex_unlock_ramlist();
2236 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2243 RAMBLOCK_FOREACH(block
) {
2244 offset
= addr
- block
->offset
;
2245 if (offset
< block
->max_length
) {
2246 vaddr
= ramblock_ptr(block
, offset
);
2247 if (block
->flags
& RAM_PREALLOC
) {
2249 } else if (xen_enabled()) {
2253 flags
|= block
->flags
& RAM_SHARED
?
2254 MAP_SHARED
: MAP_PRIVATE
;
2255 flags
|= block
->flags
& RAM_NORESERVE
? MAP_NORESERVE
: 0;
2256 if (block
->fd
>= 0) {
2257 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2258 flags
, block
->fd
, offset
);
2260 flags
|= MAP_ANONYMOUS
;
2261 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2264 if (area
!= vaddr
) {
2265 error_report("Could not remap addr: "
2266 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2270 memory_try_enable_merging(vaddr
, length
);
2271 qemu_ram_setup_dump(vaddr
, length
);
2276 #endif /* !_WIN32 */
2278 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2279 * This should not be used for general purpose DMA. Use address_space_map
2280 * or address_space_rw instead. For local memory (e.g. video ram) that the
2281 * device owns, use memory_region_get_ram_ptr.
2283 * Called within RCU critical section.
2285 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2287 RAMBlock
*block
= ram_block
;
2289 if (block
== NULL
) {
2290 block
= qemu_get_ram_block(addr
);
2291 addr
-= block
->offset
;
2294 if (xen_enabled() && block
->host
== NULL
) {
2295 /* We need to check if the requested address is in the RAM
2296 * because we don't want to map the entire memory in QEMU.
2297 * In that case just map until the end of the page.
2299 if (block
->offset
== 0) {
2300 return xen_map_cache(addr
, 0, 0, false);
2303 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2305 return ramblock_ptr(block
, addr
);
2308 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2309 * but takes a size argument.
2311 * Called within RCU critical section.
2313 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2314 hwaddr
*size
, bool lock
)
2316 RAMBlock
*block
= ram_block
;
2321 if (block
== NULL
) {
2322 block
= qemu_get_ram_block(addr
);
2323 addr
-= block
->offset
;
2325 *size
= MIN(*size
, block
->max_length
- addr
);
2327 if (xen_enabled() && block
->host
== NULL
) {
2328 /* We need to check if the requested address is in the RAM
2329 * because we don't want to map the entire memory in QEMU.
2330 * In that case just map the requested area.
2332 if (block
->offset
== 0) {
2333 return xen_map_cache(addr
, *size
, lock
, lock
);
2336 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2339 return ramblock_ptr(block
, addr
);
2342 /* Return the offset of a hostpointer within a ramblock */
2343 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2345 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2346 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2347 assert(res
< rb
->max_length
);
2353 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2356 * ptr: Host pointer to look up
2357 * round_offset: If true round the result offset down to a page boundary
2358 * *ram_addr: set to result ram_addr
2359 * *offset: set to result offset within the RAMBlock
2361 * Returns: RAMBlock (or NULL if not found)
2363 * By the time this function returns, the returned pointer is not protected
2364 * by RCU anymore. If the caller is not within an RCU critical section and
2365 * does not hold the iothread lock, it must have other means of protecting the
2366 * pointer, such as a reference to the region that includes the incoming
2369 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2373 uint8_t *host
= ptr
;
2375 if (xen_enabled()) {
2376 ram_addr_t ram_addr
;
2377 RCU_READ_LOCK_GUARD();
2378 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2379 block
= qemu_get_ram_block(ram_addr
);
2381 *offset
= ram_addr
- block
->offset
;
2386 RCU_READ_LOCK_GUARD();
2387 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2388 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2392 RAMBLOCK_FOREACH(block
) {
2393 /* This case append when the block is not mapped. */
2394 if (block
->host
== NULL
) {
2397 if (host
- block
->host
< block
->max_length
) {
2405 *offset
= (host
- block
->host
);
2407 *offset
&= TARGET_PAGE_MASK
;
2413 * Finds the named RAMBlock
2415 * name: The name of RAMBlock to find
2417 * Returns: RAMBlock (or NULL if not found)
2419 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2423 RAMBLOCK_FOREACH(block
) {
2424 if (!strcmp(name
, block
->idstr
)) {
2432 /* Some of the softmmu routines need to translate from a host pointer
2433 (typically a TLB entry) back to a ram offset. */
2434 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2439 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2441 return RAM_ADDR_INVALID
;
2444 return block
->offset
+ offset
;
2447 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2448 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2449 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2450 const void *buf
, hwaddr len
);
2451 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2452 bool is_write
, MemTxAttrs attrs
);
2454 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2455 unsigned len
, MemTxAttrs attrs
)
2457 subpage_t
*subpage
= opaque
;
2461 #if defined(DEBUG_SUBPAGE)
2462 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2463 subpage
, len
, addr
);
2465 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2469 *data
= ldn_p(buf
, len
);
2473 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2474 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2476 subpage_t
*subpage
= opaque
;
2479 #if defined(DEBUG_SUBPAGE)
2480 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2481 " value %"PRIx64
"\n",
2482 __func__
, subpage
, len
, addr
, value
);
2484 stn_p(buf
, len
, value
);
2485 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2488 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2489 unsigned len
, bool is_write
,
2492 subpage_t
*subpage
= opaque
;
2493 #if defined(DEBUG_SUBPAGE)
2494 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2495 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2498 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2499 len
, is_write
, attrs
);
2502 static const MemoryRegionOps subpage_ops
= {
2503 .read_with_attrs
= subpage_read
,
2504 .write_with_attrs
= subpage_write
,
2505 .impl
.min_access_size
= 1,
2506 .impl
.max_access_size
= 8,
2507 .valid
.min_access_size
= 1,
2508 .valid
.max_access_size
= 8,
2509 .valid
.accepts
= subpage_accepts
,
2510 .endianness
= DEVICE_NATIVE_ENDIAN
,
2513 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2518 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2520 idx
= SUBPAGE_IDX(start
);
2521 eidx
= SUBPAGE_IDX(end
);
2522 #if defined(DEBUG_SUBPAGE)
2523 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2524 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2526 for (; idx
<= eidx
; idx
++) {
2527 mmio
->sub_section
[idx
] = section
;
2533 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2537 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2538 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2541 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2542 NULL
, TARGET_PAGE_SIZE
);
2543 mmio
->iomem
.subpage
= true;
2544 #if defined(DEBUG_SUBPAGE)
2545 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2546 mmio
, base
, TARGET_PAGE_SIZE
);
2552 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2555 MemoryRegionSection section
= {
2558 .offset_within_address_space
= 0,
2559 .offset_within_region
= 0,
2560 .size
= int128_2_64(),
2563 return phys_section_add(map
, §ion
);
2566 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2567 hwaddr index
, MemTxAttrs attrs
)
2569 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2570 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2571 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2572 MemoryRegionSection
*sections
= d
->map
.sections
;
2574 return §ions
[index
& ~TARGET_PAGE_MASK
];
2577 static void io_mem_init(void)
2579 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2583 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2585 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2588 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2589 assert(n
== PHYS_SECTION_UNASSIGNED
);
2591 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2596 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2598 phys_sections_free(&d
->map
);
2602 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2606 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2608 CPUAddressSpace
*cpuas
;
2610 /* Wait for the CPU to end the current TB. This avoids the following
2614 * ---------------------- -------------------------
2615 * TLB check -> slow path
2616 * notdirty_mem_write
2620 * TLB check -> fast path
2624 * by pushing the migration thread's memory read after the vCPU thread has
2625 * written the memory.
2627 if (replay_mode
== REPLAY_MODE_NONE
) {
2629 * VGA can make calls to this function while updating the screen.
2630 * In record/replay mode this causes a deadlock, because
2631 * run_on_cpu waits for rr mutex. Therefore no races are possible
2632 * in this case and no need for making run_on_cpu when
2633 * record/replay is enabled.
2635 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2636 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2640 static void tcg_commit(MemoryListener
*listener
)
2642 CPUAddressSpace
*cpuas
;
2643 AddressSpaceDispatch
*d
;
2645 assert(tcg_enabled());
2646 /* since each CPU stores ram addresses in its TLB cache, we must
2647 reset the modified entries */
2648 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2649 cpu_reloading_memory_map();
2650 /* The CPU and TLB are protected by the iothread lock.
2651 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2652 * may have split the RCU critical section.
2654 d
= address_space_to_dispatch(cpuas
->as
);
2655 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2656 tlb_flush(cpuas
->cpu
);
2659 static void memory_map_init(void)
2661 system_memory
= g_malloc(sizeof(*system_memory
));
2663 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2664 address_space_init(&address_space_memory
, system_memory
, "memory");
2666 system_io
= g_malloc(sizeof(*system_io
));
2667 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2669 address_space_init(&address_space_io
, system_io
, "I/O");
2672 MemoryRegion
*get_system_memory(void)
2674 return system_memory
;
2677 MemoryRegion
*get_system_io(void)
2682 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2685 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2686 addr
+= memory_region_get_ram_addr(mr
);
2688 /* No early return if dirty_log_mask is or becomes 0, because
2689 * cpu_physical_memory_set_dirty_range will still call
2690 * xen_modified_memory.
2692 if (dirty_log_mask
) {
2694 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2696 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2697 assert(tcg_enabled());
2698 tb_invalidate_phys_range(addr
, addr
+ length
);
2699 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2701 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2704 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2707 * In principle this function would work on other memory region types too,
2708 * but the ROM device use case is the only one where this operation is
2709 * necessary. Other memory regions should use the
2710 * address_space_read/write() APIs.
2712 assert(memory_region_is_romd(mr
));
2714 invalidate_and_set_dirty(mr
, addr
, size
);
2717 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2719 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2721 /* Regions are assumed to support 1-4 byte accesses unless
2722 otherwise specified. */
2723 if (access_size_max
== 0) {
2724 access_size_max
= 4;
2727 /* Bound the maximum access by the alignment of the address. */
2728 if (!mr
->ops
->impl
.unaligned
) {
2729 unsigned align_size_max
= addr
& -addr
;
2730 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2731 access_size_max
= align_size_max
;
2735 /* Don't attempt accesses larger than the maximum. */
2736 if (l
> access_size_max
) {
2737 l
= access_size_max
;
2744 static bool prepare_mmio_access(MemoryRegion
*mr
)
2746 bool release_lock
= false;
2748 if (!qemu_mutex_iothread_locked()) {
2749 qemu_mutex_lock_iothread();
2750 release_lock
= true;
2752 if (mr
->flush_coalesced_mmio
) {
2753 qemu_flush_coalesced_mmio_buffer();
2756 return release_lock
;
2759 /* Called within RCU critical section. */
2760 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2763 hwaddr len
, hwaddr addr1
,
2764 hwaddr l
, MemoryRegion
*mr
)
2768 MemTxResult result
= MEMTX_OK
;
2769 bool release_lock
= false;
2770 const uint8_t *buf
= ptr
;
2773 if (!memory_access_is_direct(mr
, true)) {
2774 release_lock
|= prepare_mmio_access(mr
);
2775 l
= memory_access_size(mr
, l
, addr1
);
2776 /* XXX: could force current_cpu to NULL to avoid
2778 val
= ldn_he_p(buf
, l
);
2779 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2780 size_memop(l
), attrs
);
2783 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2784 memcpy(ram_ptr
, buf
, l
);
2785 invalidate_and_set_dirty(mr
, addr1
, l
);
2789 qemu_mutex_unlock_iothread();
2790 release_lock
= false;
2802 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2808 /* Called from RCU critical section. */
2809 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2810 const void *buf
, hwaddr len
)
2815 MemTxResult result
= MEMTX_OK
;
2818 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2819 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2825 /* Called within RCU critical section. */
2826 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2827 MemTxAttrs attrs
, void *ptr
,
2828 hwaddr len
, hwaddr addr1
, hwaddr l
,
2833 MemTxResult result
= MEMTX_OK
;
2834 bool release_lock
= false;
2837 fuzz_dma_read_cb(addr
, len
, mr
);
2839 if (!memory_access_is_direct(mr
, false)) {
2841 release_lock
|= prepare_mmio_access(mr
);
2842 l
= memory_access_size(mr
, l
, addr1
);
2843 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2844 size_memop(l
), attrs
);
2845 stn_he_p(buf
, l
, val
);
2848 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2849 memcpy(buf
, ram_ptr
, l
);
2853 qemu_mutex_unlock_iothread();
2854 release_lock
= false;
2866 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2872 /* Called from RCU critical section. */
2873 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2874 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2881 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2882 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2886 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2887 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2889 MemTxResult result
= MEMTX_OK
;
2893 RCU_READ_LOCK_GUARD();
2894 fv
= address_space_to_flatview(as
);
2895 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2901 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2903 const void *buf
, hwaddr len
)
2905 MemTxResult result
= MEMTX_OK
;
2909 RCU_READ_LOCK_GUARD();
2910 fv
= address_space_to_flatview(as
);
2911 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2917 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2918 void *buf
, hwaddr len
, bool is_write
)
2921 return address_space_write(as
, addr
, attrs
, buf
, len
);
2923 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2927 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2928 hwaddr len
, bool is_write
)
2930 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2931 buf
, len
, is_write
);
2934 enum write_rom_type
{
2939 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2944 enum write_rom_type type
)
2950 const uint8_t *buf
= ptr
;
2952 RCU_READ_LOCK_GUARD();
2955 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
2957 if (!(memory_region_is_ram(mr
) ||
2958 memory_region_is_romd(mr
))) {
2959 l
= memory_access_size(mr
, l
, addr1
);
2962 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
2965 memcpy(ram_ptr
, buf
, l
);
2966 invalidate_and_set_dirty(mr
, addr1
, l
);
2969 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
2980 /* used for ROM loading : can write in RAM and ROM */
2981 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
2983 const void *buf
, hwaddr len
)
2985 return address_space_write_rom_internal(as
, addr
, attrs
,
2986 buf
, len
, WRITE_DATA
);
2989 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
2992 * This function should do the same thing as an icache flush that was
2993 * triggered from within the guest. For TCG we are always cache coherent,
2994 * so there is no need to flush anything. For KVM / Xen we need to flush
2995 * the host's instruction cache at least.
2997 if (tcg_enabled()) {
3001 address_space_write_rom_internal(&address_space_memory
,
3002 start
, MEMTXATTRS_UNSPECIFIED
,
3003 NULL
, len
, FLUSH_CACHE
);
3014 static BounceBuffer bounce
;
3016 typedef struct MapClient
{
3018 QLIST_ENTRY(MapClient
) link
;
3021 QemuMutex map_client_list_lock
;
3022 static QLIST_HEAD(, MapClient
) map_client_list
3023 = QLIST_HEAD_INITIALIZER(map_client_list
);
3025 static void cpu_unregister_map_client_do(MapClient
*client
)
3027 QLIST_REMOVE(client
, link
);
3031 static void cpu_notify_map_clients_locked(void)
3035 while (!QLIST_EMPTY(&map_client_list
)) {
3036 client
= QLIST_FIRST(&map_client_list
);
3037 qemu_bh_schedule(client
->bh
);
3038 cpu_unregister_map_client_do(client
);
3042 void cpu_register_map_client(QEMUBH
*bh
)
3044 MapClient
*client
= g_malloc(sizeof(*client
));
3046 qemu_mutex_lock(&map_client_list_lock
);
3048 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3049 if (!qatomic_read(&bounce
.in_use
)) {
3050 cpu_notify_map_clients_locked();
3052 qemu_mutex_unlock(&map_client_list_lock
);
3055 void cpu_exec_init_all(void)
3057 qemu_mutex_init(&ram_list
.mutex
);
3058 /* The data structures we set up here depend on knowing the page size,
3059 * so no more changes can be made after this point.
3060 * In an ideal world, nothing we did before we had finished the
3061 * machine setup would care about the target page size, and we could
3062 * do this much later, rather than requiring board models to state
3063 * up front what their requirements are.
3065 finalize_target_page_bits();
3068 qemu_mutex_init(&map_client_list_lock
);
3071 void cpu_unregister_map_client(QEMUBH
*bh
)
3075 qemu_mutex_lock(&map_client_list_lock
);
3076 QLIST_FOREACH(client
, &map_client_list
, link
) {
3077 if (client
->bh
== bh
) {
3078 cpu_unregister_map_client_do(client
);
3082 qemu_mutex_unlock(&map_client_list_lock
);
3085 static void cpu_notify_map_clients(void)
3087 qemu_mutex_lock(&map_client_list_lock
);
3088 cpu_notify_map_clients_locked();
3089 qemu_mutex_unlock(&map_client_list_lock
);
3092 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3093 bool is_write
, MemTxAttrs attrs
)
3100 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3101 if (!memory_access_is_direct(mr
, is_write
)) {
3102 l
= memory_access_size(mr
, l
, addr
);
3103 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3114 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3115 hwaddr len
, bool is_write
,
3121 RCU_READ_LOCK_GUARD();
3122 fv
= address_space_to_flatview(as
);
3123 result
= flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3128 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3130 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3131 bool is_write
, MemTxAttrs attrs
)
3135 MemoryRegion
*this_mr
;
3141 if (target_len
== 0) {
3146 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3147 &len
, is_write
, attrs
);
3148 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3154 /* Map a physical memory region into a host virtual address.
3155 * May map a subset of the requested range, given by and returned in *plen.
3156 * May return NULL if resources needed to perform the mapping are exhausted.
3157 * Use only for reads OR writes - not for read-modify-write operations.
3158 * Use cpu_register_map_client() to know when retrying the map operation is
3159 * likely to succeed.
3161 void *address_space_map(AddressSpace
*as
,
3178 RCU_READ_LOCK_GUARD();
3179 fv
= address_space_to_flatview(as
);
3180 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3182 if (!memory_access_is_direct(mr
, is_write
)) {
3183 if (qatomic_xchg(&bounce
.in_use
, true)) {
3187 /* Avoid unbounded allocations */
3188 l
= MIN(l
, TARGET_PAGE_SIZE
);
3189 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3193 memory_region_ref(mr
);
3196 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3201 return bounce
.buffer
;
3205 memory_region_ref(mr
);
3206 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3207 l
, is_write
, attrs
);
3208 fuzz_dma_read_cb(addr
, *plen
, mr
);
3209 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3214 /* Unmaps a memory region previously mapped by address_space_map().
3215 * Will also mark the memory as dirty if is_write is true. access_len gives
3216 * the amount of memory that was actually read or written by the caller.
3218 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3219 bool is_write
, hwaddr access_len
)
3221 if (buffer
!= bounce
.buffer
) {
3225 mr
= memory_region_from_host(buffer
, &addr1
);
3228 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3230 if (xen_enabled()) {
3231 xen_invalidate_map_cache_entry(buffer
);
3233 memory_region_unref(mr
);
3237 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3238 bounce
.buffer
, access_len
);
3240 qemu_vfree(bounce
.buffer
);
3241 bounce
.buffer
= NULL
;
3242 memory_region_unref(bounce
.mr
);
3243 qatomic_mb_set(&bounce
.in_use
, false);
3244 cpu_notify_map_clients();
3247 void *cpu_physical_memory_map(hwaddr addr
,
3251 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3252 MEMTXATTRS_UNSPECIFIED
);
3255 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3256 bool is_write
, hwaddr access_len
)
3258 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3261 #define ARG1_DECL AddressSpace *as
3264 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3265 #define RCU_READ_LOCK(...) rcu_read_lock()
3266 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3267 #include "memory_ldst.c.inc"
3269 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3275 AddressSpaceDispatch
*d
;
3283 cache
->fv
= address_space_get_flatview(as
);
3284 d
= flatview_to_dispatch(cache
->fv
);
3285 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3288 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3289 * Take that into account to compute how many bytes are there between
3290 * cache->xlat and the end of the section.
3292 diff
= int128_sub(cache
->mrs
.size
,
3293 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3294 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3297 memory_region_ref(mr
);
3298 if (memory_access_is_direct(mr
, is_write
)) {
3299 /* We don't care about the memory attributes here as we're only
3300 * doing this if we found actual RAM, which behaves the same
3301 * regardless of attributes; so UNSPECIFIED is fine.
3303 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3304 cache
->xlat
, l
, is_write
,
3305 MEMTXATTRS_UNSPECIFIED
);
3306 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3312 cache
->is_write
= is_write
;
3316 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3320 assert(cache
->is_write
);
3321 if (likely(cache
->ptr
)) {
3322 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3326 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3328 if (!cache
->mrs
.mr
) {
3332 if (xen_enabled()) {
3333 xen_invalidate_map_cache_entry(cache
->ptr
);
3335 memory_region_unref(cache
->mrs
.mr
);
3336 flatview_unref(cache
->fv
);
3337 cache
->mrs
.mr
= NULL
;
3341 /* Called from RCU critical section. This function has the same
3342 * semantics as address_space_translate, but it only works on a
3343 * predefined range of a MemoryRegion that was mapped with
3344 * address_space_cache_init.
3346 static inline MemoryRegion
*address_space_translate_cached(
3347 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3348 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3350 MemoryRegionSection section
;
3352 IOMMUMemoryRegion
*iommu_mr
;
3353 AddressSpace
*target_as
;
3355 assert(!cache
->ptr
);
3356 *xlat
= addr
+ cache
->xlat
;
3359 iommu_mr
= memory_region_get_iommu(mr
);
3365 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3366 NULL
, is_write
, true,
3371 /* Called from RCU critical section. address_space_read_cached uses this
3372 * out of line function when the target is an MMIO or IOMMU region.
3375 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3376 void *buf
, hwaddr len
)
3382 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3383 MEMTXATTRS_UNSPECIFIED
);
3384 return flatview_read_continue(cache
->fv
,
3385 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3389 /* Called from RCU critical section. address_space_write_cached uses this
3390 * out of line function when the target is an MMIO or IOMMU region.
3393 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3394 const void *buf
, hwaddr len
)
3400 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3401 MEMTXATTRS_UNSPECIFIED
);
3402 return flatview_write_continue(cache
->fv
,
3403 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3407 #define ARG1_DECL MemoryRegionCache *cache
3409 #define SUFFIX _cached_slow
3410 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3411 #define RCU_READ_LOCK() ((void)0)
3412 #define RCU_READ_UNLOCK() ((void)0)
3413 #include "memory_ldst.c.inc"
3415 /* virtual memory access for debug (includes writing to ROM) */
3416 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3417 void *ptr
, target_ulong len
, bool is_write
)
3420 target_ulong l
, page
;
3423 cpu_synchronize_state(cpu
);
3429 page
= addr
& TARGET_PAGE_MASK
;
3430 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3431 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3432 /* if no physical page mapped, return an error */
3433 if (phys_addr
== -1)
3435 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3438 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3440 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3443 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3446 if (res
!= MEMTX_OK
) {
3457 * Allows code that needs to deal with migration bitmaps etc to still be built
3458 * target independent.
3460 size_t qemu_target_page_size(void)
3462 return TARGET_PAGE_SIZE
;
3465 int qemu_target_page_bits(void)
3467 return TARGET_PAGE_BITS
;
3470 int qemu_target_page_bits_min(void)
3472 return TARGET_PAGE_BITS_MIN
;
3475 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3481 RCU_READ_LOCK_GUARD();
3482 mr
= address_space_translate(&address_space_memory
,
3483 phys_addr
, &phys_addr
, &l
, false,
3484 MEMTXATTRS_UNSPECIFIED
);
3486 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3490 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3495 RCU_READ_LOCK_GUARD();
3496 RAMBLOCK_FOREACH(block
) {
3497 ret
= func(block
, opaque
);
3506 * Unmap pages of memory from start to start+length such that
3507 * they a) read as 0, b) Trigger whatever fault mechanism
3508 * the OS provides for postcopy.
3509 * The pages must be unmapped by the end of the function.
3510 * Returns: 0 on success, none-0 on failure
3513 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3517 uint8_t *host_startaddr
= rb
->host
+ start
;
3519 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3520 error_report("ram_block_discard_range: Unaligned start address: %p",
3525 if ((start
+ length
) <= rb
->max_length
) {
3526 bool need_madvise
, need_fallocate
;
3527 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3528 error_report("ram_block_discard_range: Unaligned length: %zx",
3533 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3535 /* The logic here is messy;
3536 * madvise DONTNEED fails for hugepages
3537 * fallocate works on hugepages and shmem
3538 * shared anonymous memory requires madvise REMOVE
3540 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3541 need_fallocate
= rb
->fd
!= -1;
3542 if (need_fallocate
) {
3543 /* For a file, this causes the area of the file to be zero'd
3544 * if read, and for hugetlbfs also causes it to be unmapped
3545 * so a userfault will trigger.
3547 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3548 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3552 error_report("ram_block_discard_range: Failed to fallocate "
3553 "%s:%" PRIx64
" +%zx (%d)",
3554 rb
->idstr
, start
, length
, ret
);
3559 error_report("ram_block_discard_range: fallocate not available/file"
3560 "%s:%" PRIx64
" +%zx (%d)",
3561 rb
->idstr
, start
, length
, ret
);
3566 /* For normal RAM this causes it to be unmapped,
3567 * for shared memory it causes the local mapping to disappear
3568 * and to fall back on the file contents (which we just
3569 * fallocate'd away).
3571 #if defined(CONFIG_MADVISE)
3572 if (qemu_ram_is_shared(rb
) && rb
->fd
< 0) {
3573 ret
= madvise(host_startaddr
, length
, QEMU_MADV_REMOVE
);
3575 ret
= madvise(host_startaddr
, length
, QEMU_MADV_DONTNEED
);
3579 error_report("ram_block_discard_range: Failed to discard range "
3580 "%s:%" PRIx64
" +%zx (%d)",
3581 rb
->idstr
, start
, length
, ret
);
3586 error_report("ram_block_discard_range: MADVISE not available"
3587 "%s:%" PRIx64
" +%zx (%d)",
3588 rb
->idstr
, start
, length
, ret
);
3592 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3593 need_madvise
, need_fallocate
, ret
);
3595 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3596 "/%zx/" RAM_ADDR_FMT
")",
3597 rb
->idstr
, start
, length
, rb
->max_length
);
3604 bool ramblock_is_pmem(RAMBlock
*rb
)
3606 return rb
->flags
& RAM_PMEM
;
3609 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3611 if (start
== end
- 1) {
3612 qemu_printf("\t%3d ", start
);
3614 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3616 qemu_printf(" skip=%d ", skip
);
3617 if (ptr
== PHYS_MAP_NODE_NIL
) {
3618 qemu_printf(" ptr=NIL");
3620 qemu_printf(" ptr=#%d", ptr
);
3622 qemu_printf(" ptr=[%d]", ptr
);
3627 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3628 int128_sub((size), int128_one())) : 0)
3630 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3634 qemu_printf(" Dispatch\n");
3635 qemu_printf(" Physical sections\n");
3637 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3638 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3639 const char *names
[] = { " [unassigned]", " [not dirty]",
3640 " [ROM]", " [watch]" };
3642 qemu_printf(" #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
3645 s
->offset_within_address_space
,
3646 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
3647 s
->mr
->name
? s
->mr
->name
: "(noname)",
3648 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3649 s
->mr
== root
? " [ROOT]" : "",
3650 s
== d
->mru_section
? " [MRU]" : "",
3651 s
->mr
->is_iommu
? " [iommu]" : "");
3654 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3655 s
->mr
->alias
->name
: "noname");
3660 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3661 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3662 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3665 Node
*n
= d
->map
.nodes
+ i
;
3667 qemu_printf(" [%d]\n", i
);
3669 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3670 PhysPageEntry
*pe
= *n
+ j
;
3672 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3676 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3682 if (jprev
!= ARRAY_SIZE(*n
)) {
3683 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3688 /* Require any discards to work. */
3689 static unsigned int ram_block_discard_required_cnt
;
3690 /* Require only coordinated discards to work. */
3691 static unsigned int ram_block_coordinated_discard_required_cnt
;
3692 /* Disable any discards. */
3693 static unsigned int ram_block_discard_disabled_cnt
;
3694 /* Disable only uncoordinated discards. */
3695 static unsigned int ram_block_uncoordinated_discard_disabled_cnt
;
3696 static QemuMutex ram_block_discard_disable_mutex
;
3698 static void ram_block_discard_disable_mutex_lock(void)
3700 static gsize initialized
;
3702 if (g_once_init_enter(&initialized
)) {
3703 qemu_mutex_init(&ram_block_discard_disable_mutex
);
3704 g_once_init_leave(&initialized
, 1);
3706 qemu_mutex_lock(&ram_block_discard_disable_mutex
);
3709 static void ram_block_discard_disable_mutex_unlock(void)
3711 qemu_mutex_unlock(&ram_block_discard_disable_mutex
);
3714 int ram_block_discard_disable(bool state
)
3718 ram_block_discard_disable_mutex_lock();
3720 ram_block_discard_disabled_cnt
--;
3721 } else if (ram_block_discard_required_cnt
||
3722 ram_block_coordinated_discard_required_cnt
) {
3725 ram_block_discard_disabled_cnt
++;
3727 ram_block_discard_disable_mutex_unlock();
3731 int ram_block_uncoordinated_discard_disable(bool state
)
3735 ram_block_discard_disable_mutex_lock();
3737 ram_block_uncoordinated_discard_disabled_cnt
--;
3738 } else if (ram_block_discard_required_cnt
) {
3741 ram_block_uncoordinated_discard_disabled_cnt
++;
3743 ram_block_discard_disable_mutex_unlock();
3747 int ram_block_discard_require(bool state
)
3751 ram_block_discard_disable_mutex_lock();
3753 ram_block_discard_required_cnt
--;
3754 } else if (ram_block_discard_disabled_cnt
||
3755 ram_block_uncoordinated_discard_disabled_cnt
) {
3758 ram_block_discard_required_cnt
++;
3760 ram_block_discard_disable_mutex_unlock();
3764 int ram_block_coordinated_discard_require(bool state
)
3768 ram_block_discard_disable_mutex_lock();
3770 ram_block_coordinated_discard_required_cnt
--;
3771 } else if (ram_block_discard_disabled_cnt
) {
3774 ram_block_coordinated_discard_required_cnt
++;
3776 ram_block_discard_disable_mutex_unlock();
3780 bool ram_block_discard_is_disabled(void)
3782 return qatomic_read(&ram_block_discard_disabled_cnt
) ||
3783 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt
);
3786 bool ram_block_discard_is_required(void)
3788 return qatomic_read(&ram_block_discard_required_cnt
) ||
3789 qatomic_read(&ram_block_coordinated_discard_required_cnt
);