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 "exec/page-vary.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
26 #include "qemu/hbitmap.h"
27 #include "qemu/madvise.h"
28 #include "qemu/lockable.h"
31 #include "hw/core/tcg-cpu-ops.h"
32 #endif /* CONFIG_TCG */
34 #include "exec/exec-all.h"
35 #include "exec/page-protection.h"
36 #include "exec/target_page.h"
37 #include "hw/qdev-core.h"
38 #include "hw/qdev-properties.h"
39 #include "hw/boards.h"
40 #include "sysemu/xen.h"
41 #include "sysemu/kvm.h"
42 #include "sysemu/tcg.h"
43 #include "sysemu/qtest.h"
44 #include "qemu/timer.h"
45 #include "qemu/config-file.h"
46 #include "qemu/error-report.h"
47 #include "qemu/qemu-print.h"
49 #include "qemu/memalign.h"
50 #include "exec/memory.h"
51 #include "exec/ioport.h"
52 #include "sysemu/dma.h"
53 #include "sysemu/hostmem.h"
54 #include "sysemu/hw_accel.h"
55 #include "sysemu/xen-mapcache.h"
58 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
59 #include <linux/falloc.h>
62 #include "qemu/rcu_queue.h"
63 #include "qemu/main-loop.h"
64 #include "exec/translate-all.h"
65 #include "sysemu/replay.h"
67 #include "exec/memory-internal.h"
68 #include "exec/ram_addr.h"
70 #include "qemu/pmem.h"
72 #include "migration/vmstate.h"
74 #include "qemu/range.h"
76 #include "qemu/mmap-alloc.h"
79 #include "monitor/monitor.h"
81 #ifdef CONFIG_LIBDAXCTL
82 #include <daxctl/libdaxctl.h>
85 //#define DEBUG_SUBPAGE
87 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
88 * are protected by the ramlist lock.
90 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
92 static MemoryRegion
*system_memory
;
93 static MemoryRegion
*system_io
;
95 AddressSpace address_space_io
;
96 AddressSpace address_space_memory
;
98 static MemoryRegion io_mem_unassigned
;
100 typedef struct PhysPageEntry PhysPageEntry
;
102 struct PhysPageEntry
{
103 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
105 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
109 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
111 /* Size of the L2 (and L3, etc) page tables. */
112 #define ADDR_SPACE_BITS 64
115 #define P_L2_SIZE (1 << P_L2_BITS)
117 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
119 typedef PhysPageEntry Node
[P_L2_SIZE
];
121 typedef struct PhysPageMap
{
124 unsigned sections_nb
;
125 unsigned sections_nb_alloc
;
127 unsigned nodes_nb_alloc
;
129 MemoryRegionSection
*sections
;
132 struct AddressSpaceDispatch
{
133 MemoryRegionSection
*mru_section
;
134 /* This is a multi-level map on the physical address space.
135 * The bottom level has pointers to MemoryRegionSections.
137 PhysPageEntry phys_map
;
141 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
142 typedef struct subpage_t
{
146 uint16_t sub_section
[];
149 #define PHYS_SECTION_UNASSIGNED 0
151 static void io_mem_init(void);
152 static void memory_map_init(void);
153 static void tcg_log_global_after_sync(MemoryListener
*listener
);
154 static void tcg_commit(MemoryListener
*listener
);
157 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
158 * @cpu: the CPU whose AddressSpace this is
159 * @as: the AddressSpace itself
160 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
161 * @tcg_as_listener: listener for tracking changes to the AddressSpace
163 typedef struct CPUAddressSpace
{
166 struct AddressSpaceDispatch
*memory_dispatch
;
167 MemoryListener tcg_as_listener
;
170 struct DirtyBitmapSnapshot
{
173 unsigned long dirty
[];
176 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
178 static unsigned alloc_hint
= 16;
179 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
180 map
->nodes_nb_alloc
= MAX(alloc_hint
, map
->nodes_nb
+ nodes
);
181 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
182 alloc_hint
= map
->nodes_nb_alloc
;
186 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
193 ret
= map
->nodes_nb
++;
195 assert(ret
!= PHYS_MAP_NODE_NIL
);
196 assert(ret
!= map
->nodes_nb_alloc
);
198 e
.skip
= leaf
? 0 : 1;
199 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
200 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
201 memcpy(&p
[i
], &e
, sizeof(e
));
206 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
207 hwaddr
*index
, uint64_t *nb
, uint16_t leaf
,
211 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
213 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
214 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
216 p
= map
->nodes
[lp
->ptr
];
217 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
219 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
220 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
226 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
232 static void phys_page_set(AddressSpaceDispatch
*d
,
233 hwaddr index
, uint64_t nb
,
236 /* Wildly overreserve - it doesn't matter much. */
237 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
239 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
242 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
243 * and update our entry so we can skip it and go directly to the destination.
245 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
247 unsigned valid_ptr
= P_L2_SIZE
;
252 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
257 for (i
= 0; i
< P_L2_SIZE
; i
++) {
258 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
265 phys_page_compact(&p
[i
], nodes
);
269 /* We can only compress if there's only one child. */
274 assert(valid_ptr
< P_L2_SIZE
);
276 /* Don't compress if it won't fit in the # of bits we have. */
277 if (P_L2_LEVELS
>= (1 << 6) &&
278 lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 6)) {
282 lp
->ptr
= p
[valid_ptr
].ptr
;
283 if (!p
[valid_ptr
].skip
) {
284 /* If our only child is a leaf, make this a leaf. */
285 /* By design, we should have made this node a leaf to begin with so we
286 * should never reach here.
287 * But since it's so simple to handle this, let's do it just in case we
292 lp
->skip
+= p
[valid_ptr
].skip
;
296 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
298 if (d
->phys_map
.skip
) {
299 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
303 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
306 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
307 * the section must cover the entire address space.
309 return int128_gethi(section
->size
) ||
310 range_covers_byte(section
->offset_within_address_space
,
311 int128_getlo(section
->size
), addr
);
314 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
316 PhysPageEntry lp
= d
->phys_map
, *p
;
317 Node
*nodes
= d
->map
.nodes
;
318 MemoryRegionSection
*sections
= d
->map
.sections
;
319 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
322 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
323 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
324 return §ions
[PHYS_SECTION_UNASSIGNED
];
327 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
330 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
331 return §ions
[lp
.ptr
];
333 return §ions
[PHYS_SECTION_UNASSIGNED
];
337 /* Called from RCU critical section */
338 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
340 bool resolve_subpage
)
342 MemoryRegionSection
*section
= qatomic_read(&d
->mru_section
);
345 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
346 !section_covers_addr(section
, addr
)) {
347 section
= phys_page_find(d
, addr
);
348 qatomic_set(&d
->mru_section
, section
);
350 if (resolve_subpage
&& section
->mr
->subpage
) {
351 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
352 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
357 /* Called from RCU critical section */
358 static MemoryRegionSection
*
359 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
360 hwaddr
*plen
, bool resolve_subpage
)
362 MemoryRegionSection
*section
;
366 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
367 /* Compute offset within MemoryRegionSection */
368 addr
-= section
->offset_within_address_space
;
370 /* Compute offset within MemoryRegion */
371 *xlat
= addr
+ section
->offset_within_region
;
375 /* MMIO registers can be expected to perform full-width accesses based only
376 * on their address, without considering adjacent registers that could
377 * decode to completely different MemoryRegions. When such registers
378 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
379 * regions overlap wildly. For this reason we cannot clamp the accesses
382 * If the length is small (as is the case for address_space_ldl/stl),
383 * everything works fine. If the incoming length is large, however,
384 * the caller really has to do the clamping through memory_access_size.
386 if (memory_region_is_ram(mr
)) {
387 diff
= int128_sub(section
->size
, int128_make64(addr
));
388 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
394 * address_space_translate_iommu - translate an address through an IOMMU
395 * memory region and then through the target address space.
397 * @iommu_mr: the IOMMU memory region that we start the translation from
398 * @addr: the address to be translated through the MMU
399 * @xlat: the translated address offset within the destination memory region.
400 * It cannot be %NULL.
401 * @plen_out: valid read/write length of the translated address. It
403 * @page_mask_out: page mask for the translated address. This
404 * should only be meaningful for IOMMU translated
405 * addresses, since there may be huge pages that this bit
406 * would tell. It can be %NULL if we don't care about it.
407 * @is_write: whether the translation operation is for write
408 * @is_mmio: whether this can be MMIO, set true if it can
409 * @target_as: the address space targeted by the IOMMU
410 * @attrs: transaction attributes
412 * This function is called from RCU critical section. It is the common
413 * part of flatview_do_translate and address_space_translate_cached.
415 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
418 hwaddr
*page_mask_out
,
421 AddressSpace
**target_as
,
424 MemoryRegionSection
*section
;
425 hwaddr page_mask
= (hwaddr
)-1;
429 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
433 if (imrc
->attrs_to_index
) {
434 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
437 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
438 IOMMU_WO
: IOMMU_RO
, iommu_idx
);
440 if (!(iotlb
.perm
& (1 << is_write
))) {
444 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
445 | (addr
& iotlb
.addr_mask
));
446 page_mask
&= iotlb
.addr_mask
;
447 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
448 *target_as
= iotlb
.target_as
;
450 section
= address_space_translate_internal(
451 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
454 iommu_mr
= memory_region_get_iommu(section
->mr
);
455 } while (unlikely(iommu_mr
));
458 *page_mask_out
= page_mask
;
463 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
467 * flatview_do_translate - translate an address in FlatView
469 * @fv: the flat view that we want to translate on
470 * @addr: the address to be translated in above address space
471 * @xlat: the translated address offset within memory region. It
473 * @plen_out: valid read/write length of the translated address. It
474 * can be @NULL when we don't care about it.
475 * @page_mask_out: page mask for the translated address. This
476 * should only be meaningful for IOMMU translated
477 * addresses, since there may be huge pages that this bit
478 * would tell. It can be @NULL if we don't care about it.
479 * @is_write: whether the translation operation is for write
480 * @is_mmio: whether this can be MMIO, set true if it can
481 * @target_as: the address space targeted by the IOMMU
482 * @attrs: memory transaction attributes
484 * This function is called from RCU critical section
486 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
490 hwaddr
*page_mask_out
,
493 AddressSpace
**target_as
,
496 MemoryRegionSection
*section
;
497 IOMMUMemoryRegion
*iommu_mr
;
498 hwaddr plen
= (hwaddr
)(-1);
504 section
= address_space_translate_internal(
505 flatview_to_dispatch(fv
), addr
, xlat
,
508 iommu_mr
= memory_region_get_iommu(section
->mr
);
509 if (unlikely(iommu_mr
)) {
510 return address_space_translate_iommu(iommu_mr
, xlat
,
511 plen_out
, page_mask_out
,
516 /* Not behind an IOMMU, use default page size. */
517 *page_mask_out
= ~TARGET_PAGE_MASK
;
523 /* Called from RCU critical section */
524 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
525 bool is_write
, MemTxAttrs attrs
)
527 MemoryRegionSection section
;
528 hwaddr xlat
, page_mask
;
531 * This can never be MMIO, and we don't really care about plen,
534 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
535 NULL
, &page_mask
, is_write
, false, &as
,
538 /* Illegal translation */
539 if (section
.mr
== &io_mem_unassigned
) {
543 /* Convert memory region offset into address space offset */
544 xlat
+= section
.offset_within_address_space
-
545 section
.offset_within_region
;
547 return (IOMMUTLBEntry
) {
549 .iova
= addr
& ~page_mask
,
550 .translated_addr
= xlat
& ~page_mask
,
551 .addr_mask
= page_mask
,
552 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
557 return (IOMMUTLBEntry
) {0};
560 /* Called from RCU critical section */
561 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
562 hwaddr
*plen
, bool is_write
,
566 MemoryRegionSection section
;
567 AddressSpace
*as
= NULL
;
569 /* This can be MMIO, so setup MMIO bit. */
570 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
571 is_write
, true, &as
, attrs
);
574 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
575 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
576 *plen
= MIN(page
, *plen
);
582 typedef struct TCGIOMMUNotifier
{
590 static void tcg_iommu_unmap_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
592 TCGIOMMUNotifier
*notifier
= container_of(n
, TCGIOMMUNotifier
, n
);
594 if (!notifier
->active
) {
597 tlb_flush(notifier
->cpu
);
598 notifier
->active
= false;
599 /* We leave the notifier struct on the list to avoid reallocating it later.
600 * Generally the number of IOMMUs a CPU deals with will be small.
601 * In any case we can't unregister the iommu notifier from a notify
606 static void tcg_register_iommu_notifier(CPUState
*cpu
,
607 IOMMUMemoryRegion
*iommu_mr
,
610 /* Make sure this CPU has an IOMMU notifier registered for this
611 * IOMMU/IOMMU index combination, so that we can flush its TLB
612 * when the IOMMU tells us the mappings we've cached have changed.
614 MemoryRegion
*mr
= MEMORY_REGION(iommu_mr
);
615 TCGIOMMUNotifier
*notifier
= NULL
;
618 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
619 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
620 if (notifier
->mr
== mr
&& notifier
->iommu_idx
== iommu_idx
) {
624 if (i
== cpu
->iommu_notifiers
->len
) {
625 /* Not found, add a new entry at the end of the array */
626 cpu
->iommu_notifiers
= g_array_set_size(cpu
->iommu_notifiers
, i
+ 1);
627 notifier
= g_new0(TCGIOMMUNotifier
, 1);
628 g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
) = notifier
;
631 notifier
->iommu_idx
= iommu_idx
;
633 /* Rather than trying to register interest in the specific part
634 * of the iommu's address space that we've accessed and then
635 * expand it later as subsequent accesses touch more of it, we
636 * just register interest in the whole thing, on the assumption
637 * that iommu reconfiguration will be rare.
639 iommu_notifier_init(¬ifier
->n
,
640 tcg_iommu_unmap_notify
,
641 IOMMU_NOTIFIER_UNMAP
,
645 memory_region_register_iommu_notifier(notifier
->mr
, ¬ifier
->n
,
649 if (!notifier
->active
) {
650 notifier
->active
= true;
654 void tcg_iommu_free_notifier_list(CPUState
*cpu
)
656 /* Destroy the CPU's notifier list */
658 TCGIOMMUNotifier
*notifier
;
660 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
661 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
662 memory_region_unregister_iommu_notifier(notifier
->mr
, ¬ifier
->n
);
665 g_array_free(cpu
->iommu_notifiers
, true);
668 void tcg_iommu_init_notifier_list(CPUState
*cpu
)
670 cpu
->iommu_notifiers
= g_array_new(false, true, sizeof(TCGIOMMUNotifier
*));
673 /* Called from RCU critical section */
674 MemoryRegionSection
*
675 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr orig_addr
,
676 hwaddr
*xlat
, hwaddr
*plen
,
677 MemTxAttrs attrs
, int *prot
)
679 MemoryRegionSection
*section
;
680 IOMMUMemoryRegion
*iommu_mr
;
681 IOMMUMemoryRegionClass
*imrc
;
684 hwaddr addr
= orig_addr
;
685 AddressSpaceDispatch
*d
= cpu
->cpu_ases
[asidx
].memory_dispatch
;
688 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
690 iommu_mr
= memory_region_get_iommu(section
->mr
);
695 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
697 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
698 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
699 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
700 * doesn't short-cut its translation table walk.
702 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
703 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
704 | (addr
& iotlb
.addr_mask
));
705 /* Update the caller's prot bits to remove permissions the IOMMU
706 * is giving us a failure response for. If we get down to no
707 * permissions left at all we can give up now.
709 if (!(iotlb
.perm
& IOMMU_RO
)) {
710 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
712 if (!(iotlb
.perm
& IOMMU_WO
)) {
713 *prot
&= ~PAGE_WRITE
;
720 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
723 assert(!memory_region_is_iommu(section
->mr
));
729 * We should be given a page-aligned address -- certainly
730 * tlb_set_page_with_attrs() does so. The page offset of xlat
731 * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.
732 * The page portion of xlat will be logged by memory_region_access_valid()
733 * when this memory access is rejected, so use the original untranslated
736 assert((orig_addr
& ~TARGET_PAGE_MASK
) == 0);
738 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
741 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
742 const char *prefix
, MemoryRegion
*mr
)
744 CPUAddressSpace
*newas
;
745 AddressSpace
*as
= g_new0(AddressSpace
, 1);
749 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
750 address_space_init(as
, mr
, as_name
);
753 /* Target code should have set num_ases before calling us */
754 assert(asidx
< cpu
->num_ases
);
757 /* address space 0 gets the convenience alias */
761 /* KVM cannot currently support multiple address spaces. */
762 assert(asidx
== 0 || !kvm_enabled());
764 if (!cpu
->cpu_ases
) {
765 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
768 newas
= &cpu
->cpu_ases
[asidx
];
772 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
773 newas
->tcg_as_listener
.commit
= tcg_commit
;
774 newas
->tcg_as_listener
.name
= "tcg";
775 memory_listener_register(&newas
->tcg_as_listener
, as
);
779 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
781 /* Return the AddressSpace corresponding to the specified index */
782 return cpu
->cpu_ases
[asidx
].as
;
785 /* Called from RCU critical section */
786 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
790 block
= qatomic_rcu_read(&ram_list
.mru_block
);
791 if (block
&& addr
- block
->offset
< block
->max_length
) {
794 RAMBLOCK_FOREACH(block
) {
795 if (addr
- block
->offset
< block
->max_length
) {
800 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
804 /* It is safe to write mru_block outside the BQL. This
809 * xxx removed from list
813 * call_rcu(reclaim_ramblock, xxx);
816 * qatomic_rcu_set is not needed here. The block was already published
817 * when it was placed into the list. Here we're just making an extra
818 * copy of the pointer.
820 ram_list
.mru_block
= block
;
824 void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
831 assert(tcg_enabled());
832 end
= TARGET_PAGE_ALIGN(start
+ length
);
833 start
&= TARGET_PAGE_MASK
;
835 RCU_READ_LOCK_GUARD();
836 block
= qemu_get_ram_block(start
);
837 assert(block
== qemu_get_ram_block(end
- 1));
838 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
840 tlb_reset_dirty(cpu
, start1
, length
);
844 /* Note: start and end must be within the same ram block. */
845 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
849 DirtyMemoryBlocks
*blocks
;
850 unsigned long end
, page
, start_page
;
853 uint64_t mr_offset
, mr_size
;
859 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
860 start_page
= start
>> TARGET_PAGE_BITS
;
863 WITH_RCU_READ_LOCK_GUARD() {
864 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
865 ramblock
= qemu_get_ram_block(start
);
866 /* Range sanity check on the ramblock */
867 assert(start
>= ramblock
->offset
&&
868 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
871 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
872 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
873 unsigned long num
= MIN(end
- page
,
874 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
876 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
881 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
882 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
883 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
887 cpu_physical_memory_dirty_bits_cleared(start
, length
);
893 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
894 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
896 DirtyMemoryBlocks
*blocks
;
897 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
898 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
899 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
900 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
901 DirtyBitmapSnapshot
*snap
;
902 unsigned long page
, end
, dest
;
904 snap
= g_malloc0(sizeof(*snap
) +
905 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
909 page
= first
>> TARGET_PAGE_BITS
;
910 end
= last
>> TARGET_PAGE_BITS
;
913 WITH_RCU_READ_LOCK_GUARD() {
914 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
917 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
918 unsigned long ofs
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
919 unsigned long num
= MIN(end
- page
,
920 DIRTY_MEMORY_BLOCK_SIZE
- ofs
);
922 assert(QEMU_IS_ALIGNED(ofs
, (1 << BITS_PER_LEVEL
)));
923 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
924 ofs
>>= BITS_PER_LEVEL
;
926 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
927 blocks
->blocks
[idx
] + ofs
,
930 dest
+= num
>> BITS_PER_LEVEL
;
934 cpu_physical_memory_dirty_bits_cleared(start
, length
);
936 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
941 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
945 unsigned long page
, end
;
947 assert(start
>= snap
->start
);
948 assert(start
+ length
<= snap
->end
);
950 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
951 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
954 if (test_bit(page
, snap
->dirty
)) {
962 /* Called from RCU critical section */
963 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
964 MemoryRegionSection
*section
)
966 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
967 return section
- d
->map
.sections
;
970 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
972 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
974 static uint16_t phys_section_add(PhysPageMap
*map
,
975 MemoryRegionSection
*section
)
977 /* The physical section number is ORed with a page-aligned
978 * pointer to produce the iotlb entries. Thus it should
979 * never overflow into the page-aligned value.
981 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
983 if (map
->sections_nb
== map
->sections_nb_alloc
) {
984 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
985 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
986 map
->sections_nb_alloc
);
988 map
->sections
[map
->sections_nb
] = *section
;
989 memory_region_ref(section
->mr
);
990 return map
->sections_nb
++;
993 static void phys_section_destroy(MemoryRegion
*mr
)
995 bool have_sub_page
= mr
->subpage
;
997 memory_region_unref(mr
);
1000 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1001 object_unref(OBJECT(&subpage
->iomem
));
1006 static void phys_sections_free(PhysPageMap
*map
)
1008 while (map
->sections_nb
> 0) {
1009 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1010 phys_section_destroy(section
->mr
);
1012 g_free(map
->sections
);
1016 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1018 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1020 hwaddr base
= section
->offset_within_address_space
1022 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1023 MemoryRegionSection subsection
= {
1024 .offset_within_address_space
= base
,
1025 .size
= int128_make64(TARGET_PAGE_SIZE
),
1029 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1031 if (!(existing
->mr
->subpage
)) {
1032 subpage
= subpage_init(fv
, base
);
1034 subsection
.mr
= &subpage
->iomem
;
1035 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1036 phys_section_add(&d
->map
, &subsection
));
1038 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1040 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1041 end
= start
+ int128_get64(section
->size
) - 1;
1042 subpage_register(subpage
, start
, end
,
1043 phys_section_add(&d
->map
, section
));
1047 static void register_multipage(FlatView
*fv
,
1048 MemoryRegionSection
*section
)
1050 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1051 hwaddr start_addr
= section
->offset_within_address_space
;
1052 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1053 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1057 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1061 * The range in *section* may look like this:
1065 * where s stands for subpage and P for page.
1067 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1069 MemoryRegionSection remain
= *section
;
1070 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1072 /* register first subpage */
1073 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1074 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1075 - remain
.offset_within_address_space
;
1077 MemoryRegionSection now
= remain
;
1078 now
.size
= int128_min(int128_make64(left
), now
.size
);
1079 register_subpage(fv
, &now
);
1080 if (int128_eq(remain
.size
, now
.size
)) {
1083 remain
.size
= int128_sub(remain
.size
, now
.size
);
1084 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1085 remain
.offset_within_region
+= int128_get64(now
.size
);
1088 /* register whole pages */
1089 if (int128_ge(remain
.size
, page_size
)) {
1090 MemoryRegionSection now
= remain
;
1091 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1092 register_multipage(fv
, &now
);
1093 if (int128_eq(remain
.size
, now
.size
)) {
1096 remain
.size
= int128_sub(remain
.size
, now
.size
);
1097 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1098 remain
.offset_within_region
+= int128_get64(now
.size
);
1101 /* register last subpage */
1102 register_subpage(fv
, &remain
);
1105 void qemu_flush_coalesced_mmio_buffer(void)
1108 kvm_flush_coalesced_mmio_buffer();
1111 void qemu_mutex_lock_ramlist(void)
1113 qemu_mutex_lock(&ram_list
.mutex
);
1116 void qemu_mutex_unlock_ramlist(void)
1118 qemu_mutex_unlock(&ram_list
.mutex
);
1121 GString
*ram_block_format(void)
1125 GString
*buf
= g_string_new("");
1127 RCU_READ_LOCK_GUARD();
1128 g_string_append_printf(buf
, "%24s %8s %18s %18s %18s %18s %3s\n",
1129 "Block Name", "PSize", "Offset", "Used", "Total",
1132 RAMBLOCK_FOREACH(block
) {
1133 psize
= size_to_str(block
->page_size
);
1134 g_string_append_printf(buf
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1135 " 0x%016" PRIx64
" 0x%016" PRIx64
" %3s\n",
1136 block
->idstr
, psize
,
1137 (uint64_t)block
->offset
,
1138 (uint64_t)block
->used_length
,
1139 (uint64_t)block
->max_length
,
1140 (uint64_t)(uintptr_t)block
->host
,
1141 block
->mr
->readonly
? "ro" : "rw");
1149 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1151 long *hpsize_min
= opaque
;
1153 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1154 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1155 long hpsize
= host_memory_backend_pagesize(backend
);
1157 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1158 *hpsize_min
= hpsize
;
1165 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1167 long *hpsize_max
= opaque
;
1169 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1170 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1171 long hpsize
= host_memory_backend_pagesize(backend
);
1173 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1174 *hpsize_max
= hpsize
;
1182 * TODO: We assume right now that all mapped host memory backends are
1183 * used as RAM, however some might be used for different purposes.
1185 long qemu_minrampagesize(void)
1187 long hpsize
= LONG_MAX
;
1188 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1190 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1194 long qemu_maxrampagesize(void)
1197 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1199 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1204 static int64_t get_file_size(int fd
)
1207 #if defined(__linux__)
1210 if (fstat(fd
, &st
) < 0) {
1214 /* Special handling for devdax character devices */
1215 if (S_ISCHR(st
.st_mode
)) {
1216 g_autofree
char *subsystem_path
= NULL
;
1217 g_autofree
char *subsystem
= NULL
;
1219 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1220 major(st
.st_rdev
), minor(st
.st_rdev
));
1221 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1223 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1224 g_autofree
char *size_path
= NULL
;
1225 g_autofree
char *size_str
= NULL
;
1227 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1228 major(st
.st_rdev
), minor(st
.st_rdev
));
1230 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1231 return g_ascii_strtoll(size_str
, NULL
, 0);
1235 #endif /* defined(__linux__) */
1237 /* st.st_size may be zero for special files yet lseek(2) works */
1238 size
= lseek(fd
, 0, SEEK_END
);
1245 static int64_t get_file_align(int fd
)
1248 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1251 if (fstat(fd
, &st
) < 0) {
1255 /* Special handling for devdax character devices */
1256 if (S_ISCHR(st
.st_mode
)) {
1257 g_autofree
char *path
= NULL
;
1258 g_autofree
char *rpath
= NULL
;
1259 struct daxctl_ctx
*ctx
;
1260 struct daxctl_region
*region
;
1263 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1264 major(st
.st_rdev
), minor(st
.st_rdev
));
1265 rpath
= realpath(path
, NULL
);
1270 rc
= daxctl_new(&ctx
);
1275 daxctl_region_foreach(ctx
, region
) {
1276 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1277 align
= daxctl_region_get_align(region
);
1283 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1288 static int file_ram_open(const char *path
,
1289 const char *region_name
,
1294 char *sanitized_name
;
1300 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1303 * open(O_RDONLY) won't fail with EISDIR. Check manually if we
1304 * opened a directory and fail similarly to how we fail ENOENT
1305 * in readonly mode. Note that mkstemp() would imply O_RDWR.
1308 struct stat file_stat
;
1310 if (fstat(fd
, &file_stat
)) {
1312 if (errno
== EINTR
) {
1316 } else if (S_ISDIR(file_stat
.st_mode
)) {
1321 /* @path names an existing file, use it */
1324 if (errno
== ENOENT
) {
1326 /* Refuse to create new, readonly files. */
1329 /* @path names a file that doesn't exist, create it */
1330 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1335 } else if (errno
== EISDIR
) {
1336 /* @path names a directory, create a file there */
1337 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1338 sanitized_name
= g_strdup(region_name
);
1339 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1345 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1347 g_free(sanitized_name
);
1349 fd
= mkstemp(filename
);
1357 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1361 * Try again on EINTR and EEXIST. The latter happens when
1362 * something else creates the file between our two open().
1369 static void *file_ram_alloc(RAMBlock
*block
,
1376 uint32_t qemu_map_flags
;
1379 block
->page_size
= qemu_fd_getpagesize(fd
);
1380 if (block
->mr
->align
% block
->page_size
) {
1381 error_setg(errp
, "alignment 0x%" PRIx64
1382 " must be multiples of page size 0x%zx",
1383 block
->mr
->align
, block
->page_size
);
1385 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1386 error_setg(errp
, "alignment 0x%" PRIx64
1387 " must be a power of two", block
->mr
->align
);
1389 } else if (offset
% block
->page_size
) {
1390 error_setg(errp
, "offset 0x%" PRIx64
1391 " must be multiples of page size 0x%zx",
1392 offset
, block
->page_size
);
1395 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1396 #if defined(__s390x__)
1397 if (kvm_enabled()) {
1398 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1402 if (memory
< block
->page_size
) {
1403 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1404 "or larger than page size 0x%zx",
1405 memory
, block
->page_size
);
1409 memory
= ROUND_UP(memory
, block
->page_size
);
1412 * ftruncate is not supported by hugetlbfs in older
1413 * hosts, so don't bother bailing out on errors.
1414 * If anything goes wrong with it under other filesystems,
1417 * Do not truncate the non-empty backend file to avoid corrupting
1418 * the existing data in the file. Disabling shrinking is not
1419 * enough. For example, the current vNVDIMM implementation stores
1420 * the guest NVDIMM labels at the end of the backend file. If the
1421 * backend file is later extended, QEMU will not be able to find
1422 * those labels. Therefore, extending the non-empty backend file
1423 * is disabled as well.
1425 if (truncate
&& ftruncate(fd
, offset
+ memory
)) {
1426 perror("ftruncate");
1429 qemu_map_flags
= (block
->flags
& RAM_READONLY
) ? QEMU_MAP_READONLY
: 0;
1430 qemu_map_flags
|= (block
->flags
& RAM_SHARED
) ? QEMU_MAP_SHARED
: 0;
1431 qemu_map_flags
|= (block
->flags
& RAM_PMEM
) ? QEMU_MAP_SYNC
: 0;
1432 qemu_map_flags
|= (block
->flags
& RAM_NORESERVE
) ? QEMU_MAP_NORESERVE
: 0;
1433 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, qemu_map_flags
, offset
);
1434 if (area
== MAP_FAILED
) {
1435 error_setg_errno(errp
, errno
,
1436 "unable to map backing store for guest RAM");
1441 block
->fd_offset
= offset
;
1446 /* Allocate space within the ram_addr_t space that governs the
1448 * Called with the ramlist lock held.
1450 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1452 RAMBlock
*block
, *next_block
;
1453 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1455 assert(size
!= 0); /* it would hand out same offset multiple times */
1457 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1461 RAMBLOCK_FOREACH(block
) {
1462 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1464 /* Align blocks to start on a 'long' in the bitmap
1465 * which makes the bitmap sync'ing take the fast path.
1467 candidate
= block
->offset
+ block
->max_length
;
1468 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1470 /* Search for the closest following block
1473 RAMBLOCK_FOREACH(next_block
) {
1474 if (next_block
->offset
>= candidate
) {
1475 next
= MIN(next
, next_block
->offset
);
1479 /* If it fits remember our place and remember the size
1480 * of gap, but keep going so that we might find a smaller
1481 * gap to fill so avoiding fragmentation.
1483 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1485 mingap
= next
- candidate
;
1488 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1491 if (offset
== RAM_ADDR_MAX
) {
1492 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1497 trace_find_ram_offset(size
, offset
);
1502 static unsigned long last_ram_page(void)
1505 ram_addr_t last
= 0;
1507 RCU_READ_LOCK_GUARD();
1508 RAMBLOCK_FOREACH(block
) {
1509 last
= MAX(last
, block
->offset
+ block
->max_length
);
1511 return last
>> TARGET_PAGE_BITS
;
1514 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1518 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1519 if (!machine_dump_guest_core(current_machine
)) {
1520 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1522 perror("qemu_madvise");
1523 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1524 "but dump-guest-core=off specified\n");
1529 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1534 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1539 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1544 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1546 return rb
->used_length
;
1549 ram_addr_t
qemu_ram_get_max_length(RAMBlock
*rb
)
1551 return rb
->max_length
;
1554 bool qemu_ram_is_shared(RAMBlock
*rb
)
1556 return rb
->flags
& RAM_SHARED
;
1559 bool qemu_ram_is_noreserve(RAMBlock
*rb
)
1561 return rb
->flags
& RAM_NORESERVE
;
1564 /* Note: Only set at the start of postcopy */
1565 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1567 return rb
->flags
& RAM_UF_ZEROPAGE
;
1570 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1572 rb
->flags
|= RAM_UF_ZEROPAGE
;
1575 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1577 return rb
->flags
& RAM_MIGRATABLE
;
1580 void qemu_ram_set_migratable(RAMBlock
*rb
)
1582 rb
->flags
|= RAM_MIGRATABLE
;
1585 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1587 rb
->flags
&= ~RAM_MIGRATABLE
;
1590 bool qemu_ram_is_named_file(RAMBlock
*rb
)
1592 return rb
->flags
& RAM_NAMED_FILE
;
1595 int qemu_ram_get_fd(RAMBlock
*rb
)
1600 /* Called with the BQL held. */
1601 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1606 assert(!new_block
->idstr
[0]);
1609 char *id
= qdev_get_dev_path(dev
);
1611 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1615 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1617 RCU_READ_LOCK_GUARD();
1618 RAMBLOCK_FOREACH(block
) {
1619 if (block
!= new_block
&&
1620 !strcmp(block
->idstr
, new_block
->idstr
)) {
1621 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1628 /* Called with the BQL held. */
1629 void qemu_ram_unset_idstr(RAMBlock
*block
)
1631 /* FIXME: arch_init.c assumes that this is not called throughout
1632 * migration. Ignore the problem since hot-unplug during migration
1633 * does not work anyway.
1636 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1640 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1642 return rb
->page_size
;
1645 /* Returns the largest size of page in use */
1646 size_t qemu_ram_pagesize_largest(void)
1651 RAMBLOCK_FOREACH(block
) {
1652 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1658 static int memory_try_enable_merging(void *addr
, size_t len
)
1660 if (!machine_mem_merge(current_machine
)) {
1661 /* disabled by the user */
1665 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1669 * Resizing RAM while migrating can result in the migration being canceled.
1670 * Care has to be taken if the guest might have already detected the memory.
1672 * As memory core doesn't know how is memory accessed, it is up to
1673 * resize callback to update device state and/or add assertions to detect
1674 * misuse, if necessary.
1676 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1678 const ram_addr_t oldsize
= block
->used_length
;
1679 const ram_addr_t unaligned_size
= newsize
;
1683 newsize
= TARGET_PAGE_ALIGN(newsize
);
1684 newsize
= REAL_HOST_PAGE_ALIGN(newsize
);
1686 if (block
->used_length
== newsize
) {
1688 * We don't have to resize the ram block (which only knows aligned
1689 * sizes), however, we have to notify if the unaligned size changed.
1691 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1692 memory_region_set_size(block
->mr
, unaligned_size
);
1693 if (block
->resized
) {
1694 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1700 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1701 error_setg_errno(errp
, EINVAL
,
1702 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1703 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1704 newsize
, block
->used_length
);
1708 if (block
->max_length
< newsize
) {
1709 error_setg_errno(errp
, EINVAL
,
1710 "Size too large: %s: 0x" RAM_ADDR_FMT
1711 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1712 newsize
, block
->max_length
);
1716 /* Notify before modifying the ram block and touching the bitmaps. */
1718 ram_block_notify_resize(block
->host
, oldsize
, newsize
);
1721 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1722 block
->used_length
= newsize
;
1723 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1725 memory_region_set_size(block
->mr
, unaligned_size
);
1726 if (block
->resized
) {
1727 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1733 * Trigger sync on the given ram block for range [start, start + length]
1734 * with the backing store if one is available.
1736 * @Note: this is supposed to be a synchronous op.
1738 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1740 /* The requested range should fit in within the block range */
1741 g_assert((start
+ length
) <= block
->used_length
);
1743 #ifdef CONFIG_LIBPMEM
1744 /* The lack of support for pmem should not block the sync */
1745 if (ramblock_is_pmem(block
)) {
1746 void *addr
= ramblock_ptr(block
, start
);
1747 pmem_persist(addr
, length
);
1751 if (block
->fd
>= 0) {
1753 * Case there is no support for PMEM or the memory has not been
1754 * specified as persistent (or is not one) - use the msync.
1755 * Less optimal but still achieves the same goal
1757 void *addr
= ramblock_ptr(block
, start
);
1758 if (qemu_msync(addr
, length
, block
->fd
)) {
1759 warn_report("%s: failed to sync memory range: start: "
1760 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1761 __func__
, start
, length
);
1766 /* Called with ram_list.mutex held */
1767 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1768 ram_addr_t new_ram_size
)
1770 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1771 DIRTY_MEMORY_BLOCK_SIZE
);
1772 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1773 DIRTY_MEMORY_BLOCK_SIZE
);
1776 /* Only need to extend if block count increased */
1777 if (new_num_blocks
<= old_num_blocks
) {
1781 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1782 DirtyMemoryBlocks
*old_blocks
;
1783 DirtyMemoryBlocks
*new_blocks
;
1786 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1787 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1788 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1790 if (old_num_blocks
) {
1791 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1792 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1795 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1796 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1799 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1802 g_free_rcu(old_blocks
, rcu
);
1807 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
)
1809 const bool noreserve
= qemu_ram_is_noreserve(new_block
);
1810 const bool shared
= qemu_ram_is_shared(new_block
);
1812 RAMBlock
*last_block
= NULL
;
1813 bool free_on_error
= false;
1814 ram_addr_t old_ram_size
, new_ram_size
;
1817 old_ram_size
= last_ram_page();
1819 qemu_mutex_lock_ramlist();
1820 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1822 if (!new_block
->host
) {
1823 if (xen_enabled()) {
1824 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1825 new_block
->mr
, &err
);
1827 error_propagate(errp
, err
);
1828 qemu_mutex_unlock_ramlist();
1832 new_block
->host
= qemu_anon_ram_alloc(new_block
->max_length
,
1833 &new_block
->mr
->align
,
1835 if (!new_block
->host
) {
1836 error_setg_errno(errp
, errno
,
1837 "cannot set up guest memory '%s'",
1838 memory_region_name(new_block
->mr
));
1839 qemu_mutex_unlock_ramlist();
1842 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1843 free_on_error
= true;
1847 if (new_block
->flags
& RAM_GUEST_MEMFD
) {
1850 assert(kvm_enabled());
1851 assert(new_block
->guest_memfd
< 0);
1853 ret
= ram_block_discard_require(true);
1855 error_setg_errno(errp
, -ret
,
1856 "cannot set up private guest memory: discard currently blocked");
1857 error_append_hint(errp
, "Are you using assigned devices?\n");
1861 new_block
->guest_memfd
= kvm_create_guest_memfd(new_block
->max_length
,
1863 if (new_block
->guest_memfd
< 0) {
1864 qemu_mutex_unlock_ramlist();
1869 new_ram_size
= MAX(old_ram_size
,
1870 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1871 if (new_ram_size
> old_ram_size
) {
1872 dirty_memory_extend(old_ram_size
, new_ram_size
);
1874 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1875 * QLIST (which has an RCU-friendly variant) does not have insertion at
1876 * tail, so save the last element in last_block.
1878 RAMBLOCK_FOREACH(block
) {
1880 if (block
->max_length
< new_block
->max_length
) {
1885 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1886 } else if (last_block
) {
1887 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1888 } else { /* list is empty */
1889 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1891 ram_list
.mru_block
= NULL
;
1893 /* Write list before version */
1896 qemu_mutex_unlock_ramlist();
1898 cpu_physical_memory_set_dirty_range(new_block
->offset
,
1899 new_block
->used_length
,
1902 if (new_block
->host
) {
1903 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
1904 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
1906 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1907 * Configure it unless the machine is a qtest server, in which case
1908 * KVM is not used and it may be forked (eg for fuzzing purposes).
1910 if (!qtest_enabled()) {
1911 qemu_madvise(new_block
->host
, new_block
->max_length
,
1912 QEMU_MADV_DONTFORK
);
1914 ram_block_notify_add(new_block
->host
, new_block
->used_length
,
1915 new_block
->max_length
);
1920 if (free_on_error
) {
1921 qemu_anon_ram_free(new_block
->host
, new_block
->max_length
);
1922 new_block
->host
= NULL
;
1927 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
1928 uint32_t ram_flags
, int fd
, off_t offset
,
1931 RAMBlock
*new_block
;
1932 Error
*local_err
= NULL
;
1933 int64_t file_size
, file_align
;
1935 /* Just support these ram flags by now. */
1936 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
| RAM_NORESERVE
|
1937 RAM_PROTECTED
| RAM_NAMED_FILE
| RAM_READONLY
|
1938 RAM_READONLY_FD
| RAM_GUEST_MEMFD
)) == 0);
1940 if (xen_enabled()) {
1941 error_setg(errp
, "-mem-path not supported with Xen");
1945 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1947 "host lacks kvm mmu notifiers, -mem-path unsupported");
1951 size
= TARGET_PAGE_ALIGN(size
);
1952 size
= REAL_HOST_PAGE_ALIGN(size
);
1954 file_size
= get_file_size(fd
);
1955 if (file_size
> offset
&& file_size
< (offset
+ size
)) {
1956 error_setg(errp
, "backing store size 0x%" PRIx64
1957 " does not match 'size' option 0x" RAM_ADDR_FMT
,
1962 file_align
= get_file_align(fd
);
1963 if (file_align
> 0 && file_align
> mr
->align
) {
1964 error_setg(errp
, "backing store align 0x%" PRIx64
1965 " is larger than 'align' option 0x%" PRIx64
,
1966 file_align
, mr
->align
);
1970 new_block
= g_malloc0(sizeof(*new_block
));
1972 new_block
->used_length
= size
;
1973 new_block
->max_length
= size
;
1974 new_block
->flags
= ram_flags
;
1975 new_block
->guest_memfd
= -1;
1976 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, !file_size
, offset
,
1978 if (!new_block
->host
) {
1983 ram_block_add(new_block
, &local_err
);
1986 error_propagate(errp
, local_err
);
1994 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
1995 uint32_t ram_flags
, const char *mem_path
,
1996 off_t offset
, Error
**errp
)
2002 fd
= file_ram_open(mem_path
, memory_region_name(mr
),
2003 !!(ram_flags
& RAM_READONLY_FD
), &created
);
2005 error_setg_errno(errp
, -fd
, "can't open backing store %s for guest RAM",
2007 if (!(ram_flags
& RAM_READONLY_FD
) && !(ram_flags
& RAM_SHARED
) &&
2010 * If we can open the file R/O (note: will never create a new file)
2011 * and we are dealing with a private mapping, there are still ways
2012 * to consume such files and get RAM instead of ROM.
2014 fd
= file_ram_open(mem_path
, memory_region_name(mr
), true,
2021 error_append_hint(errp
, "Consider opening the backing store"
2022 " read-only but still creating writable RAM using"
2023 " '-object memory-backend-file,readonly=on,rom=off...'"
2024 " (see \"VM templating\" documentation)\n");
2029 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, offset
, errp
);
2043 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2044 void (*resized
)(const char*,
2047 void *host
, uint32_t ram_flags
,
2048 MemoryRegion
*mr
, Error
**errp
)
2050 RAMBlock
*new_block
;
2051 Error
*local_err
= NULL
;
2054 assert((ram_flags
& ~(RAM_SHARED
| RAM_RESIZEABLE
| RAM_PREALLOC
|
2055 RAM_NORESERVE
| RAM_GUEST_MEMFD
)) == 0);
2056 assert(!host
^ (ram_flags
& RAM_PREALLOC
));
2058 align
= qemu_real_host_page_size();
2059 align
= MAX(align
, TARGET_PAGE_SIZE
);
2060 size
= ROUND_UP(size
, align
);
2061 max_size
= ROUND_UP(max_size
, align
);
2063 new_block
= g_malloc0(sizeof(*new_block
));
2065 new_block
->resized
= resized
;
2066 new_block
->used_length
= size
;
2067 new_block
->max_length
= max_size
;
2068 assert(max_size
>= size
);
2070 new_block
->guest_memfd
= -1;
2071 new_block
->page_size
= qemu_real_host_page_size();
2072 new_block
->host
= host
;
2073 new_block
->flags
= ram_flags
;
2074 ram_block_add(new_block
, &local_err
);
2077 error_propagate(errp
, local_err
);
2083 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2084 MemoryRegion
*mr
, Error
**errp
)
2086 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, RAM_PREALLOC
, mr
,
2090 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, uint32_t ram_flags
,
2091 MemoryRegion
*mr
, Error
**errp
)
2093 assert((ram_flags
& ~(RAM_SHARED
| RAM_NORESERVE
| RAM_GUEST_MEMFD
)) == 0);
2094 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, ram_flags
, mr
, errp
);
2097 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2098 void (*resized
)(const char*,
2101 MemoryRegion
*mr
, Error
**errp
)
2103 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
,
2104 RAM_RESIZEABLE
, mr
, errp
);
2107 static void reclaim_ramblock(RAMBlock
*block
)
2109 if (block
->flags
& RAM_PREALLOC
) {
2111 } else if (xen_enabled()) {
2112 xen_invalidate_map_cache_entry(block
->host
);
2114 } else if (block
->fd
>= 0) {
2115 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2119 qemu_anon_ram_free(block
->host
, block
->max_length
);
2122 if (block
->guest_memfd
>= 0) {
2123 close(block
->guest_memfd
);
2124 ram_block_discard_require(false);
2130 void qemu_ram_free(RAMBlock
*block
)
2137 ram_block_notify_remove(block
->host
, block
->used_length
,
2141 qemu_mutex_lock_ramlist();
2142 QLIST_REMOVE_RCU(block
, next
);
2143 ram_list
.mru_block
= NULL
;
2144 /* Write list before version */
2147 call_rcu(block
, reclaim_ramblock
, rcu
);
2148 qemu_mutex_unlock_ramlist();
2152 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2160 RAMBLOCK_FOREACH(block
) {
2161 offset
= addr
- block
->offset
;
2162 if (offset
< block
->max_length
) {
2163 vaddr
= ramblock_ptr(block
, offset
);
2164 if (block
->flags
& RAM_PREALLOC
) {
2166 } else if (xen_enabled()) {
2170 flags
|= block
->flags
& RAM_SHARED
?
2171 MAP_SHARED
: MAP_PRIVATE
;
2172 flags
|= block
->flags
& RAM_NORESERVE
? MAP_NORESERVE
: 0;
2174 prot
|= block
->flags
& RAM_READONLY
? 0 : PROT_WRITE
;
2175 if (block
->fd
>= 0) {
2176 area
= mmap(vaddr
, length
, prot
, flags
, block
->fd
,
2177 offset
+ block
->fd_offset
);
2179 flags
|= MAP_ANONYMOUS
;
2180 area
= mmap(vaddr
, length
, prot
, flags
, -1, 0);
2182 if (area
!= vaddr
) {
2183 error_report("Could not remap addr: "
2184 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2188 memory_try_enable_merging(vaddr
, length
);
2189 qemu_ram_setup_dump(vaddr
, length
);
2194 #endif /* !_WIN32 */
2197 * Return a host pointer to guest's ram.
2198 * For Xen, foreign mappings get created if they don't already exist.
2200 * @block: block for the RAM to lookup (optional and may be NULL).
2201 * @addr: address within the memory region.
2202 * @size: pointer to requested size (optional and may be NULL).
2203 * size may get modified and return a value smaller than
2204 * what was requested.
2205 * @lock: wether to lock the mapping in xen-mapcache until invalidated.
2206 * @is_write: hint wether to map RW or RO in the xen-mapcache.
2207 * (optional and may always be set to true).
2209 * Called within RCU critical section.
2211 static void *qemu_ram_ptr_length(RAMBlock
*block
, ram_addr_t addr
,
2212 hwaddr
*size
, bool lock
,
2217 if (size
&& *size
== 0) {
2221 if (block
== NULL
) {
2222 block
= qemu_get_ram_block(addr
);
2223 addr
-= block
->offset
;
2226 *size
= MIN(*size
, block
->max_length
- addr
);
2230 if (xen_enabled() && block
->host
== NULL
) {
2231 /* We need to check if the requested address is in the RAM
2232 * because we don't want to map the entire memory in QEMU.
2233 * In that case just map the requested area.
2235 if (xen_mr_is_memory(block
->mr
)) {
2236 return xen_map_cache(block
->mr
, block
->offset
+ addr
,
2238 lock
, lock
, is_write
);
2241 block
->host
= xen_map_cache(block
->mr
, block
->offset
,
2247 return ramblock_ptr(block
, addr
);
2251 * Return a host pointer to ram allocated with qemu_ram_alloc.
2252 * This should not be used for general purpose DMA. Use address_space_map
2253 * or address_space_rw instead. For local memory (e.g. video ram) that the
2254 * device owns, use memory_region_get_ram_ptr.
2256 * Called within RCU critical section.
2258 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2260 return qemu_ram_ptr_length(ram_block
, addr
, NULL
, false, true);
2263 /* Return the offset of a hostpointer within a ramblock */
2264 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2266 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2267 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2268 assert(res
< rb
->max_length
);
2273 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2277 uint8_t *host
= ptr
;
2279 if (xen_enabled()) {
2280 ram_addr_t ram_addr
;
2281 RCU_READ_LOCK_GUARD();
2282 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2283 if (ram_addr
== RAM_ADDR_INVALID
) {
2287 block
= qemu_get_ram_block(ram_addr
);
2289 *offset
= ram_addr
- block
->offset
;
2294 RCU_READ_LOCK_GUARD();
2295 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2296 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2300 RAMBLOCK_FOREACH(block
) {
2301 /* This case append when the block is not mapped. */
2302 if (block
->host
== NULL
) {
2305 if (host
- block
->host
< block
->max_length
) {
2313 *offset
= (host
- block
->host
);
2315 *offset
&= TARGET_PAGE_MASK
;
2321 * Finds the named RAMBlock
2323 * name: The name of RAMBlock to find
2325 * Returns: RAMBlock (or NULL if not found)
2327 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2331 RAMBLOCK_FOREACH(block
) {
2332 if (!strcmp(name
, block
->idstr
)) {
2341 * Some of the system routines need to translate from a host pointer
2342 * (typically a TLB entry) back to a ram offset.
2344 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2349 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2351 return RAM_ADDR_INVALID
;
2354 return block
->offset
+ offset
;
2357 ram_addr_t
qemu_ram_addr_from_host_nofail(void *ptr
)
2359 ram_addr_t ram_addr
;
2361 ram_addr
= qemu_ram_addr_from_host(ptr
);
2362 if (ram_addr
== RAM_ADDR_INVALID
) {
2363 error_report("Bad ram pointer %p", ptr
);
2369 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2370 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2371 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2372 const void *buf
, hwaddr len
);
2373 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2374 bool is_write
, MemTxAttrs attrs
);
2376 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2377 unsigned len
, MemTxAttrs attrs
)
2379 subpage_t
*subpage
= opaque
;
2383 #if defined(DEBUG_SUBPAGE)
2384 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
"\n", __func__
,
2385 subpage
, len
, addr
);
2387 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2391 *data
= ldn_p(buf
, len
);
2395 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2396 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2398 subpage_t
*subpage
= opaque
;
2401 #if defined(DEBUG_SUBPAGE)
2402 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
2403 " value %"PRIx64
"\n",
2404 __func__
, subpage
, len
, addr
, value
);
2406 stn_p(buf
, len
, value
);
2407 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2410 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2411 unsigned len
, bool is_write
,
2414 subpage_t
*subpage
= opaque
;
2415 #if defined(DEBUG_SUBPAGE)
2416 printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx
"\n",
2417 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2420 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2421 len
, is_write
, attrs
);
2424 static const MemoryRegionOps subpage_ops
= {
2425 .read_with_attrs
= subpage_read
,
2426 .write_with_attrs
= subpage_write
,
2427 .impl
.min_access_size
= 1,
2428 .impl
.max_access_size
= 8,
2429 .valid
.min_access_size
= 1,
2430 .valid
.max_access_size
= 8,
2431 .valid
.accepts
= subpage_accepts
,
2432 .endianness
= DEVICE_NATIVE_ENDIAN
,
2435 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2440 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2442 idx
= SUBPAGE_IDX(start
);
2443 eidx
= SUBPAGE_IDX(end
);
2444 #if defined(DEBUG_SUBPAGE)
2445 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2446 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2448 for (; idx
<= eidx
; idx
++) {
2449 mmio
->sub_section
[idx
] = section
;
2455 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2459 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2460 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2463 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2464 NULL
, TARGET_PAGE_SIZE
);
2465 mmio
->iomem
.subpage
= true;
2466 #if defined(DEBUG_SUBPAGE)
2467 printf("%s: %p base " HWADDR_FMT_plx
" len %08x\n", __func__
,
2468 mmio
, base
, TARGET_PAGE_SIZE
);
2474 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2477 MemoryRegionSection section
= {
2480 .offset_within_address_space
= 0,
2481 .offset_within_region
= 0,
2482 .size
= int128_2_64(),
2485 return phys_section_add(map
, §ion
);
2488 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2489 hwaddr index
, MemTxAttrs attrs
)
2491 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2492 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2493 AddressSpaceDispatch
*d
= cpuas
->memory_dispatch
;
2494 int section_index
= index
& ~TARGET_PAGE_MASK
;
2495 MemoryRegionSection
*ret
;
2497 assert(section_index
< d
->map
.sections_nb
);
2498 ret
= d
->map
.sections
+ section_index
;
2500 assert(ret
->mr
->ops
);
2505 static void io_mem_init(void)
2507 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2511 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2513 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2516 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2517 assert(n
== PHYS_SECTION_UNASSIGNED
);
2519 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2524 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2526 phys_sections_free(&d
->map
);
2530 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2534 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2536 CPUAddressSpace
*cpuas
;
2538 /* Wait for the CPU to end the current TB. This avoids the following
2542 * ---------------------- -------------------------
2543 * TLB check -> slow path
2544 * notdirty_mem_write
2548 * TLB check -> fast path
2552 * by pushing the migration thread's memory read after the vCPU thread has
2553 * written the memory.
2555 if (replay_mode
== REPLAY_MODE_NONE
) {
2557 * VGA can make calls to this function while updating the screen.
2558 * In record/replay mode this causes a deadlock, because
2559 * run_on_cpu waits for rr mutex. Therefore no races are possible
2560 * in this case and no need for making run_on_cpu when
2561 * record/replay is enabled.
2563 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2564 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2568 static void tcg_commit_cpu(CPUState
*cpu
, run_on_cpu_data data
)
2570 CPUAddressSpace
*cpuas
= data
.host_ptr
;
2572 cpuas
->memory_dispatch
= address_space_to_dispatch(cpuas
->as
);
2576 static void tcg_commit(MemoryListener
*listener
)
2578 CPUAddressSpace
*cpuas
;
2581 assert(tcg_enabled());
2582 /* since each CPU stores ram addresses in its TLB cache, we must
2583 reset the modified entries */
2584 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2588 * Defer changes to as->memory_dispatch until the cpu is quiescent.
2589 * Otherwise we race between (1) other cpu threads and (2) ongoing
2590 * i/o for the current cpu thread, with data cached by mmu_lookup().
2592 * In addition, queueing the work function will kick the cpu back to
2593 * the main loop, which will end the RCU critical section and reclaim
2594 * the memory data structures.
2596 * That said, the listener is also called during realize, before
2597 * all of the tcg machinery for run-on is initialized: thus halt_cond.
2599 if (cpu
->halt_cond
) {
2600 async_run_on_cpu(cpu
, tcg_commit_cpu
, RUN_ON_CPU_HOST_PTR(cpuas
));
2602 tcg_commit_cpu(cpu
, RUN_ON_CPU_HOST_PTR(cpuas
));
2606 static void memory_map_init(void)
2608 system_memory
= g_malloc(sizeof(*system_memory
));
2610 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2611 address_space_init(&address_space_memory
, system_memory
, "memory");
2613 system_io
= g_malloc(sizeof(*system_io
));
2614 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2616 address_space_init(&address_space_io
, system_io
, "I/O");
2619 MemoryRegion
*get_system_memory(void)
2621 return system_memory
;
2624 MemoryRegion
*get_system_io(void)
2629 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2632 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2633 addr
+= memory_region_get_ram_addr(mr
);
2635 /* No early return if dirty_log_mask is or becomes 0, because
2636 * cpu_physical_memory_set_dirty_range will still call
2637 * xen_modified_memory.
2639 if (dirty_log_mask
) {
2641 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2643 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2644 assert(tcg_enabled());
2645 tb_invalidate_phys_range(addr
, addr
+ length
- 1);
2646 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2648 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2651 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2654 * In principle this function would work on other memory region types too,
2655 * but the ROM device use case is the only one where this operation is
2656 * necessary. Other memory regions should use the
2657 * address_space_read/write() APIs.
2659 assert(memory_region_is_romd(mr
));
2661 invalidate_and_set_dirty(mr
, addr
, size
);
2664 int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2666 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2668 /* Regions are assumed to support 1-4 byte accesses unless
2669 otherwise specified. */
2670 if (access_size_max
== 0) {
2671 access_size_max
= 4;
2674 /* Bound the maximum access by the alignment of the address. */
2675 if (!mr
->ops
->impl
.unaligned
) {
2676 unsigned align_size_max
= addr
& -addr
;
2677 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2678 access_size_max
= align_size_max
;
2682 /* Don't attempt accesses larger than the maximum. */
2683 if (l
> access_size_max
) {
2684 l
= access_size_max
;
2691 bool prepare_mmio_access(MemoryRegion
*mr
)
2693 bool release_lock
= false;
2695 if (!bql_locked()) {
2697 release_lock
= true;
2699 if (mr
->flush_coalesced_mmio
) {
2700 qemu_flush_coalesced_mmio_buffer();
2703 return release_lock
;
2707 * flatview_access_allowed
2708 * @mr: #MemoryRegion to be accessed
2709 * @attrs: memory transaction attributes
2710 * @addr: address within that memory region
2711 * @len: the number of bytes to access
2713 * Check if a memory transaction is allowed.
2715 * Returns: true if transaction is allowed, false if denied.
2717 static bool flatview_access_allowed(MemoryRegion
*mr
, MemTxAttrs attrs
,
2718 hwaddr addr
, hwaddr len
)
2720 if (likely(!attrs
.memory
)) {
2723 if (memory_region_is_ram(mr
)) {
2726 qemu_log_mask(LOG_GUEST_ERROR
,
2727 "Invalid access to non-RAM device at "
2728 "addr 0x%" HWADDR_PRIX
", size %" HWADDR_PRIu
", "
2729 "region '%s'\n", addr
, len
, memory_region_name(mr
));
2733 static MemTxResult
flatview_write_continue_step(MemTxAttrs attrs
,
2735 hwaddr len
, hwaddr mr_addr
,
2736 hwaddr
*l
, MemoryRegion
*mr
)
2738 if (!flatview_access_allowed(mr
, attrs
, mr_addr
, *l
)) {
2739 return MEMTX_ACCESS_ERROR
;
2742 if (!memory_access_is_direct(mr
, true)) {
2745 bool release_lock
= prepare_mmio_access(mr
);
2747 *l
= memory_access_size(mr
, *l
, mr_addr
);
2749 * XXX: could force current_cpu to NULL to avoid
2754 * Assure Coverity (and ourselves) that we are not going to OVERRUN
2755 * the buffer by following ldn_he_p().
2757 #ifdef QEMU_STATIC_ANALYSIS
2758 assert((*l
== 1 && len
>= 1) ||
2759 (*l
== 2 && len
>= 2) ||
2760 (*l
== 4 && len
>= 4) ||
2761 (*l
== 8 && len
>= 8));
2763 val
= ldn_he_p(buf
, *l
);
2764 result
= memory_region_dispatch_write(mr
, mr_addr
, val
,
2765 size_memop(*l
), attrs
);
2773 uint8_t *ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, mr_addr
, l
,
2776 memmove(ram_ptr
, buf
, *l
);
2777 invalidate_and_set_dirty(mr
, mr_addr
, *l
);
2783 /* Called within RCU critical section. */
2784 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2787 hwaddr len
, hwaddr mr_addr
,
2788 hwaddr l
, MemoryRegion
*mr
)
2790 MemTxResult result
= MEMTX_OK
;
2791 const uint8_t *buf
= ptr
;
2794 result
|= flatview_write_continue_step(attrs
, buf
, len
, mr_addr
, &l
,
2806 mr
= flatview_translate(fv
, addr
, &mr_addr
, &l
, true, attrs
);
2812 /* Called from RCU critical section. */
2813 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2814 const void *buf
, hwaddr len
)
2821 mr
= flatview_translate(fv
, addr
, &mr_addr
, &l
, true, attrs
);
2822 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2823 return MEMTX_ACCESS_ERROR
;
2825 return flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2829 static MemTxResult
flatview_read_continue_step(MemTxAttrs attrs
, uint8_t *buf
,
2830 hwaddr len
, hwaddr mr_addr
,
2834 if (!flatview_access_allowed(mr
, attrs
, mr_addr
, *l
)) {
2835 return MEMTX_ACCESS_ERROR
;
2838 if (!memory_access_is_direct(mr
, false)) {
2842 bool release_lock
= prepare_mmio_access(mr
);
2844 *l
= memory_access_size(mr
, *l
, mr_addr
);
2845 result
= memory_region_dispatch_read(mr
, mr_addr
, &val
, size_memop(*l
),
2849 * Assure Coverity (and ourselves) that we are not going to OVERRUN
2850 * the buffer by following stn_he_p().
2852 #ifdef QEMU_STATIC_ANALYSIS
2853 assert((*l
== 1 && len
>= 1) ||
2854 (*l
== 2 && len
>= 2) ||
2855 (*l
== 4 && len
>= 4) ||
2856 (*l
== 8 && len
>= 8));
2858 stn_he_p(buf
, *l
, val
);
2866 uint8_t *ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, mr_addr
, l
,
2869 memcpy(buf
, ram_ptr
, *l
);
2875 /* Called within RCU critical section. */
2876 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2877 MemTxAttrs attrs
, void *ptr
,
2878 hwaddr len
, hwaddr mr_addr
, hwaddr l
,
2881 MemTxResult result
= MEMTX_OK
;
2884 fuzz_dma_read_cb(addr
, len
, mr
);
2886 result
|= flatview_read_continue_step(attrs
, buf
, len
, mr_addr
, &l
, mr
);
2897 mr
= flatview_translate(fv
, addr
, &mr_addr
, &l
, false, attrs
);
2903 /* Called from RCU critical section. */
2904 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2905 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2912 mr
= flatview_translate(fv
, addr
, &mr_addr
, &l
, false, attrs
);
2913 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2914 return MEMTX_ACCESS_ERROR
;
2916 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2920 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2921 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2923 MemTxResult result
= MEMTX_OK
;
2927 RCU_READ_LOCK_GUARD();
2928 fv
= address_space_to_flatview(as
);
2929 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2935 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2937 const void *buf
, hwaddr len
)
2939 MemTxResult result
= MEMTX_OK
;
2943 RCU_READ_LOCK_GUARD();
2944 fv
= address_space_to_flatview(as
);
2945 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2951 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2952 void *buf
, hwaddr len
, bool is_write
)
2955 return address_space_write(as
, addr
, attrs
, buf
, len
);
2957 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2961 MemTxResult
address_space_set(AddressSpace
*as
, hwaddr addr
,
2962 uint8_t c
, hwaddr len
, MemTxAttrs attrs
)
2964 #define FILLBUF_SIZE 512
2965 uint8_t fillbuf
[FILLBUF_SIZE
];
2967 MemTxResult error
= MEMTX_OK
;
2969 memset(fillbuf
, c
, FILLBUF_SIZE
);
2971 l
= len
< FILLBUF_SIZE
? len
: FILLBUF_SIZE
;
2972 error
|= address_space_write(as
, addr
, attrs
, fillbuf
, l
);
2980 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2981 hwaddr len
, bool is_write
)
2983 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2984 buf
, len
, is_write
);
2987 enum write_rom_type
{
2992 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2997 enum write_rom_type type
)
3003 const uint8_t *buf
= ptr
;
3005 RCU_READ_LOCK_GUARD();
3008 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
3010 if (!(memory_region_is_ram(mr
) ||
3011 memory_region_is_romd(mr
))) {
3012 l
= memory_access_size(mr
, l
, addr1
);
3015 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
3018 memcpy(ram_ptr
, buf
, l
);
3019 invalidate_and_set_dirty(mr
, addr1
, l
);
3022 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
3033 /* used for ROM loading : can write in RAM and ROM */
3034 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
3036 const void *buf
, hwaddr len
)
3038 return address_space_write_rom_internal(as
, addr
, attrs
,
3039 buf
, len
, WRITE_DATA
);
3042 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
3045 * This function should do the same thing as an icache flush that was
3046 * triggered from within the guest. For TCG we are always cache coherent,
3047 * so there is no need to flush anything. For KVM / Xen we need to flush
3048 * the host's instruction cache at least.
3050 if (tcg_enabled()) {
3054 address_space_write_rom_internal(&address_space_memory
,
3055 start
, MEMTXATTRS_UNSPECIFIED
,
3056 NULL
, len
, FLUSH_CACHE
);
3060 address_space_unregister_map_client_do(AddressSpaceMapClient
*client
)
3062 QLIST_REMOVE(client
, link
);
3066 static void address_space_notify_map_clients_locked(AddressSpace
*as
)
3068 AddressSpaceMapClient
*client
;
3070 while (!QLIST_EMPTY(&as
->map_client_list
)) {
3071 client
= QLIST_FIRST(&as
->map_client_list
);
3072 qemu_bh_schedule(client
->bh
);
3073 address_space_unregister_map_client_do(client
);
3077 void address_space_register_map_client(AddressSpace
*as
, QEMUBH
*bh
)
3079 AddressSpaceMapClient
*client
= g_malloc(sizeof(*client
));
3081 QEMU_LOCK_GUARD(&as
->map_client_list_lock
);
3083 QLIST_INSERT_HEAD(&as
->map_client_list
, client
, link
);
3084 /* Write map_client_list before reading in_use. */
3086 if (!qatomic_read(&as
->bounce
.in_use
)) {
3087 address_space_notify_map_clients_locked(as
);
3091 void cpu_exec_init_all(void)
3093 qemu_mutex_init(&ram_list
.mutex
);
3094 /* The data structures we set up here depend on knowing the page size,
3095 * so no more changes can be made after this point.
3096 * In an ideal world, nothing we did before we had finished the
3097 * machine setup would care about the target page size, and we could
3098 * do this much later, rather than requiring board models to state
3099 * up front what their requirements are.
3101 finalize_target_page_bits();
3106 void address_space_unregister_map_client(AddressSpace
*as
, QEMUBH
*bh
)
3108 AddressSpaceMapClient
*client
;
3110 QEMU_LOCK_GUARD(&as
->map_client_list_lock
);
3111 QLIST_FOREACH(client
, &as
->map_client_list
, link
) {
3112 if (client
->bh
== bh
) {
3113 address_space_unregister_map_client_do(client
);
3119 static void address_space_notify_map_clients(AddressSpace
*as
)
3121 QEMU_LOCK_GUARD(&as
->map_client_list_lock
);
3122 address_space_notify_map_clients_locked(as
);
3125 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3126 bool is_write
, MemTxAttrs attrs
)
3133 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3134 if (!memory_access_is_direct(mr
, is_write
)) {
3135 l
= memory_access_size(mr
, l
, addr
);
3136 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3147 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3148 hwaddr len
, bool is_write
,
3153 RCU_READ_LOCK_GUARD();
3154 fv
= address_space_to_flatview(as
);
3155 return flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3159 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3161 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3162 bool is_write
, MemTxAttrs attrs
)
3166 MemoryRegion
*this_mr
;
3172 if (target_len
== 0) {
3177 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3178 &len
, is_write
, attrs
);
3179 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3185 /* Map a physical memory region into a host virtual address.
3186 * May map a subset of the requested range, given by and returned in *plen.
3187 * May return NULL if resources needed to perform the mapping are exhausted.
3188 * Use only for reads OR writes - not for read-modify-write operations.
3189 * Use address_space_register_map_client() to know when retrying the map
3190 * operation is likely to succeed.
3192 void *address_space_map(AddressSpace
*as
,
3203 trace_address_space_map(as
, addr
, len
, is_write
, *(uint32_t *) &attrs
);
3210 RCU_READ_LOCK_GUARD();
3211 fv
= address_space_to_flatview(as
);
3212 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3214 if (!memory_access_is_direct(mr
, is_write
)) {
3215 if (qatomic_xchg(&as
->bounce
.in_use
, true)) {
3219 /* Avoid unbounded allocations */
3220 l
= MIN(l
, TARGET_PAGE_SIZE
);
3221 as
->bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3222 as
->bounce
.addr
= addr
;
3225 memory_region_ref(mr
);
3228 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3229 as
->bounce
.buffer
, l
);
3233 return as
->bounce
.buffer
;
3237 memory_region_ref(mr
);
3238 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3239 l
, is_write
, attrs
);
3240 fuzz_dma_read_cb(addr
, *plen
, mr
);
3241 return qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true, is_write
);
3244 /* Unmaps a memory region previously mapped by address_space_map().
3245 * Will also mark the memory as dirty if is_write is true. access_len gives
3246 * the amount of memory that was actually read or written by the caller.
3248 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3249 bool is_write
, hwaddr access_len
)
3251 if (buffer
!= as
->bounce
.buffer
) {
3255 mr
= memory_region_from_host(buffer
, &addr1
);
3258 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3260 if (xen_enabled()) {
3261 xen_invalidate_map_cache_entry(buffer
);
3263 memory_region_unref(mr
);
3267 address_space_write(as
, as
->bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3268 as
->bounce
.buffer
, access_len
);
3270 qemu_vfree(as
->bounce
.buffer
);
3271 as
->bounce
.buffer
= NULL
;
3272 memory_region_unref(as
->bounce
.mr
);
3273 /* Clear in_use before reading map_client_list. */
3274 qatomic_set_mb(&as
->bounce
.in_use
, false);
3275 address_space_notify_map_clients(as
);
3278 void *cpu_physical_memory_map(hwaddr addr
,
3282 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3283 MEMTXATTRS_UNSPECIFIED
);
3286 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3287 bool is_write
, hwaddr access_len
)
3289 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3292 #define ARG1_DECL AddressSpace *as
3295 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3296 #define RCU_READ_LOCK(...) rcu_read_lock()
3297 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3298 #include "memory_ldst.c.inc"
3300 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3306 AddressSpaceDispatch
*d
;
3314 cache
->fv
= address_space_get_flatview(as
);
3315 d
= flatview_to_dispatch(cache
->fv
);
3316 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3319 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3320 * Take that into account to compute how many bytes are there between
3321 * cache->xlat and the end of the section.
3323 diff
= int128_sub(cache
->mrs
.size
,
3324 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3325 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3328 memory_region_ref(mr
);
3329 if (memory_access_is_direct(mr
, is_write
)) {
3330 /* We don't care about the memory attributes here as we're only
3331 * doing this if we found actual RAM, which behaves the same
3332 * regardless of attributes; so UNSPECIFIED is fine.
3334 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3335 cache
->xlat
, l
, is_write
,
3336 MEMTXATTRS_UNSPECIFIED
);
3337 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true,
3344 cache
->is_write
= is_write
;
3348 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3352 assert(cache
->is_write
);
3353 if (likely(cache
->ptr
)) {
3354 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3358 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3360 if (!cache
->mrs
.mr
) {
3364 if (xen_enabled()) {
3365 xen_invalidate_map_cache_entry(cache
->ptr
);
3367 memory_region_unref(cache
->mrs
.mr
);
3368 flatview_unref(cache
->fv
);
3369 cache
->mrs
.mr
= NULL
;
3373 /* Called from RCU critical section. This function has the same
3374 * semantics as address_space_translate, but it only works on a
3375 * predefined range of a MemoryRegion that was mapped with
3376 * address_space_cache_init.
3378 static inline MemoryRegion
*address_space_translate_cached(
3379 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3380 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3382 MemoryRegionSection section
;
3384 IOMMUMemoryRegion
*iommu_mr
;
3385 AddressSpace
*target_as
;
3387 assert(!cache
->ptr
);
3388 *xlat
= addr
+ cache
->xlat
;
3391 iommu_mr
= memory_region_get_iommu(mr
);
3397 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3398 NULL
, is_write
, true,
3403 /* Called within RCU critical section. */
3404 static MemTxResult
address_space_write_continue_cached(MemTxAttrs attrs
,
3411 MemTxResult result
= MEMTX_OK
;
3412 const uint8_t *buf
= ptr
;
3415 result
|= flatview_write_continue_step(attrs
, buf
, len
, mr_addr
, &l
,
3432 /* Called within RCU critical section. */
3433 static MemTxResult
address_space_read_continue_cached(MemTxAttrs attrs
,
3434 void *ptr
, hwaddr len
,
3435 hwaddr mr_addr
, hwaddr l
,
3438 MemTxResult result
= MEMTX_OK
;
3442 result
|= flatview_read_continue_step(attrs
, buf
, len
, mr_addr
, &l
, mr
);
3456 /* Called from RCU critical section. address_space_read_cached uses this
3457 * out of line function when the target is an MMIO or IOMMU region.
3460 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3461 void *buf
, hwaddr len
)
3467 mr
= address_space_translate_cached(cache
, addr
, &mr_addr
, &l
, false,
3468 MEMTXATTRS_UNSPECIFIED
);
3469 return address_space_read_continue_cached(MEMTXATTRS_UNSPECIFIED
,
3470 buf
, len
, mr_addr
, l
, mr
);
3473 /* Called from RCU critical section. address_space_write_cached uses this
3474 * out of line function when the target is an MMIO or IOMMU region.
3477 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3478 const void *buf
, hwaddr len
)
3484 mr
= address_space_translate_cached(cache
, addr
, &mr_addr
, &l
, true,
3485 MEMTXATTRS_UNSPECIFIED
);
3486 return address_space_write_continue_cached(MEMTXATTRS_UNSPECIFIED
,
3487 buf
, len
, mr_addr
, l
, mr
);
3490 #define ARG1_DECL MemoryRegionCache *cache
3492 #define SUFFIX _cached_slow
3493 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3494 #define RCU_READ_LOCK() ((void)0)
3495 #define RCU_READ_UNLOCK() ((void)0)
3496 #include "memory_ldst.c.inc"
3498 /* virtual memory access for debug (includes writing to ROM) */
3499 int cpu_memory_rw_debug(CPUState
*cpu
, vaddr addr
,
3500 void *ptr
, size_t len
, bool is_write
)
3506 cpu_synchronize_state(cpu
);
3512 page
= addr
& TARGET_PAGE_MASK
;
3513 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3514 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3515 /* if no physical page mapped, return an error */
3516 if (phys_addr
== -1)
3518 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3521 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3523 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3526 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3529 if (res
!= MEMTX_OK
) {
3539 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3544 RCU_READ_LOCK_GUARD();
3545 mr
= address_space_translate(&address_space_memory
,
3546 phys_addr
, &phys_addr
, &l
, false,
3547 MEMTXATTRS_UNSPECIFIED
);
3549 return !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3552 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3557 RCU_READ_LOCK_GUARD();
3558 RAMBLOCK_FOREACH(block
) {
3559 ret
= func(block
, opaque
);
3568 * Unmap pages of memory from start to start+length such that
3569 * they a) read as 0, b) Trigger whatever fault mechanism
3570 * the OS provides for postcopy.
3571 * The pages must be unmapped by the end of the function.
3572 * Returns: 0 on success, none-0 on failure
3575 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3579 uint8_t *host_startaddr
= rb
->host
+ start
;
3581 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3582 error_report("%s: Unaligned start address: %p",
3583 __func__
, host_startaddr
);
3587 if ((start
+ length
) <= rb
->max_length
) {
3588 bool need_madvise
, need_fallocate
;
3589 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3590 error_report("%s: Unaligned length: %zx", __func__
, length
);
3594 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3596 /* The logic here is messy;
3597 * madvise DONTNEED fails for hugepages
3598 * fallocate works on hugepages and shmem
3599 * shared anonymous memory requires madvise REMOVE
3601 need_madvise
= (rb
->page_size
== qemu_real_host_page_size());
3602 need_fallocate
= rb
->fd
!= -1;
3603 if (need_fallocate
) {
3604 /* For a file, this causes the area of the file to be zero'd
3605 * if read, and for hugetlbfs also causes it to be unmapped
3606 * so a userfault will trigger.
3608 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3610 * fallocate() will fail with readonly files. Let's print a
3611 * proper error message.
3613 if (rb
->flags
& RAM_READONLY_FD
) {
3614 error_report("%s: Discarding RAM with readonly files is not"
3615 " supported", __func__
);
3620 * We'll discard data from the actual file, even though we only
3621 * have a MAP_PRIVATE mapping, possibly messing with other
3622 * MAP_PRIVATE/MAP_SHARED mappings. There is no easy way to
3623 * change that behavior whithout violating the promised
3624 * semantics of ram_block_discard_range().
3626 * Only warn, because it works as long as nobody else uses that
3629 if (!qemu_ram_is_shared(rb
)) {
3630 warn_report_once("%s: Discarding RAM"
3631 " in private file mappings is possibly"
3632 " dangerous, because it will modify the"
3633 " underlying file and will affect other"
3634 " users of the file", __func__
);
3637 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3641 error_report("%s: Failed to fallocate %s:%" PRIx64
" +%zx (%d)",
3642 __func__
, rb
->idstr
, start
, length
, ret
);
3647 error_report("%s: fallocate not available/file"
3648 "%s:%" PRIx64
" +%zx (%d)",
3649 __func__
, rb
->idstr
, start
, length
, ret
);
3654 /* For normal RAM this causes it to be unmapped,
3655 * for shared memory it causes the local mapping to disappear
3656 * and to fall back on the file contents (which we just
3657 * fallocate'd away).
3659 #if defined(CONFIG_MADVISE)
3660 if (qemu_ram_is_shared(rb
) && rb
->fd
< 0) {
3661 ret
= madvise(host_startaddr
, length
, QEMU_MADV_REMOVE
);
3663 ret
= madvise(host_startaddr
, length
, QEMU_MADV_DONTNEED
);
3667 error_report("%s: Failed to discard range "
3668 "%s:%" PRIx64
" +%zx (%d)",
3669 __func__
, rb
->idstr
, start
, length
, ret
);
3674 error_report("%s: MADVISE not available %s:%" PRIx64
" +%zx (%d)",
3675 __func__
, rb
->idstr
, start
, length
, ret
);
3679 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3680 need_madvise
, need_fallocate
, ret
);
3682 error_report("%s: Overrun block '%s' (%" PRIu64
"/%zx/" RAM_ADDR_FMT
")",
3683 __func__
, rb
->idstr
, start
, length
, rb
->max_length
);
3690 int ram_block_discard_guest_memfd_range(RAMBlock
*rb
, uint64_t start
,
3695 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3696 ret
= fallocate(rb
->guest_memfd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3701 error_report("%s: Failed to fallocate %s:%" PRIx64
" +%zx (%d)",
3702 __func__
, rb
->idstr
, start
, length
, ret
);
3706 error_report("%s: fallocate not available %s:%" PRIx64
" +%zx (%d)",
3707 __func__
, rb
->idstr
, start
, length
, ret
);
3713 bool ramblock_is_pmem(RAMBlock
*rb
)
3715 return rb
->flags
& RAM_PMEM
;
3718 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3720 if (start
== end
- 1) {
3721 qemu_printf("\t%3d ", start
);
3723 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3725 qemu_printf(" skip=%d ", skip
);
3726 if (ptr
== PHYS_MAP_NODE_NIL
) {
3727 qemu_printf(" ptr=NIL");
3729 qemu_printf(" ptr=#%d", ptr
);
3731 qemu_printf(" ptr=[%d]", ptr
);
3736 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3737 int128_sub((size), int128_one())) : 0)
3739 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3743 qemu_printf(" Dispatch\n");
3744 qemu_printf(" Physical sections\n");
3746 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3747 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3748 const char *names
[] = { " [unassigned]", " [not dirty]",
3749 " [ROM]", " [watch]" };
3751 qemu_printf(" #%d @" HWADDR_FMT_plx
".." HWADDR_FMT_plx
3754 s
->offset_within_address_space
,
3755 s
->offset_within_address_space
+ MR_SIZE(s
->size
),
3756 s
->mr
->name
? s
->mr
->name
: "(noname)",
3757 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3758 s
->mr
== root
? " [ROOT]" : "",
3759 s
== d
->mru_section
? " [MRU]" : "",
3760 s
->mr
->is_iommu
? " [iommu]" : "");
3763 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3764 s
->mr
->alias
->name
: "noname");
3769 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3770 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3771 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3774 Node
*n
= d
->map
.nodes
+ i
;
3776 qemu_printf(" [%d]\n", i
);
3778 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3779 PhysPageEntry
*pe
= *n
+ j
;
3781 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3785 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3791 if (jprev
!= ARRAY_SIZE(*n
)) {
3792 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3797 /* Require any discards to work. */
3798 static unsigned int ram_block_discard_required_cnt
;
3799 /* Require only coordinated discards to work. */
3800 static unsigned int ram_block_coordinated_discard_required_cnt
;
3801 /* Disable any discards. */
3802 static unsigned int ram_block_discard_disabled_cnt
;
3803 /* Disable only uncoordinated discards. */
3804 static unsigned int ram_block_uncoordinated_discard_disabled_cnt
;
3805 static QemuMutex ram_block_discard_disable_mutex
;
3807 static void ram_block_discard_disable_mutex_lock(void)
3809 static gsize initialized
;
3811 if (g_once_init_enter(&initialized
)) {
3812 qemu_mutex_init(&ram_block_discard_disable_mutex
);
3813 g_once_init_leave(&initialized
, 1);
3815 qemu_mutex_lock(&ram_block_discard_disable_mutex
);
3818 static void ram_block_discard_disable_mutex_unlock(void)
3820 qemu_mutex_unlock(&ram_block_discard_disable_mutex
);
3823 int ram_block_discard_disable(bool state
)
3827 ram_block_discard_disable_mutex_lock();
3829 ram_block_discard_disabled_cnt
--;
3830 } else if (ram_block_discard_required_cnt
||
3831 ram_block_coordinated_discard_required_cnt
) {
3834 ram_block_discard_disabled_cnt
++;
3836 ram_block_discard_disable_mutex_unlock();
3840 int ram_block_uncoordinated_discard_disable(bool state
)
3844 ram_block_discard_disable_mutex_lock();
3846 ram_block_uncoordinated_discard_disabled_cnt
--;
3847 } else if (ram_block_discard_required_cnt
) {
3850 ram_block_uncoordinated_discard_disabled_cnt
++;
3852 ram_block_discard_disable_mutex_unlock();
3856 int ram_block_discard_require(bool state
)
3860 ram_block_discard_disable_mutex_lock();
3862 ram_block_discard_required_cnt
--;
3863 } else if (ram_block_discard_disabled_cnt
||
3864 ram_block_uncoordinated_discard_disabled_cnt
) {
3867 ram_block_discard_required_cnt
++;
3869 ram_block_discard_disable_mutex_unlock();
3873 int ram_block_coordinated_discard_require(bool state
)
3877 ram_block_discard_disable_mutex_lock();
3879 ram_block_coordinated_discard_required_cnt
--;
3880 } else if (ram_block_discard_disabled_cnt
) {
3883 ram_block_coordinated_discard_required_cnt
++;
3885 ram_block_discard_disable_mutex_unlock();
3889 bool ram_block_discard_is_disabled(void)
3891 return qatomic_read(&ram_block_discard_disabled_cnt
) ||
3892 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt
);
3895 bool ram_block_discard_is_required(void)
3897 return qatomic_read(&ram_block_discard_required_cnt
) ||
3898 qatomic_read(&ram_block_coordinated_discard_required_cnt
);