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"
30 #include "hw/core/tcg-cpu-ops.h"
31 #endif /* CONFIG_TCG */
33 #include "exec/exec-all.h"
34 #include "exec/target_page.h"
35 #include "hw/qdev-core.h"
36 #include "hw/qdev-properties.h"
37 #include "hw/boards.h"
38 #include "hw/xen/xen.h"
39 #include "sysemu/kvm.h"
40 #include "sysemu/tcg.h"
41 #include "sysemu/qtest.h"
42 #include "qemu/timer.h"
43 #include "qemu/config-file.h"
44 #include "qemu/error-report.h"
45 #include "qemu/qemu-print.h"
47 #include "qemu/memalign.h"
48 #include "exec/memory.h"
49 #include "exec/ioport.h"
50 #include "sysemu/dma.h"
51 #include "sysemu/hostmem.h"
52 #include "sysemu/hw_accel.h"
53 #include "sysemu/xen-mapcache.h"
54 #include "trace/trace-root.h"
56 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
57 #include <linux/falloc.h>
60 #include "qemu/rcu_queue.h"
61 #include "qemu/main-loop.h"
62 #include "exec/translate-all.h"
63 #include "sysemu/replay.h"
65 #include "exec/memory-internal.h"
66 #include "exec/ram_addr.h"
68 #include "qemu/pmem.h"
70 #include "migration/vmstate.h"
72 #include "qemu/range.h"
74 #include "qemu/mmap-alloc.h"
77 #include "monitor/monitor.h"
79 #ifdef CONFIG_LIBDAXCTL
80 #include <daxctl/libdaxctl.h>
83 //#define DEBUG_SUBPAGE
85 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
86 * are protected by the ramlist lock.
88 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
90 static MemoryRegion
*system_memory
;
91 static MemoryRegion
*system_io
;
93 AddressSpace address_space_io
;
94 AddressSpace address_space_memory
;
96 static MemoryRegion io_mem_unassigned
;
98 typedef struct PhysPageEntry PhysPageEntry
;
100 struct PhysPageEntry
{
101 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
103 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
107 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
109 /* Size of the L2 (and L3, etc) page tables. */
110 #define ADDR_SPACE_BITS 64
113 #define P_L2_SIZE (1 << P_L2_BITS)
115 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
117 typedef PhysPageEntry Node
[P_L2_SIZE
];
119 typedef struct PhysPageMap
{
122 unsigned sections_nb
;
123 unsigned sections_nb_alloc
;
125 unsigned nodes_nb_alloc
;
127 MemoryRegionSection
*sections
;
130 struct AddressSpaceDispatch
{
131 MemoryRegionSection
*mru_section
;
132 /* This is a multi-level map on the physical address space.
133 * The bottom level has pointers to MemoryRegionSections.
135 PhysPageEntry phys_map
;
139 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
140 typedef struct subpage_t
{
144 uint16_t sub_section
[];
147 #define PHYS_SECTION_UNASSIGNED 0
149 static void io_mem_init(void);
150 static void memory_map_init(void);
151 static void tcg_log_global_after_sync(MemoryListener
*listener
);
152 static void tcg_commit(MemoryListener
*listener
);
155 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
156 * @cpu: the CPU whose AddressSpace this is
157 * @as: the AddressSpace itself
158 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
159 * @tcg_as_listener: listener for tracking changes to the AddressSpace
161 struct CPUAddressSpace
{
164 struct AddressSpaceDispatch
*memory_dispatch
;
165 MemoryListener tcg_as_listener
;
168 struct DirtyBitmapSnapshot
{
171 unsigned long dirty
[];
174 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
176 static unsigned alloc_hint
= 16;
177 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
178 map
->nodes_nb_alloc
= MAX(alloc_hint
, map
->nodes_nb
+ nodes
);
179 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
180 alloc_hint
= map
->nodes_nb_alloc
;
184 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
191 ret
= map
->nodes_nb
++;
193 assert(ret
!= PHYS_MAP_NODE_NIL
);
194 assert(ret
!= map
->nodes_nb_alloc
);
196 e
.skip
= leaf
? 0 : 1;
197 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
198 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
199 memcpy(&p
[i
], &e
, sizeof(e
));
204 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
205 hwaddr
*index
, uint64_t *nb
, uint16_t leaf
,
209 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
211 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
212 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
214 p
= map
->nodes
[lp
->ptr
];
215 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
217 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
218 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
224 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
230 static void phys_page_set(AddressSpaceDispatch
*d
,
231 hwaddr index
, uint64_t nb
,
234 /* Wildly overreserve - it doesn't matter much. */
235 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
237 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
240 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
241 * and update our entry so we can skip it and go directly to the destination.
243 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
245 unsigned valid_ptr
= P_L2_SIZE
;
250 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
255 for (i
= 0; i
< P_L2_SIZE
; i
++) {
256 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
263 phys_page_compact(&p
[i
], nodes
);
267 /* We can only compress if there's only one child. */
272 assert(valid_ptr
< P_L2_SIZE
);
274 /* Don't compress if it won't fit in the # of bits we have. */
275 if (P_L2_LEVELS
>= (1 << 6) &&
276 lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 6)) {
280 lp
->ptr
= p
[valid_ptr
].ptr
;
281 if (!p
[valid_ptr
].skip
) {
282 /* If our only child is a leaf, make this a leaf. */
283 /* By design, we should have made this node a leaf to begin with so we
284 * should never reach here.
285 * But since it's so simple to handle this, let's do it just in case we
290 lp
->skip
+= p
[valid_ptr
].skip
;
294 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
296 if (d
->phys_map
.skip
) {
297 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
301 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
304 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
305 * the section must cover the entire address space.
307 return int128_gethi(section
->size
) ||
308 range_covers_byte(section
->offset_within_address_space
,
309 int128_getlo(section
->size
), addr
);
312 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
314 PhysPageEntry lp
= d
->phys_map
, *p
;
315 Node
*nodes
= d
->map
.nodes
;
316 MemoryRegionSection
*sections
= d
->map
.sections
;
317 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
320 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
321 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
322 return §ions
[PHYS_SECTION_UNASSIGNED
];
325 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
328 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
329 return §ions
[lp
.ptr
];
331 return §ions
[PHYS_SECTION_UNASSIGNED
];
335 /* Called from RCU critical section */
336 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
338 bool resolve_subpage
)
340 MemoryRegionSection
*section
= qatomic_read(&d
->mru_section
);
343 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
344 !section_covers_addr(section
, addr
)) {
345 section
= phys_page_find(d
, addr
);
346 qatomic_set(&d
->mru_section
, section
);
348 if (resolve_subpage
&& section
->mr
->subpage
) {
349 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
350 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
355 /* Called from RCU critical section */
356 static MemoryRegionSection
*
357 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
358 hwaddr
*plen
, bool resolve_subpage
)
360 MemoryRegionSection
*section
;
364 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
365 /* Compute offset within MemoryRegionSection */
366 addr
-= section
->offset_within_address_space
;
368 /* Compute offset within MemoryRegion */
369 *xlat
= addr
+ section
->offset_within_region
;
373 /* MMIO registers can be expected to perform full-width accesses based only
374 * on their address, without considering adjacent registers that could
375 * decode to completely different MemoryRegions. When such registers
376 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
377 * regions overlap wildly. For this reason we cannot clamp the accesses
380 * If the length is small (as is the case for address_space_ldl/stl),
381 * everything works fine. If the incoming length is large, however,
382 * the caller really has to do the clamping through memory_access_size.
384 if (memory_region_is_ram(mr
)) {
385 diff
= int128_sub(section
->size
, int128_make64(addr
));
386 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
392 * address_space_translate_iommu - translate an address through an IOMMU
393 * memory region and then through the target address space.
395 * @iommu_mr: the IOMMU memory region that we start the translation from
396 * @addr: the address to be translated through the MMU
397 * @xlat: the translated address offset within the destination memory region.
398 * It cannot be %NULL.
399 * @plen_out: valid read/write length of the translated address. It
401 * @page_mask_out: page mask for the translated address. This
402 * should only be meaningful for IOMMU translated
403 * addresses, since there may be huge pages that this bit
404 * would tell. It can be %NULL if we don't care about it.
405 * @is_write: whether the translation operation is for write
406 * @is_mmio: whether this can be MMIO, set true if it can
407 * @target_as: the address space targeted by the IOMMU
408 * @attrs: transaction attributes
410 * This function is called from RCU critical section. It is the common
411 * part of flatview_do_translate and address_space_translate_cached.
413 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
416 hwaddr
*page_mask_out
,
419 AddressSpace
**target_as
,
422 MemoryRegionSection
*section
;
423 hwaddr page_mask
= (hwaddr
)-1;
427 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
431 if (imrc
->attrs_to_index
) {
432 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
435 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
436 IOMMU_WO
: IOMMU_RO
, iommu_idx
);
438 if (!(iotlb
.perm
& (1 << is_write
))) {
442 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
443 | (addr
& iotlb
.addr_mask
));
444 page_mask
&= iotlb
.addr_mask
;
445 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
446 *target_as
= iotlb
.target_as
;
448 section
= address_space_translate_internal(
449 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
452 iommu_mr
= memory_region_get_iommu(section
->mr
);
453 } while (unlikely(iommu_mr
));
456 *page_mask_out
= page_mask
;
461 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
465 * flatview_do_translate - translate an address in FlatView
467 * @fv: the flat view that we want to translate on
468 * @addr: the address to be translated in above address space
469 * @xlat: the translated address offset within memory region. It
471 * @plen_out: valid read/write length of the translated address. It
472 * can be @NULL when we don't care about it.
473 * @page_mask_out: page mask for the translated address. This
474 * should only be meaningful for IOMMU translated
475 * addresses, since there may be huge pages that this bit
476 * would tell. It can be @NULL if we don't care about it.
477 * @is_write: whether the translation operation is for write
478 * @is_mmio: whether this can be MMIO, set true if it can
479 * @target_as: the address space targeted by the IOMMU
480 * @attrs: memory transaction attributes
482 * This function is called from RCU critical section
484 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
488 hwaddr
*page_mask_out
,
491 AddressSpace
**target_as
,
494 MemoryRegionSection
*section
;
495 IOMMUMemoryRegion
*iommu_mr
;
496 hwaddr plen
= (hwaddr
)(-1);
502 section
= address_space_translate_internal(
503 flatview_to_dispatch(fv
), addr
, xlat
,
506 iommu_mr
= memory_region_get_iommu(section
->mr
);
507 if (unlikely(iommu_mr
)) {
508 return address_space_translate_iommu(iommu_mr
, xlat
,
509 plen_out
, page_mask_out
,
514 /* Not behind an IOMMU, use default page size. */
515 *page_mask_out
= ~TARGET_PAGE_MASK
;
521 /* Called from RCU critical section */
522 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
523 bool is_write
, MemTxAttrs attrs
)
525 MemoryRegionSection section
;
526 hwaddr xlat
, page_mask
;
529 * This can never be MMIO, and we don't really care about plen,
532 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
533 NULL
, &page_mask
, is_write
, false, &as
,
536 /* Illegal translation */
537 if (section
.mr
== &io_mem_unassigned
) {
541 /* Convert memory region offset into address space offset */
542 xlat
+= section
.offset_within_address_space
-
543 section
.offset_within_region
;
545 return (IOMMUTLBEntry
) {
547 .iova
= addr
& ~page_mask
,
548 .translated_addr
= xlat
& ~page_mask
,
549 .addr_mask
= page_mask
,
550 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
555 return (IOMMUTLBEntry
) {0};
558 /* Called from RCU critical section */
559 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
560 hwaddr
*plen
, bool is_write
,
564 MemoryRegionSection section
;
565 AddressSpace
*as
= NULL
;
567 /* This can be MMIO, so setup MMIO bit. */
568 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
569 is_write
, true, &as
, attrs
);
572 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
573 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
574 *plen
= MIN(page
, *plen
);
580 typedef struct TCGIOMMUNotifier
{
588 static void tcg_iommu_unmap_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
590 TCGIOMMUNotifier
*notifier
= container_of(n
, TCGIOMMUNotifier
, n
);
592 if (!notifier
->active
) {
595 tlb_flush(notifier
->cpu
);
596 notifier
->active
= false;
597 /* We leave the notifier struct on the list to avoid reallocating it later.
598 * Generally the number of IOMMUs a CPU deals with will be small.
599 * In any case we can't unregister the iommu notifier from a notify
604 static void tcg_register_iommu_notifier(CPUState
*cpu
,
605 IOMMUMemoryRegion
*iommu_mr
,
608 /* Make sure this CPU has an IOMMU notifier registered for this
609 * IOMMU/IOMMU index combination, so that we can flush its TLB
610 * when the IOMMU tells us the mappings we've cached have changed.
612 MemoryRegion
*mr
= MEMORY_REGION(iommu_mr
);
613 TCGIOMMUNotifier
*notifier
= NULL
;
616 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
617 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
618 if (notifier
->mr
== mr
&& notifier
->iommu_idx
== iommu_idx
) {
622 if (i
== cpu
->iommu_notifiers
->len
) {
623 /* Not found, add a new entry at the end of the array */
624 cpu
->iommu_notifiers
= g_array_set_size(cpu
->iommu_notifiers
, i
+ 1);
625 notifier
= g_new0(TCGIOMMUNotifier
, 1);
626 g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
) = notifier
;
629 notifier
->iommu_idx
= iommu_idx
;
631 /* Rather than trying to register interest in the specific part
632 * of the iommu's address space that we've accessed and then
633 * expand it later as subsequent accesses touch more of it, we
634 * just register interest in the whole thing, on the assumption
635 * that iommu reconfiguration will be rare.
637 iommu_notifier_init(¬ifier
->n
,
638 tcg_iommu_unmap_notify
,
639 IOMMU_NOTIFIER_UNMAP
,
643 memory_region_register_iommu_notifier(notifier
->mr
, ¬ifier
->n
,
647 if (!notifier
->active
) {
648 notifier
->active
= true;
652 void tcg_iommu_free_notifier_list(CPUState
*cpu
)
654 /* Destroy the CPU's notifier list */
656 TCGIOMMUNotifier
*notifier
;
658 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
659 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
660 memory_region_unregister_iommu_notifier(notifier
->mr
, ¬ifier
->n
);
663 g_array_free(cpu
->iommu_notifiers
, true);
666 void tcg_iommu_init_notifier_list(CPUState
*cpu
)
668 cpu
->iommu_notifiers
= g_array_new(false, true, sizeof(TCGIOMMUNotifier
*));
671 /* Called from RCU critical section */
672 MemoryRegionSection
*
673 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr orig_addr
,
674 hwaddr
*xlat
, hwaddr
*plen
,
675 MemTxAttrs attrs
, int *prot
)
677 MemoryRegionSection
*section
;
678 IOMMUMemoryRegion
*iommu_mr
;
679 IOMMUMemoryRegionClass
*imrc
;
682 hwaddr addr
= orig_addr
;
683 AddressSpaceDispatch
*d
=
684 qatomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
687 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
689 iommu_mr
= memory_region_get_iommu(section
->mr
);
694 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
696 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
697 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
698 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
699 * doesn't short-cut its translation table walk.
701 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
702 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
703 | (addr
& iotlb
.addr_mask
));
704 /* Update the caller's prot bits to remove permissions the IOMMU
705 * is giving us a failure response for. If we get down to no
706 * permissions left at all we can give up now.
708 if (!(iotlb
.perm
& IOMMU_RO
)) {
709 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
711 if (!(iotlb
.perm
& IOMMU_WO
)) {
712 *prot
&= ~PAGE_WRITE
;
719 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
722 assert(!memory_region_is_iommu(section
->mr
));
728 * We should be given a page-aligned address -- certainly
729 * tlb_set_page_with_attrs() does so. The page offset of xlat
730 * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.
731 * The page portion of xlat will be logged by memory_region_access_valid()
732 * when this memory access is rejected, so use the original untranslated
735 assert((orig_addr
& ~TARGET_PAGE_MASK
) == 0);
737 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
740 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
741 const char *prefix
, MemoryRegion
*mr
)
743 CPUAddressSpace
*newas
;
744 AddressSpace
*as
= g_new0(AddressSpace
, 1);
748 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
749 address_space_init(as
, mr
, as_name
);
752 /* Target code should have set num_ases before calling us */
753 assert(asidx
< cpu
->num_ases
);
756 /* address space 0 gets the convenience alias */
760 /* KVM cannot currently support multiple address spaces. */
761 assert(asidx
== 0 || !kvm_enabled());
763 if (!cpu
->cpu_ases
) {
764 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
767 newas
= &cpu
->cpu_ases
[asidx
];
771 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
772 newas
->tcg_as_listener
.commit
= tcg_commit
;
773 newas
->tcg_as_listener
.name
= "tcg";
774 memory_listener_register(&newas
->tcg_as_listener
, as
);
778 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
780 /* Return the AddressSpace corresponding to the specified index */
781 return cpu
->cpu_ases
[asidx
].as
;
784 /* Called from RCU critical section */
785 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
789 block
= qatomic_rcu_read(&ram_list
.mru_block
);
790 if (block
&& addr
- block
->offset
< block
->max_length
) {
793 RAMBLOCK_FOREACH(block
) {
794 if (addr
- block
->offset
< block
->max_length
) {
799 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
803 /* It is safe to write mru_block outside the iothread lock. This
808 * xxx removed from list
812 * call_rcu(reclaim_ramblock, xxx);
815 * qatomic_rcu_set is not needed here. The block was already published
816 * when it was placed into the list. Here we're just making an extra
817 * copy of the pointer.
819 ram_list
.mru_block
= block
;
823 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
830 assert(tcg_enabled());
831 end
= TARGET_PAGE_ALIGN(start
+ length
);
832 start
&= TARGET_PAGE_MASK
;
834 RCU_READ_LOCK_GUARD();
835 block
= qemu_get_ram_block(start
);
836 assert(block
== qemu_get_ram_block(end
- 1));
837 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
839 tlb_reset_dirty(cpu
, start1
, length
);
843 /* Note: start and end must be within the same ram block. */
844 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
848 DirtyMemoryBlocks
*blocks
;
849 unsigned long end
, page
, start_page
;
852 uint64_t mr_offset
, mr_size
;
858 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
859 start_page
= start
>> TARGET_PAGE_BITS
;
862 WITH_RCU_READ_LOCK_GUARD() {
863 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
864 ramblock
= qemu_get_ram_block(start
);
865 /* Range sanity check on the ramblock */
866 assert(start
>= ramblock
->offset
&&
867 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
870 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
871 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
872 unsigned long num
= MIN(end
- page
,
873 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
875 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
880 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
881 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
882 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
885 if (dirty
&& tcg_enabled()) {
886 tlb_reset_dirty_range_all(start
, length
);
892 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
893 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
895 DirtyMemoryBlocks
*blocks
;
896 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
897 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
898 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
899 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
900 DirtyBitmapSnapshot
*snap
;
901 unsigned long page
, end
, dest
;
903 snap
= g_malloc0(sizeof(*snap
) +
904 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
908 page
= first
>> TARGET_PAGE_BITS
;
909 end
= last
>> TARGET_PAGE_BITS
;
912 WITH_RCU_READ_LOCK_GUARD() {
913 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
916 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
917 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
918 unsigned long num
= MIN(end
- page
,
919 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
921 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
922 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
923 offset
>>= BITS_PER_LEVEL
;
925 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
926 blocks
->blocks
[idx
] + offset
,
929 dest
+= num
>> BITS_PER_LEVEL
;
934 tlb_reset_dirty_range_all(start
, length
);
937 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
942 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
946 unsigned long page
, end
;
948 assert(start
>= snap
->start
);
949 assert(start
+ length
<= snap
->end
);
951 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
952 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
955 if (test_bit(page
, snap
->dirty
)) {
963 /* Called from RCU critical section */
964 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
965 MemoryRegionSection
*section
)
967 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
968 return section
- d
->map
.sections
;
971 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
973 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
975 static uint16_t phys_section_add(PhysPageMap
*map
,
976 MemoryRegionSection
*section
)
978 /* The physical section number is ORed with a page-aligned
979 * pointer to produce the iotlb entries. Thus it should
980 * never overflow into the page-aligned value.
982 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
984 if (map
->sections_nb
== map
->sections_nb_alloc
) {
985 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
986 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
987 map
->sections_nb_alloc
);
989 map
->sections
[map
->sections_nb
] = *section
;
990 memory_region_ref(section
->mr
);
991 return map
->sections_nb
++;
994 static void phys_section_destroy(MemoryRegion
*mr
)
996 bool have_sub_page
= mr
->subpage
;
998 memory_region_unref(mr
);
1000 if (have_sub_page
) {
1001 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1002 object_unref(OBJECT(&subpage
->iomem
));
1007 static void phys_sections_free(PhysPageMap
*map
)
1009 while (map
->sections_nb
> 0) {
1010 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1011 phys_section_destroy(section
->mr
);
1013 g_free(map
->sections
);
1017 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1019 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1021 hwaddr base
= section
->offset_within_address_space
1023 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1024 MemoryRegionSection subsection
= {
1025 .offset_within_address_space
= base
,
1026 .size
= int128_make64(TARGET_PAGE_SIZE
),
1030 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1032 if (!(existing
->mr
->subpage
)) {
1033 subpage
= subpage_init(fv
, base
);
1035 subsection
.mr
= &subpage
->iomem
;
1036 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1037 phys_section_add(&d
->map
, &subsection
));
1039 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1041 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1042 end
= start
+ int128_get64(section
->size
) - 1;
1043 subpage_register(subpage
, start
, end
,
1044 phys_section_add(&d
->map
, section
));
1048 static void register_multipage(FlatView
*fv
,
1049 MemoryRegionSection
*section
)
1051 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1052 hwaddr start_addr
= section
->offset_within_address_space
;
1053 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1054 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1058 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1062 * The range in *section* may look like this:
1066 * where s stands for subpage and P for page.
1068 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1070 MemoryRegionSection remain
= *section
;
1071 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1073 /* register first subpage */
1074 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1075 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1076 - remain
.offset_within_address_space
;
1078 MemoryRegionSection now
= remain
;
1079 now
.size
= int128_min(int128_make64(left
), now
.size
);
1080 register_subpage(fv
, &now
);
1081 if (int128_eq(remain
.size
, now
.size
)) {
1084 remain
.size
= int128_sub(remain
.size
, now
.size
);
1085 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1086 remain
.offset_within_region
+= int128_get64(now
.size
);
1089 /* register whole pages */
1090 if (int128_ge(remain
.size
, page_size
)) {
1091 MemoryRegionSection now
= remain
;
1092 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1093 register_multipage(fv
, &now
);
1094 if (int128_eq(remain
.size
, now
.size
)) {
1097 remain
.size
= int128_sub(remain
.size
, now
.size
);
1098 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1099 remain
.offset_within_region
+= int128_get64(now
.size
);
1102 /* register last subpage */
1103 register_subpage(fv
, &remain
);
1106 void qemu_flush_coalesced_mmio_buffer(void)
1109 kvm_flush_coalesced_mmio_buffer();
1112 void qemu_mutex_lock_ramlist(void)
1114 qemu_mutex_lock(&ram_list
.mutex
);
1117 void qemu_mutex_unlock_ramlist(void)
1119 qemu_mutex_unlock(&ram_list
.mutex
);
1122 GString
*ram_block_format(void)
1126 GString
*buf
= g_string_new("");
1128 RCU_READ_LOCK_GUARD();
1129 g_string_append_printf(buf
, "%24s %8s %18s %18s %18s\n",
1130 "Block Name", "PSize", "Offset", "Used", "Total");
1131 RAMBLOCK_FOREACH(block
) {
1132 psize
= size_to_str(block
->page_size
);
1133 g_string_append_printf(buf
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1134 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1135 (uint64_t)block
->offset
,
1136 (uint64_t)block
->used_length
,
1137 (uint64_t)block
->max_length
);
1144 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1146 long *hpsize_min
= opaque
;
1148 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1149 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1150 long hpsize
= host_memory_backend_pagesize(backend
);
1152 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1153 *hpsize_min
= hpsize
;
1160 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1162 long *hpsize_max
= opaque
;
1164 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1165 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1166 long hpsize
= host_memory_backend_pagesize(backend
);
1168 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1169 *hpsize_max
= hpsize
;
1177 * TODO: We assume right now that all mapped host memory backends are
1178 * used as RAM, however some might be used for different purposes.
1180 long qemu_minrampagesize(void)
1182 long hpsize
= LONG_MAX
;
1183 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1185 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1189 long qemu_maxrampagesize(void)
1192 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1194 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1199 static int64_t get_file_size(int fd
)
1202 #if defined(__linux__)
1205 if (fstat(fd
, &st
) < 0) {
1209 /* Special handling for devdax character devices */
1210 if (S_ISCHR(st
.st_mode
)) {
1211 g_autofree
char *subsystem_path
= NULL
;
1212 g_autofree
char *subsystem
= NULL
;
1214 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1215 major(st
.st_rdev
), minor(st
.st_rdev
));
1216 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1218 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1219 g_autofree
char *size_path
= NULL
;
1220 g_autofree
char *size_str
= NULL
;
1222 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1223 major(st
.st_rdev
), minor(st
.st_rdev
));
1225 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1226 return g_ascii_strtoll(size_str
, NULL
, 0);
1230 #endif /* defined(__linux__) */
1232 /* st.st_size may be zero for special files yet lseek(2) works */
1233 size
= lseek(fd
, 0, SEEK_END
);
1240 static int64_t get_file_align(int fd
)
1243 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1246 if (fstat(fd
, &st
) < 0) {
1250 /* Special handling for devdax character devices */
1251 if (S_ISCHR(st
.st_mode
)) {
1252 g_autofree
char *path
= NULL
;
1253 g_autofree
char *rpath
= NULL
;
1254 struct daxctl_ctx
*ctx
;
1255 struct daxctl_region
*region
;
1258 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1259 major(st
.st_rdev
), minor(st
.st_rdev
));
1260 rpath
= realpath(path
, NULL
);
1265 rc
= daxctl_new(&ctx
);
1270 daxctl_region_foreach(ctx
, region
) {
1271 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1272 align
= daxctl_region_get_align(region
);
1278 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1283 static int file_ram_open(const char *path
,
1284 const char *region_name
,
1290 char *sanitized_name
;
1296 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1298 /* @path names an existing file, use it */
1301 if (errno
== ENOENT
) {
1302 /* @path names a file that doesn't exist, create it */
1303 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1308 } else if (errno
== EISDIR
) {
1309 /* @path names a directory, create a file there */
1310 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1311 sanitized_name
= g_strdup(region_name
);
1312 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1318 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1320 g_free(sanitized_name
);
1322 fd
= mkstemp(filename
);
1330 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1331 error_setg_errno(errp
, errno
,
1332 "can't open backing store %s for guest RAM",
1337 * Try again on EINTR and EEXIST. The latter happens when
1338 * something else creates the file between our two open().
1345 static void *file_ram_alloc(RAMBlock
*block
,
1353 uint32_t qemu_map_flags
;
1356 block
->page_size
= qemu_fd_getpagesize(fd
);
1357 if (block
->mr
->align
% block
->page_size
) {
1358 error_setg(errp
, "alignment 0x%" PRIx64
1359 " must be multiples of page size 0x%zx",
1360 block
->mr
->align
, block
->page_size
);
1362 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1363 error_setg(errp
, "alignment 0x%" PRIx64
1364 " must be a power of two", block
->mr
->align
);
1367 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1368 #if defined(__s390x__)
1369 if (kvm_enabled()) {
1370 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1374 if (memory
< block
->page_size
) {
1375 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1376 "or larger than page size 0x%zx",
1377 memory
, block
->page_size
);
1381 memory
= ROUND_UP(memory
, block
->page_size
);
1384 * ftruncate is not supported by hugetlbfs in older
1385 * hosts, so don't bother bailing out on errors.
1386 * If anything goes wrong with it under other filesystems,
1389 * Do not truncate the non-empty backend file to avoid corrupting
1390 * the existing data in the file. Disabling shrinking is not
1391 * enough. For example, the current vNVDIMM implementation stores
1392 * the guest NVDIMM labels at the end of the backend file. If the
1393 * backend file is later extended, QEMU will not be able to find
1394 * those labels. Therefore, extending the non-empty backend file
1395 * is disabled as well.
1397 if (truncate
&& ftruncate(fd
, memory
)) {
1398 perror("ftruncate");
1401 qemu_map_flags
= readonly
? QEMU_MAP_READONLY
: 0;
1402 qemu_map_flags
|= (block
->flags
& RAM_SHARED
) ? QEMU_MAP_SHARED
: 0;
1403 qemu_map_flags
|= (block
->flags
& RAM_PMEM
) ? QEMU_MAP_SYNC
: 0;
1404 qemu_map_flags
|= (block
->flags
& RAM_NORESERVE
) ? QEMU_MAP_NORESERVE
: 0;
1405 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, qemu_map_flags
, offset
);
1406 if (area
== MAP_FAILED
) {
1407 error_setg_errno(errp
, errno
,
1408 "unable to map backing store for guest RAM");
1417 /* Allocate space within the ram_addr_t space that governs the
1419 * Called with the ramlist lock held.
1421 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1423 RAMBlock
*block
, *next_block
;
1424 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1426 assert(size
!= 0); /* it would hand out same offset multiple times */
1428 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1432 RAMBLOCK_FOREACH(block
) {
1433 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1435 /* Align blocks to start on a 'long' in the bitmap
1436 * which makes the bitmap sync'ing take the fast path.
1438 candidate
= block
->offset
+ block
->max_length
;
1439 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1441 /* Search for the closest following block
1444 RAMBLOCK_FOREACH(next_block
) {
1445 if (next_block
->offset
>= candidate
) {
1446 next
= MIN(next
, next_block
->offset
);
1450 /* If it fits remember our place and remember the size
1451 * of gap, but keep going so that we might find a smaller
1452 * gap to fill so avoiding fragmentation.
1454 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1456 mingap
= next
- candidate
;
1459 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1462 if (offset
== RAM_ADDR_MAX
) {
1463 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1468 trace_find_ram_offset(size
, offset
);
1473 static unsigned long last_ram_page(void)
1476 ram_addr_t last
= 0;
1478 RCU_READ_LOCK_GUARD();
1479 RAMBLOCK_FOREACH(block
) {
1480 last
= MAX(last
, block
->offset
+ block
->max_length
);
1482 return last
>> TARGET_PAGE_BITS
;
1485 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1489 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1490 if (!machine_dump_guest_core(current_machine
)) {
1491 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1493 perror("qemu_madvise");
1494 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1495 "but dump_guest_core=off specified\n");
1500 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1505 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1510 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1515 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1517 return rb
->used_length
;
1520 ram_addr_t
qemu_ram_get_max_length(RAMBlock
*rb
)
1522 return rb
->max_length
;
1525 bool qemu_ram_is_shared(RAMBlock
*rb
)
1527 return rb
->flags
& RAM_SHARED
;
1530 bool qemu_ram_is_noreserve(RAMBlock
*rb
)
1532 return rb
->flags
& RAM_NORESERVE
;
1535 /* Note: Only set at the start of postcopy */
1536 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1538 return rb
->flags
& RAM_UF_ZEROPAGE
;
1541 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1543 rb
->flags
|= RAM_UF_ZEROPAGE
;
1546 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1548 return rb
->flags
& RAM_MIGRATABLE
;
1551 void qemu_ram_set_migratable(RAMBlock
*rb
)
1553 rb
->flags
|= RAM_MIGRATABLE
;
1556 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1558 rb
->flags
&= ~RAM_MIGRATABLE
;
1561 int qemu_ram_get_fd(RAMBlock
*rb
)
1566 /* Called with iothread lock held. */
1567 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1572 assert(!new_block
->idstr
[0]);
1575 char *id
= qdev_get_dev_path(dev
);
1577 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1581 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1583 RCU_READ_LOCK_GUARD();
1584 RAMBLOCK_FOREACH(block
) {
1585 if (block
!= new_block
&&
1586 !strcmp(block
->idstr
, new_block
->idstr
)) {
1587 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1594 /* Called with iothread lock held. */
1595 void qemu_ram_unset_idstr(RAMBlock
*block
)
1597 /* FIXME: arch_init.c assumes that this is not called throughout
1598 * migration. Ignore the problem since hot-unplug during migration
1599 * does not work anyway.
1602 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1606 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1608 return rb
->page_size
;
1611 /* Returns the largest size of page in use */
1612 size_t qemu_ram_pagesize_largest(void)
1617 RAMBLOCK_FOREACH(block
) {
1618 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1624 static int memory_try_enable_merging(void *addr
, size_t len
)
1626 if (!machine_mem_merge(current_machine
)) {
1627 /* disabled by the user */
1631 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1635 * Resizing RAM while migrating can result in the migration being canceled.
1636 * Care has to be taken if the guest might have already detected the memory.
1638 * As memory core doesn't know how is memory accessed, it is up to
1639 * resize callback to update device state and/or add assertions to detect
1640 * misuse, if necessary.
1642 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1644 const ram_addr_t oldsize
= block
->used_length
;
1645 const ram_addr_t unaligned_size
= newsize
;
1649 newsize
= HOST_PAGE_ALIGN(newsize
);
1651 if (block
->used_length
== newsize
) {
1653 * We don't have to resize the ram block (which only knows aligned
1654 * sizes), however, we have to notify if the unaligned size changed.
1656 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1657 memory_region_set_size(block
->mr
, unaligned_size
);
1658 if (block
->resized
) {
1659 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1665 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1666 error_setg_errno(errp
, EINVAL
,
1667 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1668 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1669 newsize
, block
->used_length
);
1673 if (block
->max_length
< newsize
) {
1674 error_setg_errno(errp
, EINVAL
,
1675 "Size too large: %s: 0x" RAM_ADDR_FMT
1676 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1677 newsize
, block
->max_length
);
1681 /* Notify before modifying the ram block and touching the bitmaps. */
1683 ram_block_notify_resize(block
->host
, oldsize
, newsize
);
1686 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1687 block
->used_length
= newsize
;
1688 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1690 memory_region_set_size(block
->mr
, unaligned_size
);
1691 if (block
->resized
) {
1692 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1698 * Trigger sync on the given ram block for range [start, start + length]
1699 * with the backing store if one is available.
1701 * @Note: this is supposed to be a synchronous op.
1703 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1705 /* The requested range should fit in within the block range */
1706 g_assert((start
+ length
) <= block
->used_length
);
1708 #ifdef CONFIG_LIBPMEM
1709 /* The lack of support for pmem should not block the sync */
1710 if (ramblock_is_pmem(block
)) {
1711 void *addr
= ramblock_ptr(block
, start
);
1712 pmem_persist(addr
, length
);
1716 if (block
->fd
>= 0) {
1718 * Case there is no support for PMEM or the memory has not been
1719 * specified as persistent (or is not one) - use the msync.
1720 * Less optimal but still achieves the same goal
1722 void *addr
= ramblock_ptr(block
, start
);
1723 if (qemu_msync(addr
, length
, block
->fd
)) {
1724 warn_report("%s: failed to sync memory range: start: "
1725 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1726 __func__
, start
, length
);
1731 /* Called with ram_list.mutex held */
1732 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1733 ram_addr_t new_ram_size
)
1735 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1736 DIRTY_MEMORY_BLOCK_SIZE
);
1737 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1738 DIRTY_MEMORY_BLOCK_SIZE
);
1741 /* Only need to extend if block count increased */
1742 if (new_num_blocks
<= old_num_blocks
) {
1746 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1747 DirtyMemoryBlocks
*old_blocks
;
1748 DirtyMemoryBlocks
*new_blocks
;
1751 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1752 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1753 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1755 if (old_num_blocks
) {
1756 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1757 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1760 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1761 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1764 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1767 g_free_rcu(old_blocks
, rcu
);
1772 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
)
1774 const bool noreserve
= qemu_ram_is_noreserve(new_block
);
1775 const bool shared
= qemu_ram_is_shared(new_block
);
1777 RAMBlock
*last_block
= NULL
;
1778 ram_addr_t old_ram_size
, new_ram_size
;
1781 old_ram_size
= last_ram_page();
1783 qemu_mutex_lock_ramlist();
1784 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1786 if (!new_block
->host
) {
1787 if (xen_enabled()) {
1788 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1789 new_block
->mr
, &err
);
1791 error_propagate(errp
, err
);
1792 qemu_mutex_unlock_ramlist();
1796 new_block
->host
= qemu_anon_ram_alloc(new_block
->max_length
,
1797 &new_block
->mr
->align
,
1799 if (!new_block
->host
) {
1800 error_setg_errno(errp
, errno
,
1801 "cannot set up guest memory '%s'",
1802 memory_region_name(new_block
->mr
));
1803 qemu_mutex_unlock_ramlist();
1806 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1810 new_ram_size
= MAX(old_ram_size
,
1811 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1812 if (new_ram_size
> old_ram_size
) {
1813 dirty_memory_extend(old_ram_size
, new_ram_size
);
1815 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1816 * QLIST (which has an RCU-friendly variant) does not have insertion at
1817 * tail, so save the last element in last_block.
1819 RAMBLOCK_FOREACH(block
) {
1821 if (block
->max_length
< new_block
->max_length
) {
1826 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1827 } else if (last_block
) {
1828 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1829 } else { /* list is empty */
1830 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1832 ram_list
.mru_block
= NULL
;
1834 /* Write list before version */
1837 qemu_mutex_unlock_ramlist();
1839 cpu_physical_memory_set_dirty_range(new_block
->offset
,
1840 new_block
->used_length
,
1843 if (new_block
->host
) {
1844 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
1845 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
1847 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1848 * Configure it unless the machine is a qtest server, in which case
1849 * KVM is not used and it may be forked (eg for fuzzing purposes).
1851 if (!qtest_enabled()) {
1852 qemu_madvise(new_block
->host
, new_block
->max_length
,
1853 QEMU_MADV_DONTFORK
);
1855 ram_block_notify_add(new_block
->host
, new_block
->used_length
,
1856 new_block
->max_length
);
1861 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
1862 uint32_t ram_flags
, int fd
, off_t offset
,
1863 bool readonly
, Error
**errp
)
1865 RAMBlock
*new_block
;
1866 Error
*local_err
= NULL
;
1867 int64_t file_size
, file_align
;
1869 /* Just support these ram flags by now. */
1870 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
| RAM_NORESERVE
|
1871 RAM_PROTECTED
)) == 0);
1873 if (xen_enabled()) {
1874 error_setg(errp
, "-mem-path not supported with Xen");
1878 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1880 "host lacks kvm mmu notifiers, -mem-path unsupported");
1884 size
= HOST_PAGE_ALIGN(size
);
1885 file_size
= get_file_size(fd
);
1886 if (file_size
> 0 && file_size
< size
) {
1887 error_setg(errp
, "backing store size 0x%" PRIx64
1888 " does not match 'size' option 0x" RAM_ADDR_FMT
,
1893 file_align
= get_file_align(fd
);
1894 if (file_align
> 0 && file_align
> mr
->align
) {
1895 error_setg(errp
, "backing store align 0x%" PRIx64
1896 " is larger than 'align' option 0x%" PRIx64
,
1897 file_align
, mr
->align
);
1901 new_block
= g_malloc0(sizeof(*new_block
));
1903 new_block
->used_length
= size
;
1904 new_block
->max_length
= size
;
1905 new_block
->flags
= ram_flags
;
1906 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, readonly
,
1907 !file_size
, offset
, errp
);
1908 if (!new_block
->host
) {
1913 ram_block_add(new_block
, &local_err
);
1916 error_propagate(errp
, local_err
);
1924 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
1925 uint32_t ram_flags
, const char *mem_path
,
1926 bool readonly
, Error
**errp
)
1932 fd
= file_ram_open(mem_path
, memory_region_name(mr
), readonly
, &created
,
1938 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, 0, readonly
, errp
);
1952 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
1953 void (*resized
)(const char*,
1956 void *host
, uint32_t ram_flags
,
1957 MemoryRegion
*mr
, Error
**errp
)
1959 RAMBlock
*new_block
;
1960 Error
*local_err
= NULL
;
1962 assert((ram_flags
& ~(RAM_SHARED
| RAM_RESIZEABLE
| RAM_PREALLOC
|
1963 RAM_NORESERVE
)) == 0);
1964 assert(!host
^ (ram_flags
& RAM_PREALLOC
));
1966 size
= HOST_PAGE_ALIGN(size
);
1967 max_size
= HOST_PAGE_ALIGN(max_size
);
1968 new_block
= g_malloc0(sizeof(*new_block
));
1970 new_block
->resized
= resized
;
1971 new_block
->used_length
= size
;
1972 new_block
->max_length
= max_size
;
1973 assert(max_size
>= size
);
1975 new_block
->page_size
= qemu_real_host_page_size();
1976 new_block
->host
= host
;
1977 new_block
->flags
= ram_flags
;
1978 ram_block_add(new_block
, &local_err
);
1981 error_propagate(errp
, local_err
);
1987 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
1988 MemoryRegion
*mr
, Error
**errp
)
1990 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, RAM_PREALLOC
, mr
,
1994 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, uint32_t ram_flags
,
1995 MemoryRegion
*mr
, Error
**errp
)
1997 assert((ram_flags
& ~(RAM_SHARED
| RAM_NORESERVE
)) == 0);
1998 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, ram_flags
, mr
, errp
);
2001 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2002 void (*resized
)(const char*,
2005 MemoryRegion
*mr
, Error
**errp
)
2007 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
,
2008 RAM_RESIZEABLE
, mr
, errp
);
2011 static void reclaim_ramblock(RAMBlock
*block
)
2013 if (block
->flags
& RAM_PREALLOC
) {
2015 } else if (xen_enabled()) {
2016 xen_invalidate_map_cache_entry(block
->host
);
2018 } else if (block
->fd
>= 0) {
2019 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2023 qemu_anon_ram_free(block
->host
, block
->max_length
);
2028 void qemu_ram_free(RAMBlock
*block
)
2035 ram_block_notify_remove(block
->host
, block
->used_length
,
2039 qemu_mutex_lock_ramlist();
2040 QLIST_REMOVE_RCU(block
, next
);
2041 ram_list
.mru_block
= NULL
;
2042 /* Write list before version */
2045 call_rcu(block
, reclaim_ramblock
, rcu
);
2046 qemu_mutex_unlock_ramlist();
2050 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2057 RAMBLOCK_FOREACH(block
) {
2058 offset
= addr
- block
->offset
;
2059 if (offset
< block
->max_length
) {
2060 vaddr
= ramblock_ptr(block
, offset
);
2061 if (block
->flags
& RAM_PREALLOC
) {
2063 } else if (xen_enabled()) {
2067 flags
|= block
->flags
& RAM_SHARED
?
2068 MAP_SHARED
: MAP_PRIVATE
;
2069 flags
|= block
->flags
& RAM_NORESERVE
? MAP_NORESERVE
: 0;
2070 if (block
->fd
>= 0) {
2071 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2072 flags
, block
->fd
, offset
);
2074 flags
|= MAP_ANONYMOUS
;
2075 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2078 if (area
!= vaddr
) {
2079 error_report("Could not remap addr: "
2080 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2084 memory_try_enable_merging(vaddr
, length
);
2085 qemu_ram_setup_dump(vaddr
, length
);
2090 #endif /* !_WIN32 */
2092 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2093 * This should not be used for general purpose DMA. Use address_space_map
2094 * or address_space_rw instead. For local memory (e.g. video ram) that the
2095 * device owns, use memory_region_get_ram_ptr.
2097 * Called within RCU critical section.
2099 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2101 RAMBlock
*block
= ram_block
;
2103 if (block
== NULL
) {
2104 block
= qemu_get_ram_block(addr
);
2105 addr
-= block
->offset
;
2108 if (xen_enabled() && block
->host
== NULL
) {
2109 /* We need to check if the requested address is in the RAM
2110 * because we don't want to map the entire memory in QEMU.
2111 * In that case just map until the end of the page.
2113 if (block
->offset
== 0) {
2114 return xen_map_cache(addr
, 0, 0, false);
2117 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2119 return ramblock_ptr(block
, addr
);
2122 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2123 * but takes a size argument.
2125 * Called within RCU critical section.
2127 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2128 hwaddr
*size
, bool lock
)
2130 RAMBlock
*block
= ram_block
;
2135 if (block
== NULL
) {
2136 block
= qemu_get_ram_block(addr
);
2137 addr
-= block
->offset
;
2139 *size
= MIN(*size
, block
->max_length
- addr
);
2141 if (xen_enabled() && block
->host
== NULL
) {
2142 /* We need to check if the requested address is in the RAM
2143 * because we don't want to map the entire memory in QEMU.
2144 * In that case just map the requested area.
2146 if (block
->offset
== 0) {
2147 return xen_map_cache(addr
, *size
, lock
, lock
);
2150 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2153 return ramblock_ptr(block
, addr
);
2156 /* Return the offset of a hostpointer within a ramblock */
2157 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2159 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2160 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2161 assert(res
< rb
->max_length
);
2167 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2170 * ptr: Host pointer to look up
2171 * round_offset: If true round the result offset down to a page boundary
2172 * *ram_addr: set to result ram_addr
2173 * *offset: set to result offset within the RAMBlock
2175 * Returns: RAMBlock (or NULL if not found)
2177 * By the time this function returns, the returned pointer is not protected
2178 * by RCU anymore. If the caller is not within an RCU critical section and
2179 * does not hold the iothread lock, it must have other means of protecting the
2180 * pointer, such as a reference to the region that includes the incoming
2183 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2187 uint8_t *host
= ptr
;
2189 if (xen_enabled()) {
2190 ram_addr_t ram_addr
;
2191 RCU_READ_LOCK_GUARD();
2192 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2193 block
= qemu_get_ram_block(ram_addr
);
2195 *offset
= ram_addr
- block
->offset
;
2200 RCU_READ_LOCK_GUARD();
2201 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2202 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2206 RAMBLOCK_FOREACH(block
) {
2207 /* This case append when the block is not mapped. */
2208 if (block
->host
== NULL
) {
2211 if (host
- block
->host
< block
->max_length
) {
2219 *offset
= (host
- block
->host
);
2221 *offset
&= TARGET_PAGE_MASK
;
2227 * Finds the named RAMBlock
2229 * name: The name of RAMBlock to find
2231 * Returns: RAMBlock (or NULL if not found)
2233 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2237 RAMBLOCK_FOREACH(block
) {
2238 if (!strcmp(name
, block
->idstr
)) {
2246 /* Some of the softmmu routines need to translate from a host pointer
2247 (typically a TLB entry) back to a ram offset. */
2248 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2253 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2255 return RAM_ADDR_INVALID
;
2258 return block
->offset
+ offset
;
2261 ram_addr_t
qemu_ram_addr_from_host_nofail(void *ptr
)
2263 ram_addr_t ram_addr
;
2265 ram_addr
= qemu_ram_addr_from_host(ptr
);
2266 if (ram_addr
== RAM_ADDR_INVALID
) {
2267 error_report("Bad ram pointer %p", ptr
);
2273 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2274 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2275 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2276 const void *buf
, hwaddr len
);
2277 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2278 bool is_write
, MemTxAttrs attrs
);
2280 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2281 unsigned len
, MemTxAttrs attrs
)
2283 subpage_t
*subpage
= opaque
;
2287 #if defined(DEBUG_SUBPAGE)
2288 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
"\n", __func__
,
2289 subpage
, len
, addr
);
2291 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2295 *data
= ldn_p(buf
, len
);
2299 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2300 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2302 subpage_t
*subpage
= opaque
;
2305 #if defined(DEBUG_SUBPAGE)
2306 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
2307 " value %"PRIx64
"\n",
2308 __func__
, subpage
, len
, addr
, value
);
2310 stn_p(buf
, len
, value
);
2311 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2314 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2315 unsigned len
, bool is_write
,
2318 subpage_t
*subpage
= opaque
;
2319 #if defined(DEBUG_SUBPAGE)
2320 printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx
"\n",
2321 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2324 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2325 len
, is_write
, attrs
);
2328 static const MemoryRegionOps subpage_ops
= {
2329 .read_with_attrs
= subpage_read
,
2330 .write_with_attrs
= subpage_write
,
2331 .impl
.min_access_size
= 1,
2332 .impl
.max_access_size
= 8,
2333 .valid
.min_access_size
= 1,
2334 .valid
.max_access_size
= 8,
2335 .valid
.accepts
= subpage_accepts
,
2336 .endianness
= DEVICE_NATIVE_ENDIAN
,
2339 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2344 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2346 idx
= SUBPAGE_IDX(start
);
2347 eidx
= SUBPAGE_IDX(end
);
2348 #if defined(DEBUG_SUBPAGE)
2349 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2350 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2352 for (; idx
<= eidx
; idx
++) {
2353 mmio
->sub_section
[idx
] = section
;
2359 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2363 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2364 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2367 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2368 NULL
, TARGET_PAGE_SIZE
);
2369 mmio
->iomem
.subpage
= true;
2370 #if defined(DEBUG_SUBPAGE)
2371 printf("%s: %p base " HWADDR_FMT_plx
" len %08x\n", __func__
,
2372 mmio
, base
, TARGET_PAGE_SIZE
);
2378 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2381 MemoryRegionSection section
= {
2384 .offset_within_address_space
= 0,
2385 .offset_within_region
= 0,
2386 .size
= int128_2_64(),
2389 return phys_section_add(map
, §ion
);
2392 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2393 hwaddr index
, MemTxAttrs attrs
)
2395 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2396 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2397 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2398 MemoryRegionSection
*sections
= d
->map
.sections
;
2400 return §ions
[index
& ~TARGET_PAGE_MASK
];
2403 static void io_mem_init(void)
2405 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2409 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2411 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2414 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2415 assert(n
== PHYS_SECTION_UNASSIGNED
);
2417 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2422 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2424 phys_sections_free(&d
->map
);
2428 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2432 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2434 CPUAddressSpace
*cpuas
;
2436 /* Wait for the CPU to end the current TB. This avoids the following
2440 * ---------------------- -------------------------
2441 * TLB check -> slow path
2442 * notdirty_mem_write
2446 * TLB check -> fast path
2450 * by pushing the migration thread's memory read after the vCPU thread has
2451 * written the memory.
2453 if (replay_mode
== REPLAY_MODE_NONE
) {
2455 * VGA can make calls to this function while updating the screen.
2456 * In record/replay mode this causes a deadlock, because
2457 * run_on_cpu waits for rr mutex. Therefore no races are possible
2458 * in this case and no need for making run_on_cpu when
2459 * record/replay is enabled.
2461 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2462 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2466 static void tcg_commit(MemoryListener
*listener
)
2468 CPUAddressSpace
*cpuas
;
2469 AddressSpaceDispatch
*d
;
2471 assert(tcg_enabled());
2472 /* since each CPU stores ram addresses in its TLB cache, we must
2473 reset the modified entries */
2474 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2475 cpu_reloading_memory_map();
2476 /* The CPU and TLB are protected by the iothread lock.
2477 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2478 * may have split the RCU critical section.
2480 d
= address_space_to_dispatch(cpuas
->as
);
2481 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2482 tlb_flush(cpuas
->cpu
);
2485 static void memory_map_init(void)
2487 system_memory
= g_malloc(sizeof(*system_memory
));
2489 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2490 address_space_init(&address_space_memory
, system_memory
, "memory");
2492 system_io
= g_malloc(sizeof(*system_io
));
2493 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2495 address_space_init(&address_space_io
, system_io
, "I/O");
2498 MemoryRegion
*get_system_memory(void)
2500 return system_memory
;
2503 MemoryRegion
*get_system_io(void)
2508 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2511 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2512 addr
+= memory_region_get_ram_addr(mr
);
2514 /* No early return if dirty_log_mask is or becomes 0, because
2515 * cpu_physical_memory_set_dirty_range will still call
2516 * xen_modified_memory.
2518 if (dirty_log_mask
) {
2520 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2522 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2523 assert(tcg_enabled());
2524 tb_invalidate_phys_range(addr
, addr
+ length
);
2525 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2527 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2530 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2533 * In principle this function would work on other memory region types too,
2534 * but the ROM device use case is the only one where this operation is
2535 * necessary. Other memory regions should use the
2536 * address_space_read/write() APIs.
2538 assert(memory_region_is_romd(mr
));
2540 invalidate_and_set_dirty(mr
, addr
, size
);
2543 int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2545 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2547 /* Regions are assumed to support 1-4 byte accesses unless
2548 otherwise specified. */
2549 if (access_size_max
== 0) {
2550 access_size_max
= 4;
2553 /* Bound the maximum access by the alignment of the address. */
2554 if (!mr
->ops
->impl
.unaligned
) {
2555 unsigned align_size_max
= addr
& -addr
;
2556 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2557 access_size_max
= align_size_max
;
2561 /* Don't attempt accesses larger than the maximum. */
2562 if (l
> access_size_max
) {
2563 l
= access_size_max
;
2570 bool prepare_mmio_access(MemoryRegion
*mr
)
2572 bool release_lock
= false;
2574 if (!qemu_mutex_iothread_locked()) {
2575 qemu_mutex_lock_iothread();
2576 release_lock
= true;
2578 if (mr
->flush_coalesced_mmio
) {
2579 qemu_flush_coalesced_mmio_buffer();
2582 return release_lock
;
2586 * flatview_access_allowed
2587 * @mr: #MemoryRegion to be accessed
2588 * @attrs: memory transaction attributes
2589 * @addr: address within that memory region
2590 * @len: the number of bytes to access
2592 * Check if a memory transaction is allowed.
2594 * Returns: true if transaction is allowed, false if denied.
2596 static bool flatview_access_allowed(MemoryRegion
*mr
, MemTxAttrs attrs
,
2597 hwaddr addr
, hwaddr len
)
2599 if (likely(!attrs
.memory
)) {
2602 if (memory_region_is_ram(mr
)) {
2605 qemu_log_mask(LOG_GUEST_ERROR
,
2606 "Invalid access to non-RAM device at "
2607 "addr 0x%" HWADDR_PRIX
", size %" HWADDR_PRIu
", "
2608 "region '%s'\n", addr
, len
, memory_region_name(mr
));
2612 /* Called within RCU critical section. */
2613 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2616 hwaddr len
, hwaddr addr1
,
2617 hwaddr l
, MemoryRegion
*mr
)
2621 MemTxResult result
= MEMTX_OK
;
2622 bool release_lock
= false;
2623 const uint8_t *buf
= ptr
;
2626 if (!flatview_access_allowed(mr
, attrs
, addr1
, l
)) {
2627 result
|= MEMTX_ACCESS_ERROR
;
2629 } else if (!memory_access_is_direct(mr
, true)) {
2630 release_lock
|= prepare_mmio_access(mr
);
2631 l
= memory_access_size(mr
, l
, addr1
);
2632 /* XXX: could force current_cpu to NULL to avoid
2634 val
= ldn_he_p(buf
, l
);
2635 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2636 size_memop(l
), attrs
);
2639 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2640 memmove(ram_ptr
, buf
, l
);
2641 invalidate_and_set_dirty(mr
, addr1
, l
);
2645 qemu_mutex_unlock_iothread();
2646 release_lock
= false;
2658 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2664 /* Called from RCU critical section. */
2665 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2666 const void *buf
, hwaddr len
)
2673 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2674 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2675 return MEMTX_ACCESS_ERROR
;
2677 return flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2681 /* Called within RCU critical section. */
2682 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2683 MemTxAttrs attrs
, void *ptr
,
2684 hwaddr len
, hwaddr addr1
, hwaddr l
,
2689 MemTxResult result
= MEMTX_OK
;
2690 bool release_lock
= false;
2693 fuzz_dma_read_cb(addr
, len
, mr
);
2695 if (!flatview_access_allowed(mr
, attrs
, addr1
, l
)) {
2696 result
|= MEMTX_ACCESS_ERROR
;
2698 } else if (!memory_access_is_direct(mr
, false)) {
2700 release_lock
|= prepare_mmio_access(mr
);
2701 l
= memory_access_size(mr
, l
, addr1
);
2702 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2703 size_memop(l
), attrs
);
2704 stn_he_p(buf
, l
, val
);
2707 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2708 memcpy(buf
, ram_ptr
, l
);
2712 qemu_mutex_unlock_iothread();
2713 release_lock
= false;
2725 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2731 /* Called from RCU critical section. */
2732 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2733 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2740 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2741 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2742 return MEMTX_ACCESS_ERROR
;
2744 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2748 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2749 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2751 MemTxResult result
= MEMTX_OK
;
2755 RCU_READ_LOCK_GUARD();
2756 fv
= address_space_to_flatview(as
);
2757 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2763 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2765 const void *buf
, hwaddr len
)
2767 MemTxResult result
= MEMTX_OK
;
2771 RCU_READ_LOCK_GUARD();
2772 fv
= address_space_to_flatview(as
);
2773 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2779 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2780 void *buf
, hwaddr len
, bool is_write
)
2783 return address_space_write(as
, addr
, attrs
, buf
, len
);
2785 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2789 MemTxResult
address_space_set(AddressSpace
*as
, hwaddr addr
,
2790 uint8_t c
, hwaddr len
, MemTxAttrs attrs
)
2792 #define FILLBUF_SIZE 512
2793 uint8_t fillbuf
[FILLBUF_SIZE
];
2795 MemTxResult error
= MEMTX_OK
;
2797 memset(fillbuf
, c
, FILLBUF_SIZE
);
2799 l
= len
< FILLBUF_SIZE
? len
: FILLBUF_SIZE
;
2800 error
|= address_space_write(as
, addr
, attrs
, fillbuf
, l
);
2808 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2809 hwaddr len
, bool is_write
)
2811 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2812 buf
, len
, is_write
);
2815 enum write_rom_type
{
2820 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2825 enum write_rom_type type
)
2831 const uint8_t *buf
= ptr
;
2833 RCU_READ_LOCK_GUARD();
2836 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
2838 if (!(memory_region_is_ram(mr
) ||
2839 memory_region_is_romd(mr
))) {
2840 l
= memory_access_size(mr
, l
, addr1
);
2843 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
2846 memcpy(ram_ptr
, buf
, l
);
2847 invalidate_and_set_dirty(mr
, addr1
, l
);
2850 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
2861 /* used for ROM loading : can write in RAM and ROM */
2862 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
2864 const void *buf
, hwaddr len
)
2866 return address_space_write_rom_internal(as
, addr
, attrs
,
2867 buf
, len
, WRITE_DATA
);
2870 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
2873 * This function should do the same thing as an icache flush that was
2874 * triggered from within the guest. For TCG we are always cache coherent,
2875 * so there is no need to flush anything. For KVM / Xen we need to flush
2876 * the host's instruction cache at least.
2878 if (tcg_enabled()) {
2882 address_space_write_rom_internal(&address_space_memory
,
2883 start
, MEMTXATTRS_UNSPECIFIED
,
2884 NULL
, len
, FLUSH_CACHE
);
2895 static BounceBuffer bounce
;
2897 typedef struct MapClient
{
2899 QLIST_ENTRY(MapClient
) link
;
2902 QemuMutex map_client_list_lock
;
2903 static QLIST_HEAD(, MapClient
) map_client_list
2904 = QLIST_HEAD_INITIALIZER(map_client_list
);
2906 static void cpu_unregister_map_client_do(MapClient
*client
)
2908 QLIST_REMOVE(client
, link
);
2912 static void cpu_notify_map_clients_locked(void)
2916 while (!QLIST_EMPTY(&map_client_list
)) {
2917 client
= QLIST_FIRST(&map_client_list
);
2918 qemu_bh_schedule(client
->bh
);
2919 cpu_unregister_map_client_do(client
);
2923 void cpu_register_map_client(QEMUBH
*bh
)
2925 MapClient
*client
= g_malloc(sizeof(*client
));
2927 qemu_mutex_lock(&map_client_list_lock
);
2929 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
2930 if (!qatomic_read(&bounce
.in_use
)) {
2931 cpu_notify_map_clients_locked();
2933 qemu_mutex_unlock(&map_client_list_lock
);
2936 void cpu_exec_init_all(void)
2938 qemu_mutex_init(&ram_list
.mutex
);
2939 /* The data structures we set up here depend on knowing the page size,
2940 * so no more changes can be made after this point.
2941 * In an ideal world, nothing we did before we had finished the
2942 * machine setup would care about the target page size, and we could
2943 * do this much later, rather than requiring board models to state
2944 * up front what their requirements are.
2946 finalize_target_page_bits();
2949 qemu_mutex_init(&map_client_list_lock
);
2952 void cpu_unregister_map_client(QEMUBH
*bh
)
2956 qemu_mutex_lock(&map_client_list_lock
);
2957 QLIST_FOREACH(client
, &map_client_list
, link
) {
2958 if (client
->bh
== bh
) {
2959 cpu_unregister_map_client_do(client
);
2963 qemu_mutex_unlock(&map_client_list_lock
);
2966 static void cpu_notify_map_clients(void)
2968 qemu_mutex_lock(&map_client_list_lock
);
2969 cpu_notify_map_clients_locked();
2970 qemu_mutex_unlock(&map_client_list_lock
);
2973 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2974 bool is_write
, MemTxAttrs attrs
)
2981 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
2982 if (!memory_access_is_direct(mr
, is_write
)) {
2983 l
= memory_access_size(mr
, l
, addr
);
2984 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
2995 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
2996 hwaddr len
, bool is_write
,
3001 RCU_READ_LOCK_GUARD();
3002 fv
= address_space_to_flatview(as
);
3003 return flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3007 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3009 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3010 bool is_write
, MemTxAttrs attrs
)
3014 MemoryRegion
*this_mr
;
3020 if (target_len
== 0) {
3025 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3026 &len
, is_write
, attrs
);
3027 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3033 /* Map a physical memory region into a host virtual address.
3034 * May map a subset of the requested range, given by and returned in *plen.
3035 * May return NULL if resources needed to perform the mapping are exhausted.
3036 * Use only for reads OR writes - not for read-modify-write operations.
3037 * Use cpu_register_map_client() to know when retrying the map operation is
3038 * likely to succeed.
3040 void *address_space_map(AddressSpace
*as
,
3056 RCU_READ_LOCK_GUARD();
3057 fv
= address_space_to_flatview(as
);
3058 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3060 if (!memory_access_is_direct(mr
, is_write
)) {
3061 if (qatomic_xchg(&bounce
.in_use
, true)) {
3065 /* Avoid unbounded allocations */
3066 l
= MIN(l
, TARGET_PAGE_SIZE
);
3067 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3071 memory_region_ref(mr
);
3074 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3079 return bounce
.buffer
;
3083 memory_region_ref(mr
);
3084 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3085 l
, is_write
, attrs
);
3086 fuzz_dma_read_cb(addr
, *plen
, mr
);
3087 return qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3090 /* Unmaps a memory region previously mapped by address_space_map().
3091 * Will also mark the memory as dirty if is_write is true. access_len gives
3092 * the amount of memory that was actually read or written by the caller.
3094 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3095 bool is_write
, hwaddr access_len
)
3097 if (buffer
!= bounce
.buffer
) {
3101 mr
= memory_region_from_host(buffer
, &addr1
);
3104 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3106 if (xen_enabled()) {
3107 xen_invalidate_map_cache_entry(buffer
);
3109 memory_region_unref(mr
);
3113 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3114 bounce
.buffer
, access_len
);
3116 qemu_vfree(bounce
.buffer
);
3117 bounce
.buffer
= NULL
;
3118 memory_region_unref(bounce
.mr
);
3119 qatomic_mb_set(&bounce
.in_use
, false);
3120 cpu_notify_map_clients();
3123 void *cpu_physical_memory_map(hwaddr addr
,
3127 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3128 MEMTXATTRS_UNSPECIFIED
);
3131 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3132 bool is_write
, hwaddr access_len
)
3134 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3137 #define ARG1_DECL AddressSpace *as
3140 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3141 #define RCU_READ_LOCK(...) rcu_read_lock()
3142 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3143 #include "memory_ldst.c.inc"
3145 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3151 AddressSpaceDispatch
*d
;
3159 cache
->fv
= address_space_get_flatview(as
);
3160 d
= flatview_to_dispatch(cache
->fv
);
3161 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3164 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3165 * Take that into account to compute how many bytes are there between
3166 * cache->xlat and the end of the section.
3168 diff
= int128_sub(cache
->mrs
.size
,
3169 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3170 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3173 memory_region_ref(mr
);
3174 if (memory_access_is_direct(mr
, is_write
)) {
3175 /* We don't care about the memory attributes here as we're only
3176 * doing this if we found actual RAM, which behaves the same
3177 * regardless of attributes; so UNSPECIFIED is fine.
3179 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3180 cache
->xlat
, l
, is_write
,
3181 MEMTXATTRS_UNSPECIFIED
);
3182 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3188 cache
->is_write
= is_write
;
3192 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3196 assert(cache
->is_write
);
3197 if (likely(cache
->ptr
)) {
3198 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3202 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3204 if (!cache
->mrs
.mr
) {
3208 if (xen_enabled()) {
3209 xen_invalidate_map_cache_entry(cache
->ptr
);
3211 memory_region_unref(cache
->mrs
.mr
);
3212 flatview_unref(cache
->fv
);
3213 cache
->mrs
.mr
= NULL
;
3217 /* Called from RCU critical section. This function has the same
3218 * semantics as address_space_translate, but it only works on a
3219 * predefined range of a MemoryRegion that was mapped with
3220 * address_space_cache_init.
3222 static inline MemoryRegion
*address_space_translate_cached(
3223 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3224 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3226 MemoryRegionSection section
;
3228 IOMMUMemoryRegion
*iommu_mr
;
3229 AddressSpace
*target_as
;
3231 assert(!cache
->ptr
);
3232 *xlat
= addr
+ cache
->xlat
;
3235 iommu_mr
= memory_region_get_iommu(mr
);
3241 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3242 NULL
, is_write
, true,
3247 /* Called from RCU critical section. address_space_read_cached uses this
3248 * out of line function when the target is an MMIO or IOMMU region.
3251 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3252 void *buf
, hwaddr len
)
3258 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3259 MEMTXATTRS_UNSPECIFIED
);
3260 return flatview_read_continue(cache
->fv
,
3261 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3265 /* Called from RCU critical section. address_space_write_cached uses this
3266 * out of line function when the target is an MMIO or IOMMU region.
3269 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3270 const void *buf
, hwaddr len
)
3276 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3277 MEMTXATTRS_UNSPECIFIED
);
3278 return flatview_write_continue(cache
->fv
,
3279 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3283 #define ARG1_DECL MemoryRegionCache *cache
3285 #define SUFFIX _cached_slow
3286 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3287 #define RCU_READ_LOCK() ((void)0)
3288 #define RCU_READ_UNLOCK() ((void)0)
3289 #include "memory_ldst.c.inc"
3291 /* virtual memory access for debug (includes writing to ROM) */
3292 int cpu_memory_rw_debug(CPUState
*cpu
, vaddr addr
,
3293 void *ptr
, size_t len
, bool is_write
)
3299 cpu_synchronize_state(cpu
);
3305 page
= addr
& TARGET_PAGE_MASK
;
3306 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3307 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3308 /* if no physical page mapped, return an error */
3309 if (phys_addr
== -1)
3311 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3314 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3316 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3319 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3322 if (res
!= MEMTX_OK
) {
3333 * Allows code that needs to deal with migration bitmaps etc to still be built
3334 * target independent.
3336 size_t qemu_target_page_size(void)
3338 return TARGET_PAGE_SIZE
;
3341 int qemu_target_page_bits(void)
3343 return TARGET_PAGE_BITS
;
3346 int qemu_target_page_bits_min(void)
3348 return TARGET_PAGE_BITS_MIN
;
3351 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3356 RCU_READ_LOCK_GUARD();
3357 mr
= address_space_translate(&address_space_memory
,
3358 phys_addr
, &phys_addr
, &l
, false,
3359 MEMTXATTRS_UNSPECIFIED
);
3361 return !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3364 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3369 RCU_READ_LOCK_GUARD();
3370 RAMBLOCK_FOREACH(block
) {
3371 ret
= func(block
, opaque
);
3380 * Unmap pages of memory from start to start+length such that
3381 * they a) read as 0, b) Trigger whatever fault mechanism
3382 * the OS provides for postcopy.
3383 * The pages must be unmapped by the end of the function.
3384 * Returns: 0 on success, none-0 on failure
3387 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3391 uint8_t *host_startaddr
= rb
->host
+ start
;
3393 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3394 error_report("ram_block_discard_range: Unaligned start address: %p",
3399 if ((start
+ length
) <= rb
->max_length
) {
3400 bool need_madvise
, need_fallocate
;
3401 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3402 error_report("ram_block_discard_range: Unaligned length: %zx",
3407 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3409 /* The logic here is messy;
3410 * madvise DONTNEED fails for hugepages
3411 * fallocate works on hugepages and shmem
3412 * shared anonymous memory requires madvise REMOVE
3414 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3415 need_fallocate
= rb
->fd
!= -1;
3416 if (need_fallocate
) {
3417 /* For a file, this causes the area of the file to be zero'd
3418 * if read, and for hugetlbfs also causes it to be unmapped
3419 * so a userfault will trigger.
3421 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3422 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3426 error_report("ram_block_discard_range: Failed to fallocate "
3427 "%s:%" PRIx64
" +%zx (%d)",
3428 rb
->idstr
, start
, length
, ret
);
3433 error_report("ram_block_discard_range: fallocate not available/file"
3434 "%s:%" PRIx64
" +%zx (%d)",
3435 rb
->idstr
, start
, length
, ret
);
3440 /* For normal RAM this causes it to be unmapped,
3441 * for shared memory it causes the local mapping to disappear
3442 * and to fall back on the file contents (which we just
3443 * fallocate'd away).
3445 #if defined(CONFIG_MADVISE)
3446 if (qemu_ram_is_shared(rb
) && rb
->fd
< 0) {
3447 ret
= madvise(host_startaddr
, length
, QEMU_MADV_REMOVE
);
3449 ret
= madvise(host_startaddr
, length
, QEMU_MADV_DONTNEED
);
3453 error_report("ram_block_discard_range: Failed to discard range "
3454 "%s:%" PRIx64
" +%zx (%d)",
3455 rb
->idstr
, start
, length
, ret
);
3460 error_report("ram_block_discard_range: MADVISE not available"
3461 "%s:%" PRIx64
" +%zx (%d)",
3462 rb
->idstr
, start
, length
, ret
);
3466 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3467 need_madvise
, need_fallocate
, ret
);
3469 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3470 "/%zx/" RAM_ADDR_FMT
")",
3471 rb
->idstr
, start
, length
, rb
->max_length
);
3478 bool ramblock_is_pmem(RAMBlock
*rb
)
3480 return rb
->flags
& RAM_PMEM
;
3483 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3485 if (start
== end
- 1) {
3486 qemu_printf("\t%3d ", start
);
3488 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3490 qemu_printf(" skip=%d ", skip
);
3491 if (ptr
== PHYS_MAP_NODE_NIL
) {
3492 qemu_printf(" ptr=NIL");
3494 qemu_printf(" ptr=#%d", ptr
);
3496 qemu_printf(" ptr=[%d]", ptr
);
3501 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3502 int128_sub((size), int128_one())) : 0)
3504 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3508 qemu_printf(" Dispatch\n");
3509 qemu_printf(" Physical sections\n");
3511 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3512 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3513 const char *names
[] = { " [unassigned]", " [not dirty]",
3514 " [ROM]", " [watch]" };
3516 qemu_printf(" #%d @" HWADDR_FMT_plx
".." HWADDR_FMT_plx
3519 s
->offset_within_address_space
,
3520 s
->offset_within_address_space
+ MR_SIZE(s
->size
),
3521 s
->mr
->name
? s
->mr
->name
: "(noname)",
3522 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3523 s
->mr
== root
? " [ROOT]" : "",
3524 s
== d
->mru_section
? " [MRU]" : "",
3525 s
->mr
->is_iommu
? " [iommu]" : "");
3528 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3529 s
->mr
->alias
->name
: "noname");
3534 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3535 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3536 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3539 Node
*n
= d
->map
.nodes
+ i
;
3541 qemu_printf(" [%d]\n", i
);
3543 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3544 PhysPageEntry
*pe
= *n
+ j
;
3546 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3550 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3556 if (jprev
!= ARRAY_SIZE(*n
)) {
3557 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3562 /* Require any discards to work. */
3563 static unsigned int ram_block_discard_required_cnt
;
3564 /* Require only coordinated discards to work. */
3565 static unsigned int ram_block_coordinated_discard_required_cnt
;
3566 /* Disable any discards. */
3567 static unsigned int ram_block_discard_disabled_cnt
;
3568 /* Disable only uncoordinated discards. */
3569 static unsigned int ram_block_uncoordinated_discard_disabled_cnt
;
3570 static QemuMutex ram_block_discard_disable_mutex
;
3572 static void ram_block_discard_disable_mutex_lock(void)
3574 static gsize initialized
;
3576 if (g_once_init_enter(&initialized
)) {
3577 qemu_mutex_init(&ram_block_discard_disable_mutex
);
3578 g_once_init_leave(&initialized
, 1);
3580 qemu_mutex_lock(&ram_block_discard_disable_mutex
);
3583 static void ram_block_discard_disable_mutex_unlock(void)
3585 qemu_mutex_unlock(&ram_block_discard_disable_mutex
);
3588 int ram_block_discard_disable(bool state
)
3592 ram_block_discard_disable_mutex_lock();
3594 ram_block_discard_disabled_cnt
--;
3595 } else if (ram_block_discard_required_cnt
||
3596 ram_block_coordinated_discard_required_cnt
) {
3599 ram_block_discard_disabled_cnt
++;
3601 ram_block_discard_disable_mutex_unlock();
3605 int ram_block_uncoordinated_discard_disable(bool state
)
3609 ram_block_discard_disable_mutex_lock();
3611 ram_block_uncoordinated_discard_disabled_cnt
--;
3612 } else if (ram_block_discard_required_cnt
) {
3615 ram_block_uncoordinated_discard_disabled_cnt
++;
3617 ram_block_discard_disable_mutex_unlock();
3621 int ram_block_discard_require(bool state
)
3625 ram_block_discard_disable_mutex_lock();
3627 ram_block_discard_required_cnt
--;
3628 } else if (ram_block_discard_disabled_cnt
||
3629 ram_block_uncoordinated_discard_disabled_cnt
) {
3632 ram_block_discard_required_cnt
++;
3634 ram_block_discard_disable_mutex_unlock();
3638 int ram_block_coordinated_discard_require(bool state
)
3642 ram_block_discard_disable_mutex_lock();
3644 ram_block_coordinated_discard_required_cnt
--;
3645 } else if (ram_block_discard_disabled_cnt
) {
3648 ram_block_coordinated_discard_required_cnt
++;
3650 ram_block_discard_disable_mutex_unlock();
3654 bool ram_block_discard_is_disabled(void)
3656 return qatomic_read(&ram_block_discard_disabled_cnt
) ||
3657 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt
);
3660 bool ram_block_discard_is_required(void)
3662 return qatomic_read(&ram_block_discard_required_cnt
) ||
3663 qatomic_read(&ram_block_coordinated_discard_required_cnt
);