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"
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 "exec/address-spaces.h"
51 #include "sysemu/xen-mapcache.h"
52 #include "trace/trace-root.h"
54 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
55 #include <linux/falloc.h>
58 #include "qemu/rcu_queue.h"
59 #include "qemu/main-loop.h"
60 #include "exec/translate-all.h"
61 #include "sysemu/replay.h"
63 #include "exec/memory-internal.h"
64 #include "exec/ram_addr.h"
67 #include "qemu/pmem.h"
69 #include "migration/vmstate.h"
71 #include "qemu/range.h"
73 #include "qemu/mmap-alloc.h"
76 #include "monitor/monitor.h"
78 #ifdef CONFIG_LIBDAXCTL
79 #include <daxctl/libdaxctl.h>
82 //#define DEBUG_SUBPAGE
84 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
85 * are protected by the ramlist lock.
87 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
89 static MemoryRegion
*system_memory
;
90 static MemoryRegion
*system_io
;
92 AddressSpace address_space_io
;
93 AddressSpace address_space_memory
;
95 static MemoryRegion io_mem_unassigned
;
97 typedef struct PhysPageEntry PhysPageEntry
;
99 struct PhysPageEntry
{
100 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
102 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
106 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
108 /* Size of the L2 (and L3, etc) page tables. */
109 #define ADDR_SPACE_BITS 64
112 #define P_L2_SIZE (1 << P_L2_BITS)
114 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
116 typedef PhysPageEntry Node
[P_L2_SIZE
];
118 typedef struct PhysPageMap
{
121 unsigned sections_nb
;
122 unsigned sections_nb_alloc
;
124 unsigned nodes_nb_alloc
;
126 MemoryRegionSection
*sections
;
129 struct AddressSpaceDispatch
{
130 MemoryRegionSection
*mru_section
;
131 /* This is a multi-level map on the physical address space.
132 * The bottom level has pointers to MemoryRegionSections.
134 PhysPageEntry phys_map
;
138 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
139 typedef struct subpage_t
{
143 uint16_t sub_section
[];
146 #define PHYS_SECTION_UNASSIGNED 0
148 static void io_mem_init(void);
149 static void memory_map_init(void);
150 static void tcg_log_global_after_sync(MemoryListener
*listener
);
151 static void tcg_commit(MemoryListener
*listener
);
154 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
155 * @cpu: the CPU whose AddressSpace this is
156 * @as: the AddressSpace itself
157 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
158 * @tcg_as_listener: listener for tracking changes to the AddressSpace
160 struct CPUAddressSpace
{
163 struct AddressSpaceDispatch
*memory_dispatch
;
164 MemoryListener tcg_as_listener
;
167 struct DirtyBitmapSnapshot
{
170 unsigned long dirty
[];
173 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
175 static unsigned alloc_hint
= 16;
176 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
177 map
->nodes_nb_alloc
= MAX(alloc_hint
, map
->nodes_nb
+ nodes
);
178 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
179 alloc_hint
= map
->nodes_nb_alloc
;
183 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
190 ret
= map
->nodes_nb
++;
192 assert(ret
!= PHYS_MAP_NODE_NIL
);
193 assert(ret
!= map
->nodes_nb_alloc
);
195 e
.skip
= leaf
? 0 : 1;
196 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
197 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
198 memcpy(&p
[i
], &e
, sizeof(e
));
203 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
204 hwaddr
*index
, uint64_t *nb
, uint16_t leaf
,
208 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
210 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
211 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
213 p
= map
->nodes
[lp
->ptr
];
214 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
216 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
217 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
223 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
229 static void phys_page_set(AddressSpaceDispatch
*d
,
230 hwaddr index
, uint64_t nb
,
233 /* Wildly overreserve - it doesn't matter much. */
234 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
236 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
239 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
240 * and update our entry so we can skip it and go directly to the destination.
242 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
244 unsigned valid_ptr
= P_L2_SIZE
;
249 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
254 for (i
= 0; i
< P_L2_SIZE
; i
++) {
255 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
262 phys_page_compact(&p
[i
], nodes
);
266 /* We can only compress if there's only one child. */
271 assert(valid_ptr
< P_L2_SIZE
);
273 /* Don't compress if it won't fit in the # of bits we have. */
274 if (P_L2_LEVELS
>= (1 << 6) &&
275 lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 6)) {
279 lp
->ptr
= p
[valid_ptr
].ptr
;
280 if (!p
[valid_ptr
].skip
) {
281 /* If our only child is a leaf, make this a leaf. */
282 /* By design, we should have made this node a leaf to begin with so we
283 * should never reach here.
284 * But since it's so simple to handle this, let's do it just in case we
289 lp
->skip
+= p
[valid_ptr
].skip
;
293 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
295 if (d
->phys_map
.skip
) {
296 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
300 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
303 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
304 * the section must cover the entire address space.
306 return int128_gethi(section
->size
) ||
307 range_covers_byte(section
->offset_within_address_space
,
308 int128_getlo(section
->size
), addr
);
311 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
313 PhysPageEntry lp
= d
->phys_map
, *p
;
314 Node
*nodes
= d
->map
.nodes
;
315 MemoryRegionSection
*sections
= d
->map
.sections
;
316 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
319 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
320 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
321 return §ions
[PHYS_SECTION_UNASSIGNED
];
324 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
327 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
328 return §ions
[lp
.ptr
];
330 return §ions
[PHYS_SECTION_UNASSIGNED
];
334 /* Called from RCU critical section */
335 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
337 bool resolve_subpage
)
339 MemoryRegionSection
*section
= qatomic_read(&d
->mru_section
);
342 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
343 !section_covers_addr(section
, addr
)) {
344 section
= phys_page_find(d
, addr
);
345 qatomic_set(&d
->mru_section
, section
);
347 if (resolve_subpage
&& section
->mr
->subpage
) {
348 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
349 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
354 /* Called from RCU critical section */
355 static MemoryRegionSection
*
356 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
357 hwaddr
*plen
, bool resolve_subpage
)
359 MemoryRegionSection
*section
;
363 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
364 /* Compute offset within MemoryRegionSection */
365 addr
-= section
->offset_within_address_space
;
367 /* Compute offset within MemoryRegion */
368 *xlat
= addr
+ section
->offset_within_region
;
372 /* MMIO registers can be expected to perform full-width accesses based only
373 * on their address, without considering adjacent registers that could
374 * decode to completely different MemoryRegions. When such registers
375 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
376 * regions overlap wildly. For this reason we cannot clamp the accesses
379 * If the length is small (as is the case for address_space_ldl/stl),
380 * everything works fine. If the incoming length is large, however,
381 * the caller really has to do the clamping through memory_access_size.
383 if (memory_region_is_ram(mr
)) {
384 diff
= int128_sub(section
->size
, int128_make64(addr
));
385 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
391 * address_space_translate_iommu - translate an address through an IOMMU
392 * memory region and then through the target address space.
394 * @iommu_mr: the IOMMU memory region that we start the translation from
395 * @addr: the address to be translated through the MMU
396 * @xlat: the translated address offset within the destination memory region.
397 * It cannot be %NULL.
398 * @plen_out: valid read/write length of the translated address. It
400 * @page_mask_out: page mask for the translated address. This
401 * should only be meaningful for IOMMU translated
402 * addresses, since there may be huge pages that this bit
403 * would tell. It can be %NULL if we don't care about it.
404 * @is_write: whether the translation operation is for write
405 * @is_mmio: whether this can be MMIO, set true if it can
406 * @target_as: the address space targeted by the IOMMU
407 * @attrs: transaction attributes
409 * This function is called from RCU critical section. It is the common
410 * part of flatview_do_translate and address_space_translate_cached.
412 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
415 hwaddr
*page_mask_out
,
418 AddressSpace
**target_as
,
421 MemoryRegionSection
*section
;
422 hwaddr page_mask
= (hwaddr
)-1;
426 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
430 if (imrc
->attrs_to_index
) {
431 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
434 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
435 IOMMU_WO
: IOMMU_RO
, iommu_idx
);
437 if (!(iotlb
.perm
& (1 << is_write
))) {
441 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
442 | (addr
& iotlb
.addr_mask
));
443 page_mask
&= iotlb
.addr_mask
;
444 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
445 *target_as
= iotlb
.target_as
;
447 section
= address_space_translate_internal(
448 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
451 iommu_mr
= memory_region_get_iommu(section
->mr
);
452 } while (unlikely(iommu_mr
));
455 *page_mask_out
= page_mask
;
460 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
464 * flatview_do_translate - translate an address in FlatView
466 * @fv: the flat view that we want to translate on
467 * @addr: the address to be translated in above address space
468 * @xlat: the translated address offset within memory region. It
470 * @plen_out: valid read/write length of the translated address. It
471 * can be @NULL when we don't care about it.
472 * @page_mask_out: page mask for the translated address. This
473 * should only be meaningful for IOMMU translated
474 * addresses, since there may be huge pages that this bit
475 * would tell. It can be @NULL if we don't care about it.
476 * @is_write: whether the translation operation is for write
477 * @is_mmio: whether this can be MMIO, set true if it can
478 * @target_as: the address space targeted by the IOMMU
479 * @attrs: memory transaction attributes
481 * This function is called from RCU critical section
483 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
487 hwaddr
*page_mask_out
,
490 AddressSpace
**target_as
,
493 MemoryRegionSection
*section
;
494 IOMMUMemoryRegion
*iommu_mr
;
495 hwaddr plen
= (hwaddr
)(-1);
501 section
= address_space_translate_internal(
502 flatview_to_dispatch(fv
), addr
, xlat
,
505 iommu_mr
= memory_region_get_iommu(section
->mr
);
506 if (unlikely(iommu_mr
)) {
507 return address_space_translate_iommu(iommu_mr
, xlat
,
508 plen_out
, page_mask_out
,
513 /* Not behind an IOMMU, use default page size. */
514 *page_mask_out
= ~TARGET_PAGE_MASK
;
520 /* Called from RCU critical section */
521 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
522 bool is_write
, MemTxAttrs attrs
)
524 MemoryRegionSection section
;
525 hwaddr xlat
, page_mask
;
528 * This can never be MMIO, and we don't really care about plen,
531 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
532 NULL
, &page_mask
, is_write
, false, &as
,
535 /* Illegal translation */
536 if (section
.mr
== &io_mem_unassigned
) {
540 /* Convert memory region offset into address space offset */
541 xlat
+= section
.offset_within_address_space
-
542 section
.offset_within_region
;
544 return (IOMMUTLBEntry
) {
546 .iova
= addr
& ~page_mask
,
547 .translated_addr
= xlat
& ~page_mask
,
548 .addr_mask
= page_mask
,
549 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
554 return (IOMMUTLBEntry
) {0};
557 /* Called from RCU critical section */
558 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
559 hwaddr
*plen
, bool is_write
,
563 MemoryRegionSection section
;
564 AddressSpace
*as
= NULL
;
566 /* This can be MMIO, so setup MMIO bit. */
567 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
568 is_write
, true, &as
, attrs
);
571 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
572 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
573 *plen
= MIN(page
, *plen
);
579 typedef struct TCGIOMMUNotifier
{
587 static void tcg_iommu_unmap_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
589 TCGIOMMUNotifier
*notifier
= container_of(n
, TCGIOMMUNotifier
, n
);
591 if (!notifier
->active
) {
594 tlb_flush(notifier
->cpu
);
595 notifier
->active
= false;
596 /* We leave the notifier struct on the list to avoid reallocating it later.
597 * Generally the number of IOMMUs a CPU deals with will be small.
598 * In any case we can't unregister the iommu notifier from a notify
603 static void tcg_register_iommu_notifier(CPUState
*cpu
,
604 IOMMUMemoryRegion
*iommu_mr
,
607 /* Make sure this CPU has an IOMMU notifier registered for this
608 * IOMMU/IOMMU index combination, so that we can flush its TLB
609 * when the IOMMU tells us the mappings we've cached have changed.
611 MemoryRegion
*mr
= MEMORY_REGION(iommu_mr
);
612 TCGIOMMUNotifier
*notifier
= NULL
;
615 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
616 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
617 if (notifier
->mr
== mr
&& notifier
->iommu_idx
== iommu_idx
) {
621 if (i
== cpu
->iommu_notifiers
->len
) {
622 /* Not found, add a new entry at the end of the array */
623 cpu
->iommu_notifiers
= g_array_set_size(cpu
->iommu_notifiers
, i
+ 1);
624 notifier
= g_new0(TCGIOMMUNotifier
, 1);
625 g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
) = notifier
;
628 notifier
->iommu_idx
= iommu_idx
;
630 /* Rather than trying to register interest in the specific part
631 * of the iommu's address space that we've accessed and then
632 * expand it later as subsequent accesses touch more of it, we
633 * just register interest in the whole thing, on the assumption
634 * that iommu reconfiguration will be rare.
636 iommu_notifier_init(¬ifier
->n
,
637 tcg_iommu_unmap_notify
,
638 IOMMU_NOTIFIER_UNMAP
,
642 memory_region_register_iommu_notifier(notifier
->mr
, ¬ifier
->n
,
646 if (!notifier
->active
) {
647 notifier
->active
= true;
651 void tcg_iommu_free_notifier_list(CPUState
*cpu
)
653 /* Destroy the CPU's notifier list */
655 TCGIOMMUNotifier
*notifier
;
657 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
658 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
659 memory_region_unregister_iommu_notifier(notifier
->mr
, ¬ifier
->n
);
662 g_array_free(cpu
->iommu_notifiers
, true);
665 void tcg_iommu_init_notifier_list(CPUState
*cpu
)
667 cpu
->iommu_notifiers
= g_array_new(false, true, sizeof(TCGIOMMUNotifier
*));
670 /* Called from RCU critical section */
671 MemoryRegionSection
*
672 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr addr
,
673 hwaddr
*xlat
, hwaddr
*plen
,
674 MemTxAttrs attrs
, int *prot
)
676 MemoryRegionSection
*section
;
677 IOMMUMemoryRegion
*iommu_mr
;
678 IOMMUMemoryRegionClass
*imrc
;
681 AddressSpaceDispatch
*d
=
682 qatomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
685 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
687 iommu_mr
= memory_region_get_iommu(section
->mr
);
692 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
694 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
695 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
696 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
697 * doesn't short-cut its translation table walk.
699 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
700 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
701 | (addr
& iotlb
.addr_mask
));
702 /* Update the caller's prot bits to remove permissions the IOMMU
703 * is giving us a failure response for. If we get down to no
704 * permissions left at all we can give up now.
706 if (!(iotlb
.perm
& IOMMU_RO
)) {
707 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
709 if (!(iotlb
.perm
& IOMMU_WO
)) {
710 *prot
&= ~PAGE_WRITE
;
717 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
720 assert(!memory_region_is_iommu(section
->mr
));
725 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
728 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
729 const char *prefix
, MemoryRegion
*mr
)
731 CPUAddressSpace
*newas
;
732 AddressSpace
*as
= g_new0(AddressSpace
, 1);
736 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
737 address_space_init(as
, mr
, as_name
);
740 /* Target code should have set num_ases before calling us */
741 assert(asidx
< cpu
->num_ases
);
744 /* address space 0 gets the convenience alias */
748 /* KVM cannot currently support multiple address spaces. */
749 assert(asidx
== 0 || !kvm_enabled());
751 if (!cpu
->cpu_ases
) {
752 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
755 newas
= &cpu
->cpu_ases
[asidx
];
759 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
760 newas
->tcg_as_listener
.commit
= tcg_commit
;
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
)
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
);
784 wp
= g_malloc(sizeof(*wp
));
790 /* keep all GDB-injected watchpoints in front */
791 if (flags
& BP_GDB
) {
792 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
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
);
809 /* Remove a specific watchpoint. */
810 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
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
);
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
);
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
);
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
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
)
873 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
874 if (watchpoint_address_matches(wp
, addr
, len
)) {
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
);
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();
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 * Don't process the watchpoints when we are
911 * in a reverse debugging operation.
916 if (flags
== BP_MEM_READ
) {
917 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
919 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
921 wp
->hitaddr
= MAX(addr
, wp
->vaddr
);
922 wp
->hitattrs
= attrs
;
923 if (!cpu
->watchpoint_hit
) {
924 if (wp
->flags
& BP_CPU
&& cc
->tcg_ops
->debug_check_watchpoint
&&
925 !cc
->tcg_ops
->debug_check_watchpoint(cpu
, wp
)) {
926 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
929 cpu
->watchpoint_hit
= wp
;
932 tb_check_watchpoint(cpu
, ra
);
933 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
934 cpu
->exception_index
= EXCP_DEBUG
;
936 cpu_loop_exit_restore(cpu
, ra
);
938 /* Force execution of one insn next time. */
939 cpu
->cflags_next_tb
= 1 | curr_cflags(cpu
);
942 cpu_restore_state(cpu
, ra
, true);
944 cpu_loop_exit_noexc(cpu
);
948 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
953 #endif /* CONFIG_TCG */
955 /* Called from RCU critical section */
956 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
960 block
= qatomic_rcu_read(&ram_list
.mru_block
);
961 if (block
&& addr
- block
->offset
< block
->max_length
) {
964 RAMBLOCK_FOREACH(block
) {
965 if (addr
- block
->offset
< block
->max_length
) {
970 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
974 /* It is safe to write mru_block outside the iothread lock. This
979 * xxx removed from list
983 * call_rcu(reclaim_ramblock, xxx);
986 * qatomic_rcu_set is not needed here. The block was already published
987 * when it was placed into the list. Here we're just making an extra
988 * copy of the pointer.
990 ram_list
.mru_block
= block
;
994 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
1001 assert(tcg_enabled());
1002 end
= TARGET_PAGE_ALIGN(start
+ length
);
1003 start
&= TARGET_PAGE_MASK
;
1005 RCU_READ_LOCK_GUARD();
1006 block
= qemu_get_ram_block(start
);
1007 assert(block
== qemu_get_ram_block(end
- 1));
1008 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
1010 tlb_reset_dirty(cpu
, start1
, length
);
1014 /* Note: start and end must be within the same ram block. */
1015 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
1019 DirtyMemoryBlocks
*blocks
;
1020 unsigned long end
, page
, start_page
;
1023 uint64_t mr_offset
, mr_size
;
1029 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
1030 start_page
= start
>> TARGET_PAGE_BITS
;
1033 WITH_RCU_READ_LOCK_GUARD() {
1034 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1035 ramblock
= qemu_get_ram_block(start
);
1036 /* Range sanity check on the ramblock */
1037 assert(start
>= ramblock
->offset
&&
1038 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
1040 while (page
< end
) {
1041 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1042 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1043 unsigned long num
= MIN(end
- page
,
1044 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1046 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
1051 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
1052 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
1053 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
1056 if (dirty
&& tcg_enabled()) {
1057 tlb_reset_dirty_range_all(start
, length
);
1063 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
1064 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
1066 DirtyMemoryBlocks
*blocks
;
1067 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
1068 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
1069 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
1070 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
1071 DirtyBitmapSnapshot
*snap
;
1072 unsigned long page
, end
, dest
;
1074 snap
= g_malloc0(sizeof(*snap
) +
1075 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1076 snap
->start
= first
;
1079 page
= first
>> TARGET_PAGE_BITS
;
1080 end
= last
>> TARGET_PAGE_BITS
;
1083 WITH_RCU_READ_LOCK_GUARD() {
1084 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1086 while (page
< end
) {
1087 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1088 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1089 unsigned long num
= MIN(end
- page
,
1090 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1092 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1093 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1094 offset
>>= BITS_PER_LEVEL
;
1096 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1097 blocks
->blocks
[idx
] + offset
,
1100 dest
+= num
>> BITS_PER_LEVEL
;
1104 if (tcg_enabled()) {
1105 tlb_reset_dirty_range_all(start
, length
);
1108 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
1113 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1117 unsigned long page
, end
;
1119 assert(start
>= snap
->start
);
1120 assert(start
+ length
<= snap
->end
);
1122 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1123 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1125 while (page
< end
) {
1126 if (test_bit(page
, snap
->dirty
)) {
1134 /* Called from RCU critical section */
1135 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1136 MemoryRegionSection
*section
)
1138 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
1139 return section
- d
->map
.sections
;
1142 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1144 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1146 static uint16_t phys_section_add(PhysPageMap
*map
,
1147 MemoryRegionSection
*section
)
1149 /* The physical section number is ORed with a page-aligned
1150 * pointer to produce the iotlb entries. Thus it should
1151 * never overflow into the page-aligned value.
1153 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1155 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1156 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1157 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1158 map
->sections_nb_alloc
);
1160 map
->sections
[map
->sections_nb
] = *section
;
1161 memory_region_ref(section
->mr
);
1162 return map
->sections_nb
++;
1165 static void phys_section_destroy(MemoryRegion
*mr
)
1167 bool have_sub_page
= mr
->subpage
;
1169 memory_region_unref(mr
);
1171 if (have_sub_page
) {
1172 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1173 object_unref(OBJECT(&subpage
->iomem
));
1178 static void phys_sections_free(PhysPageMap
*map
)
1180 while (map
->sections_nb
> 0) {
1181 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1182 phys_section_destroy(section
->mr
);
1184 g_free(map
->sections
);
1188 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1190 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1192 hwaddr base
= section
->offset_within_address_space
1194 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1195 MemoryRegionSection subsection
= {
1196 .offset_within_address_space
= base
,
1197 .size
= int128_make64(TARGET_PAGE_SIZE
),
1201 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1203 if (!(existing
->mr
->subpage
)) {
1204 subpage
= subpage_init(fv
, base
);
1206 subsection
.mr
= &subpage
->iomem
;
1207 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1208 phys_section_add(&d
->map
, &subsection
));
1210 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1212 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1213 end
= start
+ int128_get64(section
->size
) - 1;
1214 subpage_register(subpage
, start
, end
,
1215 phys_section_add(&d
->map
, section
));
1219 static void register_multipage(FlatView
*fv
,
1220 MemoryRegionSection
*section
)
1222 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1223 hwaddr start_addr
= section
->offset_within_address_space
;
1224 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1225 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1229 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1233 * The range in *section* may look like this:
1237 * where s stands for subpage and P for page.
1239 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1241 MemoryRegionSection remain
= *section
;
1242 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1244 /* register first subpage */
1245 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1246 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1247 - remain
.offset_within_address_space
;
1249 MemoryRegionSection now
= remain
;
1250 now
.size
= int128_min(int128_make64(left
), now
.size
);
1251 register_subpage(fv
, &now
);
1252 if (int128_eq(remain
.size
, now
.size
)) {
1255 remain
.size
= int128_sub(remain
.size
, now
.size
);
1256 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1257 remain
.offset_within_region
+= int128_get64(now
.size
);
1260 /* register whole pages */
1261 if (int128_ge(remain
.size
, page_size
)) {
1262 MemoryRegionSection now
= remain
;
1263 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1264 register_multipage(fv
, &now
);
1265 if (int128_eq(remain
.size
, now
.size
)) {
1268 remain
.size
= int128_sub(remain
.size
, now
.size
);
1269 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1270 remain
.offset_within_region
+= int128_get64(now
.size
);
1273 /* register last subpage */
1274 register_subpage(fv
, &remain
);
1277 void qemu_flush_coalesced_mmio_buffer(void)
1280 kvm_flush_coalesced_mmio_buffer();
1283 void qemu_mutex_lock_ramlist(void)
1285 qemu_mutex_lock(&ram_list
.mutex
);
1288 void qemu_mutex_unlock_ramlist(void)
1290 qemu_mutex_unlock(&ram_list
.mutex
);
1293 void ram_block_dump(Monitor
*mon
)
1298 RCU_READ_LOCK_GUARD();
1299 monitor_printf(mon
, "%24s %8s %18s %18s %18s\n",
1300 "Block Name", "PSize", "Offset", "Used", "Total");
1301 RAMBLOCK_FOREACH(block
) {
1302 psize
= size_to_str(block
->page_size
);
1303 monitor_printf(mon
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1304 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1305 (uint64_t)block
->offset
,
1306 (uint64_t)block
->used_length
,
1307 (uint64_t)block
->max_length
);
1314 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1315 * may or may not name the same files / on the same filesystem now as
1316 * when we actually open and map them. Iterate over the file
1317 * descriptors instead, and use qemu_fd_getpagesize().
1319 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1321 long *hpsize_min
= opaque
;
1323 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1324 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1325 long hpsize
= host_memory_backend_pagesize(backend
);
1327 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1328 *hpsize_min
= hpsize
;
1335 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1337 long *hpsize_max
= opaque
;
1339 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1340 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1341 long hpsize
= host_memory_backend_pagesize(backend
);
1343 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1344 *hpsize_max
= hpsize
;
1352 * TODO: We assume right now that all mapped host memory backends are
1353 * used as RAM, however some might be used for different purposes.
1355 long qemu_minrampagesize(void)
1357 long hpsize
= LONG_MAX
;
1358 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1360 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1364 long qemu_maxrampagesize(void)
1367 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1369 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1373 long qemu_minrampagesize(void)
1375 return qemu_real_host_page_size
;
1377 long qemu_maxrampagesize(void)
1379 return qemu_real_host_page_size
;
1384 static int64_t get_file_size(int fd
)
1387 #if defined(__linux__)
1390 if (fstat(fd
, &st
) < 0) {
1394 /* Special handling for devdax character devices */
1395 if (S_ISCHR(st
.st_mode
)) {
1396 g_autofree
char *subsystem_path
= NULL
;
1397 g_autofree
char *subsystem
= NULL
;
1399 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1400 major(st
.st_rdev
), minor(st
.st_rdev
));
1401 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1403 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1404 g_autofree
char *size_path
= NULL
;
1405 g_autofree
char *size_str
= NULL
;
1407 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1408 major(st
.st_rdev
), minor(st
.st_rdev
));
1410 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1411 return g_ascii_strtoll(size_str
, NULL
, 0);
1415 #endif /* defined(__linux__) */
1417 /* st.st_size may be zero for special files yet lseek(2) works */
1418 size
= lseek(fd
, 0, SEEK_END
);
1425 static int64_t get_file_align(int fd
)
1428 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1431 if (fstat(fd
, &st
) < 0) {
1435 /* Special handling for devdax character devices */
1436 if (S_ISCHR(st
.st_mode
)) {
1437 g_autofree
char *path
= NULL
;
1438 g_autofree
char *rpath
= NULL
;
1439 struct daxctl_ctx
*ctx
;
1440 struct daxctl_region
*region
;
1443 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1444 major(st
.st_rdev
), minor(st
.st_rdev
));
1445 rpath
= realpath(path
, NULL
);
1447 rc
= daxctl_new(&ctx
);
1452 daxctl_region_foreach(ctx
, region
) {
1453 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1454 align
= daxctl_region_get_align(region
);
1460 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1465 static int file_ram_open(const char *path
,
1466 const char *region_name
,
1472 char *sanitized_name
;
1478 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1480 /* @path names an existing file, use it */
1483 if (errno
== ENOENT
) {
1484 /* @path names a file that doesn't exist, create it */
1485 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1490 } else if (errno
== EISDIR
) {
1491 /* @path names a directory, create a file there */
1492 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1493 sanitized_name
= g_strdup(region_name
);
1494 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1500 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1502 g_free(sanitized_name
);
1504 fd
= mkstemp(filename
);
1512 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1513 error_setg_errno(errp
, errno
,
1514 "can't open backing store %s for guest RAM",
1519 * Try again on EINTR and EEXIST. The latter happens when
1520 * something else creates the file between our two open().
1527 static void *file_ram_alloc(RAMBlock
*block
,
1537 block
->page_size
= qemu_fd_getpagesize(fd
);
1538 if (block
->mr
->align
% block
->page_size
) {
1539 error_setg(errp
, "alignment 0x%" PRIx64
1540 " must be multiples of page size 0x%zx",
1541 block
->mr
->align
, block
->page_size
);
1543 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1544 error_setg(errp
, "alignment 0x%" PRIx64
1545 " must be a power of two", block
->mr
->align
);
1548 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1549 #if defined(__s390x__)
1550 if (kvm_enabled()) {
1551 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1555 if (memory
< block
->page_size
) {
1556 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1557 "or larger than page size 0x%zx",
1558 memory
, block
->page_size
);
1562 memory
= ROUND_UP(memory
, block
->page_size
);
1565 * ftruncate is not supported by hugetlbfs in older
1566 * hosts, so don't bother bailing out on errors.
1567 * If anything goes wrong with it under other filesystems,
1570 * Do not truncate the non-empty backend file to avoid corrupting
1571 * the existing data in the file. Disabling shrinking is not
1572 * enough. For example, the current vNVDIMM implementation stores
1573 * the guest NVDIMM labels at the end of the backend file. If the
1574 * backend file is later extended, QEMU will not be able to find
1575 * those labels. Therefore, extending the non-empty backend file
1576 * is disabled as well.
1578 if (truncate
&& ftruncate(fd
, memory
)) {
1579 perror("ftruncate");
1582 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, readonly
,
1583 block
->flags
& RAM_SHARED
, block
->flags
& RAM_PMEM
,
1585 if (area
== MAP_FAILED
) {
1586 error_setg_errno(errp
, errno
,
1587 "unable to map backing store for guest RAM");
1596 /* Allocate space within the ram_addr_t space that governs the
1598 * Called with the ramlist lock held.
1600 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1602 RAMBlock
*block
, *next_block
;
1603 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1605 assert(size
!= 0); /* it would hand out same offset multiple times */
1607 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1611 RAMBLOCK_FOREACH(block
) {
1612 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1614 /* Align blocks to start on a 'long' in the bitmap
1615 * which makes the bitmap sync'ing take the fast path.
1617 candidate
= block
->offset
+ block
->max_length
;
1618 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1620 /* Search for the closest following block
1623 RAMBLOCK_FOREACH(next_block
) {
1624 if (next_block
->offset
>= candidate
) {
1625 next
= MIN(next
, next_block
->offset
);
1629 /* If it fits remember our place and remember the size
1630 * of gap, but keep going so that we might find a smaller
1631 * gap to fill so avoiding fragmentation.
1633 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1635 mingap
= next
- candidate
;
1638 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1641 if (offset
== RAM_ADDR_MAX
) {
1642 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1647 trace_find_ram_offset(size
, offset
);
1652 static unsigned long last_ram_page(void)
1655 ram_addr_t last
= 0;
1657 RCU_READ_LOCK_GUARD();
1658 RAMBLOCK_FOREACH(block
) {
1659 last
= MAX(last
, block
->offset
+ block
->max_length
);
1661 return last
>> TARGET_PAGE_BITS
;
1664 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1668 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1669 if (!machine_dump_guest_core(current_machine
)) {
1670 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1672 perror("qemu_madvise");
1673 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1674 "but dump_guest_core=off specified\n");
1679 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1684 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1689 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1694 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1696 return rb
->used_length
;
1699 bool qemu_ram_is_shared(RAMBlock
*rb
)
1701 return rb
->flags
& RAM_SHARED
;
1704 /* Note: Only set at the start of postcopy */
1705 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1707 return rb
->flags
& RAM_UF_ZEROPAGE
;
1710 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1712 rb
->flags
|= RAM_UF_ZEROPAGE
;
1715 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1717 return rb
->flags
& RAM_MIGRATABLE
;
1720 void qemu_ram_set_migratable(RAMBlock
*rb
)
1722 rb
->flags
|= RAM_MIGRATABLE
;
1725 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1727 rb
->flags
&= ~RAM_MIGRATABLE
;
1730 /* Called with iothread lock held. */
1731 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1736 assert(!new_block
->idstr
[0]);
1739 char *id
= qdev_get_dev_path(dev
);
1741 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1745 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1747 RCU_READ_LOCK_GUARD();
1748 RAMBLOCK_FOREACH(block
) {
1749 if (block
!= new_block
&&
1750 !strcmp(block
->idstr
, new_block
->idstr
)) {
1751 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1758 /* Called with iothread lock held. */
1759 void qemu_ram_unset_idstr(RAMBlock
*block
)
1761 /* FIXME: arch_init.c assumes that this is not called throughout
1762 * migration. Ignore the problem since hot-unplug during migration
1763 * does not work anyway.
1766 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1770 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1772 return rb
->page_size
;
1775 /* Returns the largest size of page in use */
1776 size_t qemu_ram_pagesize_largest(void)
1781 RAMBLOCK_FOREACH(block
) {
1782 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1788 static int memory_try_enable_merging(void *addr
, size_t len
)
1790 if (!machine_mem_merge(current_machine
)) {
1791 /* disabled by the user */
1795 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1798 /* Only legal before guest might have detected the memory size: e.g. on
1799 * incoming migration, or right after reset.
1801 * As memory core doesn't know how is memory accessed, it is up to
1802 * resize callback to update device state and/or add assertions to detect
1803 * misuse, if necessary.
1805 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1807 const ram_addr_t unaligned_size
= newsize
;
1811 newsize
= HOST_PAGE_ALIGN(newsize
);
1813 if (block
->used_length
== newsize
) {
1815 * We don't have to resize the ram block (which only knows aligned
1816 * sizes), however, we have to notify if the unaligned size changed.
1818 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1819 memory_region_set_size(block
->mr
, unaligned_size
);
1820 if (block
->resized
) {
1821 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1827 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1828 error_setg_errno(errp
, EINVAL
,
1829 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1830 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1831 newsize
, block
->used_length
);
1835 if (block
->max_length
< newsize
) {
1836 error_setg_errno(errp
, EINVAL
,
1837 "Size too large: %s: 0x" RAM_ADDR_FMT
1838 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1839 newsize
, block
->max_length
);
1843 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1844 block
->used_length
= newsize
;
1845 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1847 memory_region_set_size(block
->mr
, unaligned_size
);
1848 if (block
->resized
) {
1849 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1855 * Trigger sync on the given ram block for range [start, start + length]
1856 * with the backing store if one is available.
1858 * @Note: this is supposed to be a synchronous op.
1860 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1862 /* The requested range should fit in within the block range */
1863 g_assert((start
+ length
) <= block
->used_length
);
1865 #ifdef CONFIG_LIBPMEM
1866 /* The lack of support for pmem should not block the sync */
1867 if (ramblock_is_pmem(block
)) {
1868 void *addr
= ramblock_ptr(block
, start
);
1869 pmem_persist(addr
, length
);
1873 if (block
->fd
>= 0) {
1875 * Case there is no support for PMEM or the memory has not been
1876 * specified as persistent (or is not one) - use the msync.
1877 * Less optimal but still achieves the same goal
1879 void *addr
= ramblock_ptr(block
, start
);
1880 if (qemu_msync(addr
, length
, block
->fd
)) {
1881 warn_report("%s: failed to sync memory range: start: "
1882 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1883 __func__
, start
, length
);
1888 /* Called with ram_list.mutex held */
1889 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1890 ram_addr_t new_ram_size
)
1892 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1893 DIRTY_MEMORY_BLOCK_SIZE
);
1894 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1895 DIRTY_MEMORY_BLOCK_SIZE
);
1898 /* Only need to extend if block count increased */
1899 if (new_num_blocks
<= old_num_blocks
) {
1903 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1904 DirtyMemoryBlocks
*old_blocks
;
1905 DirtyMemoryBlocks
*new_blocks
;
1908 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1909 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1910 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1912 if (old_num_blocks
) {
1913 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1914 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1917 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1918 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1921 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1924 g_free_rcu(old_blocks
, rcu
);
1929 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
, bool shared
)
1932 RAMBlock
*last_block
= NULL
;
1933 ram_addr_t old_ram_size
, new_ram_size
;
1936 old_ram_size
= last_ram_page();
1938 qemu_mutex_lock_ramlist();
1939 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1941 if (!new_block
->host
) {
1942 if (xen_enabled()) {
1943 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1944 new_block
->mr
, &err
);
1946 error_propagate(errp
, err
);
1947 qemu_mutex_unlock_ramlist();
1951 new_block
->host
= qemu_anon_ram_alloc(new_block
->max_length
,
1952 &new_block
->mr
->align
,
1954 if (!new_block
->host
) {
1955 error_setg_errno(errp
, errno
,
1956 "cannot set up guest memory '%s'",
1957 memory_region_name(new_block
->mr
));
1958 qemu_mutex_unlock_ramlist();
1961 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1965 new_ram_size
= MAX(old_ram_size
,
1966 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1967 if (new_ram_size
> old_ram_size
) {
1968 dirty_memory_extend(old_ram_size
, new_ram_size
);
1970 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1971 * QLIST (which has an RCU-friendly variant) does not have insertion at
1972 * tail, so save the last element in last_block.
1974 RAMBLOCK_FOREACH(block
) {
1976 if (block
->max_length
< new_block
->max_length
) {
1981 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1982 } else if (last_block
) {
1983 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1984 } else { /* list is empty */
1985 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1987 ram_list
.mru_block
= NULL
;
1989 /* Write list before version */
1992 qemu_mutex_unlock_ramlist();
1994 cpu_physical_memory_set_dirty_range(new_block
->offset
,
1995 new_block
->used_length
,
1998 if (new_block
->host
) {
1999 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
2000 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
2002 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2003 * Configure it unless the machine is a qtest server, in which case
2004 * KVM is not used and it may be forked (eg for fuzzing purposes).
2006 if (!qtest_enabled()) {
2007 qemu_madvise(new_block
->host
, new_block
->max_length
,
2008 QEMU_MADV_DONTFORK
);
2010 ram_block_notify_add(new_block
->host
, new_block
->max_length
);
2015 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
2016 uint32_t ram_flags
, int fd
, off_t offset
,
2017 bool readonly
, Error
**errp
)
2019 RAMBlock
*new_block
;
2020 Error
*local_err
= NULL
;
2021 int64_t file_size
, file_align
;
2023 /* Just support these ram flags by now. */
2024 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
)) == 0);
2026 if (xen_enabled()) {
2027 error_setg(errp
, "-mem-path not supported with Xen");
2031 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2033 "host lacks kvm mmu notifiers, -mem-path unsupported");
2037 size
= HOST_PAGE_ALIGN(size
);
2038 file_size
= get_file_size(fd
);
2039 if (file_size
> 0 && file_size
< size
) {
2040 error_setg(errp
, "backing store size 0x%" PRIx64
2041 " does not match 'size' option 0x" RAM_ADDR_FMT
,
2046 file_align
= get_file_align(fd
);
2047 if (file_align
> 0 && mr
&& file_align
> mr
->align
) {
2048 error_setg(errp
, "backing store align 0x%" PRIx64
2049 " is larger than 'align' option 0x%" PRIx64
,
2050 file_align
, mr
->align
);
2054 new_block
= g_malloc0(sizeof(*new_block
));
2056 new_block
->used_length
= size
;
2057 new_block
->max_length
= size
;
2058 new_block
->flags
= ram_flags
;
2059 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, readonly
,
2060 !file_size
, offset
, errp
);
2061 if (!new_block
->host
) {
2066 ram_block_add(new_block
, &local_err
, ram_flags
& RAM_SHARED
);
2069 error_propagate(errp
, local_err
);
2077 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2078 uint32_t ram_flags
, const char *mem_path
,
2079 bool readonly
, Error
**errp
)
2085 fd
= file_ram_open(mem_path
, memory_region_name(mr
), readonly
, &created
,
2091 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, 0, readonly
, errp
);
2105 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2106 void (*resized
)(const char*,
2109 void *host
, bool resizeable
, bool share
,
2110 MemoryRegion
*mr
, Error
**errp
)
2112 RAMBlock
*new_block
;
2113 Error
*local_err
= NULL
;
2115 size
= HOST_PAGE_ALIGN(size
);
2116 max_size
= HOST_PAGE_ALIGN(max_size
);
2117 new_block
= g_malloc0(sizeof(*new_block
));
2119 new_block
->resized
= resized
;
2120 new_block
->used_length
= size
;
2121 new_block
->max_length
= max_size
;
2122 assert(max_size
>= size
);
2124 new_block
->page_size
= qemu_real_host_page_size
;
2125 new_block
->host
= host
;
2127 new_block
->flags
|= RAM_PREALLOC
;
2130 new_block
->flags
|= RAM_RESIZEABLE
;
2132 ram_block_add(new_block
, &local_err
, share
);
2135 error_propagate(errp
, local_err
);
2141 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2142 MemoryRegion
*mr
, Error
**errp
)
2144 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, false,
2148 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, bool share
,
2149 MemoryRegion
*mr
, Error
**errp
)
2151 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, false,
2155 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2156 void (*resized
)(const char*,
2159 MemoryRegion
*mr
, Error
**errp
)
2161 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
, true,
2165 static void reclaim_ramblock(RAMBlock
*block
)
2167 if (block
->flags
& RAM_PREALLOC
) {
2169 } else if (xen_enabled()) {
2170 xen_invalidate_map_cache_entry(block
->host
);
2172 } else if (block
->fd
>= 0) {
2173 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2177 qemu_anon_ram_free(block
->host
, block
->max_length
);
2182 void qemu_ram_free(RAMBlock
*block
)
2189 ram_block_notify_remove(block
->host
, block
->max_length
);
2192 qemu_mutex_lock_ramlist();
2193 QLIST_REMOVE_RCU(block
, next
);
2194 ram_list
.mru_block
= NULL
;
2195 /* Write list before version */
2198 call_rcu(block
, reclaim_ramblock
, rcu
);
2199 qemu_mutex_unlock_ramlist();
2203 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2210 RAMBLOCK_FOREACH(block
) {
2211 offset
= addr
- block
->offset
;
2212 if (offset
< block
->max_length
) {
2213 vaddr
= ramblock_ptr(block
, offset
);
2214 if (block
->flags
& RAM_PREALLOC
) {
2216 } else if (xen_enabled()) {
2220 if (block
->fd
>= 0) {
2221 flags
|= (block
->flags
& RAM_SHARED
?
2222 MAP_SHARED
: MAP_PRIVATE
);
2223 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2224 flags
, block
->fd
, offset
);
2226 flags
|= MAP_PRIVATE
| MAP_ANONYMOUS
;
2227 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2230 if (area
!= vaddr
) {
2231 error_report("Could not remap addr: "
2232 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2236 memory_try_enable_merging(vaddr
, length
);
2237 qemu_ram_setup_dump(vaddr
, length
);
2242 #endif /* !_WIN32 */
2244 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2245 * This should not be used for general purpose DMA. Use address_space_map
2246 * or address_space_rw instead. For local memory (e.g. video ram) that the
2247 * device owns, use memory_region_get_ram_ptr.
2249 * Called within RCU critical section.
2251 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2253 RAMBlock
*block
= ram_block
;
2255 if (block
== NULL
) {
2256 block
= qemu_get_ram_block(addr
);
2257 addr
-= block
->offset
;
2260 if (xen_enabled() && block
->host
== NULL
) {
2261 /* We need to check if the requested address is in the RAM
2262 * because we don't want to map the entire memory in QEMU.
2263 * In that case just map until the end of the page.
2265 if (block
->offset
== 0) {
2266 return xen_map_cache(addr
, 0, 0, false);
2269 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2271 return ramblock_ptr(block
, addr
);
2274 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2275 * but takes a size argument.
2277 * Called within RCU critical section.
2279 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2280 hwaddr
*size
, bool lock
)
2282 RAMBlock
*block
= ram_block
;
2287 if (block
== NULL
) {
2288 block
= qemu_get_ram_block(addr
);
2289 addr
-= block
->offset
;
2291 *size
= MIN(*size
, block
->max_length
- addr
);
2293 if (xen_enabled() && block
->host
== NULL
) {
2294 /* We need to check if the requested address is in the RAM
2295 * because we don't want to map the entire memory in QEMU.
2296 * In that case just map the requested area.
2298 if (block
->offset
== 0) {
2299 return xen_map_cache(addr
, *size
, lock
, lock
);
2302 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2305 return ramblock_ptr(block
, addr
);
2308 /* Return the offset of a hostpointer within a ramblock */
2309 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2311 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2312 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2313 assert(res
< rb
->max_length
);
2319 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2322 * ptr: Host pointer to look up
2323 * round_offset: If true round the result offset down to a page boundary
2324 * *ram_addr: set to result ram_addr
2325 * *offset: set to result offset within the RAMBlock
2327 * Returns: RAMBlock (or NULL if not found)
2329 * By the time this function returns, the returned pointer is not protected
2330 * by RCU anymore. If the caller is not within an RCU critical section and
2331 * does not hold the iothread lock, it must have other means of protecting the
2332 * pointer, such as a reference to the region that includes the incoming
2335 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2339 uint8_t *host
= ptr
;
2341 if (xen_enabled()) {
2342 ram_addr_t ram_addr
;
2343 RCU_READ_LOCK_GUARD();
2344 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2345 block
= qemu_get_ram_block(ram_addr
);
2347 *offset
= ram_addr
- block
->offset
;
2352 RCU_READ_LOCK_GUARD();
2353 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2354 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2358 RAMBLOCK_FOREACH(block
) {
2359 /* This case append when the block is not mapped. */
2360 if (block
->host
== NULL
) {
2363 if (host
- block
->host
< block
->max_length
) {
2371 *offset
= (host
- block
->host
);
2373 *offset
&= TARGET_PAGE_MASK
;
2379 * Finds the named RAMBlock
2381 * name: The name of RAMBlock to find
2383 * Returns: RAMBlock (or NULL if not found)
2385 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2389 RAMBLOCK_FOREACH(block
) {
2390 if (!strcmp(name
, block
->idstr
)) {
2398 /* Some of the softmmu routines need to translate from a host pointer
2399 (typically a TLB entry) back to a ram offset. */
2400 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2405 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2407 return RAM_ADDR_INVALID
;
2410 return block
->offset
+ offset
;
2413 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2414 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2415 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2416 const void *buf
, hwaddr len
);
2417 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2418 bool is_write
, MemTxAttrs attrs
);
2420 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2421 unsigned len
, MemTxAttrs attrs
)
2423 subpage_t
*subpage
= opaque
;
2427 #if defined(DEBUG_SUBPAGE)
2428 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2429 subpage
, len
, addr
);
2431 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2435 *data
= ldn_p(buf
, len
);
2439 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2440 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2442 subpage_t
*subpage
= opaque
;
2445 #if defined(DEBUG_SUBPAGE)
2446 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2447 " value %"PRIx64
"\n",
2448 __func__
, subpage
, len
, addr
, value
);
2450 stn_p(buf
, len
, value
);
2451 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2454 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2455 unsigned len
, bool is_write
,
2458 subpage_t
*subpage
= opaque
;
2459 #if defined(DEBUG_SUBPAGE)
2460 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2461 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2464 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2465 len
, is_write
, attrs
);
2468 static const MemoryRegionOps subpage_ops
= {
2469 .read_with_attrs
= subpage_read
,
2470 .write_with_attrs
= subpage_write
,
2471 .impl
.min_access_size
= 1,
2472 .impl
.max_access_size
= 8,
2473 .valid
.min_access_size
= 1,
2474 .valid
.max_access_size
= 8,
2475 .valid
.accepts
= subpage_accepts
,
2476 .endianness
= DEVICE_NATIVE_ENDIAN
,
2479 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2484 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2486 idx
= SUBPAGE_IDX(start
);
2487 eidx
= SUBPAGE_IDX(end
);
2488 #if defined(DEBUG_SUBPAGE)
2489 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2490 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2492 for (; idx
<= eidx
; idx
++) {
2493 mmio
->sub_section
[idx
] = section
;
2499 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2503 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2504 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2507 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2508 NULL
, TARGET_PAGE_SIZE
);
2509 mmio
->iomem
.subpage
= true;
2510 #if defined(DEBUG_SUBPAGE)
2511 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2512 mmio
, base
, TARGET_PAGE_SIZE
);
2518 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2521 MemoryRegionSection section
= {
2524 .offset_within_address_space
= 0,
2525 .offset_within_region
= 0,
2526 .size
= int128_2_64(),
2529 return phys_section_add(map
, §ion
);
2532 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2533 hwaddr index
, MemTxAttrs attrs
)
2535 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2536 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2537 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2538 MemoryRegionSection
*sections
= d
->map
.sections
;
2540 return §ions
[index
& ~TARGET_PAGE_MASK
];
2543 static void io_mem_init(void)
2545 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2549 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2551 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2554 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2555 assert(n
== PHYS_SECTION_UNASSIGNED
);
2557 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2562 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2564 phys_sections_free(&d
->map
);
2568 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2572 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2574 CPUAddressSpace
*cpuas
;
2576 /* Wait for the CPU to end the current TB. This avoids the following
2580 * ---------------------- -------------------------
2581 * TLB check -> slow path
2582 * notdirty_mem_write
2586 * TLB check -> fast path
2590 * by pushing the migration thread's memory read after the vCPU thread has
2591 * written the memory.
2593 if (replay_mode
== REPLAY_MODE_NONE
) {
2595 * VGA can make calls to this function while updating the screen.
2596 * In record/replay mode this causes a deadlock, because
2597 * run_on_cpu waits for rr mutex. Therefore no races are possible
2598 * in this case and no need for making run_on_cpu when
2599 * record/replay is not enabled.
2601 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2602 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2606 static void tcg_commit(MemoryListener
*listener
)
2608 CPUAddressSpace
*cpuas
;
2609 AddressSpaceDispatch
*d
;
2611 assert(tcg_enabled());
2612 /* since each CPU stores ram addresses in its TLB cache, we must
2613 reset the modified entries */
2614 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2615 cpu_reloading_memory_map();
2616 /* The CPU and TLB are protected by the iothread lock.
2617 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2618 * may have split the RCU critical section.
2620 d
= address_space_to_dispatch(cpuas
->as
);
2621 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2622 tlb_flush(cpuas
->cpu
);
2625 static void memory_map_init(void)
2627 system_memory
= g_malloc(sizeof(*system_memory
));
2629 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2630 address_space_init(&address_space_memory
, system_memory
, "memory");
2632 system_io
= g_malloc(sizeof(*system_io
));
2633 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2635 address_space_init(&address_space_io
, system_io
, "I/O");
2638 MemoryRegion
*get_system_memory(void)
2640 return system_memory
;
2643 MemoryRegion
*get_system_io(void)
2648 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2651 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2652 addr
+= memory_region_get_ram_addr(mr
);
2654 /* No early return if dirty_log_mask is or becomes 0, because
2655 * cpu_physical_memory_set_dirty_range will still call
2656 * xen_modified_memory.
2658 if (dirty_log_mask
) {
2660 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2662 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2663 assert(tcg_enabled());
2664 tb_invalidate_phys_range(addr
, addr
+ length
);
2665 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2667 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2670 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2673 * In principle this function would work on other memory region types too,
2674 * but the ROM device use case is the only one where this operation is
2675 * necessary. Other memory regions should use the
2676 * address_space_read/write() APIs.
2678 assert(memory_region_is_romd(mr
));
2680 invalidate_and_set_dirty(mr
, addr
, size
);
2683 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2685 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2687 /* Regions are assumed to support 1-4 byte accesses unless
2688 otherwise specified. */
2689 if (access_size_max
== 0) {
2690 access_size_max
= 4;
2693 /* Bound the maximum access by the alignment of the address. */
2694 if (!mr
->ops
->impl
.unaligned
) {
2695 unsigned align_size_max
= addr
& -addr
;
2696 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2697 access_size_max
= align_size_max
;
2701 /* Don't attempt accesses larger than the maximum. */
2702 if (l
> access_size_max
) {
2703 l
= access_size_max
;
2710 static bool prepare_mmio_access(MemoryRegion
*mr
)
2712 bool release_lock
= false;
2714 if (!qemu_mutex_iothread_locked()) {
2715 qemu_mutex_lock_iothread();
2716 release_lock
= true;
2718 if (mr
->flush_coalesced_mmio
) {
2719 qemu_flush_coalesced_mmio_buffer();
2722 return release_lock
;
2725 /* Called within RCU critical section. */
2726 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2729 hwaddr len
, hwaddr addr1
,
2730 hwaddr l
, MemoryRegion
*mr
)
2734 MemTxResult result
= MEMTX_OK
;
2735 bool release_lock
= false;
2736 const uint8_t *buf
= ptr
;
2739 if (!memory_access_is_direct(mr
, true)) {
2740 release_lock
|= prepare_mmio_access(mr
);
2741 l
= memory_access_size(mr
, l
, addr1
);
2742 /* XXX: could force current_cpu to NULL to avoid
2744 val
= ldn_he_p(buf
, l
);
2745 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2746 size_memop(l
), attrs
);
2749 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2750 memcpy(ram_ptr
, buf
, l
);
2751 invalidate_and_set_dirty(mr
, addr1
, l
);
2755 qemu_mutex_unlock_iothread();
2756 release_lock
= false;
2768 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2774 /* Called from RCU critical section. */
2775 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2776 const void *buf
, hwaddr len
)
2781 MemTxResult result
= MEMTX_OK
;
2784 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2785 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2791 /* Called within RCU critical section. */
2792 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2793 MemTxAttrs attrs
, void *ptr
,
2794 hwaddr len
, hwaddr addr1
, hwaddr l
,
2799 MemTxResult result
= MEMTX_OK
;
2800 bool release_lock
= false;
2803 fuzz_dma_read_cb(addr
, len
, mr
);
2805 if (!memory_access_is_direct(mr
, false)) {
2807 release_lock
|= prepare_mmio_access(mr
);
2808 l
= memory_access_size(mr
, l
, addr1
);
2809 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2810 size_memop(l
), attrs
);
2811 stn_he_p(buf
, l
, val
);
2814 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2815 memcpy(buf
, ram_ptr
, l
);
2819 qemu_mutex_unlock_iothread();
2820 release_lock
= false;
2832 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2838 /* Called from RCU critical section. */
2839 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2840 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2847 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2848 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2852 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2853 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2855 MemTxResult result
= MEMTX_OK
;
2859 RCU_READ_LOCK_GUARD();
2860 fv
= address_space_to_flatview(as
);
2861 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2867 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2869 const void *buf
, hwaddr len
)
2871 MemTxResult result
= MEMTX_OK
;
2875 RCU_READ_LOCK_GUARD();
2876 fv
= address_space_to_flatview(as
);
2877 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2883 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2884 void *buf
, hwaddr len
, bool is_write
)
2887 return address_space_write(as
, addr
, attrs
, buf
, len
);
2889 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2893 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2894 hwaddr len
, bool is_write
)
2896 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2897 buf
, len
, is_write
);
2900 enum write_rom_type
{
2905 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2910 enum write_rom_type type
)
2916 const uint8_t *buf
= ptr
;
2918 RCU_READ_LOCK_GUARD();
2921 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
2923 if (!(memory_region_is_ram(mr
) ||
2924 memory_region_is_romd(mr
))) {
2925 l
= memory_access_size(mr
, l
, addr1
);
2928 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
2931 memcpy(ram_ptr
, buf
, l
);
2932 invalidate_and_set_dirty(mr
, addr1
, l
);
2935 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
2946 /* used for ROM loading : can write in RAM and ROM */
2947 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
2949 const void *buf
, hwaddr len
)
2951 return address_space_write_rom_internal(as
, addr
, attrs
,
2952 buf
, len
, WRITE_DATA
);
2955 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
2958 * This function should do the same thing as an icache flush that was
2959 * triggered from within the guest. For TCG we are always cache coherent,
2960 * so there is no need to flush anything. For KVM / Xen we need to flush
2961 * the host's instruction cache at least.
2963 if (tcg_enabled()) {
2967 address_space_write_rom_internal(&address_space_memory
,
2968 start
, MEMTXATTRS_UNSPECIFIED
,
2969 NULL
, len
, FLUSH_CACHE
);
2980 static BounceBuffer bounce
;
2982 typedef struct MapClient
{
2984 QLIST_ENTRY(MapClient
) link
;
2987 QemuMutex map_client_list_lock
;
2988 static QLIST_HEAD(, MapClient
) map_client_list
2989 = QLIST_HEAD_INITIALIZER(map_client_list
);
2991 static void cpu_unregister_map_client_do(MapClient
*client
)
2993 QLIST_REMOVE(client
, link
);
2997 static void cpu_notify_map_clients_locked(void)
3001 while (!QLIST_EMPTY(&map_client_list
)) {
3002 client
= QLIST_FIRST(&map_client_list
);
3003 qemu_bh_schedule(client
->bh
);
3004 cpu_unregister_map_client_do(client
);
3008 void cpu_register_map_client(QEMUBH
*bh
)
3010 MapClient
*client
= g_malloc(sizeof(*client
));
3012 qemu_mutex_lock(&map_client_list_lock
);
3014 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3015 if (!qatomic_read(&bounce
.in_use
)) {
3016 cpu_notify_map_clients_locked();
3018 qemu_mutex_unlock(&map_client_list_lock
);
3021 void cpu_exec_init_all(void)
3023 qemu_mutex_init(&ram_list
.mutex
);
3024 /* The data structures we set up here depend on knowing the page size,
3025 * so no more changes can be made after this point.
3026 * In an ideal world, nothing we did before we had finished the
3027 * machine setup would care about the target page size, and we could
3028 * do this much later, rather than requiring board models to state
3029 * up front what their requirements are.
3031 finalize_target_page_bits();
3034 qemu_mutex_init(&map_client_list_lock
);
3037 void cpu_unregister_map_client(QEMUBH
*bh
)
3041 qemu_mutex_lock(&map_client_list_lock
);
3042 QLIST_FOREACH(client
, &map_client_list
, link
) {
3043 if (client
->bh
== bh
) {
3044 cpu_unregister_map_client_do(client
);
3048 qemu_mutex_unlock(&map_client_list_lock
);
3051 static void cpu_notify_map_clients(void)
3053 qemu_mutex_lock(&map_client_list_lock
);
3054 cpu_notify_map_clients_locked();
3055 qemu_mutex_unlock(&map_client_list_lock
);
3058 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3059 bool is_write
, MemTxAttrs attrs
)
3066 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3067 if (!memory_access_is_direct(mr
, is_write
)) {
3068 l
= memory_access_size(mr
, l
, addr
);
3069 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3080 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3081 hwaddr len
, bool is_write
,
3087 RCU_READ_LOCK_GUARD();
3088 fv
= address_space_to_flatview(as
);
3089 result
= flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3094 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3096 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3097 bool is_write
, MemTxAttrs attrs
)
3101 MemoryRegion
*this_mr
;
3107 if (target_len
== 0) {
3112 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3113 &len
, is_write
, attrs
);
3114 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3120 /* Map a physical memory region into a host virtual address.
3121 * May map a subset of the requested range, given by and returned in *plen.
3122 * May return NULL if resources needed to perform the mapping are exhausted.
3123 * Use only for reads OR writes - not for read-modify-write operations.
3124 * Use cpu_register_map_client() to know when retrying the map operation is
3125 * likely to succeed.
3127 void *address_space_map(AddressSpace
*as
,
3144 RCU_READ_LOCK_GUARD();
3145 fv
= address_space_to_flatview(as
);
3146 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3148 if (!memory_access_is_direct(mr
, is_write
)) {
3149 if (qatomic_xchg(&bounce
.in_use
, true)) {
3153 /* Avoid unbounded allocations */
3154 l
= MIN(l
, TARGET_PAGE_SIZE
);
3155 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3159 memory_region_ref(mr
);
3162 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3167 return bounce
.buffer
;
3171 memory_region_ref(mr
);
3172 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3173 l
, is_write
, attrs
);
3174 fuzz_dma_read_cb(addr
, *plen
, mr
);
3175 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3180 /* Unmaps a memory region previously mapped by address_space_map().
3181 * Will also mark the memory as dirty if is_write is true. access_len gives
3182 * the amount of memory that was actually read or written by the caller.
3184 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3185 bool is_write
, hwaddr access_len
)
3187 if (buffer
!= bounce
.buffer
) {
3191 mr
= memory_region_from_host(buffer
, &addr1
);
3194 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3196 if (xen_enabled()) {
3197 xen_invalidate_map_cache_entry(buffer
);
3199 memory_region_unref(mr
);
3203 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3204 bounce
.buffer
, access_len
);
3206 qemu_vfree(bounce
.buffer
);
3207 bounce
.buffer
= NULL
;
3208 memory_region_unref(bounce
.mr
);
3209 qatomic_mb_set(&bounce
.in_use
, false);
3210 cpu_notify_map_clients();
3213 void *cpu_physical_memory_map(hwaddr addr
,
3217 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3218 MEMTXATTRS_UNSPECIFIED
);
3221 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3222 bool is_write
, hwaddr access_len
)
3224 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3227 #define ARG1_DECL AddressSpace *as
3230 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3231 #define RCU_READ_LOCK(...) rcu_read_lock()
3232 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3233 #include "memory_ldst.c.inc"
3235 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3241 AddressSpaceDispatch
*d
;
3249 cache
->fv
= address_space_get_flatview(as
);
3250 d
= flatview_to_dispatch(cache
->fv
);
3251 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3254 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3255 * Take that into account to compute how many bytes are there between
3256 * cache->xlat and the end of the section.
3258 diff
= int128_sub(cache
->mrs
.size
,
3259 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3260 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3263 memory_region_ref(mr
);
3264 if (memory_access_is_direct(mr
, is_write
)) {
3265 /* We don't care about the memory attributes here as we're only
3266 * doing this if we found actual RAM, which behaves the same
3267 * regardless of attributes; so UNSPECIFIED is fine.
3269 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3270 cache
->xlat
, l
, is_write
,
3271 MEMTXATTRS_UNSPECIFIED
);
3272 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3278 cache
->is_write
= is_write
;
3282 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3286 assert(cache
->is_write
);
3287 if (likely(cache
->ptr
)) {
3288 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3292 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3294 if (!cache
->mrs
.mr
) {
3298 if (xen_enabled()) {
3299 xen_invalidate_map_cache_entry(cache
->ptr
);
3301 memory_region_unref(cache
->mrs
.mr
);
3302 flatview_unref(cache
->fv
);
3303 cache
->mrs
.mr
= NULL
;
3307 /* Called from RCU critical section. This function has the same
3308 * semantics as address_space_translate, but it only works on a
3309 * predefined range of a MemoryRegion that was mapped with
3310 * address_space_cache_init.
3312 static inline MemoryRegion
*address_space_translate_cached(
3313 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3314 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3316 MemoryRegionSection section
;
3318 IOMMUMemoryRegion
*iommu_mr
;
3319 AddressSpace
*target_as
;
3321 assert(!cache
->ptr
);
3322 *xlat
= addr
+ cache
->xlat
;
3325 iommu_mr
= memory_region_get_iommu(mr
);
3331 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3332 NULL
, is_write
, true,
3337 /* Called from RCU critical section. address_space_read_cached uses this
3338 * out of line function when the target is an MMIO or IOMMU region.
3341 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3342 void *buf
, hwaddr len
)
3348 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3349 MEMTXATTRS_UNSPECIFIED
);
3350 return flatview_read_continue(cache
->fv
,
3351 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3355 /* Called from RCU critical section. address_space_write_cached uses this
3356 * out of line function when the target is an MMIO or IOMMU region.
3359 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3360 const void *buf
, hwaddr len
)
3366 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3367 MEMTXATTRS_UNSPECIFIED
);
3368 return flatview_write_continue(cache
->fv
,
3369 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3373 #define ARG1_DECL MemoryRegionCache *cache
3375 #define SUFFIX _cached_slow
3376 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3377 #define RCU_READ_LOCK() ((void)0)
3378 #define RCU_READ_UNLOCK() ((void)0)
3379 #include "memory_ldst.c.inc"
3381 /* virtual memory access for debug (includes writing to ROM) */
3382 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3383 void *ptr
, target_ulong len
, bool is_write
)
3386 target_ulong l
, page
;
3389 cpu_synchronize_state(cpu
);
3395 page
= addr
& TARGET_PAGE_MASK
;
3396 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3397 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3398 /* if no physical page mapped, return an error */
3399 if (phys_addr
== -1)
3401 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3404 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3406 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3409 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3412 if (res
!= MEMTX_OK
) {
3423 * Allows code that needs to deal with migration bitmaps etc to still be built
3424 * target independent.
3426 size_t qemu_target_page_size(void)
3428 return TARGET_PAGE_SIZE
;
3431 int qemu_target_page_bits(void)
3433 return TARGET_PAGE_BITS
;
3436 int qemu_target_page_bits_min(void)
3438 return TARGET_PAGE_BITS_MIN
;
3441 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3447 RCU_READ_LOCK_GUARD();
3448 mr
= address_space_translate(&address_space_memory
,
3449 phys_addr
, &phys_addr
, &l
, false,
3450 MEMTXATTRS_UNSPECIFIED
);
3452 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3456 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3461 RCU_READ_LOCK_GUARD();
3462 RAMBLOCK_FOREACH(block
) {
3463 ret
= func(block
, opaque
);
3472 * Unmap pages of memory from start to start+length such that
3473 * they a) read as 0, b) Trigger whatever fault mechanism
3474 * the OS provides for postcopy.
3475 * The pages must be unmapped by the end of the function.
3476 * Returns: 0 on success, none-0 on failure
3479 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3483 uint8_t *host_startaddr
= rb
->host
+ start
;
3485 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3486 error_report("ram_block_discard_range: Unaligned start address: %p",
3491 if ((start
+ length
) <= rb
->used_length
) {
3492 bool need_madvise
, need_fallocate
;
3493 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3494 error_report("ram_block_discard_range: Unaligned length: %zx",
3499 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3501 /* The logic here is messy;
3502 * madvise DONTNEED fails for hugepages
3503 * fallocate works on hugepages and shmem
3505 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3506 need_fallocate
= rb
->fd
!= -1;
3507 if (need_fallocate
) {
3508 /* For a file, this causes the area of the file to be zero'd
3509 * if read, and for hugetlbfs also causes it to be unmapped
3510 * so a userfault will trigger.
3512 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3513 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3517 error_report("ram_block_discard_range: Failed to fallocate "
3518 "%s:%" PRIx64
" +%zx (%d)",
3519 rb
->idstr
, start
, length
, ret
);
3524 error_report("ram_block_discard_range: fallocate not available/file"
3525 "%s:%" PRIx64
" +%zx (%d)",
3526 rb
->idstr
, start
, length
, ret
);
3531 /* For normal RAM this causes it to be unmapped,
3532 * for shared memory it causes the local mapping to disappear
3533 * and to fall back on the file contents (which we just
3534 * fallocate'd away).
3536 #if defined(CONFIG_MADVISE)
3537 ret
= madvise(host_startaddr
, length
, MADV_DONTNEED
);
3540 error_report("ram_block_discard_range: Failed to discard range "
3541 "%s:%" PRIx64
" +%zx (%d)",
3542 rb
->idstr
, start
, length
, ret
);
3547 error_report("ram_block_discard_range: MADVISE not available"
3548 "%s:%" PRIx64
" +%zx (%d)",
3549 rb
->idstr
, start
, length
, ret
);
3553 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3554 need_madvise
, need_fallocate
, ret
);
3556 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3557 "/%zx/" RAM_ADDR_FMT
")",
3558 rb
->idstr
, start
, length
, rb
->used_length
);
3565 bool ramblock_is_pmem(RAMBlock
*rb
)
3567 return rb
->flags
& RAM_PMEM
;
3570 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3572 if (start
== end
- 1) {
3573 qemu_printf("\t%3d ", start
);
3575 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3577 qemu_printf(" skip=%d ", skip
);
3578 if (ptr
== PHYS_MAP_NODE_NIL
) {
3579 qemu_printf(" ptr=NIL");
3581 qemu_printf(" ptr=#%d", ptr
);
3583 qemu_printf(" ptr=[%d]", ptr
);
3588 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3589 int128_sub((size), int128_one())) : 0)
3591 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3595 qemu_printf(" Dispatch\n");
3596 qemu_printf(" Physical sections\n");
3598 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3599 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3600 const char *names
[] = { " [unassigned]", " [not dirty]",
3601 " [ROM]", " [watch]" };
3603 qemu_printf(" #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
3606 s
->offset_within_address_space
,
3607 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
3608 s
->mr
->name
? s
->mr
->name
: "(noname)",
3609 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3610 s
->mr
== root
? " [ROOT]" : "",
3611 s
== d
->mru_section
? " [MRU]" : "",
3612 s
->mr
->is_iommu
? " [iommu]" : "");
3615 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3616 s
->mr
->alias
->name
: "noname");
3621 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3622 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3623 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3626 Node
*n
= d
->map
.nodes
+ i
;
3628 qemu_printf(" [%d]\n", i
);
3630 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3631 PhysPageEntry
*pe
= *n
+ j
;
3633 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3637 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3643 if (jprev
!= ARRAY_SIZE(*n
)) {
3644 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3650 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3651 * required to work and cannot be disabled.
3653 static int ram_block_discard_disabled
;
3655 int ram_block_discard_disable(bool state
)
3660 qatomic_dec(&ram_block_discard_disabled
);
3665 old
= qatomic_read(&ram_block_discard_disabled
);
3669 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
3670 old
, old
+ 1) != old
);
3674 int ram_block_discard_require(bool state
)
3679 qatomic_inc(&ram_block_discard_disabled
);
3684 old
= qatomic_read(&ram_block_discard_disabled
);
3688 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
3689 old
, old
- 1) != old
);
3693 bool ram_block_discard_is_disabled(void)
3695 return qatomic_read(&ram_block_discard_disabled
) > 0;
3698 bool ram_block_discard_is_required(void)
3700 return qatomic_read(&ram_block_discard_disabled
) < 0;